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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0db2dd2c6d1ca4339ae33d85c054f8ff21926500 | 19,146,964,276,509 | 2744146be3aee1a75b68584d38c168eb72aefbcc | /0318/src/day8/ContinueTest.java | 706569cd8678b0aa1bb2a5995cfafee09a8d9661 | [] | no_license | NaYejin94/Day8-with-eclipse | https://github.com/NaYejin94/Day8-with-eclipse | f2636fe79736734c65454c10dddbf636d4176948 | 5baf307c45bb0be795859d07ef5692d27296cd8a | refs/heads/master | 2023-03-26T19:08:27.814000 | 2021-03-23T14:45:09 | 2021-03-23T14:45:09 | 350,748,773 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day8;
public class ContinueTest {
public static void main(String[] args) {
/*
분기문 - 제어를 다른 위치로 옮기는 명령
break - 반복문이나 switch문의 case를 벗어날 때 사용
continue - 반복문의 반복을 한번 건너뛰고 다음 반복을 실행 할 때 사용
- 다음 반복 위치로 이동
- 반복문 안에서만 사용 가능
return - 메서드의 실행을 종료하고 호출원으로 복귀
*/
for(int i=1;i<=10;i++) {
if(i==5) continue;
System.out.println("i="+i);
}
System.out.println("\n========break========");
for(int i=1;i<=10;i++) {
if(i==5) break;
System.out.println("i="+i);
}
System.out.println("\n========중첩 for : break========");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
if(j==1) break;
System.out.println("i="+i+", j="+j);
}
}
System.out.println("\n========중첩 for : continue========");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
if(j==1) continue;
System.out.println("i="+i+", j="+j);
}
}
/*
이름 붙은 반복문
- 중첩 for에서 반복문 앞에 이름(Label)을 붙이고 break문과 continue문에
이름을(Label) 지정해줌으로써 하나 이상의 반복문을 벗어나거나 반복을
건너 뛸 수 있다.
*/
Loop1 :for(int i=2;i<=9;i++) {
for(int j=1;j<=9;j++) {
if(j==5) {
//break Loop1;
//continue Loop1;
//break;
continue;
}
System.out.println(i+"*"+j+"="+i*j);
}//안쪽for
System.out.println();
}//바깥for
}
}
| UHC | Java | 1,593 | java | ContinueTest.java | Java | [] | null | [] | package day8;
public class ContinueTest {
public static void main(String[] args) {
/*
분기문 - 제어를 다른 위치로 옮기는 명령
break - 반복문이나 switch문의 case를 벗어날 때 사용
continue - 반복문의 반복을 한번 건너뛰고 다음 반복을 실행 할 때 사용
- 다음 반복 위치로 이동
- 반복문 안에서만 사용 가능
return - 메서드의 실행을 종료하고 호출원으로 복귀
*/
for(int i=1;i<=10;i++) {
if(i==5) continue;
System.out.println("i="+i);
}
System.out.println("\n========break========");
for(int i=1;i<=10;i++) {
if(i==5) break;
System.out.println("i="+i);
}
System.out.println("\n========중첩 for : break========");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
if(j==1) break;
System.out.println("i="+i+", j="+j);
}
}
System.out.println("\n========중첩 for : continue========");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
if(j==1) continue;
System.out.println("i="+i+", j="+j);
}
}
/*
이름 붙은 반복문
- 중첩 for에서 반복문 앞에 이름(Label)을 붙이고 break문과 continue문에
이름을(Label) 지정해줌으로써 하나 이상의 반복문을 벗어나거나 반복을
건너 뛸 수 있다.
*/
Loop1 :for(int i=2;i<=9;i++) {
for(int j=1;j<=9;j++) {
if(j==5) {
//break Loop1;
//continue Loop1;
//break;
continue;
}
System.out.println(i+"*"+j+"="+i*j);
}//안쪽for
System.out.println();
}//바깥for
}
}
| 1,593 | 0.508235 | 0.487059 | 68 | 17.75 | 16.503454 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.676471 | false | false | 4 |
b542451820277d0c91528f5f13c0bee1c3770213 | 17,188,459,178,470 | 165075ad2488bac38e293e2566eb1154f10d830e | /com/shynixn/thegreatswordartonlinerpg/resources/events/cardinal/AincradPlayerLoginEvent.java | f2fff3b575fca27aa9e649de52fff818e82a68d6 | [] | no_license | Rhinorulz/SAO-RPG | https://github.com/Rhinorulz/SAO-RPG | 97c128f893e755790f17dc7b21d8c68987fcc4fb | 2c564bee3bd344a8cd6d462053cb175c216e470f | refs/heads/master | 2021-01-10T15:27:26.388000 | 2016-03-03T02:44:02 | 2016-03-03T02:44:02 | 53,014,593 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Decompiled with CFR 0_110.
*
* Could not load the following classes:
* org.bukkit.entity.Player
*/
package com.shynixn.thegreatswordartonlinerpg.resources.events.cardinal;
import com.shynixn.thegreatswordartonlinerpg.resources.events.AincradPlayerEvent;
import org.bukkit.entity.Player;
public class AincradPlayerLoginEvent
extends AincradPlayerEvent {
public AincradPlayerLoginEvent(Player player) {
super(player);
}
}
| UTF-8 | Java | 451 | java | AincradPlayerLoginEvent.java | Java | [] | null | [] | /*
* Decompiled with CFR 0_110.
*
* Could not load the following classes:
* org.bukkit.entity.Player
*/
package com.shynixn.thegreatswordartonlinerpg.resources.events.cardinal;
import com.shynixn.thegreatswordartonlinerpg.resources.events.AincradPlayerEvent;
import org.bukkit.entity.Player;
public class AincradPlayerLoginEvent
extends AincradPlayerEvent {
public AincradPlayerLoginEvent(Player player) {
super(player);
}
}
| 451 | 0.776053 | 0.767184 | 17 | 25.470589 | 24.46875 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.235294 | false | false | 4 |
f73b675a85816bf2665633d7ee330ab1072bb1dc | 32,504,312,548,174 | 5286e210d4a938212a407a0dd05a945fca4f070c | /IMDemo/app/src/main/java/com/example/apple/imdemo/controller/activity/NewGroupActivity.java | d89f76d4c4f357123811fc0aa24c6a8a00c426a3 | [] | no_license | ningxingxing/IMDemo | https://github.com/ningxingxing/IMDemo | efdc84c69a71d80baf381762c27383a9ab5c3d4d | 75406308f3d00e32660c3959aa85c19eae8f54f3 | refs/heads/master | 2021-01-13T13:21:38.003000 | 2017-01-11T08:19:25 | 2017-01-11T08:19:25 | 78,617,650 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.apple.imdemo.controller.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.example.apple.imdemo.R;
import com.example.apple.imdemo.model.Model;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroupManager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
//创建新群
public class NewGroupActivity extends AppCompatActivity {
@BindView(R.id.new_group_name)
EditText newGroupName;
@BindView(R.id.new_group_desc)
EditText newGroupDesc;
@BindView(R.id.new_group_public)
CheckBox newGroupPublic;
@BindView(R.id.new_group_invite)
CheckBox newGroupInvite;
@BindView(R.id.new_group_create)
Button newGroupCreate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
setContentView(R.layout.activity_new_group);
ButterKnife.bind(this);
if (getSupportActionBar() != null) {//隐藏标题栏
getSupportActionBar().hide();
}
initData();
}
private void initData() {
}
@OnClick({ R.id.new_group_create})
public void onClick(View view) {
switch (view.getId()) {
case R.id.new_group_create://创建按钮的点击事件
// 跳转到选择联系人页面
Intent intent = new Intent(NewGroupActivity.this, PickContactActivity.class);
startActivityForResult(intent, 1);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 成功获取到联系人
if (resultCode == RESULT_OK) {
// 创建群
createGroup(data.getStringArrayExtra("members"));
}
}
/**
*创建群
*/
private void createGroup(final String[] memberses) {
//群名称
final String groupName = newGroupName.getText().toString();
//群描述
final String groupDesc = newGroupDesc.getText().toString();
Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
@Override
public void run() {
//去环信服务器创建群
//参数一:群名称:参数二:群描述:参数三:群成员:参数四:原因:参数五:参数设置
EMGroupManager.EMGroupOptions options = new EMGroupManager.EMGroupOptions();
options.maxUsers = 200;//群最多容纳多撒后人
EMGroupManager.EMGroupStyle groupStyle = null;
if (newGroupPublic.isChecked()){//公开
if (newGroupInvite.isChecked()){
groupStyle = EMGroupManager.EMGroupStyle.EMGroupStylePublicOpenJoin;//开放群邀请
}else {
groupStyle = EMGroupManager.EMGroupStyle.EMGroupStylePublicJoinNeedApproval;//需要邀请
}
}else {
if (newGroupInvite.isChecked()){//开放群邀请
groupStyle = EMGroupManager.EMGroupStyle.EMGroupStylePrivateMemberCanInvite;//群成员也可以邀请
}else {
groupStyle = EMGroupManager.EMGroupStyle.EMGroupStylePrivateOnlyOwnerInvite;//只有群主
}
}
options.style = groupStyle;//创建群类型
try {
EMClient.getInstance().groupManager().createGroup(groupName,groupDesc,memberses,"申请加入群",options);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplication(),"创建群成功",Toast.LENGTH_SHORT).show();
//结束当前页面
finish();
}
});
}catch (Exception e){
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplication(),"创建群失败",Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
}
| UTF-8 | Java | 4,785 | java | NewGroupActivity.java | Java | [] | null | [] | package com.example.apple.imdemo.controller.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.example.apple.imdemo.R;
import com.example.apple.imdemo.model.Model;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroupManager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
//创建新群
public class NewGroupActivity extends AppCompatActivity {
@BindView(R.id.new_group_name)
EditText newGroupName;
@BindView(R.id.new_group_desc)
EditText newGroupDesc;
@BindView(R.id.new_group_public)
CheckBox newGroupPublic;
@BindView(R.id.new_group_invite)
CheckBox newGroupInvite;
@BindView(R.id.new_group_create)
Button newGroupCreate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
setContentView(R.layout.activity_new_group);
ButterKnife.bind(this);
if (getSupportActionBar() != null) {//隐藏标题栏
getSupportActionBar().hide();
}
initData();
}
private void initData() {
}
@OnClick({ R.id.new_group_create})
public void onClick(View view) {
switch (view.getId()) {
case R.id.new_group_create://创建按钮的点击事件
// 跳转到选择联系人页面
Intent intent = new Intent(NewGroupActivity.this, PickContactActivity.class);
startActivityForResult(intent, 1);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 成功获取到联系人
if (resultCode == RESULT_OK) {
// 创建群
createGroup(data.getStringArrayExtra("members"));
}
}
/**
*创建群
*/
private void createGroup(final String[] memberses) {
//群名称
final String groupName = newGroupName.getText().toString();
//群描述
final String groupDesc = newGroupDesc.getText().toString();
Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
@Override
public void run() {
//去环信服务器创建群
//参数一:群名称:参数二:群描述:参数三:群成员:参数四:原因:参数五:参数设置
EMGroupManager.EMGroupOptions options = new EMGroupManager.EMGroupOptions();
options.maxUsers = 200;//群最多容纳多撒后人
EMGroupManager.EMGroupStyle groupStyle = null;
if (newGroupPublic.isChecked()){//公开
if (newGroupInvite.isChecked()){
groupStyle = EMGroupManager.EMGroupStyle.EMGroupStylePublicOpenJoin;//开放群邀请
}else {
groupStyle = EMGroupManager.EMGroupStyle.EMGroupStylePublicJoinNeedApproval;//需要邀请
}
}else {
if (newGroupInvite.isChecked()){//开放群邀请
groupStyle = EMGroupManager.EMGroupStyle.EMGroupStylePrivateMemberCanInvite;//群成员也可以邀请
}else {
groupStyle = EMGroupManager.EMGroupStyle.EMGroupStylePrivateOnlyOwnerInvite;//只有群主
}
}
options.style = groupStyle;//创建群类型
try {
EMClient.getInstance().groupManager().createGroup(groupName,groupDesc,memberses,"申请加入群",options);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplication(),"创建群成功",Toast.LENGTH_SHORT).show();
//结束当前页面
finish();
}
});
}catch (Exception e){
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplication(),"创建群失败",Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
}
| 4,785 | 0.57348 | 0.572358 | 146 | 29.527397 | 27.124825 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.445205 | false | false | 4 |
e8f29e0e8b787cdd7f83df355580ae25c4998c40 | 5,583,457,535,898 | 930dac132b424f33f7492c5bd570b6fba8bdc4c2 | /IteratorSort/src/main/java/Iter/ListIterator.java | a71e6b7a2a879d52dee919ef27d0b46d503cf412 | [] | no_license | JanSzewczyk/TO | https://github.com/JanSzewczyk/TO | 378b9a1a6011bb74218c6c0cb87895f83c8dd533 | 9f1683911ead27412778bf0730034cc6f35d34be | refs/heads/master | 2018-12-24T23:28:35.376000 | 2018-12-14T22:56:51 | 2018-12-14T22:56:51 | 153,525,493 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Iter;
import java.util.List;
public class ListIterator implements Iterator {
private int posistion = 0;
private List<int[]> items;
public ListIterator(List< int[] > items){
this.items = items;
}
public boolean hasNext() {
if (posistion >= items.size() || items.get(posistion) == null){
return false;
}
return true;
}
public int[] next() {
int item[] = items.get(posistion);
posistion++;
return item;
}
}
| UTF-8 | Java | 517 | java | ListIterator.java | Java | [] | null | [] | package Iter;
import java.util.List;
public class ListIterator implements Iterator {
private int posistion = 0;
private List<int[]> items;
public ListIterator(List< int[] > items){
this.items = items;
}
public boolean hasNext() {
if (posistion >= items.size() || items.get(posistion) == null){
return false;
}
return true;
}
public int[] next() {
int item[] = items.get(posistion);
posistion++;
return item;
}
}
| 517 | 0.562863 | 0.560928 | 25 | 19.68 | 17.939276 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48 | false | false | 4 |
00666ff56259836a7d4d8413c907cb1dff766415 | 12,824,772,388,315 | fc0a6db48786214efc5077e129f5a5cd94d8220e | /src/GestionControles/GestionEstadoControles.java | e9f1ad45cd2252f6d06a43b61f16b011f004636b | [] | no_license | dolfhandler/GanaderiaSystem | https://github.com/dolfhandler/GanaderiaSystem | 66016df6576f21e3074c03da0706e255cfb7c832 | 4b8eb5098ca5a17f02cd858d8bc3b064a38fb9c0 | refs/heads/master | 2022-10-20T10:45:44.089000 | 2022-10-01T00:47:44 | 2022-10-01T00:47:44 | 264,756,594 | 0 | 0 | null | true | 2020-05-17T21:04:27 | 2020-05-17T21:04:26 | 2020-05-16T23:37:23 | 2020-05-16T23:37:21 | 9,523 | 0 | 0 | 0 | null | false | false | /*
* 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 GestionControles;
import com.toedter.calendar.JDateChooser;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author DOLFHANDLER
*/
public class GestionEstadoControles {
private ArrayList<Control> controles;
public GestionEstadoControles() {
controles = new ArrayList<>();
}
public void addControl(Control control) {
controles.add(control);
}
public void limpiarControles() {
for (Control control : controles) {
limpiarComponente(control);
}
}
public void habilitarControles() {
for (Control control : controles) {
habilitarComponente(control);
}
}
public void deshabilitarControles() {
for (Control control : controles) {
deshabilitarComponente(control);
}
}
private void limpiarComponente(Control control) {
if (control.getControl() instanceof JLabel) {
JLabel componente = ((JLabel) control.getControl());
componente.setText("");
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JTable) {
JTable componente = ((JTable) control.getControl());
componente.setModel(new DefaultTableModel());
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JComboBox) {
JComboBox componente = ((JComboBox) control.getControl());
componente.setSelectedIndex(0);
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JSpinner) {
JSpinner componente = ((JSpinner) control.getControl());
componente.setValue(0);
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JSlider) {
JSlider componente = ((JSlider) control.getControl());
componente.setValue(0);
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JTextArea) {
JTextArea componente = ((JTextArea) control.getControl());
componente.setText("");
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JTextField) {
JTextField componente = ((JTextField) control.getControl());
componente.setText("");
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JPasswordField) {
JPasswordField componente = ((JPasswordField) control.getControl());
componente.setText("");
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JTextPane) {
JTextPane componente = ((JTextPane) control.getControl());
componente.setText("");
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JCheckBox) {
JCheckBox componente = ((JCheckBox) control.getControl());
componente.setSelected(false);
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JRadioButton) {
JRadioButton componente = ((JRadioButton) control.getControl());
componente.setSelected(false);
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JDateChooser) {
JDateChooser componente = ((JDateChooser) control.getControl());
componente.setCalendar(Calendar.getInstance());
componente.setEnabled(control.estaHabilitado());
}
}
private void habilitarComponente(Control control) {
boolean habilitar = true;
if (control.getControl() instanceof JLabel) {
JLabel componente = ((JLabel) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTable) {
JTable componente = ((JTable) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JComboBox) {
JComboBox componente = ((JComboBox) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JSpinner) {
JSpinner componente = ((JSpinner) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JSlider) {
JSlider componente = ((JSlider) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTextArea) {
JTextArea componente = ((JTextArea) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTextField) {
JTextField componente = ((JTextField) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JPasswordField) {
JPasswordField componente = ((JPasswordField) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTextPane) {
JTextPane componente = ((JTextPane) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JCheckBox) {
JCheckBox componente = ((JCheckBox) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JRadioButton) {
JRadioButton componente = ((JRadioButton) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JButton) {
JButton componente = ((JButton) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JDateChooser) {
JDateChooser componente = ((JDateChooser) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JPanel) {
JPanel componente = ((JPanel) control.getControl());
componente.setEnabled(habilitar);
}
}
private void deshabilitarComponente(Control control) {
boolean habilitar = false;
if (control.getControl() instanceof JLabel) {
JLabel componente = ((JLabel) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTable) {
JTable componente = ((JTable) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JComboBox) {
JComboBox componente = ((JComboBox) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JSpinner) {
JSpinner componente = ((JSpinner) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JSlider) {
JSlider componente = ((JSlider) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTextArea) {
JTextArea componente = ((JTextArea) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTextField) {
JTextField componente = ((JTextField) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JPasswordField) {
JPasswordField componente = ((JPasswordField) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTextPane) {
JTextPane componente = ((JTextPane) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JCheckBox) {
JCheckBox componente = ((JCheckBox) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JRadioButton) {
JRadioButton componente = ((JRadioButton) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JButton) {
JButton componente = ((JButton) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JDateChooser) {
JDateChooser componente = ((JDateChooser) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JPanel) {
JPanel componente = ((JPanel) control.getControl());
componente.setEnabled(habilitar);
}
}
}
| UTF-8 | Java | 9,698 | java | GestionEstadoControles.java | Java | [
{
"context": ".swing.table.DefaultTableModel;\n\n/**\n *\n * @author DOLFHANDLER\n */\npublic class GestionEstadoControles {\n\n pr",
"end": 827,
"score": 0.9993832111358643,
"start": 816,
"tag": "USERNAME",
"value": "DOLFHANDLER"
}
] | 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 GestionControles;
import com.toedter.calendar.JDateChooser;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author DOLFHANDLER
*/
public class GestionEstadoControles {
private ArrayList<Control> controles;
public GestionEstadoControles() {
controles = new ArrayList<>();
}
public void addControl(Control control) {
controles.add(control);
}
public void limpiarControles() {
for (Control control : controles) {
limpiarComponente(control);
}
}
public void habilitarControles() {
for (Control control : controles) {
habilitarComponente(control);
}
}
public void deshabilitarControles() {
for (Control control : controles) {
deshabilitarComponente(control);
}
}
private void limpiarComponente(Control control) {
if (control.getControl() instanceof JLabel) {
JLabel componente = ((JLabel) control.getControl());
componente.setText("");
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JTable) {
JTable componente = ((JTable) control.getControl());
componente.setModel(new DefaultTableModel());
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JComboBox) {
JComboBox componente = ((JComboBox) control.getControl());
componente.setSelectedIndex(0);
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JSpinner) {
JSpinner componente = ((JSpinner) control.getControl());
componente.setValue(0);
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JSlider) {
JSlider componente = ((JSlider) control.getControl());
componente.setValue(0);
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JTextArea) {
JTextArea componente = ((JTextArea) control.getControl());
componente.setText("");
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JTextField) {
JTextField componente = ((JTextField) control.getControl());
componente.setText("");
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JPasswordField) {
JPasswordField componente = ((JPasswordField) control.getControl());
componente.setText("");
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JTextPane) {
JTextPane componente = ((JTextPane) control.getControl());
componente.setText("");
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JCheckBox) {
JCheckBox componente = ((JCheckBox) control.getControl());
componente.setSelected(false);
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JRadioButton) {
JRadioButton componente = ((JRadioButton) control.getControl());
componente.setSelected(false);
componente.setEnabled(control.estaHabilitado());
} else if (control.getControl() instanceof JDateChooser) {
JDateChooser componente = ((JDateChooser) control.getControl());
componente.setCalendar(Calendar.getInstance());
componente.setEnabled(control.estaHabilitado());
}
}
private void habilitarComponente(Control control) {
boolean habilitar = true;
if (control.getControl() instanceof JLabel) {
JLabel componente = ((JLabel) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTable) {
JTable componente = ((JTable) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JComboBox) {
JComboBox componente = ((JComboBox) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JSpinner) {
JSpinner componente = ((JSpinner) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JSlider) {
JSlider componente = ((JSlider) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTextArea) {
JTextArea componente = ((JTextArea) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTextField) {
JTextField componente = ((JTextField) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JPasswordField) {
JPasswordField componente = ((JPasswordField) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTextPane) {
JTextPane componente = ((JTextPane) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JCheckBox) {
JCheckBox componente = ((JCheckBox) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JRadioButton) {
JRadioButton componente = ((JRadioButton) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JButton) {
JButton componente = ((JButton) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JDateChooser) {
JDateChooser componente = ((JDateChooser) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JPanel) {
JPanel componente = ((JPanel) control.getControl());
componente.setEnabled(habilitar);
}
}
private void deshabilitarComponente(Control control) {
boolean habilitar = false;
if (control.getControl() instanceof JLabel) {
JLabel componente = ((JLabel) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTable) {
JTable componente = ((JTable) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JComboBox) {
JComboBox componente = ((JComboBox) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JSpinner) {
JSpinner componente = ((JSpinner) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JSlider) {
JSlider componente = ((JSlider) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTextArea) {
JTextArea componente = ((JTextArea) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTextField) {
JTextField componente = ((JTextField) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JPasswordField) {
JPasswordField componente = ((JPasswordField) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JTextPane) {
JTextPane componente = ((JTextPane) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JCheckBox) {
JCheckBox componente = ((JCheckBox) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JRadioButton) {
JRadioButton componente = ((JRadioButton) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JButton) {
JButton componente = ((JButton) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JDateChooser) {
JDateChooser componente = ((JDateChooser) control.getControl());
componente.setEnabled(habilitar);
} else if (control.getControl() instanceof JPanel) {
JPanel componente = ((JPanel) control.getControl());
componente.setEnabled(habilitar);
}
}
}
| 9,698 | 0.649309 | 0.649 | 208 | 45.625 | 22.600496 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.591346 | false | false | 4 |
1093935305d70fc3f61b98500ef68c880ddfdb09 | 24,215,025,662,621 | 60b90dc7f1d4ca6e5cc8850f8e9df0187b41fb17 | /new/DEMOSpringUsingHibernate/src/main/java/com/thinkitive/DEMOSpringUsingHibernate/dao/EmployeeDAO.java | 62f7121a9ace1a90a52123474d3f2e3d0eeb9a3a | [] | no_license | anurag-thinkitive/assingment | https://github.com/anurag-thinkitive/assingment | 6727b8c44596a36af2691a7bc224fe1d6f8976a1 | f26abd555103c58cd1ef0702cf7890eab0982131 | refs/heads/main | 2023-03-02T04:35:18.568000 | 2021-02-10T12:35:27 | 2021-02-10T12:35:27 | 333,127,373 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.thinkitive.DEMOSpringUsingHibernate.dao;
import java.util.List;
import com.thinkitive.DEMOSpringUsingHibernate.model.Employee;
public interface EmployeeDAO {
public void addEmployee(Employee e);
public void deleteEmployee(Employee e);
public List<Employee> getEmployee(int empid);
public void updateEmployee(Employee e);
public List<Employee> getall ();
;
}
| UTF-8 | Java | 384 | java | EmployeeDAO.java | Java | [] | null | [] | package com.thinkitive.DEMOSpringUsingHibernate.dao;
import java.util.List;
import com.thinkitive.DEMOSpringUsingHibernate.model.Employee;
public interface EmployeeDAO {
public void addEmployee(Employee e);
public void deleteEmployee(Employee e);
public List<Employee> getEmployee(int empid);
public void updateEmployee(Employee e);
public List<Employee> getall ();
;
}
| 384 | 0.791667 | 0.791667 | 17 | 21.588236 | 21.406593 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
41f5497435f110f1da1753a1e13b01a2be9c8947 | 21,732,534,575,640 | 7fc179608a7421096b450ba749b745d3161a093e | /src/main/java/com/org/woody/woodylibrary/view/TopBarContain.java | 7b5527c3f4b0dc272684587160e126cd5e261dcd | [] | no_license | woodygithub/woodylibrary | https://github.com/woodygithub/woodylibrary | dc067239cce9cbad1351a2de213605d274175f3d | 9df6b4cbd89ad6e2acbd03458cb0cb3891d67a76 | refs/heads/master | 2021-01-10T21:04:41.019000 | 2014-11-07T07:52:53 | 2014-11-07T07:52:53 | 26,309,409 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.org.woody.woodylibrary.view;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.org.woody.woodylibrary.R;
/**类似ActionBar,可以方便集成使用的一个TopBarView */
public class TopBarContain extends LinearLayout {
public static int DefaultBgResId = android.R.color.black;//默认背景
LinearLayout topbar;
View contentView;
TextView titleTv;
Button leftBtn;
Button rightBtn;
ProgressBar progressBar;
@SuppressLint("NewApi")
public TopBarContain(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public TopBarContain(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TopBarContain(Context context) {
super(context);
init();
}
private void init(){
setOrientation(VERTICAL);
topbar= (LinearLayout) View.inflate(getContext(), R.layout.topbar, null);
topbar.setBackgroundResource(DefaultBgResId);
titleTv=(TextView)topbar.findViewById(R.id.topbar_title);
leftBtn=(Button) topbar.findViewById(R.id.topbar_left_btn);
rightBtn=(Button) topbar.findViewById(R.id.topbar_right_btn);
addView(topbar, 0);
progressBar=(ProgressBar) topbar.findViewById(R.id.topbar_progress);
}
public View getTopBar(){
return topbar;
}
public TopBarContain setBackgroundRes(int resId){
topbar.setBackgroundResource(resId);
return this;
}
public TopBarContain setTitle(int resId){
return setTitle(getContext().getString(resId));
}
public TopBarContain setTitle(CharSequence title){
titleTv.setText(title);
return this;
}
public TopBarContain setTitleBg(int resId){
titleTv.setBackgroundResource(resId);
return this;
}
public TopBarContain setTitle(CharSequence title, int drawableLeft, int drawableRight){
titleTv.setText(title);
titleTv.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, 0, drawableRight, 0);
return this;
}
public TopBarContain setProgress(int progress){
progressBar.setProgress(progress);
if(progress>0&&progress<100) progressBar.setVisibility(View.VISIBLE);
else progressBar.setVisibility(View.INVISIBLE);
return this;
}
public TopBarContain setLeftFinish(String btn, int drawableResId){
return setLeftBtn(btn, drawableResId, new OnClickListener() {
@Override
public void onClick(View v) {
Context context=getContext();
if(context instanceof Activity){
((Activity) context).finish();
}
}
});
}
public TopBarContain setLeftBtn(String btn, OnClickListener clickListener){
return setLeftBtn(btn, 0, clickListener);
}
public TopBarContain setLeftBtn(int drawableResId, OnClickListener clickListener){
return setLeftBtn(null, drawableResId, clickListener);
}
public TopBarContain setLeftBtn(String btn, int drawableResId, OnClickListener clickListener){
leftBtn.setText(btn);
leftBtn.setVisibility(View.VISIBLE);
leftBtn.setCompoundDrawablesWithIntrinsicBounds(drawableResId, 0, 0, 0);
leftBtn.setOnClickListener(clickListener);
return this;
}
public TopBarContain setRightBtn(String btn, OnClickListener clickListener){
return setRightBtn(btn, 0, clickListener);
}
public TopBarContain setRightBtn(int drawableResId, OnClickListener clickListener){
return setRightBtn(null, drawableResId, clickListener);
}
public TopBarContain setRightBtn(String btn, int drawableResId, OnClickListener clickListener){
rightBtn.setText(btn);
rightBtn.setVisibility(View.VISIBLE);
rightBtn.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawableResId, 0);
rightBtn.setOnClickListener(clickListener);
return this;
}
public TopBarContain setContentView(int resId){
return setContentView(View.inflate(getContext(), resId, null));
}
public TopBarContain setContentView(View view){
contentView=view;
removeAllViews();
addView(topbar);
addView(view, -1, -1);
return this;
}
public View getContentView(){
return contentView;
}
/**在topBar底下再加一个View,共用TopBar的底色 */
public TopBarContain addViewInner(View view){
topbar.addView(view);
return this;
}
}
| UTF-8 | Java | 4,334 | java | TopBarContain.java | Java | [] | null | [] | package com.org.woody.woodylibrary.view;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.org.woody.woodylibrary.R;
/**类似ActionBar,可以方便集成使用的一个TopBarView */
public class TopBarContain extends LinearLayout {
public static int DefaultBgResId = android.R.color.black;//默认背景
LinearLayout topbar;
View contentView;
TextView titleTv;
Button leftBtn;
Button rightBtn;
ProgressBar progressBar;
@SuppressLint("NewApi")
public TopBarContain(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public TopBarContain(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TopBarContain(Context context) {
super(context);
init();
}
private void init(){
setOrientation(VERTICAL);
topbar= (LinearLayout) View.inflate(getContext(), R.layout.topbar, null);
topbar.setBackgroundResource(DefaultBgResId);
titleTv=(TextView)topbar.findViewById(R.id.topbar_title);
leftBtn=(Button) topbar.findViewById(R.id.topbar_left_btn);
rightBtn=(Button) topbar.findViewById(R.id.topbar_right_btn);
addView(topbar, 0);
progressBar=(ProgressBar) topbar.findViewById(R.id.topbar_progress);
}
public View getTopBar(){
return topbar;
}
public TopBarContain setBackgroundRes(int resId){
topbar.setBackgroundResource(resId);
return this;
}
public TopBarContain setTitle(int resId){
return setTitle(getContext().getString(resId));
}
public TopBarContain setTitle(CharSequence title){
titleTv.setText(title);
return this;
}
public TopBarContain setTitleBg(int resId){
titleTv.setBackgroundResource(resId);
return this;
}
public TopBarContain setTitle(CharSequence title, int drawableLeft, int drawableRight){
titleTv.setText(title);
titleTv.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, 0, drawableRight, 0);
return this;
}
public TopBarContain setProgress(int progress){
progressBar.setProgress(progress);
if(progress>0&&progress<100) progressBar.setVisibility(View.VISIBLE);
else progressBar.setVisibility(View.INVISIBLE);
return this;
}
public TopBarContain setLeftFinish(String btn, int drawableResId){
return setLeftBtn(btn, drawableResId, new OnClickListener() {
@Override
public void onClick(View v) {
Context context=getContext();
if(context instanceof Activity){
((Activity) context).finish();
}
}
});
}
public TopBarContain setLeftBtn(String btn, OnClickListener clickListener){
return setLeftBtn(btn, 0, clickListener);
}
public TopBarContain setLeftBtn(int drawableResId, OnClickListener clickListener){
return setLeftBtn(null, drawableResId, clickListener);
}
public TopBarContain setLeftBtn(String btn, int drawableResId, OnClickListener clickListener){
leftBtn.setText(btn);
leftBtn.setVisibility(View.VISIBLE);
leftBtn.setCompoundDrawablesWithIntrinsicBounds(drawableResId, 0, 0, 0);
leftBtn.setOnClickListener(clickListener);
return this;
}
public TopBarContain setRightBtn(String btn, OnClickListener clickListener){
return setRightBtn(btn, 0, clickListener);
}
public TopBarContain setRightBtn(int drawableResId, OnClickListener clickListener){
return setRightBtn(null, drawableResId, clickListener);
}
public TopBarContain setRightBtn(String btn, int drawableResId, OnClickListener clickListener){
rightBtn.setText(btn);
rightBtn.setVisibility(View.VISIBLE);
rightBtn.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawableResId, 0);
rightBtn.setOnClickListener(clickListener);
return this;
}
public TopBarContain setContentView(int resId){
return setContentView(View.inflate(getContext(), resId, null));
}
public TopBarContain setContentView(View view){
contentView=view;
removeAllViews();
addView(topbar);
addView(view, -1, -1);
return this;
}
public View getContentView(){
return contentView;
}
/**在topBar底下再加一个View,共用TopBar的底色 */
public TopBarContain addViewInner(View view){
topbar.addView(view);
return this;
}
}
| 4,334 | 0.766854 | 0.762875 | 140 | 29.514286 | 24.995281 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.121428 | false | false | 4 |
2273f04ab3b422bab691c9823ca4ee08133b0e94 | 3,375,844,356,894 | fbcf99747ab11a2bbb3231245dbb9d1319a0ed31 | /consumer1/src/main/java/com/test/consumer1/ProductConsumerApplication.java | bc779f60b9d1d41a863e3def379270f893ba9ef1 | [] | no_license | VAMSINANDINIKANTU/Pact-EcommerceApplication | https://github.com/VAMSINANDINIKANTU/Pact-EcommerceApplication | 46ee7f10121baad1282618ac2634979592a0ec25 | 8149e9ef1304c35162b34b1a73b5ec0cbebb7808 | refs/heads/master | 2022-12-21T02:07:43.609000 | 2020-07-27T08:28:28 | 2020-07-27T08:28:28 | 279,352,457 | 0 | 1 | null | false | 2020-09-17T09:30:41 | 2020-07-13T16:15:03 | 2020-07-27T08:28:31 | 2020-09-17T09:30:07 | 102 | 0 | 1 | 1 | Java | false | false | package com.test.consumer1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@SpringBootApplication
public class ProductConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ProductConsumerApplication.class, args);
}
} | UTF-8 | Java | 435 | java | ProductConsumerApplication.java | Java | [] | null | [] | package com.test.consumer1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@SpringBootApplication
public class ProductConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ProductConsumerApplication.class, args);
}
} | 435 | 0.841379 | 0.83908 | 12 | 35.333332 | 23.534843 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 4 |
06afca58d3aa9005df4fc91112fda234feda389a | 35,055,523,100,384 | ac282cb01c94c4d2204b35c0e8317f119a5ebf00 | /(25-01-2021) EP -Practical-4 _Task-1/src/prac4DAOpackage/prac4DAO.java | 819fdb833c2824580fae1e5bbb27493e57afb6f7 | [] | no_license | dsrkreddy81/EP-Practical-1 | https://github.com/dsrkreddy81/EP-Practical-1 | ccf7a528e7a2242d8e1acea5c011c50ca5541983 | d5c35df0fb1311ffc93fdcaed751fb8104166e0f | refs/heads/main | 2023-03-11T21:35:58.413000 | 2021-02-03T15:37:42 | 2021-02-03T15:37:42 | 345,559,223 | 0 | 0 | null | true | 2021-03-08T06:55:33 | 2021-03-08T06:55:32 | 2021-02-03T15:44:24 | 2021-03-08T06:33:45 | 5,071 | 0 | 0 | 0 | null | false | false | package prac4DAOpackage;
import prac4beanpackage.marketBean;
import prac4DBUtilpackage.marketDBUtil;
import java.sql.*;
public class prac4DAO
{
public int insert(marketBean mb,String database,String table) throws ClassNotFoundException, SQLException
{
Connection con=marketDBUtil.DBConnection();
Statement stmt3 = con.createStatement();
stmt3.execute("use "+database);
PreparedStatement ps=con.prepareStatement("insert into "+table+" values(?,?,?)");
ps.setInt(1, mb.getItemID());
ps.setString(2, mb.getItemName());
ps.setDouble(3, mb.getCost());
int i=ps.executeUpdate();
con.close();
return i;
}
public void display(String database,String table) throws ClassNotFoundException, SQLException
{
Connection con=marketDBUtil.DBConnection();
Statement stmt3 = con.createStatement();
stmt3.execute("use "+database);
PreparedStatement ps=con.prepareStatement("select * from "+table);
ResultSet rst=ps.executeQuery();
System.out.println("ITEM-ID\t\tNAME\t\tCOST");
while(rst.next())
{
System.out.println(rst.getInt(1)+"\t\t"+rst.getString(2)+"\t\t"+rst.getDouble(3));
}
con.close();
}
public double getcost(String database,String table) throws SQLException, ClassNotFoundException
{
Connection con=marketDBUtil.DBConnection();
Statement stmt3 = con.createStatement();
stmt3.execute("use "+database);
PreparedStatement ps=con.prepareStatement("select sum(cost) from "+table);
ResultSet rst=ps.executeQuery();
double res=0;
while(rst.next())
{
res=rst.getDouble(1);
}
con.close();
return res;
}
public void initialize(String database,String table) throws SQLException, ClassNotFoundException
{
Connection con=marketDBUtil.DBConnection();
Statement stmt1 = con.createStatement();
stmt1.execute("create database "+database);
Statement stmt3 = con.createStatement();
stmt3.execute("use "+database);
Statement stmt2=con.createStatement();
stmt2.execute("create table "+table+"(itemID int,itemName varchar(50),cost double)");
con.close();
}
}
| UTF-8 | Java | 2,088 | java | prac4DAO.java | Java | [] | null | [] | package prac4DAOpackage;
import prac4beanpackage.marketBean;
import prac4DBUtilpackage.marketDBUtil;
import java.sql.*;
public class prac4DAO
{
public int insert(marketBean mb,String database,String table) throws ClassNotFoundException, SQLException
{
Connection con=marketDBUtil.DBConnection();
Statement stmt3 = con.createStatement();
stmt3.execute("use "+database);
PreparedStatement ps=con.prepareStatement("insert into "+table+" values(?,?,?)");
ps.setInt(1, mb.getItemID());
ps.setString(2, mb.getItemName());
ps.setDouble(3, mb.getCost());
int i=ps.executeUpdate();
con.close();
return i;
}
public void display(String database,String table) throws ClassNotFoundException, SQLException
{
Connection con=marketDBUtil.DBConnection();
Statement stmt3 = con.createStatement();
stmt3.execute("use "+database);
PreparedStatement ps=con.prepareStatement("select * from "+table);
ResultSet rst=ps.executeQuery();
System.out.println("ITEM-ID\t\tNAME\t\tCOST");
while(rst.next())
{
System.out.println(rst.getInt(1)+"\t\t"+rst.getString(2)+"\t\t"+rst.getDouble(3));
}
con.close();
}
public double getcost(String database,String table) throws SQLException, ClassNotFoundException
{
Connection con=marketDBUtil.DBConnection();
Statement stmt3 = con.createStatement();
stmt3.execute("use "+database);
PreparedStatement ps=con.prepareStatement("select sum(cost) from "+table);
ResultSet rst=ps.executeQuery();
double res=0;
while(rst.next())
{
res=rst.getDouble(1);
}
con.close();
return res;
}
public void initialize(String database,String table) throws SQLException, ClassNotFoundException
{
Connection con=marketDBUtil.DBConnection();
Statement stmt1 = con.createStatement();
stmt1.execute("create database "+database);
Statement stmt3 = con.createStatement();
stmt3.execute("use "+database);
Statement stmt2=con.createStatement();
stmt2.execute("create table "+table+"(itemID int,itemName varchar(50),cost double)");
con.close();
}
}
| 2,088 | 0.714559 | 0.702107 | 61 | 32.229507 | 27.97563 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.47541 | false | false | 4 |
2d3f1be61089e639d1768fb95b25798448338e77 | 20,968,030,339,903 | bce07b3c615d115667e324a1b6f496cc3e9e34c9 | /src/domain/service/EstoqueInformatica.java | eb770640472a90011e4487e7358a1575e7574e52 | [] | no_license | Alkhanm/Estoque_Factory | https://github.com/Alkhanm/Estoque_Factory | 166b7463a5f55581e0de08a56c1715143c070738 | 92efa0120d6dae29682e8868dda2d3bdbb115361 | refs/heads/main | 2023-04-16T06:03:20.101000 | 2021-04-06T20:02:13 | 2021-04-06T20:02:13 | 354,549,669 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package domain.service;
import domain.model.Informatica;
import domain.model.Produto;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
// Implementa os métodos definidos na interface "Estoque"
// Essa classe gerência o estoque de produtos de informatica
public class EstoqueInformatica implements Estoque {
List<Informatica> listaInformaticos = new ArrayList<>();
//Lista apenas os produtos informaticos de uma determinda marca
public void filtrarMarca(String marca){
System.out.println("Listando informaticos da marca: " + marca);
listaInformaticos.stream()
.filter(p -> marca.equalsIgnoreCase(p.getMarca()))
.peek(p -> p.setNome(p.getNome().toUpperCase()))
.forEach(System.out::println);
}
@Override public void listar() {
listaInformaticos.forEach(System.out::println);
}
@Override public void valorTotal() {
double total = listaInformaticos.stream()
.map((v) -> v.getUnidade() * v.getValor())
.reduce(0.0, Double::sum);
System.out.println("O valor total: R$ " + total);
}
@Override public void adicionar(Produto prod) {
if (prod instanceof Informatica) {
this.listaInformaticos.add((Informatica) prod);
}
}
@Override public void adicionarTodos(List<Produto> produtos) {
produtos.forEach(this::adicionar);
}
@Override public void remover(int codProduto) {
this.listaInformaticos.removeIf(alimento -> alimento.getCodigo().equals(codProduto));
System.out.println("Produto de código " + codProduto + " removido");
}
}
| UTF-8 | Java | 1,684 | java | EstoqueInformatica.java | Java | [] | null | [] | package domain.service;
import domain.model.Informatica;
import domain.model.Produto;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
// Implementa os métodos definidos na interface "Estoque"
// Essa classe gerência o estoque de produtos de informatica
public class EstoqueInformatica implements Estoque {
List<Informatica> listaInformaticos = new ArrayList<>();
//Lista apenas os produtos informaticos de uma determinda marca
public void filtrarMarca(String marca){
System.out.println("Listando informaticos da marca: " + marca);
listaInformaticos.stream()
.filter(p -> marca.equalsIgnoreCase(p.getMarca()))
.peek(p -> p.setNome(p.getNome().toUpperCase()))
.forEach(System.out::println);
}
@Override public void listar() {
listaInformaticos.forEach(System.out::println);
}
@Override public void valorTotal() {
double total = listaInformaticos.stream()
.map((v) -> v.getUnidade() * v.getValor())
.reduce(0.0, Double::sum);
System.out.println("O valor total: R$ " + total);
}
@Override public void adicionar(Produto prod) {
if (prod instanceof Informatica) {
this.listaInformaticos.add((Informatica) prod);
}
}
@Override public void adicionarTodos(List<Produto> produtos) {
produtos.forEach(this::adicionar);
}
@Override public void remover(int codProduto) {
this.listaInformaticos.removeIf(alimento -> alimento.getCodigo().equals(codProduto));
System.out.println("Produto de código " + codProduto + " removido");
}
}
| 1,684 | 0.658537 | 0.657347 | 48 | 34.020832 | 26.120306 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.354167 | false | false | 4 |
e1b1df35202f34c20621cab8393bb58f95e65eb1 | 38,182,259,266,662 | e0aca33670e79d3cc35553a5401417d045ab1e30 | /src/model/bo/AccountBo.java | 8a99d99a1c5c25d02a419df022f1115497935051 | [] | no_license | vonguyenleduy/hotel | https://github.com/vonguyenleduy/hotel | 3258076b8a5f61818410fcdf9f0623357c53e051 | a41d101e824a5bc63120d0c4081c2e34a083c8bc | refs/heads/master | 2020-04-17T21:51:14.429000 | 2016-11-25T16:18:43 | 2016-11-25T16:18:43 | 67,915,603 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model.bo;
import java.util.ArrayList;
import model.bean.Account;
import model.dao.AccountDao;
public class AccountBo {
AccountDao accountDao=new AccountDao();
public void createAccount(Account account) {
// TODO Auto-generated method stub
accountDao.createAccount(account);
}
public void updateAccount(Account account) {
// TODO Auto-generated method stub
accountDao.updateAccount(account);
}
public int getAccountId(String account) {
return accountDao.getAccountId(account);
}
public ArrayList<Account> getListAccount() {
// TODO Auto-generated method stub
return accountDao.getListAccount();
}
}
| UTF-8 | Java | 639 | java | AccountBo.java | Java | [] | null | [] | package model.bo;
import java.util.ArrayList;
import model.bean.Account;
import model.dao.AccountDao;
public class AccountBo {
AccountDao accountDao=new AccountDao();
public void createAccount(Account account) {
// TODO Auto-generated method stub
accountDao.createAccount(account);
}
public void updateAccount(Account account) {
// TODO Auto-generated method stub
accountDao.updateAccount(account);
}
public int getAccountId(String account) {
return accountDao.getAccountId(account);
}
public ArrayList<Account> getListAccount() {
// TODO Auto-generated method stub
return accountDao.getListAccount();
}
}
| 639 | 0.760563 | 0.760563 | 30 | 20.299999 | 18.116568 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.133333 | false | false | 4 |
3be257f9add4b93f9de18cb3c33fe038c3a98338 | 16,114,717,353,246 | 6a1337d40aaf3355f79229f268122e8d8e8a83c2 | /DLLProjectList.java | 7b9aa655207eaf140ed07199c92ddd8c07fb01af | [] | no_license | JYing1/Abstract-Data-Types | https://github.com/JYing1/Abstract-Data-Types | 1938d0f00e19f39e60f362e070c5b01fb17c77eb | 740f05b1fdb1e79c3ca13295937dd6c6d6832397 | refs/heads/master | 2021-01-10T16:27:30.130000 | 2015-12-03T03:20:04 | 2015-12-03T03:20:04 | 44,846,674 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class DLLProjectList implements ProjectList<DLLNode> {
private DLLNode head;
private DLLNode tail;
public DLLProjectList() {
head = tail = null;
}
public void insertFirst(int value) {
if (head == null) {
head = tail = new DLLNode(value, null, null);
}
else{
head = new DLLNode(value, head, null);
head.getNext().setPrev(head);
}
}
public void insertLast(int value) {
if (tail == null) {
head = tail = new DLLNode(value, null, null);
}
else{
tail = new DLLNode(value, null, tail);
tail.getPrev().setNext(tail);
}
}
public DLLNode first() {
return head;
}
public DLLNode last() {
return tail;
}
public boolean isFirst(DLLNode p) {
if (head == p) {
return true;
}
return false;
}
public boolean isLast(DLLNode p) {
if (tail == p) {
return true;
}
return false;
}
public DLLNode before(DLLNode p) {
if (head == p) {
return null;
}
return p.getPrev();
}
public DLLNode after(DLLNode p) {
if (tail == p) {
return null;
}
return p.getNext();
}
public boolean isEmpty() {
if (tail == null) {
return true;
}
return false;
}
public int size() {
int count = 0;
DLLNode temp = head;
while (temp != null) {
temp = temp.getNext();
count++;
}
return count;
}
}
| UTF-8 | Java | 1,597 | java | DLLProjectList.java | Java | [] | null | [] | public class DLLProjectList implements ProjectList<DLLNode> {
private DLLNode head;
private DLLNode tail;
public DLLProjectList() {
head = tail = null;
}
public void insertFirst(int value) {
if (head == null) {
head = tail = new DLLNode(value, null, null);
}
else{
head = new DLLNode(value, head, null);
head.getNext().setPrev(head);
}
}
public void insertLast(int value) {
if (tail == null) {
head = tail = new DLLNode(value, null, null);
}
else{
tail = new DLLNode(value, null, tail);
tail.getPrev().setNext(tail);
}
}
public DLLNode first() {
return head;
}
public DLLNode last() {
return tail;
}
public boolean isFirst(DLLNode p) {
if (head == p) {
return true;
}
return false;
}
public boolean isLast(DLLNode p) {
if (tail == p) {
return true;
}
return false;
}
public DLLNode before(DLLNode p) {
if (head == p) {
return null;
}
return p.getPrev();
}
public DLLNode after(DLLNode p) {
if (tail == p) {
return null;
}
return p.getNext();
}
public boolean isEmpty() {
if (tail == null) {
return true;
}
return false;
}
public int size() {
int count = 0;
DLLNode temp = head;
while (temp != null) {
temp = temp.getNext();
count++;
}
return count;
}
}
| 1,597 | 0.48779 | 0.487163 | 82 | 18.475609 | 14.184521 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.804878 | false | false | 4 |
5b6fe56f740db8400e8ca937457f8cb1b24d451d | 27,565,100,158,152 | b68db67cdd80e450a13e318c19cf271dfaf3edef | /LongestSubstring.java | 122c32a6653c4fb477ecb4d7e8ef4270c119ed9f | [] | no_license | aerodc/leetCode | https://github.com/aerodc/leetCode | 2f495f2f8f8768b97a1e6bcc47f81c3f52e86ed3 | 747b6c868d7fe0bc49ecbdc88f13b594e63d972f | refs/heads/master | 2021-01-10T14:53:33.197000 | 2016-01-27T15:37:49 | 2016-01-27T15:37:49 | 45,684,260 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Arrays;
public class LongestSubstring {
public int lengthOfLongestSubstring(String s) {
int[] charMap = new int[256];
Arrays.fill(charMap, -1);
int maxLength=0,j=0;
for (int i=0; i < s.length();i++){
if(charMap[s.charAt(i)]>=j){
j=charMap[s.charAt(i)]+1;
}
charMap[s.charAt(i)]=i;
maxLength= Math.max(i-j+1, maxLength);
}
return maxLength;
}
}
| UTF-8 | Java | 467 | java | LongestSubstring.java | Java | [] | null | [] | import java.util.Arrays;
public class LongestSubstring {
public int lengthOfLongestSubstring(String s) {
int[] charMap = new int[256];
Arrays.fill(charMap, -1);
int maxLength=0,j=0;
for (int i=0; i < s.length();i++){
if(charMap[s.charAt(i)]>=j){
j=charMap[s.charAt(i)]+1;
}
charMap[s.charAt(i)]=i;
maxLength= Math.max(i-j+1, maxLength);
}
return maxLength;
}
}
| 467 | 0.535332 | 0.51606 | 30 | 14.566667 | 14.586943 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.466667 | false | false | 4 |
16c50866aa96556d771e17ee6ccae3845741b3fe | 28,578,712,434,177 | 5f14068bc906c90d1a8fcd006e830a325218658b | /TestHibernate/src/com/test/TestcascadeSave.java | 43348c6f0ae68e161dd5b66c901fc3596a4cb772 | [] | no_license | ltw546166132/SQLExample | https://github.com/ltw546166132/SQLExample | d5f05bce07820e3261af2a17e387b509ee972f41 | 902b559af384bd28c99f07a514d144a557702c5a | refs/heads/master | 2020-03-22T08:03:32.339000 | 2018-09-12T14:03:51 | 2018-09-12T14:03:51 | 139,741,734 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.Utils.HibernateUtil;
import com.javabean.Customer;
import com.javabean.LinkMan;
public class TestcascadeSave {
@Test
public void savecascade() {
Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Customer customer = new Customer();
customer.setC_name("kehu1");
customer.setC_phone("123456");
customer.setC_mobile("123456");
LinkMan linkMan1 = new LinkMan();
linkMan1.setL_name("linkman1");
linkMan1.setL_phone("linkmanphone123456");
LinkMan linkMan2 = new LinkMan();
linkMan2.setL_name("linkman2");
linkMan2.setL_phone("linkmanphone654321");
linkMan1.setCustomer(customer);
linkMan2.setCustomer(customer);
customer.getLinkmans().add(linkMan1);
customer.getLinkmans().add(linkMan2);
session.save(customer);
transaction.commit();
}
}
| UTF-8 | Java | 945 | java | TestcascadeSave.java | Java | [
{
"context": " customer = new Customer();\n\t\tcustomer.setC_name(\"kehu1\");\n\t\tcustomer.setC_phone(\"123456\");\n\t\tcustomer.se",
"end": 441,
"score": 0.9987785816192627,
"start": 436,
"tag": "USERNAME",
"value": "kehu1"
}
] | null | [] | package com.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.Utils.HibernateUtil;
import com.javabean.Customer;
import com.javabean.LinkMan;
public class TestcascadeSave {
@Test
public void savecascade() {
Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Customer customer = new Customer();
customer.setC_name("kehu1");
customer.setC_phone("123456");
customer.setC_mobile("123456");
LinkMan linkMan1 = new LinkMan();
linkMan1.setL_name("linkman1");
linkMan1.setL_phone("linkmanphone123456");
LinkMan linkMan2 = new LinkMan();
linkMan2.setL_name("linkman2");
linkMan2.setL_phone("linkmanphone654321");
linkMan1.setCustomer(customer);
linkMan2.setCustomer(customer);
customer.getLinkmans().add(linkMan1);
customer.getLinkmans().add(linkMan2);
session.save(customer);
transaction.commit();
}
}
| 945 | 0.756614 | 0.71746 | 32 | 28.53125 | 13.876654 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 4 |
36a258eab15d67da4b26799780755067914c6091 | 11,184,094,898,639 | bfc5f86968732a9bcbf63fe9906ce0cc25167859 | /src/main/java/com/ecommerce/controller/AccountController.java | 44337301f35501a874c3e07b2bd983d95f57414c | [] | no_license | fiser-tinhpt5/EcommerceService | https://github.com/fiser-tinhpt5/EcommerceService | 1e0161ac87c97ee36dfbc0677d51efbce33f3a20 | da1a847a81984e532f5e636c213dd01982fdfcd4 | refs/heads/master | 2021-01-10T11:29:19.402000 | 2016-03-29T15:14:22 | 2016-03-29T15:14:22 | 51,991,377 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ecommerce.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.ecommerce.dao.AccountDAO;
import com.ecommerce.model.Account;
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountDAO accountDAO;
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public List<Account> findAll() {
return accountDAO.findAll();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Account findById(@PathVariable(value = "id") long id) {
return accountDAO.findById(id);
}
@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody Account account) {
accountDAO.persist(account);
}
@RequestMapping(value = "", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public void update(@RequestBody Account account) {
accountDAO.update(account);
}
@RequestMapping(value = "", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public void delete(@RequestBody Account account) {
accountDAO.delete(account);
}
@RequestMapping(value = "/user-pass", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Account findByUserNamePassword(String userName, String password) {
return accountDAO.findByUserNamePassword(userName, password);
}
@RequestMapping(value = "/email", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Account findByEmail(String email) {
return accountDAO.findByEmail(email);
}
}
| UTF-8 | Java | 2,115 | java | AccountController.java | Java | [] | null | [] | package com.ecommerce.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.ecommerce.dao.AccountDAO;
import com.ecommerce.model.Account;
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountDAO accountDAO;
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public List<Account> findAll() {
return accountDAO.findAll();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Account findById(@PathVariable(value = "id") long id) {
return accountDAO.findById(id);
}
@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody Account account) {
accountDAO.persist(account);
}
@RequestMapping(value = "", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public void update(@RequestBody Account account) {
accountDAO.update(account);
}
@RequestMapping(value = "", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public void delete(@RequestBody Account account) {
accountDAO.delete(account);
}
@RequestMapping(value = "/user-pass", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Account findByUserNamePassword(String userName, String password) {
return accountDAO.findByUserNamePassword(userName, password);
}
@RequestMapping(value = "/email", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Account findByEmail(String email) {
return accountDAO.findByEmail(email);
}
}
| 2,115 | 0.760284 | 0.760284 | 67 | 29.567163 | 23.713604 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.179104 | false | false | 4 |
7402e4e31a3c0a1cb1ef6d5d42581e9c036e63ec | 11,184,094,899,751 | 5a11bf439622f5e104ad4de21e2dc2da8409e5f5 | /app/src/main/java/com/example/hsknows/accountFragment/MessageFragment.java | 1e8504cd2d7bb8e269509743b2041a298d003621 | [] | no_license | Our-project-HSKnow/HSKnow | https://github.com/Our-project-HSKnow/HSKnow | d2fb77d1a4e88042b05282bd6c19cd5a16912b80 | 9fe6c2481d4fee0f408751808639023885b9a2f6 | refs/heads/master | 2023-08-18T18:09:12.503000 | 2021-10-12T12:41:46 | 2021-10-12T12:41:46 | 356,235,977 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.hsknows.accountFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.hsknows.CardImageInfor_message;
import com.example.hsknows.MyRecyclerAdapter_message;
import com.example.myapplication.R;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Use the {@link MessageFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MessageFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private RecyclerView recyclerView;
public MessageFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment MessageFragment.
*/
// TODO: Rename and change types and number of parameters
public static MessageFragment newInstance(String param1, String param2) {
MessageFragment fragment = new MessageFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.account_message, container, false);
recyclerView = view.findViewById(R.id.account_message_recyclerview);
initDatas(3);
return view;
}
private void initDatas(int kind) {
//添加数据
List<CardImageInfor_message> list = new ArrayList<>();
list.add(new CardImageInfor_message("Title 1", "BLGS", "一阶导, 二阶导, 三阶导, 四阶导, 导导导导", kind));
list.add(new CardImageInfor_message("Title 2", "BLGS", "一阶导, 二阶导, 三阶导, 四阶导, 导导导导", kind));
list.add(new CardImageInfor_message("Title 3", "BLGS", "一阶导, 二阶导, 三阶导, 四阶导, 导导导导", kind));
//设置列表显示方式
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//设置列表默认动画效果
recyclerView.setItemAnimator(new DefaultItemAnimator());
//绑定适配器
MyRecyclerAdapter_message myAdapter = new MyRecyclerAdapter_message(list);
recyclerView.setAdapter(myAdapter);
//列表点击事件
myAdapter.setOnItemClickLitener(new MyRecyclerAdapter_message.OnItemClickLitener(){
@Override
public void onItemClick(View view, int position) {
Toast.makeText(getActivity(), "click"+ position +"item", Toast.LENGTH_SHORT).show();
}
});
}
} | UTF-8 | Java | 3,868 | java | MessageFragment.java | Java | [] | null | [] | package com.example.hsknows.accountFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.hsknows.CardImageInfor_message;
import com.example.hsknows.MyRecyclerAdapter_message;
import com.example.myapplication.R;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Use the {@link MessageFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MessageFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private RecyclerView recyclerView;
public MessageFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment MessageFragment.
*/
// TODO: Rename and change types and number of parameters
public static MessageFragment newInstance(String param1, String param2) {
MessageFragment fragment = new MessageFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.account_message, container, false);
recyclerView = view.findViewById(R.id.account_message_recyclerview);
initDatas(3);
return view;
}
private void initDatas(int kind) {
//添加数据
List<CardImageInfor_message> list = new ArrayList<>();
list.add(new CardImageInfor_message("Title 1", "BLGS", "一阶导, 二阶导, 三阶导, 四阶导, 导导导导", kind));
list.add(new CardImageInfor_message("Title 2", "BLGS", "一阶导, 二阶导, 三阶导, 四阶导, 导导导导", kind));
list.add(new CardImageInfor_message("Title 3", "BLGS", "一阶导, 二阶导, 三阶导, 四阶导, 导导导导", kind));
//设置列表显示方式
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//设置列表默认动画效果
recyclerView.setItemAnimator(new DefaultItemAnimator());
//绑定适配器
MyRecyclerAdapter_message myAdapter = new MyRecyclerAdapter_message(list);
recyclerView.setAdapter(myAdapter);
//列表点击事件
myAdapter.setOnItemClickLitener(new MyRecyclerAdapter_message.OnItemClickLitener(){
@Override
public void onItemClick(View view, int position) {
Toast.makeText(getActivity(), "click"+ position +"item", Toast.LENGTH_SHORT).show();
}
});
}
} | 3,868 | 0.683867 | 0.677349 | 102 | 35.107841 | 27.345253 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.627451 | false | false | 4 |
ec4e375f2708d9fb6415f4822d805da52e1c632c | 30,185,030,197,219 | eaf844cd0efa137fe5f536f8bc7ed5923ce39f80 | /weixin/src/main/java/kaiyi/puer/weixin/user/manager/QueryUserInGroupRequest.java | ac629d0d04998a3e905b2daef86a5dccec3fcc9b | [] | no_license | dengkai1982/teacup | https://github.com/dengkai1982/teacup | abc148eb0ead4c424842d94bd3a2c92c96ac6931 | 578bdcf68f44c603aae2d1edac3cdb594431ae5f | refs/heads/master | 2019-04-28T18:20:32.588000 | 2018-12-20T17:21:38 | 2018-12-20T17:21:39 | 94,093,132 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kaiyi.puer.weixin.user.manager;
import kaiyi.puer.http.HttpMethod;
import kaiyi.puer.weixin.WeixinInfo;
import kaiyi.puer.weixin.request.WeixinRequest;
/**
* 查询用户所在分组
*
*/
public class QueryUserInGroupRequest extends WeixinRequest<QueryUserInGroupResponse> {
private String accessToken;
private String openid;
public QueryUserInGroupRequest(WeixinInfo info, String accessToken, String openid) {
super(info);
this.accessToken = accessToken;
this.openid = openid;
}
@Override
public HttpMethod getMethod() {
return HttpMethod.POST;
}
@Override
protected boolean hasContent() {
return true;
}
@Override
protected String getContent() {
return "{\"openid\":\""+openid+"\"}";
}
@Override
public String getUrl() {
return "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token="+accessToken;
}
@Override
protected QueryUserInGroupResponse parseToResponse(String result) {
return new QueryUserInGroupResponse(result);
}
}
| UTF-8 | Java | 994 | java | QueryUserInGroupRequest.java | Java | [
{
"context": "ring openid) {\n\t\tsuper(info);\n\t\tthis.accessToken = accessToken;\n\t\tthis.openid = openid;\n\t}\n\t\n\t@Override\n\tpublic ",
"end": 462,
"score": 0.7169705033302307,
"start": 451,
"tag": "KEY",
"value": "accessToken"
}
] | null | [] | package kaiyi.puer.weixin.user.manager;
import kaiyi.puer.http.HttpMethod;
import kaiyi.puer.weixin.WeixinInfo;
import kaiyi.puer.weixin.request.WeixinRequest;
/**
* 查询用户所在分组
*
*/
public class QueryUserInGroupRequest extends WeixinRequest<QueryUserInGroupResponse> {
private String accessToken;
private String openid;
public QueryUserInGroupRequest(WeixinInfo info, String accessToken, String openid) {
super(info);
this.accessToken = accessToken;
this.openid = openid;
}
@Override
public HttpMethod getMethod() {
return HttpMethod.POST;
}
@Override
protected boolean hasContent() {
return true;
}
@Override
protected String getContent() {
return "{\"openid\":\""+openid+"\"}";
}
@Override
public String getUrl() {
return "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token="+accessToken;
}
@Override
protected QueryUserInGroupResponse parseToResponse(String result) {
return new QueryUserInGroupResponse(result);
}
}
| 994 | 0.747444 | 0.747444 | 47 | 19.80851 | 23.556757 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.12766 | false | false | 4 |
212e727334186ab2725fafd21b04797fed2fe343 | 35,957,466,208,966 | ba506656987bf519c2dad607462471d65c1dd066 | /src/main/java/net/rest/cinemaseatingmap/dao/SessionDAOImpl.java | 2d01a6014c4badc18da40e59a12f03d9adbe5326 | [] | no_license | tyanigor/cinema-seating-map | https://github.com/tyanigor/cinema-seating-map | 4408289a8e352700cc7a19cc8a6ab4a259be66b8 | decff4e77851d6d25c8a89b1acac134036500cd5 | refs/heads/master | 2021-01-13T00:14:33.562000 | 2018-05-12T07:19:10 | 2018-05-12T07:19:10 | 48,502,975 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.rest.cinemaseatingmap.dao;
import net.rest.cinemaseatingmap.model.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
/**
* Реализация DAO для сеанса
*/
@Repository("sessionDAO")
public class SessionDAOImpl extends AbstractDAO<Integer, Session> implements SessionDAO {
/**
* Получение сеанса по первичному ключу
*
* @param id - первичный ключ
* @return - модель сеанса
*/
@Override
public Session findSessionById(int id) {
return getByKey(id);
}
/**
* Сохранение сеанса
*
* @param session - модель сеанса
*/
@Override
public void persistSession(Session session) {
persist(session);
}
/**
* Удаление сеанса
*
* @param session - модель сеанса
*/
@Override
public void deleteSession(Session session) {
delete(session);
}
/**
* Получение списка сеансов
*
* @return - список моделей сеансов
*/
@Override
public List<Session> listSessions() {
return list();
}
/**
* По заданному началу сеанса и консу сеанса ищет все
* сеансы входящие в данный промежуток
*
* @param startDate - дата начала сеанса
* @param endDate - дата конца сенса
* @return - сеансы которые входят в данное условие
*/
@Override
public List<Session> findSessionByStartDateAndEndDate(Date startDate, Date endDate) {
return (List<Session>) createEntityCriteria()
.add(Restrictions.or(Restrictions.between("start", startDate, endDate),
Restrictions.between("end", startDate, endDate)))
.list();
}
}
| UTF-8 | Java | 2,098 | java | SessionDAOImpl.java | Java | [] | null | [] | package net.rest.cinemaseatingmap.dao;
import net.rest.cinemaseatingmap.model.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
/**
* Реализация DAO для сеанса
*/
@Repository("sessionDAO")
public class SessionDAOImpl extends AbstractDAO<Integer, Session> implements SessionDAO {
/**
* Получение сеанса по первичному ключу
*
* @param id - первичный ключ
* @return - модель сеанса
*/
@Override
public Session findSessionById(int id) {
return getByKey(id);
}
/**
* Сохранение сеанса
*
* @param session - модель сеанса
*/
@Override
public void persistSession(Session session) {
persist(session);
}
/**
* Удаление сеанса
*
* @param session - модель сеанса
*/
@Override
public void deleteSession(Session session) {
delete(session);
}
/**
* Получение списка сеансов
*
* @return - список моделей сеансов
*/
@Override
public List<Session> listSessions() {
return list();
}
/**
* По заданному началу сеанса и консу сеанса ищет все
* сеансы входящие в данный промежуток
*
* @param startDate - дата начала сеанса
* @param endDate - дата конца сенса
* @return - сеансы которые входят в данное условие
*/
@Override
public List<Session> findSessionByStartDateAndEndDate(Date startDate, Date endDate) {
return (List<Session>) createEntityCriteria()
.add(Restrictions.or(Restrictions.between("start", startDate, endDate),
Restrictions.between("end", startDate, endDate)))
.list();
}
}
| 2,098 | 0.622905 | 0.622905 | 72 | 23.861111 | 23.043621 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
528dfb14e80fde4d5d07fa22d8ea54ee9420550f | 35,957,466,209,907 | 69678c018546f6ff8be9333e89878d58124b1437 | /src/main/java/csns/web/controller/SiteController.java | 19b96b6d03b563244a42befce0153d6c29b34ca9 | [] | no_license | sguttula/CSNS | https://github.com/sguttula/CSNS | 552b6cc074bdd04ba825b6e0b29bdeb9069e2c5e | 67fbdbaa2c22f1a2f24ecac73aa6d83bace92b6d | refs/heads/master | 2021-07-24T11:45:49.897000 | 2020-12-31T20:39:53 | 2020-12-31T20:39:53 | 233,932,384 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package csns.web.controller;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import csns.model.academics.Course;
import csns.model.academics.Term;
import csns.model.academics.Section;
import csns.model.academics.dao.CourseDao;
import csns.model.academics.dao.SectionDao;
import csns.model.core.File;
import csns.model.core.Resource;
import csns.model.core.User;
import csns.model.core.dao.FileDao;
import csns.model.core.dao.ResourceDao;
import csns.model.site.Site;
import csns.model.site.dao.ItemDao;
import csns.model.site.dao.SiteDao;
import csns.security.SecurityUtils;
import csns.util.FileIO;
@Controller
public class SiteController {
@Autowired
private SiteDao siteDao;
@Autowired
private ItemDao itemDao;
@Autowired
private ResourceDao resourceDao;
@Autowired
private CourseDao courseDao;
@Autowired
private SectionDao sectionDao;
@Autowired
private FileDao fileDao;
@Autowired
private FileIO fileIO;
private static Logger logger = LoggerFactory
.getLogger( SiteController.class );
private Section getSection( String qtr, String cc, int sn )
{
Term term = new Term();
term.setShortString( qtr );
Course course = courseDao.getCourse( cc );
return sectionDao.getSection( term, course, sn );
}
@RequestMapping("/site/{qtr}/{cc}-{sn}")
public String view( @PathVariable String qtr, @PathVariable String cc,
@PathVariable int sn, ModelMap models )
{
Section section = getSection( qtr, cc, sn );
User user = SecurityUtils.getUser();
boolean isInstructor = section.isInstructor( user );
boolean isStudent = section.isEnrolled( user );
boolean isAdmin = user != null && user.isAdmin();
models.put( "section", section );
models.put( "isInstructor", isInstructor );
models.put( "isStudent", isStudent );
if( section == null || section.getSite() == null )
{
if( isInstructor ) models.put( "sites",
siteDao.getSites( section.getCourse(), user, 10 ) );
return "site/nosite";
}
Site site = section.getSite();
if( site.isRestricted() && !isStudent && !isInstructor && !isAdmin )
{
models.put( "message", "error.site.restricted" );
return "error";
}
if( site.isLimited() && section.getTerm().before( new Date() )
&& !isInstructor && !isAdmin )
{
models.put( "message", "error.site.limited" );
return "error";
}
return "site/view";
}
private String create( Long sectionId, Site oldSite )
{
Section section = sectionDao.getSection( sectionId );
if( section.getSite() != null )
return "redirect:" + section.getSiteUrl();
Site site = new Site( section );
if( oldSite != null )
{
site = oldSite.clone();
site.setSection( section );
if( oldSite.getSection().getSyllabus() != null
&& section.getSyllabus() == null )
{
section
.setSyllabus( oldSite.getSection().getSyllabus().clone() );
section = sectionDao.saveSection( section );
}
}
site = siteDao.saveSite( site );
logger.info( SecurityUtils.getUser().getUsername()
+ " created site for section " + section.getId() );
return "redirect:" + section.getSiteUrl() + "/block/list";
}
@RequestMapping(value = "/site/create", params = "siteId")
public String create( @RequestParam Long sectionId, Long siteId )
{
return create( sectionId, siteDao.getSite( siteId ) );
}
@RequestMapping(value = "/site/create", params = "siteUrl")
public String create( @RequestParam Long sectionId, String siteUrl,
ModelMap models )
{
String tokens[] = siteUrl.split( "/|-" );
int index = -1;
for( int i = 0; i < tokens.length; ++i )
if( tokens[i].equalsIgnoreCase( "site" ) )
{
index = i;
break;
}
if( index < 0 || tokens.length <= index + 3 )
{
models.put( "message", "error.site.invalid.url" );
return "error";
}
String qtr = tokens[index + 1];
String cc = tokens[index + 2];
int sn = Integer.parseInt( tokens[index + 3] );
return create( sectionId, getSection( qtr, cc, sn ).getSite() );
}
@RequestMapping(value = "/site/create")
public String create( @RequestParam Long sectionId )
{
return create( sectionId, (Site) null );
}
@RequestMapping("/site/{qtr}/{cc}-{sn}/settings")
public String settings( @PathVariable String qtr, @PathVariable String cc,
@PathVariable int sn, ModelMap models )
{
Section section = getSection( qtr, cc, sn );
models.put( "section", section );
models.put( "site", section.getSite() );
return "site/settings";
}
@RequestMapping("/site/{qtr}/{cc}-{sn}/settings/toggle")
@ResponseStatus(HttpStatus.OK)
public void toggleSetting( @PathVariable String qtr,
@PathVariable String cc, @PathVariable int sn,
@RequestParam String setting, ModelMap models )
{
Site site = getSection( qtr, cc, sn ).getSite();
Boolean result = site.toggleSetting( setting );
site = siteDao.saveSite( site );
logger.info( SecurityUtils.getUser().getUsername() + " set " + setting
+ " to " + result + " for site " + site.getId() );
}
private String resource( String qtr, String cc, int sn, Resource resource,
ModelMap models, HttpServletResponse response )
{
if( resource.isDeleted() )
{
models.put( "message", "error.site.item.deleted" );
models.put( "backUrl", "/site/" + qtr + "/" + cc + "-" + sn );
return "error";
}
switch( resource.getType() )
{
case TEXT:
models.put( "resource", resource );
return "site/resource";
case FILE:
fileIO.write( resource.getFile(), response );
return null;
case URL:
return "redirect:" + resource.getUrl();
default:
logger.warn( "Invalid resource type: " + resource.getType() );
return "redirect:" + getSection( qtr, cc, sn ).getSiteUrl();
}
}
@RequestMapping("/site/{qtr}/{cc}-{sn}/resource/{id}")
public String resource( @PathVariable String qtr, @PathVariable String cc,
@PathVariable int sn, @PathVariable Long id, ModelMap models,
HttpServletResponse response )
{
return resource( qtr, cc, sn, resourceDao.getResource( id ), models,
response );
}
@RequestMapping("/site/{qtr}/{cc}-{sn}/item/{id}")
public String item( @PathVariable String qtr, @PathVariable String cc,
@PathVariable int sn, @PathVariable Long id, ModelMap models,
HttpServletResponse response )
{
return resource( qtr, cc, sn, itemDao.getItem( id ).getResource(),
models, response );
}
private File getFolder( File parent, String name )
{
User user = SecurityUtils.getUser();
List<File> results = fileDao.getFiles( user, parent, name, true );
if( results.size() > 0 ) return results.get( 0 );
File folder = new File();
folder.setName( name );
folder.setFolder( true );
folder.setRegular( true );
folder.setParent( parent );
folder.setOwner( user );
folder = fileDao.saveFile( folder );
String parentName = parent != null ? parent.getName() : "root";
logger.info( user.getUsername() + " created folder " + name + " under "
+ parentName );
return folder;
}
@RequestMapping("/site/{qtr}/{cc}-{sn}/files/")
public String folder( @PathVariable String qtr, @PathVariable String cc,
@PathVariable int sn )
{
Site site = getSection( qtr, cc, sn ).getSite();
if( site.getFolder() != null )
return "redirect:/file/view?id=" + site.getFolder().getId();
File folder = getFolder( null, "Courses" );
folder = getFolder( folder, cc.toUpperCase() );
folder = getFolder( folder, qtr.toUpperCase() );
site.setFolder( folder );
site = siteDao.saveSite( site );
return "redirect:/file/view?id=" + folder.getId();
}
@RequestMapping("/site/{qtr}/{cc}-{sn}/files/remove")
public String removeFolder( @PathVariable String qtr,
@PathVariable String cc, @PathVariable int sn )
{
Site site = getSection( qtr, cc, sn ).getSite();
site.setFolder( null );
site = siteDao.saveSite( site );
return "redirect:/site/" + qtr + "/" + cc + "-" + sn;
}
}
| UTF-8 | Java | 9,595 | java | SiteController.java | Java | [] | null | [] | package csns.web.controller;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import csns.model.academics.Course;
import csns.model.academics.Term;
import csns.model.academics.Section;
import csns.model.academics.dao.CourseDao;
import csns.model.academics.dao.SectionDao;
import csns.model.core.File;
import csns.model.core.Resource;
import csns.model.core.User;
import csns.model.core.dao.FileDao;
import csns.model.core.dao.ResourceDao;
import csns.model.site.Site;
import csns.model.site.dao.ItemDao;
import csns.model.site.dao.SiteDao;
import csns.security.SecurityUtils;
import csns.util.FileIO;
@Controller
public class SiteController {
@Autowired
private SiteDao siteDao;
@Autowired
private ItemDao itemDao;
@Autowired
private ResourceDao resourceDao;
@Autowired
private CourseDao courseDao;
@Autowired
private SectionDao sectionDao;
@Autowired
private FileDao fileDao;
@Autowired
private FileIO fileIO;
private static Logger logger = LoggerFactory
.getLogger( SiteController.class );
private Section getSection( String qtr, String cc, int sn )
{
Term term = new Term();
term.setShortString( qtr );
Course course = courseDao.getCourse( cc );
return sectionDao.getSection( term, course, sn );
}
@RequestMapping("/site/{qtr}/{cc}-{sn}")
public String view( @PathVariable String qtr, @PathVariable String cc,
@PathVariable int sn, ModelMap models )
{
Section section = getSection( qtr, cc, sn );
User user = SecurityUtils.getUser();
boolean isInstructor = section.isInstructor( user );
boolean isStudent = section.isEnrolled( user );
boolean isAdmin = user != null && user.isAdmin();
models.put( "section", section );
models.put( "isInstructor", isInstructor );
models.put( "isStudent", isStudent );
if( section == null || section.getSite() == null )
{
if( isInstructor ) models.put( "sites",
siteDao.getSites( section.getCourse(), user, 10 ) );
return "site/nosite";
}
Site site = section.getSite();
if( site.isRestricted() && !isStudent && !isInstructor && !isAdmin )
{
models.put( "message", "error.site.restricted" );
return "error";
}
if( site.isLimited() && section.getTerm().before( new Date() )
&& !isInstructor && !isAdmin )
{
models.put( "message", "error.site.limited" );
return "error";
}
return "site/view";
}
private String create( Long sectionId, Site oldSite )
{
Section section = sectionDao.getSection( sectionId );
if( section.getSite() != null )
return "redirect:" + section.getSiteUrl();
Site site = new Site( section );
if( oldSite != null )
{
site = oldSite.clone();
site.setSection( section );
if( oldSite.getSection().getSyllabus() != null
&& section.getSyllabus() == null )
{
section
.setSyllabus( oldSite.getSection().getSyllabus().clone() );
section = sectionDao.saveSection( section );
}
}
site = siteDao.saveSite( site );
logger.info( SecurityUtils.getUser().getUsername()
+ " created site for section " + section.getId() );
return "redirect:" + section.getSiteUrl() + "/block/list";
}
@RequestMapping(value = "/site/create", params = "siteId")
public String create( @RequestParam Long sectionId, Long siteId )
{
return create( sectionId, siteDao.getSite( siteId ) );
}
@RequestMapping(value = "/site/create", params = "siteUrl")
public String create( @RequestParam Long sectionId, String siteUrl,
ModelMap models )
{
String tokens[] = siteUrl.split( "/|-" );
int index = -1;
for( int i = 0; i < tokens.length; ++i )
if( tokens[i].equalsIgnoreCase( "site" ) )
{
index = i;
break;
}
if( index < 0 || tokens.length <= index + 3 )
{
models.put( "message", "error.site.invalid.url" );
return "error";
}
String qtr = tokens[index + 1];
String cc = tokens[index + 2];
int sn = Integer.parseInt( tokens[index + 3] );
return create( sectionId, getSection( qtr, cc, sn ).getSite() );
}
@RequestMapping(value = "/site/create")
public String create( @RequestParam Long sectionId )
{
return create( sectionId, (Site) null );
}
@RequestMapping("/site/{qtr}/{cc}-{sn}/settings")
public String settings( @PathVariable String qtr, @PathVariable String cc,
@PathVariable int sn, ModelMap models )
{
Section section = getSection( qtr, cc, sn );
models.put( "section", section );
models.put( "site", section.getSite() );
return "site/settings";
}
@RequestMapping("/site/{qtr}/{cc}-{sn}/settings/toggle")
@ResponseStatus(HttpStatus.OK)
public void toggleSetting( @PathVariable String qtr,
@PathVariable String cc, @PathVariable int sn,
@RequestParam String setting, ModelMap models )
{
Site site = getSection( qtr, cc, sn ).getSite();
Boolean result = site.toggleSetting( setting );
site = siteDao.saveSite( site );
logger.info( SecurityUtils.getUser().getUsername() + " set " + setting
+ " to " + result + " for site " + site.getId() );
}
private String resource( String qtr, String cc, int sn, Resource resource,
ModelMap models, HttpServletResponse response )
{
if( resource.isDeleted() )
{
models.put( "message", "error.site.item.deleted" );
models.put( "backUrl", "/site/" + qtr + "/" + cc + "-" + sn );
return "error";
}
switch( resource.getType() )
{
case TEXT:
models.put( "resource", resource );
return "site/resource";
case FILE:
fileIO.write( resource.getFile(), response );
return null;
case URL:
return "redirect:" + resource.getUrl();
default:
logger.warn( "Invalid resource type: " + resource.getType() );
return "redirect:" + getSection( qtr, cc, sn ).getSiteUrl();
}
}
@RequestMapping("/site/{qtr}/{cc}-{sn}/resource/{id}")
public String resource( @PathVariable String qtr, @PathVariable String cc,
@PathVariable int sn, @PathVariable Long id, ModelMap models,
HttpServletResponse response )
{
return resource( qtr, cc, sn, resourceDao.getResource( id ), models,
response );
}
@RequestMapping("/site/{qtr}/{cc}-{sn}/item/{id}")
public String item( @PathVariable String qtr, @PathVariable String cc,
@PathVariable int sn, @PathVariable Long id, ModelMap models,
HttpServletResponse response )
{
return resource( qtr, cc, sn, itemDao.getItem( id ).getResource(),
models, response );
}
private File getFolder( File parent, String name )
{
User user = SecurityUtils.getUser();
List<File> results = fileDao.getFiles( user, parent, name, true );
if( results.size() > 0 ) return results.get( 0 );
File folder = new File();
folder.setName( name );
folder.setFolder( true );
folder.setRegular( true );
folder.setParent( parent );
folder.setOwner( user );
folder = fileDao.saveFile( folder );
String parentName = parent != null ? parent.getName() : "root";
logger.info( user.getUsername() + " created folder " + name + " under "
+ parentName );
return folder;
}
@RequestMapping("/site/{qtr}/{cc}-{sn}/files/")
public String folder( @PathVariable String qtr, @PathVariable String cc,
@PathVariable int sn )
{
Site site = getSection( qtr, cc, sn ).getSite();
if( site.getFolder() != null )
return "redirect:/file/view?id=" + site.getFolder().getId();
File folder = getFolder( null, "Courses" );
folder = getFolder( folder, cc.toUpperCase() );
folder = getFolder( folder, qtr.toUpperCase() );
site.setFolder( folder );
site = siteDao.saveSite( site );
return "redirect:/file/view?id=" + folder.getId();
}
@RequestMapping("/site/{qtr}/{cc}-{sn}/files/remove")
public String removeFolder( @PathVariable String qtr,
@PathVariable String cc, @PathVariable int sn )
{
Site site = getSection( qtr, cc, sn ).getSite();
site.setFolder( null );
site = siteDao.saveSite( site );
return "redirect:/site/" + qtr + "/" + cc + "-" + sn;
}
}
| 9,595 | 0.598228 | 0.596873 | 292 | 31.859589 | 24.468546 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 4 |
4526d10d75c6b2d54f1132a6b337c9ee6ba65415 | 35,407,710,404,815 | d5ee47692c3507ef7a649ef05f38ed0713f56ce0 | /src/Optional.java | fb9da343c23adf84d77da6dbdfbf52cf2a685f19 | [] | no_license | iamshaurya/Problem-practice | https://github.com/iamshaurya/Problem-practice | bdadc6b1a57418ce54322c8552516fea1af9f097 | 28a7ee69bf1f82c7df269bae7a132c3dfe4e65e1 | refs/heads/master | 2020-03-25T11:13:37.409000 | 2018-08-07T12:15:59 | 2018-08-07T12:15:59 | 143,723,430 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Optional {
boolean value() default false;
}
| UTF-8 | Java | 337 | java | Optional.java | Java | [] | null | [] | import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Optional {
boolean value() default false;
}
| 337 | 0.818991 | 0.818991 | 10 | 32.700001 | 20.268448 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 4 |
7bd11855507f6d3f2b51d74de8dbcf272ee3bce7 | 33,964,601,394,816 | d1f87a836af1ab76039f84fd7bab484bfec48cb4 | /Assignment 2/Backup/ZerLi_Client/src/izhar/ProductController.java | 520369b4cfa4ef1d0d60353ff8cfc08000c7b2a0 | [] | no_license | ItayAlmani/Zer-Li-Flower-Store | https://github.com/ItayAlmani/Zer-Li-Flower-Store | 6157ff811d763818ee598e097de3b671ba2f2b97 | b89080f6baa1abbd9c6e68818140c8338789d639 | refs/heads/master | 2021-09-06T12:52:37.214000 | 2018-02-06T16:16:04 | 2018-02-06T16:16:04 | 109,955,652 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package izhar;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.ArrayList;
import common.Context;
import controllers.ParentController;
import entities.CSMessage;
import entities.CSMessage.MessageType;
import entities.Product;
import entities.Product.Color;
import entities.Product.ProductType;
import izhar.interfaces.IProduct;
public class ProductController extends ParentController implements IProduct {
@Override
public void getProductByID(BigInteger prdID) throws IOException {
myMsgArr.clear();
myMsgArr.add("SELECT * FROM product WHERE productID = '"+prdID+"';");
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.SELECT,myMsgArr,Product.class));
}
@Override
public void updateProduct(Product p) throws IOException {
myMsgArr.clear();
myMsgArr.add(String.format(
"UPDATE product SET productName='%s' WHERE productID=%d;",p.getName(),p.getPrdID()));
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.UPDATE,myMsgArr));
}
@Override
public void handleGet(ArrayList<Object> obj) {
ArrayList<Product> prds = new ArrayList<>();
for (int i = 0; i < obj.size(); i += 7)
try {
prds.add(parse(
BigInteger.valueOf(Long.valueOf((int) obj.get(i))),
(String) obj.get(i + 1),
(String) obj.get(i + 2),
(float) obj.get(i + 3),
(String) obj.get(i + 4),
((int)obj.get(i + 5))!= 0,
(String)obj.get(i+6))
);
} catch (FileNotFoundException e) {
System.err.println("Couldn't find Image named "+ (String)obj.get(i+6) +".");
e.printStackTrace();
}
sendProducts(prds);
}
@Override
public Product parse(BigInteger prdID, String name, String type, float price, String color, boolean inCatalog, String imageURL) throws FileNotFoundException {
return new Product(prdID, name, type,price,color,inCatalog, "/images/"+imageURL);
}
@Override
public void sendProducts(ArrayList<Product> prds) {
String methodName = "setProducts";
Method m = null;
try {
//a controller asked data, not GUI
if(Context.askingCtrl!=null && Context.askingCtrl.size()!=0) {
m = Context.askingCtrl.get(0).getClass().getMethod(methodName,ArrayList.class);
m.invoke(Context.askingCtrl.get(0), prds);
Context.askingCtrl.remove(0);
}
else {
m = Context.currentGUI.getClass().getMethod(methodName,ArrayList.class);
m.invoke(Context.currentGUI, prds);
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
System.err.println("Couldn't invoke method '"+methodName+"'");
e1.printStackTrace();
} catch (NoSuchMethodException | SecurityException e2) {
System.err.println("No method called '"+methodName+"'");
e2.printStackTrace();
}
}
@Override
public ArrayList<Product> assembleProduct(ProductType type, Float priceStart, Float priceEnd, Color color, ArrayList<Product> products) {
/*myMsgArr.clear();
myMsgArr.add(
"SELECT *" +
"FROM product" +
"WHERE inCatalog=0 AND"
+ " productType='"+type.toString()+"' AND"
+ " price>="+priceStart+" AND"
+ " price<="+priceEnd+" AND"
+ " color='"+color.toString()+"'");
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.SELECT,myMsgArr));*/
ArrayList<Product> inConditionProds = new ArrayList<>();
if(type!=null && priceStart!=null && priceEnd!=null) {
if(color==null) {
for (Product p : products) {
if(p.getType().equals(type)
&& p.getPrice()>=priceStart
&& p.getPrice()<=priceEnd) {
inConditionProds.add(p);
}
}
}
else {
for (Product p : products) {
if(p.getType().equals(type)
&& p.getPrice()>=priceStart
&& p.getPrice()<=priceEnd) {
if(p.getColor().equals(color))
inConditionProds.add(p);
}
}
}
}
return inConditionProds;
}
@Override
public void addProduct(Product p) throws IOException {
myMsgArr.clear();
String res = "0";
if(p.isInCatalog())
res="1";
String query = "INSERT INTO orders (productName, productType, price, color, inCatalog)"
+ "VALUES ('" + p.getName() + "', '"
+ p.getType().toString() + "', '"
+ p.getPrice() + "', '"
+ p.getColor().toString() + "', '"
+ res + "');";
query += "SELECT Max(productID) from product;";
myMsgArr.add(query);
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.UPDATE, myMsgArr,Product.class));
}
@Override
public void getAllProducts() throws IOException {
myMsgArr.clear();
myMsgArr.add("SELECT * FROM product;");
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.SELECT,myMsgArr,Product.class));
}
@Override
public void getProductsInCatalog() throws IOException {
myMsgArr.clear();
myMsgArr.add("SELECT * FROM product WHERE inCatalog='1';");
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.SELECT,myMsgArr,Product.class));
}
@Override
public void getAllProductsNotInCatalog() throws IOException {
myMsgArr.clear();
myMsgArr.add("SELECT * FROM product WHERE inCatalog='0'");
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.SELECT,myMsgArr,Product.class));
}
}
| UTF-8 | Java | 5,511 | java | ProductController.java | Java | [] | null | [] | package izhar;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.ArrayList;
import common.Context;
import controllers.ParentController;
import entities.CSMessage;
import entities.CSMessage.MessageType;
import entities.Product;
import entities.Product.Color;
import entities.Product.ProductType;
import izhar.interfaces.IProduct;
public class ProductController extends ParentController implements IProduct {
@Override
public void getProductByID(BigInteger prdID) throws IOException {
myMsgArr.clear();
myMsgArr.add("SELECT * FROM product WHERE productID = '"+prdID+"';");
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.SELECT,myMsgArr,Product.class));
}
@Override
public void updateProduct(Product p) throws IOException {
myMsgArr.clear();
myMsgArr.add(String.format(
"UPDATE product SET productName='%s' WHERE productID=%d;",p.getName(),p.getPrdID()));
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.UPDATE,myMsgArr));
}
@Override
public void handleGet(ArrayList<Object> obj) {
ArrayList<Product> prds = new ArrayList<>();
for (int i = 0; i < obj.size(); i += 7)
try {
prds.add(parse(
BigInteger.valueOf(Long.valueOf((int) obj.get(i))),
(String) obj.get(i + 1),
(String) obj.get(i + 2),
(float) obj.get(i + 3),
(String) obj.get(i + 4),
((int)obj.get(i + 5))!= 0,
(String)obj.get(i+6))
);
} catch (FileNotFoundException e) {
System.err.println("Couldn't find Image named "+ (String)obj.get(i+6) +".");
e.printStackTrace();
}
sendProducts(prds);
}
@Override
public Product parse(BigInteger prdID, String name, String type, float price, String color, boolean inCatalog, String imageURL) throws FileNotFoundException {
return new Product(prdID, name, type,price,color,inCatalog, "/images/"+imageURL);
}
@Override
public void sendProducts(ArrayList<Product> prds) {
String methodName = "setProducts";
Method m = null;
try {
//a controller asked data, not GUI
if(Context.askingCtrl!=null && Context.askingCtrl.size()!=0) {
m = Context.askingCtrl.get(0).getClass().getMethod(methodName,ArrayList.class);
m.invoke(Context.askingCtrl.get(0), prds);
Context.askingCtrl.remove(0);
}
else {
m = Context.currentGUI.getClass().getMethod(methodName,ArrayList.class);
m.invoke(Context.currentGUI, prds);
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
System.err.println("Couldn't invoke method '"+methodName+"'");
e1.printStackTrace();
} catch (NoSuchMethodException | SecurityException e2) {
System.err.println("No method called '"+methodName+"'");
e2.printStackTrace();
}
}
@Override
public ArrayList<Product> assembleProduct(ProductType type, Float priceStart, Float priceEnd, Color color, ArrayList<Product> products) {
/*myMsgArr.clear();
myMsgArr.add(
"SELECT *" +
"FROM product" +
"WHERE inCatalog=0 AND"
+ " productType='"+type.toString()+"' AND"
+ " price>="+priceStart+" AND"
+ " price<="+priceEnd+" AND"
+ " color='"+color.toString()+"'");
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.SELECT,myMsgArr));*/
ArrayList<Product> inConditionProds = new ArrayList<>();
if(type!=null && priceStart!=null && priceEnd!=null) {
if(color==null) {
for (Product p : products) {
if(p.getType().equals(type)
&& p.getPrice()>=priceStart
&& p.getPrice()<=priceEnd) {
inConditionProds.add(p);
}
}
}
else {
for (Product p : products) {
if(p.getType().equals(type)
&& p.getPrice()>=priceStart
&& p.getPrice()<=priceEnd) {
if(p.getColor().equals(color))
inConditionProds.add(p);
}
}
}
}
return inConditionProds;
}
@Override
public void addProduct(Product p) throws IOException {
myMsgArr.clear();
String res = "0";
if(p.isInCatalog())
res="1";
String query = "INSERT INTO orders (productName, productType, price, color, inCatalog)"
+ "VALUES ('" + p.getName() + "', '"
+ p.getType().toString() + "', '"
+ p.getPrice() + "', '"
+ p.getColor().toString() + "', '"
+ res + "');";
query += "SELECT Max(productID) from product;";
myMsgArr.add(query);
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.UPDATE, myMsgArr,Product.class));
}
@Override
public void getAllProducts() throws IOException {
myMsgArr.clear();
myMsgArr.add("SELECT * FROM product;");
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.SELECT,myMsgArr,Product.class));
}
@Override
public void getProductsInCatalog() throws IOException {
myMsgArr.clear();
myMsgArr.add("SELECT * FROM product WHERE inCatalog='1';");
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.SELECT,myMsgArr,Product.class));
}
@Override
public void getAllProductsNotInCatalog() throws IOException {
myMsgArr.clear();
myMsgArr.add("SELECT * FROM product WHERE inCatalog='0'");
Context.clientConsole.handleMessageFromClientUI(new CSMessage(MessageType.SELECT,myMsgArr,Product.class));
}
}
| 5,511 | 0.674106 | 0.669933 | 160 | 32.443748 | 30.121368 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.15 | false | false | 4 |
4c66932e2bc5acdcc4d1bc4a9c746c37289147b0 | 38,414,187,501,484 | 05c20777f4480c9e5d4a2aa4a80fc6c64fa474cc | /src/main/java/com/x/example/ssh读取远程服务器文件.java | eebdf38a115b8b13493a9ad16942f7583e4eb4b5 | [] | no_license | hn5092/MR-FOR-WORK | https://github.com/hn5092/MR-FOR-WORK | 554538b5bb6ad1ef76054134ac291e43b68ee731 | e6eab6c0196a459b1735d0fb7b0108588e87587e | refs/heads/master | 2021-01-18T21:46:21.082000 | 2016-04-03T10:05:15 | 2016-04-03T10:05:15 | 42,495,130 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.x.example;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.connection.ChannelInputStream;
import com.sshtools.j2ssh.connection.ChannelOutputStream;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.sftp.SftpFile;
/**
* <dependency>
<groupId>sshtools</groupId>
<artifactId>j2ssh-core</artifactId>
<version>0.2.9</version>
</dependency>
* @author imad
*
*/
public class ssh读取远程服务器文件 {
public static void main(String[] args) {
// 所需jar包:j2ssh-core-0.2.2.jar
// java代码:
SshClient client=new SshClient();
try{
client.connect("此处是Linux服务器IP");
//设置用户名和密码
PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
pwd.setUsername("root");
pwd.setPassword("123456");
int result=client.authenticate(pwd);
if(result==AuthenticationProtocolState.COMPLETE){//如果连接完成
System.out.println("==============="+result);
SessionChannelClient openSessionChannel = client.openSessionChannel();
boolean executeCommand = openSessionChannel.executeCommand("ls");
ChannelInputStream inputStream = openSessionChannel.getInputStream();
inputStream.read();
List<SftpFile> list = client.openSftpClient().ls("/etc/mail/");
for (SftpFile f : list) {
System.out.println(f.getFilename());
System.out.println(f.getAbsolutePath());
if(f.getFilename().equals("aliases")){
OutputStream os = new FileOutputStream("d:/mail/"+f.getFilename());
client.openSftpClient().get("/etc/mail/aliases", os);
//以行为单位读取文件start
File file = new File("d:/mail/aliases");
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;//行号
//一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
//显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
//以行为单位读取文件end
}
}
}
}catch(IOException e){
e.printStackTrace();
}
}
}
| UTF-8 | Java | 3,791 | java | ssh读取远程服务器文件.java | Java | [
{
"context": "\t<version>0.2.9</version>\n</dependency>\n * @author imad\n *\n */\npublic class ssh读取远程服务器文件 {\n\tpublic static",
"end": 749,
"score": 0.9996284246444702,
"start": 745,
"tag": "USERNAME",
"value": "imad"
},
{
"context": "tUsername(\"root\");\n\t\t pwd.setPa... | null | [] | package com.x.example;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.connection.ChannelInputStream;
import com.sshtools.j2ssh.connection.ChannelOutputStream;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.sftp.SftpFile;
/**
* <dependency>
<groupId>sshtools</groupId>
<artifactId>j2ssh-core</artifactId>
<version>0.2.9</version>
</dependency>
* @author imad
*
*/
public class ssh读取远程服务器文件 {
public static void main(String[] args) {
// 所需jar包:j2ssh-core-0.2.2.jar
// java代码:
SshClient client=new SshClient();
try{
client.connect("此处是Linux服务器IP");
//设置用户名和密码
PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
pwd.setUsername("root");
pwd.setPassword("<PASSWORD>");
int result=client.authenticate(pwd);
if(result==AuthenticationProtocolState.COMPLETE){//如果连接完成
System.out.println("==============="+result);
SessionChannelClient openSessionChannel = client.openSessionChannel();
boolean executeCommand = openSessionChannel.executeCommand("ls");
ChannelInputStream inputStream = openSessionChannel.getInputStream();
inputStream.read();
List<SftpFile> list = client.openSftpClient().ls("/etc/mail/");
for (SftpFile f : list) {
System.out.println(f.getFilename());
System.out.println(f.getAbsolutePath());
if(f.getFilename().equals("aliases")){
OutputStream os = new FileOutputStream("d:/mail/"+f.getFilename());
client.openSftpClient().get("/etc/mail/aliases", os);
//以行为单位读取文件start
File file = new File("d:/mail/aliases");
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;//行号
//一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
//显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
//以行为单位读取文件end
}
}
}
}catch(IOException e){
e.printStackTrace();
}
}
}
| 3,795 | 0.498473 | 0.492086 | 87 | 40.379311 | 24.206602 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.827586 | false | false | 4 |
b4e811a921c08620849d661e22880e66e0f452a0 | 33,767,032,909,710 | 25ba9572bf97c3f7b4bdf16442d68e1a26f3982a | /app/src/main/java/JavaApp/user/auction/create_edit/AuctionRequest.java | 7c4058b0698c687ab636d220d82f34faa6923e40 | [] | no_license | YDima/JavaEE_app | https://github.com/YDima/JavaEE_app | 3b6fcf96b1d76edf556c36956369311f91ad07a3 | b321e3127f6854df49ec0b9247ce7d41c9c203cb | refs/heads/master | 2022-04-02T23:18:33.305000 | 2020-02-04T12:15:29 | 2020-02-04T12:15:29 | 217,107,808 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package JavaApp.user.auction.create_edit;
import JavaApp.sales.jpa.Auction;
import JavaApp.sales.jpa.AuctionParameter;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import java.math.BigDecimal;
import java.util.List;
@Named
@RequestScoped
public class AuctionRequest {
private Long id;
private Long category_id;
private String title;
private String description;
private BigDecimal price;
private List<AuctionParameter> parameters;
private String owner_username;
public AuctionRequest(Auction auction) {
this.id = auction.getId();
this.category_id = auction.getCategory_id();
this.title = auction.getTitle();
this.description = auction.getDescription();
this.price = auction.getPrice();
this.owner_username = auction.getOwner_username();
}
public AuctionRequest() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getCategory_id() {
return category_id;
}
public void setCategory_id(Long category_id) {
this.category_id = category_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public List<AuctionParameter> getParameters() {
return parameters;
}
public void setParameters(List<AuctionParameter> parameters) {
this.parameters = parameters;
}
public String getOwner_username() {
return owner_username;
}
public void setOwner_username(String owner_username) {
this.owner_username = owner_username;
}
@Override
public String toString() {
return "AuctionRequest{" +
"category=" + category_id +
", title='" + title + '\'' +
", description='" + description + '\'' +
", price=" + price +
", parameters=" + parameters +
", owner_username=" + owner_username +
'}';
}
}
| UTF-8 | Java | 2,411 | java | AuctionRequest.java | Java | [
{
"context": "public String getOwner_username() {\n return owner_username;\n }\n public void setOwner_username(String o",
"end": 1896,
"score": 0.9973546862602234,
"start": 1882,
"tag": "USERNAME",
"value": "owner_username"
},
{
"context": "ng owner_username) {\n ... | null | [] | package JavaApp.user.auction.create_edit;
import JavaApp.sales.jpa.Auction;
import JavaApp.sales.jpa.AuctionParameter;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import java.math.BigDecimal;
import java.util.List;
@Named
@RequestScoped
public class AuctionRequest {
private Long id;
private Long category_id;
private String title;
private String description;
private BigDecimal price;
private List<AuctionParameter> parameters;
private String owner_username;
public AuctionRequest(Auction auction) {
this.id = auction.getId();
this.category_id = auction.getCategory_id();
this.title = auction.getTitle();
this.description = auction.getDescription();
this.price = auction.getPrice();
this.owner_username = auction.getOwner_username();
}
public AuctionRequest() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getCategory_id() {
return category_id;
}
public void setCategory_id(Long category_id) {
this.category_id = category_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public List<AuctionParameter> getParameters() {
return parameters;
}
public void setParameters(List<AuctionParameter> parameters) {
this.parameters = parameters;
}
public String getOwner_username() {
return owner_username;
}
public void setOwner_username(String owner_username) {
this.owner_username = owner_username;
}
@Override
public String toString() {
return "AuctionRequest{" +
"category=" + category_id +
", title='" + title + '\'' +
", description='" + description + '\'' +
", price=" + price +
", parameters=" + parameters +
", owner_username=" + owner_username +
'}';
}
}
| 2,411 | 0.607632 | 0.607632 | 102 | 22.627451 | 18.761099 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.392157 | false | false | 4 |
9a4bd1a807afb2419e9951ad6540846b28943543 | 38,835,094,318,799 | 160afa226d3e4d96ed9e9df43279599f8feb6321 | /siit-project-taxcalculator/siit-project/src/main/java/com/java/siit/taxcalculator/repository/UserRolesRepository.java | 5e4fcc79b7dc020be8b78a2aff53fb6b61d580fd | [] | no_license | andreeaciutescu/App_Tax_Calculator | https://github.com/andreeaciutescu/App_Tax_Calculator | 3925356ecba27027349af978cbd39492d6bb3752 | 2c290b67bbad4144527cf6564fc71244108e8677 | refs/heads/master | 2023-08-24T22:21:46.934000 | 2021-10-21T13:56:58 | 2021-10-21T13:56:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.java.siit.taxcalculator.repository;
import com.java.siit.taxcalculator.config.UserRoles;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRolesRepository extends JpaRepository<UserRoles,String>{
UserRoles getByEmail(String email);
}
| UTF-8 | Java | 349 | java | UserRolesRepository.java | Java | [] | null | [] | package com.java.siit.taxcalculator.repository;
import com.java.siit.taxcalculator.config.UserRoles;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRolesRepository extends JpaRepository<UserRoles,String>{
UserRoles getByEmail(String email);
}
| 349 | 0.839542 | 0.839542 | 11 | 30.636364 | 27.440092 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 4 |
208068bd149a81b0fa13fef39d3cbaf218643b94 | 36,541,581,773,481 | c75d286f30f388a6c72aac427643c6f745235782 | /src/main/java/com/qinjun/autotest/tsapi/bean/APIResBody.java | 1e4ab68ddef649d13eaf2524f4d06483cb064a62 | [] | no_license | zeroneqin/tscase_api | https://github.com/zeroneqin/tscase_api | 1bd5883b9edefae9978236fc80ea0c64ae056c8c | cd020645b419f482990d702f407269a9c5a7ad67 | refs/heads/master | 2020-03-19T02:12:18.392000 | 2018-07-20T14:34:12 | 2018-07-20T14:34:12 | 135,608,918 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.qinjun.autotest.tsapi.bean;
import com.qinjun.autotest.tsapi.constant.EnumBodyFormat;
public class APIResBody {
private Long id;
private API api;
private EnumBodyFormat bodyFormat;
private String bodySchema;
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public API getApi() {
return api;
}
public void setApi(API api) {
this.api = api;
}
public EnumBodyFormat getBodyFormat() {
return bodyFormat;
}
public void setBodyFormat(EnumBodyFormat bodyFormat) {
this.bodyFormat = bodyFormat;
}
public String getBodySchema() {
return bodySchema;
}
public void setBodySchema(String bodySchema) {
this.bodySchema = bodySchema;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| UTF-8 | Java | 1,025 | java | APIResBody.java | Java | [] | null | [] | package com.qinjun.autotest.tsapi.bean;
import com.qinjun.autotest.tsapi.constant.EnumBodyFormat;
public class APIResBody {
private Long id;
private API api;
private EnumBodyFormat bodyFormat;
private String bodySchema;
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public API getApi() {
return api;
}
public void setApi(API api) {
this.api = api;
}
public EnumBodyFormat getBodyFormat() {
return bodyFormat;
}
public void setBodyFormat(EnumBodyFormat bodyFormat) {
this.bodyFormat = bodyFormat;
}
public String getBodySchema() {
return bodySchema;
}
public void setBodySchema(String bodySchema) {
this.bodySchema = bodySchema;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| 1,025 | 0.634146 | 0.634146 | 51 | 19.09804 | 17.425758 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
03cbb0e35f5948faef2924e933095357fb5ddbcc | 38,860,864,098,043 | eb4796ff56ff3fb99edd1147387da3762d08268b | /uppg9.java | ccd76bcb53f077a280372a472d295f397063748a | [] | no_license | Dodisbeaver/matematisk-programering | https://github.com/Dodisbeaver/matematisk-programering | 70f57fa1cb077f44e81fdd4d74452e1b63348e3f | f5a49b63920b7621f50edb04d51ee75faa37367b | refs/heads/master | 2022-12-29T22:18:52.226000 | 2020-10-18T16:27:40 | 2020-10-18T16:27:40 | 297,340,805 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
public class uppg9 {
public static void main(final String[] args) {
// variabler
int computerNumber = 0;
int userNumber = 0;
int shutdown = 3;
final Scanner input = new Scanner(System.in);
int guesses = 0;
int max = 0;
//så länge shutdown inte är 0 körs loopen
while(shutdown != 0)
{
//random nummer mellan [1-10]
if(shutdown == 3) {
System.out.println("Gissa ett tal mellan 1 och M. Välj svårighetsgrad för gissningsspelet genom att ge \n ett värde för M: " );
max = input.nextInt();
computerNumber = (int) (Math.random() * ((max-1) + 1) + 1);
shutdown = 1;
}
//Fråga av användaren om en gissning
System.out.println(" Gissa en siffra mellan 1 och " + max);
userNumber= input.nextInt();
guesses++;
//Vinst
if(computerNumber==userNumber)
{
System.out.println("Du gissade rätt!");
System.out.println("Datorn valde " + computerNumber + ", du gissade: " + guesses + " gånger.");
System.out.println("Vill du köra igen (1 = ja, 0 = nej)? ");
userNumber = input.nextInt();
System.out.println("Okej! " + userNumber);
if (userNumber == 1 ) {
shutdown = 3;
guesses = 0;
} else if (userNumber == 0) {
shutdown = 0;
System.out.println("Tack för att du spelade! ");
input.close();
System.exit(0);
}
}
if( (userNumber != computerNumber) && shutdown != 3)
{
System.out.println("Fel!");
if(userNumber >= computerNumber) {
System.out.println("Lägre");
} else if (userNumber <= computerNumber) {
System.out.println("Högre!");
}
}
}
}
}
| UTF-8 | Java | 2,545 | java | uppg9.java | Java | [] | null | [] |
import java.util.Scanner;
public class uppg9 {
public static void main(final String[] args) {
// variabler
int computerNumber = 0;
int userNumber = 0;
int shutdown = 3;
final Scanner input = new Scanner(System.in);
int guesses = 0;
int max = 0;
//så länge shutdown inte är 0 körs loopen
while(shutdown != 0)
{
//random nummer mellan [1-10]
if(shutdown == 3) {
System.out.println("Gissa ett tal mellan 1 och M. Välj svårighetsgrad för gissningsspelet genom att ge \n ett värde för M: " );
max = input.nextInt();
computerNumber = (int) (Math.random() * ((max-1) + 1) + 1);
shutdown = 1;
}
//Fråga av användaren om en gissning
System.out.println(" Gissa en siffra mellan 1 och " + max);
userNumber= input.nextInt();
guesses++;
//Vinst
if(computerNumber==userNumber)
{
System.out.println("Du gissade rätt!");
System.out.println("Datorn valde " + computerNumber + ", du gissade: " + guesses + " gånger.");
System.out.println("Vill du köra igen (1 = ja, 0 = nej)? ");
userNumber = input.nextInt();
System.out.println("Okej! " + userNumber);
if (userNumber == 1 ) {
shutdown = 3;
guesses = 0;
} else if (userNumber == 0) {
shutdown = 0;
System.out.println("Tack för att du spelade! ");
input.close();
System.exit(0);
}
}
if( (userNumber != computerNumber) && shutdown != 3)
{
System.out.println("Fel!");
if(userNumber >= computerNumber) {
System.out.println("Lägre");
} else if (userNumber <= computerNumber) {
System.out.println("Högre!");
}
}
}
}
}
| 2,545 | 0.390032 | 0.379351 | 70 | 35.085712 | 26.151615 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 4 |
de6c4cb54f69a2640c0b95b0b74af6d43d4c1d12 | 10,127,532,929,189 | dbd1be6d467c6e8df751092f1e41fbd6fcdef333 | /auth-service/src/main/java/com/yf/auth/service/impl/SysOrgServiceImpl.java | dbe1944fbb724f78614f7cbd0af1503c688fd203 | [] | no_license | jinghan99/girl-springcloud | https://github.com/jinghan99/girl-springcloud | 1c8c39bc0794e5c8f510831b0420b989aea700f8 | 057aed796a22230226a6ca06571d3bc8d5f69e6e | refs/heads/master | 2020-03-31T12:29:09.358000 | 2019-05-15T04:21:34 | 2019-05-15T04:21:34 | 152,217,664 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yf.auth.service.impl;
import com.yf.auth.dao.SysOrgMapper;
import com.yf.auth.dao.SysRoleOrgMapper;
import com.yf.auth.entity.SysOrgEntity;
import com.yf.auth.service.SysOrgService;
import com.yf.utils.common.CommonUtils;
import com.yf.utils.constant.MsgConstant;
import com.yf.utils.entiy.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* 组织机构
*
* @author ZhouChenglin
* @email yczclcn@163.com
* @url www.chenlintech.com
* @date 2017年8月17日 上午11:33:28
*/
@Service("sysOrgService")
public class SysOrgServiceImpl implements SysOrgService {
@Autowired
private SysOrgMapper sysOrgMapper;
@Autowired
private SysRoleOrgMapper sysRoleOrgMapper;
/**
* 机构列表:树形表格
* @return
*/
@Override
public List<SysOrgEntity> listOrg() {
return sysOrgMapper.list();
}
/**
* ztree机构数据源
* @return
*/
@Override
public List<SysOrgEntity> listOrgTree() {
List<SysOrgEntity> orgList = sysOrgMapper.list();
SysOrgEntity org = new SysOrgEntity();
org.setOrgId(0L);
org.setName("一级机构");
org.setParentId(-1L);
org.setOpen(true);
orgList.add(org);
return orgList;
}
/**
* 新增
* @param org
* @return
*/
@Override
public R saveOrg(SysOrgEntity org) {
int count = sysOrgMapper.save(org);
return CommonUtils.msg(count);
}
/**
* 根据id查询
* @param orgId
* @return
*/
@Override
public R getOrg(Long orgId) {
SysOrgEntity org = sysOrgMapper.getObjectById(orgId);
return CommonUtils.msg(org);
}
/**
* 更新
* @param org
* @return
*/
@Override
public R updateOrg(SysOrgEntity org) {
int count = sysOrgMapper.update(org);
return CommonUtils.msg(count);
}
/**
* 批量删除
* @param id
* @return
*/
@Override
public R bactchRemoveOrg(Long[] id) {
boolean children = this.hasChildren(id);
if(children) {
return R.error(MsgConstant.MSG_HAS_CHILD);
}
int count = sysOrgMapper.batchRemove(id);
sysRoleOrgMapper.batchRemoveByOrgId(id);
return CommonUtils.msg(id, count);
}
/**
* 是否含有子机构
* @param id
* @return
*/
public boolean hasChildren(Long[] id) {
for(Long parentId : id) {
int count = sysOrgMapper.countOrgChildren(parentId);
if(CommonUtils.isIntThanZero(count)) {
return true;
}
}
return false;
}
/**
* 查询所有机构id
* @param parentId
* @return
*/
@Override
public List<Long> listOrgChildren(Long parentId) {
return sysOrgMapper.listOrgChildren(parentId);
}
/**
* 递归查询所有子机构
* @param parentId
* @return
*/
@Override
public List<Long> getAllOrgChildren(Long parentId) {
List<Long> orgIds = new ArrayList<>();
List<Long> parentIds = listOrgChildren(parentId);
recursionOrgChildren(parentIds, orgIds);
return orgIds;
}
/**
* 递归查询子机构
* @param parentIds
* @param result
*/
public void recursionOrgChildren(List<Long> parentIds, List<Long> result) {
for (Long parentId : parentIds) {
List<Long> ids = listOrgChildren(parentId);
if (ids.size() > 0) {
recursionOrgChildren(ids, result);
}
result.add(parentId);
}
}
}
| UTF-8 | Java | 3,249 | java | SysOrgServiceImpl.java | Java | [
{
"context": "\nimport java.util.List;\n\n/**\n * 组织机构\n *\n * @author ZhouChenglin\n * @email yczclcn@163.com\n * @url www.chenlintech",
"end": 507,
"score": 0.9998832941055298,
"start": 495,
"tag": "NAME",
"value": "ZhouChenglin"
},
{
"context": "\n\n/**\n * 组织机构\n *\n * @author Zh... | null | [] | package com.yf.auth.service.impl;
import com.yf.auth.dao.SysOrgMapper;
import com.yf.auth.dao.SysRoleOrgMapper;
import com.yf.auth.entity.SysOrgEntity;
import com.yf.auth.service.SysOrgService;
import com.yf.utils.common.CommonUtils;
import com.yf.utils.constant.MsgConstant;
import com.yf.utils.entiy.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* 组织机构
*
* @author ZhouChenglin
* @email <EMAIL>
* @url www.chenlintech.com
* @date 2017年8月17日 上午11:33:28
*/
@Service("sysOrgService")
public class SysOrgServiceImpl implements SysOrgService {
@Autowired
private SysOrgMapper sysOrgMapper;
@Autowired
private SysRoleOrgMapper sysRoleOrgMapper;
/**
* 机构列表:树形表格
* @return
*/
@Override
public List<SysOrgEntity> listOrg() {
return sysOrgMapper.list();
}
/**
* ztree机构数据源
* @return
*/
@Override
public List<SysOrgEntity> listOrgTree() {
List<SysOrgEntity> orgList = sysOrgMapper.list();
SysOrgEntity org = new SysOrgEntity();
org.setOrgId(0L);
org.setName("一级机构");
org.setParentId(-1L);
org.setOpen(true);
orgList.add(org);
return orgList;
}
/**
* 新增
* @param org
* @return
*/
@Override
public R saveOrg(SysOrgEntity org) {
int count = sysOrgMapper.save(org);
return CommonUtils.msg(count);
}
/**
* 根据id查询
* @param orgId
* @return
*/
@Override
public R getOrg(Long orgId) {
SysOrgEntity org = sysOrgMapper.getObjectById(orgId);
return CommonUtils.msg(org);
}
/**
* 更新
* @param org
* @return
*/
@Override
public R updateOrg(SysOrgEntity org) {
int count = sysOrgMapper.update(org);
return CommonUtils.msg(count);
}
/**
* 批量删除
* @param id
* @return
*/
@Override
public R bactchRemoveOrg(Long[] id) {
boolean children = this.hasChildren(id);
if(children) {
return R.error(MsgConstant.MSG_HAS_CHILD);
}
int count = sysOrgMapper.batchRemove(id);
sysRoleOrgMapper.batchRemoveByOrgId(id);
return CommonUtils.msg(id, count);
}
/**
* 是否含有子机构
* @param id
* @return
*/
public boolean hasChildren(Long[] id) {
for(Long parentId : id) {
int count = sysOrgMapper.countOrgChildren(parentId);
if(CommonUtils.isIntThanZero(count)) {
return true;
}
}
return false;
}
/**
* 查询所有机构id
* @param parentId
* @return
*/
@Override
public List<Long> listOrgChildren(Long parentId) {
return sysOrgMapper.listOrgChildren(parentId);
}
/**
* 递归查询所有子机构
* @param parentId
* @return
*/
@Override
public List<Long> getAllOrgChildren(Long parentId) {
List<Long> orgIds = new ArrayList<>();
List<Long> parentIds = listOrgChildren(parentId);
recursionOrgChildren(parentIds, orgIds);
return orgIds;
}
/**
* 递归查询子机构
* @param parentIds
* @param result
*/
public void recursionOrgChildren(List<Long> parentIds, List<Long> result) {
for (Long parentId : parentIds) {
List<Long> ids = listOrgChildren(parentId);
if (ids.size() > 0) {
recursionOrgChildren(ids, result);
}
result.add(parentId);
}
}
}
| 3,241 | 0.689688 | 0.683585 | 160 | 18.456249 | 17.073315 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.39375 | false | false | 4 |
44242c7ae6828fed05297bca16fcbbb80ec518da | 29,317,446,775,068 | c0e1294572b1b7186cd5f2a557e6fb664b1bcda3 | /src/test/java/com/demo/HttpUtilTest.java | ab11749e9899de0ae64c802bda344390131a1de2 | [] | no_license | 13530361335/SpringBoot | https://github.com/13530361335/SpringBoot | 3028a9c5b15a69c2ed6555409247daaef8908340 | 6edcc6a5aa90ea0e9c4fd50ecb6753adc8e6db65 | refs/heads/master | 2020-04-16T04:27:24.481000 | 2019-03-11T02:54:39 | 2019-03-11T02:54:39 | 165,267,651 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo;
import com.demo.util.HttpUtil;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.junit.Test;
public class HttpUtilTest {
@Test
public void download() {
HttpUtil.downLoad("http://www.pptok.com/wp-content/uploads/2012/08/xunguang-9.jpg", "D:\\Temp\\");
}
@Test
public void parseHtml() {
Document document = HttpUtil.getHtml("https://me.csdn.net/mashuai720");
Elements elements = document.select("dt h3 a");
elements.forEach(e -> {
String href = e.attr("href");
String title = e.text();
System.out.println(href);
System.out.println(title);
});
}
}
| UTF-8 | Java | 711 | java | HttpUtilTest.java | Java | [
{
"context": " document = HttpUtil.getHtml(\"https://me.csdn.net/mashuai720\");\n Elements elements = document.select(\"d",
"end": 439,
"score": 0.9444286227226257,
"start": 429,
"tag": "USERNAME",
"value": "mashuai720"
}
] | null | [] | package com.demo;
import com.demo.util.HttpUtil;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.junit.Test;
public class HttpUtilTest {
@Test
public void download() {
HttpUtil.downLoad("http://www.pptok.com/wp-content/uploads/2012/08/xunguang-9.jpg", "D:\\Temp\\");
}
@Test
public void parseHtml() {
Document document = HttpUtil.getHtml("https://me.csdn.net/mashuai720");
Elements elements = document.select("dt h3 a");
elements.forEach(e -> {
String href = e.attr("href");
String title = e.text();
System.out.println(href);
System.out.println(title);
});
}
}
| 711 | 0.607595 | 0.592124 | 29 | 23.517241 | 24.754826 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482759 | false | false | 4 |
30fd68901b48039ae4cacc742488b74a1b541a83 | 24,172,075,985,882 | 155e41dc228d7e76e70232a4c0dcde63b39fe2c4 | /Artículos/src/main/java/com/nfsm/springboot/web/app/models/Productos.java | 3854bcc5a9539ed26b80683e7fdaf614e2ad6c70 | [] | no_license | kenia1403/proyecto_creadores | https://github.com/kenia1403/proyecto_creadores | a0d832e8c27ebd7ee8b92e5353aeff9837aee039 | 6253c146d56051a92d7da7d6715ec927b20679e4 | refs/heads/master | 2022-07-28T12:28:27.033000 | 2020-05-10T22:20:37 | 2020-05-10T22:20:37 | 262,195,037 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nfsm.springboot.web.app.models;
public class Productos {
public String nombre;
public String descripcion;
public String precio;
public String marca;
public String cantidad;
public String proveedor;
public Productos(String nombre, String descripcion, String precio, String marca, String cantidad,
String proveedor) {
super();
this.nombre = nombre;
this.descripcion = descripcion;
this.precio = precio;
this.marca = marca;
this.cantidad = cantidad;
this.proveedor = proveedor;
}
public Productos() {
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getPrecio() {
return precio;
}
public void setPrecio(String precio) {
this.precio = precio;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getCantidad() {
return cantidad;
}
public void setCantidad(String cantidad) {
this.cantidad = cantidad;
}
public String getProveedor() {
return proveedor;
}
public void setProveedor(String proveedor) {
this.proveedor = proveedor;
}
}
| UTF-8 | Java | 1,380 | java | Productos.java | Java | [] | null | [] | package com.nfsm.springboot.web.app.models;
public class Productos {
public String nombre;
public String descripcion;
public String precio;
public String marca;
public String cantidad;
public String proveedor;
public Productos(String nombre, String descripcion, String precio, String marca, String cantidad,
String proveedor) {
super();
this.nombre = nombre;
this.descripcion = descripcion;
this.precio = precio;
this.marca = marca;
this.cantidad = cantidad;
this.proveedor = proveedor;
}
public Productos() {
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getPrecio() {
return precio;
}
public void setPrecio(String precio) {
this.precio = precio;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getCantidad() {
return cantidad;
}
public void setCantidad(String cantidad) {
this.cantidad = cantidad;
}
public String getProveedor() {
return proveedor;
}
public void setProveedor(String proveedor) {
this.proveedor = proveedor;
}
}
| 1,380 | 0.678986 | 0.678986 | 73 | 16.90411 | 17.242163 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.452055 | false | false | 4 |
729dfc87dfbb3dbe3ac706841e3947c78142ff23 | 15,315,853,405,024 | 9a48b344669ded516a52e3b72c6e970e04168496 | /interview-prep/epo/dossierpersistence/trunk/src/main/java/org/epo/cms/edfs/services/dossierpersistence/util/DatabaseProperties.java | 4ef372211bbdae720189909c663431871156dc9c | [] | no_license | ankitjain-wiz/ProjectRedemption | https://github.com/ankitjain-wiz/ProjectRedemption | 6a2ebea9dadaaa1216da241959bf435a194f375e | e06b392f2e7baacea9d74e77f965192438f19ab5 | refs/heads/master | 2020-04-27T11:53:21.015000 | 2019-05-16T11:00:56 | 2019-05-16T11:00:56 | 174,310,601 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.epo.cms.edfs.services.dossierpersistence.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class DatabaseProperties {
private static final String DB_USERNAME = "${db.username}";
private static final String DB_PSWRD = "${db.password}";
private static final String DB_DRIVER = "${db.driver}";
private static final String DB_URL = "${db.url}";
private static final String DB_DIALECT = "${db.dialect}";
private static final String DB_SHOW_SQL = "${db.show_sql:false}";
private static final String DB_TRANSACTION_TIMEOUT = "${db.transaction.timeout:60}";
private static final String DB_POOL_MAX_SIZE = "${db.pool.max_size:15}";
private static final String DB_POOL_MIN_SIZE = "${db.pool.min_size:3}";
private static final String DB_POOL_AQUIRE_INCREMENT = "${db.pool.aquire_increment:3}";
private static final String DB_POOL_IDLE_TEST_PERIOD = "${db.pool.idle_test_period:0}";
private static final String DB_POOL_MAX_STATEMENTS = "${db.pool.max_statements:0}";
private static final String DB_POOL_TIMEOUT = "${db.pool.timeout:0}";
private static final String DB_POOL_TEST_ON_CHECKOUT = "${db.pool.test_on_checkout:true}";
private static final String DB_POOL_TEST_QUERY = "${db.pool.test_query:SELECT 1 FROM DUAL}";
@Value(DB_USERNAME)
private String dbUsername;
@Value(DB_PSWRD)
private String dbPassword;
@Value(DB_DRIVER)
private String dbDriver;
@Value(DB_URL)
private String dbUrl;
@Value(DB_DIALECT)
private String dbDialect;
@Value(DB_SHOW_SQL)
private String dbShowSql;
@Value(DB_TRANSACTION_TIMEOUT)
private int dbTransactionTimeout;
@Value(DB_POOL_MAX_SIZE)
private int dbPoolMaxSize;
@Value(DB_POOL_MIN_SIZE)
private int dbPoolMinSize;
@Value(DB_POOL_AQUIRE_INCREMENT)
private int dbPoolAquireIncrement;
@Value(DB_POOL_IDLE_TEST_PERIOD)
private int dbPoolIdleTestPeriod;
@Value(DB_POOL_MAX_STATEMENTS)
private int dbPoolMaxStatements;
@Value(DB_POOL_TIMEOUT)
private int dbPoolTimeout;
@Value(DB_POOL_TEST_ON_CHECKOUT)
private boolean dbPoolTestOnCheckout;
@Value(DB_POOL_TEST_QUERY)
private String dbPoolTestQuery;
public String getDbUsername() {
return dbUsername;
}
public void setDbUsername(String dbUsername) {
this.dbUsername = dbUsername;
}
public String getDbPassword() {
return dbPassword;
}
public void setDbPassword(String dbPassword) {
this.dbPassword = dbPassword;
}
public String getDbDriver() {
return dbDriver;
}
public void setDbDriver(String dbDriver) {
this.dbDriver = dbDriver;
}
public String getDbUrl() {
return dbUrl;
}
public void setDbUrl(String dbUrl) {
this.dbUrl = dbUrl;
}
public String getDbDialect() {
return dbDialect;
}
public void setDbDialect(String dbDialect) {
this.dbDialect = dbDialect;
}
public String getDbShowSql() {
return dbShowSql;
}
public void setDbShowSql(String dbShowSql) {
this.dbShowSql = dbShowSql;
}
public int getDbTransactionTimeout() {
return dbTransactionTimeout;
}
public void setDbTransactionTimeout(int dbTransactionTimeout) {
this.dbTransactionTimeout = dbTransactionTimeout;
}
public int getDbPoolMaxSize() {
return dbPoolMaxSize;
}
public void setDbPoolMaxSize(int dbPoolMaxSize) {
this.dbPoolMaxSize = dbPoolMaxSize;
}
public int getDbPoolMinSize() {
return dbPoolMinSize;
}
public void setDbPoolMinSize(int dbPoolMinSize) {
this.dbPoolMinSize = dbPoolMinSize;
}
public int getDbPoolAquireIncrement() {
return dbPoolAquireIncrement;
}
public void setDbPoolAquireIncrement(int dbPoolAquireIncrement) {
this.dbPoolAquireIncrement = dbPoolAquireIncrement;
}
public int getDbPoolIdleTestPeriod() {
return dbPoolIdleTestPeriod;
}
public void setDbPoolIdleTestPeriod(int dbPoolIdleTestPeriod) {
this.dbPoolIdleTestPeriod = dbPoolIdleTestPeriod;
}
public int getDbPoolMaxStatements() {
return dbPoolMaxStatements;
}
public void setDbPoolMaxStatements(int dbPoolMaxStatements) {
this.dbPoolMaxStatements = dbPoolMaxStatements;
}
public int getDbPoolTimeout() {
return dbPoolTimeout;
}
public void setDbPoolTimeout(int dbPoolTimeout) {
this.dbPoolTimeout = dbPoolTimeout;
}
public boolean isDbPoolTestOnCheckout() {
return dbPoolTestOnCheckout;
}
public void setDbPoolTestOnCheckout(boolean dbPoolTestOnCheckout) {
this.dbPoolTestOnCheckout = dbPoolTestOnCheckout;
}
public String getDbPoolTestQuery() {
return dbPoolTestQuery;
}
public void setDbPoolTestQuery(String dbPoolTestQuery) {
this.dbPoolTestQuery = dbPoolTestQuery;
}
}
| UTF-8 | Java | 4,595 | java | DatabaseProperties.java | Java | [] | null | [] | package org.epo.cms.edfs.services.dossierpersistence.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class DatabaseProperties {
private static final String DB_USERNAME = "${db.username}";
private static final String DB_PSWRD = "${db.password}";
private static final String DB_DRIVER = "${db.driver}";
private static final String DB_URL = "${db.url}";
private static final String DB_DIALECT = "${db.dialect}";
private static final String DB_SHOW_SQL = "${db.show_sql:false}";
private static final String DB_TRANSACTION_TIMEOUT = "${db.transaction.timeout:60}";
private static final String DB_POOL_MAX_SIZE = "${db.pool.max_size:15}";
private static final String DB_POOL_MIN_SIZE = "${db.pool.min_size:3}";
private static final String DB_POOL_AQUIRE_INCREMENT = "${db.pool.aquire_increment:3}";
private static final String DB_POOL_IDLE_TEST_PERIOD = "${db.pool.idle_test_period:0}";
private static final String DB_POOL_MAX_STATEMENTS = "${db.pool.max_statements:0}";
private static final String DB_POOL_TIMEOUT = "${db.pool.timeout:0}";
private static final String DB_POOL_TEST_ON_CHECKOUT = "${db.pool.test_on_checkout:true}";
private static final String DB_POOL_TEST_QUERY = "${db.pool.test_query:SELECT 1 FROM DUAL}";
@Value(DB_USERNAME)
private String dbUsername;
@Value(DB_PSWRD)
private String dbPassword;
@Value(DB_DRIVER)
private String dbDriver;
@Value(DB_URL)
private String dbUrl;
@Value(DB_DIALECT)
private String dbDialect;
@Value(DB_SHOW_SQL)
private String dbShowSql;
@Value(DB_TRANSACTION_TIMEOUT)
private int dbTransactionTimeout;
@Value(DB_POOL_MAX_SIZE)
private int dbPoolMaxSize;
@Value(DB_POOL_MIN_SIZE)
private int dbPoolMinSize;
@Value(DB_POOL_AQUIRE_INCREMENT)
private int dbPoolAquireIncrement;
@Value(DB_POOL_IDLE_TEST_PERIOD)
private int dbPoolIdleTestPeriod;
@Value(DB_POOL_MAX_STATEMENTS)
private int dbPoolMaxStatements;
@Value(DB_POOL_TIMEOUT)
private int dbPoolTimeout;
@Value(DB_POOL_TEST_ON_CHECKOUT)
private boolean dbPoolTestOnCheckout;
@Value(DB_POOL_TEST_QUERY)
private String dbPoolTestQuery;
public String getDbUsername() {
return dbUsername;
}
public void setDbUsername(String dbUsername) {
this.dbUsername = dbUsername;
}
public String getDbPassword() {
return dbPassword;
}
public void setDbPassword(String dbPassword) {
this.dbPassword = dbPassword;
}
public String getDbDriver() {
return dbDriver;
}
public void setDbDriver(String dbDriver) {
this.dbDriver = dbDriver;
}
public String getDbUrl() {
return dbUrl;
}
public void setDbUrl(String dbUrl) {
this.dbUrl = dbUrl;
}
public String getDbDialect() {
return dbDialect;
}
public void setDbDialect(String dbDialect) {
this.dbDialect = dbDialect;
}
public String getDbShowSql() {
return dbShowSql;
}
public void setDbShowSql(String dbShowSql) {
this.dbShowSql = dbShowSql;
}
public int getDbTransactionTimeout() {
return dbTransactionTimeout;
}
public void setDbTransactionTimeout(int dbTransactionTimeout) {
this.dbTransactionTimeout = dbTransactionTimeout;
}
public int getDbPoolMaxSize() {
return dbPoolMaxSize;
}
public void setDbPoolMaxSize(int dbPoolMaxSize) {
this.dbPoolMaxSize = dbPoolMaxSize;
}
public int getDbPoolMinSize() {
return dbPoolMinSize;
}
public void setDbPoolMinSize(int dbPoolMinSize) {
this.dbPoolMinSize = dbPoolMinSize;
}
public int getDbPoolAquireIncrement() {
return dbPoolAquireIncrement;
}
public void setDbPoolAquireIncrement(int dbPoolAquireIncrement) {
this.dbPoolAquireIncrement = dbPoolAquireIncrement;
}
public int getDbPoolIdleTestPeriod() {
return dbPoolIdleTestPeriod;
}
public void setDbPoolIdleTestPeriod(int dbPoolIdleTestPeriod) {
this.dbPoolIdleTestPeriod = dbPoolIdleTestPeriod;
}
public int getDbPoolMaxStatements() {
return dbPoolMaxStatements;
}
public void setDbPoolMaxStatements(int dbPoolMaxStatements) {
this.dbPoolMaxStatements = dbPoolMaxStatements;
}
public int getDbPoolTimeout() {
return dbPoolTimeout;
}
public void setDbPoolTimeout(int dbPoolTimeout) {
this.dbPoolTimeout = dbPoolTimeout;
}
public boolean isDbPoolTestOnCheckout() {
return dbPoolTestOnCheckout;
}
public void setDbPoolTestOnCheckout(boolean dbPoolTestOnCheckout) {
this.dbPoolTestOnCheckout = dbPoolTestOnCheckout;
}
public String getDbPoolTestQuery() {
return dbPoolTestQuery;
}
public void setDbPoolTestQuery(String dbPoolTestQuery) {
this.dbPoolTestQuery = dbPoolTestQuery;
}
}
| 4,595 | 0.759086 | 0.75691 | 162 | 27.364197 | 23.359709 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.506173 | false | false | 4 |
641635ee6c2ff86e27db2c6e2b743a85fafaafa3 | 20,203,526,208,367 | 94ba2b32f4817608c340a03640960d5f4fab53cc | /Leggo2/app/src/main/java/com/example/alex/leggo/MainActivity.java | 01a54698ae6f280a39afc16a6994044947224dba | [] | no_license | Hershey988/HACKUCSC | https://github.com/Hershey988/HACKUCSC | c35f30f089b1e126969f75f9f1bbad11ff39f5fd | 51c5592b6ecf8e5bdf6200235de8a8e43189db75 | refs/heads/master | 2021-01-13T15:57:49.752000 | 2017-01-22T13:38:09 | 2017-01-22T13:38:09 | 79,635,725 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.alex.leggo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private ImageButton b2;
private ImageButton button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (ImageButton) findViewById(R.id.event);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
StartEvent();
}
});
final ImageButton b2 = (ImageButton) findViewById(R.id.survey);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click+
StartSurvey();
}
});
final ImageButton b3 = (ImageButton) findViewById(R.id.chat);
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click+
StartChat();
}
});
}
public void StartChat() {
finish();
Intent myEvent = new Intent(getApplicationContext(), Chat_Room.class);
startActivity(myEvent);
}
public void StartSurvey() {
finish();
Intent myEvent = new Intent(getApplicationContext(), SurveyActivity.class);
startActivity(myEvent);
}
public void StartEvent() {
finish();
Intent myEvent = new Intent(getApplicationContext(), CategoryActivity.class);
startActivity(myEvent);
}
}
| UTF-8 | Java | 1,809 | java | MainActivity.java | Java | [
{
"context": "package com.example.alex.leggo;\n\nimport android.content.Intent;\nimport and",
"end": 24,
"score": 0.9548885226249695,
"start": 20,
"tag": "USERNAME",
"value": "alex"
}
] | null | [] | package com.example.alex.leggo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private ImageButton b2;
private ImageButton button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (ImageButton) findViewById(R.id.event);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
StartEvent();
}
});
final ImageButton b2 = (ImageButton) findViewById(R.id.survey);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click+
StartSurvey();
}
});
final ImageButton b3 = (ImageButton) findViewById(R.id.chat);
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click+
StartChat();
}
});
}
public void StartChat() {
finish();
Intent myEvent = new Intent(getApplicationContext(), Chat_Room.class);
startActivity(myEvent);
}
public void StartSurvey() {
finish();
Intent myEvent = new Intent(getApplicationContext(), SurveyActivity.class);
startActivity(myEvent);
}
public void StartEvent() {
finish();
Intent myEvent = new Intent(getApplicationContext(), CategoryActivity.class);
startActivity(myEvent);
}
}
| 1,809 | 0.616363 | 0.613046 | 61 | 28.655737 | 23.083515 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.508197 | false | false | 4 |
7aa81d21249dfcf1207920179e3b39ad476cbba5 | 21,698,174,793,333 | 64dfc398bf7a157eb03e196ab00e69a758432fc1 | /app/src/main/java/com/intelliworkz/admin/admingujaratabroad/NewsModel.java | 7a044e98ee54db0840e9bb940c10ac72208972f6 | [] | no_license | AnkitaPatel994/AdminGujaratAbroad | https://github.com/AnkitaPatel994/AdminGujaratAbroad | 0b7d8498232ff42e82b71b086a1b2a5921b1ac68 | ddc474cb08cbb35cb278cb4cb76e57c2f3466dc5 | refs/heads/master | 2021-01-02T09:23:48.706000 | 2017-08-03T07:44:16 | 2017-08-03T07:44:16 | 99,205,152 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.intelliworkz.admin.admingujaratabroad;
/**
* Created by pc-6 on 6/22/2017.
*/
public class NewsModel {
String newsId;
String newsCatId;
String newsTitle;
String newsDetails;
String newsImg;
String newsDate;
public NewsModel(String newsId, String newsCatId, String newsTitle, String newsDetails, String newsImg, String newsDate) {
this.newsId=newsId;
this.newsCatId=newsCatId;
this.newsTitle=newsTitle;
this.newsDetails=newsDetails;
this.newsImg=newsImg;
this.newsDate=newsDate;
}
public String getNewsId() {
return newsId;
}
public void setNewsId(String newsId) {
this.newsId = newsId;
}
public String getNewsCatId() {
return newsCatId;
}
public void setNewsCatId(String newsCatId) {
this.newsCatId = newsCatId;
}
public String getNewsTitle() {
return newsTitle;
}
public void setNewsTitle(String newsTitle) {
this.newsTitle = newsTitle;
}
public String getNewsDetails() {
return newsDetails;
}
public void setNewsDetails(String newsDetails) {
this.newsDetails = newsDetails;
}
public String getNewsImg() {
return newsImg;
}
public void setNewsImg(String newsImg) {
this.newsImg = newsImg;
}
public String getNewsDate() {
return newsDate;
}
public void setNewsDate(String newsDate) {
this.newsDate = newsDate;
}
}
| UTF-8 | Java | 1,515 | java | NewsModel.java | Java | [
{
"context": "workz.admin.admingujaratabroad;\n\n/**\n * Created by pc-6 on 6/22/2017.\n */\n\npublic class NewsModel {\n S",
"end": 74,
"score": 0.9995336532592773,
"start": 70,
"tag": "USERNAME",
"value": "pc-6"
}
] | null | [] | package com.intelliworkz.admin.admingujaratabroad;
/**
* Created by pc-6 on 6/22/2017.
*/
public class NewsModel {
String newsId;
String newsCatId;
String newsTitle;
String newsDetails;
String newsImg;
String newsDate;
public NewsModel(String newsId, String newsCatId, String newsTitle, String newsDetails, String newsImg, String newsDate) {
this.newsId=newsId;
this.newsCatId=newsCatId;
this.newsTitle=newsTitle;
this.newsDetails=newsDetails;
this.newsImg=newsImg;
this.newsDate=newsDate;
}
public String getNewsId() {
return newsId;
}
public void setNewsId(String newsId) {
this.newsId = newsId;
}
public String getNewsCatId() {
return newsCatId;
}
public void setNewsCatId(String newsCatId) {
this.newsCatId = newsCatId;
}
public String getNewsTitle() {
return newsTitle;
}
public void setNewsTitle(String newsTitle) {
this.newsTitle = newsTitle;
}
public String getNewsDetails() {
return newsDetails;
}
public void setNewsDetails(String newsDetails) {
this.newsDetails = newsDetails;
}
public String getNewsImg() {
return newsImg;
}
public void setNewsImg(String newsImg) {
this.newsImg = newsImg;
}
public String getNewsDate() {
return newsDate;
}
public void setNewsDate(String newsDate) {
this.newsDate = newsDate;
}
}
| 1,515 | 0.634323 | 0.629043 | 71 | 20.338028 | 20.475298 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.422535 | false | false | 4 |
38e7b5ced17bb3f1944a110e09e0a6a313f82bed | 3,539,053,095,312 | 1dde27e593087113d49ac2a8445d9a865f2efcba | /src/main/java/edu/ucsb/cs56/projects/games/pacman/model/ModelTrainingController.java | 4db25fe2aafe1355b296e066057ffae26733d3e7 | [] | no_license | jonasberlinma/AI-Pacman | https://github.com/jonasberlinma/AI-Pacman | fd0973e8a3b4b781fd38fd8bc51ae178c30a7afa | 42747964b305c6d0a5386ee7fce19f04bbf07abb | refs/heads/master | 2022-10-12T20:47:08.441000 | 2020-10-18T14:30:51 | 2020-10-18T14:30:51 | 83,733,571 | 2 | 0 | null | false | 2022-10-05T03:57:42 | 2017-03-02T23:00:25 | 2020-10-18T14:30:55 | 2022-10-05T03:57:41 | 739 | 1 | 0 | 2 | Java | false | false | package edu.ucsb.cs56.projects.games.pacman.model;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ModelTrainingController {
private static final String MODEL_QUEUE = "model";
private static final String GAME_QUEUE = "game";
private static Connection connection;
private static Channel channel;
private static String aiModelTrainerClassName;
private static AIModelTrainer aiModelTrainer;
public static void main(String[] args) {
boolean mqusessl = false;
String mqhost = "localhost";
int mqport = 5671; // SSL port is default
String mqusername = null;
String mqpassword = null;
boolean verbose = false;
Iterator<String> argi = new Vector<String>(Arrays.asList(args)).iterator();
while (argi.hasNext()) {
String theArg = argi.next();
switch (theArg) {
case "-mqusessl":
mqusessl = true;
break;
case "-mqhost":
mqhost = argi.next();
break;
case "-mqport":
mqport = Integer.parseInt(argi.next());
break;
case "-verbose":
verbose = true;
break;
case "-aiModelTrainerClassName":
aiModelTrainerClassName = argi.next();
break;
case "-mqusername":
mqusername = argi.next();
break;
case "-mqpassword":
mqpassword = argi.next();
break;
default:
System.out.println("Invalid command Line argument" + theArg);
System.exit(1);
}
}
// First create RabbitMQ connection, channel, and queues
//
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(mqhost);
factory.setPort(mqport);
factory.setUsername(mqusername);
factory.setPassword(mqpassword);
try {
if (mqusessl) {
factory.useSslProtocol();
}
connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare(MODEL_QUEUE, false, false, false, null);
channel.queueDeclare(GAME_QUEUE, false, false, false, null);
} catch (IOException e) {
System.err.println("MQ IOException " + e.getMessage());
e.printStackTrace();
} catch (TimeoutException e) {
System.err.println("MQ timeout " + e.getMessage());
e.printStackTrace();
} catch (KeyManagementException e) {
System.err.println("MQ: Unable to retrieve TLS keys." + e.getMessage());
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
System.err.println("MQ bad algorithm " + e.getMessage());
e.printStackTrace();
} finally {
if (channel == null) {
System.err.println("Error connecting to MQ. Channel is null");
System.exit(1);
}
}
// Now create create the AIModelTrainer of the specified kind and hand the queue
// handles
aiModelTrainer = loadTrainer();
// Finally start the model trainer
aiModelTrainer.start();
}
private static AIModelTrainer loadTrainer() {
System.out.println("Loading trainer");
AIModelTrainer aiModelTrainer = null;
try {
Class<?> theClass = Class.forName(aiModelTrainerClassName);
aiModelTrainer = (AIModelTrainer) theClass.newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
System.err.println("Failed to load trainer");
e.printStackTrace();
}
aiModelTrainer.setController(channel, GAME_QUEUE, MODEL_QUEUE);
return aiModelTrainer;
}
}
| UTF-8 | Java | 3,537 | java | ModelTrainingController.java | Java | [
{
"context": "\n\t\tfactory.setPort(mqport);\n\t\tfactory.setUsername(mqusername);\n\t\tfactory.setPassword(mqpassword);\n\t\ttry {\n\t\t\ti",
"end": 1881,
"score": 0.9995245933532715,
"start": 1871,
"tag": "USERNAME",
"value": "mqusername"
},
{
"context": "ry.setUsername(mqusername)... | null | [] | package edu.ucsb.cs56.projects.games.pacman.model;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ModelTrainingController {
private static final String MODEL_QUEUE = "model";
private static final String GAME_QUEUE = "game";
private static Connection connection;
private static Channel channel;
private static String aiModelTrainerClassName;
private static AIModelTrainer aiModelTrainer;
public static void main(String[] args) {
boolean mqusessl = false;
String mqhost = "localhost";
int mqport = 5671; // SSL port is default
String mqusername = null;
String mqpassword = null;
boolean verbose = false;
Iterator<String> argi = new Vector<String>(Arrays.asList(args)).iterator();
while (argi.hasNext()) {
String theArg = argi.next();
switch (theArg) {
case "-mqusessl":
mqusessl = true;
break;
case "-mqhost":
mqhost = argi.next();
break;
case "-mqport":
mqport = Integer.parseInt(argi.next());
break;
case "-verbose":
verbose = true;
break;
case "-aiModelTrainerClassName":
aiModelTrainerClassName = argi.next();
break;
case "-mqusername":
mqusername = argi.next();
break;
case "-mqpassword":
mqpassword = argi.next();
break;
default:
System.out.println("Invalid command Line argument" + theArg);
System.exit(1);
}
}
// First create RabbitMQ connection, channel, and queues
//
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(mqhost);
factory.setPort(mqport);
factory.setUsername(mqusername);
factory.setPassword(<PASSWORD>);
try {
if (mqusessl) {
factory.useSslProtocol();
}
connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare(MODEL_QUEUE, false, false, false, null);
channel.queueDeclare(GAME_QUEUE, false, false, false, null);
} catch (IOException e) {
System.err.println("MQ IOException " + e.getMessage());
e.printStackTrace();
} catch (TimeoutException e) {
System.err.println("MQ timeout " + e.getMessage());
e.printStackTrace();
} catch (KeyManagementException e) {
System.err.println("MQ: Unable to retrieve TLS keys." + e.getMessage());
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
System.err.println("MQ bad algorithm " + e.getMessage());
e.printStackTrace();
} finally {
if (channel == null) {
System.err.println("Error connecting to MQ. Channel is null");
System.exit(1);
}
}
// Now create create the AIModelTrainer of the specified kind and hand the queue
// handles
aiModelTrainer = loadTrainer();
// Finally start the model trainer
aiModelTrainer.start();
}
private static AIModelTrainer loadTrainer() {
System.out.println("Loading trainer");
AIModelTrainer aiModelTrainer = null;
try {
Class<?> theClass = Class.forName(aiModelTrainerClassName);
aiModelTrainer = (AIModelTrainer) theClass.newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
System.err.println("Failed to load trainer");
e.printStackTrace();
}
aiModelTrainer.setController(channel, GAME_QUEUE, MODEL_QUEUE);
return aiModelTrainer;
}
}
| 3,537 | 0.712751 | 0.710489 | 119 | 28.722689 | 20.555285 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.806723 | false | false | 4 |
805d42ceded59f42c46c6b2b08ba515b9134a100 | 16,441,134,829,216 | 5adbb497494e32cab39f955d58b1a3ab69d98090 | /BrainSim/src/ConfigWindow.java | 724e8ecfc7d8c62104c4729010102f02710c1cdf | [] | no_license | harvyso/BrainSim | https://github.com/harvyso/BrainSim | 93c65f6b86eefc62f14f75f46653b2feddcb0231 | 042e15b973e93a8569df99e89b51a11dbd9ab9b1 | refs/heads/master | 2020-03-21T22:11:19.397000 | 2018-01-15T21:22:44 | 2018-01-15T21:22:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JSlider;
import javax.swing.JCheckBox;
import javax.swing.JSpinner;
import javax.swing.SizeSequence;
import javax.swing.SpinnerNumberModel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.Random;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JComboBox;
public class ConfigWindow extends JFrame {
private JPanel contentPane;
private JSpinner eruptionPropabilitySpinner;
private JSpinner eruptionOutputSpinner;
private JSpinner thresholdSpinner;
private JSpinner cooldownSpinner;
private JSpinner linkDistanceSpinner;
private JSpinner neurocellsizeSpinner;
private JCheckBox checkBox_monocrome;
private Brain brain;
private Timer simTimer;
private Random ran;
/**
* Create the frame.
*/
public ConfigWindow(Brain brain, Timer simTimer) {
this.brain = brain;
this.simTimer = simTimer;
this.ran = new Random(1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 477, 381);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblSimulationStatus = new JLabel("Simulation Status:");
lblSimulationStatus.setBounds(10, 11, 99, 14);
contentPane.add(lblSimulationStatus);
JLabel lblPaused = new JLabel("stopped");
lblPaused.setBounds(119, 11, 87, 14);
contentPane.add(lblPaused);
JButton btnNewButton = new JButton("start");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (simTimer.isRunning()) {
simTimer.stop();
lblPaused.setText("stopped");
btnNewButton.setText("start");
} else {
simTimer.start();
lblPaused.setText("running");
btnNewButton.setText("stop");
}
}
});
btnNewButton.setBounds(216, 11, 137, 14);
contentPane.add(btnNewButton);
JLabel label_4 = new JLabel("16ms");
label_4.setBounds(363, 36, 80, 14);
contentPane.add(label_4);
JSlider slider = new JSlider();
slider.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent arg0) {
simTimer.setDelay((int) slider.getValue());
label_4.setText((int) slider.getValue() + "ms");
}
});
slider.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent arg0) {
simTimer.setDelay((int) slider.getValue());
label_4.setText((int) slider.getValue() + "ms");
}
});
slider.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent arg0) {
}
});
slider.setMaximum(1000);
slider.setMinimum(16);
slider.setValue(16);
slider.setBounds(119, 36, 234, 14);
contentPane.add(slider);
JCheckBox chckbxDrawLinkLines = new JCheckBox("draw link lines");
chckbxDrawLinkLines.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
brain.setDrawLinkLines(chckbxDrawLinkLines.isSelected());
}
});
chckbxDrawLinkLines.setBounds(10, 126, 110, 23);
contentPane.add(chckbxDrawLinkLines);
JLabel lblAddNeurocells = new JLabel("Add Neurocells:");
lblAddNeurocells.setBounds(10, 62, 80, 14);
contentPane.add(lblAddNeurocells);
JSpinner spinner = new JSpinner();
spinner.setModel(new SpinnerNumberModel(new Integer(25600),
new Integer(1), null, new Integer(1)));
spinner.setBounds(119, 62, 147, 14);
contentPane.add(spinner);
JButton btnAdd = new JButton("add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < (int) spinner.getValue(); i++) {
brain.getNeurocells()
.add(new NeuroCell(
(float) thresholdSpinner.getValue(),
(int) cooldownSpinner.getValue(),
(float) eruptionPropabilitySpinner
.getValue(),
(float) eruptionOutputSpinner.getValue(),
(int) (ran.nextFloat() * brain.getWidth()),
(int) (ran.nextFloat() * brain.getHeight()),
(int) neurocellsizeSpinner.getValue(),
Color.gray, Color.magenta, checkBox_monocrome.isSelected()));
}
}
});
btnAdd.setBounds(276, 61, 80, 15);
contentPane.add(btnAdd);
JLabel lblEruptionProbability = new JLabel("Eruption Probability:");
lblEruptionProbability.setBounds(10, 189, 99, 14);
contentPane.add(lblEruptionProbability);
eruptionPropabilitySpinner = new JSpinner();
eruptionPropabilitySpinner.setModel(new SpinnerNumberModel(new Float(
0.001), new Float(0), new Float(2), new Float(0)));
eruptionPropabilitySpinner.setBounds(119, 190, 147, 14);
contentPane.add(eruptionPropabilitySpinner);
JButton button = new JButton("set");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells()
.get(i)
.setEruptionPropability(
(float) eruptionPropabilitySpinner
.getValue());
}
}
});
button.setBounds(276, 189, 80, 15);
contentPane.add(button);
JLabel lblThreshold = new JLabel("Threshold:");
lblThreshold.setBounds(10, 240, 99, 14);
contentPane.add(lblThreshold);
thresholdSpinner = new JSpinner();
thresholdSpinner.setModel(new SpinnerNumberModel(new Float(5), null,
null, new Float(1)));
thresholdSpinner.setBounds(119, 241, 147, 14);
contentPane.add(thresholdSpinner);
JButton button_1 = new JButton("set");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i)
.setThreshold((float) thresholdSpinner.getValue());
}
}
});
button_1.setBounds(276, 240, 80, 15);
contentPane.add(button_1);
JButton button_2 = new JButton("set");
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LinkThread lThread = new LinkThread(brain, (double)linkDistanceSpinner.getValue());
lThread.run();
// destroy links
/*
ArrayList<NeuroCell> tmpList = new ArrayList<NeuroCell>();
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i).getInputs().clear();
tmpList.add(brain.getNeurocells().get(i));
}
brain.setLinkRadius((double) linkDistanceSpinner.getValue());
brain.getNeurocells().clear();
for (int i = 0; i < tmpList.size(); i++) {
brain.addNeurocell(tmpList.get(i));
}
*/
}
});
button_2.setBounds(276, 291, 80, 15);
contentPane.add(button_2);
linkDistanceSpinner = new JSpinner();
linkDistanceSpinner.setModel(new SpinnerNumberModel(new Double(9),
new Double(0), null, new Double(1)));
linkDistanceSpinner.setBounds(119, 292, 147, 14);
contentPane.add(linkDistanceSpinner);
JLabel lblLinkDistance = new JLabel("Link Distance:");
lblLinkDistance.setBounds(10, 291, 99, 14);
contentPane.add(lblLinkDistance);
JButton button_3 = new JButton("set");
button_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i)
.setCooldown((int) cooldownSpinner.getValue());
}
}
});
button_3.setBounds(276, 265, 80, 15);
contentPane.add(button_3);
cooldownSpinner = new JSpinner();
cooldownSpinner.setModel(new SpinnerNumberModel(new Integer(22),
new Integer(0), null, new Integer(1)));
cooldownSpinner.setBounds(119, 266, 147, 14);
contentPane.add(cooldownSpinner);
JLabel label = new JLabel("Cooldown:");
label.setBounds(10, 265, 99, 14);
contentPane.add(label);
JLabel label_1 = new JLabel("Neurocell Size:");
label_1.setBounds(10, 317, 99, 14);
contentPane.add(label_1);
neurocellsizeSpinner = new JSpinner();
neurocellsizeSpinner.setModel(new SpinnerNumberModel(4, 1, 100, 1));
neurocellsizeSpinner.setBounds(119, 318, 147, 14);
contentPane.add(neurocellsizeSpinner);
JButton button_4 = new JButton("set");
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i)
.setSize((int) neurocellsizeSpinner.getValue());
}
}
});
button_4.setBounds(276, 317, 80, 15);
contentPane.add(button_4);
eruptionOutputSpinner = new JSpinner();
eruptionOutputSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1)));
eruptionOutputSpinner.setBounds(119, 215, 147, 14);
contentPane.add(eruptionOutputSpinner);
JButton button_5 = new JButton("set");
button_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells()
.get(i)
.setEruptionOutput(
(float) eruptionOutputSpinner.getValue());
}
}
});
button_5.setBounds(276, 214, 80, 15);
contentPane.add(button_5);
JLabel label_2 = new JLabel("Eruption Output:");
label_2.setBounds(10, 214, 99, 14);
contentPane.add(label_2);
JButton button_6 = new JButton("clear");
button_6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
brain.getNeurocells().clear();
}
});
button_6.setBounds(366, 61, 80, 15);
contentPane.add(button_6);
JLabel label_3 = new JLabel("Timer Interval:");
label_3.setBounds(10, 36, 80, 14);
contentPane.add(label_3);
JButton button_7 = new JButton("randomize positions");
button_7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i)
.setX((int) (ran.nextFloat() * brain.getWidth()));
brain.getNeurocells().get(i)
.setY((int) (ran.nextFloat() * brain.getHeight()));
}
}
});
button_7.setBounds(119, 126, 147, 15);
contentPane.add(button_7);
JButton btnCalculateLinks = new JButton("calculate links");
btnCalculateLinks.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// destroy links
ArrayList<NeuroCell> tmpList = new ArrayList<NeuroCell>();
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i).getInputs().clear();
tmpList.add(brain.getNeurocells().get(i));
}
brain.setLinkRadius((double) linkDistanceSpinner.getValue());
brain.getNeurocells().clear();
for (int i = 0; i < tmpList.size(); i++) {
brain.addNeurocell(tmpList.get(i));
}
}
});
btnCalculateLinks.setBounds(276, 126, 147, 15);
contentPane.add(btnCalculateLinks);
JButton button_9 = new JButton("square positions");
button_9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sqrt = (int) Math.sqrt(brain.getNeurocells().size());
// get rid of rest
int tmp = sqrt * sqrt;
while (brain.getNeurocells().size() != tmp) {
brain.getNeurocells().remove(tmp);
}
spinner.setValue(tmp);
int counter = 0;
for (int i = 0; i < sqrt; i++) {
for (int k = 0; k < sqrt; k++) {
brain.getNeurocells()
.get(counter)
.setX(i * (int) neurocellsizeSpinner.getValue());
brain.getNeurocells()
.get(counter)
.setY(k * (int) neurocellsizeSpinner.getValue());
counter++;
}
}
}
});
button_9.setBounds(119, 152, 147, 15);
contentPane.add(button_9);
JCheckBox checkBox = new JCheckBox("draw rectangles");
checkBox.setSelected(true);
checkBox.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent arg0) {
brain.setDrawRects(checkBox.isSelected());
}
});
checkBox.setBounds(10, 152, 110, 23);
contentPane.add(checkBox);
JButton button_8 = new JButton("reset simulation");
button_8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i).setOutput(0.0f);
}
}
});
button_8.setBounds(276, 152, 147, 15);
contentPane.add(button_8);
JSpinner spinner_1 = new JSpinner();
spinner_1.setBounds(119, 87, 70, 14);
contentPane.add(spinner_1);
JSpinner spinner_2 = new JSpinner();
spinner_2.setBounds(199, 87, 70, 14);
contentPane.add(spinner_2);
JButton button_10 = new JButton("add");
button_10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
brain.createRectBrain((int) spinner_1.getValue(),
(int) spinner_2.getValue(),
(float) thresholdSpinner.getValue(),
(int) cooldownSpinner.getValue(),
(float) eruptionPropabilitySpinner.getValue(),
Color.black, Color.green,
(float) eruptionOutputSpinner.getValue(),
(int) neurocellsizeSpinner.getValue());
}
});
button_10.setBounds(276, 83, 80, 15);
contentPane.add(button_10);
checkBox_monocrome = new JCheckBox("monocrome");
checkBox_monocrome.setBounds(10, 100, 110, 23);
contentPane.add(checkBox_monocrome);
}
}
| UTF-8 | Java | 14,104 | java | ConfigWindow.java | Java | [] | null | [] | import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JSlider;
import javax.swing.JCheckBox;
import javax.swing.JSpinner;
import javax.swing.SizeSequence;
import javax.swing.SpinnerNumberModel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.Random;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JComboBox;
public class ConfigWindow extends JFrame {
private JPanel contentPane;
private JSpinner eruptionPropabilitySpinner;
private JSpinner eruptionOutputSpinner;
private JSpinner thresholdSpinner;
private JSpinner cooldownSpinner;
private JSpinner linkDistanceSpinner;
private JSpinner neurocellsizeSpinner;
private JCheckBox checkBox_monocrome;
private Brain brain;
private Timer simTimer;
private Random ran;
/**
* Create the frame.
*/
public ConfigWindow(Brain brain, Timer simTimer) {
this.brain = brain;
this.simTimer = simTimer;
this.ran = new Random(1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 477, 381);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblSimulationStatus = new JLabel("Simulation Status:");
lblSimulationStatus.setBounds(10, 11, 99, 14);
contentPane.add(lblSimulationStatus);
JLabel lblPaused = new JLabel("stopped");
lblPaused.setBounds(119, 11, 87, 14);
contentPane.add(lblPaused);
JButton btnNewButton = new JButton("start");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (simTimer.isRunning()) {
simTimer.stop();
lblPaused.setText("stopped");
btnNewButton.setText("start");
} else {
simTimer.start();
lblPaused.setText("running");
btnNewButton.setText("stop");
}
}
});
btnNewButton.setBounds(216, 11, 137, 14);
contentPane.add(btnNewButton);
JLabel label_4 = new JLabel("16ms");
label_4.setBounds(363, 36, 80, 14);
contentPane.add(label_4);
JSlider slider = new JSlider();
slider.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent arg0) {
simTimer.setDelay((int) slider.getValue());
label_4.setText((int) slider.getValue() + "ms");
}
});
slider.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent arg0) {
simTimer.setDelay((int) slider.getValue());
label_4.setText((int) slider.getValue() + "ms");
}
});
slider.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent arg0) {
}
});
slider.setMaximum(1000);
slider.setMinimum(16);
slider.setValue(16);
slider.setBounds(119, 36, 234, 14);
contentPane.add(slider);
JCheckBox chckbxDrawLinkLines = new JCheckBox("draw link lines");
chckbxDrawLinkLines.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
brain.setDrawLinkLines(chckbxDrawLinkLines.isSelected());
}
});
chckbxDrawLinkLines.setBounds(10, 126, 110, 23);
contentPane.add(chckbxDrawLinkLines);
JLabel lblAddNeurocells = new JLabel("Add Neurocells:");
lblAddNeurocells.setBounds(10, 62, 80, 14);
contentPane.add(lblAddNeurocells);
JSpinner spinner = new JSpinner();
spinner.setModel(new SpinnerNumberModel(new Integer(25600),
new Integer(1), null, new Integer(1)));
spinner.setBounds(119, 62, 147, 14);
contentPane.add(spinner);
JButton btnAdd = new JButton("add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < (int) spinner.getValue(); i++) {
brain.getNeurocells()
.add(new NeuroCell(
(float) thresholdSpinner.getValue(),
(int) cooldownSpinner.getValue(),
(float) eruptionPropabilitySpinner
.getValue(),
(float) eruptionOutputSpinner.getValue(),
(int) (ran.nextFloat() * brain.getWidth()),
(int) (ran.nextFloat() * brain.getHeight()),
(int) neurocellsizeSpinner.getValue(),
Color.gray, Color.magenta, checkBox_monocrome.isSelected()));
}
}
});
btnAdd.setBounds(276, 61, 80, 15);
contentPane.add(btnAdd);
JLabel lblEruptionProbability = new JLabel("Eruption Probability:");
lblEruptionProbability.setBounds(10, 189, 99, 14);
contentPane.add(lblEruptionProbability);
eruptionPropabilitySpinner = new JSpinner();
eruptionPropabilitySpinner.setModel(new SpinnerNumberModel(new Float(
0.001), new Float(0), new Float(2), new Float(0)));
eruptionPropabilitySpinner.setBounds(119, 190, 147, 14);
contentPane.add(eruptionPropabilitySpinner);
JButton button = new JButton("set");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells()
.get(i)
.setEruptionPropability(
(float) eruptionPropabilitySpinner
.getValue());
}
}
});
button.setBounds(276, 189, 80, 15);
contentPane.add(button);
JLabel lblThreshold = new JLabel("Threshold:");
lblThreshold.setBounds(10, 240, 99, 14);
contentPane.add(lblThreshold);
thresholdSpinner = new JSpinner();
thresholdSpinner.setModel(new SpinnerNumberModel(new Float(5), null,
null, new Float(1)));
thresholdSpinner.setBounds(119, 241, 147, 14);
contentPane.add(thresholdSpinner);
JButton button_1 = new JButton("set");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i)
.setThreshold((float) thresholdSpinner.getValue());
}
}
});
button_1.setBounds(276, 240, 80, 15);
contentPane.add(button_1);
JButton button_2 = new JButton("set");
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LinkThread lThread = new LinkThread(brain, (double)linkDistanceSpinner.getValue());
lThread.run();
// destroy links
/*
ArrayList<NeuroCell> tmpList = new ArrayList<NeuroCell>();
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i).getInputs().clear();
tmpList.add(brain.getNeurocells().get(i));
}
brain.setLinkRadius((double) linkDistanceSpinner.getValue());
brain.getNeurocells().clear();
for (int i = 0; i < tmpList.size(); i++) {
brain.addNeurocell(tmpList.get(i));
}
*/
}
});
button_2.setBounds(276, 291, 80, 15);
contentPane.add(button_2);
linkDistanceSpinner = new JSpinner();
linkDistanceSpinner.setModel(new SpinnerNumberModel(new Double(9),
new Double(0), null, new Double(1)));
linkDistanceSpinner.setBounds(119, 292, 147, 14);
contentPane.add(linkDistanceSpinner);
JLabel lblLinkDistance = new JLabel("Link Distance:");
lblLinkDistance.setBounds(10, 291, 99, 14);
contentPane.add(lblLinkDistance);
JButton button_3 = new JButton("set");
button_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i)
.setCooldown((int) cooldownSpinner.getValue());
}
}
});
button_3.setBounds(276, 265, 80, 15);
contentPane.add(button_3);
cooldownSpinner = new JSpinner();
cooldownSpinner.setModel(new SpinnerNumberModel(new Integer(22),
new Integer(0), null, new Integer(1)));
cooldownSpinner.setBounds(119, 266, 147, 14);
contentPane.add(cooldownSpinner);
JLabel label = new JLabel("Cooldown:");
label.setBounds(10, 265, 99, 14);
contentPane.add(label);
JLabel label_1 = new JLabel("Neurocell Size:");
label_1.setBounds(10, 317, 99, 14);
contentPane.add(label_1);
neurocellsizeSpinner = new JSpinner();
neurocellsizeSpinner.setModel(new SpinnerNumberModel(4, 1, 100, 1));
neurocellsizeSpinner.setBounds(119, 318, 147, 14);
contentPane.add(neurocellsizeSpinner);
JButton button_4 = new JButton("set");
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i)
.setSize((int) neurocellsizeSpinner.getValue());
}
}
});
button_4.setBounds(276, 317, 80, 15);
contentPane.add(button_4);
eruptionOutputSpinner = new JSpinner();
eruptionOutputSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1)));
eruptionOutputSpinner.setBounds(119, 215, 147, 14);
contentPane.add(eruptionOutputSpinner);
JButton button_5 = new JButton("set");
button_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells()
.get(i)
.setEruptionOutput(
(float) eruptionOutputSpinner.getValue());
}
}
});
button_5.setBounds(276, 214, 80, 15);
contentPane.add(button_5);
JLabel label_2 = new JLabel("Eruption Output:");
label_2.setBounds(10, 214, 99, 14);
contentPane.add(label_2);
JButton button_6 = new JButton("clear");
button_6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
brain.getNeurocells().clear();
}
});
button_6.setBounds(366, 61, 80, 15);
contentPane.add(button_6);
JLabel label_3 = new JLabel("Timer Interval:");
label_3.setBounds(10, 36, 80, 14);
contentPane.add(label_3);
JButton button_7 = new JButton("randomize positions");
button_7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i)
.setX((int) (ran.nextFloat() * brain.getWidth()));
brain.getNeurocells().get(i)
.setY((int) (ran.nextFloat() * brain.getHeight()));
}
}
});
button_7.setBounds(119, 126, 147, 15);
contentPane.add(button_7);
JButton btnCalculateLinks = new JButton("calculate links");
btnCalculateLinks.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// destroy links
ArrayList<NeuroCell> tmpList = new ArrayList<NeuroCell>();
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i).getInputs().clear();
tmpList.add(brain.getNeurocells().get(i));
}
brain.setLinkRadius((double) linkDistanceSpinner.getValue());
brain.getNeurocells().clear();
for (int i = 0; i < tmpList.size(); i++) {
brain.addNeurocell(tmpList.get(i));
}
}
});
btnCalculateLinks.setBounds(276, 126, 147, 15);
contentPane.add(btnCalculateLinks);
JButton button_9 = new JButton("square positions");
button_9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sqrt = (int) Math.sqrt(brain.getNeurocells().size());
// get rid of rest
int tmp = sqrt * sqrt;
while (brain.getNeurocells().size() != tmp) {
brain.getNeurocells().remove(tmp);
}
spinner.setValue(tmp);
int counter = 0;
for (int i = 0; i < sqrt; i++) {
for (int k = 0; k < sqrt; k++) {
brain.getNeurocells()
.get(counter)
.setX(i * (int) neurocellsizeSpinner.getValue());
brain.getNeurocells()
.get(counter)
.setY(k * (int) neurocellsizeSpinner.getValue());
counter++;
}
}
}
});
button_9.setBounds(119, 152, 147, 15);
contentPane.add(button_9);
JCheckBox checkBox = new JCheckBox("draw rectangles");
checkBox.setSelected(true);
checkBox.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent arg0) {
brain.setDrawRects(checkBox.isSelected());
}
});
checkBox.setBounds(10, 152, 110, 23);
contentPane.add(checkBox);
JButton button_8 = new JButton("reset simulation");
button_8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < brain.getNeurocells().size(); i++) {
brain.getNeurocells().get(i).setOutput(0.0f);
}
}
});
button_8.setBounds(276, 152, 147, 15);
contentPane.add(button_8);
JSpinner spinner_1 = new JSpinner();
spinner_1.setBounds(119, 87, 70, 14);
contentPane.add(spinner_1);
JSpinner spinner_2 = new JSpinner();
spinner_2.setBounds(199, 87, 70, 14);
contentPane.add(spinner_2);
JButton button_10 = new JButton("add");
button_10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
brain.createRectBrain((int) spinner_1.getValue(),
(int) spinner_2.getValue(),
(float) thresholdSpinner.getValue(),
(int) cooldownSpinner.getValue(),
(float) eruptionPropabilitySpinner.getValue(),
Color.black, Color.green,
(float) eruptionOutputSpinner.getValue(),
(int) neurocellsizeSpinner.getValue());
}
});
button_10.setBounds(276, 83, 80, 15);
contentPane.add(button_10);
checkBox_monocrome = new JCheckBox("monocrome");
checkBox_monocrome.setBounds(10, 100, 110, 23);
contentPane.add(checkBox_monocrome);
}
}
| 14,104 | 0.668959 | 0.631877 | 431 | 30.723898 | 20.499117 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.589327 | false | false | 4 |
ee7fcc5d262f727b598f95a75409645a20f88279 | 1,194,000,960,306 | a45818db5de7551b859baae0b5585c001331329a | /src/main/java/controlers/TestController.java | 3010efc9be46b70076b991562d0e6b39958d1b4c | [] | no_license | mderkaoui/bibliotheque2 | https://github.com/mderkaoui/bibliotheque2 | 27a9f1ffded2c7eee90a03236deacdcf371b718f | b6e73d024a6b976d78cd404bbdbc0e6a25685524 | refs/heads/master | 2020-05-23T04:59:13.995000 | 2019-05-14T14:51:56 | 2019-05-14T14:51:56 | 186,643,366 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controlers;
import java.io.IOException;
import java.sql.Connection;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.Livre;
import beans.User;
import beans.enums.Genre;
import beans.enums.Role;
import dao.ConnectionDB;
import dao.LivreDao;
import dao.UserDao;
/**
* Servlet implementation class TestController
*/
@WebServlet("/test-data")
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TestController() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Connection cnx = ConnectionDB.getConnection();
UserDao.insert(new User(0,"arnaud", "password", Role.ADMIN),cnx,false);
UserDao.insert(new User(0,"marcel", "123456", Role.USER),cnx,false);
UserDao.insert(new User(0,"george", "password", Role.USER),cnx,false);
UserDao.insert(new User(0,"Solène", "password", Role.USER),cnx,false);
UserDao.insert(new User(0,"Margot", "password", Role.USER),cnx,false);
UserDao.insert(new User(0,"Rachid", "password", Role.USER),cnx,false);
UserDao.insert(new User(0,"anonymous", "", Role.ANONYMOUS),cnx,false);
for (int i = 1; i <= 40; i++) {
LivreDao.insert(new Livre("livre"+i, "auteur"+i, new Date(), Genre.HORREUR), cnx, false);
}
cnx.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| UTF-8 | Java | 2,109 | java | TestController.java | Java | [
{
"context": "DB.getConnection();\n\t\t\tUserDao.insert(new User(0,\"arnaud\", \"password\", Role.ADMIN),cnx,false);\n\t\t\tUserDao.",
"end": 1106,
"score": 0.9893155097961426,
"start": 1100,
"tag": "NAME",
"value": "arnaud"
},
{
"context": ".ADMIN),cnx,false);\n\t\t\tUserDao.insert(... | null | [] | package controlers;
import java.io.IOException;
import java.sql.Connection;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.Livre;
import beans.User;
import beans.enums.Genre;
import beans.enums.Role;
import dao.ConnectionDB;
import dao.LivreDao;
import dao.UserDao;
/**
* Servlet implementation class TestController
*/
@WebServlet("/test-data")
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TestController() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Connection cnx = ConnectionDB.getConnection();
UserDao.insert(new User(0,"arnaud", "password", Role.ADMIN),cnx,false);
UserDao.insert(new User(0,"marcel", "123456", Role.USER),cnx,false);
UserDao.insert(new User(0,"george", "password", Role.USER),cnx,false);
UserDao.insert(new User(0,"Solène", "password", Role.USER),cnx,false);
UserDao.insert(new User(0,"Margot", "password", Role.USER),cnx,false);
UserDao.insert(new User(0,"Rachid", "password", Role.USER),cnx,false);
UserDao.insert(new User(0,"anonymous", "", Role.ANONYMOUS),cnx,false);
for (int i = 1; i <= 40; i++) {
LivreDao.insert(new Livre("livre"+i, "auteur"+i, new Date(), Genre.HORREUR), cnx, false);
}
cnx.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| 2,109 | 0.722486 | 0.714421 | 76 | 26.736841 | 26.153076 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.184211 | false | false | 4 |
bb7d0257458c054839a98e70189d14d7872ceb7d | 12,592,844,115,914 | 92b5c5a8459ff872794fe8dc06825af8cf0dc357 | /src/chapter17/Code17_1.java | c327a46a6a8e57353a8d99d9154a5ff8e29e0bd5 | [] | no_license | CodingDancerSky/CrackingCode | https://github.com/CodingDancerSky/CrackingCode | 1250af0dbea48b43fe22edae5764e377780bdbe8 | 075c210026dd7d3d359c30b44efa60943ca4c295 | refs/heads/master | 2020-04-09T23:40:19.562000 | 2015-08-30T21:10:31 | 2015-08-30T21:10:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chapter17;
public class Code17_1 {
static void swap1(int a,int b){
a=a-b;
b=a+b;
a=b-a;
}
static void swap2(int a, int b){
a=a^b;
b=a^b;
a=a^b;
}
public static void main(String[] args) {
int a = 1672;
int b = 9332;
// System.out.println("a: " + a);
// System.out.println("b: " + b);
swap1(a, b);
System.out.println("a: " + a);
System.out.println("b: " + b);
swap2(a, b);
System.out.println("a: " + a);
System.out.println("b: " + b);
}
}
| UTF-8 | Java | 536 | java | Code17_1.java | Java | [] | null | [] | package chapter17;
public class Code17_1 {
static void swap1(int a,int b){
a=a-b;
b=a+b;
a=b-a;
}
static void swap2(int a, int b){
a=a^b;
b=a^b;
a=a^b;
}
public static void main(String[] args) {
int a = 1672;
int b = 9332;
// System.out.println("a: " + a);
// System.out.println("b: " + b);
swap1(a, b);
System.out.println("a: " + a);
System.out.println("b: " + b);
swap2(a, b);
System.out.println("a: " + a);
System.out.println("b: " + b);
}
}
| 536 | 0.496269 | 0.464552 | 30 | 16.866667 | 13.29344 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 4 |
0073c882ecac7c51eef026487da4a3ba31b7ef7c | 618,475,305,259 | 0b6e305fa5223f51b68e8d2b4ceb7f44ca8b4d70 | /extensions/auth/portability-auth-google/src/main/java/org/datatransferproject/auth/google/GoogleAuthDataGenerator.java | 6797305b9bc09845907fdf5eaa173dd8fb83e8dc | [
"Apache-2.0"
] | permissive | heliumdatacommons/data-transfer-project | https://github.com/heliumdatacommons/data-transfer-project | 8a1b35b4b3126cdbffa35cc835ab34c03a852e11 | fe4a4991289f76ca484af20d636ec4bd5ab61668 | refs/heads/master | 2020-04-04T08:28:27.758000 | 2018-11-30T03:37:01 | 2018-11-30T03:37:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2018 The Data Transfer Project Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.datatransferproject.auth.google;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.people.v1.PeopleServiceScopes;
import com.google.api.services.tasks.TasksScopes;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.BaseEncoding;
import org.datatransferproject.spi.api.auth.AuthDataGenerator;
import org.datatransferproject.spi.api.auth.AuthServiceProviderRegistry.AuthMode;
import org.datatransferproject.spi.api.types.AuthFlowConfiguration;
import org.datatransferproject.types.transfer.auth.AppCredentials;
import org.datatransferproject.types.transfer.auth.AuthData;
import org.datatransferproject.types.transfer.auth.TokensAndUrlAuthData;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static org.datatransferproject.types.common.PortabilityCommon.AuthProtocol;
import static org.datatransferproject.types.common.PortabilityCommon.AuthProtocol.OAUTH_2;
/**
* Provides configuration for conducting an OAuth flow against the Google AD API. Returned tokens
* can be used to make requests against the Google Graph API.
*
* <p>The flow is a two-step process. First, the user is sent to an authorization page and is then
* redirected to a address in this system with the authorization code. The second step takes the
* authorization code and posts it against the AD API to obtain a token for querying the Graph API.
*
* Note: this is in the process of being deprecated in favor of OAuth2DataGenerator.
* <p>TODO(#553): Remove code/token exchange as this will be handled by frontends.
*/
public class GoogleAuthDataGenerator implements AuthDataGenerator {
private static final AuthProtocol AUTH_PROTOCOL = OAUTH_2;
// The scopes necessary to import each supported data type.
// These are READ/WRITE scopes
private static final Map<String, List<String>> IMPORT_SCOPES =
ImmutableMap.<String, List<String>>builder()
.put("CALENDAR", ImmutableList.of(CalendarScopes.CALENDAR))
.put("MAIL", ImmutableList.of(GmailScopes.GMAIL_MODIFY))
.put("PHOTOS", ImmutableList.of("https://www.googleapis.com/auth/photoslibrary"))
.put("TASKS", ImmutableList.of(TasksScopes.TASKS))
.put("CONTACTS", ImmutableList.of(PeopleServiceScopes.CONTACTS))
.build();
// The scopes necessary to export each supported data type.
// These should contain READONLY permissions
private static final Map<String, List<String>> EXPORT_SCOPES =
ImmutableMap.<String, List<String>>builder()
.put("CALENDAR", ImmutableList.of(CalendarScopes.CALENDAR_READONLY))
.put("MAIL", ImmutableList.of(GmailScopes.GMAIL_READONLY))
.put("PHOTOS", ImmutableList.of("https://www.googleapis.com/auth/photoslibrary.readonly"))
.put("TASKS", ImmutableList.of(TasksScopes.TASKS_READONLY))
.put("CONTACTS", ImmutableList.of(PeopleServiceScopes.CONTACTS_READONLY))
.build();
private final List<String> scopes;
private final String clientId;
private final String clientSecret;
private final HttpTransport httpTransport;
private final ObjectMapper objectMapper;
/**
* @param appCredentials The Application credentials that the registration portal
* (console.cloud.google.com) assigned the portability instance
* @param httpTransport The http transport to use for underlying GoogleAuthorizationCodeFlow
* @param objectMapper The json factory provider
*/
public GoogleAuthDataGenerator(
AppCredentials appCredentials,
HttpTransport httpTransport,
ObjectMapper objectMapper,
String dataType,
AuthMode mode) {
this.clientId = appCredentials.getKey();
this.clientSecret = appCredentials.getSecret();
this.httpTransport = httpTransport;
this.objectMapper = objectMapper;
this.scopes = mode == AuthMode.IMPORT ? IMPORT_SCOPES.get(dataType) : EXPORT_SCOPES.get(dataType);
}
@Override
public AuthFlowConfiguration generateConfiguration(String callbackUrl, String id) {
// TODO: Move to common location
String encodedJobId = BaseEncoding.base64Url().encode(id.getBytes(Charsets.UTF_8));
String url =
createFlow()
.newAuthorizationUrl()
.setRedirectUri(callbackUrl)
.setState(encodedJobId)
.build();
return new AuthFlowConfiguration(url, AUTH_PROTOCOL, getTokenUrl());
}
@Override
public AuthData generateAuthData(
String callbackUrl, String authCode, String id, AuthData initialAuthData, String extra) {
Preconditions.checkState(
initialAuthData == null, "Earlier auth data not expected for Google flow");
AuthorizationCodeFlow flow;
TokenResponse response;
try {
flow = createFlow();
response =
flow.newTokenRequest(authCode)
.setRedirectUri(callbackUrl)
.execute();
} catch (IOException e) {
throw new RuntimeException("Error calling AuthorizationCodeFlow.execute ", e);
}
// Figure out storage
Credential credential = null;
try {
credential = flow.createAndStoreCredential(response, id);
} catch (IOException e) {
throw new RuntimeException(
"Error calling AuthorizationCodeFlow.createAndStoreCredential ", e);
}
// TODO: Extract the Google User ID from the ID token in the auth response
// GoogleIdToken.Payload payload = ((GoogleTokenResponse) response).parseIdToken().getPayload();
return new TokensAndUrlAuthData(
credential.getAccessToken(),
credential.getRefreshToken(),
credential.getTokenServerEncodedUrl());
}
/** Creates an AuthorizationCodeFlow for use in online and offline mode. */
private GoogleAuthorizationCodeFlow createFlow() {
return new GoogleAuthorizationCodeFlow.Builder(
httpTransport,
// Figure out how to adapt objectMapper.getFactory(),
new JacksonFactory(),
clientId,
clientSecret,
scopes)
.setAccessType("offline")
// TODO: Needed for local caching
// .setDataStoreFactory(GoogleStaticObjects.getDataStoreFactory())
.setApprovalPrompt("force")
.build();
}
}
| UTF-8 | Java | 7,481 | java | GoogleAuthDataGenerator.java | Java | [] | null | [] | /*
* Copyright 2018 The Data Transfer Project Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.datatransferproject.auth.google;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.people.v1.PeopleServiceScopes;
import com.google.api.services.tasks.TasksScopes;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.BaseEncoding;
import org.datatransferproject.spi.api.auth.AuthDataGenerator;
import org.datatransferproject.spi.api.auth.AuthServiceProviderRegistry.AuthMode;
import org.datatransferproject.spi.api.types.AuthFlowConfiguration;
import org.datatransferproject.types.transfer.auth.AppCredentials;
import org.datatransferproject.types.transfer.auth.AuthData;
import org.datatransferproject.types.transfer.auth.TokensAndUrlAuthData;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static org.datatransferproject.types.common.PortabilityCommon.AuthProtocol;
import static org.datatransferproject.types.common.PortabilityCommon.AuthProtocol.OAUTH_2;
/**
* Provides configuration for conducting an OAuth flow against the Google AD API. Returned tokens
* can be used to make requests against the Google Graph API.
*
* <p>The flow is a two-step process. First, the user is sent to an authorization page and is then
* redirected to a address in this system with the authorization code. The second step takes the
* authorization code and posts it against the AD API to obtain a token for querying the Graph API.
*
* Note: this is in the process of being deprecated in favor of OAuth2DataGenerator.
* <p>TODO(#553): Remove code/token exchange as this will be handled by frontends.
*/
public class GoogleAuthDataGenerator implements AuthDataGenerator {
private static final AuthProtocol AUTH_PROTOCOL = OAUTH_2;
// The scopes necessary to import each supported data type.
// These are READ/WRITE scopes
private static final Map<String, List<String>> IMPORT_SCOPES =
ImmutableMap.<String, List<String>>builder()
.put("CALENDAR", ImmutableList.of(CalendarScopes.CALENDAR))
.put("MAIL", ImmutableList.of(GmailScopes.GMAIL_MODIFY))
.put("PHOTOS", ImmutableList.of("https://www.googleapis.com/auth/photoslibrary"))
.put("TASKS", ImmutableList.of(TasksScopes.TASKS))
.put("CONTACTS", ImmutableList.of(PeopleServiceScopes.CONTACTS))
.build();
// The scopes necessary to export each supported data type.
// These should contain READONLY permissions
private static final Map<String, List<String>> EXPORT_SCOPES =
ImmutableMap.<String, List<String>>builder()
.put("CALENDAR", ImmutableList.of(CalendarScopes.CALENDAR_READONLY))
.put("MAIL", ImmutableList.of(GmailScopes.GMAIL_READONLY))
.put("PHOTOS", ImmutableList.of("https://www.googleapis.com/auth/photoslibrary.readonly"))
.put("TASKS", ImmutableList.of(TasksScopes.TASKS_READONLY))
.put("CONTACTS", ImmutableList.of(PeopleServiceScopes.CONTACTS_READONLY))
.build();
private final List<String> scopes;
private final String clientId;
private final String clientSecret;
private final HttpTransport httpTransport;
private final ObjectMapper objectMapper;
/**
* @param appCredentials The Application credentials that the registration portal
* (console.cloud.google.com) assigned the portability instance
* @param httpTransport The http transport to use for underlying GoogleAuthorizationCodeFlow
* @param objectMapper The json factory provider
*/
public GoogleAuthDataGenerator(
AppCredentials appCredentials,
HttpTransport httpTransport,
ObjectMapper objectMapper,
String dataType,
AuthMode mode) {
this.clientId = appCredentials.getKey();
this.clientSecret = appCredentials.getSecret();
this.httpTransport = httpTransport;
this.objectMapper = objectMapper;
this.scopes = mode == AuthMode.IMPORT ? IMPORT_SCOPES.get(dataType) : EXPORT_SCOPES.get(dataType);
}
@Override
public AuthFlowConfiguration generateConfiguration(String callbackUrl, String id) {
// TODO: Move to common location
String encodedJobId = BaseEncoding.base64Url().encode(id.getBytes(Charsets.UTF_8));
String url =
createFlow()
.newAuthorizationUrl()
.setRedirectUri(callbackUrl)
.setState(encodedJobId)
.build();
return new AuthFlowConfiguration(url, AUTH_PROTOCOL, getTokenUrl());
}
@Override
public AuthData generateAuthData(
String callbackUrl, String authCode, String id, AuthData initialAuthData, String extra) {
Preconditions.checkState(
initialAuthData == null, "Earlier auth data not expected for Google flow");
AuthorizationCodeFlow flow;
TokenResponse response;
try {
flow = createFlow();
response =
flow.newTokenRequest(authCode)
.setRedirectUri(callbackUrl)
.execute();
} catch (IOException e) {
throw new RuntimeException("Error calling AuthorizationCodeFlow.execute ", e);
}
// Figure out storage
Credential credential = null;
try {
credential = flow.createAndStoreCredential(response, id);
} catch (IOException e) {
throw new RuntimeException(
"Error calling AuthorizationCodeFlow.createAndStoreCredential ", e);
}
// TODO: Extract the Google User ID from the ID token in the auth response
// GoogleIdToken.Payload payload = ((GoogleTokenResponse) response).parseIdToken().getPayload();
return new TokensAndUrlAuthData(
credential.getAccessToken(),
credential.getRefreshToken(),
credential.getTokenServerEncodedUrl());
}
/** Creates an AuthorizationCodeFlow for use in online and offline mode. */
private GoogleAuthorizationCodeFlow createFlow() {
return new GoogleAuthorizationCodeFlow.Builder(
httpTransport,
// Figure out how to adapt objectMapper.getFactory(),
new JacksonFactory(),
clientId,
clientSecret,
scopes)
.setAccessType("offline")
// TODO: Needed for local caching
// .setDataStoreFactory(GoogleStaticObjects.getDataStoreFactory())
.setApprovalPrompt("force")
.build();
}
}
| 7,481 | 0.736265 | 0.733191 | 168 | 43.529762 | 28.422394 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 4 |
392eda68b729f99c51c71080d7a1baf69a5c0104 | 14,113,262,534,731 | 8528a3c5016f5fab8d105a24fac82d918d5f2455 | /sonar-flex-plugin/src/main/java/org/sonar/plugins/flex/FlexProfile.java | b9fd2fb0aa3d2ad5ae068f848e3676cc6641fd62 | [] | no_license | pombredanne/sonar-flex | https://github.com/pombredanne/sonar-flex | 833f873d6335e89c3aa6d9f800df02b90b708eea | b1b1e9efdb682aef7c89c54a1214f6075ab310ad | refs/heads/master | 2021-01-18T12:04:08.824000 | 2013-10-26T00:25:31 | 2013-10-26T00:25:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Sonar Flex Plugin
* Copyright (C) 2010 SonarSource
* dev@sonar.codehaus.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.flex;
import org.sonar.api.profiles.AnnotationProfileParser;
import org.sonar.api.profiles.ProfileDefinition;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.profiles.XMLProfileParser;
import org.sonar.api.rules.ActiveRule;
import org.sonar.api.utils.ValidationMessages;
import org.sonar.flex.checks.CheckList;
import org.sonar.plugins.flex.core.Flex;
public class FlexProfile extends ProfileDefinition {
private final AnnotationProfileParser annotationProfileParser;
private final XMLProfileParser xmlProfileParser;
public FlexProfile(AnnotationProfileParser annotationProfileParser, XMLProfileParser xmlProfileParser) {
this.annotationProfileParser = annotationProfileParser;
this.xmlProfileParser = xmlProfileParser;
}
@Override
public RulesProfile createProfile(ValidationMessages validation) {
RulesProfile rulesProfile = annotationProfileParser.parse(CheckList.REPOSITORY_KEY, CheckList.SONAR_WAY_PROFILE, Flex.KEY, CheckList.getChecks(), validation);
RulesProfile pmdRules = xmlProfileParser.parseResource(getClass().getClassLoader(), "org/sonar/plugins/flex/profile-sonar-way.xml", validation);
for (ActiveRule activeRule : pmdRules.getActiveRules()) {
rulesProfile.addActiveRule(activeRule);
}
return rulesProfile;
}
}
| UTF-8 | Java | 2,142 | java | FlexProfile.java | Java | [
{
"context": "/*\n * Sonar Flex Plugin\n * Copyright (C) 2010 SonarSource\n * dev@sonar.codehaus.org\n *\n * This program is f",
"end": 57,
"score": 0.9993109107017517,
"start": 46,
"tag": "USERNAME",
"value": "SonarSource"
},
{
"context": "r Flex Plugin\n * Copyright (C) 2010 SonarS... | null | [] | /*
* Sonar Flex Plugin
* Copyright (C) 2010 SonarSource
* <EMAIL>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.flex;
import org.sonar.api.profiles.AnnotationProfileParser;
import org.sonar.api.profiles.ProfileDefinition;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.profiles.XMLProfileParser;
import org.sonar.api.rules.ActiveRule;
import org.sonar.api.utils.ValidationMessages;
import org.sonar.flex.checks.CheckList;
import org.sonar.plugins.flex.core.Flex;
public class FlexProfile extends ProfileDefinition {
private final AnnotationProfileParser annotationProfileParser;
private final XMLProfileParser xmlProfileParser;
public FlexProfile(AnnotationProfileParser annotationProfileParser, XMLProfileParser xmlProfileParser) {
this.annotationProfileParser = annotationProfileParser;
this.xmlProfileParser = xmlProfileParser;
}
@Override
public RulesProfile createProfile(ValidationMessages validation) {
RulesProfile rulesProfile = annotationProfileParser.parse(CheckList.REPOSITORY_KEY, CheckList.SONAR_WAY_PROFILE, Flex.KEY, CheckList.getChecks(), validation);
RulesProfile pmdRules = xmlProfileParser.parseResource(getClass().getClassLoader(), "org/sonar/plugins/flex/profile-sonar-way.xml", validation);
for (ActiveRule activeRule : pmdRules.getActiveRules()) {
rulesProfile.addActiveRule(activeRule);
}
return rulesProfile;
}
}
| 2,127 | 0.787582 | 0.78338 | 51 | 41 | 35.596321 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705882 | false | false | 4 |
15e110c07c2d9d4d1cfa0472da478e038e6c4f8b | 13,271,448,957,830 | b79a46f2866194dcebd94472466c93962fdfd079 | /backend/src/main/java/ua/project/protester/repository/project/ProjectRepositoryImpl.java | 1b31c49035f8d8e8bbe2ead4afc5a428e256b7ec | [] | no_license | JuliaBorovets/ProTester | https://github.com/JuliaBorovets/ProTester | ac3236bf5227ae1e58a62ec397ff2a7d13e18e6f | 534e4d33ac51248ba21338fc21db6df4fe51a75d | refs/heads/master | 2023-02-05T04:24:10.152000 | 2020-12-28T20:11:11 | 2020-12-28T20:11:11 | 329,915,831 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.project.protester.repository.project;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import ua.project.protester.exception.ProjectCreateException;
import ua.project.protester.model.Project;
import ua.project.protester.model.ProjectDto;
import ua.project.protester.utils.Pagination;
import ua.project.protester.utils.PropertyExtractor;
import ua.project.protester.utils.project.ProjectDtoRowMapper;
import ua.project.protester.utils.project.ProjectRowMapper;
import java.util.List;
import java.util.Optional;
@Slf4j
@Repository
@RequiredArgsConstructor
@PropertySource("classpath:queries/project.properties")
public class ProjectRepositoryImpl implements ProjectRepository {
private final NamedParameterJdbcTemplate namedJdbcTemplate;
private final ProjectRowMapper projectRowMapper;
private final Environment env;
@Override
public Project create(Project project) throws ProjectCreateException {
log.info("IN ProjectRepositoryImpl create - project: {}", project);
KeyHolder keyHolder = new GeneratedKeyHolder();
namedJdbcTemplate.update(
PropertyExtractor.extract(env, "createProject"),
new MapSqlParameterSource()
.addValue("project_name", project.getProjectName())
.addValue("project_website_link", project.getProjectWebsiteLink())
.addValue("project_active", project.getProjectActive())
.addValue("creator_id", project.getCreatorId()),
keyHolder);
Integer id = (Integer) (Optional.ofNullable(keyHolder.getKeys())
.orElseThrow(ProjectCreateException::new)
.get("project_id"));
project.setProjectId(id.longValue());
log.info("saved project {}", project);
return project;
}
@Override
public Project update(Project project) {
log.info("IN ProjectRepositoryImpl update - project: {}", project);
namedJdbcTemplate.update(
PropertyExtractor.extract(env, "updateProject"),
new MapSqlParameterSource()
.addValue("project_id", project.getProjectId())
.addValue("project_name", project.getProjectName())
.addValue("project_website_link", project.getProjectWebsiteLink())
.addValue("project_active", project.getProjectActive())
);
log.info("updated project {}", project);
return project;
}
@Override
public Project changeStatus(Project project, Boolean isActive) {
log.info("IN ProjectRepositoryImpl changeProjectStatus - project: {}, isActive: {}", project, isActive);
namedJdbcTemplate.update(
PropertyExtractor.extract(env, "updateProjectStatus"),
new MapSqlParameterSource()
.addValue("project_id", project.getProjectId())
.addValue("project_active", isActive)
);
project.setProjectActive(isActive);
log.info("changed ProjectStatus - projectId: {}, isActive: {}", project, isActive);
return project;
}
@Override
public List<ProjectDto> findAll(Pagination pagination) {
log.info("IN ProjectRepositoryImpl findAll - pagination: {}", pagination);
return namedJdbcTemplate.query(
PropertyExtractor.extract(env, "getAllProjects"),
new MapSqlParameterSource()
.addValue("pageSize", pagination.getPageSize())
.addValue("offset", pagination.getOffset())
.addValue("filterProjectName", pagination.getSearchField() + "%"),
new ProjectDtoRowMapper());
}
@Override
public List<ProjectDto> findAllByStatus(Pagination pagination, Boolean isActive) {
log.info("IN ProjectRepositoryImpl findAllByStatus - pagination: {}, isActive: {}", pagination, isActive);
return namedJdbcTemplate.query(
PropertyExtractor.extract(env, "getAllProjectsFiltered"),
new MapSqlParameterSource()
.addValue("pageSize", pagination.getPageSize())
.addValue("offset", pagination.getOffset())
.addValue("filterProjectName", pagination.getSearchField() + "%")
.addValue("projectActive", isActive),
new ProjectDtoRowMapper());
}
@Override
public Optional<Project> findById(Long id) {
log.info("IN ProjectRepositoryImpl findById - id: {}", id);
try {
return Optional.ofNullable(
namedJdbcTemplate.queryForObject(
PropertyExtractor.extract(env, "findById"),
new MapSqlParameterSource()
.addValue("project_id", id),
projectRowMapper)
);
} catch (EmptyResultDataAccessException e) {
log.error("IN ProjectRepositoryImpl findById - id: {} not found", id);
return Optional.empty();
}
}
@Override
public Long getCountProjects(Pagination pagination) {
log.info("IN ProjectRepositoryImpl getCountProjects - pagination: {}", pagination);
return namedJdbcTemplate.queryForObject(
PropertyExtractor.extract(env, "findCountOdRecords"),
new MapSqlParameterSource()
.addValue("filterProjectName", pagination.getSearchField() + "%"),
Long.class);
}
@Override
public Long getCountProjectsByStatus(Pagination pagination, Boolean isActive) {
log.info("IN ProjectRepositoryImpl getCountProjectsByStatus - pagination: {}, isActive: {}", pagination, isActive);
return namedJdbcTemplate.queryForObject(
PropertyExtractor.extract(env, "findCountOdRecordsWithStatus"),
new MapSqlParameterSource()
.addValue("filterProjectName", pagination.getSearchField() + "%")
.addValue("projectActive", isActive),
Long.class);
}
}
| UTF-8 | Java | 6,749 | java | ProjectRepositoryImpl.java | Java | [] | null | [] | package ua.project.protester.repository.project;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import ua.project.protester.exception.ProjectCreateException;
import ua.project.protester.model.Project;
import ua.project.protester.model.ProjectDto;
import ua.project.protester.utils.Pagination;
import ua.project.protester.utils.PropertyExtractor;
import ua.project.protester.utils.project.ProjectDtoRowMapper;
import ua.project.protester.utils.project.ProjectRowMapper;
import java.util.List;
import java.util.Optional;
@Slf4j
@Repository
@RequiredArgsConstructor
@PropertySource("classpath:queries/project.properties")
public class ProjectRepositoryImpl implements ProjectRepository {
private final NamedParameterJdbcTemplate namedJdbcTemplate;
private final ProjectRowMapper projectRowMapper;
private final Environment env;
@Override
public Project create(Project project) throws ProjectCreateException {
log.info("IN ProjectRepositoryImpl create - project: {}", project);
KeyHolder keyHolder = new GeneratedKeyHolder();
namedJdbcTemplate.update(
PropertyExtractor.extract(env, "createProject"),
new MapSqlParameterSource()
.addValue("project_name", project.getProjectName())
.addValue("project_website_link", project.getProjectWebsiteLink())
.addValue("project_active", project.getProjectActive())
.addValue("creator_id", project.getCreatorId()),
keyHolder);
Integer id = (Integer) (Optional.ofNullable(keyHolder.getKeys())
.orElseThrow(ProjectCreateException::new)
.get("project_id"));
project.setProjectId(id.longValue());
log.info("saved project {}", project);
return project;
}
@Override
public Project update(Project project) {
log.info("IN ProjectRepositoryImpl update - project: {}", project);
namedJdbcTemplate.update(
PropertyExtractor.extract(env, "updateProject"),
new MapSqlParameterSource()
.addValue("project_id", project.getProjectId())
.addValue("project_name", project.getProjectName())
.addValue("project_website_link", project.getProjectWebsiteLink())
.addValue("project_active", project.getProjectActive())
);
log.info("updated project {}", project);
return project;
}
@Override
public Project changeStatus(Project project, Boolean isActive) {
log.info("IN ProjectRepositoryImpl changeProjectStatus - project: {}, isActive: {}", project, isActive);
namedJdbcTemplate.update(
PropertyExtractor.extract(env, "updateProjectStatus"),
new MapSqlParameterSource()
.addValue("project_id", project.getProjectId())
.addValue("project_active", isActive)
);
project.setProjectActive(isActive);
log.info("changed ProjectStatus - projectId: {}, isActive: {}", project, isActive);
return project;
}
@Override
public List<ProjectDto> findAll(Pagination pagination) {
log.info("IN ProjectRepositoryImpl findAll - pagination: {}", pagination);
return namedJdbcTemplate.query(
PropertyExtractor.extract(env, "getAllProjects"),
new MapSqlParameterSource()
.addValue("pageSize", pagination.getPageSize())
.addValue("offset", pagination.getOffset())
.addValue("filterProjectName", pagination.getSearchField() + "%"),
new ProjectDtoRowMapper());
}
@Override
public List<ProjectDto> findAllByStatus(Pagination pagination, Boolean isActive) {
log.info("IN ProjectRepositoryImpl findAllByStatus - pagination: {}, isActive: {}", pagination, isActive);
return namedJdbcTemplate.query(
PropertyExtractor.extract(env, "getAllProjectsFiltered"),
new MapSqlParameterSource()
.addValue("pageSize", pagination.getPageSize())
.addValue("offset", pagination.getOffset())
.addValue("filterProjectName", pagination.getSearchField() + "%")
.addValue("projectActive", isActive),
new ProjectDtoRowMapper());
}
@Override
public Optional<Project> findById(Long id) {
log.info("IN ProjectRepositoryImpl findById - id: {}", id);
try {
return Optional.ofNullable(
namedJdbcTemplate.queryForObject(
PropertyExtractor.extract(env, "findById"),
new MapSqlParameterSource()
.addValue("project_id", id),
projectRowMapper)
);
} catch (EmptyResultDataAccessException e) {
log.error("IN ProjectRepositoryImpl findById - id: {} not found", id);
return Optional.empty();
}
}
@Override
public Long getCountProjects(Pagination pagination) {
log.info("IN ProjectRepositoryImpl getCountProjects - pagination: {}", pagination);
return namedJdbcTemplate.queryForObject(
PropertyExtractor.extract(env, "findCountOdRecords"),
new MapSqlParameterSource()
.addValue("filterProjectName", pagination.getSearchField() + "%"),
Long.class);
}
@Override
public Long getCountProjectsByStatus(Pagination pagination, Boolean isActive) {
log.info("IN ProjectRepositoryImpl getCountProjectsByStatus - pagination: {}, isActive: {}", pagination, isActive);
return namedJdbcTemplate.queryForObject(
PropertyExtractor.extract(env, "findCountOdRecordsWithStatus"),
new MapSqlParameterSource()
.addValue("filterProjectName", pagination.getSearchField() + "%")
.addValue("projectActive", isActive),
Long.class);
}
}
| 6,749 | 0.640836 | 0.640391 | 167 | 39.413174 | 31.043768 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.700599 | false | false | 4 |
aff1e31c66305f5a577c9771cb574656af5a8c31 | 2,628,520,050,333 | aee2c999cdf2b5b4df9d5135963e6d98bc81c1fd | /app/src/main/java/teamprogra/app/fragment/DatePickerFragment.java | 2e55a49948969f1ddb86078b2345e2118e9b1733 | [] | no_license | AdrianLeyva/Socialize | https://github.com/AdrianLeyva/Socialize | be8c7c8fe0f4360232224b63f4fa7a93530d21e3 | 8b6199468481a922f0abe15c3b6babe0cbfe984f | refs/heads/master | 2020-12-25T10:24:56.336000 | 2016-07-14T05:41:31 | 2016-07-14T05:41:31 | 61,779,947 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package teamprogra.app.fragment;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;
import teamprogra.app.socialize.socialize.R;
/**
* Created by adrianleyva on 30/06/16.
*/
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
private String date;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Utilice la fecha actual como la fecha predeterminada en el selector
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Crear una nueva instancia de DatePickerDialog y devolverlo
DatePickerDialog dpd = new DatePickerDialog(getActivity(), android.app.AlertDialog.THEME_DEVICE_DEFAULT_DARK,this, year, month, day);
DatePicker dp = dpd.getDatePicker();
dp.setMaxDate(c.getTimeInMillis());
return dpd;
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
date = monthOfYear+1 + "/" + dayOfMonth + "/" + year;
EditText editTextBirthDay = (EditText)getActivity().findViewById(R.id.editText_birthdayDU);
editTextBirthDay.setText(date);
}
}
| UTF-8 | Java | 1,502 | java | DatePickerFragment.java | Java | [
{
"context": "ogra.app.socialize.socialize.R;\n\n/**\n * Created by adrianleyva on 30/06/16.\n */\npublic class DatePickerFragment ",
"end": 372,
"score": 0.9995047450065613,
"start": 361,
"tag": "USERNAME",
"value": "adrianleyva"
}
] | null | [] | package teamprogra.app.fragment;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;
import teamprogra.app.socialize.socialize.R;
/**
* Created by adrianleyva on 30/06/16.
*/
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
private String date;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Utilice la fecha actual como la fecha predeterminada en el selector
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Crear una nueva instancia de DatePickerDialog y devolverlo
DatePickerDialog dpd = new DatePickerDialog(getActivity(), android.app.AlertDialog.THEME_DEVICE_DEFAULT_DARK,this, year, month, day);
DatePicker dp = dpd.getDatePicker();
dp.setMaxDate(c.getTimeInMillis());
return dpd;
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
date = monthOfYear+1 + "/" + dayOfMonth + "/" + year;
EditText editTextBirthDay = (EditText)getActivity().findViewById(R.id.editText_birthdayDU);
editTextBirthDay.setText(date);
}
}
| 1,502 | 0.718376 | 0.713049 | 46 | 31.652174 | 32.068687 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.652174 | false | false | 4 |
907cb97bba2d6adc624cf3fe0dae56c0a13dde98 | 31,121,333,032,154 | cfa07a3fd33684ea618af110537b4df9e2e797ac | /src/main/java/com/sfy/dao/vo/NotFound.java | e40ca16194417fdfbad304a58dba573c04da2680 | [] | no_license | yflower/sourceDesign | https://github.com/yflower/sourceDesign | 4a0ad8eb57e74372f5d373d106f93507b000f835 | 6f2fa84ff4f9e514f06a6ab49f86a45e680ab591 | refs/heads/master | 2018-03-16T14:46:04.244000 | 2017-01-07T14:45:37 | 2017-01-07T14:45:37 | 66,798,485 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sfy.dao.vo;
/**
* Created by jal on 2016/8/30.
*/
public class NotFound {
private String status;
private String messager;
@Override
public String toString() {
return "NotFound{" +
"status='" + status + '\'' +
", messager='" + messager + '\'' +
'}';
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessager() {
return messager;
}
public void setMessager(String messager) {
this.messager = messager;
}
}
| UTF-8 | Java | 641 | java | NotFound.java | Java | [
{
"context": "package com.sfy.dao.vo;\n\n/**\n * Created by jal on 2016/8/30.\n */\npublic class NotFound {\n pri",
"end": 46,
"score": 0.9996049404144287,
"start": 43,
"tag": "USERNAME",
"value": "jal"
}
] | null | [] | package com.sfy.dao.vo;
/**
* Created by jal on 2016/8/30.
*/
public class NotFound {
private String status;
private String messager;
@Override
public String toString() {
return "NotFound{" +
"status='" + status + '\'' +
", messager='" + messager + '\'' +
'}';
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessager() {
return messager;
}
public void setMessager(String messager) {
this.messager = messager;
}
}
| 641 | 0.530421 | 0.519501 | 33 | 18.424242 | 15.599204 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 4 |
94481290aca96e2ab2e86667b5f11114b64658f7 | 35,072,702,943,787 | 8559f17bd47710a8a7e00ca4c634f636f1bf598a | /mysql-world/mysql-world-h2-hibernate-generate/src/main/java/br/com/jkavdev/mysql_hibernate/modelos/converters/ContinentEnumType.java | 371daae83b4a9a2369f9af31fa3995bcacf6730b | [] | no_license | jkavdev/mysql_database_hibernate | https://github.com/jkavdev/mysql_database_hibernate | e1480408f027be95d14566253338a52e98a7ab08 | f0e29e4605186fbb3817577e29aee9a3198ee265 | refs/heads/master | 2022-07-14T22:12:57.718000 | 2019-08-01T03:15:15 | 2019-08-01T03:15:15 | 198,530,047 | 0 | 1 | null | false | 2022-06-21T01:33:41 | 2019-07-24T00:48:42 | 2019-08-01T03:15:26 | 2022-06-21T01:33:40 | 536 | 0 | 0 | 6 | TSQL | false | false | package br.com.jkavdev.mysql_hibernate.modelos.converters;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.EnumType;
import br.com.jkavdev.mysql_hibernate.modelos.h2.Continent;
public class ContinentEnumType extends EnumType<Continent> {
private static final long serialVersionUID = 1L;
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.OTHER);
} else {
st.setObject(index, ((Continent) value).getName(), Types.CHAR);
}
}
}
| UTF-8 | Java | 784 | java | ContinentEnumType.java | Java | [] | null | [] | package br.com.jkavdev.mysql_hibernate.modelos.converters;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.EnumType;
import br.com.jkavdev.mysql_hibernate.modelos.h2.Continent;
public class ContinentEnumType extends EnumType<Continent> {
private static final long serialVersionUID = 1L;
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.OTHER);
} else {
st.setObject(index, ((Continent) value).getName(), Types.CHAR);
}
}
}
| 784 | 0.78699 | 0.784439 | 28 | 27 | 28.585711 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.321429 | false | false | 4 |
3c5500db7f59780580456e2139d753b858ec2636 | 35,115,652,614,776 | f2c3ad87d22ad2fb0c646fd81dff40e445db96e5 | /03_centralized/src/solution/CentralizedSolution.java | 4a58624f1280a00ef095f1c02cd94b61be0bc284 | [] | no_license | schreven/PDP-agents | https://github.com/schreven/PDP-agents | aa202f45e1974ae086e0b6a1075a9e665ca1c189 | b7308712419217bf2a40b99269ad47889f55cb7c | refs/heads/master | 2020-03-30T20:03:42.980000 | 2019-12-02T14:18:11 | 2019-12-02T14:18:11 | 151,571,475 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package solution;
import java.io.File;
//the list of imports
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
import java.util.HashSet;
import logist.LogistSettings;
import logist.Measures;
import logist.behavior.AuctionBehavior;
import logist.behavior.CentralizedBehavior;
import logist.agent.Agent;
import logist.config.Parsers;
import logist.simulation.Vehicle;
import logist.plan.Plan;
import logist.task.Task;
import logist.task.TaskDistribution;
import logist.task.TaskSet;
import logist.topology.Topology;
import logist.topology.Topology.City;
@SuppressWarnings("unused")
public class CentralizedSolution implements CentralizedBehavior {
private Topology topology;
private TaskDistribution distribution;
private Agent agent;
private long timeout_setup;
private long timeout_plan;
// max iteration allowed to find local optimal.
private final int maxIterations = 10000;
//vehicles and actions for the planning
private List<Vehicle> vehicles;
private Set<CentralizedAction> actions;
/* CSP Variables */
// nextTask is divided in two arrays because we have two key types (Task and Vehicle)
private Map<CentralizedAction, CentralizedAction> nextActionA;
private Map<Vehicle, CentralizedAction> nextActionV;
private Map<CentralizedAction, Integer> time;
private Map<CentralizedAction, Vehicle> vehicle;
private CentralizedPlan currentPlan;
private Map<Vehicle, Integer> availableCapacity;
//Map a pickup action with its delivery action
private Map<CentralizedAction,CentralizedAction> correspondingDelivery;
//test
@Override
public void setup(Topology topology, TaskDistribution distribution,
Agent agent) {
// this code is used to get the timeouts
LogistSettings ls = null;
try {
ls = Parsers.parseSettings("config" + File.separator + "settings_default.xml");
}
catch (Exception exc) {
System.out.println("There was a problem loading the configuration file.");
}
// the setup method cannot last more than timeout_setup milliseconds
timeout_setup = ls.get(LogistSettings.TimeoutKey.SETUP);
// the plan method cannot execute more than timeout_plan milliseconds
timeout_plan = ls.get(LogistSettings.TimeoutKey.PLAN);
this.topology = topology;
this.distribution = distribution;
this.agent = agent;
this.nextActionA = new HashMap<CentralizedAction, CentralizedAction>();
this.nextActionV = new HashMap<Vehicle, CentralizedAction>();
this.time = new HashMap<CentralizedAction, Integer>();
this.vehicle = new HashMap<CentralizedAction, Vehicle>();
//this.currentPlan; = new CentralizedPlan(this.nextActionA, this.nextActionV,
// this.time, this.vehicle, this.vehicles);
this.correspondingDelivery = new HashMap<CentralizedAction,CentralizedAction>();
}
// List of the plan for each vehicle
@Override
public List<Plan> plan(List<Vehicle> vehicles, TaskSet tasks) {
long time_start = System.currentTimeMillis(); // save current time to measure computation duration
//instantiate
this.vehicles = vehicles;
this.actions = toActionSet(tasks);
/* Use Constraint Satisfaction Problem Optimization to find list of plans*/
List<Plan> plans = new ArrayList<Plan>();
// Initialize variables with non optimized plan.
// Fails if a task has a weight bigger than any vehicle capacity.
try {
SelectInitialSolution();
} catch (Exception e) {
System.out.println(e.getMessage());
}
List<CentralizedPlan> neighbourPlans;
CentralizedPlan bestNewPlan = new CentralizedPlan(new HashMap<CentralizedAction, CentralizedAction>(),
new HashMap<Vehicle, CentralizedAction>(),
new HashMap<CentralizedAction, Integer>(),
new HashMap<CentralizedAction, Vehicle>(),
new ArrayList<Vehicle>());
// loop until criterion reached
for (int i = 0; i < maxIterations; i++) {
/* Find neighbours */
neighbourPlans = ChooseNeighbours(i);
//System.out.println("Found " + neighbourPlans.size()+ " valid neighbours");
/* Select the most promissing one */
bestNewPlan = LocalChoice(neighbourPlans, i);
//System.out.println("The cost of the the new plan is: " + bestNewPlan.getCost());
System.out.println(bestNewPlan.getCost());
//experimenting
//this.currentPlan = bestNewPlan;
setCurrentPlan(bestNewPlan);
}
/* end */
// compute plan computation duration
long time_end = System.currentTimeMillis();
long duration = time_end - time_start;
//System.out.println("The plan was generated in "+duration+" milliseconds.");
plans = this.currentPlan.getPlan();
return plans;
}
private void SelectInitialSolution() throws Exception {
/* Give all the tasks to the biggest vehicle. Only updates global variables*/
/* The vehicle only carries one task at a time with this plan*/
Integer order = 1; // order in which the task are handled by a vehicle
CentralizedAction prevAction = null; // previous action carried by a vehicle
// find biggest vehicle, i.e. vehicle with largest capacity
Vehicle bigVehicle = vehicles.get(0);
for (Vehicle vehicle : vehicles) {
if (vehicle.capacity() > bigVehicle.capacity()) {
bigVehicle = vehicle;
}
//also fill nextActionV
nextActionV.put(vehicle, null);
}
// iterate over task set
for (CentralizedAction action : actions) {
//select only pickups in the loop
if (!action.isPickup()) continue;
// if the biggest vehicle cannot carry a task, the problem is unsolvable.
if (action.getTask().weight > bigVehicle.capacity()) {
throw new Exception("The task (id: "+action.getTask().id+") has a weight too big ! Problem unsolvable.");
}
// fill arrays for pickup
if (prevAction != null) this.nextActionA.put(prevAction, action);
if (order == 1) this.nextActionV.put(bigVehicle, action);
this.time.put(action, order);
this.vehicle.put(action, bigVehicle);
order++;
// fill arrays for delivery
this.nextActionA.put(action, correspondingDelivery.get(action));
this.nextActionA.put(correspondingDelivery.get(action), null);
this.time.put(correspondingDelivery.get(action), order);
this.vehicle.put(correspondingDelivery.get(action), bigVehicle);
order++;
prevAction = correspondingDelivery.get(action);
}
//set the current plan
this.currentPlan = new CentralizedPlan(this.nextActionA,this.nextActionV,
this.time, this.vehicle, this.vehicles);
if (!verifyConstraints()) {
// verify if solution meet constraints
throw new Exception("Problem solved, but did not meet the constraints"); // shouldn't go here
}
}
private List<CentralizedPlan> ChooseNeighbours(Integer iter) {
resetCSPVariables();
/* Find neighbours to the current solution */
List<CentralizedPlan> neighbourPlans = new ArrayList<CentralizedPlan>();
//select one random vehicle "transmitting" his tasks and "shuffling" them
Vehicle chosenVehicle;
do {
Random randomizer = new Random();
chosenVehicle = vehicles.get(randomizer.nextInt(vehicles.size()));
} while(this.nextActionV.get(chosenVehicle)==null);
//not problem here, is not null.
if (this.nextActionV.get(chosenVehicle)==null) {
System.out.println("is chosen vehicle null?");
}
/*creating new plans with a task transmitted to another vehicle*/
for (Vehicle vehicleTemp : vehicles) {
if (vehicleTemp == chosenVehicle) continue;
CentralizedPlan newPlan = changingVehicle(chosenVehicle,vehicleTemp);
if (newPlan != null) {
neighbourPlans.add(newPlan);
}
}
/*creating new plans with the tasks for the vehicle shuffled*/
CentralizedAction actionTemp = nextActionV.get(chosenVehicle);
Integer lengthChosenVehicle = 0;
//compute number of actions for the vehicle
while(actionTemp != null) {
lengthChosenVehicle +=1;
actionTemp = nextActionA.get(actionTemp);
}
//if the vehicle has at least two tasks
if (lengthChosenVehicle>=2) {
for (int i = 0; i<=lengthChosenVehicle-1; i++) {
for (int j = i+1; j< lengthChosenVehicle; j++) {
CentralizedPlan newPlan = changingActionOrder(chosenVehicle,i,j);
if (newPlan != null) {
neighbourPlans.add(newPlan);
}
}
}
}
return neighbourPlans;
}
/* create new plans by changing a task from a vehicle to another */
private CentralizedPlan changingVehicle(Vehicle vehicleGive, Vehicle vehicleReceive) {
CentralizedPlan newPlan;
resetCSPVariables();
// PROBLEM HERE transmitted pickup is null
CentralizedAction transmittedPickup = this.nextActionV.get(vehicleGive);
CentralizedAction transmittedDelivery = this.correspondingDelivery.get(transmittedPickup);
if (this.nextActionV.get(vehicleGive) == null) {
System.out.println("is null entering changingVehicle");
}
if (transmittedPickup == null) {
System.out.println("test");
}
//erasing from vehicleGive chain for the pickup action
nextActionV.put(vehicleGive, nextActionA.get(transmittedPickup));
//erasing from vehicleGive chain for the delivery action
if (nextActionV.get(vehicleGive)==transmittedDelivery) {
nextActionV.put(vehicleGive, nextActionA.get(transmittedDelivery));}
else {
CentralizedAction actionTemp = nextActionV.get(vehicleGive);
while (nextActionA.get(actionTemp) != null) {
if (nextActionA.get(actionTemp) == transmittedDelivery) {
nextActionA.put(actionTemp,nextActionA.get(transmittedDelivery));
break;
}
actionTemp = nextActionA.get(actionTemp);
}
}
//update vehicleReceive chain
nextActionA.put(transmittedPickup, transmittedDelivery);
nextActionA.put(transmittedDelivery, nextActionV.get(vehicleReceive));
nextActionV.put(vehicleReceive, transmittedPickup);
updateTime(vehicleGive);
updateTime(vehicleReceive);
vehicle.put(transmittedPickup, vehicleReceive);
vehicle.put(transmittedDelivery, vehicleReceive);
if (verifyConstraints()) {
// verify if solution meet constraints
newPlan = new CentralizedPlan(nextActionA, nextActionV, time, vehicle, this.vehicles);
}
else newPlan = null;
return newPlan;
}
private CentralizedPlan changingActionOrder(Vehicle vehicle, Integer id1, Integer id2) {
CentralizedPlan newPlan;
resetCSPVariables();
Integer count;
CentralizedAction a1;
CentralizedAction aPre2;
CentralizedAction a2;
if (id1==1) {
count = 1;
Vehicle aPre1 = vehicle; //previous "action" of action 1
a1 = nextActionV.get(vehicle); //action 1
aPre2 = a1; //previous action of action 2
a2 = nextActionA.get(aPre2);
count +=1;
while(count<id2) {
aPre2 = a2;
a2 = nextActionA.get(a2);
count +=1;
}
CentralizedAction aPost2 = nextActionA.get(a2); //post action of action 2
nextActionV.put(aPre1, a2);
}
else {
CentralizedAction aPre1 = nextActionV.get(vehicle); //previous action of action 1
a1 = nextActionA.get(aPre1); //action 1
count = 2;
while (count<id1) {
aPre1 =a1;
a1 = nextActionA.get(a1);
count +=1;
}
aPre2 = a1; //previous action of action 2
a2 = nextActionA.get(aPre2);
count +=1;
while(count<id2) {
aPre2 = a2;
a2 = nextActionA.get(a2);
count +=1;
}
nextActionA.put(aPre1, a2);
}
CentralizedAction aPost1 = nextActionA.get(a1); //post action of action 1
CentralizedAction aPost2 = nextActionA.get(a2); //post action of action 2
//exchanging the tasks
if (aPost1==a2) {
nextActionA.put(a2,a1);
nextActionA.put(a1, aPost2);
}
else {
nextActionA.put(aPre2,a1);
nextActionA.put(a2,aPost1);
nextActionA.put(a1, aPost2);
}
updateTime(vehicle);
if (verifyConstraints()) {
// verify if solution meet constraints
newPlan = new CentralizedPlan(nextActionA, nextActionV, time, this.vehicle, this.vehicles);
}
else newPlan = null;
return newPlan;
}
private void updateTime(Vehicle vehicle) {
CentralizedAction actionTemp = nextActionV.get(vehicle);
Integer timeTemp = 1;
while(actionTemp != null) {
//update time
time.put(actionTemp, timeTemp);
//iterate action and time
actionTemp = nextActionA.get(actionTemp);
timeTemp +=1;
}
}
private CentralizedPlan LocalChoice(List<CentralizedPlan> neighbourPlans, Integer iter) {
CentralizedPlan bestPlan = neighbourPlans.get(0);
Random random = new Random();
Double probAddCurrent = 1.;
Double probPickSecond = 0.;
Double probPickRandom = 0.5*(maxIterations-iter)/maxIterations;
Double probIgnore = 0.2;
if (random.nextFloat() < probAddCurrent) {
neighbourPlans.add(this.currentPlan);
}
if (random.nextFloat() < probPickRandom) {
return neighbourPlans.get(random.nextInt(neighbourPlans.size()));
}
for (CentralizedPlan plan : neighbourPlans) {
if (random.nextFloat() > probIgnore) {
continue;
}
//find the best plan
if (plan.getCost() < bestPlan.getCost()) {
bestPlan = plan;
}
else if (plan.getCost() == bestPlan.getCost()) {
// if equal cost, choose randomly
if (random.nextInt()%2 == 0) bestPlan = plan;
}
}
if (random.nextFloat() < probPickSecond) {
CentralizedPlan secondBestPlan = neighbourPlans.get(0);
//find the second next best plan
for (CentralizedPlan plan : neighbourPlans) {
if (plan == bestPlan) continue;
if (plan.getCost() < secondBestPlan.getCost()) {
secondBestPlan = plan;
}
}
bestPlan = secondBestPlan;
}
return bestPlan;
}
private boolean verifyConstraints(){
/* Based on the CSP Variables, verify if all the constraints are met */
Integer capacityTemp;
CentralizedAction action;
for (CentralizedAction actionTemp : nextActionA.keySet()) {
// Constraint 1
if (actionTemp == nextActionA.get(actionTemp)) {
System.out.println("Error: Constraint 1 reached, should not happen");
return false;
}
else if (nextActionA.get(actionTemp)!=null) {
// Constraint 3
if (time.get(nextActionA.get(actionTemp)) != (time.get(actionTemp) +1 )) {
System.out.println("Error: Constraint 3 reached, should not happen");
return false;}
//Constraint 5
if (vehicle.get(nextActionA.get(actionTemp))!= vehicle.get(actionTemp)) {
System.out.println("Error: Constraint 5 reached, should not happen");
return false;}
}
//Constraint 8
if(actionTemp.isPickup()) {
if (time.get(actionTemp) > time.get(correspondingDelivery.get(actionTemp))) {
// System.out.println("Warning: Constraint 5 reached");
return false;}
}
}
for (Vehicle vehicleTemp : nextActionV.keySet()) {
if (nextActionV.get(vehicleTemp) != null) {
//Constraint 2
if (time.get(nextActionV.get(vehicleTemp))!=1) {
System.out.println("Error: Constraint 2 reached, should not happen");
return false;
}
//Constraint 4
else if (vehicle.get(nextActionV.get(vehicleTemp))!=vehicleTemp) {
System.out.println("Error: Constraint 4 reached, should not happen");
return false;
}
//Constraint 7
action = nextActionV.get(vehicleTemp);
capacityTemp = vehicleTemp.capacity();
while (action!=null) {
//substract to available capacity if pickup
if (action.isPickup()) capacityTemp -= action.getTask().weight;
//add to available capacity if delivery
else capacityTemp += action.getTask().weight;
if (capacityTemp<0) {
// System.out.println("Warning: [Constraint 7] A plan was refused, not respecting capacity constraint");
return false;
}
action = nextActionA.get(action);
}
}
}
//Constraint 6
if ((nextActionA.size()+nextActionV.size())!= (actions.size()+vehicles.size())) {
System.out.println("Error: [Constraint 6] A plan was refused, sizes don't match");
return false;}
return true;
}
private Set<CentralizedAction> toActionSet(TaskSet tasks){
Set<CentralizedAction> actionSet = new HashSet<CentralizedAction>();
for (Task taskTemp : tasks) {
//add the corresponding pickup and delivery
CentralizedAction pickupAction = new CentralizedAction(taskTemp,true);
actionSet.add(pickupAction);
CentralizedAction deliveryAction = new CentralizedAction(taskTemp,false);
actionSet.add(deliveryAction);
//updating the mapping
this.correspondingDelivery.put(pickupAction, deliveryAction);
}
return actionSet;
}
/*resets the global CSP variable to the current plan*/
private void resetCSPVariables() {
this.nextActionA = new HashMap<CentralizedAction, CentralizedAction>(this.currentPlan.getNextActionA());
this.nextActionV = new HashMap<Vehicle, CentralizedAction>(this.currentPlan.getNextActionV());
this.time = new HashMap<CentralizedAction, Integer>(this.currentPlan.getTime());
this.vehicle = new HashMap<CentralizedAction, Vehicle>(this.currentPlan.getVehicle());
}
/*set current plant*/
private void setCurrentPlan(CentralizedPlan bestPlan) {
this.currentPlan = new CentralizedPlan(bestPlan.getNextActionA(),
bestPlan.getNextActionV(), bestPlan.getTime(),
bestPlan.getVehicle(), this.vehicles);
}
}
| UTF-8 | Java | 18,973 | java | CentralizedSolution.java | Java | [] | null | [] | package solution;
import java.io.File;
//the list of imports
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
import java.util.HashSet;
import logist.LogistSettings;
import logist.Measures;
import logist.behavior.AuctionBehavior;
import logist.behavior.CentralizedBehavior;
import logist.agent.Agent;
import logist.config.Parsers;
import logist.simulation.Vehicle;
import logist.plan.Plan;
import logist.task.Task;
import logist.task.TaskDistribution;
import logist.task.TaskSet;
import logist.topology.Topology;
import logist.topology.Topology.City;
@SuppressWarnings("unused")
public class CentralizedSolution implements CentralizedBehavior {
private Topology topology;
private TaskDistribution distribution;
private Agent agent;
private long timeout_setup;
private long timeout_plan;
// max iteration allowed to find local optimal.
private final int maxIterations = 10000;
//vehicles and actions for the planning
private List<Vehicle> vehicles;
private Set<CentralizedAction> actions;
/* CSP Variables */
// nextTask is divided in two arrays because we have two key types (Task and Vehicle)
private Map<CentralizedAction, CentralizedAction> nextActionA;
private Map<Vehicle, CentralizedAction> nextActionV;
private Map<CentralizedAction, Integer> time;
private Map<CentralizedAction, Vehicle> vehicle;
private CentralizedPlan currentPlan;
private Map<Vehicle, Integer> availableCapacity;
//Map a pickup action with its delivery action
private Map<CentralizedAction,CentralizedAction> correspondingDelivery;
//test
@Override
public void setup(Topology topology, TaskDistribution distribution,
Agent agent) {
// this code is used to get the timeouts
LogistSettings ls = null;
try {
ls = Parsers.parseSettings("config" + File.separator + "settings_default.xml");
}
catch (Exception exc) {
System.out.println("There was a problem loading the configuration file.");
}
// the setup method cannot last more than timeout_setup milliseconds
timeout_setup = ls.get(LogistSettings.TimeoutKey.SETUP);
// the plan method cannot execute more than timeout_plan milliseconds
timeout_plan = ls.get(LogistSettings.TimeoutKey.PLAN);
this.topology = topology;
this.distribution = distribution;
this.agent = agent;
this.nextActionA = new HashMap<CentralizedAction, CentralizedAction>();
this.nextActionV = new HashMap<Vehicle, CentralizedAction>();
this.time = new HashMap<CentralizedAction, Integer>();
this.vehicle = new HashMap<CentralizedAction, Vehicle>();
//this.currentPlan; = new CentralizedPlan(this.nextActionA, this.nextActionV,
// this.time, this.vehicle, this.vehicles);
this.correspondingDelivery = new HashMap<CentralizedAction,CentralizedAction>();
}
// List of the plan for each vehicle
@Override
public List<Plan> plan(List<Vehicle> vehicles, TaskSet tasks) {
long time_start = System.currentTimeMillis(); // save current time to measure computation duration
//instantiate
this.vehicles = vehicles;
this.actions = toActionSet(tasks);
/* Use Constraint Satisfaction Problem Optimization to find list of plans*/
List<Plan> plans = new ArrayList<Plan>();
// Initialize variables with non optimized plan.
// Fails if a task has a weight bigger than any vehicle capacity.
try {
SelectInitialSolution();
} catch (Exception e) {
System.out.println(e.getMessage());
}
List<CentralizedPlan> neighbourPlans;
CentralizedPlan bestNewPlan = new CentralizedPlan(new HashMap<CentralizedAction, CentralizedAction>(),
new HashMap<Vehicle, CentralizedAction>(),
new HashMap<CentralizedAction, Integer>(),
new HashMap<CentralizedAction, Vehicle>(),
new ArrayList<Vehicle>());
// loop until criterion reached
for (int i = 0; i < maxIterations; i++) {
/* Find neighbours */
neighbourPlans = ChooseNeighbours(i);
//System.out.println("Found " + neighbourPlans.size()+ " valid neighbours");
/* Select the most promissing one */
bestNewPlan = LocalChoice(neighbourPlans, i);
//System.out.println("The cost of the the new plan is: " + bestNewPlan.getCost());
System.out.println(bestNewPlan.getCost());
//experimenting
//this.currentPlan = bestNewPlan;
setCurrentPlan(bestNewPlan);
}
/* end */
// compute plan computation duration
long time_end = System.currentTimeMillis();
long duration = time_end - time_start;
//System.out.println("The plan was generated in "+duration+" milliseconds.");
plans = this.currentPlan.getPlan();
return plans;
}
private void SelectInitialSolution() throws Exception {
/* Give all the tasks to the biggest vehicle. Only updates global variables*/
/* The vehicle only carries one task at a time with this plan*/
Integer order = 1; // order in which the task are handled by a vehicle
CentralizedAction prevAction = null; // previous action carried by a vehicle
// find biggest vehicle, i.e. vehicle with largest capacity
Vehicle bigVehicle = vehicles.get(0);
for (Vehicle vehicle : vehicles) {
if (vehicle.capacity() > bigVehicle.capacity()) {
bigVehicle = vehicle;
}
//also fill nextActionV
nextActionV.put(vehicle, null);
}
// iterate over task set
for (CentralizedAction action : actions) {
//select only pickups in the loop
if (!action.isPickup()) continue;
// if the biggest vehicle cannot carry a task, the problem is unsolvable.
if (action.getTask().weight > bigVehicle.capacity()) {
throw new Exception("The task (id: "+action.getTask().id+") has a weight too big ! Problem unsolvable.");
}
// fill arrays for pickup
if (prevAction != null) this.nextActionA.put(prevAction, action);
if (order == 1) this.nextActionV.put(bigVehicle, action);
this.time.put(action, order);
this.vehicle.put(action, bigVehicle);
order++;
// fill arrays for delivery
this.nextActionA.put(action, correspondingDelivery.get(action));
this.nextActionA.put(correspondingDelivery.get(action), null);
this.time.put(correspondingDelivery.get(action), order);
this.vehicle.put(correspondingDelivery.get(action), bigVehicle);
order++;
prevAction = correspondingDelivery.get(action);
}
//set the current plan
this.currentPlan = new CentralizedPlan(this.nextActionA,this.nextActionV,
this.time, this.vehicle, this.vehicles);
if (!verifyConstraints()) {
// verify if solution meet constraints
throw new Exception("Problem solved, but did not meet the constraints"); // shouldn't go here
}
}
private List<CentralizedPlan> ChooseNeighbours(Integer iter) {
resetCSPVariables();
/* Find neighbours to the current solution */
List<CentralizedPlan> neighbourPlans = new ArrayList<CentralizedPlan>();
//select one random vehicle "transmitting" his tasks and "shuffling" them
Vehicle chosenVehicle;
do {
Random randomizer = new Random();
chosenVehicle = vehicles.get(randomizer.nextInt(vehicles.size()));
} while(this.nextActionV.get(chosenVehicle)==null);
//not problem here, is not null.
if (this.nextActionV.get(chosenVehicle)==null) {
System.out.println("is chosen vehicle null?");
}
/*creating new plans with a task transmitted to another vehicle*/
for (Vehicle vehicleTemp : vehicles) {
if (vehicleTemp == chosenVehicle) continue;
CentralizedPlan newPlan = changingVehicle(chosenVehicle,vehicleTemp);
if (newPlan != null) {
neighbourPlans.add(newPlan);
}
}
/*creating new plans with the tasks for the vehicle shuffled*/
CentralizedAction actionTemp = nextActionV.get(chosenVehicle);
Integer lengthChosenVehicle = 0;
//compute number of actions for the vehicle
while(actionTemp != null) {
lengthChosenVehicle +=1;
actionTemp = nextActionA.get(actionTemp);
}
//if the vehicle has at least two tasks
if (lengthChosenVehicle>=2) {
for (int i = 0; i<=lengthChosenVehicle-1; i++) {
for (int j = i+1; j< lengthChosenVehicle; j++) {
CentralizedPlan newPlan = changingActionOrder(chosenVehicle,i,j);
if (newPlan != null) {
neighbourPlans.add(newPlan);
}
}
}
}
return neighbourPlans;
}
/* create new plans by changing a task from a vehicle to another */
private CentralizedPlan changingVehicle(Vehicle vehicleGive, Vehicle vehicleReceive) {
CentralizedPlan newPlan;
resetCSPVariables();
// PROBLEM HERE transmitted pickup is null
CentralizedAction transmittedPickup = this.nextActionV.get(vehicleGive);
CentralizedAction transmittedDelivery = this.correspondingDelivery.get(transmittedPickup);
if (this.nextActionV.get(vehicleGive) == null) {
System.out.println("is null entering changingVehicle");
}
if (transmittedPickup == null) {
System.out.println("test");
}
//erasing from vehicleGive chain for the pickup action
nextActionV.put(vehicleGive, nextActionA.get(transmittedPickup));
//erasing from vehicleGive chain for the delivery action
if (nextActionV.get(vehicleGive)==transmittedDelivery) {
nextActionV.put(vehicleGive, nextActionA.get(transmittedDelivery));}
else {
CentralizedAction actionTemp = nextActionV.get(vehicleGive);
while (nextActionA.get(actionTemp) != null) {
if (nextActionA.get(actionTemp) == transmittedDelivery) {
nextActionA.put(actionTemp,nextActionA.get(transmittedDelivery));
break;
}
actionTemp = nextActionA.get(actionTemp);
}
}
//update vehicleReceive chain
nextActionA.put(transmittedPickup, transmittedDelivery);
nextActionA.put(transmittedDelivery, nextActionV.get(vehicleReceive));
nextActionV.put(vehicleReceive, transmittedPickup);
updateTime(vehicleGive);
updateTime(vehicleReceive);
vehicle.put(transmittedPickup, vehicleReceive);
vehicle.put(transmittedDelivery, vehicleReceive);
if (verifyConstraints()) {
// verify if solution meet constraints
newPlan = new CentralizedPlan(nextActionA, nextActionV, time, vehicle, this.vehicles);
}
else newPlan = null;
return newPlan;
}
private CentralizedPlan changingActionOrder(Vehicle vehicle, Integer id1, Integer id2) {
CentralizedPlan newPlan;
resetCSPVariables();
Integer count;
CentralizedAction a1;
CentralizedAction aPre2;
CentralizedAction a2;
if (id1==1) {
count = 1;
Vehicle aPre1 = vehicle; //previous "action" of action 1
a1 = nextActionV.get(vehicle); //action 1
aPre2 = a1; //previous action of action 2
a2 = nextActionA.get(aPre2);
count +=1;
while(count<id2) {
aPre2 = a2;
a2 = nextActionA.get(a2);
count +=1;
}
CentralizedAction aPost2 = nextActionA.get(a2); //post action of action 2
nextActionV.put(aPre1, a2);
}
else {
CentralizedAction aPre1 = nextActionV.get(vehicle); //previous action of action 1
a1 = nextActionA.get(aPre1); //action 1
count = 2;
while (count<id1) {
aPre1 =a1;
a1 = nextActionA.get(a1);
count +=1;
}
aPre2 = a1; //previous action of action 2
a2 = nextActionA.get(aPre2);
count +=1;
while(count<id2) {
aPre2 = a2;
a2 = nextActionA.get(a2);
count +=1;
}
nextActionA.put(aPre1, a2);
}
CentralizedAction aPost1 = nextActionA.get(a1); //post action of action 1
CentralizedAction aPost2 = nextActionA.get(a2); //post action of action 2
//exchanging the tasks
if (aPost1==a2) {
nextActionA.put(a2,a1);
nextActionA.put(a1, aPost2);
}
else {
nextActionA.put(aPre2,a1);
nextActionA.put(a2,aPost1);
nextActionA.put(a1, aPost2);
}
updateTime(vehicle);
if (verifyConstraints()) {
// verify if solution meet constraints
newPlan = new CentralizedPlan(nextActionA, nextActionV, time, this.vehicle, this.vehicles);
}
else newPlan = null;
return newPlan;
}
private void updateTime(Vehicle vehicle) {
CentralizedAction actionTemp = nextActionV.get(vehicle);
Integer timeTemp = 1;
while(actionTemp != null) {
//update time
time.put(actionTemp, timeTemp);
//iterate action and time
actionTemp = nextActionA.get(actionTemp);
timeTemp +=1;
}
}
private CentralizedPlan LocalChoice(List<CentralizedPlan> neighbourPlans, Integer iter) {
CentralizedPlan bestPlan = neighbourPlans.get(0);
Random random = new Random();
Double probAddCurrent = 1.;
Double probPickSecond = 0.;
Double probPickRandom = 0.5*(maxIterations-iter)/maxIterations;
Double probIgnore = 0.2;
if (random.nextFloat() < probAddCurrent) {
neighbourPlans.add(this.currentPlan);
}
if (random.nextFloat() < probPickRandom) {
return neighbourPlans.get(random.nextInt(neighbourPlans.size()));
}
for (CentralizedPlan plan : neighbourPlans) {
if (random.nextFloat() > probIgnore) {
continue;
}
//find the best plan
if (plan.getCost() < bestPlan.getCost()) {
bestPlan = plan;
}
else if (plan.getCost() == bestPlan.getCost()) {
// if equal cost, choose randomly
if (random.nextInt()%2 == 0) bestPlan = plan;
}
}
if (random.nextFloat() < probPickSecond) {
CentralizedPlan secondBestPlan = neighbourPlans.get(0);
//find the second next best plan
for (CentralizedPlan plan : neighbourPlans) {
if (plan == bestPlan) continue;
if (plan.getCost() < secondBestPlan.getCost()) {
secondBestPlan = plan;
}
}
bestPlan = secondBestPlan;
}
return bestPlan;
}
private boolean verifyConstraints(){
/* Based on the CSP Variables, verify if all the constraints are met */
Integer capacityTemp;
CentralizedAction action;
for (CentralizedAction actionTemp : nextActionA.keySet()) {
// Constraint 1
if (actionTemp == nextActionA.get(actionTemp)) {
System.out.println("Error: Constraint 1 reached, should not happen");
return false;
}
else if (nextActionA.get(actionTemp)!=null) {
// Constraint 3
if (time.get(nextActionA.get(actionTemp)) != (time.get(actionTemp) +1 )) {
System.out.println("Error: Constraint 3 reached, should not happen");
return false;}
//Constraint 5
if (vehicle.get(nextActionA.get(actionTemp))!= vehicle.get(actionTemp)) {
System.out.println("Error: Constraint 5 reached, should not happen");
return false;}
}
//Constraint 8
if(actionTemp.isPickup()) {
if (time.get(actionTemp) > time.get(correspondingDelivery.get(actionTemp))) {
// System.out.println("Warning: Constraint 5 reached");
return false;}
}
}
for (Vehicle vehicleTemp : nextActionV.keySet()) {
if (nextActionV.get(vehicleTemp) != null) {
//Constraint 2
if (time.get(nextActionV.get(vehicleTemp))!=1) {
System.out.println("Error: Constraint 2 reached, should not happen");
return false;
}
//Constraint 4
else if (vehicle.get(nextActionV.get(vehicleTemp))!=vehicleTemp) {
System.out.println("Error: Constraint 4 reached, should not happen");
return false;
}
//Constraint 7
action = nextActionV.get(vehicleTemp);
capacityTemp = vehicleTemp.capacity();
while (action!=null) {
//substract to available capacity if pickup
if (action.isPickup()) capacityTemp -= action.getTask().weight;
//add to available capacity if delivery
else capacityTemp += action.getTask().weight;
if (capacityTemp<0) {
// System.out.println("Warning: [Constraint 7] A plan was refused, not respecting capacity constraint");
return false;
}
action = nextActionA.get(action);
}
}
}
//Constraint 6
if ((nextActionA.size()+nextActionV.size())!= (actions.size()+vehicles.size())) {
System.out.println("Error: [Constraint 6] A plan was refused, sizes don't match");
return false;}
return true;
}
private Set<CentralizedAction> toActionSet(TaskSet tasks){
Set<CentralizedAction> actionSet = new HashSet<CentralizedAction>();
for (Task taskTemp : tasks) {
//add the corresponding pickup and delivery
CentralizedAction pickupAction = new CentralizedAction(taskTemp,true);
actionSet.add(pickupAction);
CentralizedAction deliveryAction = new CentralizedAction(taskTemp,false);
actionSet.add(deliveryAction);
//updating the mapping
this.correspondingDelivery.put(pickupAction, deliveryAction);
}
return actionSet;
}
/*resets the global CSP variable to the current plan*/
private void resetCSPVariables() {
this.nextActionA = new HashMap<CentralizedAction, CentralizedAction>(this.currentPlan.getNextActionA());
this.nextActionV = new HashMap<Vehicle, CentralizedAction>(this.currentPlan.getNextActionV());
this.time = new HashMap<CentralizedAction, Integer>(this.currentPlan.getTime());
this.vehicle = new HashMap<CentralizedAction, Vehicle>(this.currentPlan.getVehicle());
}
/*set current plant*/
private void setCurrentPlan(CentralizedPlan bestPlan) {
this.currentPlan = new CentralizedPlan(bestPlan.getNextActionA(),
bestPlan.getNextActionV(), bestPlan.getTime(),
bestPlan.getVehicle(), this.vehicles);
}
}
| 18,973 | 0.643072 | 0.6368 | 547 | 33.685558 | 26.571346 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.872029 | false | false | 4 |
691b9dc5711cd235c8042201faf8ffa318e0e64a | 27,814,208,264,762 | 3cfc0aed60532a4aeb1f95cdcd2f72a9ee6e3fd8 | /spring/Simulator/files/Parameters.java | 11e66a6b6959c3cd7db0a10636670fa64061fb34 | [] | no_license | bsushilkumar/IIT-PROJECT | https://github.com/bsushilkumar/IIT-PROJECT | 07f2e3c0040675787628d4f52602e3371e927cba | 38564c1e50dae4f4d0466f3e78a891200f1a5a1a | refs/heads/master | 2021-09-04T11:13:25.741000 | 2018-01-12T12:07:30 | 2018-01-12T12:07:30 | 113,741,007 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package files;
import globalVariables.FileNames;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StreamTokenizer;
public class Parameters {
public static int simulationTime = 1;
public static int delayFactor = 0;
public static int blockWorkingTime = 0;
public static int noOfColours = 4;
public static int redFailWaitTime = 1;
public static int redFailVelocity = 18;
public static double warnerDistance = 0;
private static final String formatString = "/* simulationTime delayFactor "
+ "blockWorkingTime noOfColor redFailWaitTime redFailVelocity warnerDistance */";
public static void setSimulationTime(int simulationTime) {
Parameters.simulationTime = simulationTime;
}
public static int getSimulationTime() {
return simulationTime;
}
public static void setDelayFactor(int delayFactor) {
Parameters.delayFactor = delayFactor;
}
public static int getDelayFactor() {
return delayFactor;
}
public static void setBlockWorkingTime(int blockWorkingTime) {
Parameters.blockWorkingTime = blockWorkingTime;
}
public static int getBlockWorkingTime() {
return blockWorkingTime;
}
public static void setRedFailWaitTime(int redFailWaitTime) {
Parameters.redFailWaitTime = redFailWaitTime;
}
public static int getRedFailWaitTime() {
return redFailWaitTime;
}
public static void setRedFailVelocity(int redFailVelocity) {
Parameters.redFailVelocity = redFailVelocity;
}
public static int getRedFailVelocity() {
return redFailVelocity;
}
public static void setWarnerDistance(double warnerDistance) {
Parameters.warnerDistance = warnerDistance;
}
public static double getWarnerDistance() {
return warnerDistance;
}
public static void setNoOfColours(int noOfColours) {
Parameters.noOfColours = noOfColours;
}
public static int getNoOfColours() {
return noOfColours;
}
public static void readParametersFile() throws IOException {
String fileName = FileNames.getParametersFileName();
StreamTokenizer streamTokenizer = new StreamTokenizer(new FileReader(
fileName));
streamTokenizer.slashSlashComments(true);
streamTokenizer.slashStarComments(true);
streamTokenizer.nextToken();
setSimulationTime((int) streamTokenizer.nval);
streamTokenizer.nextToken();
setDelayFactor((int) streamTokenizer.nval);
streamTokenizer.nextToken();
setBlockWorkingTime((int) streamTokenizer.nval);
streamTokenizer.nextToken();
setNoOfColours((int) streamTokenizer.nval);
streamTokenizer.nextToken();
setRedFailWaitTime((int) streamTokenizer.nval);
streamTokenizer.nextToken();
setRedFailVelocity((int) streamTokenizer.nval);
streamTokenizer.nextToken();
setWarnerDistance(streamTokenizer.nval);
}
public static void writeParametersFile() throws IOException {
String fileName = FileNames.getParametersFileName();
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
bw.write(getSimulationTime() + " ");
bw.write(getDelayFactor() + " ");
bw.write(getBlockWorkingTime() + " ");
bw.write(getNoOfColours() + " ");
bw.write(getRedFailWaitTime() + " ");
bw.write(getRedFailVelocity() + " ");
bw.write(getWarnerDistance() + "\n");
bw.write(formatString);
bw.close();
}
public static void printParameters() {
System.out.println("Printing parameters");
System.out.println("Simulation Time: " + getSimulationTime());
System.out.println("Delay Factor: " + getDelayFactor());
System.out.println("Block Working Time: " + getBlockWorkingTime());
System.out.println("Number Of Colours: " + getNoOfColours());
System.out.println("Red Fail Wait Time: " + getRedFailWaitTime());
System.out.println("Red Fail Velocity: " + getRedFailVelocity());
System.out.println("Warner Distance: " + getWarnerDistance());
}
}
| UTF-8 | Java | 3,823 | java | Parameters.java | Java | [] | null | [] | package files;
import globalVariables.FileNames;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StreamTokenizer;
public class Parameters {
public static int simulationTime = 1;
public static int delayFactor = 0;
public static int blockWorkingTime = 0;
public static int noOfColours = 4;
public static int redFailWaitTime = 1;
public static int redFailVelocity = 18;
public static double warnerDistance = 0;
private static final String formatString = "/* simulationTime delayFactor "
+ "blockWorkingTime noOfColor redFailWaitTime redFailVelocity warnerDistance */";
public static void setSimulationTime(int simulationTime) {
Parameters.simulationTime = simulationTime;
}
public static int getSimulationTime() {
return simulationTime;
}
public static void setDelayFactor(int delayFactor) {
Parameters.delayFactor = delayFactor;
}
public static int getDelayFactor() {
return delayFactor;
}
public static void setBlockWorkingTime(int blockWorkingTime) {
Parameters.blockWorkingTime = blockWorkingTime;
}
public static int getBlockWorkingTime() {
return blockWorkingTime;
}
public static void setRedFailWaitTime(int redFailWaitTime) {
Parameters.redFailWaitTime = redFailWaitTime;
}
public static int getRedFailWaitTime() {
return redFailWaitTime;
}
public static void setRedFailVelocity(int redFailVelocity) {
Parameters.redFailVelocity = redFailVelocity;
}
public static int getRedFailVelocity() {
return redFailVelocity;
}
public static void setWarnerDistance(double warnerDistance) {
Parameters.warnerDistance = warnerDistance;
}
public static double getWarnerDistance() {
return warnerDistance;
}
public static void setNoOfColours(int noOfColours) {
Parameters.noOfColours = noOfColours;
}
public static int getNoOfColours() {
return noOfColours;
}
public static void readParametersFile() throws IOException {
String fileName = FileNames.getParametersFileName();
StreamTokenizer streamTokenizer = new StreamTokenizer(new FileReader(
fileName));
streamTokenizer.slashSlashComments(true);
streamTokenizer.slashStarComments(true);
streamTokenizer.nextToken();
setSimulationTime((int) streamTokenizer.nval);
streamTokenizer.nextToken();
setDelayFactor((int) streamTokenizer.nval);
streamTokenizer.nextToken();
setBlockWorkingTime((int) streamTokenizer.nval);
streamTokenizer.nextToken();
setNoOfColours((int) streamTokenizer.nval);
streamTokenizer.nextToken();
setRedFailWaitTime((int) streamTokenizer.nval);
streamTokenizer.nextToken();
setRedFailVelocity((int) streamTokenizer.nval);
streamTokenizer.nextToken();
setWarnerDistance(streamTokenizer.nval);
}
public static void writeParametersFile() throws IOException {
String fileName = FileNames.getParametersFileName();
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
bw.write(getSimulationTime() + " ");
bw.write(getDelayFactor() + " ");
bw.write(getBlockWorkingTime() + " ");
bw.write(getNoOfColours() + " ");
bw.write(getRedFailWaitTime() + " ");
bw.write(getRedFailVelocity() + " ");
bw.write(getWarnerDistance() + "\n");
bw.write(formatString);
bw.close();
}
public static void printParameters() {
System.out.println("Printing parameters");
System.out.println("Simulation Time: " + getSimulationTime());
System.out.println("Delay Factor: " + getDelayFactor());
System.out.println("Block Working Time: " + getBlockWorkingTime());
System.out.println("Number Of Colours: " + getNoOfColours());
System.out.println("Red Fail Wait Time: " + getRedFailWaitTime());
System.out.println("Red Fail Velocity: " + getRedFailVelocity());
System.out.println("Warner Distance: " + getWarnerDistance());
}
}
| 3,823 | 0.760921 | 0.758828 | 132 | 27.962122 | 23.285255 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.643939 | false | false | 4 |
32e8397a8f0a45157a38eec9b8c9464dd8d53e3e | 34,591,666,602,625 | e57083ea584d69bc9fb1b32f5ec86bdd4fca61c0 | /sample-project-5400/src/main/java/com/example/project/sample5400/other/sample4/Other4_121.java | 660d307984b2893a2f79ae7e02463743bd8f500c | [] | no_license | snicoll-scratches/test-spring-components-index | https://github.com/snicoll-scratches/test-spring-components-index | 77e0ad58c8646c7eb1d1563bf31f51aa42a0636e | aa48681414a11bb704bdbc8acabe45fa5ef2fd2d | refs/heads/main | 2021-06-13T08:46:58.532000 | 2019-12-09T15:11:10 | 2019-12-09T15:11:10 | 65,806,297 | 5 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.project.sample5400.other.sample4;
public class Other4_121 {
}
| UTF-8 | Java | 84 | java | Other4_121.java | Java | [] | null | [] | package com.example.project.sample5400.other.sample4;
public class Other4_121 {
}
| 84 | 0.785714 | 0.678571 | 5 | 15.8 | 20.913155 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 14 |
a7316705614ad24309abc163914b2ab072b8ed04 | 12,051,678,299,736 | 3d9bef1b03b111ce05b21af0f27ed05e7bcd1289 | /src/main/java/com/ai/controller/UserController.java | 1647db5f29663718a2be5496eab1c357a9576bbe | [] | no_license | WEIMINGLYU/shop19 | https://github.com/WEIMINGLYU/shop19 | 79bed4c7223c6b910c7396e2b50e3bfa864e23db | d3068360f34af6928d1b93da3d91f71a6e80496d | refs/heads/master | 2022-12-23T21:42:00.837000 | 2019-05-27T03:53:44 | 2019-05-27T03:53:44 | 188,767,587 | 0 | 0 | null | false | 2022-12-16T10:51:36 | 2019-05-27T03:53:08 | 2019-05-27T03:59:32 | 2022-12-16T10:51:33 | 9,120 | 0 | 0 | 10 | Java | false | false | package com.ai.controller;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import com.ai.po.User;
import com.ai.service.IUserService;
import com.ai.util.CheckNullUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private IUserService userService;
/*退出登录*/
@RequestMapping("closeIndex")
public String closeIndex(HttpSession session){
session.invalidate();
return "redirect:doLogin.do";
}
@RequestMapping("personal")
public String personalDo(HttpSession session){
User user = (User) session.getAttribute("user");
if(user==null){
String page = "personal";
session.setAttribute("page",page);
return "redirect:doLogin.do";
}
return "personal";
}
/*个人信息中修改路径*/
@RequestMapping("/update.do")
public void update(User user, String rePassword, HttpServletResponse response, Model model, HttpServletRequest request,HttpSession session) throws IOException, ServletException {
boolean password = CheckNullUtil.checkMessage(user.getPassword());
boolean addr = CheckNullUtil.checkMessage(user.getAddr());
boolean email = CheckNullUtil.checkMessage(user.getEmail());
boolean phone = CheckNullUtil.checkMessage(user.getPhone());
boolean flag = true;
if(!password){
model.addAttribute("password","密码不可为空");
flag = false;
}
if(!addr){
model.addAttribute("addr","地址不可为空");
flag = false;
}
if(!email){
model.addAttribute("email","邮箱不可为空");
flag = false;
}
if(!phone){
model.addAttribute("phone","手机号不可为空");
flag = false;
}
if(flag == false){
request.getRequestDispatcher("/user/personal.do").forward(request,response);
return;
}
if (user.getPhone().length() != 11) {
return;
}
if (!user.getPassword().equals(rePassword)){
return;
}
userService.updateUser(user);
User sessionUser = (User)session.getAttribute("user");
sessionUser.setAddr(user.getAddr());
sessionUser.setEmail(user.getEmail());
sessionUser.setPhone(user.getPhone());
response.getWriter().print("ok");
/* return "personal";*/
}
/*登录页面访问地址*/
@RequestMapping("/doLogin.do")
public String doLogin(){
return "login";
}
/*登录页提交,验证用户名密码*/
@RequestMapping("checkLogin.do")
public String checkLogin(String renumberMe,User user, HttpSession session,Model model,HttpServletResponse response) throws UnsupportedEncodingException {
User userByNameAndPass = userService.findUserByNameAndPass(user);
// 验证是否为空
if((user.getUsername()==null||"".equals(user.getUsername()))||(user.getPassword()==null||"".equals(user.getPassword()))){
model.addAttribute("msg2","用户名或密码不能为空");
return "login";
}
// 验证用户名和密码是否存在
if(userByNameAndPass!=null){
session.setAttribute("user",userByNameAndPass);
}else{
model.addAttribute("msg","用户名或密码错误");
return "login";
}
// 创建Cookie,存储信息
Cookie cookie = new Cookie("user", URLEncoder.encode(user.getUsername()+"-"+user.getPassword(),"UTF-8"));
if(renumberMe!=null){
cookie.setMaxAge(60*60*24*7);
cookie.setPath("/");
}else {
cookie.setMaxAge(0);
cookie.setPath("/");
}
response.addCookie(cookie);
String page = (String)session.getAttribute("page");
if (page != null){
if ("findProductByPid".equals(page)){
return "redirect:/ai.com";
}
return page;
}
return "redirect:/ai.com";
}
/*注册页面访问地址*/
@RequestMapping("/registerPage.do")
public String registerPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
return "register";
}
/*注册页面添加用户*/
@RequestMapping("/doRegister.do")
public String doRegister(User user, Model model,String yzmCode,HttpSession session){
// 非空验证;
boolean username = CheckNullUtil.checkMessage(user.getUsername());
boolean password = CheckNullUtil.checkMessage(user.getPassword());
boolean nameFlag = CheckNullUtil.checkMessage(user.getName());
boolean addr = CheckNullUtil.checkMessage(user.getAddr());
boolean email = CheckNullUtil.checkMessage(user.getEmail());
boolean phone = CheckNullUtil.checkMessage(user.getPhone());
String ComputercCode = (String) session.getAttribute("code");
if (!yzmCode.equalsIgnoreCase(ComputercCode)){
model.addAttribute("codeMsg","请输入正确的验证码信息");
return "register";
}
boolean flag = true;
if(!username){
model.addAttribute("username","用户名不可为空");
flag = false;
}
if(!password){
model.addAttribute("password","密码不可为空");
flag = false;
}
if(!addr){
model.addAttribute("addr","地址不可为空");
flag = false;
}
if(!nameFlag){
model.addAttribute("nameFlag","姓名不可为空");
flag = false;
}
if(!email){
model.addAttribute("email","邮箱不可为空");
flag = false;
}
if(!phone){
model.addAttribute("phone","手机号不可为空");
flag = false;
}
if(flag == false){
return "register";
}
userService.addUser(user);
model.addAttribute("username",user.getUsername());
return "login";
}
/**
* 注册页通过AJAX查数据库重复名字
*/
@RequestMapping("/register.do")
public void register(String username,HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println(username+"controller");
// 接受客户端信息并执行查询姓名
User user = userService.registerByName(username);
if(user==null){
response.getWriter().print("ok");
}else{
response.getWriter().print("no");
}
}
}
| UTF-8 | Java | 7,643 | java | UserController.java | Java | [
{
"context": "){\n model.addAttribute(\"username\",\"用户名不可为空\");\n flag = false;\n ",
"end": 5808,
"score": 0.8428048491477966,
"start": 5805,
"tag": "USERNAME",
"value": "用户名"
},
{
"context": "){\n model.addAttribute(\"password... | null | [] | package com.ai.controller;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import com.ai.po.User;
import com.ai.service.IUserService;
import com.ai.util.CheckNullUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private IUserService userService;
/*退出登录*/
@RequestMapping("closeIndex")
public String closeIndex(HttpSession session){
session.invalidate();
return "redirect:doLogin.do";
}
@RequestMapping("personal")
public String personalDo(HttpSession session){
User user = (User) session.getAttribute("user");
if(user==null){
String page = "personal";
session.setAttribute("page",page);
return "redirect:doLogin.do";
}
return "personal";
}
/*个人信息中修改路径*/
@RequestMapping("/update.do")
public void update(User user, String rePassword, HttpServletResponse response, Model model, HttpServletRequest request,HttpSession session) throws IOException, ServletException {
boolean password = CheckNullUtil.checkMessage(user.getPassword());
boolean addr = CheckNullUtil.checkMessage(user.getAddr());
boolean email = CheckNullUtil.checkMessage(user.getEmail());
boolean phone = CheckNullUtil.checkMessage(user.getPhone());
boolean flag = true;
if(!password){
model.addAttribute("password","密码不可为空");
flag = false;
}
if(!addr){
model.addAttribute("addr","地址不可为空");
flag = false;
}
if(!email){
model.addAttribute("email","邮箱不可为空");
flag = false;
}
if(!phone){
model.addAttribute("phone","手机号不可为空");
flag = false;
}
if(flag == false){
request.getRequestDispatcher("/user/personal.do").forward(request,response);
return;
}
if (user.getPhone().length() != 11) {
return;
}
if (!user.getPassword().equals(rePassword)){
return;
}
userService.updateUser(user);
User sessionUser = (User)session.getAttribute("user");
sessionUser.setAddr(user.getAddr());
sessionUser.setEmail(user.getEmail());
sessionUser.setPhone(user.getPhone());
response.getWriter().print("ok");
/* return "personal";*/
}
/*登录页面访问地址*/
@RequestMapping("/doLogin.do")
public String doLogin(){
return "login";
}
/*登录页提交,验证用户名密码*/
@RequestMapping("checkLogin.do")
public String checkLogin(String renumberMe,User user, HttpSession session,Model model,HttpServletResponse response) throws UnsupportedEncodingException {
User userByNameAndPass = userService.findUserByNameAndPass(user);
// 验证是否为空
if((user.getUsername()==null||"".equals(user.getUsername()))||(user.getPassword()==null||"".equals(user.getPassword()))){
model.addAttribute("msg2","用户名或密码不能为空");
return "login";
}
// 验证用户名和密码是否存在
if(userByNameAndPass!=null){
session.setAttribute("user",userByNameAndPass);
}else{
model.addAttribute("msg","用户名或密码错误");
return "login";
}
// 创建Cookie,存储信息
Cookie cookie = new Cookie("user", URLEncoder.encode(user.getUsername()+"-"+user.getPassword(),"UTF-8"));
if(renumberMe!=null){
cookie.setMaxAge(60*60*24*7);
cookie.setPath("/");
}else {
cookie.setMaxAge(0);
cookie.setPath("/");
}
response.addCookie(cookie);
String page = (String)session.getAttribute("page");
if (page != null){
if ("findProductByPid".equals(page)){
return "redirect:/ai.com";
}
return page;
}
return "redirect:/ai.com";
}
/*注册页面访问地址*/
@RequestMapping("/registerPage.do")
public String registerPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
return "register";
}
/*注册页面添加用户*/
@RequestMapping("/doRegister.do")
public String doRegister(User user, Model model,String yzmCode,HttpSession session){
// 非空验证;
boolean username = CheckNullUtil.checkMessage(user.getUsername());
boolean password = CheckNullUtil.checkMessage(user.getPassword());
boolean nameFlag = CheckNullUtil.checkMessage(user.getName());
boolean addr = CheckNullUtil.checkMessage(user.getAddr());
boolean email = CheckNullUtil.checkMessage(user.getEmail());
boolean phone = CheckNullUtil.checkMessage(user.getPhone());
String ComputercCode = (String) session.getAttribute("code");
if (!yzmCode.equalsIgnoreCase(ComputercCode)){
model.addAttribute("codeMsg","请输入正确的验证码信息");
return "register";
}
boolean flag = true;
if(!username){
model.addAttribute("username","用户名不可为空");
flag = false;
}
if(!password){
model.addAttribute("password","<PASSWORD>");
flag = false;
}
if(!addr){
model.addAttribute("addr","地址不可为空");
flag = false;
}
if(!nameFlag){
model.addAttribute("nameFlag","姓名不可为空");
flag = false;
}
if(!email){
model.addAttribute("email","邮箱不可为空");
flag = false;
}
if(!phone){
model.addAttribute("phone","手机号不可为空");
flag = false;
}
if(flag == false){
return "register";
}
userService.addUser(user);
model.addAttribute("username",user.getUsername());
return "login";
}
/**
* 注册页通过AJAX查数据库重复名字
*/
@RequestMapping("/register.do")
public void register(String username,HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println(username+"controller");
// 接受客户端信息并执行查询姓名
User user = userService.registerByName(username);
if(user==null){
response.getWriter().print("ok");
}else{
response.getWriter().print("no");
}
}
}
| 7,635 | 0.561336 | 0.55968 | 216 | 32.541668 | 27.910872 | 183 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638889 | false | false | 14 |
eafae52c46e5491fb4b877ba87dc244f6f5dc607 | 12,051,678,300,973 | 3055ff039310f7fd1cb28c405e8659fe4b579410 | /apac/core/amwaydms/src/com/amway/integration/dms/services/AddPartyCreditProfileRequest.java | 0be3b0abd60e0647fff49ad12b0f88088a88bc5c | [] | no_license | AmwayKOR/lynx-korea | https://github.com/AmwayKOR/lynx-korea | 93222f5a3138a972fbcafec40ae6aaa6a1005b3d | cef1c32f6bf5718fdf9294e12e188decd2269476 | refs/heads/master | 2021-04-27T16:50:18.440000 | 2018-02-21T07:41:35 | 2018-02-21T07:41:35 | 122,305,108 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.amway.integration.dms.services;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
*
* Dms request for add party credit profile.
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "addPartyCreditProfileRequest", propOrder =
{ "partyCreditProfileList" })
@JsonIgnoreProperties(ignoreUnknown = true)
public class AddPartyCreditProfileRequest extends BaseWebServiceInput
{
@XmlElement(nillable = true)
protected List<PartyCreditPofileObject> partyCreditProfileList;
/**
*
* @return partyCreditProfileList
*/
public List<PartyCreditPofileObject> getPartyCreditProfileList()
{
return partyCreditProfileList;
}
/**
*
* @param partyCreditProfileList
* the partyCreditProfileList to set
*/
public void setPartyCreditProfileList(final List<PartyCreditPofileObject> partyCreditProfileList)
{
this.partyCreditProfileList = partyCreditProfileList;
}
}
| UTF-8 | Java | 1,136 | java | AddPartyCreditProfileRequest.java | Java | [] | null | [] | package com.amway.integration.dms.services;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
*
* Dms request for add party credit profile.
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "addPartyCreditProfileRequest", propOrder =
{ "partyCreditProfileList" })
@JsonIgnoreProperties(ignoreUnknown = true)
public class AddPartyCreditProfileRequest extends BaseWebServiceInput
{
@XmlElement(nillable = true)
protected List<PartyCreditPofileObject> partyCreditProfileList;
/**
*
* @return partyCreditProfileList
*/
public List<PartyCreditPofileObject> getPartyCreditProfileList()
{
return partyCreditProfileList;
}
/**
*
* @param partyCreditProfileList
* the partyCreditProfileList to set
*/
public void setPartyCreditProfileList(final List<PartyCreditPofileObject> partyCreditProfileList)
{
this.partyCreditProfileList = partyCreditProfileList;
}
}
| 1,136 | 0.786972 | 0.786972 | 45 | 24.244444 | 25.597878 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.711111 | false | false | 14 |
430883afcb635d683734cbd266b874cdca229333 | 35,424,890,277,864 | 61f7554d50e4ce1e94fbacf0a8a8056a891ea4c4 | /examples/powertools-examples-sqs/src/main/java/org/demo/sqs/SqsMessageSender.java | 701d6808f758d2ccd478e0564c8087fd422ea7c4 | [
"MIT-0",
"Apache-2.0"
] | permissive | awslabs/aws-lambda-powertools-java | https://github.com/awslabs/aws-lambda-powertools-java | c4edf32569dee2ecd2376031da274cc95bc1a780 | c21d66d3ba2c2adca4b4a2e90a135e1eac6b763c | refs/heads/main | 2023-08-27T05:56:14.342000 | 2023-08-25T11:31:55 | 2023-08-25T11:31:55 | 279,408,800 | 246 | 63 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2023 Amazon.com, Inc. or its affiliates.
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.demo.sqs;
import static java.util.stream.Collectors.toList;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.ScheduledEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.IntStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.MessageAttributeValue;
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest;
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry;
import software.amazon.awssdk.services.sqs.model.SendMessageBatchResponse;
import software.amazon.lambda.powertools.logging.Logging;
import software.amazon.lambda.powertools.logging.LoggingUtils;
public class SqsMessageSender implements RequestHandler<ScheduledEvent, String> {
private static final Logger log = LogManager.getLogger(SqsMessageSender.class);
private static final SqsClient sqsClient = SqsClient.builder()
.httpClient(UrlConnectionHttpClient.create())
.build();
private static final Random random = new SecureRandom();
private static final ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
LoggingUtils.defaultObjectMapper(objectMapper);
}
@Logging(logEvent = true)
public String handleRequest(final ScheduledEvent input, final Context context) {
String queueUrl = System.getenv("QUEUE_URL");
// Push 5 messages on each invoke.
List<SendMessageBatchRequestEntry> batchRequestEntries = IntStream.range(0, 5)
.mapToObj(value ->
{
Map<String, MessageAttributeValue> attributeValueHashMap = new HashMap<>();
attributeValueHashMap.put("Key" + value, MessageAttributeValue.builder()
.dataType("String")
.stringValue("Value" + value)
.build());
byte[] array = new byte[7];
random.nextBytes(array);
return SendMessageBatchRequestEntry.builder()
.messageAttributes(attributeValueHashMap)
.id(input.getId() + value)
.messageBody("Sample Message " + value)
.build();
}).collect(toList());
SendMessageBatchResponse sendMessageBatchResponse = sqsClient.sendMessageBatch(SendMessageBatchRequest.builder()
.queueUrl(queueUrl)
.entries(batchRequestEntries)
.build());
log.info("Sent Message {}", sendMessageBatchResponse);
return "Success";
}
} | UTF-8 | Java | 3,830 | java | SqsMessageSender.java | Java | [] | null | [] | /*
* Copyright 2023 Amazon.com, Inc. or its affiliates.
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.demo.sqs;
import static java.util.stream.Collectors.toList;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.ScheduledEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.IntStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.MessageAttributeValue;
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest;
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry;
import software.amazon.awssdk.services.sqs.model.SendMessageBatchResponse;
import software.amazon.lambda.powertools.logging.Logging;
import software.amazon.lambda.powertools.logging.LoggingUtils;
public class SqsMessageSender implements RequestHandler<ScheduledEvent, String> {
private static final Logger log = LogManager.getLogger(SqsMessageSender.class);
private static final SqsClient sqsClient = SqsClient.builder()
.httpClient(UrlConnectionHttpClient.create())
.build();
private static final Random random = new SecureRandom();
private static final ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
LoggingUtils.defaultObjectMapper(objectMapper);
}
@Logging(logEvent = true)
public String handleRequest(final ScheduledEvent input, final Context context) {
String queueUrl = System.getenv("QUEUE_URL");
// Push 5 messages on each invoke.
List<SendMessageBatchRequestEntry> batchRequestEntries = IntStream.range(0, 5)
.mapToObj(value ->
{
Map<String, MessageAttributeValue> attributeValueHashMap = new HashMap<>();
attributeValueHashMap.put("Key" + value, MessageAttributeValue.builder()
.dataType("String")
.stringValue("Value" + value)
.build());
byte[] array = new byte[7];
random.nextBytes(array);
return SendMessageBatchRequestEntry.builder()
.messageAttributes(attributeValueHashMap)
.id(input.getId() + value)
.messageBody("Sample Message " + value)
.build();
}).collect(toList());
SendMessageBatchResponse sendMessageBatchResponse = sqsClient.sendMessageBatch(SendMessageBatchRequest.builder()
.queueUrl(queueUrl)
.entries(batchRequestEntries)
.build());
log.info("Sent Message {}", sendMessageBatchResponse);
return "Success";
}
} | 3,830 | 0.694256 | 0.690601 | 92 | 40.641304 | 28.809563 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false | 14 |
774b8f4e769b75f4ac02101fe117282ce8868155 | 14,018,773,284,424 | 5ec9c84647af11afa02ce359b0d2e4fe63ac5fbc | /src/com/company/Ramka.java | 6c5e7e76cc3df3ced07e3ec0e69829c6f87434ab | [] | no_license | marek357/BirdThatFlaps | https://github.com/marek357/BirdThatFlaps | 445b5da1b4c8f32dcca7c1758e954ddba190b8b3 | 834a0a8f679b111a81f54d3bf6aa5dc917c5de4c | refs/heads/master | 2020-02-08T13:29:42.793000 | 2017-08-07T17:01:17 | 2017-08-07T17:01:17 | 99,493,962 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by marekmasiak on 06.08.2017.
*/
public class Ramka extends JFrame implements KeyListener{
Panelek panelek;
public Ramka(){
super("BirdThatFlaps");
setVisible(true);
setBackground(Color.white);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setSize(new Dimension(700,700));
setLocation(500,50);
panelek = new Panelek();
panelek.start();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
panelek.updateDOWN();
}
},0L,10L);
this.getContentPane().add(panelek, BorderLayout.CENTER);
this.addKeyListener(this);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode==32){
panelek.updateUP();
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
| UTF-8 | Java | 1,257 | java | Ramka.java | Java | [
{
"context": "mer;\nimport java.util.TimerTask;\n/**\n * Created by marekmasiak on 06.08.2017.\n */\npublic class Ramka extends JFr",
"end": 211,
"score": 0.9992522597312927,
"start": 200,
"tag": "USERNAME",
"value": "marekmasiak"
}
] | null | [] | package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by marekmasiak on 06.08.2017.
*/
public class Ramka extends JFrame implements KeyListener{
Panelek panelek;
public Ramka(){
super("BirdThatFlaps");
setVisible(true);
setBackground(Color.white);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setSize(new Dimension(700,700));
setLocation(500,50);
panelek = new Panelek();
panelek.start();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
panelek.updateDOWN();
}
},0L,10L);
this.getContentPane().add(panelek, BorderLayout.CENTER);
this.addKeyListener(this);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode==32){
panelek.updateUP();
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
| 1,257 | 0.603819 | 0.584726 | 54 | 22.277779 | 16.929502 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.537037 | false | false | 14 |
a4f18cc9f41f2e21a16f57e948895ca4bdcc78b4 | 22,892,175,723,494 | 159586f102593a14230d47d30e5d7e8d4bb8ad27 | /Java Collections/ArrayList/ArrayListDemo.java | 2199ef43c958ff8068fea57f8ad875b8dbe31f21 | [] | no_license | chavannikhil802/Java-Coding-Programs | https://github.com/chavannikhil802/Java-Coding-Programs | dc3d91732a28331234881dead05dfcf9ab5d08fa | 3218cad2dbd18e8a928755da8d718e5dc6ac7690 | refs/heads/master | 2023-03-14T17:38:34.659000 | 2021-03-03T12:54:34 | 2021-03-03T12:54:34 | 284,513,839 | 1 | 0 | null | false | 2020-08-28T14:14:09 | 2020-08-02T17:57:06 | 2020-08-28T10:15:51 | 2020-08-28T14:14:08 | 29 | 0 | 0 | 0 | Java | false | false | import java.util.ArrayList;
// PROGRAM TO DEMONSTRATE THE USE OF ARRAYLIST
class ArrayListDemo {
public static void main(String[] args) {
// CREATE AN ARRAY LIST
ArrayList<String> a1 = new ArrayList<String>();
// DISPALYING THE INITIAL SIZE OF THE ARRAYLIST
System.out.println("Initial size of a1 : "+a1.size());
// ADDING ELEMENTS TO THE ARRAYLIST
a1.add("A");
a1.add("B");
a1.add("C");
a1.add("D");
a1.add("E");
a1.add("F");
System.out.println("Size of a1 after adding elements to it : "+a1.size());
// DISPLAYING THE CONTENTS OF A1
System.out.println("Contents of a1 : "+a1);
// ADDING ELEMENTS AFTER "C" (3rd POSITION)
a1.add(3,"X");
a1.add(4,"Y");
a1.add(5,"Z");
System.out.println("Size of a1 after adding elements after 'C' : "+a1.size());
// DISPLAYING THE CONTENTS OF A1
System.out.println("Contents of a1 : "+a1);
// REMOVING THE RECENTLY ADDED ELEMENTS
a1.remove("X");
a1.remove("Y");
a1.remove("Z");
System.out.println("Size of a1 after removing elements : "+a1.size());
// DISPLAYING THE CONTENTS OF A1
System.out.println("Contents of a1 : "+a1);
}
} | UTF-8 | Java | 1,307 | java | ArrayListDemo.java | Java | [] | null | [] | import java.util.ArrayList;
// PROGRAM TO DEMONSTRATE THE USE OF ARRAYLIST
class ArrayListDemo {
public static void main(String[] args) {
// CREATE AN ARRAY LIST
ArrayList<String> a1 = new ArrayList<String>();
// DISPALYING THE INITIAL SIZE OF THE ARRAYLIST
System.out.println("Initial size of a1 : "+a1.size());
// ADDING ELEMENTS TO THE ARRAYLIST
a1.add("A");
a1.add("B");
a1.add("C");
a1.add("D");
a1.add("E");
a1.add("F");
System.out.println("Size of a1 after adding elements to it : "+a1.size());
// DISPLAYING THE CONTENTS OF A1
System.out.println("Contents of a1 : "+a1);
// ADDING ELEMENTS AFTER "C" (3rd POSITION)
a1.add(3,"X");
a1.add(4,"Y");
a1.add(5,"Z");
System.out.println("Size of a1 after adding elements after 'C' : "+a1.size());
// DISPLAYING THE CONTENTS OF A1
System.out.println("Contents of a1 : "+a1);
// REMOVING THE RECENTLY ADDED ELEMENTS
a1.remove("X");
a1.remove("Y");
a1.remove("Z");
System.out.println("Size of a1 after removing elements : "+a1.size());
// DISPLAYING THE CONTENTS OF A1
System.out.println("Contents of a1 : "+a1);
}
} | 1,307 | 0.561591 | 0.535578 | 46 | 27.434782 | 23.949814 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false | 14 |
2af24a9eeec022d83678d450096b740db6c05391 | 31,860,067,435,661 | 2871ef33670228edf308c14588556c3e03e0b133 | /nano/src/main/java/com/airhacks/nano/Contexts.java | 8aac789731b737f4355592c5989d2f8a6243c8b1 | [
"Apache-2.0"
] | permissive | reevejd/nano | https://github.com/reevejd/nano | 2f02b73e830b6e87926c5487c3086d3cbf3fd858 | 27172c1d974825cdcc05d98fb4be590d5018d3b2 | refs/heads/master | 2020-05-21T05:32:45.407000 | 2017-03-12T06:12:04 | 2017-03-12T06:12:04 | 84,579,374 | 0 | 0 | null | true | 2017-03-10T16:30:37 | 2017-03-10T16:30:37 | 2017-02-16T02:40:46 | 2015-12-23T08:19:53 | 18 | 0 | 0 | 0 | null | null | null | package com.airhacks.nano;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
*
* @author airhacks.com
*/
public interface Contexts {
/*
* This interface defines a series of methods that are used to discover and define http contexts.
*/
public static List<Path> discoverContexts(Path root) {
/*
* Given a root path, this method returns a list of paths that contain
* .js files (which assumed to be http handlers)
*/
List<Path> jars = new ArrayList<>();
SimpleFileVisitor visitor = new SimpleFileVisitor<Path>() { // This visitor will visit all files in a file tree
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
/*
* The default behaviour of visitFile has been modified so that
* any JavaScript files encountered are added to the "jars" List.
*/
if (!attributes.isDirectory()) {
if (file.toString().endsWith(".js")) {
jars.add(file);
}
}
return FileVisitResult.CONTINUE;
}
};
try {
Files.walkFileTree(root, visitor);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
return jars; // at this point, jars contains a list of all file paths to JavaScript files within the root
}
public static HttpHandler instantiate(Path scriptFile) {
/*
* This method creates an HTTP handler.
* It takes a path to a JavaScript http handler file, and returns a Java HttpHandler.
*/
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("javascript"); // A JavaScript ScriptEngine will be used to evaluate JavaScript code
/* attempt to run the JavaScript script */
try {
engine.eval(new FileReader(scriptFile.toFile()));
} catch (ScriptException | FileNotFoundException ex) {
throw new IllegalStateException(ex);
}
/* casting the ScriptEngine to an Invocable
* allows the use Invocable's getInterface method,
* which maps a Java interface onto a script by matching method names
*/
Invocable invocable = (Invocable) engine;
NanoRequest request = invocable.getInterface(NanoRequest.class);
/*
* using Java 8's lambda expressions, return an HTTP handler function
*/
return (HttpExchange he) -> {
final OutputStream responseBody = he.getResponseBody();
StringBuilder builder = new StringBuilder();
ResponseWriter writer = builder::append; /* store a reference to builder's append method, which can be
passed to in a request.process call below to write an HTTP response */
/* Get the request method (get, post, etc), body, content, request headers,
and a container for the response headers. Then these are passed to the request.process method. */
final InputStream requestBody = he.getRequestBody();
String requestContent;
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(requestBody))) {
requestContent = buffer.lines().collect(Collectors.joining("\n"));
}
Headers requestHeaders = he.getRequestHeaders();
Headers responseHeaders = he.getResponseHeaders();
int statusCode = request.process( // calling request's process method will now execute the associated JavaScript process method
he.getRequestMethod(),
requestHeaders,
responseHeaders,
requestContent,
writer
);
String content = builder.toString(); /* a reference to builder's append method was
passed to request.process above, the response was written, and the response can now be retrieved from builder */
/* update the response headers and body, then flush the output stream to commit/save what was in the buffer */
he.sendResponseHeaders(statusCode, content.length());
responseBody.write(content.getBytes());
responseBody.flush();
he.close();
};
}
public static HttpContext create(HttpServer server, Path path) {
/*
* creates an http context for a given http server using a path to a JavaScript http handler
*/
HttpHandler handler = instantiate(path); // create the http handler for this path
final String extracted = extractContext(path); // get the formatted http context string
HttpContext context = server.createContext(extracted); // use the context string to create the context
context.setHandler(handler); // assign the handler for this context
System.out.println("Context registered: " + context.getPath());
return context;
}
public static String extractContext(Path path) {
/*
* Translates a file path into a http context path
* e.g. developer/java/duke.js --> /developer/java/duke
*/
String fileName = "/" + path.normalize().toString();
int lastIndexOf = fileName.lastIndexOf(".");
return fileName.substring(0, lastIndexOf);
}
}
| UTF-8 | Java | 6,347 | java | Contexts.java | Java | [
{
"context": "t javax.script.ScriptException;\n\n/**\n *\n * @author airhacks.com\n */\npublic interface Contexts {\n\n /*\n * Th",
"end": 900,
"score": 0.9993146657943726,
"start": 888,
"tag": "EMAIL",
"value": "airhacks.com"
}
] | null | [] | package com.airhacks.nano;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
*
* @author <EMAIL>
*/
public interface Contexts {
/*
* This interface defines a series of methods that are used to discover and define http contexts.
*/
public static List<Path> discoverContexts(Path root) {
/*
* Given a root path, this method returns a list of paths that contain
* .js files (which assumed to be http handlers)
*/
List<Path> jars = new ArrayList<>();
SimpleFileVisitor visitor = new SimpleFileVisitor<Path>() { // This visitor will visit all files in a file tree
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
/*
* The default behaviour of visitFile has been modified so that
* any JavaScript files encountered are added to the "jars" List.
*/
if (!attributes.isDirectory()) {
if (file.toString().endsWith(".js")) {
jars.add(file);
}
}
return FileVisitResult.CONTINUE;
}
};
try {
Files.walkFileTree(root, visitor);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
return jars; // at this point, jars contains a list of all file paths to JavaScript files within the root
}
public static HttpHandler instantiate(Path scriptFile) {
/*
* This method creates an HTTP handler.
* It takes a path to a JavaScript http handler file, and returns a Java HttpHandler.
*/
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("javascript"); // A JavaScript ScriptEngine will be used to evaluate JavaScript code
/* attempt to run the JavaScript script */
try {
engine.eval(new FileReader(scriptFile.toFile()));
} catch (ScriptException | FileNotFoundException ex) {
throw new IllegalStateException(ex);
}
/* casting the ScriptEngine to an Invocable
* allows the use Invocable's getInterface method,
* which maps a Java interface onto a script by matching method names
*/
Invocable invocable = (Invocable) engine;
NanoRequest request = invocable.getInterface(NanoRequest.class);
/*
* using Java 8's lambda expressions, return an HTTP handler function
*/
return (HttpExchange he) -> {
final OutputStream responseBody = he.getResponseBody();
StringBuilder builder = new StringBuilder();
ResponseWriter writer = builder::append; /* store a reference to builder's append method, which can be
passed to in a request.process call below to write an HTTP response */
/* Get the request method (get, post, etc), body, content, request headers,
and a container for the response headers. Then these are passed to the request.process method. */
final InputStream requestBody = he.getRequestBody();
String requestContent;
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(requestBody))) {
requestContent = buffer.lines().collect(Collectors.joining("\n"));
}
Headers requestHeaders = he.getRequestHeaders();
Headers responseHeaders = he.getResponseHeaders();
int statusCode = request.process( // calling request's process method will now execute the associated JavaScript process method
he.getRequestMethod(),
requestHeaders,
responseHeaders,
requestContent,
writer
);
String content = builder.toString(); /* a reference to builder's append method was
passed to request.process above, the response was written, and the response can now be retrieved from builder */
/* update the response headers and body, then flush the output stream to commit/save what was in the buffer */
he.sendResponseHeaders(statusCode, content.length());
responseBody.write(content.getBytes());
responseBody.flush();
he.close();
};
}
public static HttpContext create(HttpServer server, Path path) {
/*
* creates an http context for a given http server using a path to a JavaScript http handler
*/
HttpHandler handler = instantiate(path); // create the http handler for this path
final String extracted = extractContext(path); // get the formatted http context string
HttpContext context = server.createContext(extracted); // use the context string to create the context
context.setHandler(handler); // assign the handler for this context
System.out.println("Context registered: " + context.getPath());
return context;
}
public static String extractContext(Path path) {
/*
* Translates a file path into a http context path
* e.g. developer/java/duke.js --> /developer/java/duke
*/
String fileName = "/" + path.normalize().toString();
int lastIndexOf = fileName.lastIndexOf(".");
return fileName.substring(0, lastIndexOf);
}
}
| 6,342 | 0.639987 | 0.639672 | 154 | 40.214287 | 33.772533 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.564935 | false | false | 14 |
bdb92052dce3efad737aeb0ae33be08d8007b95a | 28,724,741,321,790 | 2e1f34ef0d7e1b0b14200b318c9d2a30de824b33 | /spring-learn/src/main/java/com/cognizant/springlearn/service/EmployeeService.java | 54a60d350787244d08a1bee3d7f98264c349bae4 | [] | no_license | cmkalimuthu/handsons | https://github.com/cmkalimuthu/handsons | 791bb0e9c1a15c3acec453da819e242de528a473 | 0d0d705e160d4c309c098c195fa7887ca4600357 | refs/heads/main | 2023-04-18T02:07:25.291000 | 2021-05-21T07:25:42 | 2021-05-21T07:25:42 | 348,717,599 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cognizant.springlearn.service;
import java.util.ArrayList;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cognizant.springlearn.Employee;
import com.cognizant.springlearn.Exception.EmployeeNotFoundException2;
import com.cognizant.springlearn.dao.EmployeeDao;
@Service
public class EmployeeService {
@Autowired
EmployeeDao employeeDao;
public ArrayList<Employee> getAllEmployees(){
return employeeDao.getAllEmployees();
}
public Employee updateEmployee(Employee emp) throws EmployeeNotFoundException2 {
return employeeDao.updateEmployee(emp);
}
public ArrayList<Employee> deleteEmployee(int id) throws EmployeeNotFoundException2{
return employeeDao.deleteEmployee(id);
}
public Employee addEmployee(Employee employee) {
return employeeDao.addEmployee(employee);
}
}
| UTF-8 | Java | 913 | java | EmployeeService.java | Java | [] | null | [] | package com.cognizant.springlearn.service;
import java.util.ArrayList;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cognizant.springlearn.Employee;
import com.cognizant.springlearn.Exception.EmployeeNotFoundException2;
import com.cognizant.springlearn.dao.EmployeeDao;
@Service
public class EmployeeService {
@Autowired
EmployeeDao employeeDao;
public ArrayList<Employee> getAllEmployees(){
return employeeDao.getAllEmployees();
}
public Employee updateEmployee(Employee emp) throws EmployeeNotFoundException2 {
return employeeDao.updateEmployee(emp);
}
public ArrayList<Employee> deleteEmployee(int id) throws EmployeeNotFoundException2{
return employeeDao.deleteEmployee(id);
}
public Employee addEmployee(Employee employee) {
return employeeDao.addEmployee(employee);
}
}
| 913 | 0.820372 | 0.817087 | 35 | 25.085714 | 25.677528 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.971429 | false | false | 14 |
3209f7d4f34b861e5aa67cf97fe037fb0cbaaace | 1,468,878,858,531 | 017af046c454ad937bd401bcf4adbd7b2f3eb95b | /momoapp/src/main/java/com/momo/Application.java | 00e43e82bce77851566a5a5aad621397c76d8b82 | [] | no_license | calm-sjf/apps | https://github.com/calm-sjf/apps | 47cde7294321e09d718c374626f233d1c28b9970 | 64cbb290015a789a6fbab85dd6f3e3744a455ea6 | refs/heads/master | 2023-07-29T02:13:32.808000 | 2021-09-09T02:56:00 | 2021-09-09T02:56:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.momo;
import android.widget.TextView;
import com.base.BaseApplication;
import com.screen.iface.TextStyle;
public class Application extends BaseApplication implements TextStyle {
@Override
public void onCreate() {
super.onCreate();
// ScreenManager.getInstance(this).replaceSystemDefaultFontFromAsset("font/ali
}
@Override
public void setTextStyle(TextView textView, String textStyle) {
}
}
| UTF-8 | Java | 445 | java | Application.java | Java | [] | null | [] | package com.momo;
import android.widget.TextView;
import com.base.BaseApplication;
import com.screen.iface.TextStyle;
public class Application extends BaseApplication implements TextStyle {
@Override
public void onCreate() {
super.onCreate();
// ScreenManager.getInstance(this).replaceSystemDefaultFontFromAsset("font/ali
}
@Override
public void setTextStyle(TextView textView, String textStyle) {
}
}
| 445 | 0.739326 | 0.739326 | 18 | 23.722221 | 25.661917 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 14 |
5ca8d4f3c1d7303fed8ef0b4b86567ba559f2837 | 1,468,878,859,345 | ab21a7bffdc7c2f3fa60f86d1f8505883c2ca607 | /Admin/src/main/java/admin/swagger/SwaggerConfig.java | 340fe2386df0643361374ba3919061719ebf530a | [] | no_license | yijiupi/ShopMall | https://github.com/yijiupi/ShopMall | be617afdeae52a239833768cab1ce9d58d834709 | 65752436793262cf31a82fbfa2811e8e95ecf48a | refs/heads/master | 2020-12-24T10:10:47.350000 | 2016-11-10T04:34:19 | 2016-11-10T04:34:19 | 73,247,327 | 0 | 0 | null | false | 2016-11-09T08:26:35 | 2016-11-09T02:51:06 | 2016-11-09T02:51:06 | 2016-11-09T08:26:35 | 0 | 0 | 0 | 0 | null | null | null | package admin.swagger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.models.dto.builder.ApiInfoBuilder;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
@Configuration
@EnableSwagger
@EnableWebMvc
public class SwaggerConfig {
private SpringSwaggerConfig springSwaggerConfig;
@Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
@Bean
public SwaggerSpringMvcPlugin customImplementation() {
// assuming the API lives at something like http://myapp/api
return new SwaggerSpringMvcPlugin(springSwaggerConfig).apiInfo(apiInfo()).includePatterns(".*api.*");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("TITLE").description("DESCRIPTION")
.termsOfServiceUrl("http://terms-of-services.url").license("LICENSE")
.licenseUrl("http://url-to-license.com").build();
}
}
| UTF-8 | Java | 1,315 | java | SwaggerConfig.java | Java | [] | null | [] | package admin.swagger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.models.dto.builder.ApiInfoBuilder;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
@Configuration
@EnableSwagger
@EnableWebMvc
public class SwaggerConfig {
private SpringSwaggerConfig springSwaggerConfig;
@Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
@Bean
public SwaggerSpringMvcPlugin customImplementation() {
// assuming the API lives at something like http://myapp/api
return new SwaggerSpringMvcPlugin(springSwaggerConfig).apiInfo(apiInfo()).includePatterns(".*api.*");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("TITLE").description("DESCRIPTION")
.termsOfServiceUrl("http://terms-of-services.url").license("LICENSE")
.licenseUrl("http://url-to-license.com").build();
}
}
| 1,315 | 0.814449 | 0.814449 | 37 | 34.540539 | 30.000536 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.054054 | false | false | 14 |
66a80f0eba2795d9d954e5cc8b4e93a5e95cf513 | 11,819,750,047,748 | 50e2b2884b2074482490debe5c9d778cbd7a68c9 | /app-dao/src/main/java/com/sykj/app/dao/system/impl/SearchParamDaoImpl.java | 3d76dbbfedec66caf87a46cf8656a964909203c2 | [] | no_license | xnjypt/xnhbjypt | https://github.com/xnjypt/xnhbjypt | 043ae601bec99efcd0e713826bca5339e37f3836 | d5670e1648ab00d90756a20b89f3b090536bd8a8 | refs/heads/master | 2021-05-04T01:55:55.455000 | 2017-01-08T21:04:57 | 2017-01-08T21:04:57 | 71,249,910 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sykj.app.dao.system.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.sykj.app.dao.system.SearchParamDao;
import com.sykj.app.entity.area.Province;
import com.sykj.app.entity.system.SearchParam;
import com.sykj.app.model.Pager;
import com.sykj.app.model.SystemContext;
import com.sykj.common.dao.BaseDao;
@Repository("searchParamDao")
public class SearchParamDaoImpl extends BaseDao<SearchParam> implements
SearchParamDao {
@Override
public void addSearchParam(SearchParam t) {
this.add(t);
}
@Override
public SearchParam getSearchParam(String id) {
return this.get("from SearchParam t where t.id='"+id+"'");
}
@Override
public void deleteSearchParam(String id) {
this.delete(this.getSearchParam(id));
}
@Override
public void deleteSearchParamByMenuIdMobile(SearchParam s) {
String hql = "delete from SearchParam t where t.menuId='"+s.getMenuId()+"' and t.mobile='"+s.getMobile()+"'";
this.updateByHql(hql);
}
@Override
public SearchParam getSearchParamByMenuUserId(SearchParam t) {
String hql = " from SearchParam t where t.menuId='"+t.getMenuId()+"' and t.mobile='"+t.getMobile()+"'";
List<SearchParam> list = this.list(hql);
if(list.size() > 0)
return list.get(0);
return null;
}
@Override
public Pager<SearchParam> findSearchParam(SystemContext syct, SearchParam t) {
StringBuffer hql = new StringBuffer("from SearchParam t where 1=1 ORDER BY t.createDateTime desc");
return this.find(hql.toString(),syct);
}
@Override
public SearchParam findSearchParamByUserId(String userId, String src) {
// StringBuffer hql = new StringBuffer("SELECT * from sykj_system_searchparam"
// + " WHERE mobile=(SELECT MOBILE from sykj_user_userinformation where USERID='"+userId+"')"
// + " and menuId = (SELECT ID from sykj_system_menu where src = '"+src+"')");
StringBuffer hql = new StringBuffer("from SearchParam"
+ " WHERE mobile=(SELECT mobile from UserInformation where userId='"+userId+"')"
+ " and menuId = (SELECT id from Menu where src = '"+src+"')");
return this.get(hql.toString());
}
}
| UTF-8 | Java | 2,194 | java | SearchParamDaoImpl.java | Java | [] | null | [] | package com.sykj.app.dao.system.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.sykj.app.dao.system.SearchParamDao;
import com.sykj.app.entity.area.Province;
import com.sykj.app.entity.system.SearchParam;
import com.sykj.app.model.Pager;
import com.sykj.app.model.SystemContext;
import com.sykj.common.dao.BaseDao;
@Repository("searchParamDao")
public class SearchParamDaoImpl extends BaseDao<SearchParam> implements
SearchParamDao {
@Override
public void addSearchParam(SearchParam t) {
this.add(t);
}
@Override
public SearchParam getSearchParam(String id) {
return this.get("from SearchParam t where t.id='"+id+"'");
}
@Override
public void deleteSearchParam(String id) {
this.delete(this.getSearchParam(id));
}
@Override
public void deleteSearchParamByMenuIdMobile(SearchParam s) {
String hql = "delete from SearchParam t where t.menuId='"+s.getMenuId()+"' and t.mobile='"+s.getMobile()+"'";
this.updateByHql(hql);
}
@Override
public SearchParam getSearchParamByMenuUserId(SearchParam t) {
String hql = " from SearchParam t where t.menuId='"+t.getMenuId()+"' and t.mobile='"+t.getMobile()+"'";
List<SearchParam> list = this.list(hql);
if(list.size() > 0)
return list.get(0);
return null;
}
@Override
public Pager<SearchParam> findSearchParam(SystemContext syct, SearchParam t) {
StringBuffer hql = new StringBuffer("from SearchParam t where 1=1 ORDER BY t.createDateTime desc");
return this.find(hql.toString(),syct);
}
@Override
public SearchParam findSearchParamByUserId(String userId, String src) {
// StringBuffer hql = new StringBuffer("SELECT * from sykj_system_searchparam"
// + " WHERE mobile=(SELECT MOBILE from sykj_user_userinformation where USERID='"+userId+"')"
// + " and menuId = (SELECT ID from sykj_system_menu where src = '"+src+"')");
StringBuffer hql = new StringBuffer("from SearchParam"
+ " WHERE mobile=(SELECT mobile from UserInformation where userId='"+userId+"')"
+ " and menuId = (SELECT id from Menu where src = '"+src+"')");
return this.get(hql.toString());
}
}
| 2,194 | 0.702826 | 0.701003 | 67 | 30.746269 | 31.226828 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.567164 | false | false | 14 |
6259cca214158b8087ee5746ab0b2c5fc576fea4 | 9,328,669,001,740 | ee5330406d5f2438fb7bc28274df277b8c397575 | /src/trees/ReplaceLeastGreatest.java | effd734912951b5a49fd9690a80cf841b1e15386 | [] | no_license | ankurgarg1986/Algorithms | https://github.com/ankurgarg1986/Algorithms | b51c3cd43b11c0c8875a6b995ae26b0107fa72d7 | 5b72774969f8405a805475efb1250fa93ae0e3a2 | refs/heads/master | 2020-04-16T10:53:55.511000 | 2017-03-05T17:46:42 | 2017-03-05T17:46:42 | 48,028,324 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package trees;
public class ReplaceLeastGreatest {
private static void replaceWithLeastGreatest(int[] arr) {
int n = arr.length;
int i;
Node root = new Node(arr[n-1]);
for (i = n-2; i >= 0; i--) {
insert(arr[i], root);
}
int[] ans = new int[n];
for (i = 0; i < n - 1; i++) {
ans[i] = findInorderSuccessor(root, arr[i]);
}
ans[n - 1] = -1;
}
private static int findInorderSuccessor(Node root, int val) {
if (root == null)
return -1;
Node curr = root;
Node parent = null;
while (curr != null) {
if (val == curr.data)
break;
if (val < curr.data) {
parent = curr;
curr = curr.left;
} else {
curr = curr.right;
}
}
if (curr == null)
return -1;
if (curr.right != null) {
curr = curr.right;
while (curr.left != null) {
curr = curr.left;
}
return curr.data;
} else {
if (parent == null)
return -1;
return parent.data;
}
}
private static void insert(int val, Node root) {
Node curr = root;
while (curr != null) {
if (val > curr.data) {
while (curr.right != null && val > curr.data)
curr = curr.right;
if (curr.right == null && val > curr.data) {
curr.right = new Node(val);
return;
}
} else {
while (curr.left != null && val < curr.data)
curr = curr.left;
if (curr.left == null && val < curr.data) {
curr.left = new Node(val);
return;
}
}
}
}
public static void main(String[] args) {
int arr[] = { 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 };
replaceWithLeastGreatest(arr);
}
}
| UTF-8 | Java | 1,760 | java | ReplaceLeastGreatest.java | Java | [] | null | [] | package trees;
public class ReplaceLeastGreatest {
private static void replaceWithLeastGreatest(int[] arr) {
int n = arr.length;
int i;
Node root = new Node(arr[n-1]);
for (i = n-2; i >= 0; i--) {
insert(arr[i], root);
}
int[] ans = new int[n];
for (i = 0; i < n - 1; i++) {
ans[i] = findInorderSuccessor(root, arr[i]);
}
ans[n - 1] = -1;
}
private static int findInorderSuccessor(Node root, int val) {
if (root == null)
return -1;
Node curr = root;
Node parent = null;
while (curr != null) {
if (val == curr.data)
break;
if (val < curr.data) {
parent = curr;
curr = curr.left;
} else {
curr = curr.right;
}
}
if (curr == null)
return -1;
if (curr.right != null) {
curr = curr.right;
while (curr.left != null) {
curr = curr.left;
}
return curr.data;
} else {
if (parent == null)
return -1;
return parent.data;
}
}
private static void insert(int val, Node root) {
Node curr = root;
while (curr != null) {
if (val > curr.data) {
while (curr.right != null && val > curr.data)
curr = curr.right;
if (curr.right == null && val > curr.data) {
curr.right = new Node(val);
return;
}
} else {
while (curr.left != null && val < curr.data)
curr = curr.left;
if (curr.left == null && val < curr.data) {
curr.left = new Node(val);
return;
}
}
}
}
public static void main(String[] args) {
int arr[] = { 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 };
replaceWithLeastGreatest(arr);
}
}
| 1,760 | 0.491477 | 0.469886 | 79 | 21.278481 | 17.072397 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.658228 | false | false | 14 |
b2020d8d7074c5477b9c561abac1c65c178dc057 | 25,254,407,741,618 | 79c6647ea36fa7270d21d716dfa4c93618bab821 | /src/main/java/br/com/emsouza/plugin/launch4j/util/JavaShell.java | 06223c4c0b7efef178f58b698661af9c35d6b896 | [] | no_license | emsouza/launch4j-maven-plugin | https://github.com/emsouza/launch4j-maven-plugin | bd032a36aaa2db20fe054b670623117858467087 | 06d7733cfc8852fffb9101b1567ee795543c7ee8 | refs/heads/master | 2021-01-10T20:29:22.736000 | 2013-02-06T21:50:05 | 2013-02-06T21:50:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.emsouza.plugin.launch4j.util;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.shell.Shell;
/**
* @author Eduardo Matos de Souza - SIC/NDS <br>
* D�gitro - 14/09/2012 <br>
* <a href="mailto:eduardo.souza@digitro.com.br">eduardo.souza@digitro.com.br</a>
*/
public class JavaShell extends Shell {
@Override
protected List<String> getRawCommandLine(String executable, String[] arguments) {
List<String> commandLine = new ArrayList<String>();
if (executable != null) {
commandLine.add(executable);
}
for (String arg : arguments) {
if (isQuotedArgumentsEnabled()) {
char[] escapeChars = getEscapeChars(isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped());
commandLine.add(StringUtils.quoteAndEscape(arg, getArgumentQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), '\\', false));
} else {
commandLine.add(arg);
}
}
return commandLine;
}
} | UTF-8 | Java | 1,023 | java | JavaShell.java | Java | [
{
"context": "ehaus.plexus.util.cli.shell.Shell;\n\n/**\n * @author Eduardo Matos de Souza - SIC/NDS <br>\n * D�gitro - 14/09/2012 <b",
"end": 230,
"score": 0.9998797178268433,
"start": 208,
"tag": "NAME",
"value": "Eduardo Matos de Souza"
},
{
"context": "itro - 14/09/2012 <... | null | [] | package br.com.emsouza.plugin.launch4j.util;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.shell.Shell;
/**
* @author <NAME> - SIC/NDS <br>
* D�gitro - 14/09/2012 <br>
* <a href="mailto:<EMAIL>"><EMAIL></a>
*/
public class JavaShell extends Shell {
@Override
protected List<String> getRawCommandLine(String executable, String[] arguments) {
List<String> commandLine = new ArrayList<String>();
if (executable != null) {
commandLine.add(executable);
}
for (String arg : arguments) {
if (isQuotedArgumentsEnabled()) {
char[] escapeChars = getEscapeChars(isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped());
commandLine.add(StringUtils.quoteAndEscape(arg, getArgumentQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), '\\', false));
} else {
commandLine.add(arg);
}
}
return commandLine;
}
} | 965 | 0.716944 | 0.708129 | 35 | 28.200001 | 32.716793 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.628571 | false | false | 14 |
6ddbe5e3b594d1cbe2b8381d54bd04aaa8f95d57 | 26,654,567,047,978 | fc28f7c8377853f457e0224a6db19a4e70c42f66 | /src/main/java/application/model/Producto.java | 70ef078a455e00ab443fca33b61b860fed13be71 | [] | no_license | Juanscabu/Entregable4 | https://github.com/Juanscabu/Entregable4 | 78e5684ff50ff539212d7c2fd44a1a6359b58e82 | 132426d19491f5cf239c40c7ce76c6da0e0ca98f | refs/heads/master | 2022-12-31T14:22:59.349000 | 2020-10-21T14:56:54 | 2020-10-21T14:56:54 | 304,967,801 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package application.model;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
@Entity
@Data
public class Producto {
@Id
private Long id;
@Column
private String nombre;
@Column
private float precio;
@JsonIgnore
@OneToMany(mappedBy="cliente")
private List<ProductoCliente> clientes;
public Producto() {
}
public Producto(Long id,String nombre, int precio) {
this.id = id;
this.nombre = nombre;
this.precio = precio;
}
}
| UTF-8 | Java | 675 | java | Producto.java | Java | [] | null | [] | package application.model;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
@Entity
@Data
public class Producto {
@Id
private Long id;
@Column
private String nombre;
@Column
private float precio;
@JsonIgnore
@OneToMany(mappedBy="cliente")
private List<ProductoCliente> clientes;
public Producto() {
}
public Producto(Long id,String nombre, int precio) {
this.id = id;
this.nombre = nombre;
this.precio = precio;
}
}
| 675 | 0.694815 | 0.694815 | 37 | 17.243244 | 15.073524 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.324324 | false | false | 14 |
50ec8e6364352f7465c7f4eb627d0a4381adcbb9 | 20,418,274,569,899 | 9b6d950f26455ae360f6c6bc8902eead63b3797e | /src/main/java/com/hycxkj/postage/mapper/PostageCarryModeMapper.java | d8a3090dcb6319dd7d766640d187114b9da44fe8 | [] | no_license | cspASiTa/diy | https://github.com/cspASiTa/diy | 7d28060cb23a3fcd71d802af8e677e235f80fa46 | 5732dc628f22a83d428e88fcfee90bdce28bbf64 | refs/heads/master | 2020-03-23T12:23:08.649000 | 2018-07-19T10:37:55 | 2018-07-19T10:37:55 | 141,555,463 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hycxkj.postage.mapper;
import com.hycxkj.postage.bean.PostageCarryMode;
import com.hycxkj.postage.bean.PostageCarryModeExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface PostageCarryModeMapper {
long countByExample(PostageCarryModeExample example);
int deleteByExample(PostageCarryModeExample example);
int insert(PostageCarryMode record);
int insertSelective(PostageCarryMode record);
List<PostageCarryMode> selectByExample(PostageCarryModeExample example);
int updateByExampleSelective(@Param("record") PostageCarryMode record, @Param("example") PostageCarryModeExample example);
int updateByExample(@Param("record") PostageCarryMode record, @Param("example") PostageCarryModeExample example);
} | UTF-8 | Java | 787 | java | PostageCarryModeMapper.java | Java | [] | null | [] | package com.hycxkj.postage.mapper;
import com.hycxkj.postage.bean.PostageCarryMode;
import com.hycxkj.postage.bean.PostageCarryModeExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface PostageCarryModeMapper {
long countByExample(PostageCarryModeExample example);
int deleteByExample(PostageCarryModeExample example);
int insert(PostageCarryMode record);
int insertSelective(PostageCarryMode record);
List<PostageCarryMode> selectByExample(PostageCarryModeExample example);
int updateByExampleSelective(@Param("record") PostageCarryMode record, @Param("example") PostageCarryModeExample example);
int updateByExample(@Param("record") PostageCarryMode record, @Param("example") PostageCarryModeExample example);
} | 787 | 0.811944 | 0.811944 | 22 | 34.81818 | 36.723335 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 14 |
f491c60711affbf699e7d0299a352af990e1de4e | 21,887,153,344,980 | a143ee20e7295135c7b81e5fa3ff640a20a4f7fd | /patientInformation/src/main/java/com/patientData/patientInformation/service/IPatientService.java | 9aa191df91369fd09f00024769dcb71ad9ce0bfb | [] | no_license | radiaRD/JavaDA_PROJECT9_Mediscreen | https://github.com/radiaRD/JavaDA_PROJECT9_Mediscreen | 73cfa5f1d25c2e06854748904883aac9fc55fc9b | f830f83a41790f9ac435f63ca0bc8338cbd27d75 | refs/heads/main | 2023-08-01T23:41:11.701000 | 2021-10-05T10:17:40 | 2021-10-05T10:17:40 | 331,974,158 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.patientData.patientInformation.service;
import com.patientData.patientInformation.domain.Patient;
import com.patientData.patientInformation.dto.PatientDto;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.ui.Model;
public interface IPatientService {
static final Logger logger = LogManager.getLogger(IPatientService.class);
String home(Model model, PatientDto patientDto);
void showPatientById(Integer id, Model model, PatientDto patientDto);
String updatePatient(Integer id, PatientDto patientDto, Model model);
String addPatient(PatientDto patientDto, Model model);
String validate(PatientDto patientDto, Model model);
String deletePatient(Integer id, Model model, Patient patient);
}
| UTF-8 | Java | 799 | java | IPatientService.java | Java | [] | null | [] | package com.patientData.patientInformation.service;
import com.patientData.patientInformation.domain.Patient;
import com.patientData.patientInformation.dto.PatientDto;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.ui.Model;
public interface IPatientService {
static final Logger logger = LogManager.getLogger(IPatientService.class);
String home(Model model, PatientDto patientDto);
void showPatientById(Integer id, Model model, PatientDto patientDto);
String updatePatient(Integer id, PatientDto patientDto, Model model);
String addPatient(PatientDto patientDto, Model model);
String validate(PatientDto patientDto, Model model);
String deletePatient(Integer id, Model model, Patient patient);
}
| 799 | 0.79975 | 0.797247 | 25 | 30.959999 | 29.147184 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.88 | false | false | 14 |
72463ed58b963e76916dd0343d90212a67b8a9c1 | 12,738,873,063,325 | a9e7da3027d23a71078d5407eaefcecb3b0b0482 | /src/main/java/com/nju/spider/utils/ChromeUtils.java | d449457128af098bed6115cee491493b064985eb | [] | no_license | yinshunming/spider | https://github.com/yinshunming/spider | c8d992f8db3aaf2285227aaad0040a840ecab922 | 8e069a465632d485f2d953e5542d476bec4e65bb | refs/heads/master | 2023-09-01T00:54:39.887000 | 2023-08-12T14:04:15 | 2023-08-12T14:04:15 | 222,239,315 | 0 | 1 | null | false | 2022-06-21T02:15:49 | 2019-11-17T11:43:46 | 2019-12-24T12:24:35 | 2022-06-21T02:15:46 | 4,845 | 0 | 0 | 5 | Java | false | false | package com.nju.spider.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.File;
/**
* @ClassName ChromeUtils
* @Description TODO
* @Author UPC
* @Date 2019/12/5 21:51
* @Version 1.0
*/
@Slf4j
public class ChromeUtils {
public static String doChromeCrawlWithRetryTimesUsingProxy(String url, int retryTimes) {
for (int i = 0; i < retryTimes; i++) {
String ret = doChromeCrawlUsingProxy(url);
if (StringUtils.isNotBlank(ret)) {
return ret;
}
}
return null;
}
public static String doChromeCrawlUsingProxy(String url) {
return doChromeCrawl(url, true);
}
public static String doChromeCrawlWithRetryTime(String url, int retryTimes) {
for (int i = 0; i < retryTimes; i++) {
String ret = doChromeCrawl(url);
if (StringUtils.isNotBlank(ret)) {
return ret;
}
}
return null;
}
public static String doChromeCrawl(String url) {
return doChromeCrawl(url, false);
}
public static String doChromeCrawl(String url, boolean usingProxy) {
WebDriver driver = null;
try {
ClassLoader classLoader = ChromeUtils.class.getClassLoader();
File file = new File(classLoader.getResource("chromedriver.exe").getFile());
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
ChromeOptions chromeOptions = new ChromeOptions();
//设置为 headless 模式 (必须)
if (usingProxy) {
String proxy_str = HttpUtils.proxyHost + ":" + HttpUtils.proxyPort;
Proxy proxy = new Proxy().setHttpProxy(proxy_str).setSslProxy(proxy_str);
chromeOptions.setProxy(proxy);
}
chromeOptions.addArguments("--headless");
driver = new ChromeDriver(chromeOptions);
driver.get(url);
String pageSource = driver.getPageSource();
return pageSource;
} catch(Exception ex) {
log.error("getting html using chrome encounts error", ex);
} finally {
if (driver != null) {
driver.quit();
}
}
return null;
}
public static void main(String [] args) {
String res = ChromeUtils.doChromeCrawl("https://www.google.com.hk", true);
System.out.println(res);
}
}
| UTF-8 | Java | 2,670 | java | ChromeUtils.java | Java | [
{
"context": "ssName ChromeUtils\n * @Description TODO\n * @Author UPC\n * @Date 2019/12/5 21:51\n * @Version 1.0\n */\n@Slf",
"end": 367,
"score": 0.9996446967124939,
"start": 364,
"tag": "USERNAME",
"value": "UPC"
}
] | null | [] | package com.nju.spider.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.File;
/**
* @ClassName ChromeUtils
* @Description TODO
* @Author UPC
* @Date 2019/12/5 21:51
* @Version 1.0
*/
@Slf4j
public class ChromeUtils {
public static String doChromeCrawlWithRetryTimesUsingProxy(String url, int retryTimes) {
for (int i = 0; i < retryTimes; i++) {
String ret = doChromeCrawlUsingProxy(url);
if (StringUtils.isNotBlank(ret)) {
return ret;
}
}
return null;
}
public static String doChromeCrawlUsingProxy(String url) {
return doChromeCrawl(url, true);
}
public static String doChromeCrawlWithRetryTime(String url, int retryTimes) {
for (int i = 0; i < retryTimes; i++) {
String ret = doChromeCrawl(url);
if (StringUtils.isNotBlank(ret)) {
return ret;
}
}
return null;
}
public static String doChromeCrawl(String url) {
return doChromeCrawl(url, false);
}
public static String doChromeCrawl(String url, boolean usingProxy) {
WebDriver driver = null;
try {
ClassLoader classLoader = ChromeUtils.class.getClassLoader();
File file = new File(classLoader.getResource("chromedriver.exe").getFile());
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
ChromeOptions chromeOptions = new ChromeOptions();
//设置为 headless 模式 (必须)
if (usingProxy) {
String proxy_str = HttpUtils.proxyHost + ":" + HttpUtils.proxyPort;
Proxy proxy = new Proxy().setHttpProxy(proxy_str).setSslProxy(proxy_str);
chromeOptions.setProxy(proxy);
}
chromeOptions.addArguments("--headless");
driver = new ChromeDriver(chromeOptions);
driver.get(url);
String pageSource = driver.getPageSource();
return pageSource;
} catch(Exception ex) {
log.error("getting html using chrome encounts error", ex);
} finally {
if (driver != null) {
driver.quit();
}
}
return null;
}
public static void main(String [] args) {
String res = ChromeUtils.doChromeCrawl("https://www.google.com.hk", true);
System.out.println(res);
}
}
| 2,670 | 0.604827 | 0.597662 | 86 | 29.83721 | 25.663231 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.534884 | false | false | 14 |
8547e1c7257b20d4dbbf6b7428c9ff17146213a7 | 3,985,729,714,597 | a9583f4c200e68706dee5749e8ecdbd276fc9fc3 | /src/main/java/org/kata/sokoban/warehouse/BoardElement.java | 0a3b8acfdb9d321ef240bf3a36ac15fbc466b78c | [] | no_license | IIIRepublica/sokoban | https://github.com/IIIRepublica/sokoban | dc3186d5bbcc9795ca46f3ce568b19a150f7928a | e8c34320717eac0f6eab09831612c20843dd99b4 | refs/heads/master | 2021-01-01T18:11:59.183000 | 2013-11-18T11:55:58 | 2013-11-18T11:55:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.kata.sokoban.warehouse;
public enum BoardElement {
empty, wall, storage;
}
| UTF-8 | Java | 96 | java | BoardElement.java | Java | [] | null | [] | package org.kata.sokoban.warehouse;
public enum BoardElement {
empty, wall, storage;
}
| 96 | 0.708333 | 0.708333 | 6 | 14 | 14.200939 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 14 |
9e2f55d758deba0415191b7af527f790d3e3d018 | 26,886,495,312,368 | 739b2124dde2d8c4ff527254f5b8a08d2c150d01 | /src/main/java/com/xiaoyu/hrm/mapper/IMenuMapper.java | 7fd2c9172e08801b36735bda14b939c9947493e4 | [] | no_license | itqiangyu/xiaoyu-hrm | https://github.com/itqiangyu/xiaoyu-hrm | 4ff843098ea0349d4ec5ecbc3472d0585e241309 | 98e8ab8ca1e084669d58a9fc51f49c7dbb734b42 | refs/heads/master | 2021-12-17T19:48:05.017000 | 2021-12-02T01:21:14 | 2021-12-02T01:21:14 | 248,283,514 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xiaoyu.hrm.mapper;
import com.xiaoyu.hrm.pojo.Menu;
import java.util.List;
/**
* 获取菜单栏信息
*
* @author xiaoyu
* @date 2020/3/18 23:49
*/
public interface IMenuMapper {
/**
* 获取所有菜单栏信息
* @param isPower 是否有权限:1(true,有权限)、0(false,无权限)
* @return
*/
List<Menu> getAllMenus(boolean isPower);
} | UTF-8 | Java | 405 | java | IMenuMapper.java | Java | [
{
"context": "port java.util.List;\n\n/**\n * 获取菜单栏信息\n *\n * @author xiaoyu\n * @date 2020/3/18 23:49\n */\npublic interface IMe",
"end": 125,
"score": 0.9996089935302734,
"start": 119,
"tag": "USERNAME",
"value": "xiaoyu"
}
] | null | [] | package com.xiaoyu.hrm.mapper;
import com.xiaoyu.hrm.pojo.Menu;
import java.util.List;
/**
* 获取菜单栏信息
*
* @author xiaoyu
* @date 2020/3/18 23:49
*/
public interface IMenuMapper {
/**
* 获取所有菜单栏信息
* @param isPower 是否有权限:1(true,有权限)、0(false,无权限)
* @return
*/
List<Menu> getAllMenus(boolean isPower);
} | 405 | 0.629851 | 0.591045 | 22 | 14.272727 | 15.082144 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | false | false | 14 |
184fdb94803a451e7353ceb637be644fdb0415f9 | 20,590,073,220,919 | 2eb61718f41ff06aba04eb3cbbfaa1ee3fb4e7e1 | /src/main/java/com/equator/leetcode/round1/sword/Problem14_2.java | 1959da866f3c7830c26b380f983f211332bbcb04 | [] | no_license | libinkai/superme | https://github.com/libinkai/superme | aa04c4e0a85eb29f30ed261bd28c1928e28d59ae | 25b9bd3fc0fa3c3516478b9799bf4dc4c1a1375f | refs/heads/master | 2023-02-06T19:39:49.881000 | 2023-01-30T00:48:20 | 2023-01-30T00:48:20 | 224,184,985 | 0 | 0 | null | false | 2020-10-13T17:46:18 | 2019-11-26T12:15:16 | 2020-06-06T02:34:42 | 2020-10-13T17:46:17 | 2,370 | 0 | 0 | 1 | Java | false | false | package com.equator.leetcode.round1.sword;
/**
* @Author: Equator
* @Date: 2020/2/16 12:21
**/
public class Problem14_2 {
public int cuttingRope(int n) {
if (n <= 3) {
return n - 1;
}
long res = 1;
int mod = 1000000007;
while (n > 4) {
res *= 3;
res %= mod;
n -= 3;
}
return (int) (res * n % mod);
}
}
| UTF-8 | Java | 419 | java | Problem14_2.java | Java | [
{
"context": "om.equator.leetcode.round1.sword;\n\n/**\n * @Author: Equator\n * @Date: 2020/2/16 12:21\n **/\n\npublic class Prob",
"end": 67,
"score": 0.9300380945205688,
"start": 60,
"tag": "USERNAME",
"value": "Equator"
}
] | null | [] | package com.equator.leetcode.round1.sword;
/**
* @Author: Equator
* @Date: 2020/2/16 12:21
**/
public class Problem14_2 {
public int cuttingRope(int n) {
if (n <= 3) {
return n - 1;
}
long res = 1;
int mod = 1000000007;
while (n > 4) {
res *= 3;
res %= mod;
n -= 3;
}
return (int) (res * n % mod);
}
}
| 419 | 0.429594 | 0.355609 | 22 | 18.045454 | 12.204609 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 14 |
3bd48efa8b379dbdb7872ee58ace5f714e6a9ffc | 4,836,133,186,321 | e84a623636c841eb9c3e502bfdc770fe3db1e0a5 | /TeamCode/src/main/java/org/firstinspires/ftc/teamcode/UtilitiesandMic/Colors.java | ff328497ed5d28f0345656d4c07b1b6e223e543c | [
"BSD-3-Clause"
] | permissive | 7959/7959-Relic-Recovery | https://github.com/7959/7959-Relic-Recovery | 80d41685894639479d69bfcfce97fb8bf125e6b8 | 81195e978bfe3facfc041553d948e99ce27d5e74 | refs/heads/master | 2021-09-17T03:05:08.403000 | 2017-11-07T14:22:17 | 2017-11-07T14:22:17 | 103,028,398 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.firstinspires.ftc.teamcode.UtilitiesandMic;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Animatable;
import android.view.View;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
/**
* Created by Robi on 10/12/2017.
*/
@Autonomous(name = "COLORS")
public class Colors extends LinearOpMode {
float COLOOOOORS[] = {0F, 0F, 0F};
final float COLOOOOORStoreference[] = COLOOOOORS;
int y = randstart();
int x = randstart();
int z = randstart();
public void runOpMode() throws InterruptedException {
int relativeLayoutId = hardwareMap.appContext.getResources().getIdentifier("RelativeLayout", "id", hardwareMap.appContext.getPackageName());
final View relativeLayout = ((Activity) hardwareMap.appContext).findViewById(relativeLayoutId);
waitForStart();
while(opModeIsActive()){
Color.RGBToHSV((int) (Math.random()*5*255),
(int) (Math.random()*5*255),
(int) ((Math.random()*5* 255)),
COLOOOOORS);
relativeLayout.post(new Runnable() {
public void run() {
relativeLayout.setBackgroundColor(Color.HSVToColor(0xff, COLOOOOORStoreference));
}
});
x = scale(x);
y = scale(y);
z = scale(z);
sleep(250);
}
relativeLayout.post(new Runnable() {
public void run() {
relativeLayout.setBackgroundColor(Color.TRANSPARENT);
}
});
Animatable j;
}
int randstart(){
return (int)Math.random() * 5;
}
int scale(int input){
if(input >= 5){
return 1;
} else
return input+1;
}
}
| UTF-8 | Java | 1,843 | java | Colors.java | Java | [
{
"context": ".eventloop.opmode.LinearOpMode;\n\n/**\n * Created by Robi on 10/12/2017.\n */\n@Autonomous(name = \"COLORS\")\np",
"end": 332,
"score": 0.9954228401184082,
"start": 328,
"tag": "NAME",
"value": "Robi"
}
] | null | [] | package org.firstinspires.ftc.teamcode.UtilitiesandMic;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Animatable;
import android.view.View;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
/**
* Created by Robi on 10/12/2017.
*/
@Autonomous(name = "COLORS")
public class Colors extends LinearOpMode {
float COLOOOOORS[] = {0F, 0F, 0F};
final float COLOOOOORStoreference[] = COLOOOOORS;
int y = randstart();
int x = randstart();
int z = randstart();
public void runOpMode() throws InterruptedException {
int relativeLayoutId = hardwareMap.appContext.getResources().getIdentifier("RelativeLayout", "id", hardwareMap.appContext.getPackageName());
final View relativeLayout = ((Activity) hardwareMap.appContext).findViewById(relativeLayoutId);
waitForStart();
while(opModeIsActive()){
Color.RGBToHSV((int) (Math.random()*5*255),
(int) (Math.random()*5*255),
(int) ((Math.random()*5* 255)),
COLOOOOORS);
relativeLayout.post(new Runnable() {
public void run() {
relativeLayout.setBackgroundColor(Color.HSVToColor(0xff, COLOOOOORStoreference));
}
});
x = scale(x);
y = scale(y);
z = scale(z);
sleep(250);
}
relativeLayout.post(new Runnable() {
public void run() {
relativeLayout.setBackgroundColor(Color.TRANSPARENT);
}
});
Animatable j;
}
int randstart(){
return (int)Math.random() * 5;
}
int scale(int input){
if(input >= 5){
return 1;
} else
return input+1;
}
}
| 1,843 | 0.603364 | 0.586544 | 66 | 26.924242 | 27.17079 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 14 |
5e9309c2bb23058b2892f589bcfbd7c837fd6956 | 34,737,695,543,480 | 08d9c714e238cfee8f6d1cacb3e0bb9385c321dd | /01/BankBusiness/app/src/androidTest/java/android/examples/bankbusiness/AccountTest.java | 2be2310ebe077374eb44f4797110ad89627d89dd | [] | no_license | urstory/AndroidTDD | https://github.com/urstory/AndroidTDD | a9f850f0c6e82a0f790417d1175e67d737f70083 | d2bddd07e12e84a2a9fedb050ba8a15f02eb3cec | refs/heads/master | 2020-01-23T00:39:26.374000 | 2015-05-07T05:12:22 | 2015-05-07T05:12:22 | 35,160,027 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package android.examples.bankbusiness;
import junit.framework.TestCase;
/**
* Created by kicks_000 on 2015-05-03.
*/
public class AccountTest extends TestCase {
private Account account;
public void setUp() throws Exception {
account = new Account(10000);
}
public void testAccount() throws Exception {
// Account account = this.account;
//assertFalse(true);
}
public void testGetBalance() throws Exception {
//Account account = new Account( 10000 );
// if( account.getBalance() != 10000 ) {
// fail();
// }
assertEquals("10000원으로 계좌 생성 후 잔고 조회", 10000, account.getBalance());
account = new Account( 1000 );
// if( account.getBalance() != 1000 ) {
// fail();
// }
assertEquals("1000원으로 계좌 생성 후 잔고 조회", 1000, account.getBalance());
account = new Account( 0 );
// if( account.getBalance() != 0 ) {
// fail();
// }
assertEquals("1000원으로 계좌 생성 후 잔고 조회", 0, account.getBalance());
}
public void testDeposit() throws Exception {
//Account account = new Account( 10000 );
account.deposit( 1000 );
assertEquals( "잔고 10000원 통장에 1000원 입금한 결과:", 11000, account.getBalance() );
}
public void testWithdraw() throws Exception {
//Account account = new Account( 10000 );
account.withdraw( 1000 );
assertEquals( "잔고 10000원 통장에 1000원 출금한 결과:", 9000, account.getBalance() );
}
}
| UTF-8 | Java | 1,685 | java | AccountTest.java | Java | [
{
"context": "rt junit.framework.TestCase;\r\n\r\n/**\r\n * Created by kicks_000 on 2015-05-03.\r\n */\r\npublic class AccountTest ext",
"end": 106,
"score": 0.9994466304779053,
"start": 97,
"tag": "USERNAME",
"value": "kicks_000"
}
] | null | [] | package android.examples.bankbusiness;
import junit.framework.TestCase;
/**
* Created by kicks_000 on 2015-05-03.
*/
public class AccountTest extends TestCase {
private Account account;
public void setUp() throws Exception {
account = new Account(10000);
}
public void testAccount() throws Exception {
// Account account = this.account;
//assertFalse(true);
}
public void testGetBalance() throws Exception {
//Account account = new Account( 10000 );
// if( account.getBalance() != 10000 ) {
// fail();
// }
assertEquals("10000원으로 계좌 생성 후 잔고 조회", 10000, account.getBalance());
account = new Account( 1000 );
// if( account.getBalance() != 1000 ) {
// fail();
// }
assertEquals("1000원으로 계좌 생성 후 잔고 조회", 1000, account.getBalance());
account = new Account( 0 );
// if( account.getBalance() != 0 ) {
// fail();
// }
assertEquals("1000원으로 계좌 생성 후 잔고 조회", 0, account.getBalance());
}
public void testDeposit() throws Exception {
//Account account = new Account( 10000 );
account.deposit( 1000 );
assertEquals( "잔고 10000원 통장에 1000원 입금한 결과:", 11000, account.getBalance() );
}
public void testWithdraw() throws Exception {
//Account account = new Account( 10000 );
account.withdraw( 1000 );
assertEquals( "잔고 10000원 통장에 1000원 출금한 결과:", 9000, account.getBalance() );
}
}
| 1,685 | 0.564856 | 0.498403 | 53 | 27.528301 | 24.405075 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.584906 | false | false | 14 |
ff3b1223d5e13b448a9759713cd10814b87a9331 | 38,963,943,357,409 | f32cfb31bbd176b2bfb5ef4c80af0a64948247cf | /src/main/java/pe/com/sedapal/asi/model/Contacto.java | eed1b5f992d803d731d972308bc558257d57da2d | [] | no_license | cvalenciap/CV_dummy_as | https://github.com/cvalenciap/CV_dummy_as | d3ab5e65033a3654a343f41b12ce7ff870aa9fd5 | 8dabc946d865bde87df6dd2215bed76d49e60ab0 | refs/heads/master | 2023-04-27T09:56:48.962000 | 2021-05-06T05:45:42 | 2021-05-06T05:45:42 | 364,798,109 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pe.com.sedapal.asi.model;
import java.sql.Date;
public class Contacto {
private Long n_id_cont;
private Long n_cod_area;
private Long naresuperior;
private String v_nomb_cont;
private String v_tele_cont;
private String gerencia;
private String equipo;
private Long n_estado;
private String a_v_usucre;
private Date a_d_feccre;
private String a_v_usumod;
private Date a_d_fecmod;
private String a_v_nomprg;
public Long getN_id_cont() {
return n_id_cont;
}
public void setN_id_cont(Long n_id_cont) {
this.n_id_cont = n_id_cont;
}
public Long getN_cod_area() {
return n_cod_area;
}
public void setN_cod_area(Long n_cod_area) {
this.n_cod_area = n_cod_area;
}
public String getV_nomb_cont() {
return v_nomb_cont;
}
public void setV_nomb_cont(String v_nomb_cont) {
this.v_nomb_cont = v_nomb_cont;
}
public String getV_tele_cont() {
return v_tele_cont;
}
public void setV_tele_cont(String v_tele_cont) {
this.v_tele_cont = v_tele_cont;
}
public Long getN_estado() {
return n_estado;
}
public void setN_estado(Long n_estado) {
this.n_estado = n_estado;
}
public String getA_v_usucre() {
return a_v_usucre;
}
public void setA_v_usucre(String a_v_usucre) {
this.a_v_usucre = a_v_usucre;
}
public Date getA_d_feccre() {
return a_d_feccre;
}
public void setA_d_feccre(Date a_d_feccre) {
this.a_d_feccre = a_d_feccre;
}
public String getA_v_usumod() {
return a_v_usumod;
}
public void setA_v_usumod(String a_v_usumod) {
this.a_v_usumod = a_v_usumod;
}
public Date getA_d_fecmod() {
return a_d_fecmod;
}
public void setA_d_fecmod(Date a_d_fecmod) {
this.a_d_fecmod = a_d_fecmod;
}
public String getA_v_nomprg() {
return a_v_nomprg;
}
public void setA_v_nomprg(String a_v_nomprg) {
this.a_v_nomprg = a_v_nomprg;
}
public Long getNaresuperior() {
return naresuperior;
}
public void setNaresuperior(Long naresuperior) {
this.naresuperior = naresuperior;
}
public String getGerencia() {
return gerencia;
}
public void setGerencia(String gerencia) {
this.gerencia = gerencia;
}
public String getEquipo() {
return equipo;
}
public void setEquipo(String equipo) {
this.equipo = equipo;
}
}
| UTF-8 | Java | 2,204 | java | Contacto.java | Java | [] | null | [] | package pe.com.sedapal.asi.model;
import java.sql.Date;
public class Contacto {
private Long n_id_cont;
private Long n_cod_area;
private Long naresuperior;
private String v_nomb_cont;
private String v_tele_cont;
private String gerencia;
private String equipo;
private Long n_estado;
private String a_v_usucre;
private Date a_d_feccre;
private String a_v_usumod;
private Date a_d_fecmod;
private String a_v_nomprg;
public Long getN_id_cont() {
return n_id_cont;
}
public void setN_id_cont(Long n_id_cont) {
this.n_id_cont = n_id_cont;
}
public Long getN_cod_area() {
return n_cod_area;
}
public void setN_cod_area(Long n_cod_area) {
this.n_cod_area = n_cod_area;
}
public String getV_nomb_cont() {
return v_nomb_cont;
}
public void setV_nomb_cont(String v_nomb_cont) {
this.v_nomb_cont = v_nomb_cont;
}
public String getV_tele_cont() {
return v_tele_cont;
}
public void setV_tele_cont(String v_tele_cont) {
this.v_tele_cont = v_tele_cont;
}
public Long getN_estado() {
return n_estado;
}
public void setN_estado(Long n_estado) {
this.n_estado = n_estado;
}
public String getA_v_usucre() {
return a_v_usucre;
}
public void setA_v_usucre(String a_v_usucre) {
this.a_v_usucre = a_v_usucre;
}
public Date getA_d_feccre() {
return a_d_feccre;
}
public void setA_d_feccre(Date a_d_feccre) {
this.a_d_feccre = a_d_feccre;
}
public String getA_v_usumod() {
return a_v_usumod;
}
public void setA_v_usumod(String a_v_usumod) {
this.a_v_usumod = a_v_usumod;
}
public Date getA_d_fecmod() {
return a_d_fecmod;
}
public void setA_d_fecmod(Date a_d_fecmod) {
this.a_d_fecmod = a_d_fecmod;
}
public String getA_v_nomprg() {
return a_v_nomprg;
}
public void setA_v_nomprg(String a_v_nomprg) {
this.a_v_nomprg = a_v_nomprg;
}
public Long getNaresuperior() {
return naresuperior;
}
public void setNaresuperior(Long naresuperior) {
this.naresuperior = naresuperior;
}
public String getGerencia() {
return gerencia;
}
public void setGerencia(String gerencia) {
this.gerencia = gerencia;
}
public String getEquipo() {
return equipo;
}
public void setEquipo(String equipo) {
this.equipo = equipo;
}
}
| 2,204 | 0.685118 | 0.685118 | 99 | 21.262627 | 14.960275 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.606061 | false | false | 14 |
dab7f4b8e97a7e2d9f29b28323b3d444f8353245 | 8,624,294,334,458 | a879515ccd1146c0125e1bee63f18fb542200f5d | /src/main/java/com/cpg/movieticketbooking/dao/AdminDao.java | 910ddc21e10c8c5ea122d556e100265cddd8ce9b | [] | no_license | vaibhav63/MovieTicketBookingSystem | https://github.com/vaibhav63/MovieTicketBookingSystem | 0eccf312a169cbbe86c06494cba1c193de152a1a | 1073740cf6f250df7ae8c418023461c4f1721734 | refs/heads/master | 2021-01-16T13:07:09.917000 | 2020-02-27T04:32:30 | 2020-02-27T04:32:30 | 243,133,075 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cpg.movieticketbooking.dao;
import com.cpg.movieticketbooking.beans.Movie;
import com.cpg.movieticketbooking.beans.Screen;
import com.cpg.movieticketbooking.beans.Show;
import com.cpg.movieticketbooking.beans.Theater;
public interface AdminDao {
void addTheater(Theater theater) ;
Boolean deleteTheater(Integer theaterId);
void addMovie(Movie movie);
Boolean deleteMovie(Integer movieId);
void addScreen(Screen screen);
Boolean deleteScreen(Integer screenId) ;
void addShow(Show show);
Boolean deleteShow(Long showId);
}
| UTF-8 | Java | 573 | java | AdminDao.java | Java | [] | null | [] | package com.cpg.movieticketbooking.dao;
import com.cpg.movieticketbooking.beans.Movie;
import com.cpg.movieticketbooking.beans.Screen;
import com.cpg.movieticketbooking.beans.Show;
import com.cpg.movieticketbooking.beans.Theater;
public interface AdminDao {
void addTheater(Theater theater) ;
Boolean deleteTheater(Integer theaterId);
void addMovie(Movie movie);
Boolean deleteMovie(Integer movieId);
void addScreen(Screen screen);
Boolean deleteScreen(Integer screenId) ;
void addShow(Show show);
Boolean deleteShow(Long showId);
}
| 573 | 0.771379 | 0.771379 | 26 | 21.038462 | 19.093859 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.115385 | false | false | 14 |
dc90e4a2833b3cf11ba4ad2e23c3e587b1ae47a4 | 13,091,060,336,026 | 87e352d937c15f8f3ee4967bf886872c0374300c | /src/test/java/com/hcl/hackathon/fullstack/resource/ResourceUnitTest.java | ee7256df3c849b9f462325fd7ec4db850e59842b | [] | no_license | stanislaska/full-stack-developer | https://github.com/stanislaska/full-stack-developer | 46fdfb5a0e365994742f48aa5a4706ff526cc28e | f9a42a7c4eacff65aa4e38c6897da0b5e859d7a6 | refs/heads/master | 2020-04-12T23:59:28.279000 | 2018-12-24T07:08:59 | 2018-12-24T07:08:59 | 162,835,303 | 0 | 0 | null | true | 2018-12-22T18:48:56 | 2018-12-22T18:48:55 | 2018-10-25T04:43:38 | 2018-10-25T04:43:37 | 7 | 0 | 0 | 0 | null | false | null | package com.hcl.hackathon.fullstack.resource;
import org.junit.After;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ResourceUnitTest {
@Mock
private Resource resource;
@Before
public void tearUp() {
// - Nop
}
@After
public void tearDown() {
reset(resource); // rollback to initial state ..
}
@Test
public void shouldNotBeNull() {
assertNotNull("Unexpecting this auto injected resource to be null", resource);
}
@Test
public void expectResourceHrefToBeApi() {
when(resource.getHref()).thenReturn("/api/v1/any");
assertEquals("Expecting the resource href to be equals", "/api/v1/any", resource.getHref());
verify(resource, atLeast(1)).getHref();
}
@Test
public void shouldVersionToBeEquals() {
when(resource.getVersion()).thenReturn(Version.V1);
assertEquals("Expecting the resource href to be equals", Version.V1, resource.getVersion());
verify(resource, atLeast(1)).getVersion();
}
} | UTF-8 | Java | 1,255 | java | ResourceUnitTest.java | Java | [] | null | [] | package com.hcl.hackathon.fullstack.resource;
import org.junit.After;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ResourceUnitTest {
@Mock
private Resource resource;
@Before
public void tearUp() {
// - Nop
}
@After
public void tearDown() {
reset(resource); // rollback to initial state ..
}
@Test
public void shouldNotBeNull() {
assertNotNull("Unexpecting this auto injected resource to be null", resource);
}
@Test
public void expectResourceHrefToBeApi() {
when(resource.getHref()).thenReturn("/api/v1/any");
assertEquals("Expecting the resource href to be equals", "/api/v1/any", resource.getHref());
verify(resource, atLeast(1)).getHref();
}
@Test
public void shouldVersionToBeEquals() {
when(resource.getVersion()).thenReturn(Version.V1);
assertEquals("Expecting the resource href to be equals", Version.V1, resource.getVersion());
verify(resource, atLeast(1)).getVersion();
}
} | 1,255 | 0.680478 | 0.675697 | 45 | 26.911112 | 25.669542 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 14 |
13814690995ee8db8f192c90641a41692c9ff0b1 | 7,696,581,401,325 | 1273c5df68a3abedf52e15f14567941e4ba991ff | /src/com/recargabilhete/entity/Usuario.java | 1cff0e4b88b3fc83bb4e375483a091647bce0e33 | [] | no_license | Satanihell/recarga-bilhete | https://github.com/Satanihell/recarga-bilhete | 92e1027d4541f709ef25fbb87a6be1f96904deef | 69de7dd1f926cefffb31d98f2d420b850a8cf758 | refs/heads/master | 2020-08-28T16:23:23.003000 | 2019-11-27T20:03:24 | 2019-11-27T20:03:24 | 217,751,668 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.recargabilhete.entity;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
public class Usuario {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long idUsuario;
private String nome;
@Temporal(TemporalType.DATE)
private Date dataNasc = new Date();
private long cpf;
private long rg;
private String endereco;
public long getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(long idUsuario) {
this.idUsuario = idUsuario;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Date getDataNasc() {
return dataNasc;
}
public void setDataNasc(Date dataNasc) {
this.dataNasc = dataNasc;
}
public long getCpf() {
return cpf;
}
public void setCpf(long cpf) {
this.cpf = cpf;
}
public long getRg() {
return rg;
}
public void setRg(long rg) {
this.rg = rg;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
@Override
public boolean equals(Object obj) {
if (obj != null && obj instanceof Usuario) {
Usuario usuario = (Usuario) obj;
return usuario.getIdUsuario() == this.getIdUsuario();
}
return false;
}
@Override
public String toString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
StringBuffer sb = new StringBuffer();
sb.append("IdUsuario" + getIdUsuario());
sb.append("Nome" + getNome());
sb.append("DataNasc" + sdf.format(getDataNasc()));
sb.append("CPF" + getCpf());
sb.append("RG" + getRg());
sb.append("Endereco" + getEndereco());
return sb.toString();
}
}
| UTF-8 | Java | 1,874 | java | Usuario.java | Java | [] | null | [] | package com.recargabilhete.entity;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
public class Usuario {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long idUsuario;
private String nome;
@Temporal(TemporalType.DATE)
private Date dataNasc = new Date();
private long cpf;
private long rg;
private String endereco;
public long getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(long idUsuario) {
this.idUsuario = idUsuario;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Date getDataNasc() {
return dataNasc;
}
public void setDataNasc(Date dataNasc) {
this.dataNasc = dataNasc;
}
public long getCpf() {
return cpf;
}
public void setCpf(long cpf) {
this.cpf = cpf;
}
public long getRg() {
return rg;
}
public void setRg(long rg) {
this.rg = rg;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
@Override
public boolean equals(Object obj) {
if (obj != null && obj instanceof Usuario) {
Usuario usuario = (Usuario) obj;
return usuario.getIdUsuario() == this.getIdUsuario();
}
return false;
}
@Override
public String toString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
StringBuffer sb = new StringBuffer();
sb.append("IdUsuario" + getIdUsuario());
sb.append("Nome" + getNome());
sb.append("DataNasc" + sdf.format(getDataNasc()));
sb.append("CPF" + getCpf());
sb.append("RG" + getRg());
sb.append("Endereco" + getEndereco());
return sb.toString();
}
}
| 1,874 | 0.707577 | 0.707577 | 96 | 18.520834 | 16.40946 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.375 | false | false | 14 |
099301239e8a401bbedd8ec180ab4df3af6e3470 | 1,477,468,768,776 | 08bdd164c174d24e69be25bf952322b84573f216 | /opencores/client/foundation classes/j2sdk-1_4_2-src-scsl/j2se/src/share/classes/com/sun/jdi/event/MethodExitEvent.java | a1c6b174531af60b73adccc4924d07992af1b158 | [] | no_license | hagyhang/myforthprocessor | https://github.com/hagyhang/myforthprocessor | 1861dcabcf2aeccf0ab49791f510863d97d89a77 | 210083fe71c39fa5d92f1f1acb62392a7f77aa9e | refs/heads/master | 2021-05-28T01:42:50.538000 | 2014-07-17T14:14:33 | 2014-07-17T14:14:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* @(#)MethodExitEvent.java 1.10 03/01/23
*
* Copyright 2003 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.jdi.event;
import com.sun.jdi.*;
/**
* Notification of a method return in the target VM. This event
* is generated after all code in the method has executed, but the
* location of this event is the last executed location in the method.
* Method exit events are generated for both native and non-native
* methods. Method exit events are not generated if the method terminates
* with a thrown exception.
*
* @see EventQueue
*
* @author Robert Field
* @since 1.3
*/
public interface MethodExitEvent extends LocatableEvent {
/**
* Returns the method that was exited.
*
* @return a {@link Method} which mirrors the method that was exited.
* @throws ObjectCollectedException may be thrown if class
* has been garbage collected.
*/
public Method method();
}
| UTF-8 | Java | 1,008 | java | MethodExitEvent.java | Java | [
{
"context": "wn exception. \n *\n * @see EventQueue\n *\n * @author Robert Field\n * @since 1.3\n */\npublic interface MethodExitEve",
"end": 659,
"score": 0.999841034412384,
"start": 647,
"tag": "NAME",
"value": "Robert Field"
}
] | null | [] | /*
* @(#)MethodExitEvent.java 1.10 03/01/23
*
* Copyright 2003 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.jdi.event;
import com.sun.jdi.*;
/**
* Notification of a method return in the target VM. This event
* is generated after all code in the method has executed, but the
* location of this event is the last executed location in the method.
* Method exit events are generated for both native and non-native
* methods. Method exit events are not generated if the method terminates
* with a thrown exception.
*
* @see EventQueue
*
* @author <NAME>
* @since 1.3
*/
public interface MethodExitEvent extends LocatableEvent {
/**
* Returns the method that was exited.
*
* @return a {@link Method} which mirrors the method that was exited.
* @throws ObjectCollectedException may be thrown if class
* has been garbage collected.
*/
public Method method();
}
| 1,002 | 0.702381 | 0.6875 | 35 | 27.771429 | 26.872276 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.171429 | false | false | 14 |
c1fede660deaa833b5da6b2cd80ed0f1388e9382 | 8,710,193,679,600 | 3bef4e878aed9dcc699936a404141690ac54f401 | /app/src/main/java/www/besolution/hatley/views/available_order/order_info/order_info.java | fa420a4ef29099e836b7b9eb801857e154c871c3 | [] | no_license | aboelrar/hatley_be | https://github.com/aboelrar/hatley_be | 7ce3b4d9316e43289b2c55c460f70656d0972e1d | 4cb11c4dad917a6a5b012702173d409d45d4a8de | refs/heads/master | 2020-08-10T00:29:09.694000 | 2019-12-04T15:28:06 | 2019-12-04T15:28:06 | 214,209,841 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package www.besolution.hatley.views.available_order.order_info;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.VolleyError;
import es.dmoral.toasty.Toasty;
import www.besolution.hatley.NetworkLayer.Apicalls;
import www.besolution.hatley.NetworkLayer.NetworkInterface;
import www.besolution.hatley.NetworkLayer.ResponseModel;
import www.besolution.hatley.local_data.saved_data;
import www.besolution.hatley.local_data.send_data;
import www.besolution.hatley.views.add_new_place.add_new_place;
import www.besolution.hatley.views.available_order.available_order;
import www.besolution.hatley.views.login.login;
import www.besolution.hatley.views.notifcation.my_notifcation;
import www.besolution.hatley.views.request_page.request_page;
import com.besolution.hatley.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONException;
import java.util.Calendar;
public class order_info implements NetworkInterface, OnMapReadyCallback {
String name;
Context context;
ProgressDialog pd;
public void dialog(final Context context, int resource, double widthh, String name, int stars,
String orders_count, String order_name, String from_place, String to_place, double order_location_lat,
double order_location_long, double client_location_lat, double client_location_long, final int offer_id, final int star_id) {
this.name = name;
this.context = context;
final Dialog dialog = new Dialog(context);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(resource);
int width = (int) (context.getResources().getDisplayMetrics().widthPixels * widthh);
int height = android.view.WindowManager.LayoutParams.WRAP_CONTENT;
dialog.getWindow().setLayout(width, height);
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
SupportMapFragment supportMapFragment = (SupportMapFragment) ((AppCompatActivity) context).getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
//SET USERNAME
TextView username = (TextView) dialog.findViewById(R.id.username);
username.setText(name);
//SET RATING
RatingBar rating = (RatingBar) dialog.findViewById(R.id.ratings);
rating.setRating(stars);
//ORDERS COUNT
TextView orderscount = (TextView) dialog.findViewById(R.id.orderscount);
orderscount.setText(orders_count);
//SET ORDER NAME
TextView ordername = (TextView) dialog.findViewById(R.id.order_name);
ordername.setText(order_name);
//SET FROM
TextView from = (TextView) dialog.findViewById(R.id.from);
from.setText(from_place);
//SET TO
TextView to = (TextView) dialog.findViewById(R.id.to);
to.setText(to_place);
//ARRIVAL TIME
final EditText arrival_time = (EditText) dialog.findViewById(R.id.expected_arrival_time);
//EXPECTED PRICE
final EditText expected_price = (EditText) dialog.findViewById(R.id.expected_price);
//SEND OFFER
Button send_offer = (Button) dialog.findViewById(R.id.create_offer);
send_offer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (arrival_time.getText().toString().equals("")) {
Toasty.error(context, "Please enter delivery time", Toast.LENGTH_LONG).show();
} else if (expected_price.getText().toString().equals("")) {
Toasty.error(context, "Please enter expected price", Toast.LENGTH_LONG).show();
} else {
saved_data saved_data = new saved_data();
new Apicalls(context, order_info.this).Submit_Offer(saved_data.get_userid(context), String.valueOf(offer_id),
arrival_time.getText().toString(),
expected_price.getText().toString());
pd = new ProgressDialog(context);
pd.setMessage("Loading...");
pd.show();
}
}
});
//CLOSE OFFER
ImageView cancel = (ImageView) dialog.findViewById(R.id.cancel);
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
context.startActivity(new Intent(context, available_order.class));
((AppCompatActivity) context).finish();
}
});
//ARRIVAL TIME
arrival_time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
get_date_picker(arrival_time);
}
});
dialog.show();
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
@Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
context.startActivity(new Intent(context,available_order.class));
}
return true;
}
});
}
@Override
public void OnStart() {
}
@Override
public void OnResponse(ResponseModel model) {
Toasty.success(context, "Offer Submitted Successfully", Toast.LENGTH_LONG).show();
context.startActivity(new Intent(context, my_notifcation.class));
send_data.ADD_CLIENT_NAME(context, name);
pd.cancel();
}
@Override
public void OnError(VolleyError error) {
pd.cancel();
Toasty.error(context, "Offer Not Sent.", Toast.LENGTH_LONG).show();
}
@Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(30.077899, 31.342715);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("order location"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 12.0f));
}
//GET DATE PICKER
void get_date_picker(EditText arrival_time) {
// TODO Auto-generated method stub
//To show current date in the datepicker
Calendar mcurrentDate = Calendar.getInstance();
int mYear = mcurrentDate.get(Calendar.YEAR);
int mMonth = mcurrentDate.get(Calendar.MONTH);
int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker;
mDatePicker = new DatePickerDialog(context, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
// TODO Auto-generated method stub
/* Your code to get date and time */
selectedmonth = selectedmonth + 1;
//GET TIME PICKER
get_time_picker(selectedyear, selectedmonth, selectedday, arrival_time);
}
}, mYear, mMonth, mDay);
mDatePicker.setTitle("Select Date");
mDatePicker.show();
}
//GET TIME PICKER
void get_time_picker(int selectedyear, int selectedmonth, int selectedday, EditText arrival_time) {
// TODO Auto-generated method stub
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(context, R.style.DialogTheme, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
arrival_time.setText(selectedyear + "-" + selectedmonth + "-" + selectedday + " " + selectedHour + ":" + selectedMinute + ":" + "00");
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
}
| UTF-8 | Java | 9,378 | java | order_info.java | Java | [
{
"context": "ViewById(R.id.username);\n username.setText(name);\n //SET RATING\n RatingBar rating =",
"end": 3229,
"score": 0.7796608209609985,
"start": 3225,
"tag": "NAME",
"value": "name"
}
] | null | [] | package www.besolution.hatley.views.available_order.order_info;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.VolleyError;
import es.dmoral.toasty.Toasty;
import www.besolution.hatley.NetworkLayer.Apicalls;
import www.besolution.hatley.NetworkLayer.NetworkInterface;
import www.besolution.hatley.NetworkLayer.ResponseModel;
import www.besolution.hatley.local_data.saved_data;
import www.besolution.hatley.local_data.send_data;
import www.besolution.hatley.views.add_new_place.add_new_place;
import www.besolution.hatley.views.available_order.available_order;
import www.besolution.hatley.views.login.login;
import www.besolution.hatley.views.notifcation.my_notifcation;
import www.besolution.hatley.views.request_page.request_page;
import com.besolution.hatley.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONException;
import java.util.Calendar;
public class order_info implements NetworkInterface, OnMapReadyCallback {
String name;
Context context;
ProgressDialog pd;
public void dialog(final Context context, int resource, double widthh, String name, int stars,
String orders_count, String order_name, String from_place, String to_place, double order_location_lat,
double order_location_long, double client_location_lat, double client_location_long, final int offer_id, final int star_id) {
this.name = name;
this.context = context;
final Dialog dialog = new Dialog(context);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(resource);
int width = (int) (context.getResources().getDisplayMetrics().widthPixels * widthh);
int height = android.view.WindowManager.LayoutParams.WRAP_CONTENT;
dialog.getWindow().setLayout(width, height);
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
SupportMapFragment supportMapFragment = (SupportMapFragment) ((AppCompatActivity) context).getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
//SET USERNAME
TextView username = (TextView) dialog.findViewById(R.id.username);
username.setText(name);
//SET RATING
RatingBar rating = (RatingBar) dialog.findViewById(R.id.ratings);
rating.setRating(stars);
//ORDERS COUNT
TextView orderscount = (TextView) dialog.findViewById(R.id.orderscount);
orderscount.setText(orders_count);
//SET ORDER NAME
TextView ordername = (TextView) dialog.findViewById(R.id.order_name);
ordername.setText(order_name);
//SET FROM
TextView from = (TextView) dialog.findViewById(R.id.from);
from.setText(from_place);
//SET TO
TextView to = (TextView) dialog.findViewById(R.id.to);
to.setText(to_place);
//ARRIVAL TIME
final EditText arrival_time = (EditText) dialog.findViewById(R.id.expected_arrival_time);
//EXPECTED PRICE
final EditText expected_price = (EditText) dialog.findViewById(R.id.expected_price);
//SEND OFFER
Button send_offer = (Button) dialog.findViewById(R.id.create_offer);
send_offer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (arrival_time.getText().toString().equals("")) {
Toasty.error(context, "Please enter delivery time", Toast.LENGTH_LONG).show();
} else if (expected_price.getText().toString().equals("")) {
Toasty.error(context, "Please enter expected price", Toast.LENGTH_LONG).show();
} else {
saved_data saved_data = new saved_data();
new Apicalls(context, order_info.this).Submit_Offer(saved_data.get_userid(context), String.valueOf(offer_id),
arrival_time.getText().toString(),
expected_price.getText().toString());
pd = new ProgressDialog(context);
pd.setMessage("Loading...");
pd.show();
}
}
});
//CLOSE OFFER
ImageView cancel = (ImageView) dialog.findViewById(R.id.cancel);
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
context.startActivity(new Intent(context, available_order.class));
((AppCompatActivity) context).finish();
}
});
//ARRIVAL TIME
arrival_time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
get_date_picker(arrival_time);
}
});
dialog.show();
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
@Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
context.startActivity(new Intent(context,available_order.class));
}
return true;
}
});
}
@Override
public void OnStart() {
}
@Override
public void OnResponse(ResponseModel model) {
Toasty.success(context, "Offer Submitted Successfully", Toast.LENGTH_LONG).show();
context.startActivity(new Intent(context, my_notifcation.class));
send_data.ADD_CLIENT_NAME(context, name);
pd.cancel();
}
@Override
public void OnError(VolleyError error) {
pd.cancel();
Toasty.error(context, "Offer Not Sent.", Toast.LENGTH_LONG).show();
}
@Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(30.077899, 31.342715);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("order location"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 12.0f));
}
//GET DATE PICKER
void get_date_picker(EditText arrival_time) {
// TODO Auto-generated method stub
//To show current date in the datepicker
Calendar mcurrentDate = Calendar.getInstance();
int mYear = mcurrentDate.get(Calendar.YEAR);
int mMonth = mcurrentDate.get(Calendar.MONTH);
int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker;
mDatePicker = new DatePickerDialog(context, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
// TODO Auto-generated method stub
/* Your code to get date and time */
selectedmonth = selectedmonth + 1;
//GET TIME PICKER
get_time_picker(selectedyear, selectedmonth, selectedday, arrival_time);
}
}, mYear, mMonth, mDay);
mDatePicker.setTitle("Select Date");
mDatePicker.show();
}
//GET TIME PICKER
void get_time_picker(int selectedyear, int selectedmonth, int selectedday, EditText arrival_time) {
// TODO Auto-generated method stub
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(context, R.style.DialogTheme, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
arrival_time.setText(selectedyear + "-" + selectedmonth + "-" + selectedday + " " + selectedHour + ":" + selectedMinute + ":" + "00");
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
}
| 9,378 | 0.658029 | 0.655364 | 228 | 40.13158 | 31.500212 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.780702 | false | false | 14 |
3bcc749473e204f28993ffb298f498a9b0599e5c | 2,207,613,224,855 | 18eb53b7498baa3251e121003ab94314859f0838 | /common/src/main/java/com/dzk/common/autoservice/IWebViewService.java | 87d38e6563f6c4a09dd435dd42fc9a1d1ec696c7 | [] | no_license | MirDong/WebView | https://github.com/MirDong/WebView | dfe862acf4014182f82506f39a1cab3aadf84539 | 54da89a0daaf26eb620cb9e08f5dcee261ee27c8 | refs/heads/master | 2022-12-14T18:32:47.362000 | 2020-09-07T07:06:40 | 2020-09-07T07:06:40 | 286,782,434 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dzk.common.autoservice;
import android.content.Context;
/**
* @author jackie
* @date 2020/8/11
*/
public interface IWebViewService {
/**
*
* @param context
* @param url load的url
* @param title url 页面title
* @param isShowActionBar 是否显示ActionBar
*/
void startWebViewActivity(Context context,String url,String title,boolean isShowActionBar);
void openDemoHtml(Context context);
}
| UTF-8 | Java | 453 | java | IWebViewService.java | Java | [
{
"context": ";\n\nimport android.content.Context;\n\n/**\n * @author jackie\n * @date 2020/8/11\n */\npublic interface IWebViewS",
"end": 91,
"score": 0.9953539967536926,
"start": 85,
"tag": "USERNAME",
"value": "jackie"
}
] | null | [] | package com.dzk.common.autoservice;
import android.content.Context;
/**
* @author jackie
* @date 2020/8/11
*/
public interface IWebViewService {
/**
*
* @param context
* @param url load的url
* @param title url 页面title
* @param isShowActionBar 是否显示ActionBar
*/
void startWebViewActivity(Context context,String url,String title,boolean isShowActionBar);
void openDemoHtml(Context context);
}
| 453 | 0.685649 | 0.669704 | 19 | 22.105263 | 22.360432 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 14 |
ef8dde4fdff56a1c79876b896bf3b130bac78360 | 31,078,383,424,645 | a20797c04c984ed0cd80154a04e9e81bea7ec31d | /app/src/main/java/com/ysbd/hewu/adapter/SearchPersonAdapter.java | f74792b88160dec50d9fa9a59d0be34062a90e60 | [] | no_license | risesoft123/hewu | https://github.com/risesoft123/hewu | fbf16713a2c8bd18ff5a5d8b697a8ad658db9f22 | d215e0f386e2474f9828ad476bdab16a0b655aa2 | refs/heads/master | 2018-12-22T02:18:48.235000 | 2018-10-17T08:50:21 | 2018-10-17T08:50:21 | 143,229,346 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ysbd.hewu.adapter;
import android.content.Context;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ysbd.hewu.R;
import com.ysbd.hewu.bean.SearchPersonBean;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by lcjing on 2018/5/23.
*/
public class SearchPersonAdapter extends BaseAdapter{
private List<SearchPersonBean> persons;
private Context context;
private String key="";
public SearchPersonAdapter(List<SearchPersonBean> persons, Context context) {
this.persons = persons;
this.context = context;
}
public void setKey(String key) {
this.key = key;
}
@Override
public int getCount() {
return persons.size();
}
@Override
public Object getItem(int i) {
return persons.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
Holder holder;
if (view==null) {
view= LayoutInflater.from(context).inflate(R.layout.search_person_item,null);
holder=new Holder();
holder.ivSex=view.findViewById(R.id.ivSex);
holder.ivDepart=view.findViewById(R.id.ivDepart);
holder.tvName=view.findViewById(R.id.tvName);
holder.tvDepartName=view.findViewById(R.id.tvDepart);
view.setTag(holder);
}else {
holder=(Holder) view.getTag();
}
if (persons.get(i).getSex()!=null&&persons.get(i).getSex().trim().length()>0) {
holder.ivSex.setImageResource("男".equals( persons.get(i).getSex())?R.mipmap.male:R.mipmap.female);
holder.ivSex.setVisibility(View.VISIBLE);
}else {
holder.ivSex.setVisibility(View.GONE);
}
holder.tvName.setText(toSpannableString(persons.get(i).getName(),key));
if (persons.get(i).getDepName()!=null&&persons.get(i).getDepName().trim().length()>0) {
holder.tvDepartName.setText(toSpannableString(persons.get(i).getDepName(),key));
holder.ivDepart.setVisibility(View.VISIBLE);
}else {
holder.tvDepartName.setVisibility(View.GONE);
holder.ivDepart.setVisibility(View.GONE);
}
return view;
}
public static SpannableString toSpannableString(String text, String keyWord) {
if (text==null) {
return new SpannableString("");
}
SpannableString spannableString = new SpannableString(text);
if (!TextUtils.isEmpty(text)&&keyWord!=null){
int start = 0;
Pattern pattern = Pattern.compile(keyWord, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
if (matcher.find()){
int startIndex = text.indexOf(keyWord, start);
int endIndex = startIndex + keyWord.length();
spannableString.setSpan(new ForegroundColorSpan(Color.GRAY),
startIndex,endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
startIndex,endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return spannableString;
}
private class Holder{
ImageView ivSex,ivDepart;
TextView tvName,tvDepartName;
}
}
| UTF-8 | Java | 3,813 | java | SearchPersonAdapter.java | Java | [
{
"context": "import java.util.regex.Pattern;\n\n/**\n * Created by lcjing on 2018/5/23.\n */\n\npublic class SearchPersonAdapt",
"end": 651,
"score": 0.9996569752693176,
"start": 645,
"tag": "USERNAME",
"value": "lcjing"
}
] | null | [] | package com.ysbd.hewu.adapter;
import android.content.Context;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ysbd.hewu.R;
import com.ysbd.hewu.bean.SearchPersonBean;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by lcjing on 2018/5/23.
*/
public class SearchPersonAdapter extends BaseAdapter{
private List<SearchPersonBean> persons;
private Context context;
private String key="";
public SearchPersonAdapter(List<SearchPersonBean> persons, Context context) {
this.persons = persons;
this.context = context;
}
public void setKey(String key) {
this.key = key;
}
@Override
public int getCount() {
return persons.size();
}
@Override
public Object getItem(int i) {
return persons.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
Holder holder;
if (view==null) {
view= LayoutInflater.from(context).inflate(R.layout.search_person_item,null);
holder=new Holder();
holder.ivSex=view.findViewById(R.id.ivSex);
holder.ivDepart=view.findViewById(R.id.ivDepart);
holder.tvName=view.findViewById(R.id.tvName);
holder.tvDepartName=view.findViewById(R.id.tvDepart);
view.setTag(holder);
}else {
holder=(Holder) view.getTag();
}
if (persons.get(i).getSex()!=null&&persons.get(i).getSex().trim().length()>0) {
holder.ivSex.setImageResource("男".equals( persons.get(i).getSex())?R.mipmap.male:R.mipmap.female);
holder.ivSex.setVisibility(View.VISIBLE);
}else {
holder.ivSex.setVisibility(View.GONE);
}
holder.tvName.setText(toSpannableString(persons.get(i).getName(),key));
if (persons.get(i).getDepName()!=null&&persons.get(i).getDepName().trim().length()>0) {
holder.tvDepartName.setText(toSpannableString(persons.get(i).getDepName(),key));
holder.ivDepart.setVisibility(View.VISIBLE);
}else {
holder.tvDepartName.setVisibility(View.GONE);
holder.ivDepart.setVisibility(View.GONE);
}
return view;
}
public static SpannableString toSpannableString(String text, String keyWord) {
if (text==null) {
return new SpannableString("");
}
SpannableString spannableString = new SpannableString(text);
if (!TextUtils.isEmpty(text)&&keyWord!=null){
int start = 0;
Pattern pattern = Pattern.compile(keyWord, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
if (matcher.find()){
int startIndex = text.indexOf(keyWord, start);
int endIndex = startIndex + keyWord.length();
spannableString.setSpan(new ForegroundColorSpan(Color.GRAY),
startIndex,endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
startIndex,endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return spannableString;
}
private class Holder{
ImageView ivSex,ivDepart;
TextView tvName,tvDepartName;
}
}
| 3,813 | 0.642876 | 0.640252 | 119 | 31.025209 | 26.665833 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.630252 | false | false | 14 |
a3098143f911c6655bb644d563318974efcc3c74 | 32,401,233,317,777 | cff1cb1daf4340dc415f3629c440e43a6d2e57f6 | /src/example/jms/queue/AbstarctQueueExample.java | 0e9abf7f4d2d90991a1e3ebb29c801ec257f0aea | [] | no_license | tangblack/jms_hello_queue | https://github.com/tangblack/jms_hello_queue | c12e5300ec6a2ef51b3063008615ef4c1daec349 | 34ba3e62964e1799700d1251bc4ee0eee546ac14 | refs/heads/master | 2020-04-29T12:54:33.178000 | 2012-11-15T03:56:43 | 2012-11-15T03:56:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package example.jms.queue;
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public abstract class AbstarctQueueExample
{
/*
* Note
* -Need to set up which role(default: guest) can access this queue.
* -Need to add a user belong to this role(ex: jms=guest).
*/
public static final String USER = "jms"; //TODO Change user name!!
public static final String PASSWORD = "jmsjboss"; //TODO Change password!!
public static final String QUEUE_NAME = "jms/queue/test";
public static final String CONNECTION_FACTORY_NAME = "jms/RemoteConnectionFactory";
/** get the initial context */
public InitialContext getInitialContext() throws NamingException
{
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
env.put(Context.PROVIDER_URL, "remote://localhost:4447");
env.put(Context.SECURITY_PRINCIPAL, USER); // user
env.put(Context.SECURITY_CREDENTIALS, PASSWORD); // password
return new InitialContext(env);
}
/** lookup the queue object */
public Queue getQueue(InitialContext ctx) throws NamingException
{
return (Queue) ctx.lookup(QUEUE_NAME);
}
/** lookup the queue connection factory */
public QueueConnectionFactory getQueueConnectionFactory(InitialContext ctx) throws NamingException
{
return (QueueConnectionFactory) ctx.lookup(CONNECTION_FACTORY_NAME);
}
/** create a queue connection */
public QueueConnection getQueueConnection(QueueConnectionFactory connFactory) throws JMSException
{
return connFactory.createQueueConnection(USER, PASSWORD); // user/password
}
/**
* create a queue session
*/
public QueueSession getQueueSession(QueueConnection queueConn) throws JMSException
{
/*
* public static final int AUTO_ACKNOWLEDGE = 1;
* 為自動確認,客戶端發送和接收消息不需要做額外的工作。
*
* public static final int CLIENT_ACKNOWLEDGE = 2;
* 為客戶端確認。客戶端接收到消息後,必須調用javax.jms.Message的acknowledge方法。jms服務器才會刪除消息。
*
* public static final int DUPS_OK_ACKNOWLEDGE = 3;
* 允許副本的確認模式。一旦接收方應用程序的方法調用從處理消息處返回
* ,會話對象就會確認消息的接收;而且允許重複確認。在需要考慮資源使用時,這種模式非常有效。
*/
return queueConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
}
}
| BIG5 | Java | 2,812 | java | AbstarctQueueExample.java | Java | [
{
"context": "est). \r\n\t */\r\n\tpublic static final String USER = \"jms\"; \t\t\t\t\t//TODO Change user name!!\r\n\tpublic static ",
"end": 605,
"score": 0.7287091016769409,
"start": 602,
"tag": "USERNAME",
"value": "jms"
},
{
"context": "r name!!\r\n\tpublic static final String P... | null | [] | package example.jms.queue;
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public abstract class AbstarctQueueExample
{
/*
* Note
* -Need to set up which role(default: guest) can access this queue.
* -Need to add a user belong to this role(ex: jms=guest).
*/
public static final String USER = "jms"; //TODO Change user name!!
public static final String PASSWORD = "<PASSWORD>"; //TODO Change password!!
public static final String QUEUE_NAME = "jms/queue/test";
public static final String CONNECTION_FACTORY_NAME = "jms/RemoteConnectionFactory";
/** get the initial context */
public InitialContext getInitialContext() throws NamingException
{
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
env.put(Context.PROVIDER_URL, "remote://localhost:4447");
env.put(Context.SECURITY_PRINCIPAL, USER); // user
env.put(Context.SECURITY_CREDENTIALS, PASSWORD); // password
return new InitialContext(env);
}
/** lookup the queue object */
public Queue getQueue(InitialContext ctx) throws NamingException
{
return (Queue) ctx.lookup(QUEUE_NAME);
}
/** lookup the queue connection factory */
public QueueConnectionFactory getQueueConnectionFactory(InitialContext ctx) throws NamingException
{
return (QueueConnectionFactory) ctx.lookup(CONNECTION_FACTORY_NAME);
}
/** create a queue connection */
public QueueConnection getQueueConnection(QueueConnectionFactory connFactory) throws JMSException
{
return connFactory.createQueueConnection(USER, PASSWORD); // user/password
}
/**
* create a queue session
*/
public QueueSession getQueueSession(QueueConnection queueConn) throws JMSException
{
/*
* public static final int AUTO_ACKNOWLEDGE = 1;
* 為自動確認,客戶端發送和接收消息不需要做額外的工作。
*
* public static final int CLIENT_ACKNOWLEDGE = 2;
* 為客戶端確認。客戶端接收到消息後,必須調用javax.jms.Message的acknowledge方法。jms服務器才會刪除消息。
*
* public static final int DUPS_OK_ACKNOWLEDGE = 3;
* 允許副本的確認模式。一旦接收方應用程序的方法調用從處理消息處返回
* ,會話對象就會確認消息的接收;而且允許重複確認。在需要考慮資源使用時,這種模式非常有效。
*/
return queueConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
}
}
| 2,814 | 0.733649 | 0.73089 | 74 | 32.297298 | 29.3307 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.675676 | false | false | 14 |
bd7058b71fcaa6b352804fe937a121d24d85fa6f | 3,856,880,650,260 | 8c08d45986707b79b0afd4c55d37c79051acbde4 | /org.jefcode.api_1.0.0.v20191201/src/org/jefcode/api/ui/components/WebPasswordField.java | 99222d567a4089d305a87e4675e188d88eca1f8d | [] | no_license | jhon24samuel/Virtual-system-registration | https://github.com/jhon24samuel/Virtual-system-registration | 686a187d17296f75fda26e64bd76d665b0c36a3c | 8a2ffba1bac9cb4bebc34239571548e34ccdad01 | refs/heads/master | 2020-09-27T14:45:16.738000 | 2020-02-01T00:01:27 | 2020-02-01T00:01:27 | 226,540,015 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.jefcode.api.ui.components;
import org.jefcode.api.ui.border.RoundedBorder;
import org.jefcode.api.ui.event.BorderMouseEvent;
import javax.swing.*;
import java.awt.*;
public class WebPasswordField extends JPasswordField {
public WebPasswordField(){
super();
}
public WebPasswordField(Color entered, Color exited, Color pressed, int thicknes, boolean roundedCorners) {
super();
this.setBorder(new RoundedBorder(entered,thicknes,roundedCorners));
this.addMouseListener(new BorderMouseEvent(entered, exited,pressed,thicknes,roundedCorners));
}
public void setBorderEvent(Color entered, Color exited, Color pressed,int thicknes, boolean roundedCorners){
this.setBorder(new RoundedBorder(exited,thicknes,roundedCorners));
this.addMouseListener(new BorderMouseEvent(entered, exited,pressed,thicknes,roundedCorners));
}
}
| UTF-8 | Java | 905 | java | WebPasswordField.java | Java | [] | null | [] | package org.jefcode.api.ui.components;
import org.jefcode.api.ui.border.RoundedBorder;
import org.jefcode.api.ui.event.BorderMouseEvent;
import javax.swing.*;
import java.awt.*;
public class WebPasswordField extends JPasswordField {
public WebPasswordField(){
super();
}
public WebPasswordField(Color entered, Color exited, Color pressed, int thicknes, boolean roundedCorners) {
super();
this.setBorder(new RoundedBorder(entered,thicknes,roundedCorners));
this.addMouseListener(new BorderMouseEvent(entered, exited,pressed,thicknes,roundedCorners));
}
public void setBorderEvent(Color entered, Color exited, Color pressed,int thicknes, boolean roundedCorners){
this.setBorder(new RoundedBorder(exited,thicknes,roundedCorners));
this.addMouseListener(new BorderMouseEvent(entered, exited,pressed,thicknes,roundedCorners));
}
}
| 905 | 0.751381 | 0.751381 | 25 | 35.200001 | 38.387497 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.24 | false | false | 14 |
1990568b2655638a529131b2866ca53344c0189b | 22,239,340,671,837 | 64aafb903e5ee961861a26476055a242ccbe4c83 | /src/com/ruegnerLukas/engine/input/handlers/controller/ControllerButtonMapping.java | be84bf75678cdb97c5ba63a33a2f2dcbdefcde5f | [
"MIT"
] | permissive | SMILEY4/BlocksGame | https://github.com/SMILEY4/BlocksGame | 131be0f173909556e7a3023666c671d2252ee7f3 | 67e59aba816ac39761e38db8477aa70293cf20ab | refs/heads/master | 2018-03-12T07:46:58.379000 | 2017-10-14T18:27:40 | 2017-10-14T18:27:40 | 40,069,053 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ruegnerLukas.engine.input.handlers.controller;
public class ControllerButtonMapping {
//-- PS3-Controller --//
public static final int PS3_SELECT = 0;
public static final int PS3_START = 3;
public static final int PS3_HOME = 16;
public static final int PS3_R1 = 11;
public static final int PS3_R2 = 9;
public static final int PS3_R3 = 2;
public static final int PS3_L1 = 10;
public static final int PS3_L2 = 8;
public static final int PS3_L3 = 1;
public static final int PS3_LEFT = 7;
public static final int PS3_RIGHT = 5;
public static final int PS3_UP = 4;
public static final int PS3_DOWN = 6;
public static final int PS3_TRIANGLE = 12;
public static final int PS3_CIRCLE = 13;
public static final int PS3_CROSS = 14;
public static final int PS3_SQUARE = 15;
public static String ps3TOname(int ps3Button) {
if(ps3Button == 0) return "PS3_SELECT";
if(ps3Button == 3) return "PS3_START";
if(ps3Button == 16) return "PS3_HOME";
if(ps3Button == 11) return "PS3_R1";
if(ps3Button == 9) return "PS3_R2";
if(ps3Button == 2) return "PS3_R3";
if(ps3Button == 10) return "PS3_L1";
if(ps3Button == 8) return "PS3_L2";
if(ps3Button == 1) return "PS3_L3";
if(ps3Button == 7) return "PS3_LEFT";
if(ps3Button == 5) return "PS3_RIGHT";
if(ps3Button == 4) return "PS3_UP";
if(ps3Button == 6) return "PS3_DOWN";
if(ps3Button == 12) return "PS3_TRIANGLE";
if(ps3Button == 13) return "PS3_CIRCLE";
if(ps3Button == 14) return "PS3_CROSS";
if(ps3Button == 15) return "PS3_QUAD";
return "PS3_UNKNOWN";
}
//-- XBOX-Controller --//
}
| UTF-8 | Java | 1,634 | java | ControllerButtonMapping.java | Java | [] | null | [] | package com.ruegnerLukas.engine.input.handlers.controller;
public class ControllerButtonMapping {
//-- PS3-Controller --//
public static final int PS3_SELECT = 0;
public static final int PS3_START = 3;
public static final int PS3_HOME = 16;
public static final int PS3_R1 = 11;
public static final int PS3_R2 = 9;
public static final int PS3_R3 = 2;
public static final int PS3_L1 = 10;
public static final int PS3_L2 = 8;
public static final int PS3_L3 = 1;
public static final int PS3_LEFT = 7;
public static final int PS3_RIGHT = 5;
public static final int PS3_UP = 4;
public static final int PS3_DOWN = 6;
public static final int PS3_TRIANGLE = 12;
public static final int PS3_CIRCLE = 13;
public static final int PS3_CROSS = 14;
public static final int PS3_SQUARE = 15;
public static String ps3TOname(int ps3Button) {
if(ps3Button == 0) return "PS3_SELECT";
if(ps3Button == 3) return "PS3_START";
if(ps3Button == 16) return "PS3_HOME";
if(ps3Button == 11) return "PS3_R1";
if(ps3Button == 9) return "PS3_R2";
if(ps3Button == 2) return "PS3_R3";
if(ps3Button == 10) return "PS3_L1";
if(ps3Button == 8) return "PS3_L2";
if(ps3Button == 1) return "PS3_L3";
if(ps3Button == 7) return "PS3_LEFT";
if(ps3Button == 5) return "PS3_RIGHT";
if(ps3Button == 4) return "PS3_UP";
if(ps3Button == 6) return "PS3_DOWN";
if(ps3Button == 12) return "PS3_TRIANGLE";
if(ps3Button == 13) return "PS3_CIRCLE";
if(ps3Button == 14) return "PS3_CROSS";
if(ps3Button == 15) return "PS3_QUAD";
return "PS3_UNKNOWN";
}
//-- XBOX-Controller --//
}
| 1,634 | 0.659731 | 0.589351 | 62 | 25.354839 | 18.49943 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.048387 | false | false | 14 |
0f9758c79de1ffc164a564c8ec67dc2ae97f40d1 | 16,458,314,689,468 | 813698fcda63615f03e9a7300762bf753777bcd9 | /src/com/briannakayama/configure/ConfigurationError.java | 03a9b172d572aefe5bd92a196e264b0bb030eae5 | [
"MIT"
] | permissive | briannkym/TEngine | https://github.com/briannkym/TEngine | c3a310e606cf1becbab66c79d35c048b1979d572 | 5afa6dbb26487bdc6d1ebdf1462f0c3bf57e5445 | refs/heads/master | 2021-01-11T19:02:32.321000 | 2017-01-18T03:56:22 | 2017-01-18T03:56:22 | 79,300,966 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.briannakayama.configure;
public class ConfigurationError extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = -9187088905120275485L;
public ConfigurationError(String message){
super(message);
}
public ConfigurationError(String message, Throwable cause){
super(message, cause);
}
public ConfigurationError(int lineNo, String file, String message){
super(message + "\n\tin configuration "+ file+ ":" + lineNo);
}
public ConfigurationError(int lineNo, String file, String message, Throwable cause){
super(message + "\n\tin configuration "+ file+ ":" + lineNo, cause);
}
}
| UTF-8 | Java | 645 | java | ConfigurationError.java | Java | [] | null | [] | package com.briannakayama.configure;
public class ConfigurationError extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = -9187088905120275485L;
public ConfigurationError(String message){
super(message);
}
public ConfigurationError(String message, Throwable cause){
super(message, cause);
}
public ConfigurationError(int lineNo, String file, String message){
super(message + "\n\tin configuration "+ file+ ":" + lineNo);
}
public ConfigurationError(int lineNo, String file, String message, Throwable cause){
super(message + "\n\tin configuration "+ file+ ":" + lineNo, cause);
}
}
| 645 | 0.725581 | 0.696124 | 28 | 22.035715 | 28.563816 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.357143 | false | false | 14 |
dc952fb8d87ab3d14e25fbad7fc6a58a4c1f5611 | 171,798,695,453 | fb5444a71f362cf7c960435f2571b6577eca4838 | /commercetools/commercetools-sdk-java-api/src/main/java-generated/com/commercetools/api/models/order/OrderSetDeliveryAddressActionBuilder.java | 36397f638a34369ecef43a1ea5daae4e54c16cd5 | [
"Apache-2.0"
] | permissive | bogste/commercetools-sdk-java-v2 | https://github.com/bogste/commercetools-sdk-java-v2 | 1a406f57a509282d3eb33579510377d045f7bb8b | e95dd94d90c1eb582a526c42f917df0972dd5ac9 | refs/heads/main | 2023-07-19T07:02:31.589000 | 2021-09-14T07:08:35 | 2021-09-14T07:08:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.commercetools.api.models.order;
import java.util.*;
import java.util.function.Function;
import javax.annotation.Nullable;
import io.vrap.rmf.base.client.Builder;
import io.vrap.rmf.base.client.utils.Generated;
@Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen")
public final class OrderSetDeliveryAddressActionBuilder implements Builder<OrderSetDeliveryAddressAction> {
private String deliveryId;
@Nullable
private com.commercetools.api.models.common.BaseAddress address;
public OrderSetDeliveryAddressActionBuilder deliveryId(final String deliveryId) {
this.deliveryId = deliveryId;
return this;
}
public OrderSetDeliveryAddressActionBuilder address(
Function<com.commercetools.api.models.common.BaseAddressBuilder, com.commercetools.api.models.common.BaseAddressBuilder> builder) {
this.address = builder.apply(com.commercetools.api.models.common.BaseAddressBuilder.of()).build();
return this;
}
public OrderSetDeliveryAddressActionBuilder address(
@Nullable final com.commercetools.api.models.common.BaseAddress address) {
this.address = address;
return this;
}
public String getDeliveryId() {
return this.deliveryId;
}
@Nullable
public com.commercetools.api.models.common.BaseAddress getAddress() {
return this.address;
}
public OrderSetDeliveryAddressAction build() {
Objects.requireNonNull(deliveryId, OrderSetDeliveryAddressAction.class + ": deliveryId is missing");
return new OrderSetDeliveryAddressActionImpl(deliveryId, address);
}
/**
* builds OrderSetDeliveryAddressAction without checking for non null required values
*/
public OrderSetDeliveryAddressAction buildUnchecked() {
return new OrderSetDeliveryAddressActionImpl(deliveryId, address);
}
public static OrderSetDeliveryAddressActionBuilder of() {
return new OrderSetDeliveryAddressActionBuilder();
}
public static OrderSetDeliveryAddressActionBuilder of(final OrderSetDeliveryAddressAction template) {
OrderSetDeliveryAddressActionBuilder builder = new OrderSetDeliveryAddressActionBuilder();
builder.deliveryId = template.getDeliveryId();
builder.address = template.getAddress();
return builder;
}
}
| UTF-8 | Java | 2,424 | java | OrderSetDeliveryAddressActionBuilder.java | Java | [
{
"context": "oreCodeGenerator\", comments = \"https://github.com/vrapio/rmf-codegen\")\npublic final class OrderSetDelivery",
"end": 333,
"score": 0.9992914795875549,
"start": 327,
"tag": "USERNAME",
"value": "vrapio"
}
] | null | [] |
package com.commercetools.api.models.order;
import java.util.*;
import java.util.function.Function;
import javax.annotation.Nullable;
import io.vrap.rmf.base.client.Builder;
import io.vrap.rmf.base.client.utils.Generated;
@Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen")
public final class OrderSetDeliveryAddressActionBuilder implements Builder<OrderSetDeliveryAddressAction> {
private String deliveryId;
@Nullable
private com.commercetools.api.models.common.BaseAddress address;
public OrderSetDeliveryAddressActionBuilder deliveryId(final String deliveryId) {
this.deliveryId = deliveryId;
return this;
}
public OrderSetDeliveryAddressActionBuilder address(
Function<com.commercetools.api.models.common.BaseAddressBuilder, com.commercetools.api.models.common.BaseAddressBuilder> builder) {
this.address = builder.apply(com.commercetools.api.models.common.BaseAddressBuilder.of()).build();
return this;
}
public OrderSetDeliveryAddressActionBuilder address(
@Nullable final com.commercetools.api.models.common.BaseAddress address) {
this.address = address;
return this;
}
public String getDeliveryId() {
return this.deliveryId;
}
@Nullable
public com.commercetools.api.models.common.BaseAddress getAddress() {
return this.address;
}
public OrderSetDeliveryAddressAction build() {
Objects.requireNonNull(deliveryId, OrderSetDeliveryAddressAction.class + ": deliveryId is missing");
return new OrderSetDeliveryAddressActionImpl(deliveryId, address);
}
/**
* builds OrderSetDeliveryAddressAction without checking for non null required values
*/
public OrderSetDeliveryAddressAction buildUnchecked() {
return new OrderSetDeliveryAddressActionImpl(deliveryId, address);
}
public static OrderSetDeliveryAddressActionBuilder of() {
return new OrderSetDeliveryAddressActionBuilder();
}
public static OrderSetDeliveryAddressActionBuilder of(final OrderSetDeliveryAddressAction template) {
OrderSetDeliveryAddressActionBuilder builder = new OrderSetDeliveryAddressActionBuilder();
builder.deliveryId = template.getDeliveryId();
builder.address = template.getAddress();
return builder;
}
}
| 2,424 | 0.742987 | 0.742987 | 68 | 34.632355 | 37.005127 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.426471 | false | false | 14 |
31fc84a2516646983a70dc6c27d6404867428603 | 6,871,947,740,280 | f950845b2a29a98ca2f96ffaeca8cdf88308adbf | /AN3/IP - Gramatovici Radu/echipa-16/app/src/main/java/ro/unibuc/fmi/bookstoread/Fragment/DiscoverFragment.java | 783c2d6b7a81dff365e5c8098cd1a475615cba9f | [] | no_license | joahn3/fmi | https://github.com/joahn3/fmi | ba50b35a9ce3aabe837a16e352efe37a3c899041 | e10574973938abc0e27d8f296b015031abb4f43b | refs/heads/master | 2021-10-11T10:16:46.691000 | 2019-01-24T17:24:46 | 2019-01-24T17:24:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ro.unibuc.fmi.bookstoread.Fragment;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import ro.unibuc.fmi.bookstoread.Adapter.BookListAdapter;
import ro.unibuc.fmi.bookstoread.Loader.BookLoader;
import ro.unibuc.fmi.bookstoread.Model.Book;
import ro.unibuc.fmi.bookstoread.R;
import static com.facebook.FacebookSdk.getApplicationContext;
public class DiscoverFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Book>> {
private static final String BOOK_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=";
private static final int BOOK_LOADER_ID = 1;
private TextView mEmptyStateTextView;
private RecyclerView mRecyclerView;
private BookListAdapter mAdapter;
private List<Book> bookList = new ArrayList<>();
private EditText mTitle;
private EditText mAuthor;
private EditText mSubject;
private EditText mIsbn;
private String searchQuery;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_discover, container, false);
mEmptyStateTextView = view.findViewById(R.id.no_books);
mRecyclerView = view.findViewById(R.id.books_search);
mAdapter = new BookListAdapter(bookList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(mAdapter);
mTitle = view.findViewById(R.id.title_search);
mSubject = view.findViewById(R.id.subject_search);
mAuthor = view.findViewById(R.id.author_search);
mIsbn = view.findViewById(R.id.isbn_search);
view.findViewById(R.id.search_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isValidSearch()) {
startRequest();
}else{
Toast.makeText(getActivity(), getResources().getString(R.string.search_error), Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private boolean isValidSearch() {
searchQuery = BOOK_REQUEST_URL;
if (!mTitle.getText().toString().equals("")) {
searchQuery += "+intitle:" + String.valueOf(mTitle.getText());
}
if (!mIsbn.getText().toString().equals("")) {
searchQuery += "+isbn:" + String.valueOf(mIsbn.getText());
}
if (!mAuthor.getText().toString().equals("")) {
searchQuery += "+inauthor:" + String.valueOf(mAuthor.getText());
}
if (!mSubject.getText().toString().equals("")) {
searchQuery += "+subject:" + String.valueOf(mSubject.getText());
}
return !searchQuery.equals(BOOK_REQUEST_URL);
}
private void startRequest() {
//Initialize connection
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
mEmptyStateTextView.setVisibility(View.GONE);
LoaderManager loaderManager = getLoaderManager();
loaderManager.restartLoader(BOOK_LOADER_ID, null, DiscoverFragment.this).forceLoad();
} else {
mEmptyStateTextView.setVisibility(View.VISIBLE);
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
}
@Override
public android.support.v4.content.Loader<List<Book>> onCreateLoader(int id, Bundle args) {
return new BookLoader(getActivity(), searchQuery);
}
@Override
public void onLoadFinished(android.support.v4.content.Loader<List<Book>> loader, List<Book> book) {
mAdapter.clear();
mAdapter.addList(book);
}
@Override
public void onLoaderReset(android.support.v4.content.Loader<List<Book>> loader) {
mAdapter.clear();
}
}
| UTF-8 | Java | 4,710 | java | DiscoverFragment.java | Java | [] | null | [] | package ro.unibuc.fmi.bookstoread.Fragment;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import ro.unibuc.fmi.bookstoread.Adapter.BookListAdapter;
import ro.unibuc.fmi.bookstoread.Loader.BookLoader;
import ro.unibuc.fmi.bookstoread.Model.Book;
import ro.unibuc.fmi.bookstoread.R;
import static com.facebook.FacebookSdk.getApplicationContext;
public class DiscoverFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Book>> {
private static final String BOOK_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=";
private static final int BOOK_LOADER_ID = 1;
private TextView mEmptyStateTextView;
private RecyclerView mRecyclerView;
private BookListAdapter mAdapter;
private List<Book> bookList = new ArrayList<>();
private EditText mTitle;
private EditText mAuthor;
private EditText mSubject;
private EditText mIsbn;
private String searchQuery;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_discover, container, false);
mEmptyStateTextView = view.findViewById(R.id.no_books);
mRecyclerView = view.findViewById(R.id.books_search);
mAdapter = new BookListAdapter(bookList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(mAdapter);
mTitle = view.findViewById(R.id.title_search);
mSubject = view.findViewById(R.id.subject_search);
mAuthor = view.findViewById(R.id.author_search);
mIsbn = view.findViewById(R.id.isbn_search);
view.findViewById(R.id.search_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isValidSearch()) {
startRequest();
}else{
Toast.makeText(getActivity(), getResources().getString(R.string.search_error), Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private boolean isValidSearch() {
searchQuery = BOOK_REQUEST_URL;
if (!mTitle.getText().toString().equals("")) {
searchQuery += "+intitle:" + String.valueOf(mTitle.getText());
}
if (!mIsbn.getText().toString().equals("")) {
searchQuery += "+isbn:" + String.valueOf(mIsbn.getText());
}
if (!mAuthor.getText().toString().equals("")) {
searchQuery += "+inauthor:" + String.valueOf(mAuthor.getText());
}
if (!mSubject.getText().toString().equals("")) {
searchQuery += "+subject:" + String.valueOf(mSubject.getText());
}
return !searchQuery.equals(BOOK_REQUEST_URL);
}
private void startRequest() {
//Initialize connection
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
mEmptyStateTextView.setVisibility(View.GONE);
LoaderManager loaderManager = getLoaderManager();
loaderManager.restartLoader(BOOK_LOADER_ID, null, DiscoverFragment.this).forceLoad();
} else {
mEmptyStateTextView.setVisibility(View.VISIBLE);
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
}
@Override
public android.support.v4.content.Loader<List<Book>> onCreateLoader(int id, Bundle args) {
return new BookLoader(getActivity(), searchQuery);
}
@Override
public void onLoadFinished(android.support.v4.content.Loader<List<Book>> loader, List<Book> book) {
mAdapter.clear();
mAdapter.addList(book);
}
@Override
public void onLoaderReset(android.support.v4.content.Loader<List<Book>> loader) {
mAdapter.clear();
}
}
| 4,710 | 0.689597 | 0.687473 | 121 | 37.925621 | 30.100977 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.644628 | false | false | 14 |
f27da72c433f7cdbb3de238ac98ddade3dd6738e | 33,114,197,859,874 | ee90161cdc550aa2008e19e8a705e6f5630996ca | /sso-server-core-api-mfa/src/main/java/com/lic/authentication/MultifactorAuthenticationProviderResolver.java | aa3d99dad9d16dc94f51cde0bca8e23ca9e30d74 | [] | no_license | licongwill/sso | https://github.com/licongwill/sso | c8738cdfff343c4496fa696053393e7b0af52027 | 6da224ba582b7dfe66755c6afc8b5f5f44211659 | refs/heads/master | 2023-01-22T18:06:30.673000 | 2020-12-09T07:17:00 | 2020-12-09T07:17:00 | 303,999,813 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lic.authentication;
import com.lic.services.RegisteredService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import java.io.Serializable;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
/**
* TODO
*
* @author licong
* @version 1.0
* @date 2020/11/12 10:52
*/
@FunctionalInterface
public interface MultifactorAuthenticationProviderResolver extends Serializable,Ordered {
Logger LOGGER = LoggerFactory.getLogger(MultifactorAuthenticationProviderResolver.class);
default String getName() {
return getClass().getName();
}
Set<Event> resolveEventViaAuthenticationAttribute(Authentication authentication,
Collection<String> attributeNames,
RegisteredService service,
Optional<RequestContext> context,
Collection<MultifactorAuthenticationProvider> providers,
Predicate<String> predicate);
@Override
default int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
| UTF-8 | Java | 1,425 | java | MultifactorAuthenticationProviderResolver.java | Java | [
{
"context": "til.function.Predicate;\n\n/**\n * TODO\n *\n * @author licong\n * @version 1.0\n * @date 2020/11/12 10:52\n */\n@Fu",
"end": 465,
"score": 0.9996023178100586,
"start": 459,
"tag": "USERNAME",
"value": "licong"
}
] | null | [] | package com.lic.authentication;
import com.lic.services.RegisteredService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import java.io.Serializable;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
/**
* TODO
*
* @author licong
* @version 1.0
* @date 2020/11/12 10:52
*/
@FunctionalInterface
public interface MultifactorAuthenticationProviderResolver extends Serializable,Ordered {
Logger LOGGER = LoggerFactory.getLogger(MultifactorAuthenticationProviderResolver.class);
default String getName() {
return getClass().getName();
}
Set<Event> resolveEventViaAuthenticationAttribute(Authentication authentication,
Collection<String> attributeNames,
RegisteredService service,
Optional<RequestContext> context,
Collection<MultifactorAuthenticationProvider> providers,
Predicate<String> predicate);
@Override
default int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
| 1,425 | 0.641403 | 0.630175 | 42 | 32.92857 | 31.366795 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false | 14 |
2631dea3d2e4755447ad4a64bca1db47b49e9f61 | 12,223,476,991,132 | 90b735ab04187df031dcf1f1b7a60d08f3fc2162 | /src/timeseries/tests/TestSignature.java | 4547ca0231295f94ddaee6b5fae0861f0f18501a | [] | no_license | jgeneve/recherche-series-numerique | https://github.com/jgeneve/recherche-series-numerique | 7e9452f2ab00d73c51e9d36e6591ab7f9ca889d3 | 841cef076a8cc09b7661519efac008e2efa2cb8f | refs/heads/main | 2023-01-13T21:28:57.188000 | 2020-11-19T15:50:35 | 2020-11-19T15:50:35 | 310,242,667 | 0 | 0 | null | false | 2020-11-19T15:50:36 | 2020-11-05T09:01:01 | 2020-11-10T14:58:17 | 2020-11-19T15:50:36 | 53 | 0 | 0 | 0 | Java | false | false | package timeseries.tests;
import java.util.ArrayList;
import java.util.Arrays;
import junit.framework.TestCase;
import timeseries.functions.Patterns;
public class TestSignature extends TestCase {
public void testSignature1() throws Exception {
assertEquals("=>=<<=<>>=<=====>", Patterns.getSignature(new ArrayList<>(
Arrays.asList(4, 4, 2, 2, 3, 5, 5, 6, 3, 1, 1, 2, 2, 2, 2, 2, 2, 1))));
}
public void testSignature2() throws Exception {
assertEquals("<<=>=><><><>=<=", Patterns.getSignature(new ArrayList<>(
Arrays.asList(1,2,6,6,4,4,3,5,2,5,1,5,3,3,4,4))));
}
public void testSignatureNumberOfValue() throws Exception {
assertEquals(17, Patterns.getSignature(new ArrayList<>(
Arrays.asList(4, 4, 2, 2, 3, 5, 5, 6, 3, 1, 1, 2, 2, 2, 2, 2, 2, 1))).length());
}
}
| UTF-8 | Java | 826 | java | TestSignature.java | Java | [] | null | [] | package timeseries.tests;
import java.util.ArrayList;
import java.util.Arrays;
import junit.framework.TestCase;
import timeseries.functions.Patterns;
public class TestSignature extends TestCase {
public void testSignature1() throws Exception {
assertEquals("=>=<<=<>>=<=====>", Patterns.getSignature(new ArrayList<>(
Arrays.asList(4, 4, 2, 2, 3, 5, 5, 6, 3, 1, 1, 2, 2, 2, 2, 2, 2, 1))));
}
public void testSignature2() throws Exception {
assertEquals("<<=>=><><><>=<=", Patterns.getSignature(new ArrayList<>(
Arrays.asList(1,2,6,6,4,4,3,5,2,5,1,5,3,3,4,4))));
}
public void testSignatureNumberOfValue() throws Exception {
assertEquals(17, Patterns.getSignature(new ArrayList<>(
Arrays.asList(4, 4, 2, 2, 3, 5, 5, 6, 3, 1, 1, 2, 2, 2, 2, 2, 2, 1))).length());
}
}
| 826 | 0.631961 | 0.564165 | 27 | 29.592592 | 30.129669 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.888889 | false | false | 14 |
8bdd142fd22b9c74c9138cd357ad51b2ade80f23 | 13,297,218,750,608 | 74c1055c914419434a34ae3f44d4bf87e0e0edbe | /src/ferreteria/sv/edu/unab/Dominio/Persona.java | eba5b3facdd36aaaf04b14cc4d8785256854b164 | [] | no_license | darkpastiurs/ferreteria | https://github.com/darkpastiurs/ferreteria | ead3763645612da66eeb56940bfe98c75b323b48 | ca8bd6efb30bccea1f9cd8a708dafd9ece14ceef | refs/heads/master | 2020-04-26T16:12:03.076000 | 2019-03-04T03:41:48 | 2019-03-04T03:41:48 | 173,670,647 | 0 | 0 | null | true | 2019-03-04T03:57:07 | 2019-03-04T03:57:07 | 2019-03-04T03:42:43 | 2019-03-04T03:42:42 | 84 | 0 | 0 | 0 | null | false | null | package ferreteria.sv.edu.unab.Dominio;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(schema = "flr", name = "personas")
@SequenceGenerator(schema = "flr",sequenceName = "personas_id_seq",name = "Persona_seq_id",allocationSize = 1)
@NamedQueries({
@NamedQuery(name = "Persona.findAll",query = "SELECT p FROM Persona p"),
@NamedQuery(name = "Persona.findByNombre",query = "SELECT p FROM Persona p where p.nombre =:nombre")
})
public class Persona implements Serializable {
private static final long serialVersionUID=1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Persona_seq_id")
@Column(name = "id")
private Long id;
@NotNull
@Column(name = "nombre")
private String nombre;
@NotNull
@Size(min = 5,max = 50)
@Column(name = "apellidopaterno")
private String apellidopaterno;
@Column(name = "apellidomaterno")
private String apellidomaterno;
@NotNull
@Column(name = "dui")
private String dui;
@NotNull
@Column(name = "nit")
private String nit;
@NotNull
@Column(name = "fechanacimiento")
private LocalDate fechaNacimiento;
@NotNull
@Size(min = 8)
@Column(name = "telefono")
private String telefono;
@NotNull
@Size(min = 1, max = 1)
@Column(name = "genero")
private Character genero;
@Lob
@NotNull
@Column(name = "direccion")
private String direccion;
@Column(name = "email")
@Pattern(regexp = "^[A-Za-z0-9_.-]+@(.+)$")
private String email;
@OneToOne(mappedBy = "datosPersonales",targetEntity = Empleado.class)
private Empleado empleado;
@OneToOne(mappedBy = "datosPersonales",targetEntity = Cliente.class)
private Cliente cliente;
public Persona() {
}
public Persona(Long id) {
this.id = id;
}
public Persona(Long id, String nombre, String apellidopaterno, String apellidomaterno, String dui, String nit, LocalDate fechaNacimiento, String telefono, Character genero, String direccion, String email) {
this.id = id;
this.nombre = nombre;
this.apellidopaterno = apellidopaterno;
this.apellidomaterno = apellidomaterno;
this.dui = dui;
this.nit = nit;
this.fechaNacimiento = fechaNacimiento;
this.telefono = telefono;
this.genero=genero;
this.direccion = direccion;
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellidopaterno() {
return apellidopaterno;
}
public void setApellidopaterno(String apellidopaterno) {
this.apellidopaterno = apellidopaterno;
}
public String getApellidomaterno() {
return apellidomaterno;
}
public void setApellidomaterno(String apellidomaterno) {
this.apellidomaterno = apellidomaterno;
}
public String getDui() {
return dui;
}
public void setDui(String dui) {
this.dui = dui;
}
public String getNit() {
return nit;
}
public void setNit(String nit) {
this.nit = nit;
}
public LocalDate getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(LocalDate fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public Character getGenero() {
return genero;
}
public void setGenero(Character genero) {
this.genero = genero;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Persona{" +
"id=" + id +
", nombre='" + nombre + '\'' +
", apellidopaterno='" + apellidopaterno + '\'' +
", apellidomaterno='" + apellidomaterno + '\'' +
", dui='" + dui + '\'' +
", nit='" + nit + '\'' +
", fechaNacimiento=" + fechaNacimiento +
", telefono='" + telefono + '\'' +
", genero=" + genero +
", direccion='" + direccion + '\'' +
", email='" + email + '\'' +
'}';
}
}
| UTF-8 | Java | 5,619 | java | Persona.java | Java | [
{
"context": " \"id=\" + id +\r\n \", nombre='\" + nombre + '\\'' +\r\n \", apellidopaterno='\" +",
"end": 5110,
"score": 0.6946651935577393,
"start": 5104,
"tag": "NAME",
"value": "nombre"
}
] | null | [] | package ferreteria.sv.edu.unab.Dominio;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(schema = "flr", name = "personas")
@SequenceGenerator(schema = "flr",sequenceName = "personas_id_seq",name = "Persona_seq_id",allocationSize = 1)
@NamedQueries({
@NamedQuery(name = "Persona.findAll",query = "SELECT p FROM Persona p"),
@NamedQuery(name = "Persona.findByNombre",query = "SELECT p FROM Persona p where p.nombre =:nombre")
})
public class Persona implements Serializable {
private static final long serialVersionUID=1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Persona_seq_id")
@Column(name = "id")
private Long id;
@NotNull
@Column(name = "nombre")
private String nombre;
@NotNull
@Size(min = 5,max = 50)
@Column(name = "apellidopaterno")
private String apellidopaterno;
@Column(name = "apellidomaterno")
private String apellidomaterno;
@NotNull
@Column(name = "dui")
private String dui;
@NotNull
@Column(name = "nit")
private String nit;
@NotNull
@Column(name = "fechanacimiento")
private LocalDate fechaNacimiento;
@NotNull
@Size(min = 8)
@Column(name = "telefono")
private String telefono;
@NotNull
@Size(min = 1, max = 1)
@Column(name = "genero")
private Character genero;
@Lob
@NotNull
@Column(name = "direccion")
private String direccion;
@Column(name = "email")
@Pattern(regexp = "^[A-Za-z0-9_.-]+@(.+)$")
private String email;
@OneToOne(mappedBy = "datosPersonales",targetEntity = Empleado.class)
private Empleado empleado;
@OneToOne(mappedBy = "datosPersonales",targetEntity = Cliente.class)
private Cliente cliente;
public Persona() {
}
public Persona(Long id) {
this.id = id;
}
public Persona(Long id, String nombre, String apellidopaterno, String apellidomaterno, String dui, String nit, LocalDate fechaNacimiento, String telefono, Character genero, String direccion, String email) {
this.id = id;
this.nombre = nombre;
this.apellidopaterno = apellidopaterno;
this.apellidomaterno = apellidomaterno;
this.dui = dui;
this.nit = nit;
this.fechaNacimiento = fechaNacimiento;
this.telefono = telefono;
this.genero=genero;
this.direccion = direccion;
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellidopaterno() {
return apellidopaterno;
}
public void setApellidopaterno(String apellidopaterno) {
this.apellidopaterno = apellidopaterno;
}
public String getApellidomaterno() {
return apellidomaterno;
}
public void setApellidomaterno(String apellidomaterno) {
this.apellidomaterno = apellidomaterno;
}
public String getDui() {
return dui;
}
public void setDui(String dui) {
this.dui = dui;
}
public String getNit() {
return nit;
}
public void setNit(String nit) {
this.nit = nit;
}
public LocalDate getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(LocalDate fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public Character getGenero() {
return genero;
}
public void setGenero(Character genero) {
this.genero = genero;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Persona{" +
"id=" + id +
", nombre='" + nombre + '\'' +
", apellidopaterno='" + apellidopaterno + '\'' +
", apellidomaterno='" + apellidomaterno + '\'' +
", dui='" + dui + '\'' +
", nit='" + nit + '\'' +
", fechaNacimiento=" + fechaNacimiento +
", telefono='" + telefono + '\'' +
", genero=" + genero +
", direccion='" + direccion + '\'' +
", email='" + email + '\'' +
'}';
}
}
| 5,619 | 0.601886 | 0.600107 | 203 | 25.679804 | 23.99345 | 210 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.497537 | false | false | 14 |
fac784382710c7681c6783d02e3f7c87ee1ceb15 | 34,479,997,486,979 | 1b47ebfc7a576d5aa647a7b797d38c68dff27825 | /app/src/main/java/com/macode/supapp/FindFriendActivity.java | 57a71bfbd8e776053a1a534ac57b28cd99f49e72 | [
"MIT"
] | permissive | kuya32/SupApp | https://github.com/kuya32/SupApp | 58217305a73b988fe2f15703324f9b0d0097273c | b0e91fb7623818eda15fffb3d0487c528843a2bc | refs/heads/main | 2023-03-04T12:41:38.745000 | 2021-02-15T05:21:20 | 2021-02-15T05:21:20 | 333,844,207 | 0 | 0 | MIT | false | 2021-02-15T05:21:21 | 2021-01-28T18:09:16 | 2021-02-15T05:16:06 | 2021-02-15T05:21:20 | 437 | 0 | 0 | 0 | Java | false | false | package com.macode.supapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.macode.supapp.utilities.FindFriendViewHolder;
import com.macode.supapp.utilities.Users;
import com.squareup.picasso.Picasso;
public class FindFriendActivity extends AppCompatActivity {
private FirebaseRecyclerOptions<Users> userOptions;
private FirebaseRecyclerAdapter<Users, FindFriendViewHolder> userAdapter;
private Toolbar toolbar;
private DatabaseReference userReference;
private FirebaseAuth firebaseAuth;
private FirebaseUser firebaseUser;
private RecyclerView addFindFriendRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_friend);
toolbar = findViewById(R.id.findFriendAppBar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Find Friends");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
addFindFriendRecyclerView = findViewById(R.id.findFriendRecyclerView);
addFindFriendRecyclerView.setLayoutManager(new LinearLayoutManager(this));
userReference = FirebaseDatabase.getInstance().getReference().child("Users");
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
loadUsers("");
}
private void loadUsers(String string) {
Query query = userReference.orderByChild("username").startAt(string).endAt(string + "\uf8ff");
userOptions = new FirebaseRecyclerOptions.Builder<Users>().setQuery(query, Users.class).build();
userAdapter = new FirebaseRecyclerAdapter<Users, FindFriendViewHolder>(userOptions) {
@Override
protected void onBindViewHolder(@NonNull FindFriendViewHolder holder, int position, @NonNull Users model) {
if (!firebaseUser.getUid().equals(getRef(position).getKey().toString())) {
Picasso.get().load(model.getProfileImage()).into(holder.findFriendProfileImage);
holder.findFriendUsername.setText(model.getUsername());
holder.findFriendProfession.setText(model.getProfession());
holder.findFriendStatus.setText(model.getStatus());
if (model.getStatus().equals("Online")) {
holder.statusIndicatorImage.setColorFilter(Color.GREEN);
}
} else {
holder.itemView.setVisibility(View.GONE);
holder.itemView.setLayoutParams(new RecyclerView.LayoutParams(0, 0));
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FindFriendActivity.this, ViewFriendActivity.class);
intent.putExtra("userKey", getRef(position).getKey().toString());
startActivity(intent);
}
});
}
@NonNull
@Override
public FindFriendViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_view_find_friend, parent, false);
return new FindFriendViewHolder(view);
}
};
userAdapter.startListening();
addFindFriendRecyclerView.setAdapter(userAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);
MenuItem menuItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
loadUsers(newText);
return false;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
} | UTF-8 | Java | 5,396 | java | FindFriendActivity.java | Java | [] | null | [] | package com.macode.supapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.macode.supapp.utilities.FindFriendViewHolder;
import com.macode.supapp.utilities.Users;
import com.squareup.picasso.Picasso;
public class FindFriendActivity extends AppCompatActivity {
private FirebaseRecyclerOptions<Users> userOptions;
private FirebaseRecyclerAdapter<Users, FindFriendViewHolder> userAdapter;
private Toolbar toolbar;
private DatabaseReference userReference;
private FirebaseAuth firebaseAuth;
private FirebaseUser firebaseUser;
private RecyclerView addFindFriendRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_friend);
toolbar = findViewById(R.id.findFriendAppBar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Find Friends");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
addFindFriendRecyclerView = findViewById(R.id.findFriendRecyclerView);
addFindFriendRecyclerView.setLayoutManager(new LinearLayoutManager(this));
userReference = FirebaseDatabase.getInstance().getReference().child("Users");
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
loadUsers("");
}
private void loadUsers(String string) {
Query query = userReference.orderByChild("username").startAt(string).endAt(string + "\uf8ff");
userOptions = new FirebaseRecyclerOptions.Builder<Users>().setQuery(query, Users.class).build();
userAdapter = new FirebaseRecyclerAdapter<Users, FindFriendViewHolder>(userOptions) {
@Override
protected void onBindViewHolder(@NonNull FindFriendViewHolder holder, int position, @NonNull Users model) {
if (!firebaseUser.getUid().equals(getRef(position).getKey().toString())) {
Picasso.get().load(model.getProfileImage()).into(holder.findFriendProfileImage);
holder.findFriendUsername.setText(model.getUsername());
holder.findFriendProfession.setText(model.getProfession());
holder.findFriendStatus.setText(model.getStatus());
if (model.getStatus().equals("Online")) {
holder.statusIndicatorImage.setColorFilter(Color.GREEN);
}
} else {
holder.itemView.setVisibility(View.GONE);
holder.itemView.setLayoutParams(new RecyclerView.LayoutParams(0, 0));
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FindFriendActivity.this, ViewFriendActivity.class);
intent.putExtra("userKey", getRef(position).getKey().toString());
startActivity(intent);
}
});
}
@NonNull
@Override
public FindFriendViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_view_find_friend, parent, false);
return new FindFriendViewHolder(view);
}
};
userAdapter.startListening();
addFindFriendRecyclerView.setAdapter(userAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);
MenuItem menuItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
loadUsers(newText);
return false;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
} | 5,396 | 0.660304 | 0.659748 | 126 | 40.84127 | 29.783455 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 7 |
6147fa09663d8be45c237dbaa68ef8eaea5c19f7 | 35,184,372,104,484 | aa56c0682fb25859ff54ab638bf73e34cfbe820b | /City_Maker/src/Buildings/Infrastructures/Hospital.java | a67e3dba7ab275d6db94f3d3d41d7b0e27362191 | [
"MIT"
] | permissive | G43riko/Java | https://github.com/G43riko/Java | 11f7211abbc2bc74b46f33996c764f3cad88cc27 | de5066a5fa360b4d242038ed9b9ec83bffa786d2 | refs/heads/master | 2020-06-02T14:05:08.814000 | 2016-01-24T17:17:49 | 2016-01-24T17:17:49 | 27,553,989 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Buildings.Infrastructures;
import Buildings.Building;
public class Hospital extends Building{
public int price = 4000;
public Hospital(){
}
public void dajZamestancomVyplatu() {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 260 | java | Hospital.java | Java | [] | null | [] | package Buildings.Infrastructures;
import Buildings.Building;
public class Hospital extends Building{
public int price = 4000;
public Hospital(){
}
public void dajZamestancomVyplatu() {
// TODO Auto-generated method stub
}
}
| 260 | 0.684615 | 0.669231 | 16 | 14.25 | 15.650479 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 7 |
2909f94eadaaaf6af219684d9ebcbe2febe7cc04 | 35,467,839,940,910 | fe67e2c97988e2b577f7133f37dc0a6a6436781d | /src/com/seeyon/apps/sygb/bo/GbBpResultDataBo.java | e828e54dc0159f5db08b89f7d0a5420c09788538 | [] | no_license | flypig5211/test | https://github.com/flypig5211/test | a8ac2a372df0d58f7357fa2bc519db2edcd917ec | 8794f8f78df92b05b088e826af7a7b37ab95b975 | refs/heads/master | 2023-04-05T03:06:25.921000 | 2020-05-24T06:32:50 | 2020-05-24T06:32:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.seeyon.apps.sygb.bo;
/**
* 项目:国家博物馆客开
* <p> Package: com.seeyon.apps.sygb.bo </p>
* <p> File: GbResultDataBo.java </p>
* <p> Module: 公文接口 </p>
* <p> Description: [推回公文数据返回值对象 ] </p>
* <p> Date: 2020-4-16 11:01</p>
*
* @author ML
* @version 1.0
* @email <a href="mailto:malei12257@163.com">ML</a>
* @date 2020-4-16 11:01
* @since jdk1.8
*/
public class GbBpResultDataBo {
/**
* 第三方系统编码(判断是否是有权限的系统编码)
*/
private String systemCode;
/**
* 第三方传递的业务码
*/
private String thirdBusinessCode;
/**
* 公文相关数据
*/
private GbBpDataBo data;
public String getSystemCode() {
return systemCode;
}
public void setSystemCode(String systemCode) {
this.systemCode = systemCode;
}
public String getThirdBusinessCode() {
return thirdBusinessCode;
}
public void setThirdBusinessCode(String thirdBusinessCode) {
this.thirdBusinessCode = thirdBusinessCode;
}
public GbBpDataBo getData() {
return data;
}
public void setData(GbBpDataBo data) {
this.data = data;
}
}
| UTF-8 | Java | 1,243 | java | GbBpResultDataBo.java | Java | [
{
"context": "/p>\n * <p> Date: 2020-4-16 11:01</p>\n *\n * @author ML\n * @version 1.0\n * @email <a href=\"mailto:malei12",
"end": 249,
"score": 0.9766616225242615,
"start": 247,
"tag": "USERNAME",
"value": "ML"
},
{
"context": "thor ML\n * @version 1.0\n * @email <a href=\"mailto:... | null | [] | package com.seeyon.apps.sygb.bo;
/**
* 项目:国家博物馆客开
* <p> Package: com.seeyon.apps.sygb.bo </p>
* <p> File: GbResultDataBo.java </p>
* <p> Module: 公文接口 </p>
* <p> Description: [推回公文数据返回值对象 ] </p>
* <p> Date: 2020-4-16 11:01</p>
*
* @author ML
* @version 1.0
* @email <a href="mailto:<EMAIL>">ML</a>
* @date 2020-4-16 11:01
* @since jdk1.8
*/
public class GbBpResultDataBo {
/**
* 第三方系统编码(判断是否是有权限的系统编码)
*/
private String systemCode;
/**
* 第三方传递的业务码
*/
private String thirdBusinessCode;
/**
* 公文相关数据
*/
private GbBpDataBo data;
public String getSystemCode() {
return systemCode;
}
public void setSystemCode(String systemCode) {
this.systemCode = systemCode;
}
public String getThirdBusinessCode() {
return thirdBusinessCode;
}
public void setThirdBusinessCode(String thirdBusinessCode) {
this.thirdBusinessCode = thirdBusinessCode;
}
public GbBpDataBo getData() {
return data;
}
public void setData(GbBpDataBo data) {
this.data = data;
}
}
| 1,232 | 0.606792 | 0.576407 | 55 | 19.345455 | 17.008253 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | false | false | 7 |
ffc746ac32911568228c3d3c2e0ad84fabaa872b | 25,769,873,704 | e5340ee95b8eec1dff5812efeb70ae023eca15cc | /OfficeAssistant/src/com/lzz/officeassistant/order/OrderMeetingRoomActivity.java | cea4c7f0e78b2305a6436c1f3ed70930ace03de9 | [] | no_license | skycobo/OfficeAssistant | https://github.com/skycobo/OfficeAssistant | 9feeba80605f2951581bd2489c0008be3cbb3866 | 1ce2d15528177210eaf9734e231a0fe6d5b8c889 | refs/heads/master | 2021-01-13T08:24:55.783000 | 2016-11-24T04:40:30 | 2016-11-24T04:40:30 | 72,411,123 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lzz.officeassistant.order;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import com.lzz.officeassistant.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class OrderMeetingRoomActivity extends Activity implements View.OnTouchListener{
private EditText et_orderMR_topic;
private EditText et_orderMR_startTime;
private EditText et_orderMR_endTime;
private String [] timeArray;
private String mRGID;
private String name;
private String orderTeam;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
String response = (String) msg.obj;
if(response.equals("预约成功!")){
Toast.makeText(OrderMeetingRoomActivity.this, "预约成功!", 0).show();
onBackPressed();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_mr);
SharedPreferences sp = getSharedPreferences("currentUser", Context.MODE_PRIVATE);
String currentUser = sp.getString("account", null);
sp = getSharedPreferences(currentUser,Context.MODE_PRIVATE);
orderTeam = sp.getString("teamID", null);
et_orderMR_topic = (EditText) findViewById(R.id.et_orderMR_topic);
et_orderMR_startTime = (EditText) findViewById(R.id.et_orderMR_startTime);
et_orderMR_endTime = (EditText)findViewById(R.id.et_orderMR_endTime);
Button b_orderMR_order = (Button) findViewById(R.id.b_orderMR_order);
Intent i = getIntent();
mRGID = i.getStringExtra("mRGID");
name = i.getStringExtra("name");
String time = i.getStringExtra("time");
System.out.println(time);
timeArray = time.split("\\.");
b_orderMR_order.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(!et_orderMR_topic.getText().toString().equals("")){
if(!et_orderMR_startTime.getText().toString().equals("")&&!et_orderMR_endTime.getText().toString().equals("")){
String startTime = et_orderMR_startTime.getText().toString();
String endTime = et_orderMR_endTime.getText().toString();
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date d1 = null;
Date d2 = null;
Date now = new Date();
try {
d1 = s.parse(startTime);
d2 = s.parse(endTime);
now = s.parse(s.format(now));
} catch (ParseException e) {
e.printStackTrace();
}
if(d1.getTime()<d2.getTime()){
if(d1.getTime()>=now.getTime()){
int counter = 0;
Date start = null;
Date end = null;
for(int i =0;i<timeArray.length/2;i++){
try {
start = s.parse(timeArray[2*i]);
end = s.parse(timeArray[2*i+1]);
} catch (ParseException e) {
e.printStackTrace();
}
if(d1.getTime()>=end.getTime()||d2.getTime()<=start.getTime()){
counter ++;
}
}
if(counter == timeArray.length/2){
orderMeetingRoom();
}else{
Toast.makeText(OrderMeetingRoomActivity.this, "预定会议时间有冲突!", 0).show();
}
}else{
Toast.makeText(OrderMeetingRoomActivity.this, "开始时间不应早于现在!", 0).show();
}
}else{
Toast.makeText(OrderMeetingRoomActivity.this, "开始时间应该早于结束时间!", 0).show();
}
}else{
Toast.makeText(OrderMeetingRoomActivity.this, "会议时间不能为空!", 0).show();
}
}else{
Toast.makeText(OrderMeetingRoomActivity.this, "会议标题不能为空!", 0).show();
}
}
});
et_orderMR_startTime.setOnTouchListener(this);
et_orderMR_endTime.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = View.inflate(this, R.layout.data_time_dialog, null);
final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
final TimePicker timePicker = (android.widget.TimePicker) view.findViewById(R.id.time_picker);
builder.setView(view);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);
timePicker.setIs24HourView(true);
timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
timePicker.setCurrentMinute(Calendar.MINUTE);
if (v.getId() == R.id.et_orderMR_startTime) {
final int inType = et_orderMR_startTime.getInputType();
et_orderMR_startTime.setInputType(InputType.TYPE_NULL);
et_orderMR_startTime.onTouchEvent(event);
et_orderMR_startTime.setInputType(inType);
et_orderMR_startTime.setSelection(et_orderMR_startTime.getText().length());
builder.setTitle("选取起始时间");
builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
StringBuffer sb = new StringBuffer();
sb.append(String.format("%d-%02d-%02d",
datePicker.getYear(),
datePicker.getMonth() + 1,
datePicker.getDayOfMonth()));
sb.append(" ");
sb.append(String.format("%02d:%02d",
timePicker.getCurrentHour(),
timePicker.getCurrentMinute()));
et_orderMR_startTime.setText(sb);
et_orderMR_endTime.requestFocus();
dialog.cancel();
}
});
} else if (v.getId() == R.id.et_orderMR_endTime) {
int inType = et_orderMR_endTime.getInputType();
et_orderMR_endTime.setInputType(InputType.TYPE_NULL);
et_orderMR_endTime.onTouchEvent(event);
et_orderMR_endTime.setInputType(inType);
et_orderMR_endTime.setSelection(et_orderMR_endTime.getText().length());
builder.setTitle("选取结束时间");
builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
StringBuffer sb = new StringBuffer();
sb.append(String.format("%d-%02d-%02d",
datePicker.getYear(),
datePicker.getMonth() + 1,
datePicker.getDayOfMonth()));
sb.append(" ");
sb.append(String.format("%02d:%02d",
timePicker.getCurrentHour(),
timePicker.getCurrentMinute()));
et_orderMR_endTime.setText(sb);
dialog.cancel();
}
});
}
Dialog dialog = builder.create();
dialog.show();
}
return true;
}
private void orderMeetingRoom(){
new Thread(new Runnable(){
@Override
public void run() {
HttpClient httpClient=null;
try{
httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.skycobo.com:8080/OfficeAssistantServer/OrderMeetingRoom");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mRGID",mRGID));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("topic", et_orderMR_topic.getText().toString()));
params.add(new BasicNameValuePair("orderTeam", orderTeam));
params.add(new BasicNameValuePair("startTime", et_orderMR_startTime.getText().toString()));
params.add(new BasicNameValuePair("endTime", et_orderMR_endTime.getText().toString()));
System.out.println("dd"+et_orderMR_startTime.getText().toString().length());
UrlEncodedFormEntity entry = new UrlEncodedFormEntity(params,"utf-8");
httpPost.setEntity(entry);
HttpResponse httpResponse = httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode() == 200){
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity,"utf-8");
Message message = new Message();
message.what = 0;
message.obj = response;
handler.sendMessage(message);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(httpClient!=null){
httpClient.getConnectionManager().shutdown();
}
}
}
}).start();
}
}
| UTF-8 | Java | 10,414 | java | OrderMeetingRoomActivity.java | Java | [] | null | [] | package com.lzz.officeassistant.order;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import com.lzz.officeassistant.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class OrderMeetingRoomActivity extends Activity implements View.OnTouchListener{
private EditText et_orderMR_topic;
private EditText et_orderMR_startTime;
private EditText et_orderMR_endTime;
private String [] timeArray;
private String mRGID;
private String name;
private String orderTeam;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
String response = (String) msg.obj;
if(response.equals("预约成功!")){
Toast.makeText(OrderMeetingRoomActivity.this, "预约成功!", 0).show();
onBackPressed();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_mr);
SharedPreferences sp = getSharedPreferences("currentUser", Context.MODE_PRIVATE);
String currentUser = sp.getString("account", null);
sp = getSharedPreferences(currentUser,Context.MODE_PRIVATE);
orderTeam = sp.getString("teamID", null);
et_orderMR_topic = (EditText) findViewById(R.id.et_orderMR_topic);
et_orderMR_startTime = (EditText) findViewById(R.id.et_orderMR_startTime);
et_orderMR_endTime = (EditText)findViewById(R.id.et_orderMR_endTime);
Button b_orderMR_order = (Button) findViewById(R.id.b_orderMR_order);
Intent i = getIntent();
mRGID = i.getStringExtra("mRGID");
name = i.getStringExtra("name");
String time = i.getStringExtra("time");
System.out.println(time);
timeArray = time.split("\\.");
b_orderMR_order.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(!et_orderMR_topic.getText().toString().equals("")){
if(!et_orderMR_startTime.getText().toString().equals("")&&!et_orderMR_endTime.getText().toString().equals("")){
String startTime = et_orderMR_startTime.getText().toString();
String endTime = et_orderMR_endTime.getText().toString();
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date d1 = null;
Date d2 = null;
Date now = new Date();
try {
d1 = s.parse(startTime);
d2 = s.parse(endTime);
now = s.parse(s.format(now));
} catch (ParseException e) {
e.printStackTrace();
}
if(d1.getTime()<d2.getTime()){
if(d1.getTime()>=now.getTime()){
int counter = 0;
Date start = null;
Date end = null;
for(int i =0;i<timeArray.length/2;i++){
try {
start = s.parse(timeArray[2*i]);
end = s.parse(timeArray[2*i+1]);
} catch (ParseException e) {
e.printStackTrace();
}
if(d1.getTime()>=end.getTime()||d2.getTime()<=start.getTime()){
counter ++;
}
}
if(counter == timeArray.length/2){
orderMeetingRoom();
}else{
Toast.makeText(OrderMeetingRoomActivity.this, "预定会议时间有冲突!", 0).show();
}
}else{
Toast.makeText(OrderMeetingRoomActivity.this, "开始时间不应早于现在!", 0).show();
}
}else{
Toast.makeText(OrderMeetingRoomActivity.this, "开始时间应该早于结束时间!", 0).show();
}
}else{
Toast.makeText(OrderMeetingRoomActivity.this, "会议时间不能为空!", 0).show();
}
}else{
Toast.makeText(OrderMeetingRoomActivity.this, "会议标题不能为空!", 0).show();
}
}
});
et_orderMR_startTime.setOnTouchListener(this);
et_orderMR_endTime.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = View.inflate(this, R.layout.data_time_dialog, null);
final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
final TimePicker timePicker = (android.widget.TimePicker) view.findViewById(R.id.time_picker);
builder.setView(view);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);
timePicker.setIs24HourView(true);
timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
timePicker.setCurrentMinute(Calendar.MINUTE);
if (v.getId() == R.id.et_orderMR_startTime) {
final int inType = et_orderMR_startTime.getInputType();
et_orderMR_startTime.setInputType(InputType.TYPE_NULL);
et_orderMR_startTime.onTouchEvent(event);
et_orderMR_startTime.setInputType(inType);
et_orderMR_startTime.setSelection(et_orderMR_startTime.getText().length());
builder.setTitle("选取起始时间");
builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
StringBuffer sb = new StringBuffer();
sb.append(String.format("%d-%02d-%02d",
datePicker.getYear(),
datePicker.getMonth() + 1,
datePicker.getDayOfMonth()));
sb.append(" ");
sb.append(String.format("%02d:%02d",
timePicker.getCurrentHour(),
timePicker.getCurrentMinute()));
et_orderMR_startTime.setText(sb);
et_orderMR_endTime.requestFocus();
dialog.cancel();
}
});
} else if (v.getId() == R.id.et_orderMR_endTime) {
int inType = et_orderMR_endTime.getInputType();
et_orderMR_endTime.setInputType(InputType.TYPE_NULL);
et_orderMR_endTime.onTouchEvent(event);
et_orderMR_endTime.setInputType(inType);
et_orderMR_endTime.setSelection(et_orderMR_endTime.getText().length());
builder.setTitle("选取结束时间");
builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
StringBuffer sb = new StringBuffer();
sb.append(String.format("%d-%02d-%02d",
datePicker.getYear(),
datePicker.getMonth() + 1,
datePicker.getDayOfMonth()));
sb.append(" ");
sb.append(String.format("%02d:%02d",
timePicker.getCurrentHour(),
timePicker.getCurrentMinute()));
et_orderMR_endTime.setText(sb);
dialog.cancel();
}
});
}
Dialog dialog = builder.create();
dialog.show();
}
return true;
}
private void orderMeetingRoom(){
new Thread(new Runnable(){
@Override
public void run() {
HttpClient httpClient=null;
try{
httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.skycobo.com:8080/OfficeAssistantServer/OrderMeetingRoom");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mRGID",mRGID));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("topic", et_orderMR_topic.getText().toString()));
params.add(new BasicNameValuePair("orderTeam", orderTeam));
params.add(new BasicNameValuePair("startTime", et_orderMR_startTime.getText().toString()));
params.add(new BasicNameValuePair("endTime", et_orderMR_endTime.getText().toString()));
System.out.println("dd"+et_orderMR_startTime.getText().toString().length());
UrlEncodedFormEntity entry = new UrlEncodedFormEntity(params,"utf-8");
httpPost.setEntity(entry);
HttpResponse httpResponse = httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode() == 200){
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity,"utf-8");
Message message = new Message();
message.what = 0;
message.obj = response;
handler.sendMessage(message);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(httpClient!=null){
httpClient.getConnectionManager().shutdown();
}
}
}
}).start();
}
}
| 10,414 | 0.622274 | 0.617212 | 273 | 36.626373 | 26.233238 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.523809 | false | false | 7 |
1399844f88b8f1dd9e8eac5123e201d7cd87115d | 36,644,660,975,222 | 571e2788fa8543d417d5254cd67b665d4df03789 | /src/main/java/com/iktpreobuka/eDnevnik/repositories/ClassRepository.java | 57041fd075fe633fbf180402ce5384bb1bc4869a | [] | no_license | Stefan89-git/eDnevnik | https://github.com/Stefan89-git/eDnevnik | 7169c8f2922449e5398f8011d4cd0bab1458c087 | 8ae7272a111d98346486f61ef248ff69007cd0bb | refs/heads/main | 2023-07-08T23:02:59.611000 | 2021-08-01T23:17:34 | 2021-08-01T23:17:34 | 391,745,459 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.iktpreobuka.eDnevnik.repositories;
import org.springframework.data.repository.CrudRepository;
import com.iktpreobuka.eDnevnik.entities.ClassEntity;
public interface ClassRepository extends CrudRepository<ClassEntity, Integer>{
Boolean existsByClassNumberAndSchoolYear(Integer classNumber, Integer schoolYear);
}
| UTF-8 | Java | 329 | java | ClassRepository.java | Java | [] | null | [] | package com.iktpreobuka.eDnevnik.repositories;
import org.springframework.data.repository.CrudRepository;
import com.iktpreobuka.eDnevnik.entities.ClassEntity;
public interface ClassRepository extends CrudRepository<ClassEntity, Integer>{
Boolean existsByClassNumberAndSchoolYear(Integer classNumber, Integer schoolYear);
}
| 329 | 0.860182 | 0.860182 | 10 | 31.9 | 33.296997 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 7 |
321f39570f8d02c2778db7cca70472978318c5a3 | 31,301,721,701,739 | b2538660b4f6d855ab4d4d4429c26025e40d9e2f | /src/main/java/model/method/pso/hdpso/core/FitnessCalculator.java | be7eaa62b4b2109b81fd9577f1037eb1d08e04b7 | [] | no_license | Syafiqq/skripsi.hdpso.scheduling | https://github.com/Syafiqq/skripsi.hdpso.scheduling | 0b06e18aa2db657646e6196ea21aef7df0ed60f8 | aed84cea961c5842f38b19fed54ddf2fbaf5d353 | refs/heads/master | 2021-01-19T08:12:45.722000 | 2017-03-27T03:23:37 | 2017-03-27T03:23:37 | 72,266,178 | 0 | 0 | null | false | 2019-05-21T23:33:26 | 2016-10-29T05:09:42 | 2017-04-07T10:58:58 | 2019-05-21T23:33:22 | 1,046 | 0 | 0 | 1 | Java | false | false | package model.method.pso.hdpso.core;
/*
* This <skripsi.hdpso.scheduling> project in package <model.method.pso.hdpso.core> created by :
* Name : syafiq
* Date / Time : 22 November 2016, 4:21 PM.
* Email : syafiq.rezpector@gmail.com
* Github : syafiqq
*/
@SuppressWarnings("WeakerAccess") public interface FitnessCalculator<T>
{
void calculate(T data);
}
| UTF-8 | Java | 388 | java | FitnessCalculator.java | Java | [
{
"context": "od.pso.hdpso.core> created by : \n * Name : syafiq\n * Date / Time : 22 November 2016, 4:21 PM.\n * E",
"end": 163,
"score": 0.8237862586975098,
"start": 157,
"tag": "USERNAME",
"value": "syafiq"
},
{
"context": "me : 22 November 2016, 4:21 PM.\n * Email ... | null | [] | package model.method.pso.hdpso.core;
/*
* This <skripsi.hdpso.scheduling> project in package <model.method.pso.hdpso.core> created by :
* Name : syafiq
* Date / Time : 22 November 2016, 4:21 PM.
* Email : <EMAIL>
* Github : syafiqq
*/
@SuppressWarnings("WeakerAccess") public interface FitnessCalculator<T>
{
void calculate(T data);
}
| 369 | 0.67268 | 0.649485 | 13 | 28.846153 | 28.750507 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 7 |
ad55e69f7f524b5c80013f191d7b0a12f533f9e8 | 32,839,319,992,969 | b5d0e54b3299fc814a81b77467b4799d21ea974d | /JavaPractice/src/com/raj/fundamentals/arrays/ArraysToList.java | 4dfab09a3a8b0686a9a45f66e68e56071681cd85 | [] | no_license | rajkhare1/java-practice | https://github.com/rajkhare1/java-practice | 6f9ab5e5d01e0428e511c72dc6fcab0a7249082f | e140790900361096b15c2185c1a07ce7a30df537 | refs/heads/master | 2020-09-21T14:48:53.200000 | 2020-06-23T05:29:34 | 2020-06-23T05:29:34 | 224,821,760 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.raj.fundamentals.arrays;
import java.util.Arrays;
import java.util.List;
public class ArraysToList {
public static void main(String[] args) {
String[] strArr;
strArr = new String[5];
strArr[0] = "JAVA";
strArr[1] = "C++";
strArr[2] = "PERL";
strArr[3] = "STRUTS";
strArr[4] = "PLAY";
System.out.println("strArr:: "+Arrays.toString(strArr)+" Size of array: "+strArr.length);
//now convert arrays into List
List<String> strList = Arrays.asList(strArr);
System.out.println("Created List Size: "+strList.size());
System.out.println(strList);
}
}
| UTF-8 | Java | 601 | java | ArraysToList.java | Java | [] | null | [] | package com.raj.fundamentals.arrays;
import java.util.Arrays;
import java.util.List;
public class ArraysToList {
public static void main(String[] args) {
String[] strArr;
strArr = new String[5];
strArr[0] = "JAVA";
strArr[1] = "C++";
strArr[2] = "PERL";
strArr[3] = "STRUTS";
strArr[4] = "PLAY";
System.out.println("strArr:: "+Arrays.toString(strArr)+" Size of array: "+strArr.length);
//now convert arrays into List
List<String> strList = Arrays.asList(strArr);
System.out.println("Created List Size: "+strList.size());
System.out.println(strList);
}
}
| 601 | 0.65391 | 0.643927 | 23 | 25.130434 | 21.125513 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.217391 | false | false | 7 |
6955c6347ff1c8fec9777710e5c51427a1eac759 | 35,132,832,512,223 | daa789996d154f0579230b4585e0599ff420ae5d | /TopNews/src/com/huaxun/radio/provider/FMPDemo.java | 2cdba07f582519ec0af52c959561c87e2f04e7b8 | [] | no_license | huaxun66/TopNews | https://github.com/huaxun66/TopNews | 55e4eee126df504169cfc0bcb3caad61f7a4cfa7 | 861e0bb2daab412b01a47da16e39c28d80553a7f | refs/heads/master | 2021-08-19T13:49:20.469000 | 2017-11-26T13:19:57 | 2017-11-26T13:19:57 | 108,969,838 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* FFmpegMediaPlayer: A unified interface for playing audio files and streams.
*
* Copyright 2014 William Seemann
*
* 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.huaxun.radio.provider;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import com.huaxun.R;
import com.huaxun.radio.provider.MusicUtils.ServiceToken;
public class FMPDemo extends FragmentActivity implements ServiceConnection {
private IMediaPlaybackService mService = null;
private ServiceToken mToken;
private Button controlButton;
private long [] list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fmpdemo);
final EditText uriText = (EditText) findViewById(R.id.uri);
// uriText.setText("mms://live.cri.cn/en4");
// uriText.setText("rtsp://alive.rbc.cn/fm974/0/1945285/32/32/2002");
uriText.setText("rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov");
controlButton = (Button)findViewById(R.id.control_button);
controlButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
if (mService.isPlaying()){
mService.pause();
controlButton.setText("播放");
}
if (! mService.isPlaying()){
mService.open(list, 0);
controlButton.setText("暂停");
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
Intent intent = getIntent();
// Populate the edit text field with the intent uri, if available
Uri uri = intent.getData();
if (intent.getExtras() != null &&
intent.getExtras().getCharSequence(Intent.EXTRA_TEXT) != null) {
uri = Uri.parse(intent.getExtras().getCharSequence(Intent.EXTRA_TEXT).toString());
}
if (uri != null) {
try {
uriText.setText(URLDecoder.decode(uri.toString(), "UTF-8"));
} catch (UnsupportedEncodingException e1) {
}
}
setIntent(null);
Button goButton = (Button) findViewById(R.id.go_button);
goButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Clear the error message
uriText.setError(null);
// Hide the keyboard
InputMethodManager imm = (InputMethodManager)
FMPDemo.this.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(uriText.getWindowToken(), 0);
String uri = uriText.getText().toString();
if (uri.equals("")) {
uriText.setError("错误");
return;
}
String uriString = uriText.getText().toString();
try {
list = new long[1];
list[0] = MusicUtils.insert(FMPDemo.this, uriString);
mService.open(list, 0);
controlButton.setText("暂停");
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
mToken = MusicUtils.bindToService(this, this);
}
@Override
public void onDestroy() {
MusicUtils.unbindFromService(mToken);
mService = null;
super.onDestroy();
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IMediaPlaybackService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
finish();
}
}
| UTF-8 | Java | 4,345 | java | FMPDemo.java | Java | [
{
"context": "ying audio files and streams.\n *\n * Copyright 2014 William Seemann\n * \n * Licensed under the Apache License, Version",
"end": 118,
"score": 0.9998070597648621,
"start": 103,
"tag": "NAME",
"value": "William Seemann"
},
{
"context": "945285/32/32/2002\");\n \turiT... | null | [] | /*
* FFmpegMediaPlayer: A unified interface for playing audio files and streams.
*
* Copyright 2014 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.huaxun.radio.provider;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import com.huaxun.R;
import com.huaxun.radio.provider.MusicUtils.ServiceToken;
public class FMPDemo extends FragmentActivity implements ServiceConnection {
private IMediaPlaybackService mService = null;
private ServiceToken mToken;
private Button controlButton;
private long [] list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fmpdemo);
final EditText uriText = (EditText) findViewById(R.id.uri);
// uriText.setText("mms://live.cri.cn/en4");
// uriText.setText("rtsp://alive.rbc.cn/fm974/0/1945285/32/32/2002");
uriText.setText("rtsp://192.168.3.11/vod/mp4:BigBuckBunny_115k.mov");
controlButton = (Button)findViewById(R.id.control_button);
controlButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
if (mService.isPlaying()){
mService.pause();
controlButton.setText("播放");
}
if (! mService.isPlaying()){
mService.open(list, 0);
controlButton.setText("暂停");
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
Intent intent = getIntent();
// Populate the edit text field with the intent uri, if available
Uri uri = intent.getData();
if (intent.getExtras() != null &&
intent.getExtras().getCharSequence(Intent.EXTRA_TEXT) != null) {
uri = Uri.parse(intent.getExtras().getCharSequence(Intent.EXTRA_TEXT).toString());
}
if (uri != null) {
try {
uriText.setText(URLDecoder.decode(uri.toString(), "UTF-8"));
} catch (UnsupportedEncodingException e1) {
}
}
setIntent(null);
Button goButton = (Button) findViewById(R.id.go_button);
goButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Clear the error message
uriText.setError(null);
// Hide the keyboard
InputMethodManager imm = (InputMethodManager)
FMPDemo.this.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(uriText.getWindowToken(), 0);
String uri = uriText.getText().toString();
if (uri.equals("")) {
uriText.setError("错误");
return;
}
String uriString = uriText.getText().toString();
try {
list = new long[1];
list[0] = MusicUtils.insert(FMPDemo.this, uriString);
mService.open(list, 0);
controlButton.setText("暂停");
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
mToken = MusicUtils.bindToService(this, this);
}
@Override
public void onDestroy() {
MusicUtils.unbindFromService(mToken);
mService = null;
super.onDestroy();
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IMediaPlaybackService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
finish();
}
}
| 4,334 | 0.694618 | 0.682837 | 152 | 27.480263 | 23.263357 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.361842 | false | false | 7 |
44e004dd12af8590da2ec3c5ab2bd19d55becbe8 | 36,885,179,148,596 | 188397b55bc65550c6ab0bfa196bfdaf2d16d931 | /android_java/MySecretary/app/src/main/java/com/my/taste/dial/AlarmActivity.java | f52b19ffc9bf68d6011d340cf3d7e93f99b40a2e | [] | no_license | baehyewon/programming | https://github.com/baehyewon/programming | f09f5316c43ebacffca06aae6781c3f934368b11 | 55ed94b2a490665233b115ed7e942e07ece1f624 | refs/heads/master | 2020-03-26T16:50:07.872000 | 2018-09-10T05:33:07 | 2018-09-10T05:33:07 | 145,126,387 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.my.taste.dial;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.my.taste.AlarmUtil;
import com.my.taste.R;
public class AlarmActivity extends Activity implements View.OnClickListener{
private TextView txtMessage;
private Dialog DlgManager = null;
private Button btnOk;
private int intentAlarmId = 0;
private String intentName = "";
private String intentPhone = "";
private String intentBirthday = "";
private String intentMessage = "";
private String intentWill = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
//setContentView(R.layout.activity_alarm);
txtMessage = (TextView) findViewById(R.id.aa_txt_message);
btnOk = (Button)findViewById(R.id.aa_btn_ok);
btnOk.setOnClickListener(this);
}
@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
if(intent != null)
{
intentAlarmId = intent.getIntExtra("alarmId", 0);
intentName = intent.getStringExtra("name");
intentPhone = intent.getStringExtra("phone");
intentBirthday = intent.getStringExtra("birthday");
intentMessage = intent.getStringExtra("message");
intentWill = intent.getStringExtra("will_given_gift");
String AlarmMsg = "";
AlarmMsg = "";
if(intentName!= null)
AlarmMsg = intentName + "의\n";
if (intentWill != null)
AlarmMsg += intentWill + "가\n";
if(intentBirthday != null)
AlarmMsg += intentBirthday + " 입니다!.\n오늘도 화이팅!!";
txtMessage.setText(AlarmMsg);
Vibrator vibrator;
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
AlarmUtil.unregisterAlarm(this, intentAlarmId);
}
}
@Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.aa_btn_ok:
finish();
break;
/*
String[] splitResult = intentBirthday.split("-");
int year = Integer.parseInt(splitResult[0]);
int month = Integer.parseInt(splitResult[1]);
int day = Integer.parseInt(splitResult[2]);
AlarmUtil.setSms(this, intentAlarmId, intentName, intentPhone, intentMessage, year, month-1, day, intentWill);
*/
/*
Intent intent = new Intent(this, SmsActivity.class);
intent.putExtra("name", intentName);
intent.putExtra("phone", intentPhone);
intent.putExtra("message", intentMessage);
startActivity(intent);
*/
}
}
}
| UTF-8 | Java | 3,162 | java | AlarmActivity.java | Java | [] | null | [] | package com.my.taste.dial;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.my.taste.AlarmUtil;
import com.my.taste.R;
public class AlarmActivity extends Activity implements View.OnClickListener{
private TextView txtMessage;
private Dialog DlgManager = null;
private Button btnOk;
private int intentAlarmId = 0;
private String intentName = "";
private String intentPhone = "";
private String intentBirthday = "";
private String intentMessage = "";
private String intentWill = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
//setContentView(R.layout.activity_alarm);
txtMessage = (TextView) findViewById(R.id.aa_txt_message);
btnOk = (Button)findViewById(R.id.aa_btn_ok);
btnOk.setOnClickListener(this);
}
@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
if(intent != null)
{
intentAlarmId = intent.getIntExtra("alarmId", 0);
intentName = intent.getStringExtra("name");
intentPhone = intent.getStringExtra("phone");
intentBirthday = intent.getStringExtra("birthday");
intentMessage = intent.getStringExtra("message");
intentWill = intent.getStringExtra("will_given_gift");
String AlarmMsg = "";
AlarmMsg = "";
if(intentName!= null)
AlarmMsg = intentName + "의\n";
if (intentWill != null)
AlarmMsg += intentWill + "가\n";
if(intentBirthday != null)
AlarmMsg += intentBirthday + " 입니다!.\n오늘도 화이팅!!";
txtMessage.setText(AlarmMsg);
Vibrator vibrator;
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
AlarmUtil.unregisterAlarm(this, intentAlarmId);
}
}
@Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.aa_btn_ok:
finish();
break;
/*
String[] splitResult = intentBirthday.split("-");
int year = Integer.parseInt(splitResult[0]);
int month = Integer.parseInt(splitResult[1]);
int day = Integer.parseInt(splitResult[2]);
AlarmUtil.setSms(this, intentAlarmId, intentName, intentPhone, intentMessage, year, month-1, day, intentWill);
*/
/*
Intent intent = new Intent(this, SmsActivity.class);
intent.putExtra("name", intentName);
intent.putExtra("phone", intentPhone);
intent.putExtra("message", intentMessage);
startActivity(intent);
*/
}
}
}
| 3,162 | 0.599363 | 0.596178 | 106 | 28.622641 | 24.210732 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.669811 | false | false | 7 |
9ab28909b84c2a24bdf00e114875f3c068656391 | 36,885,179,150,154 | 437bd13017a1c3d01194cd9d1250b8bb55b0de32 | /src/main/java/com/example/ing2/entity/test.java | 57767c5b3bab02a56da21227569d9dd4fc0de897 | [] | no_license | kamalmorinou2018/pds-ing-2 | https://github.com/kamalmorinou2018/pds-ing-2 | 024772a48469b3f1020d5989814637078f12e411 | 72b3b50320a72898318acb10e614aceb4ba22f72 | refs/heads/master | 2022-12-22T06:15:08.121000 | 2020-06-07T22:15:02 | 2020-06-07T22:15:02 | 269,621,208 | 0 | 0 | null | false | 2022-12-10T05:59:22 | 2020-06-05T11:57:36 | 2020-06-07T22:25:41 | 2022-12-10T05:59:21 | 678 | 0 | 0 | 1 | Java | false | false | package com.example.ing2.entity;
| UTF-8 | Java | 36 | java | test.java | Java | [] | null | [] | package com.example.ing2.entity;
| 36 | 0.75 | 0.722222 | 1 | 32 | 0 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 7 |
4af9d3e6bba8df793605d64252467527e9169d7b | 8,443,905,750,378 | abeb3d5b06a5d70ff318df4161e7cec02e00035b | /e6soft-flow/src/main/java/com/e6soft/bpm/dao/FlownodeDao.java | 9f163e6be93b4776d05dd09c453b4b9a29dec21d | [] | no_license | buptlibin/e6soft | https://github.com/buptlibin/e6soft | a3726e4c9321c7924da211756bf580f3cc578353 | 6b3af4c6e3a313fff0189f76ac4bb16feb8a9c77 | refs/heads/master | 2019-04-15T01:32:41.257000 | 2014-06-16T06:33:04 | 2014-06-16T06:33:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.e6soft.bpm.dao;
import java.util.List;
import com.e6soft.bpm.model.Flownode;
import com.e6soft.core.mybatis.EntityDao;
public interface FlownodeDao extends EntityDao<Flownode,String> {
/**
* 根据流程id获取所有节点
* @param flowbaseId
* @return
*/
public List<Flownode> getFlowNodesByflowbaseId(String flowbaseId);
/**
* 判断是否有开始节点
* @param flowbaseId
* @return
*/
public boolean hasStartNode(String flowbaseId);
/**
* 判断是否有结束节点
* @param flowbaseId
* @return
*/
public boolean hasEndNode(String flowbaseId);
/**
* 判断是否所有节点都有表单模板
* @param flowbaseId
* @return
*/
public boolean isAllNodeHasFormModel(String flowbaseId);
/**
* 更加流程ID将节点所有表单模板清空
* @param flowId
*/
public void resetFormModeByFlowId(String flowId);
/**
* 根据流程获取开始节点
* @param flowId
* @return
*/
public Flownode getStartNodeByFlowId(String flowId);
}
| UTF-8 | Java | 1,021 | java | FlownodeDao.java | Java | [] | null | [] | package com.e6soft.bpm.dao;
import java.util.List;
import com.e6soft.bpm.model.Flownode;
import com.e6soft.core.mybatis.EntityDao;
public interface FlownodeDao extends EntityDao<Flownode,String> {
/**
* 根据流程id获取所有节点
* @param flowbaseId
* @return
*/
public List<Flownode> getFlowNodesByflowbaseId(String flowbaseId);
/**
* 判断是否有开始节点
* @param flowbaseId
* @return
*/
public boolean hasStartNode(String flowbaseId);
/**
* 判断是否有结束节点
* @param flowbaseId
* @return
*/
public boolean hasEndNode(String flowbaseId);
/**
* 判断是否所有节点都有表单模板
* @param flowbaseId
* @return
*/
public boolean isAllNodeHasFormModel(String flowbaseId);
/**
* 更加流程ID将节点所有表单模板清空
* @param flowId
*/
public void resetFormModeByFlowId(String flowId);
/**
* 根据流程获取开始节点
* @param flowId
* @return
*/
public Flownode getStartNodeByFlowId(String flowId);
}
| 1,021 | 0.70124 | 0.697858 | 51 | 16.392157 | 18.23171 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.019608 | false | false | 7 |
9c7ce131e8674e57b274c09276e1aebbbd89faf0 | 36,807,869,742,958 | 96705a57dc83485d6c178a7c17e814bc010c0e73 | /Technogise/ChessBoard.java | a7deb849b4219f3d9085fa02e0ff6774e70aae13 | [] | no_license | BhattChandresh/code_CoreJava | https://github.com/BhattChandresh/code_CoreJava | 9f9904b9e9fd9249d07fac78b03bd6e77fe19b9d | 8b2d055a46f5523659984eca3339584842fe5604 | refs/heads/master | 2022-10-24T13:25:09.398000 | 2020-06-10T13:45:19 | 2020-06-10T13:45:19 | 110,662,703 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Version : 1.0
* Author : Chandresh Bhatt
* Objective :
* Convert the Cell Number (H1) received from user to Co-ordinates (0,0) for internal processing.
* After processing, convert the Co-ordinates(7,7) to Cell Number(A8) in order to display the possible cell numbers to user.
*/
package com.technogise.code.interview;
import java.util.HashMap;
import java.util.Map;
public class ChessBoard {
// Declaration for 8X8 Grid
private static int[][] grid = new int[8][8];
//Identify the cell number a name
static Map<String,String> cellPositionToCoordinate = new HashMap<String,String>();
static Map<String,String> CoordinateToCellPosition = new HashMap<String, String>();
// Create and Initialize the 8x8 Grid
static {
System.out.println("Initializing the Chess Board....");
String cellRow = "";
for (int row = 0; row < 8; row++) {
if (row == 0)
cellRow = "H";
else if (row == 1)
cellRow = "G";
else if (row == 2)
cellRow = "F";
else if (row == 3)
cellRow = "E";
else if (row == 4)
cellRow = "D";
else if (row == 5)
cellRow = "C";
else if (row == 6)
cellRow = "B";
else if (row == 7)
cellRow = "A";
for (int column = 0; column < 8; column++) {
grid[row][column] = 0;
String input = Integer.toString(row) + Integer.toString(column);
cellPositionToCoordinate.put((cellRow + (column + 1)),(Integer.toString(row) + Integer.toString(column)));
CoordinateToCellPosition.put(input,(cellRow + (column + 1)));
}
}
System.out.println("Chess Board initialization completes ....");
}
// For production use this method is not required.
// This is for testing purpose only.
public void testInitializationOfChessBoard() {
String cellRow = "";
for(int row=0;row<8;row++) {
System.out.println();
if (row == 0)
cellRow = "H";
else if (row == 1)
cellRow = "G";
else if (row == 2)
cellRow = "F";
else if (row == 3)
cellRow = "E";
else if (row == 4)
cellRow = "D";
else if (row == 5)
cellRow = "C";
else if (row == 6)
cellRow = "B";
else if (row == 7)
cellRow = "A";
for(int column=0;column<8;column++){
//System.out.print("grid["+ row + "][" + column + "] : " + cellPositionToCoordinate.get(cellRow + (column+1)) + " | " + (cellRow + (column+1)));
//System.out.print("[" + row + "][" + column + "] : " + cellPositionToCoordinate.get(cellRow + (column+1)) + " | " + (cellRow + (column+1)) + " || ");
System.out.print("[" + row + "][" + column + "] : " + cellPositionToCoordinate.get(cellRow + (column+1)) + " | " + (cellRow + (column+1)) + " || ");
}
}
System.out.println();
}
}
| UTF-8 | Java | 3,221 | java | ChessBoard.java | Java | [
{
"context": "/**\n * Version : 1.0\n * Author : Chandresh Bhatt\n * Objective :\n * Convert the Cell Number (H1)",
"end": 50,
"score": 0.9998683929443359,
"start": 35,
"tag": "NAME",
"value": "Chandresh Bhatt"
}
] | null | [] | /**
* Version : 1.0
* Author : <NAME>
* Objective :
* Convert the Cell Number (H1) received from user to Co-ordinates (0,0) for internal processing.
* After processing, convert the Co-ordinates(7,7) to Cell Number(A8) in order to display the possible cell numbers to user.
*/
package com.technogise.code.interview;
import java.util.HashMap;
import java.util.Map;
public class ChessBoard {
// Declaration for 8X8 Grid
private static int[][] grid = new int[8][8];
//Identify the cell number a name
static Map<String,String> cellPositionToCoordinate = new HashMap<String,String>();
static Map<String,String> CoordinateToCellPosition = new HashMap<String, String>();
// Create and Initialize the 8x8 Grid
static {
System.out.println("Initializing the Chess Board....");
String cellRow = "";
for (int row = 0; row < 8; row++) {
if (row == 0)
cellRow = "H";
else if (row == 1)
cellRow = "G";
else if (row == 2)
cellRow = "F";
else if (row == 3)
cellRow = "E";
else if (row == 4)
cellRow = "D";
else if (row == 5)
cellRow = "C";
else if (row == 6)
cellRow = "B";
else if (row == 7)
cellRow = "A";
for (int column = 0; column < 8; column++) {
grid[row][column] = 0;
String input = Integer.toString(row) + Integer.toString(column);
cellPositionToCoordinate.put((cellRow + (column + 1)),(Integer.toString(row) + Integer.toString(column)));
CoordinateToCellPosition.put(input,(cellRow + (column + 1)));
}
}
System.out.println("Chess Board initialization completes ....");
}
// For production use this method is not required.
// This is for testing purpose only.
public void testInitializationOfChessBoard() {
String cellRow = "";
for(int row=0;row<8;row++) {
System.out.println();
if (row == 0)
cellRow = "H";
else if (row == 1)
cellRow = "G";
else if (row == 2)
cellRow = "F";
else if (row == 3)
cellRow = "E";
else if (row == 4)
cellRow = "D";
else if (row == 5)
cellRow = "C";
else if (row == 6)
cellRow = "B";
else if (row == 7)
cellRow = "A";
for(int column=0;column<8;column++){
//System.out.print("grid["+ row + "][" + column + "] : " + cellPositionToCoordinate.get(cellRow + (column+1)) + " | " + (cellRow + (column+1)));
//System.out.print("[" + row + "][" + column + "] : " + cellPositionToCoordinate.get(cellRow + (column+1)) + " | " + (cellRow + (column+1)) + " || ");
System.out.print("[" + row + "][" + column + "] : " + cellPositionToCoordinate.get(cellRow + (column+1)) + " | " + (cellRow + (column+1)) + " || ");
}
}
System.out.println();
}
}
| 3,212 | 0.494256 | 0.479665 | 81 | 38.76543 | 34.574047 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.728395 | false | false | 7 |
4edb05c273aa3d4e7a2500362e51cb862099d174 | 33,956,011,484,561 | 0ce177627cc99aca831d2e7693ffc46d3ece4d34 | /src/com/covertatt/MainActivity.java | d8c3395b99d1f3d50eea337dc8d5a7da4471e265 | [] | no_license | pavithraRavichandran3095/Banking-Application | https://github.com/pavithraRavichandran3095/Banking-Application | ff2a2edfb6c9d459434a9c9511540b779c2eb2af | 6f46a7a06bea2c154812251853a31d0816677a0b | refs/heads/master | 2021-01-19T23:57:07.265000 | 2017-04-22T07:48:41 | 2017-04-22T07:48:41 | 89,052,117 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.covertatt;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Random;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.widget.Button;
import android.widget.Toast;
import android.preference.PreferenceManager;
public class MainActivity extends Activity implements CollectionsDataInterface
{
public static Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
Random rand=new Random();
static String Servervalue="";
static String username="",accno="";
DefaultHttpClient httpClient=null;
HttpGet getRequest=null;
HttpResponse res=null;
InputStream is=null;
byte[] b=null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
static Boolean bool=true;
int ch;
// static Context con=null;
// private Button pinb0,pinb1,pinb2,pinb3,pinb4,pinb5,pinb6,pinb7,pinb8,pinb9;
// private Button conformbutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// con=this;
setContentView(R.layout.activity_main);
try
{
Bundle extras=this.getIntent().getExtras();
username=extras.getString("username");
accno=extras.getString("accno");
// urlcall("username:"+username+"accno:"+accno);
bool=true;
Servervalue="";
suffleKeypadGenereate();
b1=(Button) findViewById(R.id.button2);
b2=(Button) findViewById(R.id.button3);
b3=(Button) findViewById(R.id.button4);
b4=(Button) findViewById(R.id.button5);
b5=(Button) findViewById(R.id.button6);
b6=(Button) findViewById(R.id.button7);
b7=(Button) findViewById(R.id.button8);
b8=(Button) findViewById(R.id.button9);
b9=(Button) findViewById(R.id.button10);
b0=(Button) findViewById(R.id.button11);
b1.setText(" "+String.valueOf(checkNum.get(1))+" ");
b2.setText(" "+String.valueOf(checkNum.get(2))+" ");
b3.setText(" "+String.valueOf(checkNum.get(3))+" ");
b4.setText(" "+String.valueOf(checkNum.get(4))+" ");
b5.setText(" "+String.valueOf(checkNum.get(5))+" ");
b6.setText(" "+String.valueOf(checkNum.get(6))+" ");
b7.setText(" "+String.valueOf(checkNum.get(7))+" ");
b8.setText(" "+String.valueOf(checkNum.get(8))+" ");
b9.setText(" "+String.valueOf(checkNum.get(9))+" ");
b0.setText(" "+String.valueOf(checkNum.get(0))+" ");
Thread t = new Thread()
{
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(2000);
runOnUiThread(new Runnable() {
@Override
public void run()
{
if(bool)
{
if(Servervalue.replace("\n","").trim().equals("Success"))
{
// urlcall("Inside if:"+Servervalue);
bool=false;
Intent i=new Intent(getApplicationContext(),UserBankServiceActivity.class);
i.putExtra("username",username);
i.putExtra("accno",accno);
i.putExtra("status","");
i.putExtra("statusw","");
i.putExtra("statusfund","");
startActivity(i);
//startActivity(i);
}
else if(Servervalue.replace("\n","").trim().equals("Error"))
{
try
{
// urlcall("Inside else:"+Servervalue);
Intent i=new Intent(getApplicationContext(),LoginActivity.class);
i.putExtra("regis","hai");
startActivity(i);
String lat="",lng="";
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
bool=false;
if(location != null)
{
lat=String.valueOf(location.getLatitude());
lng=String.valueOf(location.getLongitude());
}
SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
httpClient = new DefaultHttpClient();
getRequest=new HttpGet(FstIpAddress.ipaddstr+"/Register?hidden=loginfailed&username="+username+"&lati="+lat+"&longti="+lng);
res= httpClient.execute(getRequest);
is= res.getEntity().getContent();
b=null;
bos = new ByteArrayOutputStream();
ch=0;
while((ch = is.read()) != -1)
{
bos.write(ch);
}
b=bos.toByteArray();
Servervalue = new String(b);
String st="";
if(Servervalue.replace("\n","").trim().equalsIgnoreCase("Done"))
{
st="Invalid Pass Code !";
}
else
{
String spp[]=Servervalue.replace("\n","").trim().split("\\-");
try
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(spp[1], null,"Your ATM Account has been\nblocked !", null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"SMS failed, please try again later!",Toast.LENGTH_LONG).show();
}
st="Your Account has been\nblocked !";
}
}
catch (Exception e) {
// urlcall("insideThread"+e);
}
}
else if(Servervalue.equalsIgnoreCase("WrongPIN"))
{
Toast.makeText(getApplicationContext(), "Enter Your 4 Digit PIN Correctly", Toast.LENGTH_LONG);
}
}
}
});
}
} catch (InterruptedException e)
{
}
}
};
t.start();
}
catch(Exception e)
{
// urlcall("exceptioninmain==="+e);
}
}
public void suffleKeypadGenereate()
{
int array[]={0,1,2,3,4,5,6,7,8,9};
try
{
for (int i=0; i<array.length; i++)
{
int randomPosition = rand.nextInt(array.length);
int temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
for (int i=0; i<array.length; i++)
{
checkNum.add(array[i]);
}
// urlcall("thevectorvalue"+checkNum.toString());
}
catch(Exception e)
{
// urlcall("ERRORAtSuffleKeyGenerate"+e);
}
}
public void PINChecking(String checkPINEntered,Context conn)
{
try
{
if(checkPINEntered.length()==4)
{
hMac hm=new hMac();
hm.Sourcemac1(username,checkPINEntered);
String mac=hm.hm;
//urlcall("hmacDoneSuccessfully"+mac);
//urlcall("Ipadrr:"+FstIpAddress.ipaddstr);
httpClient = new DefaultHttpClient();
getRequest=new HttpGet(FstIpAddress.ipaddstr+"/Register?hidden=loginpincheck&username="+username+"&hashpin="+mac);
// urlcall("urlcallsuccess");
res= httpClient.execute(getRequest);
is= res.getEntity().getContent();
byte[] b=null;
bos = new ByteArrayOutputStream();
int ch;
while((ch = is.read()) != -1)
{
bos.write(ch);
}
b=bos.toByteArray();
Servervalue = new String(b);
}
else
{
checkPINEntered="";
Servervalue="WrongPIN";
}
}
catch(Exception e)
{
// urlcall("exceptionInpinChecking"+e);
}
}
// public static void urlcall(String value)//deleted static type
// {
// try
// {
// value=value.replace(" ", "%20");
// URL u=new
// URL("http://10.0.0.17:9999/PSOEMandroid/Myservicecheck?value="+value);
// BufferedReader br=new BufferedReader(new
// InputStreamReader(u.openStream()));
// String str=br.readLine();
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// }
}
| UTF-8 | Java | 9,758 | java | MainActivity.java | Java | [
{
"context": "tent().getExtras();\r\n\t\tusername=extras.getString(\"username\");\r\n accno=extras.getString(\"accno\");\r\n// ",
"end": 1654,
"score": 0.9972940683364868,
"start": 1646,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ass);\r\n\t \t\t\t\... | null | [] | package com.covertatt;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Random;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.widget.Button;
import android.widget.Toast;
import android.preference.PreferenceManager;
public class MainActivity extends Activity implements CollectionsDataInterface
{
public static Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
Random rand=new Random();
static String Servervalue="";
static String username="",accno="";
DefaultHttpClient httpClient=null;
HttpGet getRequest=null;
HttpResponse res=null;
InputStream is=null;
byte[] b=null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
static Boolean bool=true;
int ch;
// static Context con=null;
// private Button pinb0,pinb1,pinb2,pinb3,pinb4,pinb5,pinb6,pinb7,pinb8,pinb9;
// private Button conformbutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// con=this;
setContentView(R.layout.activity_main);
try
{
Bundle extras=this.getIntent().getExtras();
username=extras.getString("username");
accno=extras.getString("accno");
// urlcall("username:"+username+"accno:"+accno);
bool=true;
Servervalue="";
suffleKeypadGenereate();
b1=(Button) findViewById(R.id.button2);
b2=(Button) findViewById(R.id.button3);
b3=(Button) findViewById(R.id.button4);
b4=(Button) findViewById(R.id.button5);
b5=(Button) findViewById(R.id.button6);
b6=(Button) findViewById(R.id.button7);
b7=(Button) findViewById(R.id.button8);
b8=(Button) findViewById(R.id.button9);
b9=(Button) findViewById(R.id.button10);
b0=(Button) findViewById(R.id.button11);
b1.setText(" "+String.valueOf(checkNum.get(1))+" ");
b2.setText(" "+String.valueOf(checkNum.get(2))+" ");
b3.setText(" "+String.valueOf(checkNum.get(3))+" ");
b4.setText(" "+String.valueOf(checkNum.get(4))+" ");
b5.setText(" "+String.valueOf(checkNum.get(5))+" ");
b6.setText(" "+String.valueOf(checkNum.get(6))+" ");
b7.setText(" "+String.valueOf(checkNum.get(7))+" ");
b8.setText(" "+String.valueOf(checkNum.get(8))+" ");
b9.setText(" "+String.valueOf(checkNum.get(9))+" ");
b0.setText(" "+String.valueOf(checkNum.get(0))+" ");
Thread t = new Thread()
{
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(2000);
runOnUiThread(new Runnable() {
@Override
public void run()
{
if(bool)
{
if(Servervalue.replace("\n","").trim().equals("Success"))
{
// urlcall("Inside if:"+Servervalue);
bool=false;
Intent i=new Intent(getApplicationContext(),UserBankServiceActivity.class);
i.putExtra("username",username);
i.putExtra("accno",accno);
i.putExtra("status","");
i.putExtra("statusw","");
i.putExtra("statusfund","");
startActivity(i);
//startActivity(i);
}
else if(Servervalue.replace("\n","").trim().equals("Error"))
{
try
{
// urlcall("Inside else:"+Servervalue);
Intent i=new Intent(getApplicationContext(),LoginActivity.class);
i.putExtra("regis","hai");
startActivity(i);
String lat="",lng="";
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
bool=false;
if(location != null)
{
lat=String.valueOf(location.getLatitude());
lng=String.valueOf(location.getLongitude());
}
SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
httpClient = new DefaultHttpClient();
getRequest=new HttpGet(FstIpAddress.ipaddstr+"/Register?hidden=loginfailed&username="+username+"&lati="+lat+"&longti="+lng);
res= httpClient.execute(getRequest);
is= res.getEntity().getContent();
b=null;
bos = new ByteArrayOutputStream();
ch=0;
while((ch = is.read()) != -1)
{
bos.write(ch);
}
b=bos.toByteArray();
Servervalue = new String(b);
String st="";
if(Servervalue.replace("\n","").trim().equalsIgnoreCase("Done"))
{
st="Invalid Pass Code !";
}
else
{
String spp[]=Servervalue.replace("\n","").trim().split("\\-");
try
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(spp[1], null,"Your ATM Account has been\nblocked !", null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"SMS failed, please try again later!",Toast.LENGTH_LONG).show();
}
st="Your Account has been\nblocked !";
}
}
catch (Exception e) {
// urlcall("insideThread"+e);
}
}
else if(Servervalue.equalsIgnoreCase("WrongPIN"))
{
Toast.makeText(getApplicationContext(), "Enter Your 4 Digit PIN Correctly", Toast.LENGTH_LONG);
}
}
}
});
}
} catch (InterruptedException e)
{
}
}
};
t.start();
}
catch(Exception e)
{
// urlcall("exceptioninmain==="+e);
}
}
public void suffleKeypadGenereate()
{
int array[]={0,1,2,3,4,5,6,7,8,9};
try
{
for (int i=0; i<array.length; i++)
{
int randomPosition = rand.nextInt(array.length);
int temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
for (int i=0; i<array.length; i++)
{
checkNum.add(array[i]);
}
// urlcall("thevectorvalue"+checkNum.toString());
}
catch(Exception e)
{
// urlcall("ERRORAtSuffleKeyGenerate"+e);
}
}
public void PINChecking(String checkPINEntered,Context conn)
{
try
{
if(checkPINEntered.length()==4)
{
hMac hm=new hMac();
hm.Sourcemac1(username,checkPINEntered);
String mac=hm.hm;
//urlcall("hmacDoneSuccessfully"+mac);
//urlcall("Ipadrr:"+FstIpAddress.ipaddstr);
httpClient = new DefaultHttpClient();
getRequest=new HttpGet(FstIpAddress.ipaddstr+"/Register?hidden=loginpincheck&username="+username+"&hashpin="+mac);
// urlcall("urlcallsuccess");
res= httpClient.execute(getRequest);
is= res.getEntity().getContent();
byte[] b=null;
bos = new ByteArrayOutputStream();
int ch;
while((ch = is.read()) != -1)
{
bos.write(ch);
}
b=bos.toByteArray();
Servervalue = new String(b);
}
else
{
checkPINEntered="";
Servervalue="WrongPIN";
}
}
catch(Exception e)
{
// urlcall("exceptionInpinChecking"+e);
}
}
// public static void urlcall(String value)//deleted static type
// {
// try
// {
// value=value.replace(" ", "%20");
// URL u=new
// URL("http://10.0.0.17:9999/PSOEMandroid/Myservicecheck?value="+value);
// BufferedReader br=new BufferedReader(new
// InputStreamReader(u.openStream()));
// String str=br.readLine();
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// }
}
| 9,758 | 0.520803 | 0.510863 | 273 | 33.743591 | 25.814075 | 149 | false | false | 29 | 0.002972 | 0 | 0 | 0 | 0 | 3.472528 | false | false | 7 |
ccc13fab88986ab15be6673396ca9a55f3fd11e8 | 35,416,300,350,704 | aaf8d7f2691c73b6dd17bef4117910e935363c3e | /venture/src/sonnicon/venture/world/blocks/distribution/DuctLiquidIO.java | b7cf6e49ea494b89982eda0d09f553c9f2285192 | [] | no_license | ThePythonGuy3/venturemod | https://github.com/ThePythonGuy3/venturemod | 4c0b28672020575f223f2ca11505817a468a4dd1 | 515f1295272bf4879d3d5f27dbb0b26b88571b16 | refs/heads/master | 2022-06-08T10:46:32.430000 | 2020-05-02T16:34:01 | 2020-05-02T16:34:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sonnicon.venture.world.blocks.distribution;
import io.anuke.mindustry.type.Liquid;
import io.anuke.mindustry.world.Tile;
import sonnicon.venture.types.DuctIOType;
public class DuctLiquidIO extends DuctIO{
protected final int timerFlow = timers++;
public DuctLiquidIO(String name){
super(name);
hasLiquids = true;
outputsLiquid = true;
type = DuctIOType.liquid;
}
@Override
public void update(Tile tile){
super.update(tile);
if(tile.entity().enabled() && tile.entity.liquids.total() > 0.001f && tile.entity.timer.get(timerFlow, 1)){
tile.entity().liquids.each((liquid, v) -> tryDumpLiquid(tile, liquid));
}
}
@Override
public boolean acceptLiquid(Tile tile, Tile source, Liquid liquid, float amount){
DuctIO.DuctIOEntity entity = tile.entity();
if(entity.ductNetwork == null) return false;
return entity.enabled() && entity.input && tile.getTeam() == source.getTeam() && entity.ductNetwork.canAcceptLiquids(tile, liquid, amount);
}
@Override
public void handleLiquid(Tile tile, Tile source, Liquid liquid, float amount){
DuctIO.DuctIOEntity entity = tile.entity();
if(!acceptLiquid(tile, source, liquid, amount)) return;
entity.ductNetwork.handleLiquid(tile, liquid, amount);
}
}
| UTF-8 | Java | 1,358 | java | DuctLiquidIO.java | Java | [] | null | [] | package sonnicon.venture.world.blocks.distribution;
import io.anuke.mindustry.type.Liquid;
import io.anuke.mindustry.world.Tile;
import sonnicon.venture.types.DuctIOType;
public class DuctLiquidIO extends DuctIO{
protected final int timerFlow = timers++;
public DuctLiquidIO(String name){
super(name);
hasLiquids = true;
outputsLiquid = true;
type = DuctIOType.liquid;
}
@Override
public void update(Tile tile){
super.update(tile);
if(tile.entity().enabled() && tile.entity.liquids.total() > 0.001f && tile.entity.timer.get(timerFlow, 1)){
tile.entity().liquids.each((liquid, v) -> tryDumpLiquid(tile, liquid));
}
}
@Override
public boolean acceptLiquid(Tile tile, Tile source, Liquid liquid, float amount){
DuctIO.DuctIOEntity entity = tile.entity();
if(entity.ductNetwork == null) return false;
return entity.enabled() && entity.input && tile.getTeam() == source.getTeam() && entity.ductNetwork.canAcceptLiquids(tile, liquid, amount);
}
@Override
public void handleLiquid(Tile tile, Tile source, Liquid liquid, float amount){
DuctIO.DuctIOEntity entity = tile.entity();
if(!acceptLiquid(tile, source, liquid, amount)) return;
entity.ductNetwork.handleLiquid(tile, liquid, amount);
}
}
| 1,358 | 0.669367 | 0.665685 | 39 | 33.820515 | 33.791119 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.846154 | false | false | 7 |
04f8d05dcb9b91a4b553e4c4b201a8dfaaae1b3b | 8,727,373,595,248 | 14d706f080d11a9598ea08e043c6c4622a6c7770 | /src/controller/ArtToMusicController.java | 9c2a9cddd8dbe154d78d5870cd376ec2dc8b1153 | [] | no_license | desmetr/ArtToMusic | https://github.com/desmetr/ArtToMusic | 0697a8dbd55d2a8eb13a1f73d5a7cd1a3a71ded0 | 4bcee62d28ed1848aec52d8b10c5140328529149 | refs/heads/master | 2021-01-11T01:33:54.104000 | 2017-05-11T15:56:51 | 2017-05-11T15:56:51 | 70,594,670 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controller;
public class ArtToMusicController
{
public ArtToMusicController()
{
}
}
| UTF-8 | Java | 106 | java | ArtToMusicController.java | Java | [] | null | [] | package controller;
public class ArtToMusicController
{
public ArtToMusicController()
{
}
}
| 106 | 0.698113 | 0.698113 | 8 | 12.25 | 13.198011 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 7 |
5c5b28efdb6557fb35418090195be37f750bb05c | 34,033,320,900,200 | 83842e3dfc35c8f56d9093379025d3f9d5912b7d | /src/model/BbsDTO.java | 6ab2047c2aa57bba7f6631bca3b279b56c6cd0b8 | [] | no_license | pinocchio9702/K09MariaBoard | https://github.com/pinocchio9702/K09MariaBoard | f2ddca7268d49ea5edb681a5d22aef499f904506 | d5077e4a60551480efe989ff20476c79db3e1ad6 | refs/heads/master | 2023-02-08T18:02:54.126000 | 2020-12-23T09:37:19 | 2020-12-23T09:37:19 | 323,860,499 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model;
/*
DTO 클래스를 만들때는 테이블정의서를 참조한다.
기본적으로 테이블과 동일한 형태로 멤버변수를 정의하면 된다.
멤버변수의 타입은 특별한 경우를 제외하고는 대부분 String으로
정의한다. 꼭 필요한 경우에만 int, double로 정의한다.
*/
public class BbsDTO {
private String num;//일련변호
private String title;//제목
private String content;//내용
private String id;//작성자아이디(member테이블 참조)
private java.sql.Date postDate;//작성일
private String visitcount;//조회수
/*
회원테이블과 join하여 이름을 가져오기 위해 DTO클래스에
name컬럼을 추가한다.
*/
private String name;
//생성자는 기술하지 않는다.
//getter/setter만 기술한다.
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the num
*/
public String getNum() {
return num;
}
/**
* @param num the num to set
*/
public void setNum(String num) {
this.num = num;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return the content
*/
public String getContent() {
return content;
}
/**
* @param content the content to set
*/
public void setContent(String content) {
this.content = content;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the postdate
*/
public java.sql.Date getPostDate() {
return postDate;
}
/**
* @param postdate the postdate to set
*/
public void setPostDate(java.sql.Date postdate) {
this.postDate = postdate;
}
/**
* @return the visitcount
*/
public String getVisitcount() {
return visitcount;
}
/**
* @param visitcount the visitcount to set
*/
public void setVisitcount(String visitcount) {
this.visitcount = visitcount;
}
}
| UTF-8 | Java | 2,303 | java | BbsDTO.java | Java | [] | null | [] | package model;
/*
DTO 클래스를 만들때는 테이블정의서를 참조한다.
기본적으로 테이블과 동일한 형태로 멤버변수를 정의하면 된다.
멤버변수의 타입은 특별한 경우를 제외하고는 대부분 String으로
정의한다. 꼭 필요한 경우에만 int, double로 정의한다.
*/
public class BbsDTO {
private String num;//일련변호
private String title;//제목
private String content;//내용
private String id;//작성자아이디(member테이블 참조)
private java.sql.Date postDate;//작성일
private String visitcount;//조회수
/*
회원테이블과 join하여 이름을 가져오기 위해 DTO클래스에
name컬럼을 추가한다.
*/
private String name;
//생성자는 기술하지 않는다.
//getter/setter만 기술한다.
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the num
*/
public String getNum() {
return num;
}
/**
* @param num the num to set
*/
public void setNum(String num) {
this.num = num;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return the content
*/
public String getContent() {
return content;
}
/**
* @param content the content to set
*/
public void setContent(String content) {
this.content = content;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the postdate
*/
public java.sql.Date getPostDate() {
return postDate;
}
/**
* @param postdate the postdate to set
*/
public void setPostDate(java.sql.Date postdate) {
this.postDate = postdate;
}
/**
* @return the visitcount
*/
public String getVisitcount() {
return visitcount;
}
/**
* @param visitcount the visitcount to set
*/
public void setVisitcount(String visitcount) {
this.visitcount = visitcount;
}
}
| 2,303 | 0.596588 | 0.596588 | 118 | 14.889831 | 13.705612 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.245763 | false | false | 7 |
2070edd0c99b9233809599428f967673f07cc1d5 | 28,381,143,956,455 | b8ceedc92306034d6edd33fef22143c96f342a36 | /src/test/java/seedu/address/logic/commands/PayCommandTest.java | cfe4a839c19a7584d50f024f02ca0740206af6a2 | [
"MIT"
] | permissive | AY1920S1-CS2103T-F13-1/main | https://github.com/AY1920S1-CS2103T-F13-1/main | aa04f087a5cd11e6d8a2758cea5623d3054265bd | c6262e35daa2f807d8415cbe4dde8f62a110ba71 | refs/heads/master | 2020-07-25T07:05:44.886000 | 2019-11-11T09:41:36 | 2019-11-11T09:41:36 | 208,202,695 | 1 | 5 | NOASSERTION | true | 2019-11-11T09:41:38 | 2019-09-13T05:41:11 | 2019-11-11T09:35:18 | 2019-11-11T09:41:37 | 26,452 | 2 | 5 | 13 | Java | false | false | package seedu.address.logic.commands;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.commons.core.Messages.MESSAGE_NOT_IN_SERVE_MODE;
import static seedu.address.commons.core.Messages.MESSAGE_NO_OUTSTANDING_FINE;
import static seedu.address.logic.commands.CommandTestUtil.VALID_CENT_AMOUNT;
import static seedu.address.logic.commands.CommandTestUtil.assertCommandFailure;
import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess;
import static seedu.address.testutil.TypicalBorrowers.IDA;
import static seedu.address.testutil.TypicalBorrowers.JANNA;
import static seedu.address.testutil.TypicalLoans.LOAN_8;
import static seedu.address.testutil.TypicalLoans.LOAN_9;
import org.junit.jupiter.api.Test;
import seedu.address.commons.util.FineUtil;
import seedu.address.model.BorrowerRecords;
import seedu.address.model.Catalog;
import seedu.address.model.LoanRecords;
import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.UserPrefs;
class PayCommandTest {
@Test
public void execute_outstandingFines_paymentSuccessful() {
BorrowerRecords borrowerRecords = new BorrowerRecords();
borrowerRecords.addBorrower(JANNA);
LoanRecords loanRecords = new LoanRecords();
loanRecords.addLoan(LOAN_8);
loanRecords.addLoan(LOAN_9);
Model actualModel = new ModelManager(new Catalog(), loanRecords, borrowerRecords, new UserPrefs());
actualModel.setServingBorrower(JANNA);
Model expectedModel = new ModelManager(new Catalog(), new LoanRecords(loanRecords),
new BorrowerRecords(borrowerRecords), new UserPrefs());
expectedModel.setServingBorrower(JANNA);
PayCommand payCommand = new PayCommand(VALID_CENT_AMOUNT);
int change = expectedModel.payFines(VALID_CENT_AMOUNT);
String amountPaidInDollars = FineUtil.centsToDollarString(VALID_CENT_AMOUNT - change);
String outstandingFineInDollars = FineUtil.centsToDollarString(
expectedModel.getServingBorrower().getOutstandingFineAmount());
String changeInDollars = FineUtil.centsToDollarString(change);
String expectedMessage = String.format(PayCommand.MESSAGE_SUCCESS, amountPaidInDollars, JANNA,
outstandingFineInDollars, changeInDollars);
assertCommandSuccess(payCommand, actualModel, expectedMessage, expectedModel);
}
@Test
public void execute_notInServeMode_paymentUnsuccessful() {
BorrowerRecords borrowerRecords = new BorrowerRecords();
borrowerRecords.addBorrower(JANNA);
LoanRecords loanRecords = new LoanRecords();
loanRecords.addLoan(LOAN_8);
loanRecords.addLoan(LOAN_9);
Model model = new ModelManager(new Catalog(), loanRecords, borrowerRecords, new UserPrefs());
PayCommand payCommand = new PayCommand(VALID_CENT_AMOUNT);
String expectedMessage = MESSAGE_NOT_IN_SERVE_MODE;
assertCommandFailure(payCommand, model, expectedMessage);
}
@Test
public void execute_noOutstandingFines_paymentUnsuccessful() {
BorrowerRecords borrowerRecords = new BorrowerRecords();
borrowerRecords.addBorrower(IDA);
Model model = new ModelManager(new Catalog(), new LoanRecords(), borrowerRecords, new UserPrefs());
model.setServingBorrower(IDA);
PayCommand payCommand = new PayCommand(VALID_CENT_AMOUNT);
String expectedMessage = MESSAGE_NO_OUTSTANDING_FINE;
assertCommandFailure(payCommand, model, expectedMessage);
}
@Test
public void equals() {
PayCommand payCommand1 = new PayCommand(VALID_CENT_AMOUNT);
PayCommand payCommand2 = new PayCommand(VALID_CENT_AMOUNT);
PayCommand payCommand3 = new PayCommand(VALID_CENT_AMOUNT + 10);
// same object -> returns true
assertTrue(payCommand1.equals(payCommand1));
// same values -> returns true
assertTrue(payCommand1.equals(payCommand2));
// different values -> returns false
assertFalse(payCommand1.equals(payCommand3));
// null -> returns false
assertFalse(payCommand1.equals(null));
// different type -> returns false
assertFalse(payCommand1.equals(1));
}
}
| UTF-8 | Java | 4,378 | java | PayCommandTest.java | Java | [
{
"context": "werRecords();\n borrowerRecords.addBorrower(JANNA);\n\n LoanRecords loanRecords = new Loan",
"end": 1304,
"score": 0.5839243531227112,
"start": 1303,
"tag": "NAME",
"value": "J"
},
{
"context": "werRecords();\n borrowerRecords.addBorrower(JANNA);\n\... | null | [] | package seedu.address.logic.commands;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.commons.core.Messages.MESSAGE_NOT_IN_SERVE_MODE;
import static seedu.address.commons.core.Messages.MESSAGE_NO_OUTSTANDING_FINE;
import static seedu.address.logic.commands.CommandTestUtil.VALID_CENT_AMOUNT;
import static seedu.address.logic.commands.CommandTestUtil.assertCommandFailure;
import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess;
import static seedu.address.testutil.TypicalBorrowers.IDA;
import static seedu.address.testutil.TypicalBorrowers.JANNA;
import static seedu.address.testutil.TypicalLoans.LOAN_8;
import static seedu.address.testutil.TypicalLoans.LOAN_9;
import org.junit.jupiter.api.Test;
import seedu.address.commons.util.FineUtil;
import seedu.address.model.BorrowerRecords;
import seedu.address.model.Catalog;
import seedu.address.model.LoanRecords;
import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.UserPrefs;
class PayCommandTest {
@Test
public void execute_outstandingFines_paymentSuccessful() {
BorrowerRecords borrowerRecords = new BorrowerRecords();
borrowerRecords.addBorrower(JANNA);
LoanRecords loanRecords = new LoanRecords();
loanRecords.addLoan(LOAN_8);
loanRecords.addLoan(LOAN_9);
Model actualModel = new ModelManager(new Catalog(), loanRecords, borrowerRecords, new UserPrefs());
actualModel.setServingBorrower(JANNA);
Model expectedModel = new ModelManager(new Catalog(), new LoanRecords(loanRecords),
new BorrowerRecords(borrowerRecords), new UserPrefs());
expectedModel.setServingBorrower(JANNA);
PayCommand payCommand = new PayCommand(VALID_CENT_AMOUNT);
int change = expectedModel.payFines(VALID_CENT_AMOUNT);
String amountPaidInDollars = FineUtil.centsToDollarString(VALID_CENT_AMOUNT - change);
String outstandingFineInDollars = FineUtil.centsToDollarString(
expectedModel.getServingBorrower().getOutstandingFineAmount());
String changeInDollars = FineUtil.centsToDollarString(change);
String expectedMessage = String.format(PayCommand.MESSAGE_SUCCESS, amountPaidInDollars, JANNA,
outstandingFineInDollars, changeInDollars);
assertCommandSuccess(payCommand, actualModel, expectedMessage, expectedModel);
}
@Test
public void execute_notInServeMode_paymentUnsuccessful() {
BorrowerRecords borrowerRecords = new BorrowerRecords();
borrowerRecords.addBorrower(JANNA);
LoanRecords loanRecords = new LoanRecords();
loanRecords.addLoan(LOAN_8);
loanRecords.addLoan(LOAN_9);
Model model = new ModelManager(new Catalog(), loanRecords, borrowerRecords, new UserPrefs());
PayCommand payCommand = new PayCommand(VALID_CENT_AMOUNT);
String expectedMessage = MESSAGE_NOT_IN_SERVE_MODE;
assertCommandFailure(payCommand, model, expectedMessage);
}
@Test
public void execute_noOutstandingFines_paymentUnsuccessful() {
BorrowerRecords borrowerRecords = new BorrowerRecords();
borrowerRecords.addBorrower(IDA);
Model model = new ModelManager(new Catalog(), new LoanRecords(), borrowerRecords, new UserPrefs());
model.setServingBorrower(IDA);
PayCommand payCommand = new PayCommand(VALID_CENT_AMOUNT);
String expectedMessage = MESSAGE_NO_OUTSTANDING_FINE;
assertCommandFailure(payCommand, model, expectedMessage);
}
@Test
public void equals() {
PayCommand payCommand1 = new PayCommand(VALID_CENT_AMOUNT);
PayCommand payCommand2 = new PayCommand(VALID_CENT_AMOUNT);
PayCommand payCommand3 = new PayCommand(VALID_CENT_AMOUNT + 10);
// same object -> returns true
assertTrue(payCommand1.equals(payCommand1));
// same values -> returns true
assertTrue(payCommand1.equals(payCommand2));
// different values -> returns false
assertFalse(payCommand1.equals(payCommand3));
// null -> returns false
assertFalse(payCommand1.equals(null));
// different type -> returns false
assertFalse(payCommand1.equals(1));
}
}
| 4,378 | 0.735267 | 0.730699 | 108 | 39.537037 | 30.764465 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.768519 | false | false | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.