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
sequence | 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
sequence | 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5d7ef4510bee118183e007d9ce6df7ed35a0f1f6 | 33,809,982,606,403 | 7577011d16a65ee28bedd3a18df08e6e4c98be74 | /src/test/java/com/wgg/muwd/util/TestUtil.java | e89e669ff1380b1a115a62459f2a5b182ba4ec75 | [] | no_license | elennick/muwd | https://github.com/elennick/muwd | 8a94cfe7f4d3887db419d4e1886dc7eaa1f22d58 | d1e67c47dfaa6504748a35dbef54eb79da16f151 | refs/heads/master | 2021-01-21T18:53:09.533000 | 2018-02-04T15:24:11 | 2018-02-04T15:24:11 | 36,568,030 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wgg.muwd.util;
import com.wgg.muwd.client.PlayerCharacter;
import com.wgg.muwd.command.Command;
import com.wgg.muwd.world.World;
import java.util.Optional;
public final class TestUtil {
private TestUtil() {}
public static Command getTestCommand(String commandValue, String response) {
return new MockCommand(commandValue, response);
}
private static class MockCommand extends Command {
private String commandValue;
private String response;
public MockCommand(String commandValue, String response) {
this.commandValue = commandValue;
this.response = response;
}
@Override
public String getCommandValue() {
return commandValue;
}
@Override
public Optional<String> getResponse(String[] input, World world, PlayerCharacter client) {
return Optional.of(response);
}
@Override
public String getHelpText() {
return "test help text";
}
}
}
| UTF-8 | Java | 1,049 | java | TestUtil.java | Java | [] | null | [] | package com.wgg.muwd.util;
import com.wgg.muwd.client.PlayerCharacter;
import com.wgg.muwd.command.Command;
import com.wgg.muwd.world.World;
import java.util.Optional;
public final class TestUtil {
private TestUtil() {}
public static Command getTestCommand(String commandValue, String response) {
return new MockCommand(commandValue, response);
}
private static class MockCommand extends Command {
private String commandValue;
private String response;
public MockCommand(String commandValue, String response) {
this.commandValue = commandValue;
this.response = response;
}
@Override
public String getCommandValue() {
return commandValue;
}
@Override
public Optional<String> getResponse(String[] input, World world, PlayerCharacter client) {
return Optional.of(response);
}
@Override
public String getHelpText() {
return "test help text";
}
}
}
| 1,049 | 0.641563 | 0.641563 | 44 | 22.84091 | 23.519762 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409091 | false | false | 9 |
c74246c0c349401ab1706c8b276da4e75330841e | 33,809,982,608,288 | edae712b3ad480a58729b6ca01acb9a152925f55 | /src/com/kosta/day12/FindCharacters.java | 75cfe1c4185af1f725ed2d9aa37b8e46955abcb6 | [] | no_license | Sunny-Heo-myth/KOSTA | https://github.com/Sunny-Heo-myth/KOSTA | fc6996f2c3a5fe5595628a0563c58b910a738a9d | fec49eacbd902a674d62df6a119cb97216bdeb26 | refs/heads/master | 2023-07-16T00:21:33.669000 | 2021-09-04T14:25:09 | 2021-09-04T14:25:09 | 392,935,941 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kosta.day12;
public class FindCharacters {
static int countChar(String str, char c) {
int cnt = 0;
for(char i : str.toCharArray()) {
if(i == c) {
cnt++;
}
}
return cnt;
}
}
| UTF-8 | Java | 207 | java | FindCharacters.java | Java | [] | null | [] | package com.kosta.day12;
public class FindCharacters {
static int countChar(String str, char c) {
int cnt = 0;
for(char i : str.toCharArray()) {
if(i == c) {
cnt++;
}
}
return cnt;
}
}
| 207 | 0.589372 | 0.574879 | 14 | 13.785714 | 13.496976 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.785714 | false | false | 9 |
03fef4fe8d5446bf46bba0742f96a5e6bd396528 | 33,835,752,407,109 | 13c917f290cef7a6d931888a2ebc4e33cfa0d164 | /app/src/main/java/com/example/administrator/fastjson/view/MyView.java | d27bc32947aa802aa03c399b8d555c38935af2ff | [] | no_license | zfer/FastJson | https://github.com/zfer/FastJson | e4a60562ed9280cd4e60c01b118518aec1f1aca6 | 1d0b9a81a4d1794aad754e990648327d3c1d229e | refs/heads/master | 2018-10-15T19:17:12.368000 | 2017-06-12T06:17:44 | 2017-06-12T06:17:44 | 94,061,692 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.administrator.fastjson.view;
import com.example.administrator.fastjson.bean.Country;
import java.util.List;
/**
* Created by Administrator on 2017-06-09.
*/
public interface MyView {
void showInfo(List<Country> country_list);
void showProgressDialog();
void hideProgressDialog();
void showError(String msg);
}
| UTF-8 | Java | 351 | java | MyView.java | Java | [
{
"context": "ountry;\n\nimport java.util.List;\n\n/**\n * Created by Administrator on 2017-06-09.\n */\npublic interface MyView {\n ",
"end": 162,
"score": 0.9394102096557617,
"start": 149,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | package com.example.administrator.fastjson.view;
import com.example.administrator.fastjson.bean.Country;
import java.util.List;
/**
* Created by Administrator on 2017-06-09.
*/
public interface MyView {
void showInfo(List<Country> country_list);
void showProgressDialog();
void hideProgressDialog();
void showError(String msg);
}
| 351 | 0.74359 | 0.720798 | 15 | 22.4 | 19.272779 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 9 |
40674f7e85f7bbc54280aa6e5caa4c797db1a680 | 34,660,386,128,336 | b5817ece3f0794e0fcdd2edb6edfc1f4a7a8f50d | /src/main/java/models/Movie.java | 3169e4dc5f51e0c6da8dc3e35300e43e05c7fdb7 | [
"MIT"
] | permissive | malethr/moviesApi | https://github.com/malethr/moviesApi | 24dcd8c395773a913df6a6ce8e458fc06d643e5b | 626273f03c1d6193a4c68d05429b0332c81626d9 | refs/heads/master | 2021-01-20T05:15:45.284000 | 2017-08-28T16:07:40 | 2017-08-28T16:07:40 | 101,424,641 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package models;
/**
* Created by mariathomas on 8/25/17.
*/
public class Movie {
private String title;
private String description;
private String myear;
private String director;
private String trailer;
private int id;
public Movie(String title, String description) {
this.title = title;
this.description = description;
this.myear = "not available";
this.director = "not available";
this.trailer = "not available";
}
public Movie(String title, String description, String myear, String director, String trailer) {
this.title = title;
this.description = description;
this.myear = myear;
this.director = director;
this.trailer = trailer;
}
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 String getMyear() {
return myear;
}
public void setMyear(String myear) {
this.myear = myear;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getTrailer() {
return trailer;
}
public void setTrailer(String trailer) {
this.trailer = trailer;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Movie movie = (Movie) o;
if (id != movie.id) return false;
if (!title.equals(movie.title)) return false;
if (!description.equals(movie.description)) return false;
if (myear != null ? !myear.equals(movie.myear) : movie.myear != null) return false;
if (director != null ? !director.equals(movie.director) : movie.director != null) return false;
return trailer != null ? trailer.equals(movie.trailer) : movie.trailer == null;
}
@Override
public int hashCode() {
int result = title.hashCode();
result = 31 * result + description.hashCode();
result = 31 * result + (myear != null ? myear.hashCode() : 0);
result = 31 * result + (director != null ? director.hashCode() : 0);
result = 31 * result + (trailer != null ? trailer.hashCode() : 0);
result = 31 * result + id;
return result;
}
}
| UTF-8 | Java | 2,689 | java | Movie.java | Java | [
{
"context": "package models;\n\n/**\n * Created by mariathomas on 8/25/17.\n */\npublic class Movie {\n private ",
"end": 46,
"score": 0.8927690982818604,
"start": 35,
"tag": "USERNAME",
"value": "mariathomas"
}
] | null | [] | package models;
/**
* Created by mariathomas on 8/25/17.
*/
public class Movie {
private String title;
private String description;
private String myear;
private String director;
private String trailer;
private int id;
public Movie(String title, String description) {
this.title = title;
this.description = description;
this.myear = "not available";
this.director = "not available";
this.trailer = "not available";
}
public Movie(String title, String description, String myear, String director, String trailer) {
this.title = title;
this.description = description;
this.myear = myear;
this.director = director;
this.trailer = trailer;
}
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 String getMyear() {
return myear;
}
public void setMyear(String myear) {
this.myear = myear;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getTrailer() {
return trailer;
}
public void setTrailer(String trailer) {
this.trailer = trailer;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Movie movie = (Movie) o;
if (id != movie.id) return false;
if (!title.equals(movie.title)) return false;
if (!description.equals(movie.description)) return false;
if (myear != null ? !myear.equals(movie.myear) : movie.myear != null) return false;
if (director != null ? !director.equals(movie.director) : movie.director != null) return false;
return trailer != null ? trailer.equals(movie.trailer) : movie.trailer == null;
}
@Override
public int hashCode() {
int result = title.hashCode();
result = 31 * result + description.hashCode();
result = 31 * result + (myear != null ? myear.hashCode() : 0);
result = 31 * result + (director != null ? director.hashCode() : 0);
result = 31 * result + (trailer != null ? trailer.hashCode() : 0);
result = 31 * result + id;
return result;
}
}
| 2,689 | 0.590554 | 0.58386 | 104 | 24.85577 | 23.635622 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
1e049fa174f0f0da3813891a6e944dfc8da7558d | 34,918,084,163,235 | 26ff25c26259ee308b3c950d5cbe590f4c693640 | /app/src/main/java/com/example/bottomsheets/BottomSheetFragment.java | d8ce0ce061c4263a22020f0a606bc893e34e4a95 | [] | no_license | kudoNick/BottomSheets | https://github.com/kudoNick/BottomSheets | 9e823eb55afb42ce31db5dde6018d60e70e24c8a | bdb1bde7ab305cc71d6795ba51754dd4cf737ea4 | refs/heads/master | 2022-11-03T02:44:53.570000 | 2020-06-16T08:26:20 | 2020-06-16T08:26:20 | 271,690,078 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.bottomsheets;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
public class BottomSheetFragment extends BottomSheetDialogFragment {
private BottomSheetListener bottomSheetListener;
LinearLayout linearLayout1,linearLayout2,linearLayout3,linearLayout4,linearLayout5;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_bottom_sheet_dialog, container, false);
bottomSheetListener = (BottomSheetListener) getContext();
linearLayout1 = view.findViewById(R.id.line1);
linearLayout2 = view.findViewById(R.id.line2);
linearLayout3 = view.findViewById(R.id.line3);
linearLayout4 = view.findViewById(R.id.line4);
linearLayout5 = view.findViewById(R.id.line5);
linearLayout1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetListener.onBottomSheetClick("PreView");
dismiss();
}
});
linearLayout2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetListener.onBottomSheetClick("Share");
dismiss();
}
});
linearLayout3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetListener.onBottomSheetClick("Get Link");
dismiss();
}
});
linearLayout4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetListener.onBottomSheetClick("Make a Copy");
dismiss();
}
});
linearLayout5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetListener.onBottomSheetClick("Email a copy");
dismiss();
}
});
return view;
}
public interface BottomSheetListener{
void onBottomSheetClick(String text);
}
// @Override
// public void onAttach(@NonNull Context context) {
// super.onAttach(context);
//
// try {
// bottomSheetListener = (BottomSheetListener) context;
// } catch (ClassCastException e) {
// throw new ClassCastException(context.toString() + " must implement BottomSheetLestener");
// }
// }
}
| UTF-8 | Java | 3,069 | java | BottomSheetFragment.java | Java | [] | null | [] | package com.example.bottomsheets;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
public class BottomSheetFragment extends BottomSheetDialogFragment {
private BottomSheetListener bottomSheetListener;
LinearLayout linearLayout1,linearLayout2,linearLayout3,linearLayout4,linearLayout5;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_bottom_sheet_dialog, container, false);
bottomSheetListener = (BottomSheetListener) getContext();
linearLayout1 = view.findViewById(R.id.line1);
linearLayout2 = view.findViewById(R.id.line2);
linearLayout3 = view.findViewById(R.id.line3);
linearLayout4 = view.findViewById(R.id.line4);
linearLayout5 = view.findViewById(R.id.line5);
linearLayout1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetListener.onBottomSheetClick("PreView");
dismiss();
}
});
linearLayout2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetListener.onBottomSheetClick("Share");
dismiss();
}
});
linearLayout3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetListener.onBottomSheetClick("Get Link");
dismiss();
}
});
linearLayout4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetListener.onBottomSheetClick("Make a Copy");
dismiss();
}
});
linearLayout5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetListener.onBottomSheetClick("Email a copy");
dismiss();
}
});
return view;
}
public interface BottomSheetListener{
void onBottomSheetClick(String text);
}
// @Override
// public void onAttach(@NonNull Context context) {
// super.onAttach(context);
//
// try {
// bottomSheetListener = (BottomSheetListener) context;
// } catch (ClassCastException e) {
// throw new ClassCastException(context.toString() + " must implement BottomSheetLestener");
// }
// }
}
| 3,069 | 0.648746 | 0.642229 | 88 | 33.875 | 28.62882 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.556818 | false | false | 9 |
8a30103a6e80ae65d0f504796cfb199ee9796761 | 18,554,258,788,975 | 1c4a988180378b3daeef980b9fa4a29753bcc938 | /app/src/main/java/com/example/thinkanddo/ChatActivity.java | 56e921edbf68ef88c4092f2e3e333a2d5ffb6460 | [] | no_license | FarihaPenon/OnlyOnlyThinkAndDo | https://github.com/FarihaPenon/OnlyOnlyThinkAndDo | 24be109325f173e412fc9e9156e4fd35fb936f7c | 4074b9b83974e9e61adc392d2583e57c5397a80b | refs/heads/master | 2021-01-15T03:25:37.555000 | 2020-02-24T21:16:55 | 2020-02-24T21:16:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.thinkanddo;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.thinkanddo.adapters.AdapterChat;
import com.example.thinkanddo.models.ModelChat;
import com.example.thinkanddo.models.ModelUsers;
import com.example.thinkanddo.notifications.APIService;
import com.example.thinkanddo.notifications.Client;
import com.example.thinkanddo.notifications.Data;
import com.example.thinkanddo.notifications.Response;
import com.example.thinkanddo.notifications.Sender;
import com.example.thinkanddo.notifications.Token;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
public class ChatActivity extends AppCompatActivity {
Toolbar toolbar;
RecyclerView recyclerView;
ImageButton sendBtn;
ImageView profileIv;
TextView nameTv, userStatusTv;
EditText messageEt;
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
DatabaseReference usersDbRef;
String hisUid;
String myUid;
String hisImage;
APIService apiService;
boolean notify= false;
//for checking if the uer has seen message or not.
ValueEventListener seenListener;
DatabaseReference userRefForSeen;
List<ModelChat> chatList;
AdapterChat adapterChat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("");
recyclerView = findViewById(R.id.chat_recyclerView);
sendBtn = findViewById(R.id.sendBtn);
profileIv = findViewById(R.id.profileIv);
nameTv = findViewById(R.id.nameTv);
userStatusTv = findViewById(R.id.userStatusTv);
messageEt = findViewById(R.id.messageEt);
firebaseAuth=firebaseAuth.getInstance();
Context context;
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
//create api service
apiService= Client.getRetrofit("https://fcm.googleapis.com/").create(APIService.class);
/*on Clicking user from users list we have passed that uid using intent
So get the uid here to get user image, name and start chat with that user.
*/
Intent intent = getIntent();
hisUid = intent.getStringExtra("hisUid");
firebaseDatabase = firebaseDatabase.getInstance();
usersDbRef = firebaseDatabase.getReference("Users");
//search user to get that users info
Query userQuery = usersDbRef.orderByChild("uid").equalTo(hisUid);
//get user picture and name
userQuery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//check until required info is received.
for(DataSnapshot ds:dataSnapshot.getChildren()){
//get data
String name ="" + ds.child("name").getValue();
hisImage ="" + ds.child("image").getValue();
String typingStatus ="" + ds.child("typingTo").getValue();
if (typingStatus.equals(myUid)){
userStatusTv.setText("typing...");
}
else{
String onineStatus = "" + ds.child("onlineStatus").getValue();
if(onineStatus.equals("online")){
userStatusTv.setText(onineStatus);
}
else{
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(Long.parseLong(onineStatus));
String dateTime = DateFormat.format("dd/mm/yyyy hh:mm aa",cal).toString();
userStatusTv.setText("Last seen at: "+ dateTime);
}
}
//set data
nameTv.setText(name);
try{
Picasso.get().load(hisImage).placeholder(R.drawable.ic_default).into(profileIv);
}
catch(Exception e){
Picasso.get().load(R.drawable.ic_default).into(profileIv);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
notify=true;
// get text from edittext
String message = messageEt.getText().toString().trim();
if(TextUtils.isEmpty(message)){
Toast.makeText(ChatActivity.this,"Cannot send empty mess..",Toast.LENGTH_LONG).show();
}
else{
sendMessage(message);
}
//reset edittext after sending message
messageEt.setText("");
}
});
messageEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().trim().length() == 0){
checkTypingStatus("noOne");
}
else {
checkTypingStatus(hisUid);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
messageEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().trim().length() == 0){
checkTypingStatus("noOne");
}
else {
checkTypingStatus(hisUid);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
readMessages();
seenMessage();
}
private void seenMessage() {
userRefForSeen = FirebaseDatabase.getInstance().getReference("Chats");
seenListener = userRefForSeen.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
ModelChat chat = ds.getValue(ModelChat.class);
if(chat.getReceiver().equals(myUid)&&chat.getSender().equals(hisUid)){
HashMap<String, Object> hasSeenHashMap = new HashMap<>();
hasSeenHashMap.put("isSeen", true);
ds.getRef().updateChildren(hasSeenHashMap);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void readMessages() {
chatList = new ArrayList<>();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Chats");
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
chatList.clear();
for(DataSnapshot ds: dataSnapshot.getChildren()){
ModelChat chat = ds.getValue(ModelChat.class);
if(chat.getReceiver().equals(myUid) && chat.getSender().equals(hisUid)||
chat.getReceiver().equals(hisUid) && chat.getSender().equals(myUid)){
chatList.add(chat);
}
adapterChat = new AdapterChat(ChatActivity.this,chatList,hisImage);
adapterChat.notifyDataSetChanged();
//set Adapter to recyclerview
recyclerView.setAdapter(adapterChat);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(final String message) {
/* "Chats" node will be created that will contains all chats
Whenever user sends message it will create new child in "Chats" node and that child will contain
sender: UID of sender
receiver: UID of receiver
message: the actual message
*/
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
String timestamp = String.valueOf(System.currentTimeMillis());
HashMap<String,Object> hashMap = new HashMap<>();
hashMap.put("sender",myUid);
hashMap.put("receiver",hisUid);
hashMap.put("message",message);
hashMap.put("timestamp",timestamp);
hashMap.put("isSeen",false);
databaseReference.child("Chats").push().setValue(hashMap);
final DatabaseReference database=FirebaseDatabase.getInstance().getReference("Users").child(myUid);
database.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ModelUsers user= dataSnapshot.getValue(ModelUsers.class);
if(notify){
sentNotification(hisUid,user.getName(), message);
}
notify=false;
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void sentNotification(final String hisUid, final String name, final String message) {
DatabaseReference allTokens= FirebaseDatabase.getInstance().getReference("Tokens");
Query query=allTokens.orderByKey().equalTo(hisUid);
query.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot){
for(DataSnapshot ds: dataSnapshot.getChildren()){
Token token=ds.getValue(Token.class);
Data data= new Data(myUid, name+":"+message,"New Message",hisUid, R.drawable.ic_default); //R.drawable.ic_default_img;
Sender sender=new Sender(data,token.getToken());
apiService.sendNotification(sender)
.enqueue(new Callback<Response>() {
@Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
Toast.makeText(ChatActivity.this,""+response.message(),Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<Response> call, Throwable t) {
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void checkUserStatus(){
FirebaseUser user =firebaseAuth.getCurrentUser();
if(user!=null){
//mprofileTv.setText(user.getEmail());
myUid = user.getUid();
}else{
startActivity(new Intent(this, MainActivity.class));
finish();
}
}
private void checkOnlineStatus(String status){
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Users").child(myUid);
HashMap<String, Object> hashMap =new HashMap<>();
hashMap.put("onlineStatus", status);
dbRef.updateChildren(hashMap);
}
private void checkTypingStatus(String typing){
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Users").child(myUid);
HashMap<String, Object> hashMap =new HashMap<>();
hashMap.put("typingTo", typing);
dbRef.updateChildren(hashMap);
}
@Override
protected void onStart() {
checkUserStatus();
checkOnlineStatus("online");
checkTypingStatus("noOne");
super.onStart();
}
@Override
protected void onPause() {
super.onPause();
String timestamp = String.valueOf(System.currentTimeMillis());
checkOnlineStatus(timestamp);
userRefForSeen.removeEventListener(seenListener);
}
@Override
protected void onResume() {
checkOnlineStatus("online");
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
menu.findItem(R.id.action_search).setVisible(false);
menu.findItem(R.id.action_add_post).setVisible(false);
return super.onCreateOptionsMenu(menu);
//x+y=1;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_logout){
firebaseAuth.signOut();
checkUserStatus();
}
return super.onOptionsItemSelected(item);
}
}
| UTF-8 | Java | 15,001 | java | ChatActivity.java | Java | [] | null | [] | package com.example.thinkanddo;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.thinkanddo.adapters.AdapterChat;
import com.example.thinkanddo.models.ModelChat;
import com.example.thinkanddo.models.ModelUsers;
import com.example.thinkanddo.notifications.APIService;
import com.example.thinkanddo.notifications.Client;
import com.example.thinkanddo.notifications.Data;
import com.example.thinkanddo.notifications.Response;
import com.example.thinkanddo.notifications.Sender;
import com.example.thinkanddo.notifications.Token;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
public class ChatActivity extends AppCompatActivity {
Toolbar toolbar;
RecyclerView recyclerView;
ImageButton sendBtn;
ImageView profileIv;
TextView nameTv, userStatusTv;
EditText messageEt;
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
DatabaseReference usersDbRef;
String hisUid;
String myUid;
String hisImage;
APIService apiService;
boolean notify= false;
//for checking if the uer has seen message or not.
ValueEventListener seenListener;
DatabaseReference userRefForSeen;
List<ModelChat> chatList;
AdapterChat adapterChat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("");
recyclerView = findViewById(R.id.chat_recyclerView);
sendBtn = findViewById(R.id.sendBtn);
profileIv = findViewById(R.id.profileIv);
nameTv = findViewById(R.id.nameTv);
userStatusTv = findViewById(R.id.userStatusTv);
messageEt = findViewById(R.id.messageEt);
firebaseAuth=firebaseAuth.getInstance();
Context context;
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
//create api service
apiService= Client.getRetrofit("https://fcm.googleapis.com/").create(APIService.class);
/*on Clicking user from users list we have passed that uid using intent
So get the uid here to get user image, name and start chat with that user.
*/
Intent intent = getIntent();
hisUid = intent.getStringExtra("hisUid");
firebaseDatabase = firebaseDatabase.getInstance();
usersDbRef = firebaseDatabase.getReference("Users");
//search user to get that users info
Query userQuery = usersDbRef.orderByChild("uid").equalTo(hisUid);
//get user picture and name
userQuery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//check until required info is received.
for(DataSnapshot ds:dataSnapshot.getChildren()){
//get data
String name ="" + ds.child("name").getValue();
hisImage ="" + ds.child("image").getValue();
String typingStatus ="" + ds.child("typingTo").getValue();
if (typingStatus.equals(myUid)){
userStatusTv.setText("typing...");
}
else{
String onineStatus = "" + ds.child("onlineStatus").getValue();
if(onineStatus.equals("online")){
userStatusTv.setText(onineStatus);
}
else{
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(Long.parseLong(onineStatus));
String dateTime = DateFormat.format("dd/mm/yyyy hh:mm aa",cal).toString();
userStatusTv.setText("Last seen at: "+ dateTime);
}
}
//set data
nameTv.setText(name);
try{
Picasso.get().load(hisImage).placeholder(R.drawable.ic_default).into(profileIv);
}
catch(Exception e){
Picasso.get().load(R.drawable.ic_default).into(profileIv);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
notify=true;
// get text from edittext
String message = messageEt.getText().toString().trim();
if(TextUtils.isEmpty(message)){
Toast.makeText(ChatActivity.this,"Cannot send empty mess..",Toast.LENGTH_LONG).show();
}
else{
sendMessage(message);
}
//reset edittext after sending message
messageEt.setText("");
}
});
messageEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().trim().length() == 0){
checkTypingStatus("noOne");
}
else {
checkTypingStatus(hisUid);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
messageEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().trim().length() == 0){
checkTypingStatus("noOne");
}
else {
checkTypingStatus(hisUid);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
readMessages();
seenMessage();
}
private void seenMessage() {
userRefForSeen = FirebaseDatabase.getInstance().getReference("Chats");
seenListener = userRefForSeen.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
ModelChat chat = ds.getValue(ModelChat.class);
if(chat.getReceiver().equals(myUid)&&chat.getSender().equals(hisUid)){
HashMap<String, Object> hasSeenHashMap = new HashMap<>();
hasSeenHashMap.put("isSeen", true);
ds.getRef().updateChildren(hasSeenHashMap);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void readMessages() {
chatList = new ArrayList<>();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Chats");
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
chatList.clear();
for(DataSnapshot ds: dataSnapshot.getChildren()){
ModelChat chat = ds.getValue(ModelChat.class);
if(chat.getReceiver().equals(myUid) && chat.getSender().equals(hisUid)||
chat.getReceiver().equals(hisUid) && chat.getSender().equals(myUid)){
chatList.add(chat);
}
adapterChat = new AdapterChat(ChatActivity.this,chatList,hisImage);
adapterChat.notifyDataSetChanged();
//set Adapter to recyclerview
recyclerView.setAdapter(adapterChat);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(final String message) {
/* "Chats" node will be created that will contains all chats
Whenever user sends message it will create new child in "Chats" node and that child will contain
sender: UID of sender
receiver: UID of receiver
message: the actual message
*/
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
String timestamp = String.valueOf(System.currentTimeMillis());
HashMap<String,Object> hashMap = new HashMap<>();
hashMap.put("sender",myUid);
hashMap.put("receiver",hisUid);
hashMap.put("message",message);
hashMap.put("timestamp",timestamp);
hashMap.put("isSeen",false);
databaseReference.child("Chats").push().setValue(hashMap);
final DatabaseReference database=FirebaseDatabase.getInstance().getReference("Users").child(myUid);
database.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ModelUsers user= dataSnapshot.getValue(ModelUsers.class);
if(notify){
sentNotification(hisUid,user.getName(), message);
}
notify=false;
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void sentNotification(final String hisUid, final String name, final String message) {
DatabaseReference allTokens= FirebaseDatabase.getInstance().getReference("Tokens");
Query query=allTokens.orderByKey().equalTo(hisUid);
query.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot){
for(DataSnapshot ds: dataSnapshot.getChildren()){
Token token=ds.getValue(Token.class);
Data data= new Data(myUid, name+":"+message,"New Message",hisUid, R.drawable.ic_default); //R.drawable.ic_default_img;
Sender sender=new Sender(data,token.getToken());
apiService.sendNotification(sender)
.enqueue(new Callback<Response>() {
@Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
Toast.makeText(ChatActivity.this,""+response.message(),Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<Response> call, Throwable t) {
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void checkUserStatus(){
FirebaseUser user =firebaseAuth.getCurrentUser();
if(user!=null){
//mprofileTv.setText(user.getEmail());
myUid = user.getUid();
}else{
startActivity(new Intent(this, MainActivity.class));
finish();
}
}
private void checkOnlineStatus(String status){
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Users").child(myUid);
HashMap<String, Object> hashMap =new HashMap<>();
hashMap.put("onlineStatus", status);
dbRef.updateChildren(hashMap);
}
private void checkTypingStatus(String typing){
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Users").child(myUid);
HashMap<String, Object> hashMap =new HashMap<>();
hashMap.put("typingTo", typing);
dbRef.updateChildren(hashMap);
}
@Override
protected void onStart() {
checkUserStatus();
checkOnlineStatus("online");
checkTypingStatus("noOne");
super.onStart();
}
@Override
protected void onPause() {
super.onPause();
String timestamp = String.valueOf(System.currentTimeMillis());
checkOnlineStatus(timestamp);
userRefForSeen.removeEventListener(seenListener);
}
@Override
protected void onResume() {
checkOnlineStatus("online");
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
menu.findItem(R.id.action_search).setVisible(false);
menu.findItem(R.id.action_add_post).setVisible(false);
return super.onCreateOptionsMenu(menu);
//x+y=1;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_logout){
firebaseAuth.signOut();
checkUserStatus();
}
return super.onOptionsItemSelected(item);
}
}
| 15,001 | 0.598027 | 0.59736 | 442 | 32.938915 | 28.176294 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.527149 | false | false | 9 |
33576ab1975426616dc2f42448bc7c49f861ea96 | 9,165,460,264,075 | 8c416a893af6cb21473cebbd1c63b848ce496ffc | /numberfacts/src/main/java/com/zdvdev/numberfacts/fragment/FactsFragment.java | 9fb39c2ad93697b5c69b2378bf53991977ead78b | [] | no_license | aballano/NumberFacts | https://github.com/aballano/NumberFacts | 1c91c237c57ef66ef2c5a6400c1f7cc1f9bd458d | 49906e4e8742ec7b5a5eb93f18f5dfd573d08a53 | refs/heads/master | 2021-05-30T20:00:23.743000 | 2014-06-06T07:50:28 | 2014-06-06T07:50:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zdvdev.numberfacts.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.zdvdev.numberfacts.BuildConfig;
import com.zdvdev.numberfacts.R;
import com.zdvdev.numberfacts.async.OnJobStatusChangedListener;
import com.zdvdev.numberfacts.common.Util;
import com.zdvdev.numberfacts.datamodel.DataManager;
import com.zdvdev.numberfacts.datamodel.model.FactType;
import com.zdvdev.numberfacts.datamodel.model.ResponseFact;
import retrofit.RetrofitError;
/**
* Created with Android Studio.
*
* @author Shyish
* Date: 27/03/14
*/
public class FactsFragment extends Fragment
implements OnJobStatusChangedListener<ResponseFact>, TextWatcher, RadioGroup.OnCheckedChangeListener, InputFilter {
private static final String PLAY_URL = "http://goo.gl/U1GTpx";
@InjectView(R.id.factsfragment_number_edittext) EditText numberEditText;
@InjectView(R.id.factsfragment_fact_textview) TextView factTextView;
@InjectView(R.id.factsfragment_type_group) RadioGroup typeRadioGroup;
@InjectView(R.id.factsfragment_getfact_button) Button getFactButton;
@InjectView(R.id.factsfragment_share_button) ImageButton shareButton;
private FactType currentFact = FactType.TRIVIA;
public FactsFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.facts_fragment_layout, container, false);
ButterKnife.inject(this, rootView);
return rootView;
}
@Override public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
typeRadioGroup.setOnCheckedChangeListener(this);
typeRadioGroup.check(typeRadioGroup.getChildAt(0).getId());
numberEditText.setFilters(new InputFilter[] {this});
numberEditText.addTextChangedListener(this);
}
@OnClick(R.id.factsfragment_getfact_button) void onGetFactButtonClicked() {
String number = numberEditText.getText().toString();
if (number.contains("/") && !Util.validateMDDate(number)) {
numberEditText.setError(getString(R.string.error_date));
} else {
DataManager.getFact(number, this, this, currentFact);
}
}
@OnClick(R.id.factsfragment_share_button) void onShareButtonClicked() {
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(android.content.Intent.EXTRA_SUBJECT, "Take a look at this fact!");
share.putExtra(android.content.Intent.EXTRA_TEXT, "Did you know that " + factTextView.getText() + "? (via NumberFacts " + PLAY_URL +
')');
//TODO try to compress the text for twitter share(?)
startActivity(Intent.createChooser(share, "Share this fact"));
}
/**
* ********************
* InputFilter METHOD *
* ********************
*/
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int k = start; k < end; k++) {
char c = source.charAt(k);
//Only allows digits or digits plus the '/' char if the current fact type is DATE
if (!(Character.isDigit(c) || (currentFact == FactType.DATE && c == '/'))) {
return "";
}
}
return null;
}
/**
* ************************************
* OnJobStatusChangedListener METHODS *
* ************************************
*/
@Override public void onCompleted(ResponseFact fact) {
if (!TextUtils.isEmpty(fact.getText())) {
factTextView.setText(fact.getText());
shareButton.setVisibility(View.VISIBLE);
}
}
@Override public void onError(Throwable throwable) {
factTextView.setText("");
shareButton.setVisibility(View.INVISIBLE);
if (throwable instanceof RetrofitError && ((RetrofitError) throwable).isNetworkError()) {
Toast.makeText(getActivity(), getString(R.string.error_internet), Toast.LENGTH_SHORT).show();
} else if (BuildConfig.DEBUG) {
numberEditText.setError(throwable.getMessage());
}
}
@Override public void onUpdate(int progress) {}
/**
* *********************************
* OnCheckedChangeListener METHODS *
* *********************************
*/
@Override public void onCheckedChanged(RadioGroup group, int checkedId) {
// Clear the edittext to avoid invalid chars in other fact types.
if (numberEditText.getText().toString().contains("/")) {
factTextView.setText("");
numberEditText.setText("");
}
int radioButtonID = group.getCheckedRadioButtonId();
View radioButton = group.findViewById(radioButtonID);
currentFact = FactType.values()[group.indexOfChild(radioButton)];
if (currentFact == FactType.DATE) {
numberEditText.setHint(R.string.write_number_date_hint);
numberEditText.setInputType(InputType.TYPE_CLASS_TEXT);
} else {
numberEditText.setHint(R.string.write_number_hint);
numberEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
}
/**
* *********************
* TextWatcher METHODS *
* *********************
*/
@Override public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) {
getFactButton.setText(R.string.get_fact);
} else {
getFactButton.setText(R.string.random_fact);
}
}
@Override public void afterTextChanged(Editable s) {}
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
} | UTF-8 | Java | 5,939 | java | FactsFragment.java | Java | [
{
"context": "\n/**\n * Created with Android Studio.\n *\n * @author Shyish\n * Date: 27/03/14\n */\npublic class FactsF",
"end": 1142,
"score": 0.9968636631965637,
"start": 1136,
"tag": "NAME",
"value": "Shyish"
}
] | null | [] | package com.zdvdev.numberfacts.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.zdvdev.numberfacts.BuildConfig;
import com.zdvdev.numberfacts.R;
import com.zdvdev.numberfacts.async.OnJobStatusChangedListener;
import com.zdvdev.numberfacts.common.Util;
import com.zdvdev.numberfacts.datamodel.DataManager;
import com.zdvdev.numberfacts.datamodel.model.FactType;
import com.zdvdev.numberfacts.datamodel.model.ResponseFact;
import retrofit.RetrofitError;
/**
* Created with Android Studio.
*
* @author Shyish
* Date: 27/03/14
*/
public class FactsFragment extends Fragment
implements OnJobStatusChangedListener<ResponseFact>, TextWatcher, RadioGroup.OnCheckedChangeListener, InputFilter {
private static final String PLAY_URL = "http://goo.gl/U1GTpx";
@InjectView(R.id.factsfragment_number_edittext) EditText numberEditText;
@InjectView(R.id.factsfragment_fact_textview) TextView factTextView;
@InjectView(R.id.factsfragment_type_group) RadioGroup typeRadioGroup;
@InjectView(R.id.factsfragment_getfact_button) Button getFactButton;
@InjectView(R.id.factsfragment_share_button) ImageButton shareButton;
private FactType currentFact = FactType.TRIVIA;
public FactsFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.facts_fragment_layout, container, false);
ButterKnife.inject(this, rootView);
return rootView;
}
@Override public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
typeRadioGroup.setOnCheckedChangeListener(this);
typeRadioGroup.check(typeRadioGroup.getChildAt(0).getId());
numberEditText.setFilters(new InputFilter[] {this});
numberEditText.addTextChangedListener(this);
}
@OnClick(R.id.factsfragment_getfact_button) void onGetFactButtonClicked() {
String number = numberEditText.getText().toString();
if (number.contains("/") && !Util.validateMDDate(number)) {
numberEditText.setError(getString(R.string.error_date));
} else {
DataManager.getFact(number, this, this, currentFact);
}
}
@OnClick(R.id.factsfragment_share_button) void onShareButtonClicked() {
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(android.content.Intent.EXTRA_SUBJECT, "Take a look at this fact!");
share.putExtra(android.content.Intent.EXTRA_TEXT, "Did you know that " + factTextView.getText() + "? (via NumberFacts " + PLAY_URL +
')');
//TODO try to compress the text for twitter share(?)
startActivity(Intent.createChooser(share, "Share this fact"));
}
/**
* ********************
* InputFilter METHOD *
* ********************
*/
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int k = start; k < end; k++) {
char c = source.charAt(k);
//Only allows digits or digits plus the '/' char if the current fact type is DATE
if (!(Character.isDigit(c) || (currentFact == FactType.DATE && c == '/'))) {
return "";
}
}
return null;
}
/**
* ************************************
* OnJobStatusChangedListener METHODS *
* ************************************
*/
@Override public void onCompleted(ResponseFact fact) {
if (!TextUtils.isEmpty(fact.getText())) {
factTextView.setText(fact.getText());
shareButton.setVisibility(View.VISIBLE);
}
}
@Override public void onError(Throwable throwable) {
factTextView.setText("");
shareButton.setVisibility(View.INVISIBLE);
if (throwable instanceof RetrofitError && ((RetrofitError) throwable).isNetworkError()) {
Toast.makeText(getActivity(), getString(R.string.error_internet), Toast.LENGTH_SHORT).show();
} else if (BuildConfig.DEBUG) {
numberEditText.setError(throwable.getMessage());
}
}
@Override public void onUpdate(int progress) {}
/**
* *********************************
* OnCheckedChangeListener METHODS *
* *********************************
*/
@Override public void onCheckedChanged(RadioGroup group, int checkedId) {
// Clear the edittext to avoid invalid chars in other fact types.
if (numberEditText.getText().toString().contains("/")) {
factTextView.setText("");
numberEditText.setText("");
}
int radioButtonID = group.getCheckedRadioButtonId();
View radioButton = group.findViewById(radioButtonID);
currentFact = FactType.values()[group.indexOfChild(radioButton)];
if (currentFact == FactType.DATE) {
numberEditText.setHint(R.string.write_number_date_hint);
numberEditText.setInputType(InputType.TYPE_CLASS_TEXT);
} else {
numberEditText.setHint(R.string.write_number_hint);
numberEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
}
/**
* *********************
* TextWatcher METHODS *
* *********************
*/
@Override public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) {
getFactButton.setText(R.string.get_fact);
} else {
getFactButton.setText(R.string.random_fact);
}
}
@Override public void afterTextChanged(Editable s) {}
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
} | 5,939 | 0.720828 | 0.719145 | 176 | 32.75 | 28.952253 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.778409 | false | false | 9 |
96e1eb3025a0efec2d19c8d1e690df057a9848de | 8,237,747,328,161 | 5b2ea3393763d7b1ffdd2baab804d1c4dda7c6c5 | /src/test/java/JUnitParameterisedTest.java | e6c60870f824bebe876dd1b2ccf080ad8756d986 | [] | no_license | itagakishintaro/selenium-study | https://github.com/itagakishintaro/selenium-study | 27d331a57cadea78761be50123a39815c5448f1c | e2507f2ca8ec74d0ea5083d023a65d4354258e47 | refs/heads/master | 2021-01-16T21:02:22.121000 | 2014-12-01T05:27:37 | 2014-12-01T05:27:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Created by itdbd on 2014/12/01.
*/
@RunWith(Theories.class)
public class JUnitParameterisedTest {
private WebDriver driver;
@Before
public void setUp() {
driver = new FirefoxDriver();
}
@After
public void tearDown() {
driver.quit();
}
@DataPoints // ここで複数のテストデータを定義
public static Fixture[] PARAMs = {
new Fixture("btnK", "Google 検索"),
new Fixture("btnI", "I'm Feeling Lucky")
};
@Theory
public void JUnitパラメタライズドテスト(Fixture fixture) {
driver.get("http://www.google.co.jp");
// パラメータの値ごとにテストを実施
WebElement element = driver.findElement(By.name(fixture.name));
assertThat( element.getAttribute("value"), is(fixture.value) );
}
static class Fixture{
String name;
String value;
public Fixture(String name, String value){
this.name = name;
this.value = value;
}
}
}
| UTF-8 | Java | 1,550 | java | JUnitParameterisedTest.java | Java | [
{
"context": "mcrest.MatcherAssert.assertThat;\n/**\n * Created by itdbd on 2014/12/01.\n */\n@RunWith(Theories.class)\npubli",
"end": 531,
"score": 0.9988828897476196,
"start": 526,
"tag": "USERNAME",
"value": "itdbd"
}
] | null | [] | import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Created by itdbd on 2014/12/01.
*/
@RunWith(Theories.class)
public class JUnitParameterisedTest {
private WebDriver driver;
@Before
public void setUp() {
driver = new FirefoxDriver();
}
@After
public void tearDown() {
driver.quit();
}
@DataPoints // ここで複数のテストデータを定義
public static Fixture[] PARAMs = {
new Fixture("btnK", "Google 検索"),
new Fixture("btnI", "I'm Feeling Lucky")
};
@Theory
public void JUnitパラメタライズドテスト(Fixture fixture) {
driver.get("http://www.google.co.jp");
// パラメータの値ごとにテストを実施
WebElement element = driver.findElement(By.name(fixture.name));
assertThat( element.getAttribute("value"), is(fixture.value) );
}
static class Fixture{
String name;
String value;
public Fixture(String name, String value){
this.name = name;
this.value = value;
}
}
}
| 1,550 | 0.675103 | 0.669631 | 55 | 25.581818 | 19.00688 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.527273 | false | false | 9 |
e6233fdb84484c6f339b462c66306ab0dee16a0a | 8,237,747,329,664 | 5888c2402bf712eda7405aad6c3c5e1450abcb3f | /test/src/main/java/lk/exame/test/controller/ResultController.java | 3af65af9c973032624d1a43d38cd0dd139fb4ed2 | [
"MIT"
] | permissive | TharakaCz/Mock-Exame-Final | https://github.com/TharakaCz/Mock-Exame-Final | ef58ba9f29097320c444394823184a0a248d90c9 | b0ed54d904d38abe84f3d62c2add4b4c2591d2d1 | refs/heads/master | 2020-05-19T17:05:12.534000 | 2019-05-31T11:58:45 | 2019-05-31T11:58:45 | 185,125,931 | 0 | 0 | MIT | false | 2019-05-31T11:58:46 | 2019-05-06T04:55:24 | 2019-05-27T12:11:33 | 2019-05-31T11:58:45 | 121 | 0 | 0 | 0 | Java | false | false | package lk.exame.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lk.exame.test.service.ResultService;
/**
*
* @author Tharaka Chandralal
*/
@RestController
@CrossOrigin
@RequestMapping(value = "/api/v1/result")
public class ResultController {
@Autowired
private ResultService resultService;
@GetMapping(value = "/findResult/{examId}")
private ResponseEntity<Object>findResultExamId(@PathVariable Integer examId){
try {
return new ResponseEntity<Object>(resultService.findByExamId(examId),HttpStatus.OK);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping(value = "/findResultUserName/{userName}")
private ResponseEntity<Object>findResultQuesName(@PathVariable String userName){
try {
return new ResponseEntity<Object>(resultService.findByUserName(userName),HttpStatus.OK);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| UTF-8 | Java | 1,576 | java | ResultController.java | Java | [
{
"context": "me.test.service.ResultService;\n\n/**\n * \n * @author Tharaka Chandralal\n */\n@RestController\n@CrossOrigin\n@RequestMapping(",
"end": 579,
"score": 0.9998722076416016,
"start": 561,
"tag": "NAME",
"value": "Tharaka Chandralal"
}
] | null | [] | package lk.exame.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lk.exame.test.service.ResultService;
/**
*
* @author <NAME>
*/
@RestController
@CrossOrigin
@RequestMapping(value = "/api/v1/result")
public class ResultController {
@Autowired
private ResultService resultService;
@GetMapping(value = "/findResult/{examId}")
private ResponseEntity<Object>findResultExamId(@PathVariable Integer examId){
try {
return new ResponseEntity<Object>(resultService.findByExamId(examId),HttpStatus.OK);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping(value = "/findResultUserName/{userName}")
private ResponseEntity<Object>findResultQuesName(@PathVariable String userName){
try {
return new ResponseEntity<Object>(resultService.findByUserName(userName),HttpStatus.OK);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| 1,564 | 0.781726 | 0.781091 | 49 | 31.163265 | 28.727678 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.489796 | false | false | 9 |
1055acdec3bc9baec2ca77e154d6ac0a438e33de | 34,789,235,147,819 | 093ddcec313ecc80dbaa96c43797ff53fc090b56 | /app/src/main/java/com/easylife/proplayer/Payment/PaymentActivity.java | 98a06c3789f11e6fe3ff8e26627af4ffb683acbc | [] | no_license | subhadiprudra/ProPlayer | https://github.com/subhadiprudra/ProPlayer | 3c92b711e6aa5c62a14187d640cd7e07f967ffed | 294eed9b627c1031da7fe70d5138a4ee9280b894 | refs/heads/master | 2023-03-02T17:40:10.710000 | 2021-02-14T09:33:44 | 2021-02-14T09:33:44 | 338,770,164 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.easylife.proplayer.Payment;
import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.easylife.proplayer.BasicFunctions;
import com.easylife.proplayer.R;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.paytm.pgsdk.PaytmOrder;
import com.paytm.pgsdk.PaytmPGService;
import com.paytm.pgsdk.PaytmPaymentTransactionCallback;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
public class PaymentActivity extends AppCompatActivity implements PaytmPaymentTransactionCallback {
String customerId = "";
String orderId = "";
String mid = "ohqCBM01981723810929";
String amount = "";
DatabaseReference reference;
BasicFunctions basicFunctions ;
Dialog dialogLoading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
basicFunctions=new BasicFunctions(this);
dialogLoading=new Dialog(this);
dialogLoading.setContentView(R.layout.loading_view);
dialogLoading.setCancelable(false);
ImageView imageView1 =dialogLoading.findViewById(R.id.loading_img);
Glide.with(this).load(R.drawable.loading).into(imageView1);
customerId = generateString();
orderId = generateString();
amount = getIntent().getStringExtra("amount");
getCheckSum cs = new getCheckSum();
cs.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public class getCheckSum extends AsyncTask<ArrayList<String>, Void, String> {
JSONObject jsonObject;
String url ="https://slushier-skin.000webhostapp.com/generateChecksum.php";
//TODO your server's url here (www.xyz/checksumGenerate.php)
String varifyurl = "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp";
String CHECKSUMHASH ="";
@Override
protected void onPreExecute() {
dialogLoading.show();
}
protected String doInBackground(ArrayList<String>... alldata) {
JsonParse jsonParser = new JsonParse(PaymentActivity.this);
String param=
"MID="+mid+
"&ORDER_ID=" + orderId+
"&CUST_ID="+customerId+
"&CHANNEL_ID=WAP&TXN_AMOUNT="+amount+"&WEBSITE=DEFAULT"+
"&CALLBACK_URL="+ varifyurl+"&INDUSTRY_TYPE_ID=Retail";
Log.e("PostData",param);
jsonObject= jsonParser.makeHttpRequest(url,"POST",param);
Log.e("CheckSum result >>",jsonObject.toString());
if(jsonObject != null){
Log.e("CheckSum result >>",jsonObject.toString());
try {
CHECKSUMHASH=jsonObject.has("CHECKSUMHASH")?jsonObject.getString("CHECKSUMHASH"):"";
Log.e("CheckSum result >>",CHECKSUMHASH);
} catch (JSONException e) {
e.printStackTrace();
}
}
return CHECKSUMHASH;
}
@Override
protected void onPostExecute(String result) {
Log.e(" setup acc "," signup result " + result);
// PaytmPGService Service = PaytmPGService.getStagingService();
PaytmPGService Service = PaytmPGService.getProductionService();
HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("MID", mid);
paramMap.put("ORDER_ID", orderId);
paramMap.put("CUST_ID", customerId);
paramMap.put("CHANNEL_ID", "WAP");
paramMap.put("TXN_AMOUNT", amount);
paramMap.put("WEBSITE", "DEFAULT");
paramMap.put("CALLBACK_URL" ,varifyurl);
paramMap.put("CHECKSUMHASH" ,CHECKSUMHASH);
paramMap.put("INDUSTRY_TYPE_ID", "Retail");
PaytmOrder Order = new PaytmOrder(paramMap);
Log.e("checksum ", "param "+ paramMap.toString());
Service.initialize(Order,null);
Service.startPaymentTransaction(PaymentActivity.this, true,
true,
PaymentActivity.this );
if (dialogLoading.isShowing()) {
dialogLoading.dismiss();
}
}
}
@Override
public void onTransactionResponse(Bundle inResponse) {
if(inResponse.getString("STATUS").equals("TXN_SUCCESS")){
Toast.makeText(this, "Payment successful", Toast.LENGTH_LONG).show();
dialogLoading.show();
reference= FirebaseDatabase.getInstance().getReference("accounts").child(basicFunctions.read("id")).child("balance");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String b= dataSnapshot.getValue(String.class);
int ba= Integer.parseInt(b);
ba= ba+Integer.parseInt(amount);
String bal= String.valueOf(ba);
reference.setValue(bal).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
if (dialogLoading.isShowing()) {
dialogLoading.dismiss();
}
finish();
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
Log.e("xxxxxxxxxxxxxx",inResponse.toString());
}
@Override
public void networkNotAvailable() {
Log.e("Trans ", "Network Not Available" );
Toast.makeText(this, "Network Not Available", Toast.LENGTH_LONG).show();
finish();
}
@Override
public void clientAuthenticationFailed(String s) {
Log.e("Trans ", " Authentication Failed "+ s );
Toast.makeText(this, "Authentication Failed", Toast.LENGTH_LONG).show();
finish();
}
@Override
public void someUIErrorOccurred(String s) {
Log.e("Trans ", " ui fail respon "+ s );
Toast.makeText(this, "UI Error Occurred", Toast.LENGTH_LONG).show();
finish();
}
@Override
public void onErrorLoadingWebPage(int i, String s, String s1) {
Log.e("Trans ", " error loading pagerespon true "+ s + " s1 " + s1);
Toast.makeText(this, "onErrorLoadingWebPage", Toast.LENGTH_LONG).show();
finish();
}
@Override
public void onBackPressedCancelTransaction() {
Toast.makeText(this, "Transaction Cancel", Toast.LENGTH_LONG).show();
Log.e("Trans ", " cancel call back respon " );
finish();
}
@Override
public void onTransactionCancel(String s, Bundle bundle) {
Toast.makeText(this, "Transaction Cancel", Toast.LENGTH_LONG).show();
Log.e("Trans ", " transaction cancel " );
finish();
}
private String generateString() {
String uuid = UUID.randomUUID().toString();
return uuid.replaceAll("-", "");
}
}
| UTF-8 | Java | 7,891 | java | PaymentActivity.java | Java | [] | null | [] | package com.easylife.proplayer.Payment;
import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.easylife.proplayer.BasicFunctions;
import com.easylife.proplayer.R;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.paytm.pgsdk.PaytmOrder;
import com.paytm.pgsdk.PaytmPGService;
import com.paytm.pgsdk.PaytmPaymentTransactionCallback;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
public class PaymentActivity extends AppCompatActivity implements PaytmPaymentTransactionCallback {
String customerId = "";
String orderId = "";
String mid = "ohqCBM01981723810929";
String amount = "";
DatabaseReference reference;
BasicFunctions basicFunctions ;
Dialog dialogLoading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
basicFunctions=new BasicFunctions(this);
dialogLoading=new Dialog(this);
dialogLoading.setContentView(R.layout.loading_view);
dialogLoading.setCancelable(false);
ImageView imageView1 =dialogLoading.findViewById(R.id.loading_img);
Glide.with(this).load(R.drawable.loading).into(imageView1);
customerId = generateString();
orderId = generateString();
amount = getIntent().getStringExtra("amount");
getCheckSum cs = new getCheckSum();
cs.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public class getCheckSum extends AsyncTask<ArrayList<String>, Void, String> {
JSONObject jsonObject;
String url ="https://slushier-skin.000webhostapp.com/generateChecksum.php";
//TODO your server's url here (www.xyz/checksumGenerate.php)
String varifyurl = "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp";
String CHECKSUMHASH ="";
@Override
protected void onPreExecute() {
dialogLoading.show();
}
protected String doInBackground(ArrayList<String>... alldata) {
JsonParse jsonParser = new JsonParse(PaymentActivity.this);
String param=
"MID="+mid+
"&ORDER_ID=" + orderId+
"&CUST_ID="+customerId+
"&CHANNEL_ID=WAP&TXN_AMOUNT="+amount+"&WEBSITE=DEFAULT"+
"&CALLBACK_URL="+ varifyurl+"&INDUSTRY_TYPE_ID=Retail";
Log.e("PostData",param);
jsonObject= jsonParser.makeHttpRequest(url,"POST",param);
Log.e("CheckSum result >>",jsonObject.toString());
if(jsonObject != null){
Log.e("CheckSum result >>",jsonObject.toString());
try {
CHECKSUMHASH=jsonObject.has("CHECKSUMHASH")?jsonObject.getString("CHECKSUMHASH"):"";
Log.e("CheckSum result >>",CHECKSUMHASH);
} catch (JSONException e) {
e.printStackTrace();
}
}
return CHECKSUMHASH;
}
@Override
protected void onPostExecute(String result) {
Log.e(" setup acc "," signup result " + result);
// PaytmPGService Service = PaytmPGService.getStagingService();
PaytmPGService Service = PaytmPGService.getProductionService();
HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("MID", mid);
paramMap.put("ORDER_ID", orderId);
paramMap.put("CUST_ID", customerId);
paramMap.put("CHANNEL_ID", "WAP");
paramMap.put("TXN_AMOUNT", amount);
paramMap.put("WEBSITE", "DEFAULT");
paramMap.put("CALLBACK_URL" ,varifyurl);
paramMap.put("CHECKSUMHASH" ,CHECKSUMHASH);
paramMap.put("INDUSTRY_TYPE_ID", "Retail");
PaytmOrder Order = new PaytmOrder(paramMap);
Log.e("checksum ", "param "+ paramMap.toString());
Service.initialize(Order,null);
Service.startPaymentTransaction(PaymentActivity.this, true,
true,
PaymentActivity.this );
if (dialogLoading.isShowing()) {
dialogLoading.dismiss();
}
}
}
@Override
public void onTransactionResponse(Bundle inResponse) {
if(inResponse.getString("STATUS").equals("TXN_SUCCESS")){
Toast.makeText(this, "Payment successful", Toast.LENGTH_LONG).show();
dialogLoading.show();
reference= FirebaseDatabase.getInstance().getReference("accounts").child(basicFunctions.read("id")).child("balance");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String b= dataSnapshot.getValue(String.class);
int ba= Integer.parseInt(b);
ba= ba+Integer.parseInt(amount);
String bal= String.valueOf(ba);
reference.setValue(bal).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
if (dialogLoading.isShowing()) {
dialogLoading.dismiss();
}
finish();
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
Log.e("xxxxxxxxxxxxxx",inResponse.toString());
}
@Override
public void networkNotAvailable() {
Log.e("Trans ", "Network Not Available" );
Toast.makeText(this, "Network Not Available", Toast.LENGTH_LONG).show();
finish();
}
@Override
public void clientAuthenticationFailed(String s) {
Log.e("Trans ", " Authentication Failed "+ s );
Toast.makeText(this, "Authentication Failed", Toast.LENGTH_LONG).show();
finish();
}
@Override
public void someUIErrorOccurred(String s) {
Log.e("Trans ", " ui fail respon "+ s );
Toast.makeText(this, "UI Error Occurred", Toast.LENGTH_LONG).show();
finish();
}
@Override
public void onErrorLoadingWebPage(int i, String s, String s1) {
Log.e("Trans ", " error loading pagerespon true "+ s + " s1 " + s1);
Toast.makeText(this, "onErrorLoadingWebPage", Toast.LENGTH_LONG).show();
finish();
}
@Override
public void onBackPressedCancelTransaction() {
Toast.makeText(this, "Transaction Cancel", Toast.LENGTH_LONG).show();
Log.e("Trans ", " cancel call back respon " );
finish();
}
@Override
public void onTransactionCancel(String s, Bundle bundle) {
Toast.makeText(this, "Transaction Cancel", Toast.LENGTH_LONG).show();
Log.e("Trans ", " transaction cancel " );
finish();
}
private String generateString() {
String uuid = UUID.randomUUID().toString();
return uuid.replaceAll("-", "");
}
}
| 7,891 | 0.605753 | 0.602965 | 245 | 31.208164 | 27.91272 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657143 | false | false | 9 |
d44d7ebae6678c71cf7193a5fc70132fd8418af3 | 37,520,834,330,635 | 958a8643a2e8658b078f5f17fb537a8781a5bcb3 | /app/src/main/java/com/example/tommy_2/bikeguidence/RouteSelection.java | ed70aaea7bd57aef0ed51daf80ae6842fb64f6c6 | [] | no_license | sullivt03/Android-Bike-Guidance | https://github.com/sullivt03/Android-Bike-Guidance | bb6f511631ab0ad7fa9499460d9876ede0418c41 | 19b5ed1aacfc2dc25a607f0422e85245ae057bac | refs/heads/master | 2021-01-19T05:19:44.904000 | 2015-05-06T15:45:33 | 2015-05-06T15:45:33 | 33,962,310 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.tommy_2.bikeguidence;
/**
* Created by tommy_2 on 4/6/2015.
*/
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class RouteSelection extends Activity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.route_selection);
Button Route_1_OK =
(Button) findViewById(R.id.route_selection_1);
Route_1_OK.setOnClickListener(this);
Button Route_2_OK =
(Button) findViewById(R.id.route_selection_2);
Route_2_OK.setOnClickListener(this);
Button Route_3_OK =
(Button) findViewById(R.id.route_selection_3);
Route_3_OK.setOnClickListener(this);
Button Route_4_OK =
(Button) findViewById(R.id.route_selection_4);
Route_4_OK.setOnClickListener(this);
Button Route_EXIT =
(Button) findViewById(R.id.route_selection_exit);
Route_EXIT.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.route_selection_1:
Intent i = new Intent(
RouteSelection.this, ElevenMileRoute.class);
startActivity(i);
break;
case R.id.route_selection_2:
Intent j = new Intent(
RouteSelection.this, TwentyMileMap.class);
startActivity(j);
break;
case R.id.route_selection_3:
Intent k = new Intent(
RouteSelection.this, FortyFiveMileMap.class);
startActivity(k);
break;
case R.id.route_selection_4:
Intent r = new Intent(
RouteSelection.this, SixtyTwoMileMap.class);
startActivity(r);
break;
case R.id.route_selection_exit:
Intent t = new Intent(
RouteSelection.this, Login.class);
startActivity(t);
break;
}
}
}
| UTF-8 | Java | 2,291 | java | RouteSelection.java | Java | [
{
"context": "package com.example.tommy_2.bikeguidence;\n\n/**\n * Created by tommy_2 on 4/6/2",
"end": 27,
"score": 0.9283385872840881,
"start": 20,
"tag": "USERNAME",
"value": "tommy_2"
},
{
"context": "m.example.tommy_2.bikeguidence;\n\n/**\n * Created by tommy_2 on 4/6/2015.\n */\nimport android.app.Activity;\nimp",
"end": 68,
"score": 0.9995874762535095,
"start": 61,
"tag": "USERNAME",
"value": "tommy_2"
}
] | null | [] | package com.example.tommy_2.bikeguidence;
/**
* Created by tommy_2 on 4/6/2015.
*/
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class RouteSelection extends Activity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.route_selection);
Button Route_1_OK =
(Button) findViewById(R.id.route_selection_1);
Route_1_OK.setOnClickListener(this);
Button Route_2_OK =
(Button) findViewById(R.id.route_selection_2);
Route_2_OK.setOnClickListener(this);
Button Route_3_OK =
(Button) findViewById(R.id.route_selection_3);
Route_3_OK.setOnClickListener(this);
Button Route_4_OK =
(Button) findViewById(R.id.route_selection_4);
Route_4_OK.setOnClickListener(this);
Button Route_EXIT =
(Button) findViewById(R.id.route_selection_exit);
Route_EXIT.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.route_selection_1:
Intent i = new Intent(
RouteSelection.this, ElevenMileRoute.class);
startActivity(i);
break;
case R.id.route_selection_2:
Intent j = new Intent(
RouteSelection.this, TwentyMileMap.class);
startActivity(j);
break;
case R.id.route_selection_3:
Intent k = new Intent(
RouteSelection.this, FortyFiveMileMap.class);
startActivity(k);
break;
case R.id.route_selection_4:
Intent r = new Intent(
RouteSelection.this, SixtyTwoMileMap.class);
startActivity(r);
break;
case R.id.route_selection_exit:
Intent t = new Intent(
RouteSelection.this, Login.class);
startActivity(t);
break;
}
}
}
| 2,291 | 0.557398 | 0.546923 | 76 | 29.144737 | 21.710236 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
07566e3e4f728a8779994ad1352e599e29fd3aa9 | 29,188,597,807,060 | 6f60d6ba6acee9432b6fa05dc1ec92038ad1ef8c | /src/main/java/pro/spboot/EurasclimatApplication.java | 710d1a24a615a8c1b9787805bf450f06f4534df0 | [] | no_license | gprohorov/eurasclimat | https://github.com/gprohorov/eurasclimat | 87abc1e90121112c45bd6612e706f4d82ea1cd14 | 50bf568eb94bcca63b9ae5b6cf2da379610fbd95 | refs/heads/master | 2017-06-24T16:30:43.408000 | 2017-03-01T18:55:09 | 2017-03-01T18:55:09 | 83,589,624 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pro.spboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import pro.spboot.controller.TestController;
import javax.annotation.PostConstruct;
@SpringBootApplication
public class EurasclimatApplication {
@Autowired
private TestController testController;
@PostConstruct
public void init(){
testController.showAll();
}
public static void main(String[] args) {
SpringApplication.run(EurasclimatApplication.class, args);
}
}
| UTF-8 | Java | 586 | java | EurasclimatApplication.java | Java | [] | null | [] | package pro.spboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import pro.spboot.controller.TestController;
import javax.annotation.PostConstruct;
@SpringBootApplication
public class EurasclimatApplication {
@Autowired
private TestController testController;
@PostConstruct
public void init(){
testController.showAll();
}
public static void main(String[] args) {
SpringApplication.run(EurasclimatApplication.class, args);
}
}
| 586 | 0.8157 | 0.8157 | 28 | 19.928572 | 22.142281 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 9 |
82fc23415e80b268ede235c0c08358372e5e9918 | 39,307,540,700,364 | cbbdec7392af1fa7e2e1af45b70952fae6f569b4 | /project-demo/im/src/main/java/com/star/im/handler/AuthHandler.java | a6e3a46d0652a86ce7839756e1ab28733c62846f | [] | no_license | starisgeek/projects-all | https://github.com/starisgeek/projects-all | 3a58f24a5ecc0b6748605596bb60e87ede5badbd | f822e9b665cffa8c038a756218ef04bb4723926a | refs/heads/master | 2020-03-28T16:03:33.537000 | 2019-01-19T13:23:21 | 2019-01-19T13:23:21 | 148,654,851 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.star.im.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.star.im.util.SessionManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandler.Sharable;
@Sharable
public class AuthHandler extends ChannelInboundHandlerAdapter {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public static final AuthHandler INSTANCE = new AuthHandler();
private AuthHandler() {
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (SessionManager.hasLogin(ctx.channel())) {
ctx.pipeline().remove(this);
super.channelRead(ctx, msg);
} else {
ctx.channel().close();
}
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
logger.info("登录成功,删除自己");
super.handlerRemoved(ctx);
}
}
| UTF-8 | Java | 965 | java | AuthHandler.java | Java | [] | null | [] | package com.star.im.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.star.im.util.SessionManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandler.Sharable;
@Sharable
public class AuthHandler extends ChannelInboundHandlerAdapter {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public static final AuthHandler INSTANCE = new AuthHandler();
private AuthHandler() {
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (SessionManager.hasLogin(ctx.channel())) {
ctx.pipeline().remove(this);
super.channelRead(ctx, msg);
} else {
ctx.channel().close();
}
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
logger.info("登录成功,删除自己");
super.handlerRemoved(ctx);
}
}
| 965 | 0.741834 | 0.739726 | 36 | 24.361111 | 24.253468 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.277778 | false | false | 9 |
c31b91c9a12b407be3bf400bec25ae1d4b956dfd | 36,627,481,143,185 | 4bfa992adde7ca3c8125f7d38c4e52793ca603a5 | /src/com/java/abstracttest/AbstractDemo2.java | d67419e6919ae503f2d7f95b0b936813e38f9db0 | [] | no_license | veeraravi/COREJAVA | https://github.com/veeraravi/COREJAVA | 7f402af7b72a801d6d9ef8ef192e055ff0ba7a23 | 9a4bb555edb9dc48bf37607817bb8cd8446e3502 | refs/heads/master | 2021-01-11T14:37:34.144000 | 2017-01-27T03:43:13 | 2017-01-27T03:43:13 | 80,178,052 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.java.abstracttest;
abstract class BANK{
abstract public int getROI();
}
class ICICI extends BANK{
@Override
public int getROI() {
System.out.println("i am from ICICI our ROI is "+10);
return 10;
}
}
class HDFC extends BANK{
@Override
public int getROI() {
System.out.println("i am from HDFC our ROI is "+10);
return 10;
}
}
public class AbstractDemo2 {
public static void main(String[] args) {
}
}
| UTF-8 | Java | 453 | java | AbstractDemo2.java | Java | [] | null | [] | package com.java.abstracttest;
abstract class BANK{
abstract public int getROI();
}
class ICICI extends BANK{
@Override
public int getROI() {
System.out.println("i am from ICICI our ROI is "+10);
return 10;
}
}
class HDFC extends BANK{
@Override
public int getROI() {
System.out.println("i am from HDFC our ROI is "+10);
return 10;
}
}
public class AbstractDemo2 {
public static void main(String[] args) {
}
}
| 453 | 0.657837 | 0.637969 | 38 | 10.921053 | 15.187221 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.868421 | false | false | 9 |
a1472709afae13438e0fec58542cb0fb3b7a3714 | 35,940,286,381,003 | db6d5f6ba0dc3540c944b729ad6d116a9ad954cb | /usage/flink_sql/src/main/java/com/ns/bdp/flink/sql/OrderNumsPerMinutesSql.java | e441bd2d78c73e007a2a1a8a74c343856d04b2d0 | [] | no_license | xuyicn/flink-learn | https://github.com/xuyicn/flink-learn | be76ff3dee5bef44c11c093bed2f80645f0b9f38 | c9beac437172beb3a59a022324a909a6fa6ac7f4 | refs/heads/master | 2022-04-21T20:48:11.374000 | 2020-04-24T06:09:18 | 2020-04-24T06:09:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ns.bdp.flink.sql;
import com.ns.bdp.flink.util.CommodityData;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Module Desc:
* 用于统计每分钟的订单数量。
* 模拟数据格式:时间戳(long),用户id(String),订单id(String),价格(double)
*/
public class OrderNumsPerMinutesSql {
public static final Logger logger = LoggerFactory.getLogger(OrderNumsPerMinutesSql.class);
public static final String JOB_NAME = OrderNumsPerMinutesSql.class.getSimpleName();
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
EnvironmentSettings settings = EnvironmentSettings.newInstance()
.useOldPlanner().inStreamingMode().build();
StreamTableEnvironment tEnv = StreamTableEnvironment.create(env, settings);
DataStream<String> lineStream = env.fromCollection(CommodityData.simulateData());
DataStream<Row> rowStream = lineStream.map(new MapFunction<String, Row>() {
@Override
// 如果输入数据非法,业务需要根据实际情况处理
public Row map(String line) throws Exception {
String[] splits = line.split(",");
long time = Long.parseLong(splits[0]);
String oid = splits[2];
return Row.of(time, oid);
}
}).returns(Types.ROW(Types.LONG, Types.STRING));
DataStream<Row> watermarkStream = rowStream.assignTimestampsAndWatermarks(
new BoundedOutOfOrdernessTimestampExtractor<Row>(Time.minutes(0)) {
@Override
public long extractTimestamp(Row row) {
return (long) row.getField(0);
}
});
tEnv.createTemporaryView("t_orders", watermarkStream, "atime,oid,rowtime.rowtime");
String sql = "select tumble_start(rowtime,interval '1' minute) as wstart," +
"tumble_end(rowtime,interval '1' minute) as wend," +
"count(oid) as total " +
"from t_orders " +
"group by tumble(rowtime,interval '1' minute)";
Table table = tEnv.sqlQuery(sql);
DataStream<Row> reultStream = tEnv.toAppendStream(table, Row.class);
reultStream.addSink(new SinkFunction<Row>() {
@Override
public void invoke(Row value, Context context) throws Exception {
logger.info("value: " + value.toString());
}
}).setParallelism(1);
env.execute(JOB_NAME);
}
}
| UTF-8 | Java | 3,448 | java | OrderNumsPerMinutesSql.java | Java | [] | null | [] | package com.ns.bdp.flink.sql;
import com.ns.bdp.flink.util.CommodityData;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Module Desc:
* 用于统计每分钟的订单数量。
* 模拟数据格式:时间戳(long),用户id(String),订单id(String),价格(double)
*/
public class OrderNumsPerMinutesSql {
public static final Logger logger = LoggerFactory.getLogger(OrderNumsPerMinutesSql.class);
public static final String JOB_NAME = OrderNumsPerMinutesSql.class.getSimpleName();
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
EnvironmentSettings settings = EnvironmentSettings.newInstance()
.useOldPlanner().inStreamingMode().build();
StreamTableEnvironment tEnv = StreamTableEnvironment.create(env, settings);
DataStream<String> lineStream = env.fromCollection(CommodityData.simulateData());
DataStream<Row> rowStream = lineStream.map(new MapFunction<String, Row>() {
@Override
// 如果输入数据非法,业务需要根据实际情况处理
public Row map(String line) throws Exception {
String[] splits = line.split(",");
long time = Long.parseLong(splits[0]);
String oid = splits[2];
return Row.of(time, oid);
}
}).returns(Types.ROW(Types.LONG, Types.STRING));
DataStream<Row> watermarkStream = rowStream.assignTimestampsAndWatermarks(
new BoundedOutOfOrdernessTimestampExtractor<Row>(Time.minutes(0)) {
@Override
public long extractTimestamp(Row row) {
return (long) row.getField(0);
}
});
tEnv.createTemporaryView("t_orders", watermarkStream, "atime,oid,rowtime.rowtime");
String sql = "select tumble_start(rowtime,interval '1' minute) as wstart," +
"tumble_end(rowtime,interval '1' minute) as wend," +
"count(oid) as total " +
"from t_orders " +
"group by tumble(rowtime,interval '1' minute)";
Table table = tEnv.sqlQuery(sql);
DataStream<Row> reultStream = tEnv.toAppendStream(table, Row.class);
reultStream.addSink(new SinkFunction<Row>() {
@Override
public void invoke(Row value, Context context) throws Exception {
logger.info("value: " + value.toString());
}
}).setParallelism(1);
env.execute(JOB_NAME);
}
}
| 3,448 | 0.676965 | 0.673965 | 72 | 45.305557 | 28.512491 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.736111 | false | false | 9 |
cb5fa5a4a315d87675766b38cf62e7346580a52d | 39,101,382,304,252 | f3aaa490a4e7dbfa15effea7d300d812a33345ec | /onlinejudge/11498 - Division of Nlogonia/DivOfNlogonia.java | 9a533db21bb669f7f038d778c2a78ca1a19d02e7 | [] | no_license | Zeldacrafter/onlinejudge | https://github.com/Zeldacrafter/onlinejudge | 37cab1894621997b834652b3d9192ed2dcb4b997 | 2f26c99d77beec95f0837f4e06634437cff34ce1 | refs/heads/master | 2020-09-06T17:21:40.663000 | 2020-08-29T13:46:12 | 2020-08-29T13:46:12 | 220,492,285 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class DivOfNlogonia {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(true) {
int queries = s.nextInt();
if(queries == 0) break;
int n = s.nextInt();
int m = s.nextInt();
for(int i = 0; i < queries; i++) {
int x = s.nextInt();
int y = s.nextInt();
if(x == n || y == m) System.out.println("divisa");
else if(x < n && y > m) System.out.println("NO");
else if(x > n && y > m) System.out.println("NE");
else if(x > n && y < m) System.out.println("SE");
else if(x < n && y < m) System.out.println("SO");
}
}
s.close();
}
}
| UTF-8 | Java | 817 | java | DivOfNlogonia.java | Java | [] | null | [] | import java.util.Scanner;
public class DivOfNlogonia {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(true) {
int queries = s.nextInt();
if(queries == 0) break;
int n = s.nextInt();
int m = s.nextInt();
for(int i = 0; i < queries; i++) {
int x = s.nextInt();
int y = s.nextInt();
if(x == n || y == m) System.out.println("divisa");
else if(x < n && y > m) System.out.println("NO");
else if(x > n && y > m) System.out.println("NE");
else if(x > n && y < m) System.out.println("SE");
else if(x < n && y < m) System.out.println("SO");
}
}
s.close();
}
}
| 817 | 0.433293 | 0.430845 | 29 | 27.172413 | 23.121969 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62069 | false | false | 9 |
7f2ed9870c16dc4c29bde15978e24f8b8d7b68d4 | 20,289,425,522,771 | ce2c7acbee5ed58402ca5c1001a8ffe6b1913cc9 | /src/com/arclight/collectorx/xmlparsers/ListXMLParser.java | 306f9e8040935153723dc4e4b05fdabef2975b88 | [] | no_license | Arclights/CollectorX | https://github.com/Arclights/CollectorX | aefb018779237f3f9fa3db896da0eb470255417e | 50efe6d5d52d2c4c5c6a72165da1235785595b12 | refs/heads/master | 2021-01-22T02:34:03.185000 | 2014-02-27T23:47:28 | 2014-02-27T23:47:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.arclight.collectorx.xmlparsers;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import com.arclight.collectorx.moviecontainers.MovieListItem;
public class ListXMLParser {
// We don't use namespaces
private static final String ns = null;
public static ArrayList<MovieListItem> parse(InputStream input)
throws XmlPullParserException, IOException {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(input, "utf8");
ArrayList<MovieListItem> mli = new ArrayList<MovieListItem>();
parser.nextTag();
parser.require(XmlPullParser.START_TAG, ns, "movielist");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
mli.add(parseMovieListItem(parser));
}
parser.require(XmlPullParser.END_TAG, ns, "movielist");
return mli;
}
private static MovieListItem parseMovieListItem(XmlPullParser parser)
throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "movielistitem");
String id = "";
String title = "";
int year = 0;
Bitmap thumbnail = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("id")) {
id = parseid(parser);
} else if (name.equals("title")) {
title = parseTitle(parser);
} else if (name.equals("year")) {
year = parseYear(parser);
} else if (name.equals("thumbnail")) {
thumbnail = parseThumbnail(parser);
}
}
parser.require(XmlPullParser.END_TAG, ns, "movielistitem");
return new MovieListItem(id, title, year, thumbnail);
}
private static String parseid(XmlPullParser parser)
throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "id");
String id = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "id");
return id;
}
private static String parseTitle(XmlPullParser parser)
throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "title");
String title = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "title");
return title;
}
private static int parseYear(XmlPullParser parser)
throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "year");
int year = readInteger(parser);
parser.require(XmlPullParser.END_TAG, ns, "year");
return year;
}
private static Bitmap parseThumbnail(XmlPullParser parser)
throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "thumbnail");
String thumbnail = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "thumbnail");
byte[] bytes = Base64.decode(thumbnail, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
private static String readText(XmlPullParser parser) throws IOException,
XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText().replaceAll("\\s\\s+", " ");
parser.nextTag();
}
return result;
}
private static int readInteger(XmlPullParser parser) throws IOException,
XmlPullParserException {
int result = 0;
if (parser.next() == XmlPullParser.TEXT) {
result = Integer.parseInt(parser.getText());
parser.nextTag();
}
return result;
}
}
| UTF-8 | Java | 3,758 | java | ListXMLParser.java | Java | [] | null | [] | package com.arclight.collectorx.xmlparsers;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import com.arclight.collectorx.moviecontainers.MovieListItem;
public class ListXMLParser {
// We don't use namespaces
private static final String ns = null;
public static ArrayList<MovieListItem> parse(InputStream input)
throws XmlPullParserException, IOException {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(input, "utf8");
ArrayList<MovieListItem> mli = new ArrayList<MovieListItem>();
parser.nextTag();
parser.require(XmlPullParser.START_TAG, ns, "movielist");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
mli.add(parseMovieListItem(parser));
}
parser.require(XmlPullParser.END_TAG, ns, "movielist");
return mli;
}
private static MovieListItem parseMovieListItem(XmlPullParser parser)
throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "movielistitem");
String id = "";
String title = "";
int year = 0;
Bitmap thumbnail = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("id")) {
id = parseid(parser);
} else if (name.equals("title")) {
title = parseTitle(parser);
} else if (name.equals("year")) {
year = parseYear(parser);
} else if (name.equals("thumbnail")) {
thumbnail = parseThumbnail(parser);
}
}
parser.require(XmlPullParser.END_TAG, ns, "movielistitem");
return new MovieListItem(id, title, year, thumbnail);
}
private static String parseid(XmlPullParser parser)
throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "id");
String id = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "id");
return id;
}
private static String parseTitle(XmlPullParser parser)
throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "title");
String title = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "title");
return title;
}
private static int parseYear(XmlPullParser parser)
throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "year");
int year = readInteger(parser);
parser.require(XmlPullParser.END_TAG, ns, "year");
return year;
}
private static Bitmap parseThumbnail(XmlPullParser parser)
throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "thumbnail");
String thumbnail = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "thumbnail");
byte[] bytes = Base64.decode(thumbnail, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
private static String readText(XmlPullParser parser) throws IOException,
XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText().replaceAll("\\s\\s+", " ");
parser.nextTag();
}
return result;
}
private static int readInteger(XmlPullParser parser) throws IOException,
XmlPullParserException {
int result = 0;
if (parser.next() == XmlPullParser.TEXT) {
result = Integer.parseInt(parser.getText());
parser.nextTag();
}
return result;
}
}
| 3,758 | 0.732304 | 0.728845 | 121 | 30.057852 | 22.260775 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.495868 | false | false | 9 |
5f5ec8187e39e15aa518b6a20bd3c2cabf23a2d3 | 13,503,377,194,319 | 3a0ad6b2233831158e172cc5e038e9d5ca7fe80d | /src/dao/feature/FeatureDaoFile.java | bd75a033ed95352d2ca72829e3241fff1f02ad03 | [] | no_license | walkap/delphino | https://github.com/walkap/delphino | d674402d3957a3b22564efa3be73e6ebbf4fb523 | bbe832d9a44f1a36ac89fd92222acd687c2e91df | refs/heads/master | 2021-09-06T10:30:16.550000 | 2018-02-05T15:04:22 | 2018-02-05T15:04:22 | 112,827,709 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dao.feature;
import entity.Feature;
import java.io.*;
import java.util.ArrayList;
public class FeatureDaoFile implements FeatureDao{
private static final String fileName = "C:\\Projects\\delphino\\feature.ser";
public void newFeatureFile() {
String path = "C:\\Projects\\delphino\\feature.ser";
try {
File file = new File(path);
if (file.exists())
System.out.println("Il file " + path + " esiste");
else if (file.createNewFile())
System.out.println("Il file " + path + " è stato creato");
else
System.out.println("Il file " + path + " non può essere creato");
} catch (IOException e) {
e.printStackTrace();
}
}
public void updateFeature (Feature f) {
String nameF = f.getName();
String descriptionF = f.getDescription();
try {
if(isFeaturePresent(f)){
ArrayList<Feature> list = deserialize();
for (int j=0; j < list.size(); j++){
if(list.get(j).getName().equals(f.getName())){
list.get(j).setName(nameF);
list.get(j).setDescription(descriptionF);
this.serialize(list);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isFeaturePresent(Feature f){
ArrayList<Feature> myList = deserialize();
for (int j = 0; j < myList.size(); j++) {
if (myList.get(j).getName().equals(f.getName())) {
return true;
}
}
return false;
}
public void insertFeature(Feature f) {
ArrayList<Feature> myList = new ArrayList<>();
try {
if (!isFeaturePresent(f)) {
myList = deserialize();
myList.add(f);
this.serialize(myList);
}
}catch (Exception e){
e.printStackTrace();
}
}
public void deleteFeature(Feature f) {
ArrayList<Feature> myList = new ArrayList<>();
File file = new File(fileName);
if(!file.exists()) {
FeatureDaoFile fDFJ = new FeatureDaoFile();
fDFJ.newFeatureFile();
}
try {
if (isFeaturePresent(f)) {
myList = deserialize();
for (int j = 0; j < myList.size(); j++) {
if (myList.get(j).isEqualTo(f)) {
myList.remove(j);
if (myList.size() == 0) {
try {
PrintWriter writer = new PrintWriter(fileName);
writer.print("");
writer.close();
return;
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
this.serialize(myList);
return;
}
}
}
} catch (Exception e){
e.printStackTrace();
}
}
private void serialize(ArrayList<Feature> list) {
try {
File file = new File(fileName);
if(!file.exists()) {
FeatureDaoFile fDFJ = new FeatureDaoFile();
fDFJ.newFeatureFile();
}
FileOutputStream fileOS = new FileOutputStream(fileName);
ObjectOutputStream o = new ObjectOutputStream(fileOS);
o.writeObject(list);
o.close();
fileOS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private ArrayList<Feature> deserialize() {
ArrayList<Feature> myList = new ArrayList<>();
File file = new File(fileName);
if(!file.exists()) {
FeatureDaoFile fDFJ = new FeatureDaoFile();
fDFJ.newFeatureFile();
}
try {
FileInputStream fileOS = new FileInputStream(fileName);
ObjectInputStream in = new ObjectInputStream(fileOS);
myList = (ArrayList<Feature>) in.readObject();
} catch (EOFException e){
}catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
for (int j = 0; j < myList.size(); j++) {
}
return myList;
}
public ArrayList<Feature> getFeatures() {
ArrayList<Feature> list = new ArrayList<>();
list = deserialize();
return list;
}
public Feature getFeature(String nameF) {
Feature newFeature = null;
FeatureDaoFile fDFJ = new FeatureDaoFile();
ArrayList<Feature> myList = fDFJ.deserialize();
for (int j = 0; j < myList.size(); j++) {
if ((myList.get(j).getName()).equals(nameF)) {
newFeature = new Feature(myList.get(j).getName()
, myList.get(j).getDescription());
}
}
return newFeature;
}
}
| UTF-8 | Java | 5,222 | java | FeatureDaoFile.java | Java | [] | null | [] | package dao.feature;
import entity.Feature;
import java.io.*;
import java.util.ArrayList;
public class FeatureDaoFile implements FeatureDao{
private static final String fileName = "C:\\Projects\\delphino\\feature.ser";
public void newFeatureFile() {
String path = "C:\\Projects\\delphino\\feature.ser";
try {
File file = new File(path);
if (file.exists())
System.out.println("Il file " + path + " esiste");
else if (file.createNewFile())
System.out.println("Il file " + path + " è stato creato");
else
System.out.println("Il file " + path + " non può essere creato");
} catch (IOException e) {
e.printStackTrace();
}
}
public void updateFeature (Feature f) {
String nameF = f.getName();
String descriptionF = f.getDescription();
try {
if(isFeaturePresent(f)){
ArrayList<Feature> list = deserialize();
for (int j=0; j < list.size(); j++){
if(list.get(j).getName().equals(f.getName())){
list.get(j).setName(nameF);
list.get(j).setDescription(descriptionF);
this.serialize(list);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isFeaturePresent(Feature f){
ArrayList<Feature> myList = deserialize();
for (int j = 0; j < myList.size(); j++) {
if (myList.get(j).getName().equals(f.getName())) {
return true;
}
}
return false;
}
public void insertFeature(Feature f) {
ArrayList<Feature> myList = new ArrayList<>();
try {
if (!isFeaturePresent(f)) {
myList = deserialize();
myList.add(f);
this.serialize(myList);
}
}catch (Exception e){
e.printStackTrace();
}
}
public void deleteFeature(Feature f) {
ArrayList<Feature> myList = new ArrayList<>();
File file = new File(fileName);
if(!file.exists()) {
FeatureDaoFile fDFJ = new FeatureDaoFile();
fDFJ.newFeatureFile();
}
try {
if (isFeaturePresent(f)) {
myList = deserialize();
for (int j = 0; j < myList.size(); j++) {
if (myList.get(j).isEqualTo(f)) {
myList.remove(j);
if (myList.size() == 0) {
try {
PrintWriter writer = new PrintWriter(fileName);
writer.print("");
writer.close();
return;
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
this.serialize(myList);
return;
}
}
}
} catch (Exception e){
e.printStackTrace();
}
}
private void serialize(ArrayList<Feature> list) {
try {
File file = new File(fileName);
if(!file.exists()) {
FeatureDaoFile fDFJ = new FeatureDaoFile();
fDFJ.newFeatureFile();
}
FileOutputStream fileOS = new FileOutputStream(fileName);
ObjectOutputStream o = new ObjectOutputStream(fileOS);
o.writeObject(list);
o.close();
fileOS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private ArrayList<Feature> deserialize() {
ArrayList<Feature> myList = new ArrayList<>();
File file = new File(fileName);
if(!file.exists()) {
FeatureDaoFile fDFJ = new FeatureDaoFile();
fDFJ.newFeatureFile();
}
try {
FileInputStream fileOS = new FileInputStream(fileName);
ObjectInputStream in = new ObjectInputStream(fileOS);
myList = (ArrayList<Feature>) in.readObject();
} catch (EOFException e){
}catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
for (int j = 0; j < myList.size(); j++) {
}
return myList;
}
public ArrayList<Feature> getFeatures() {
ArrayList<Feature> list = new ArrayList<>();
list = deserialize();
return list;
}
public Feature getFeature(String nameF) {
Feature newFeature = null;
FeatureDaoFile fDFJ = new FeatureDaoFile();
ArrayList<Feature> myList = fDFJ.deserialize();
for (int j = 0; j < myList.size(); j++) {
if ((myList.get(j).getName()).equals(nameF)) {
newFeature = new Feature(myList.get(j).getName()
, myList.get(j).getDescription());
}
}
return newFeature;
}
}
| 5,222 | 0.477778 | 0.476628 | 182 | 27.681318 | 22.38518 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 9 |
ab3c8cb6858a07238e3f36f6fa7d42b88f26d0b7 | 5,729,486,394,943 | 21b6dd2b6e78b54c1dbb2a5a5df4d1b24d0920c7 | /data/src/main/java/ru/yarobot/util/RetrofitApiFactory.java | b669ff47ef095d2c916d47512a8e3d9385c5b31a | [] | no_license | MihailovJava/ya-robot-android | https://github.com/MihailovJava/ya-robot-android | 2a4db9f724a555f98ee511f534a636dfcd984320 | d2884e8b54074ce3ca54a2b1f7f8d1b06555e3df | refs/heads/master | 2021-01-21T14:23:18.192000 | 2016-06-12T18:47:23 | 2016-06-12T18:47:23 | 58,867,513 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.yarobot.util;
import retrofit2.Retrofit;
public class RetrofitApiFactory {
Retrofit retrofit;
/**
* Constructor
* @param retrofit retrofit instance
*/
public RetrofitApiFactory(Retrofit retrofit) {
this.retrofit = retrofit;
}
/**
* Method for build retrofit REST API service
* @param serviceClass specific REST API class
* @param <S> REST API interface
* @return Retrofit service
* @see Retrofit
*/
public <S> S build(Class<S> serviceClass) {
return retrofit.create(serviceClass);
}
} | UTF-8 | Java | 592 | java | RetrofitApiFactory.java | Java | [] | null | [] | package ru.yarobot.util;
import retrofit2.Retrofit;
public class RetrofitApiFactory {
Retrofit retrofit;
/**
* Constructor
* @param retrofit retrofit instance
*/
public RetrofitApiFactory(Retrofit retrofit) {
this.retrofit = retrofit;
}
/**
* Method for build retrofit REST API service
* @param serviceClass specific REST API class
* @param <S> REST API interface
* @return Retrofit service
* @see Retrofit
*/
public <S> S build(Class<S> serviceClass) {
return retrofit.create(serviceClass);
}
} | 592 | 0.638514 | 0.636824 | 30 | 18.766666 | 18.0844 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 9 |
43e87504a61d5a9325e7c200313853bc55618766 | 20,727,512,186,063 | 12a7297a916109587db5ce40601df66e74aea7b3 | /hw12/Multiply.java | f09a7cbb70c530693d41c5ff5c49dcce070152ba | [] | no_license | jhc417/CSE2 | https://github.com/jhc417/CSE2 | 30e79a0585d9cecec7a704caeda33778700fcf75 | b5bc9e11b1c653e0ed9414bdc387cbfc375326b0 | refs/heads/master | 2021-01-01T06:00:18.639000 | 2015-05-01T02:38:08 | 2015-05-01T02:38:08 | 29,740,495 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Jack Curran
// 4/20/2015
// hw12
//CSE002
//import scanner
import java.util.Scanner;
//declare class
public class Multiply{
//main method
public static void main (String[]args){
//declare scanner
Scanner myScanner;
//construct scanner
myScanner = new Scanner (System.in);
//while loop to make sure dimensions are compatible
int counter=0;
int width=0;
int height=0;
int width2=0;
int height2=0;
while(counter<1){
//ask user for width and height of each matrix
System.out.println("Enter the width of the first matrix: ");
width=myScanner.nextInt();
System.out.println("Enter the height of the first matrix: ");
height=myScanner.nextInt();
System.out.println("Enter the width of the second matrix: ");
width2=myScanner.nextInt();
System.out.println("Enter the height of the second matrix: ");
height2=myScanner.nextInt();
System.out.println("xxxxxxxxx");
//check to see if matrices are compatible for multiplication
if (width!=height2){
System.out.println("The dimensions you entered are not compatible"+
" for multiplication. Enter again:");
}
else if (width<1||height<1||width2<1||height2<1){
System.out.println("The dimensions you entered were not all "+
"positive. Enter again:");
}
else{
counter++;
}
}
//create both arrays
int [][] myArray = new int [width][height];
int [][] myArray2 = new int [width2][height2];
//call randomMatrix method to assign random
//numbers to each section of first matrix/array
myArray = randomMatrix(width, height);
//call method to print out first matrix/array
System.out.println("First Matrix:");
printMatrix(myArray);
//call randomMatrix method to assign random
//numbers to each section of second matrix/array
myArray2=randomMatrix(width2, height2);
//call method to print out second matrix/array
System.out.println("Second Matrix:");
printMatrix(myArray2);
// call multiply method to multiply the two arrays/matrices
int [][] myArray4 = multiply(myArray, myArray2, height, width);
System.out.println("Final Matrix:");
printMatrix(myArray4);
}
// random matrix method
public static int [] [] randomMatrix(int n1, int n2){
int [][] myArray3= new int [n1][n2];
for (int row=0; row<myArray3.length ;row++){
for (int column=0; column<myArray3[row].length; column++){
myArray3[row][column] = (int) ((Math.random()*20)-10);
}
}
return myArray3;
}
public static void printMatrix(int [][] myArray3){
for (int a=0; a<myArray3.length; a++){
for (int b=0; b<myArray3[a].length; b++){
System.out.print(" "+ myArray3[a][b]);
}
System.out.println("");
}
System.out.println("xxxxxxxxx");
}
public static int [][] multiply(int [][] myArray, int [][] myArray2, int height, int width2){
int [][] myArray4 = new int [height][width2];
for (int z=0; z<myArray4.length; z++){
for(int y=0; y<myArray4[0].length; y++){
for (int v=0; v<myArray4[0].length; v++){
myArray4[z][y]+= (myArray[z][v]*myArray2[v][y]);
}
}
}
return myArray4;
}
}
| UTF-8 | Java | 3,786 | java | Multiply.java | Java | [
{
"context": "// Jack Curran\n// 4/20/2015\n// hw12\n//CSE002\n\n//import scanner\ni",
"end": 14,
"score": 0.9998686909675598,
"start": 3,
"tag": "NAME",
"value": "Jack Curran"
}
] | null | [] | // <NAME>
// 4/20/2015
// hw12
//CSE002
//import scanner
import java.util.Scanner;
//declare class
public class Multiply{
//main method
public static void main (String[]args){
//declare scanner
Scanner myScanner;
//construct scanner
myScanner = new Scanner (System.in);
//while loop to make sure dimensions are compatible
int counter=0;
int width=0;
int height=0;
int width2=0;
int height2=0;
while(counter<1){
//ask user for width and height of each matrix
System.out.println("Enter the width of the first matrix: ");
width=myScanner.nextInt();
System.out.println("Enter the height of the first matrix: ");
height=myScanner.nextInt();
System.out.println("Enter the width of the second matrix: ");
width2=myScanner.nextInt();
System.out.println("Enter the height of the second matrix: ");
height2=myScanner.nextInt();
System.out.println("xxxxxxxxx");
//check to see if matrices are compatible for multiplication
if (width!=height2){
System.out.println("The dimensions you entered are not compatible"+
" for multiplication. Enter again:");
}
else if (width<1||height<1||width2<1||height2<1){
System.out.println("The dimensions you entered were not all "+
"positive. Enter again:");
}
else{
counter++;
}
}
//create both arrays
int [][] myArray = new int [width][height];
int [][] myArray2 = new int [width2][height2];
//call randomMatrix method to assign random
//numbers to each section of first matrix/array
myArray = randomMatrix(width, height);
//call method to print out first matrix/array
System.out.println("First Matrix:");
printMatrix(myArray);
//call randomMatrix method to assign random
//numbers to each section of second matrix/array
myArray2=randomMatrix(width2, height2);
//call method to print out second matrix/array
System.out.println("Second Matrix:");
printMatrix(myArray2);
// call multiply method to multiply the two arrays/matrices
int [][] myArray4 = multiply(myArray, myArray2, height, width);
System.out.println("Final Matrix:");
printMatrix(myArray4);
}
// random matrix method
public static int [] [] randomMatrix(int n1, int n2){
int [][] myArray3= new int [n1][n2];
for (int row=0; row<myArray3.length ;row++){
for (int column=0; column<myArray3[row].length; column++){
myArray3[row][column] = (int) ((Math.random()*20)-10);
}
}
return myArray3;
}
public static void printMatrix(int [][] myArray3){
for (int a=0; a<myArray3.length; a++){
for (int b=0; b<myArray3[a].length; b++){
System.out.print(" "+ myArray3[a][b]);
}
System.out.println("");
}
System.out.println("xxxxxxxxx");
}
public static int [][] multiply(int [][] myArray, int [][] myArray2, int height, int width2){
int [][] myArray4 = new int [height][width2];
for (int z=0; z<myArray4.length; z++){
for(int y=0; y<myArray4[0].length; y++){
for (int v=0; v<myArray4[0].length; v++){
myArray4[z][y]+= (myArray[z][v]*myArray2[v][y]);
}
}
}
return myArray4;
}
}
| 3,781 | 0.540676 | 0.520866 | 105 | 34.819046 | 23.096395 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657143 | false | false | 9 |
a05bae84262c24457e1ecb997a6add834c35f68f | 31,988,916,442,407 | b5bfcb30e612f78d74006ef7ef2b6c103bbe9cf1 | /src/osmedile/intellij/stringmanip/filter/GrepAction.java | 53f2e90ebbb99e6efa362df50df69ee45d65bc69 | [
"Apache-2.0"
] | permissive | barseghyanartur/StringManipulation | https://github.com/barseghyanartur/StringManipulation | fabe9798c7b00de0fe373aef3f8e8b2b8ee5b351 | 3228bcbb33aaeab851d056d7d9d32aa7fffac9f5 | refs/heads/master | 2020-04-03T20:41:03.153000 | 2018-10-31T23:50:41 | 2018-10-31T23:50:41 | 155,553,904 | 0 | 0 | null | true | 2018-10-31T12:29:19 | 2018-10-31T12:29:19 | 2018-10-31T12:29:17 | 2018-10-10T20:34:59 | 403 | 0 | 0 | 0 | null | false | null | package osmedile.intellij.stringmanip.filter;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import osmedile.intellij.stringmanip.MyEditorAction;
import osmedile.intellij.stringmanip.MyEditorWriteActionHandler;
import osmedile.intellij.stringmanip.utils.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author Olivier Smedile
* @version $Id: GrepAction.java 60 2008-04-18 06:51:03Z osmedile $
*/
public class GrepAction extends MyEditorAction {
public GrepAction() {
this(new GrepFilter() {
@Override
public boolean execute(String text, String grepos) {
return text.contains(grepos);
}
});
}
interface GrepFilter {
boolean execute(String text, String grepos);
}
public GrepAction(final GrepFilter shouldAdd) {
super(null);
setupHandler(new MyEditorWriteActionHandler<String>(getActionClass()) {
@NotNull
@Override
protected Pair<Boolean, String> beforeWriteAction(Editor editor, DataContext dataContext) {
final SelectionModel selectionModel = editor.getSelectionModel();
if (selectionModel.hasSelection()) {
String grepos = Messages.showInputDialog(editor.getProject(), "Grep text", "Grep", null);
if (!StringUtil.isEmptyOrSpaces(grepos)) {
return continueExecution(grepos);
}
} else {
Messages.showInfoMessage(editor.getProject(), "Please select text, before using grep", "Grep");
}
return stopExecution();
}
@Override
protected void executeWriteAction(Editor editor, @Nullable Caret caret, DataContext dataContext, String grepos) {
// Column mode not supported
if (editor.isColumnMode()) {
return;
}
final SelectionModel selectionModel = editor.getSelectionModel();
if (selectionModel.hasSelection()) {
if (StringUtil.isEmptyOrSpaces(grepos)) {
return;
}
final String selectedText = selectionModel.getSelectedText();
String[] textParts = selectedText.split("\n");
Collection<String> result = new ArrayList<String>();
for (String textPart : textParts) {
if (shouldAdd.execute(textPart, grepos)) {
result.add(textPart);
}
}
String[] res = result.toArray(new String[result.size()]);
final String s = StringUtils.join(res, '\n');
editor.getDocument().replaceString(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(), s);
}
}
});
}
} | UTF-8 | Java | 2,754 | java | GrepAction.java | Java | [
{
"context": "List;\nimport java.util.Collection;\n\n/**\n * @author Olivier Smedile\n * @version $Id: GrepAction.java 60 2008-04-18 06",
"end": 715,
"score": 0.9998795390129089,
"start": 700,
"tag": "NAME",
"value": "Olivier Smedile"
}
] | null | [] | package osmedile.intellij.stringmanip.filter;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import osmedile.intellij.stringmanip.MyEditorAction;
import osmedile.intellij.stringmanip.MyEditorWriteActionHandler;
import osmedile.intellij.stringmanip.utils.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author <NAME>
* @version $Id: GrepAction.java 60 2008-04-18 06:51:03Z osmedile $
*/
public class GrepAction extends MyEditorAction {
public GrepAction() {
this(new GrepFilter() {
@Override
public boolean execute(String text, String grepos) {
return text.contains(grepos);
}
});
}
interface GrepFilter {
boolean execute(String text, String grepos);
}
public GrepAction(final GrepFilter shouldAdd) {
super(null);
setupHandler(new MyEditorWriteActionHandler<String>(getActionClass()) {
@NotNull
@Override
protected Pair<Boolean, String> beforeWriteAction(Editor editor, DataContext dataContext) {
final SelectionModel selectionModel = editor.getSelectionModel();
if (selectionModel.hasSelection()) {
String grepos = Messages.showInputDialog(editor.getProject(), "Grep text", "Grep", null);
if (!StringUtil.isEmptyOrSpaces(grepos)) {
return continueExecution(grepos);
}
} else {
Messages.showInfoMessage(editor.getProject(), "Please select text, before using grep", "Grep");
}
return stopExecution();
}
@Override
protected void executeWriteAction(Editor editor, @Nullable Caret caret, DataContext dataContext, String grepos) {
// Column mode not supported
if (editor.isColumnMode()) {
return;
}
final SelectionModel selectionModel = editor.getSelectionModel();
if (selectionModel.hasSelection()) {
if (StringUtil.isEmptyOrSpaces(grepos)) {
return;
}
final String selectedText = selectionModel.getSelectedText();
String[] textParts = selectedText.split("\n");
Collection<String> result = new ArrayList<String>();
for (String textPart : textParts) {
if (shouldAdd.execute(textPart, grepos)) {
result.add(textPart);
}
}
String[] res = result.toArray(new String[result.size()]);
final String s = StringUtils.join(res, '\n');
editor.getDocument().replaceString(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(), s);
}
}
});
}
} | 2,745 | 0.728395 | 0.722585 | 89 | 29.955055 | 28.475067 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.853933 | false | false | 9 |
3fa76eaf9dfe97166c64f9f48f537aa535c259b9 | 4,801,773,466,540 | 077415036a3876608f5b060adeec882f85f19682 | /src/main/java/org/yoda/db/data/QueryTable.java | 6960025ffb5c5a513f87a1e5f998d2cf93c2d8d9 | [] | no_license | brucechin/Yoda | https://github.com/brucechin/Yoda | aef97cd27098fe0dc82f99d7942194129a362cd6 | 9ef4727611623d099ded3e96e9eb36dd5360d81c | refs/heads/master | 2020-12-03T10:03:33.300000 | 2020-01-31T05:14:38 | 2020-01-31T05:14:38 | 231,276,970 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.yoda.db.data;
import org.apache.commons.lang3.StringUtils;
import org.yoda.plan.slice.SliceKeyDefinition;
import org.yoda.type.SecureRelDataTypeField;
import org.yoda.type.SecureRelRecordType;
import org.yoda.util.Utilities;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
public class QueryTable implements Serializable {
int tupleSize = 0;
int tupleCount = 0;
private List<Tuple> tuples = null; // null until explicitly decrypted if init'd to PortableSecArray
transient private SecureRelRecordType schema;
public QueryTable(List<Tuple> tuples) throws Exception {
this.tuples = tuples;
if (tuples != null && !tuples.isEmpty()) {
schema = tuples.get(0).schema;
tupleCount = tuples.size();
tupleSize = schema.size();
}
}
public QueryTable(boolean[] bits, SecureRelRecordType s) throws Exception {
schema = s;
tupleSize = schema.size();
tupleCount = bits.length / tupleSize;
assert (bits.length == (tupleCount * tupleSize));
tuples = new ArrayList<Tuple>();
for (int i = 0; i < tupleCount; ++i) {
boolean[] tupleBits = Arrays.copyOfRange(bits, i * tupleSize, (i + 1) * tupleSize);
Tuple t = new Tuple(tupleBits, schema);
tuples.add(t);
}
}
public QueryTable(SecureRelRecordType outSchema) {
schema = outSchema;
tupleSize = schema.size();
tupleCount = 0;
tuples = new ArrayList<Tuple>();
}
public static boolean[] toBinary(List<Tuple> tuples) throws Exception {
if (tuples == null || tuples.isEmpty())
return null;
int tCount = tuples.size();
int tSize = tuples.get(0).schema.size();
boolean[] tableBits = new boolean[tCount * tSize];
int tIdx = 0;
for (Tuple t : tuples) {
List<Boolean> bitArray = t.serializeToBinary();
if (bitArray.size() != tSize) {
throw new Exception("Tuple size mismatched! (probably owing to varchars not matching specified length)");
}
for (Boolean b : bitArray) {
tableBits[tIdx] = b;
++tIdx;
}
}
return tableBits;
}
public void addTuples(QueryTable src) {
if (src == null)
return;
for (Tuple t : src.tuples) {
tuples.add(t);
}
}
// compare outputs by sorting them first
public void sort() {
Collections.sort(tuples);
}
public String printBitArray(boolean[] bits) {
StringBuffer buf = new StringBuffer();
for (boolean b : bits) {
char o = b == true ? '1' : '0';
buf.append(o);
}
return buf.toString();
}
public SecureRelRecordType getSchema() {
return schema;
}
public void setSchema(SecureRelRecordType s) {
schema = s;
}
// for use in testing
public void truncateData(int limit) {
if (tuples == null)
return;
while (tuples.size() > limit) {
tuples.remove(tuples.size() - 1);
}
}
public List<Tuple> tuples() {
return tuples;
}
public void toBinaryFile(String dstFile) throws Exception {
String tuplesStr = this.toBinaryString();
Utilities.writeFile(dstFile, tuplesStr);
}
public String toBinaryString() throws Exception {
String tupleStr = "";
for (Tuple t : tuples) {
tupleStr += t.toBinaryString();
}
return tupleStr;
}
public int tupleSize() throws IOException {
if (schema != null)
return schema.size();
if (tuples == null || tuples.isEmpty()) {
return 0;
}
return tuples.get(0).size();
}
public boolean[] toBinary() throws Exception {
if (tuples == null || tuples.isEmpty())
return null;
return toBinary(tuples);
}
public int tupleCount() {
if (tuples == null) {
return 0;
}
return tuples.size();
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof QueryTable) {
QueryTable qt = (QueryTable) o;
if (qt.tuples.size() != tuples.size()) {
return false;
}
if (qt.tuples == this.tuples) {
return true;
}
if (qt.tuples.equals(this.tuples)) {
return true;
}
}
return false;
}
public Tuple getTuple(int i) {
return tuples.get(i);
}
public String toString() {
String ret = new String();
List<String> attrNames = new ArrayList<String>();
if (schema == null || schema.getAttributes().isEmpty()) {
return null;
}
for (SecureRelDataTypeField r : schema.getAttributes()) {
attrNames.add(r.getName());
}
ret = "(" + StringUtils.join(attrNames.toArray(), ", ") + ")\n";
if (tuples != null)
for (Tuple t : tuples) {
ret += t.toString() + "\n";
}
return ret;
}
Tuple extractSliceValue(Tuple src, List<Integer> sliceIdxs) {
Tuple ret = new Tuple();
for (int i : sliceIdxs) {
ret.addField(src.getField(i));
}
return ret;
}
public Map<Tuple, List<Tuple>> asSlices(SliceKeyDefinition key) throws Exception {
// for each distinct value in slice key, list tuples associated with it
Map<Tuple, List<Tuple>> slices = new LinkedHashMap<Tuple, List<Tuple>>();
List<Integer> sliceIdxs = new ArrayList<Integer>();
// what field(s) are associated with a slice?
for (SecureRelDataTypeField slice : key.getAttributes()) {
int i = 0;
for (SecureRelDataTypeField r : schema.getAttributes()) {
if (slice != null && r != null && slice.getName().equals(r.getName()) && slice.getIndex() == r.getIndex()) {
sliceIdxs.add(i);
break;
}
++i;
}
}
if (sliceIdxs.isEmpty())
throw new Exception("No slices matched with source data!");
for (Tuple t : tuples) {
Tuple value = extractSliceValue(t, sliceIdxs);
if (slices.containsKey(value)) {
slices.get(value).add(t);
} else {
List<Tuple> tmp = new ArrayList<Tuple>();
tmp.add(t);
if (slices.containsKey(t))
throw new Exception("Input not sorted by slice key!"); // no repeat keys
slices.put(value, tmp);
}
}
return slices;
}
}
| UTF-8 | Java | 6,989 | java | QueryTable.java | Java | [] | null | [] | package org.yoda.db.data;
import org.apache.commons.lang3.StringUtils;
import org.yoda.plan.slice.SliceKeyDefinition;
import org.yoda.type.SecureRelDataTypeField;
import org.yoda.type.SecureRelRecordType;
import org.yoda.util.Utilities;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
public class QueryTable implements Serializable {
int tupleSize = 0;
int tupleCount = 0;
private List<Tuple> tuples = null; // null until explicitly decrypted if init'd to PortableSecArray
transient private SecureRelRecordType schema;
public QueryTable(List<Tuple> tuples) throws Exception {
this.tuples = tuples;
if (tuples != null && !tuples.isEmpty()) {
schema = tuples.get(0).schema;
tupleCount = tuples.size();
tupleSize = schema.size();
}
}
public QueryTable(boolean[] bits, SecureRelRecordType s) throws Exception {
schema = s;
tupleSize = schema.size();
tupleCount = bits.length / tupleSize;
assert (bits.length == (tupleCount * tupleSize));
tuples = new ArrayList<Tuple>();
for (int i = 0; i < tupleCount; ++i) {
boolean[] tupleBits = Arrays.copyOfRange(bits, i * tupleSize, (i + 1) * tupleSize);
Tuple t = new Tuple(tupleBits, schema);
tuples.add(t);
}
}
public QueryTable(SecureRelRecordType outSchema) {
schema = outSchema;
tupleSize = schema.size();
tupleCount = 0;
tuples = new ArrayList<Tuple>();
}
public static boolean[] toBinary(List<Tuple> tuples) throws Exception {
if (tuples == null || tuples.isEmpty())
return null;
int tCount = tuples.size();
int tSize = tuples.get(0).schema.size();
boolean[] tableBits = new boolean[tCount * tSize];
int tIdx = 0;
for (Tuple t : tuples) {
List<Boolean> bitArray = t.serializeToBinary();
if (bitArray.size() != tSize) {
throw new Exception("Tuple size mismatched! (probably owing to varchars not matching specified length)");
}
for (Boolean b : bitArray) {
tableBits[tIdx] = b;
++tIdx;
}
}
return tableBits;
}
public void addTuples(QueryTable src) {
if (src == null)
return;
for (Tuple t : src.tuples) {
tuples.add(t);
}
}
// compare outputs by sorting them first
public void sort() {
Collections.sort(tuples);
}
public String printBitArray(boolean[] bits) {
StringBuffer buf = new StringBuffer();
for (boolean b : bits) {
char o = b == true ? '1' : '0';
buf.append(o);
}
return buf.toString();
}
public SecureRelRecordType getSchema() {
return schema;
}
public void setSchema(SecureRelRecordType s) {
schema = s;
}
// for use in testing
public void truncateData(int limit) {
if (tuples == null)
return;
while (tuples.size() > limit) {
tuples.remove(tuples.size() - 1);
}
}
public List<Tuple> tuples() {
return tuples;
}
public void toBinaryFile(String dstFile) throws Exception {
String tuplesStr = this.toBinaryString();
Utilities.writeFile(dstFile, tuplesStr);
}
public String toBinaryString() throws Exception {
String tupleStr = "";
for (Tuple t : tuples) {
tupleStr += t.toBinaryString();
}
return tupleStr;
}
public int tupleSize() throws IOException {
if (schema != null)
return schema.size();
if (tuples == null || tuples.isEmpty()) {
return 0;
}
return tuples.get(0).size();
}
public boolean[] toBinary() throws Exception {
if (tuples == null || tuples.isEmpty())
return null;
return toBinary(tuples);
}
public int tupleCount() {
if (tuples == null) {
return 0;
}
return tuples.size();
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof QueryTable) {
QueryTable qt = (QueryTable) o;
if (qt.tuples.size() != tuples.size()) {
return false;
}
if (qt.tuples == this.tuples) {
return true;
}
if (qt.tuples.equals(this.tuples)) {
return true;
}
}
return false;
}
public Tuple getTuple(int i) {
return tuples.get(i);
}
public String toString() {
String ret = new String();
List<String> attrNames = new ArrayList<String>();
if (schema == null || schema.getAttributes().isEmpty()) {
return null;
}
for (SecureRelDataTypeField r : schema.getAttributes()) {
attrNames.add(r.getName());
}
ret = "(" + StringUtils.join(attrNames.toArray(), ", ") + ")\n";
if (tuples != null)
for (Tuple t : tuples) {
ret += t.toString() + "\n";
}
return ret;
}
Tuple extractSliceValue(Tuple src, List<Integer> sliceIdxs) {
Tuple ret = new Tuple();
for (int i : sliceIdxs) {
ret.addField(src.getField(i));
}
return ret;
}
public Map<Tuple, List<Tuple>> asSlices(SliceKeyDefinition key) throws Exception {
// for each distinct value in slice key, list tuples associated with it
Map<Tuple, List<Tuple>> slices = new LinkedHashMap<Tuple, List<Tuple>>();
List<Integer> sliceIdxs = new ArrayList<Integer>();
// what field(s) are associated with a slice?
for (SecureRelDataTypeField slice : key.getAttributes()) {
int i = 0;
for (SecureRelDataTypeField r : schema.getAttributes()) {
if (slice != null && r != null && slice.getName().equals(r.getName()) && slice.getIndex() == r.getIndex()) {
sliceIdxs.add(i);
break;
}
++i;
}
}
if (sliceIdxs.isEmpty())
throw new Exception("No slices matched with source data!");
for (Tuple t : tuples) {
Tuple value = extractSliceValue(t, sliceIdxs);
if (slices.containsKey(value)) {
slices.get(value).add(t);
} else {
List<Tuple> tmp = new ArrayList<Tuple>();
tmp.add(t);
if (slices.containsKey(t))
throw new Exception("Input not sorted by slice key!"); // no repeat keys
slices.put(value, tmp);
}
}
return slices;
}
}
| 6,989 | 0.533982 | 0.531693 | 284 | 23.609156 | 23.846605 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.415493 | false | false | 9 |
d9d0e06e4a1af48f9665ec1fb3ed9aae48b24786 | 23,338,852,313,888 | 1d15736922eae7a30a6bf117ae005d351abb0aad | /DungeonCrawler/src/dungeoncrawler/game/object/Bonus.java | fa19ed5caa11764a8af6f4449d5bd9b949fe07df | [] | no_license | weyzohorth/DungeonCrawler | https://github.com/weyzohorth/DungeonCrawler | 884cfa125dbcd396b5019a2c059d982cf26bb98c | cf8152791b16d0e2f51c498b9010fd4f46665f3d | refs/heads/master | 2021-01-01T20:06:26.387000 | 2017-10-15T23:53:08 | 2017-10-15T23:53:08 | 6,539,738 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dungeoncrawler.game.object;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import dungeoncrawler.Data;
import dungeoncrawler.SoundManager;
import dungeoncrawler.game.Map;
import dungeoncrawler.game.character.Player;
import dungeoncrawler.gui.Font;
public class Bonus extends AObject
{
public enum e_bonus
{
STRENGTH(1, true), HEALTH(3, true),
ATKSPEED(0.2f, false), SPEED(0.2f, false), SIGHT(1, false), HEAL(20, true);
private float _value;
private boolean _mult;
private e_bonus(float value, boolean mult) { _value = value; _mult = mult; }
public float getValue() { return _value * (! _mult ? 1 : Data.sum.difficulty); }
}
private int _currWait = 0;
private int _waitTime = 15;
private Font _font;
private float _maxY = 30;
private float _textY = 0;
private int _offsetY = 0;
private float _incrY = 0.5f;
private int _timeDisplay = 60;
private e_bonus _type;
protected String _name;
protected float _value;
private String _message;
public Bonus(Map map, float mult) throws SlickException
{
super(map);
_offsetY = 20;
init(e_bonus.values()[(int)(Math.random() * e_bonus.values().length - 1)], mult);
}
public Bonus(Map map, e_bonus type, float mult) throws SlickException
{
super(map);
init(type, mult);
}
private void init(e_bonus type, float mult) throws SlickException
{
setFly(true);
SoundManager.play(SoundManager.bonus);
_font = new Font(Data.font_path + "jawbrko1.ttf", 20, true, false, new Color(150, 255, 150));
_type = type;
Player player = _map.getPlayer();
float value = _type.getValue() * mult;
switch(_type)
{
case ATKSPEED:
Data.sum.atkspd += value;
player.setAttackSpeed(player.getAttackSpeed() + value);
_message = Float.toString((int)(value * 100) / 100.0f);
break;
case HEAL:
player.addHealth((int)value);
_message = Integer.toString((int)value);
break;
case HEALTH:
Data.sum.health += value;
player.setHealthMax(player.getHealthMax() + (int)value);
_message = Integer.toString((int)value);
break;
case SIGHT:
Data.sum.sightdistance += value;
player.setSightDistance(player.getSightDistance() + (int)value);
_message = Integer.toString((int)value);
break;
case SPEED:
Data.sum.speed += value;
player.setSpeed(player.getSpeed() + value);
_message = Float.toString((int)(value * 100) / 100.0f);
break;
case STRENGTH:
Data.sum.strength += value;
_message = Integer.toString((int)value);
player.setStrength(player.getStrength() + (int)value);
break;
}
}
@Override
public void update(GameContainer gc, int delta)
{
if (_maxY <= _textY)
{
if (0 < _timeDisplay)
_timeDisplay--;
else
delete();
}
else
{
_textY += _incrY;
if (_waitTime <= ++_currWait)
_currWait = 0;
}
}
@Override
public void drawAt(float x, float y)
{
float tw = 32;
float th = 32;
_font.drawText(_type.name() + " " + _message,
(int)(x * tw) - 5, (int)(y * th - 15 - _textY - _offsetY));
}
}
| UTF-8 | Java | 3,063 | java | Bonus.java | Java | [] | null | [] | package dungeoncrawler.game.object;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import dungeoncrawler.Data;
import dungeoncrawler.SoundManager;
import dungeoncrawler.game.Map;
import dungeoncrawler.game.character.Player;
import dungeoncrawler.gui.Font;
public class Bonus extends AObject
{
public enum e_bonus
{
STRENGTH(1, true), HEALTH(3, true),
ATKSPEED(0.2f, false), SPEED(0.2f, false), SIGHT(1, false), HEAL(20, true);
private float _value;
private boolean _mult;
private e_bonus(float value, boolean mult) { _value = value; _mult = mult; }
public float getValue() { return _value * (! _mult ? 1 : Data.sum.difficulty); }
}
private int _currWait = 0;
private int _waitTime = 15;
private Font _font;
private float _maxY = 30;
private float _textY = 0;
private int _offsetY = 0;
private float _incrY = 0.5f;
private int _timeDisplay = 60;
private e_bonus _type;
protected String _name;
protected float _value;
private String _message;
public Bonus(Map map, float mult) throws SlickException
{
super(map);
_offsetY = 20;
init(e_bonus.values()[(int)(Math.random() * e_bonus.values().length - 1)], mult);
}
public Bonus(Map map, e_bonus type, float mult) throws SlickException
{
super(map);
init(type, mult);
}
private void init(e_bonus type, float mult) throws SlickException
{
setFly(true);
SoundManager.play(SoundManager.bonus);
_font = new Font(Data.font_path + "jawbrko1.ttf", 20, true, false, new Color(150, 255, 150));
_type = type;
Player player = _map.getPlayer();
float value = _type.getValue() * mult;
switch(_type)
{
case ATKSPEED:
Data.sum.atkspd += value;
player.setAttackSpeed(player.getAttackSpeed() + value);
_message = Float.toString((int)(value * 100) / 100.0f);
break;
case HEAL:
player.addHealth((int)value);
_message = Integer.toString((int)value);
break;
case HEALTH:
Data.sum.health += value;
player.setHealthMax(player.getHealthMax() + (int)value);
_message = Integer.toString((int)value);
break;
case SIGHT:
Data.sum.sightdistance += value;
player.setSightDistance(player.getSightDistance() + (int)value);
_message = Integer.toString((int)value);
break;
case SPEED:
Data.sum.speed += value;
player.setSpeed(player.getSpeed() + value);
_message = Float.toString((int)(value * 100) / 100.0f);
break;
case STRENGTH:
Data.sum.strength += value;
_message = Integer.toString((int)value);
player.setStrength(player.getStrength() + (int)value);
break;
}
}
@Override
public void update(GameContainer gc, int delta)
{
if (_maxY <= _textY)
{
if (0 < _timeDisplay)
_timeDisplay--;
else
delete();
}
else
{
_textY += _incrY;
if (_waitTime <= ++_currWait)
_currWait = 0;
}
}
@Override
public void drawAt(float x, float y)
{
float tw = 32;
float th = 32;
_font.drawText(_type.name() + " " + _message,
(int)(x * tw) - 5, (int)(y * th - 15 - _textY - _offsetY));
}
}
| 3,063 | 0.665687 | 0.646425 | 121 | 24.314049 | 21.697786 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.512397 | false | false | 9 |
09297099742ca0bcf0fd60d899d6c0a011b7d17a | 32,444,182,973,391 | d532fada853476b3b1844ad7deb34d17dec99a26 | /app/src/main/java/com/slider/alex/textslider/GameActivity.java | 757f88c5b1c1dd4c8e90b8e4cb0918cfe420c9c5 | [] | no_license | alex-alk/Textslider | https://github.com/alex-alk/Textslider | 161a77b2c0c8d29ff6411fb756ac99f1f21ce860 | 52c3f3e2447c8b1683d44e01f90285964984ec9e | refs/heads/master | 2022-08-18T23:21:16.911000 | 2022-07-26T11:14:15 | 2022-07-26T11:14:15 | 145,305,721 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.slider.alex.textslider;
import android.app.ActionBar;
import android.graphics.Color;
import android.graphics.Point;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.Display;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import static android.widget.TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM;
public class GameActivity extends AppCompatActivity {
static String msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
TextView tv = findViewById(R.id.textView5);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int y = size.y-100;
int x =size.x;
float density = getResources().getDisplayMetrics().scaledDensity;
String spSizeStr = MainActivity.spSizeStr;
float textSize=0;
switch(spSizeStr){
case "100%":
textSize = y/density;
break;
case "50%":
textSize = (y+50)/density/2;
break;
case "10%":
textSize = (y+90)/density/10;
break;
case "25%":
textSize = (y+75)/density/4;
break;
case "75%":
textSize = (y+25)/density/1.3f;
}
tv.setTextSize(textSize);
ConstraintLayout frame = findViewById(R.id.frame);
ViewGroup.LayoutParams a= frame.getLayoutParams();
String bcolorstr = MainActivity.spTextBackStr;
String colorstr = MainActivity.spTextColorStr;
int bcolor=Integer.parseInt(bcolorstr);
int color=Integer.parseInt(colorstr);
frame.setBackgroundColor(bcolor);
tv.setTextColor(color);
tv.setText(MainActivity.text);
msg = MainActivity.text;
tv.measure(0,0);
if(tv.getMeasuredWidth()>x)
a.width = tv.getMeasuredWidth();
else
a.width = x;
frame.setLayoutParams(a);
int speed = Integer.parseInt(MainActivity.spSpeedStr);
int width = tv.getMeasuredWidth();
float duration = width*15/(density*speed);
if(speed!=0) {
TranslateAnimation animation = new TranslateAnimation(x, -width, 0, 0);
animation.setDuration((int) duration);
animation.setInterpolator(new LinearInterpolator());
animation.setFillAfter(true);
animation.setRepeatMode(Animation.RESTART);
animation.setRepeatCount(Animation.INFINITE);
tv.startAnimation(animation);
}
}
}
| UTF-8 | Java | 3,147 | java | GameActivity.java | Java | [] | null | [] | package com.slider.alex.textslider;
import android.app.ActionBar;
import android.graphics.Color;
import android.graphics.Point;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.Display;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import static android.widget.TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM;
public class GameActivity extends AppCompatActivity {
static String msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
TextView tv = findViewById(R.id.textView5);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int y = size.y-100;
int x =size.x;
float density = getResources().getDisplayMetrics().scaledDensity;
String spSizeStr = MainActivity.spSizeStr;
float textSize=0;
switch(spSizeStr){
case "100%":
textSize = y/density;
break;
case "50%":
textSize = (y+50)/density/2;
break;
case "10%":
textSize = (y+90)/density/10;
break;
case "25%":
textSize = (y+75)/density/4;
break;
case "75%":
textSize = (y+25)/density/1.3f;
}
tv.setTextSize(textSize);
ConstraintLayout frame = findViewById(R.id.frame);
ViewGroup.LayoutParams a= frame.getLayoutParams();
String bcolorstr = MainActivity.spTextBackStr;
String colorstr = MainActivity.spTextColorStr;
int bcolor=Integer.parseInt(bcolorstr);
int color=Integer.parseInt(colorstr);
frame.setBackgroundColor(bcolor);
tv.setTextColor(color);
tv.setText(MainActivity.text);
msg = MainActivity.text;
tv.measure(0,0);
if(tv.getMeasuredWidth()>x)
a.width = tv.getMeasuredWidth();
else
a.width = x;
frame.setLayoutParams(a);
int speed = Integer.parseInt(MainActivity.spSpeedStr);
int width = tv.getMeasuredWidth();
float duration = width*15/(density*speed);
if(speed!=0) {
TranslateAnimation animation = new TranslateAnimation(x, -width, 0, 0);
animation.setDuration((int) duration);
animation.setInterpolator(new LinearInterpolator());
animation.setFillAfter(true);
animation.setRepeatMode(Animation.RESTART);
animation.setRepeatCount(Animation.INFINITE);
tv.startAnimation(animation);
}
}
}
| 3,147 | 0.644423 | 0.632348 | 93 | 32.838711 | 19.105417 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.752688 | false | false | 9 |
d0864d45c282638b28d31880df636a119453fc2c | 21,251,498,203,359 | a5e00ecda54b25f2895c0f18fc888a071daf4a44 | /MazeProject/src/tests/CompareTimeTest.java | 14cd3cb6f24f74853d127998b1c4138195138e28 | [] | no_license | pawellski/MazeProject | https://github.com/pawellski/MazeProject | 264cb285ed8900a2eea161add04ab553eb1e420c | 4c271081e42c9f46dfb567e6c163f408de99f68b | refs/heads/master | 2020-09-13T08:04:22.276000 | 2019-12-02T21:22:53 | 2019-12-02T21:22:53 | 222,704,554 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tests;
import algorithms.BFS;
import algorithms.Tremaux;
import maze.Maze;
/**
*
* @author Paweł
*/
public class CompareTimeTest {
private BFS bfs;
private Tremaux tremaux;
private Maze maze;
private long[] bfsTime;
private long[] tremauxTime;
public CompareTimeTest() {
}
public void compareTime(int repeat, int executeOneMaze) {
bfsTime = new long[repeat];
tremauxTime = new long[repeat];
for (int i = 1; i < repeat + 1; i++) {
maze = new Maze(10 * i, 10 * i);
maze.generate();
long tmpBFS = 0;
long tmpTremaux = 0;
for (int j = 0; j < executeOneMaze; j++) {
bfs = new BFS(maze);
tremaux = new Tremaux(maze);
long startBFS = System.nanoTime();
bfs.createGraph();
bfs.searchWay();
long stopBFS = System.nanoTime();
long startTremaux = System.nanoTime();
tremaux.solveMaze();
long stopTremaux = System.nanoTime();
tmpBFS = tmpBFS + (stopBFS - startBFS);
tmpTremaux = tmpTremaux + (stopTremaux - startTremaux);
}
bfsTime[i - 1] = tmpBFS / executeOneMaze;
tremauxTime[i - 1] = tmpTremaux / executeOneMaze;
}
}
public void displayBFSTime() {
System.out.println("Time BFS:");
for (int i = 0; i < bfsTime.length; i++) {
System.out.println(bfsTime[i]);
}
}
public void displayTremauxTime() {
System.out.println("Time Tremaux:");
for (int i = 0; i < tremauxTime.length; i++) {
System.out.println(tremauxTime[i]);
}
}
}
| UTF-8 | Java | 2,018 | java | CompareTimeTest.java | Java | [
{
"context": "Tremaux;\r\nimport maze.Maze;\r\n\r\n/**\r\n *\r\n * @author Paweł\r\n */\r\npublic class CompareTimeTest {\r\n\r\n private",
"end": 306,
"score": 0.9605306386947632,
"start": 301,
"tag": "NAME",
"value": "Paweł"
}
] | 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 tests;
import algorithms.BFS;
import algorithms.Tremaux;
import maze.Maze;
/**
*
* @author Paweł
*/
public class CompareTimeTest {
private BFS bfs;
private Tremaux tremaux;
private Maze maze;
private long[] bfsTime;
private long[] tremauxTime;
public CompareTimeTest() {
}
public void compareTime(int repeat, int executeOneMaze) {
bfsTime = new long[repeat];
tremauxTime = new long[repeat];
for (int i = 1; i < repeat + 1; i++) {
maze = new Maze(10 * i, 10 * i);
maze.generate();
long tmpBFS = 0;
long tmpTremaux = 0;
for (int j = 0; j < executeOneMaze; j++) {
bfs = new BFS(maze);
tremaux = new Tremaux(maze);
long startBFS = System.nanoTime();
bfs.createGraph();
bfs.searchWay();
long stopBFS = System.nanoTime();
long startTremaux = System.nanoTime();
tremaux.solveMaze();
long stopTremaux = System.nanoTime();
tmpBFS = tmpBFS + (stopBFS - startBFS);
tmpTremaux = tmpTremaux + (stopTremaux - startTremaux);
}
bfsTime[i - 1] = tmpBFS / executeOneMaze;
tremauxTime[i - 1] = tmpTremaux / executeOneMaze;
}
}
public void displayBFSTime() {
System.out.println("Time BFS:");
for (int i = 0; i < bfsTime.length; i++) {
System.out.println(bfsTime[i]);
}
}
public void displayTremauxTime() {
System.out.println("Time Tremaux:");
for (int i = 0; i < tremauxTime.length; i++) {
System.out.println(tremauxTime[i]);
}
}
}
| 2,018 | 0.528012 | 0.521567 | 70 | 26.814285 | 21.332264 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false | 9 |
2a0406706086114c87f58cbcc4051cc2256794ad | 18,141,941,882,589 | 8fe0d0028aa064a32d93af2209a2da1782be21cd | /demo/src/main/java/com/soft/demo/repository/StudentRepository.java | 84f25e658b449a6cb206e488b07e0c5b9027a004 | [] | no_license | juancarloscoripoma/springboot | https://github.com/juancarloscoripoma/springboot | 9c7df05b051b2a34d2f4da85f42cafa9bcd0db78 | 35916f2f7f5ec3859e9b18a17364bd310a150334 | refs/heads/master | 2020-04-17T22:49:01.912000 | 2019-02-28T22:41:25 | 2019-02-28T22:41:25 | 167,009,832 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.soft.demo.repository;
import com.soft.demo.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@SuppressWarnings("unused")
@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
@Query(value = "select sum( cs.course_id*cs.student_id ) mult from student st "+
"inner join course_student cs on st.id=cs.student_id "+
"where st.id<=?1",
nativeQuery = true)
List<Object[]> findMultipleById(Long studentId);
@Query(value = "select id, firstname,age,course_id from student st "+
"inner join course_student cs on st.id=cs.student_id where st.id=?1",
nativeQuery = true)
List<Object[]> findStudentAndCourseById(Long studentId);
}
| UTF-8 | Java | 899 | java | StudentRepository.java | Java | [] | null | [] | package com.soft.demo.repository;
import com.soft.demo.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@SuppressWarnings("unused")
@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
@Query(value = "select sum( cs.course_id*cs.student_id ) mult from student st "+
"inner join course_student cs on st.id=cs.student_id "+
"where st.id<=?1",
nativeQuery = true)
List<Object[]> findMultipleById(Long studentId);
@Query(value = "select id, firstname,age,course_id from student st "+
"inner join course_student cs on st.id=cs.student_id where st.id=?1",
nativeQuery = true)
List<Object[]> findStudentAndCourseById(Long studentId);
}
| 899 | 0.713014 | 0.71079 | 24 | 36.458332 | 27.86871 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 9 |
4177edb4fe64338223675fa8c1bd76a71fd611a3 | 7,945,689,545,933 | f5de1f267b59df411d8262a6b0ecc5a2d16aa143 | /selfUpgrade/src/main/java/com/vanilla/hyx/selfUpgrade/StorageUtils.java | 1d45b266d6a1b0ce7a63b05e36db3590870eb285 | [
"Apache-2.0"
] | permissive | MichaelHyx/selfUpgrade | https://github.com/MichaelHyx/selfUpgrade | f03e29a4dd9436c80d26715b4867d5a657087f52 | 0f0af9c2072dc230a48368a20b8ebd99a62af159 | refs/heads/master | 2020-04-18T10:14:13.511000 | 2016-09-11T08:17:39 | 2016-09-11T08:17:39 | 67,918,061 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright 2011-2013 Sergey Tarasevich
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.vanilla.hyx.selfUpgrade;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static android.os.Environment.MEDIA_MOUNTED;
/**
* Provides application storage paths
*
* @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
* @since 1.0.0
*/
final class StorageUtils {
private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";
private static final String TAG = "StorageUtils";
private StorageUtils() {
}
/**
* Returns application cache directory. Cache directory will be created on SD card
* <i>("/Android/data/[app_package_name]/cache")</i> if card is mounted and app has appropriate permission. Else -
* Android defines cache directory on device's file system.
*
* @param context Application context
* @return Cache {@link File directory}
*/
public static File getCacheDirectory(Context context) {
File appCacheDir = null;
if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
appCacheDir = getExternalCacheDir(context);
}
if (appCacheDir == null) {
appCacheDir = context.getCacheDir();
}
if (appCacheDir == null) {
Log.w(TAG, "Can't define system cache directory! The app should be re-installed.");
}
return appCacheDir;
}
private static File getExternalCacheDir(Context context) {
File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
if (!appCacheDir.exists()) {
if (!appCacheDir.mkdirs()) {
Log.w(TAG, "Unable to create external cache directory");
return null;
}
try {
new File(appCacheDir, ".nomedia").createNewFile();
} catch (IOException e) {
Log.i(TAG, "Can't create \".nomedia\" file in application external cache directory");
}
}
return appCacheDir;
}
private static boolean hasExternalStoragePermission(Context context) {
int perm = context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION);
return perm == PackageManager.PERMISSION_GRANTED;
}
/**
* 保存已下载安装包信息
* @param context
* @param currentVersion 安装包版本
* @param currentURL 安装包下载地址
* @param downloadedSize 安装包已下载大小
* @param totalSize 安装包大小
*/
public static void saveDownloadInfo(Context context, int currentVersion, String currentURL, int downloadedSize, int totalSize) {
SharedPreferences sharedPreferences= context.getSharedPreferences("updateInfo", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("currentVersion", String.valueOf(currentVersion));
editor.putString("currentURL", currentURL);
editor.putString("downloadedSize", String.valueOf(downloadedSize));
editor.putString("totalSize", String.valueOf(totalSize));
editor.commit();
}
/**
*获取已下载安装包信息,只包含最新一次下载的安装包信息
* @param context
* @return
*/
public static Map<String, String> getDownloadInfo(Context context) {
Map<String, String> result = new HashMap<String, String>();
SharedPreferences sharedPreferences= context.getSharedPreferences("updateInfo", Activity.MODE_PRIVATE);
result.put("currentVersion", sharedPreferences.getString("currentVersion", "0"));
result.put("currentURL", sharedPreferences.getString("currentURL", ""));
result.put("downloadedSize", sharedPreferences.getString("downloadedSize", "0"));
result.put("totalSize", sharedPreferences.getString("totalSize", "0"));
return result;
}
}
| UTF-8 | Java | 5,039 | java | StorageUtils.java | Java | [
{
"context": "***************************\n * Copyright 2011-2013 Sergey Tarasevich\n * <p>\n * Licensed under the Apache License, Vers",
"end": 121,
"score": 0.9998893141746521,
"start": 104,
"tag": "NAME",
"value": "Sergey Tarasevich"
},
{
"context": "* Provides application storage paths\n *\n * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)\n * @since 1.0.0\n */\nf",
"end": 1235,
"score": 0.9998863339424133,
"start": 1218,
"tag": "NAME",
"value": "Sergey Tarasevich"
}
] | null | [] | /*******************************************************************************
* Copyright 2011-2013 <NAME>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.vanilla.hyx.selfUpgrade;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static android.os.Environment.MEDIA_MOUNTED;
/**
* Provides application storage paths
*
* @author <NAME> (nostra13[at]gmail[dot]com)
* @since 1.0.0
*/
final class StorageUtils {
private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";
private static final String TAG = "StorageUtils";
private StorageUtils() {
}
/**
* Returns application cache directory. Cache directory will be created on SD card
* <i>("/Android/data/[app_package_name]/cache")</i> if card is mounted and app has appropriate permission. Else -
* Android defines cache directory on device's file system.
*
* @param context Application context
* @return Cache {@link File directory}
*/
public static File getCacheDirectory(Context context) {
File appCacheDir = null;
if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
appCacheDir = getExternalCacheDir(context);
}
if (appCacheDir == null) {
appCacheDir = context.getCacheDir();
}
if (appCacheDir == null) {
Log.w(TAG, "Can't define system cache directory! The app should be re-installed.");
}
return appCacheDir;
}
private static File getExternalCacheDir(Context context) {
File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
if (!appCacheDir.exists()) {
if (!appCacheDir.mkdirs()) {
Log.w(TAG, "Unable to create external cache directory");
return null;
}
try {
new File(appCacheDir, ".nomedia").createNewFile();
} catch (IOException e) {
Log.i(TAG, "Can't create \".nomedia\" file in application external cache directory");
}
}
return appCacheDir;
}
private static boolean hasExternalStoragePermission(Context context) {
int perm = context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION);
return perm == PackageManager.PERMISSION_GRANTED;
}
/**
* 保存已下载安装包信息
* @param context
* @param currentVersion 安装包版本
* @param currentURL 安装包下载地址
* @param downloadedSize 安装包已下载大小
* @param totalSize 安装包大小
*/
public static void saveDownloadInfo(Context context, int currentVersion, String currentURL, int downloadedSize, int totalSize) {
SharedPreferences sharedPreferences= context.getSharedPreferences("updateInfo", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("currentVersion", String.valueOf(currentVersion));
editor.putString("currentURL", currentURL);
editor.putString("downloadedSize", String.valueOf(downloadedSize));
editor.putString("totalSize", String.valueOf(totalSize));
editor.commit();
}
/**
*获取已下载安装包信息,只包含最新一次下载的安装包信息
* @param context
* @return
*/
public static Map<String, String> getDownloadInfo(Context context) {
Map<String, String> result = new HashMap<String, String>();
SharedPreferences sharedPreferences= context.getSharedPreferences("updateInfo", Activity.MODE_PRIVATE);
result.put("currentVersion", sharedPreferences.getString("currentVersion", "0"));
result.put("currentURL", sharedPreferences.getString("currentURL", ""));
result.put("downloadedSize", sharedPreferences.getString("downloadedSize", "0"));
result.put("totalSize", sharedPreferences.getString("totalSize", "0"));
return result;
}
}
| 5,017 | 0.659345 | 0.655278 | 125 | 38.335999 | 33.214439 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.608 | false | false | 9 |
6cae7022b69841936ab8f702a88155eb7e0af8d2 | 4,612,794,934,739 | 4a43cb82586cbab07fe93bcc8ba6400bc91eb491 | /app/src/main/java/com/nist/washintondc/PackageList.java | 03a0a1add1d21927c5b42163fb3b62c3e061e891 | [] | no_license | SteveEmmanuel/WashingtonDC | https://github.com/SteveEmmanuel/WashingtonDC | 4c5588b58bf242c876608561ce89647329863026 | 2fe4ab70e1e20aba469b68d4f201e3acbde08845 | refs/heads/master | 2022-06-10T05:02:12.617000 | 2018-12-26T11:15:45 | 2018-12-26T11:15:45 | 177,387,639 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nist.washintondc;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link PackageList.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link PackageList#newInstance} factory method to
* create an instance of this fragment.
*/
public class PackageList extends Fragment implements View.OnClickListener{
// 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 OnFragmentInteractionListener mListener;
private Context mContext;
List<Packages> packages;
GridView gridView;
CustomGridViewAdapter adapter;
TextView packageName, packagePrice, packageInfo, packageTime;
Button selectBtn, updateBtn;
Button hatchPrice, suvPrice, sedanPrice;
LinearLayout priceCard, hatchCard, sedanCard, suvCard;
private long selectedPackage;
public PackageList() {
// 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 PackageList.
*/
// TODO: Rename and change types and number of parameters
public static PackageList newInstance(String param1, String param2) {
PackageList fragment = new PackageList();
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);
mContext = getActivity().getApplicationContext();
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
initializeData();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity())
.setActionBarTitle("Select Package");
View view = inflater.inflate(R.layout.fragment_package_list, container, false);
selectBtn = (Button) view.findViewById(R.id.select);
selectBtn.setVisibility(View.VISIBLE);
updateBtn = (Button) view.findViewById(R.id.selectEdit);
updateBtn.setVisibility(View.GONE);
selectBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CustomerDetails newFragment = new CustomerDetails();
Bundle bundle = new Bundle();
bundle.putLong("selectedPackage", selectedPackage);
bundle.putString("carType", priceCard.getTag().toString().toLowerCase());
newFragment.setArguments(bundle);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment, newFragment);
transaction.addToBackStack("packageList");
// Commit the transaction
transaction.commit();
}
});
packageName = (TextView)view.findViewById(R.id.packageName);
packagePrice = (TextView)view.findViewById(R.id.packagePrice);
packageInfo = (TextView)view.findViewById(R.id.packageInfo);
packageInfo.setMovementMethod(new ScrollingMovementMethod());
packageTime= (TextView)view.findViewById(R.id.packageTime);
hatchPrice = (Button) view.findViewById(R.id.hatchPrice);
suvPrice = (Button) view.findViewById(R.id.suvPrice);
sedanPrice = (Button) view.findViewById(R.id.sedanPrice);
hatchCard = (LinearLayout) view.findViewById(R.id.hatchCard);
sedanCard = (LinearLayout) view.findViewById(R.id.sedanCard);
suvCard = (LinearLayout) view.findViewById(R.id.suvCard);
hatchCard.setOnClickListener(this);
sedanCard.setOnClickListener(this);
suvCard.setOnClickListener(this);
priceCard = hatchCard;
hatchCard.setBackgroundColor(Color.parseColor("#b1efe9"));
gridView= view.findViewById(R.id.gridview);
adapter=new CustomGridViewAdapter(this.getContext(), packages);
gridView.setAdapter(adapter);
selectedPackage = packages.get(0).getId();
packageName.setText(packages.get(0).getName());
packageInfo.setText(packages.get(0).getInfo());
Double time = (double)(packages.get(0).getTime())/60;
time = Double.parseDouble(String.format("%.3f", time));
packageTime.setText(time.toString());
final LinearLayout prices = (LinearLayout) view.findViewById(R.id.prices);
if(packages.get(0).getPrice().getHatch() == 0L || packages.get(0).getPrice().getSuv() == 0L ||
packages.get(0).getPrice().getSedan() == 0L){
hatchPrice.setText(" ");
suvPrice.setText(" ");
sedanPrice.setText(" ");
}
else{
hatchPrice.setText(packages.get(0).getPrice().getHatch().toString());
suvPrice.setText(packages.get(0).getPrice().getSuv().toString());
sedanPrice.setText(packages.get(0).getPrice().getSedan().toString());
}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
packageName.setText(packages.get(i).getName());
packageInfo.setText(packages.get(i).getInfo());
Double time = (double)(packages.get(i).getTime())/60;
packageTime.setText(time.toString());
if(packages.get(i).getPrice().getHatch() == 0L || packages.get(i).getPrice().getSuv() == 0L ||
packages.get(i).getPrice().getSedan() == 0L){
hatchPrice.setText(" ");
suvPrice.setText(" ");
sedanPrice.setText(" ");
}
else{
hatchPrice.setText(packages.get(i).getPrice().getHatch().toString());
suvPrice.setText(packages.get(i).getPrice().getSuv().toString());
sedanPrice.setText(packages.get(i).getPrice().getSedan().toString());
}
for (int j = 0; j< packages.size(); j++) {
packages.get(j).setSelected(false);
}
packages.get(i).setSelected(true);
selectedPackage = packages.get(i).getId();
adapter.notifyDataSetChanged();
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onPackageListFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onPackageListFragmentInteraction(Uri uri);
}
private void initializeData(){
Bundle arguments = getArguments();
String type = arguments.getString("type");
DaoSession daoSession = ((App) getActivity().getApplication()).getDaoSession();
packages = daoSession.getPackagesDao().queryBuilder()
.where(PackagesDao.Properties.Type.eq(type)).list();
packages.get(0).setSelected(true);
for(int i=1;i<packages.size();i++) {
packages.get(i).setSelected(false);
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.hatchCard:
setFocus(priceCard, hatchCard);
break;
case R.id.sedanCard :
setFocus(priceCard, sedanCard);
break;
case R.id.suvCard :
setFocus(priceCard, suvCard);
break;
}
}
private void setFocus(LinearLayout priceCard, LinearLayout cardFocus){
priceCard.setBackgroundColor(Color.TRANSPARENT);
cardFocus.setBackgroundColor(Color.parseColor("#b1efe9"));
this.priceCard = cardFocus;
}
}
| UTF-8 | Java | 10,357 | java | PackageList.java | Java | [] | null | [] | package com.nist.washintondc;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link PackageList.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link PackageList#newInstance} factory method to
* create an instance of this fragment.
*/
public class PackageList extends Fragment implements View.OnClickListener{
// 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 OnFragmentInteractionListener mListener;
private Context mContext;
List<Packages> packages;
GridView gridView;
CustomGridViewAdapter adapter;
TextView packageName, packagePrice, packageInfo, packageTime;
Button selectBtn, updateBtn;
Button hatchPrice, suvPrice, sedanPrice;
LinearLayout priceCard, hatchCard, sedanCard, suvCard;
private long selectedPackage;
public PackageList() {
// 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 PackageList.
*/
// TODO: Rename and change types and number of parameters
public static PackageList newInstance(String param1, String param2) {
PackageList fragment = new PackageList();
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);
mContext = getActivity().getApplicationContext();
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
initializeData();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity())
.setActionBarTitle("Select Package");
View view = inflater.inflate(R.layout.fragment_package_list, container, false);
selectBtn = (Button) view.findViewById(R.id.select);
selectBtn.setVisibility(View.VISIBLE);
updateBtn = (Button) view.findViewById(R.id.selectEdit);
updateBtn.setVisibility(View.GONE);
selectBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CustomerDetails newFragment = new CustomerDetails();
Bundle bundle = new Bundle();
bundle.putLong("selectedPackage", selectedPackage);
bundle.putString("carType", priceCard.getTag().toString().toLowerCase());
newFragment.setArguments(bundle);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment, newFragment);
transaction.addToBackStack("packageList");
// Commit the transaction
transaction.commit();
}
});
packageName = (TextView)view.findViewById(R.id.packageName);
packagePrice = (TextView)view.findViewById(R.id.packagePrice);
packageInfo = (TextView)view.findViewById(R.id.packageInfo);
packageInfo.setMovementMethod(new ScrollingMovementMethod());
packageTime= (TextView)view.findViewById(R.id.packageTime);
hatchPrice = (Button) view.findViewById(R.id.hatchPrice);
suvPrice = (Button) view.findViewById(R.id.suvPrice);
sedanPrice = (Button) view.findViewById(R.id.sedanPrice);
hatchCard = (LinearLayout) view.findViewById(R.id.hatchCard);
sedanCard = (LinearLayout) view.findViewById(R.id.sedanCard);
suvCard = (LinearLayout) view.findViewById(R.id.suvCard);
hatchCard.setOnClickListener(this);
sedanCard.setOnClickListener(this);
suvCard.setOnClickListener(this);
priceCard = hatchCard;
hatchCard.setBackgroundColor(Color.parseColor("#b1efe9"));
gridView= view.findViewById(R.id.gridview);
adapter=new CustomGridViewAdapter(this.getContext(), packages);
gridView.setAdapter(adapter);
selectedPackage = packages.get(0).getId();
packageName.setText(packages.get(0).getName());
packageInfo.setText(packages.get(0).getInfo());
Double time = (double)(packages.get(0).getTime())/60;
time = Double.parseDouble(String.format("%.3f", time));
packageTime.setText(time.toString());
final LinearLayout prices = (LinearLayout) view.findViewById(R.id.prices);
if(packages.get(0).getPrice().getHatch() == 0L || packages.get(0).getPrice().getSuv() == 0L ||
packages.get(0).getPrice().getSedan() == 0L){
hatchPrice.setText(" ");
suvPrice.setText(" ");
sedanPrice.setText(" ");
}
else{
hatchPrice.setText(packages.get(0).getPrice().getHatch().toString());
suvPrice.setText(packages.get(0).getPrice().getSuv().toString());
sedanPrice.setText(packages.get(0).getPrice().getSedan().toString());
}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
packageName.setText(packages.get(i).getName());
packageInfo.setText(packages.get(i).getInfo());
Double time = (double)(packages.get(i).getTime())/60;
packageTime.setText(time.toString());
if(packages.get(i).getPrice().getHatch() == 0L || packages.get(i).getPrice().getSuv() == 0L ||
packages.get(i).getPrice().getSedan() == 0L){
hatchPrice.setText(" ");
suvPrice.setText(" ");
sedanPrice.setText(" ");
}
else{
hatchPrice.setText(packages.get(i).getPrice().getHatch().toString());
suvPrice.setText(packages.get(i).getPrice().getSuv().toString());
sedanPrice.setText(packages.get(i).getPrice().getSedan().toString());
}
for (int j = 0; j< packages.size(); j++) {
packages.get(j).setSelected(false);
}
packages.get(i).setSelected(true);
selectedPackage = packages.get(i).getId();
adapter.notifyDataSetChanged();
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onPackageListFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onPackageListFragmentInteraction(Uri uri);
}
private void initializeData(){
Bundle arguments = getArguments();
String type = arguments.getString("type");
DaoSession daoSession = ((App) getActivity().getApplication()).getDaoSession();
packages = daoSession.getPackagesDao().queryBuilder()
.where(PackagesDao.Properties.Type.eq(type)).list();
packages.get(0).setSelected(true);
for(int i=1;i<packages.size();i++) {
packages.get(i).setSelected(false);
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.hatchCard:
setFocus(priceCard, hatchCard);
break;
case R.id.sedanCard :
setFocus(priceCard, sedanCard);
break;
case R.id.suvCard :
setFocus(priceCard, suvCard);
break;
}
}
private void setFocus(LinearLayout priceCard, LinearLayout cardFocus){
priceCard.setBackgroundColor(Color.TRANSPARENT);
cardFocus.setBackgroundColor(Color.parseColor("#b1efe9"));
this.priceCard = cardFocus;
}
}
| 10,357 | 0.634547 | 0.629719 | 284 | 35.468311 | 27.596355 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.605634 | false | false | 9 |
d5665baf635cb0242bdbd9a5302d8b38fbe34fb7 | 1,640,677,567,442 | 8c7e7cc3ad574e5d30b9d6ce5467a1f1418514b7 | /Interfacesss/src/Gamma.java | 2c60ca270807bc77e400042ebdca67d94440eae1 | [] | no_license | fero656565/OOP_Derin | https://github.com/fero656565/OOP_Derin | c6a94dc59010052dad9aa2cd73375d8289360fb0 | 109baa18e268ea5d02ba0d8e6ba2f88cb0d85c2a | refs/heads/master | 2020-04-24T14:16:54.963000 | 2019-05-02T09:54:06 | 2019-05-02T09:54:06 | 172,015,508 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Gamma {
}
| UTF-8 | Java | 23 | java | Gamma.java | Java | [] | null | [] | public class Gamma {
}
| 23 | 0.695652 | 0.695652 | 2 | 10.5 | 9.5 | 20 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | false | false | 9 |
5aab700d34898b0ba3eda7eb4707661d6a522adf | 15,393,162,842,563 | 72cc77b9ea1967c374d4991f7303000d4350f558 | /sixeswild/game/entity/Mode.java | 5c51dbf8ffbb80e2d3feab21191cdda1f8b5de1d | [] | no_license | isamunakagawa/aces-and-kings | https://github.com/isamunakagawa/aces-and-kings | f410c39fa2b2e6ec5fb08fef59b10b7743340c47 | e7b58de4e9a38897425d7d8d9671f43a38fdd6ff | refs/heads/master | 2020-12-24T12:40:25.960000 | 2016-12-20T22:02:11 | 2016-12-20T22:02:11 | 72,965,161 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package game.entity;
/**
*
*
*
*/
public class Mode {
/** Enum type of different game modes.*/
public enum gameMode {PUZZLE, LIGHTNING, RELEASE, ELIMINATION}
/** Game mode for the level.*/
gameMode mode;
/**Countdown associated with the game mode.*/
int countDown;
/**
* Game mode constructor that creates a mode object,
* given its parameters.
* @param mode, gameMode enum type
* @param initialCount
*/
public Mode(gameMode mode, int initialCount){
this.mode = mode;
this.countDown = initialCount;
}
/** Decrements the countdown amount.*/
public void decrement(){
if (this.countDown > 0) {
this.countDown -= 1;
}
System.out.println(this.countDown);
}
/**Boolean function that checks if the game mode is Puzzle.*/
public boolean isPuzzle() {
Boolean bool = this.mode == gameMode.PUZZLE;
System.out.println(bool);
return bool;
}
/**Boolean function that checks if the game mode is Lightning.*/
public boolean isLightning() {
return this.mode == gameMode.LIGHTNING;
}
/**Boolean function that checks if the game mode is Release.*/
public boolean isRelease() {
return this.mode == gameMode.RELEASE;
}
/**Boolean function that checks if the game mode is Elimination.*/
public boolean isElimination() {
return this.mode == gameMode.ELIMINATION;
}
/**Returns the countdown value.*/
public int getCountdown() {
return this.countDown;
}
}
| UTF-8 | Java | 1,420 | java | Mode.java | Java | [] | null | [] | package game.entity;
/**
*
*
*
*/
public class Mode {
/** Enum type of different game modes.*/
public enum gameMode {PUZZLE, LIGHTNING, RELEASE, ELIMINATION}
/** Game mode for the level.*/
gameMode mode;
/**Countdown associated with the game mode.*/
int countDown;
/**
* Game mode constructor that creates a mode object,
* given its parameters.
* @param mode, gameMode enum type
* @param initialCount
*/
public Mode(gameMode mode, int initialCount){
this.mode = mode;
this.countDown = initialCount;
}
/** Decrements the countdown amount.*/
public void decrement(){
if (this.countDown > 0) {
this.countDown -= 1;
}
System.out.println(this.countDown);
}
/**Boolean function that checks if the game mode is Puzzle.*/
public boolean isPuzzle() {
Boolean bool = this.mode == gameMode.PUZZLE;
System.out.println(bool);
return bool;
}
/**Boolean function that checks if the game mode is Lightning.*/
public boolean isLightning() {
return this.mode == gameMode.LIGHTNING;
}
/**Boolean function that checks if the game mode is Release.*/
public boolean isRelease() {
return this.mode == gameMode.RELEASE;
}
/**Boolean function that checks if the game mode is Elimination.*/
public boolean isElimination() {
return this.mode == gameMode.ELIMINATION;
}
/**Returns the countdown value.*/
public int getCountdown() {
return this.countDown;
}
}
| 1,420 | 0.68662 | 0.685211 | 62 | 21.903225 | 19.956169 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.419355 | false | false | 9 |
d4a5618634165f1aa5e0c58c0e88229449b6eb14 | 29,463,475,701,514 | b92b76428acdab2121f18e1b6e5038431e51ab21 | /designpattern/src/main/java/designpattern/visitor/Student.java | 74745eda5bda2714b7073c3e929df3ef4367219e | [] | no_license | DeanJons99/springbootlearn | https://github.com/DeanJons99/springbootlearn | 98d799ac1d9d6aad8f1d19dbc46b40ac0facf390 | acfa258abe0ef32896f3f860503cb5ad3bea5a04 | refs/heads/master | 2021-03-20T11:06:56.421000 | 2020-03-14T03:14:48 | 2020-03-14T03:14:48 | 247,202,270 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package designpattern.visitor;
public class Student implements Element {
private String name;
private Integer grade; //成绩
private Integer paperCount;
public Student(String name, Integer grade, Integer paperCount) {
this.name = name;
this.grade = grade;
this.paperCount = paperCount;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
public Integer getPaperCount() {
return paperCount;
}
public void setPaperCount(Integer paperCount) {
this.paperCount = paperCount;
}
}
| UTF-8 | Java | 865 | java | Student.java | Java | [] | null | [] | package designpattern.visitor;
public class Student implements Element {
private String name;
private Integer grade; //成绩
private Integer paperCount;
public Student(String name, Integer grade, Integer paperCount) {
this.name = name;
this.grade = grade;
this.paperCount = paperCount;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
public Integer getPaperCount() {
return paperCount;
}
public void setPaperCount(Integer paperCount) {
this.paperCount = paperCount;
}
}
| 865 | 0.615563 | 0.615563 | 42 | 19.5 | 17.15094 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380952 | false | false | 9 |
394d12a467200bfc8ba172b155daa52b45b092d6 | 24,824,911,019,052 | d4b71cc11038550d4bf475bd263ce77f7e956da9 | /src/main/java/uz/pdp/apphrmanagement/entity/enums/RoleEnum.java | 1caa01426b60421ea992e06b60844c3f3a53622e | [] | no_license | Muhammad0224/app-hr-management | https://github.com/Muhammad0224/app-hr-management | 509ba196b03e2a7f0c6cc8e6d1ba154becf1e8a5 | 0946b5434e1e6c8aa80405d09ee59188954fd498 | refs/heads/master | 2023-07-02T05:50:21.188000 | 2021-08-07T18:39:43 | 2021-08-07T18:39:43 | 393,323,049 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uz.pdp.apphrmanagement.entity.enums;
public enum RoleEnum {
ROLE_ADMIN,
ROLE_DIRECTOR,
ROLE_HR_MANAGER,
ROLE_WORKER
}
| UTF-8 | Java | 143 | java | RoleEnum.java | Java | [] | null | [] | package uz.pdp.apphrmanagement.entity.enums;
public enum RoleEnum {
ROLE_ADMIN,
ROLE_DIRECTOR,
ROLE_HR_MANAGER,
ROLE_WORKER
}
| 143 | 0.699301 | 0.699301 | 8 | 16.875 | 12.830018 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
e1b1b5185c3b90816f4378c7702db1ecbe2431a1 | 24,283,745,142,811 | 688c66d40f8bbd5114c04c2fc4e78eb44625d19e | /jet/server/src/main/java/client/ClientApp.java | 73983fbd1066f0b56162fa92be05a6bf552e7207 | [] | no_license | multinames/java-courses | https://github.com/multinames/java-courses | 67bddff2be114ba568afc0b6a2cf8e58f3d774d3 | bd75e9c44081199aa0e85c9f588ec9677a05a9aa | refs/heads/master | 2022-12-23T18:28:29.440000 | 2020-09-30T05:30:49 | 2020-09-30T05:30:49 | 226,126,693 | 0 | 0 | null | false | 2022-12-16T15:09:16 | 2019-12-05T14:57:55 | 2020-09-30T05:31:13 | 2022-12-16T15:09:16 | 479 | 0 | 0 | 11 | Java | false | false | package client;
import java.io.*;
import java.net.Socket;
public class ClientApp {
public static void main(String[] args) {
System.out.println("Инициализация подключения к серверу");
try(Socket socket = new Socket("localhost", 10000)){
System.out.println("Соединение установлено");
FileReader fileReader = new FileReader("httpPackage");
BufferedReader reader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String str = "";
while ((str = reader.readLine()) != null){
stringBuilder.append(str);
}
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(stringBuilder.toString());
writer.flush();
socket.shutdownOutput();
InputStreamReader inr = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inr);
while (!bufferedReader.ready()){
Thread.sleep(50);
}
String answer = "";
while ((answer = bufferedReader.readLine()) != null){
System.out.println(answer);
}
}
catch (InterruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Соединение разорвано");
}
}
| UTF-8 | Java | 1,713 | java | ClientApp.java | Java | [] | null | [] | package client;
import java.io.*;
import java.net.Socket;
public class ClientApp {
public static void main(String[] args) {
System.out.println("Инициализация подключения к серверу");
try(Socket socket = new Socket("localhost", 10000)){
System.out.println("Соединение установлено");
FileReader fileReader = new FileReader("httpPackage");
BufferedReader reader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String str = "";
while ((str = reader.readLine()) != null){
stringBuilder.append(str);
}
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(stringBuilder.toString());
writer.flush();
socket.shutdownOutput();
InputStreamReader inr = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inr);
while (!bufferedReader.ready()){
Thread.sleep(50);
}
String answer = "";
while ((answer = bufferedReader.readLine()) != null){
System.out.println(answer);
}
}
catch (InterruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Соединение разорвано");
}
}
| 1,713 | 0.571603 | 0.567337 | 53 | 29.962265 | 23.776445 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490566 | false | false | 9 |
d10f7f2be746668fd28306ffb2294256da2cc3ce | 19,722,489,828,057 | 9c3deb06c8571fc6ac6e8df0af900949782454e6 | /src/main/java/com/community/framework/utils/MessageChannelCLClient.java | e08ce4de184c93d03734308189f0e02a4796ba53 | [] | no_license | xeonye/community | https://github.com/xeonye/community | d7a81dca1427e21917656850d97cac61995d9a50 | c5122d93bc847cbe2be7f85bd0e2c7c1b1c2f64b | refs/heads/master | 2020-03-11T09:42:02.297000 | 2015-04-03T08:23:48 | 2015-04-03T08:23:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.community.framework.utils;
import com.bcloud.msg.http.HttpSender;
/*
* 创蓝短信验证码服务接口
*/
public class MessageChannelCLClient {
private static String uri = "http://222.73.117.158/msg/HttpBatchSendSM"; //应用地址
private static String account = "jiekou-cs-01"; //账号
private static String pswd = "Tch147256"; //密码
private static boolean needstatus = true; //是否需要状态报告,需要true,不需要false
private static String product = ""; //产品ID
private static String extno = ""; //扩展码
/*
* 群发短信方法
*/
public static String batchSend(String mobiles, String content) {
String result = "";
try {
String resultCode = HttpSender.batchSend(uri, account, pswd, mobiles, content, needstatus, product, extno);
String[] resultArr = resultCode.split(",");
if(resultArr.length == 2) {
if(Integer.parseInt(resultArr[1].substring(0, 1)) == 0) {
result = getReturnCode(Integer.parseInt(resultArr[1].substring(0, 1)));
} else {
result = getReturnCode(Integer.parseInt(resultArr[1].substring(0, 3)));
}
} else {
result = "返回码格式错误" + resultCode;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/*
* TODO 处理返回值,参见HTTP协议文档
*/
public static String getReturnCode(int code) {
String result;
switch (code) {
case 0:
result = "提交成功";
break;
case 101:
result = "无此用户";
break;
case 102:
result = "密码错";
break;
case 103:
result = "提交过快(提交速度超过流速限制)";
break;
case 104:
result = "系统忙(因平台侧原因,暂时无法处理提交的短信)";
break;
case 105:
result = "敏感短信(短信内容包含敏感词)";
break;
case 106:
result = "消息长度错(>536或<=0)";
break;
case 107:
result = "包含错误的手机号码";
break;
case 108:
result = "手机号码个数错(群发>50000或<=0;单发>200或<=0)";
break;
case 109:
result = "无发送额度(该用户可用短信数已使用完)";
break;
case 110:
result = "不在发送时间内";
break;
case 111:
result = "超出该账户当月发送额度限制";
break;
case 112:
result = "无此产品,用户没有订购该产品";
break;
case 113:
result = "extno格式错(非数字或者长度不对)";
break;
case 115:
result = "自动审核驳回";
break;
case 116:
result = "签名不合法,未带签名(用户必须带签名的前提下)";
break;
case 117:
result = "IP地址认证错,请求调用的IP地址不是系统登记的IP地址";
break;
case 118:
result = "用户没有相应的发送权限";
break;
case 119:
result = "用户已过期";
break;
default :
result = "未知错误";
}
return result;
}
public static void main(String[] args) {
try {
String result = batchSend("18618166710,15001300375", "验证码:123456");
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
} | UTF-8 | Java | 3,298 | java | MessageChannelCLClient.java | Java | [
{
"context": "Client {\r\n\t\r\n\tprivate static String uri = \"http://222.73.117.158/msg/HttpBatchSendSM\"; //应用地址\r\n\tprivate static Str",
"end": 198,
"score": 0.9691925048828125,
"start": 184,
"tag": "IP_ADDRESS",
"value": "222.73.117.158"
},
{
"context": "endSM\"; //应用地址\r\n\tprivate static String account = \"jiekou-cs-01\"; //账号\r\n\tprivate static String pswd = \"Tch147256\"",
"end": 275,
"score": 0.9667359590530396,
"start": 263,
"tag": "KEY",
"value": "jiekou-cs-01"
},
{
"context": "ekou-cs-01\"; //账号\r\n\tprivate static String pswd = \"Tch147256\"; //密码\r\n\tprivate static boolean needstatus = true",
"end": 324,
"score": 0.9935543537139893,
"start": 315,
"tag": "PASSWORD",
"value": "Tch147256"
}
] | null | [] | package com.community.framework.utils;
import com.bcloud.msg.http.HttpSender;
/*
* 创蓝短信验证码服务接口
*/
public class MessageChannelCLClient {
private static String uri = "http://172.16.31.10/msg/HttpBatchSendSM"; //应用地址
private static String account = "<KEY>"; //账号
private static String pswd = "<PASSWORD>"; //密码
private static boolean needstatus = true; //是否需要状态报告,需要true,不需要false
private static String product = ""; //产品ID
private static String extno = ""; //扩展码
/*
* 群发短信方法
*/
public static String batchSend(String mobiles, String content) {
String result = "";
try {
String resultCode = HttpSender.batchSend(uri, account, pswd, mobiles, content, needstatus, product, extno);
String[] resultArr = resultCode.split(",");
if(resultArr.length == 2) {
if(Integer.parseInt(resultArr[1].substring(0, 1)) == 0) {
result = getReturnCode(Integer.parseInt(resultArr[1].substring(0, 1)));
} else {
result = getReturnCode(Integer.parseInt(resultArr[1].substring(0, 3)));
}
} else {
result = "返回码格式错误" + resultCode;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/*
* TODO 处理返回值,参见HTTP协议文档
*/
public static String getReturnCode(int code) {
String result;
switch (code) {
case 0:
result = "提交成功";
break;
case 101:
result = "无此用户";
break;
case 102:
result = "密码错";
break;
case 103:
result = "提交过快(提交速度超过流速限制)";
break;
case 104:
result = "系统忙(因平台侧原因,暂时无法处理提交的短信)";
break;
case 105:
result = "敏感短信(短信内容包含敏感词)";
break;
case 106:
result = "消息长度错(>536或<=0)";
break;
case 107:
result = "包含错误的手机号码";
break;
case 108:
result = "手机号码个数错(群发>50000或<=0;单发>200或<=0)";
break;
case 109:
result = "无发送额度(该用户可用短信数已使用完)";
break;
case 110:
result = "不在发送时间内";
break;
case 111:
result = "超出该账户当月发送额度限制";
break;
case 112:
result = "无此产品,用户没有订购该产品";
break;
case 113:
result = "extno格式错(非数字或者长度不对)";
break;
case 115:
result = "自动审核驳回";
break;
case 116:
result = "签名不合法,未带签名(用户必须带签名的前提下)";
break;
case 117:
result = "IP地址认证错,请求调用的IP地址不是系统登记的IP地址";
break;
case 118:
result = "用户没有相应的发送权限";
break;
case 119:
result = "用户已过期";
break;
default :
result = "未知错误";
}
return result;
}
public static void main(String[] args) {
try {
String result = batchSend("18618166710,15001300375", "验证码:123456");
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
} | 3,290 | 0.595326 | 0.54822 | 115 | 21.460869 | 19.860947 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.417391 | false | false | 9 |
fae629818dbd36549e1260b9e2c6a85b516c14aa | 9,242,769,636,216 | 7b975497f4b86fe807dac770c8936c6a36c1aa00 | /four/src/main/java/com/loveseriously/catCode/CodeMaker.java | 19a786acdc83b16bdbd8e3f18fd019efda3ef692 | [] | no_license | LoveSeriously/intellij-plugin | https://github.com/LoveSeriously/intellij-plugin | 273c142cc8c1137cc1c9652164bf4bbe6d92ea4c | 5b89789defcd27374f1fedb8d6c6e9047c9a83ef | refs/heads/master | 2020-07-09T14:30:29.484000 | 2019-10-14T00:35:23 | 2019-10-14T00:35:23 | 201,250,725 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.loveseriously.catCode;
import com.intellij.openapi.components.ApplicationComponent;
/**
* @author lw
* @date 2019-08-20
*/
public class CodeMaker implements ApplicationComponent {
public CodeMaker() {
}
@Override
public void initComponent() {
}
@Override
public void disposeComponent() {
}
@Override
public String getComponentName() {
return "com.xiaohansong.codemaker.CodeMaker";
}
}
| UTF-8 | Java | 457 | java | CodeMaker.java | Java | [
{
"context": "i.components.ApplicationComponent;\n\n/**\n * @author lw\n * @date 2019-08-20\n */\npublic class CodeMaker im",
"end": 115,
"score": 0.9885604977607727,
"start": 113,
"tag": "USERNAME",
"value": "lw"
}
] | null | [] | package com.loveseriously.catCode;
import com.intellij.openapi.components.ApplicationComponent;
/**
* @author lw
* @date 2019-08-20
*/
public class CodeMaker implements ApplicationComponent {
public CodeMaker() {
}
@Override
public void initComponent() {
}
@Override
public void disposeComponent() {
}
@Override
public String getComponentName() {
return "com.xiaohansong.codemaker.CodeMaker";
}
}
| 457 | 0.673961 | 0.656455 | 25 | 17.280001 | 18.758507 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.12 | false | false | 9 |
34947aa794050b16ec8107609e8f01ef43b55876 | 23,622,320,152,271 | 59c048af517112593e9dde12bde2b6db3ddfbcbd | /src/LinkedList/LinkedList.java | 27ebbd52e3e3e239b7f2cc6ebbfa880bc4bab005 | [] | no_license | avish9024/DataStructures | https://github.com/avish9024/DataStructures | e7c958b724c5604c1751be61bdbf311e00405587 | 13836670e78d77ec0d3572a7498822c96eb0f72b | refs/heads/main | 2023-07-24T00:41:44.052000 | 2021-08-26T15:32:48 | 2021-08-26T15:32:48 | 399,866,410 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package LinkedList;
import java.util.HashSet;
import java.util.List;
public class LinkedList {
Node head;
int size;
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public Node reverseList() {
Node prev = null, curr = head, next = null;
while(curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
public Node insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
size = 1;
return head;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
size++;
}
return head;
}
public Node insertSorted(int data) {
Node newNode = new Node(data);
Node current = head;
Node previous = null;
while(current != null && data > current.data){
previous = current;
current = current.next;
}
if(previous == null){
head = newNode;
}else{
previous.next = newNode;
}
newNode.next = current;
size++;
return head;
}
public int getDecimalValue() {
if (head == null) {
System.out.println("List is empty");
return -1;
}
int num = head.data;
while (head.next != null) {
num = num * 2 + head.next.data;
head = head.next;
}
return num;
}
public void printList() {
if (head == null) {
System.out.print("List is empty");
return;
}
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public int getMiddle() {
if (head == null) {
System.out.println("List is Empty");
return -1;
}
Node temp1 = head, temp2 = head;
while (temp2 != null && temp2.next != null) {
temp1 = temp1.next;
temp2 = temp2.next.next;
}
return temp1.data;
}
public boolean deleteNode(int data) {
if (head == null) {
System.out.println("List is empty");
return false;
}
Node prev = null, curr = head;
while (curr.data != data) {
prev = curr;
curr = curr.next;
}
if (prev == null) {
head = head.next;
} else {
prev.next = curr.next;
}
return true;
}
public boolean deleteNodeAtIndex(int pos) {
if (head == null) return false;
if (pos == 0) {
head = head.next;
return true;
}
int curr = 0;
Node temp = head, prev = null;
while (curr != pos) {
if (temp == null || temp.next == null) return false;
prev = temp;
temp = temp.next;
curr++;
}
prev.next = temp.next;
return true;
}
public void deleteDuplicates() {
Node curr = head;
HashSet<Integer> h = new HashSet<>();
while(curr != null) {
h.add(curr.data);
if (curr.next == null) {
break;
}
if (h.contains(curr.next.data)) {
curr.next = curr.next.next;
} else {
curr = curr.next;
}
}
}
}
| UTF-8 | Java | 3,761 | java | LinkedList.java | Java | [] | null | [] | package LinkedList;
import java.util.HashSet;
import java.util.List;
public class LinkedList {
Node head;
int size;
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public Node reverseList() {
Node prev = null, curr = head, next = null;
while(curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
public Node insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
size = 1;
return head;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
size++;
}
return head;
}
public Node insertSorted(int data) {
Node newNode = new Node(data);
Node current = head;
Node previous = null;
while(current != null && data > current.data){
previous = current;
current = current.next;
}
if(previous == null){
head = newNode;
}else{
previous.next = newNode;
}
newNode.next = current;
size++;
return head;
}
public int getDecimalValue() {
if (head == null) {
System.out.println("List is empty");
return -1;
}
int num = head.data;
while (head.next != null) {
num = num * 2 + head.next.data;
head = head.next;
}
return num;
}
public void printList() {
if (head == null) {
System.out.print("List is empty");
return;
}
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public int getMiddle() {
if (head == null) {
System.out.println("List is Empty");
return -1;
}
Node temp1 = head, temp2 = head;
while (temp2 != null && temp2.next != null) {
temp1 = temp1.next;
temp2 = temp2.next.next;
}
return temp1.data;
}
public boolean deleteNode(int data) {
if (head == null) {
System.out.println("List is empty");
return false;
}
Node prev = null, curr = head;
while (curr.data != data) {
prev = curr;
curr = curr.next;
}
if (prev == null) {
head = head.next;
} else {
prev.next = curr.next;
}
return true;
}
public boolean deleteNodeAtIndex(int pos) {
if (head == null) return false;
if (pos == 0) {
head = head.next;
return true;
}
int curr = 0;
Node temp = head, prev = null;
while (curr != pos) {
if (temp == null || temp.next == null) return false;
prev = temp;
temp = temp.next;
curr++;
}
prev.next = temp.next;
return true;
}
public void deleteDuplicates() {
Node curr = head;
HashSet<Integer> h = new HashSet<>();
while(curr != null) {
h.add(curr.data);
if (curr.next == null) {
break;
}
if (h.contains(curr.next.data)) {
curr.next = curr.next.next;
} else {
curr = curr.next;
}
}
}
}
| 3,761 | 0.437384 | 0.433395 | 156 | 23.108974 | 13.713448 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.544872 | false | false | 9 |
13ce099a75ae7bb095d3594d29a7d8812351f67e | 22,840,636,148,895 | 58e9a574199c9e087beaf22101159d7ca307d241 | /Core/src/main/java/net/lightning/core/stats/GameStats.java | e34c46b24b45f7caff97806e4ee1a7649bf44fbd | [] | no_license | Slysidus/plugins-archive | https://github.com/Slysidus/plugins-archive | f742f4a0e0b8695a632831417857a247c47be1f5 | d3cb723d4b287455c07aa9de7429f2bc9fdee9bc | refs/heads/master | 2023-03-04T22:08:57.866000 | 2021-02-16T12:35:46 | 2021-02-16T12:38:16 | 339,393,631 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.lightning.core.stats;
public interface GameStats {
}
| UTF-8 | Java | 69 | java | GameStats.java | Java | [] | null | [] | package net.lightning.core.stats;
public interface GameStats {
}
| 69 | 0.753623 | 0.753623 | 7 | 8.857142 | 13.757373 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 9 |
77a91aa9c8fa1a363d6f4e0644c0bdb3c106994a | 22,677,427,344,643 | 28919c8e4be24ba562ef9c5f153aa435df3fc20e | /src/main/java/masterSpringMvc/search/TwitterSearch.java | d4790ef398ae3f9e49ed4121a9d18c0e00d60b59 | [] | no_license | zgithubber/masterSpringMVC | https://github.com/zgithubber/masterSpringMVC | 79c91ce1b0beb772a5970c5a83fae31c78846212 | 8ca4bb96dfd3d2b449340b34fda7793b3888d488 | refs/heads/master | 2021-01-10T01:46:11.450000 | 2016-04-04T09:27:08 | 2016-04-04T09:27:08 | 55,223,470 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package masterSpringMvc.search;
import java.util.List;
public interface TwitterSearch {
public abstract List<LightTweet> search(String searchType,
List<String> keywords);
} | UTF-8 | Java | 180 | java | TwitterSearch.java | Java | [] | null | [] | package masterSpringMvc.search;
import java.util.List;
public interface TwitterSearch {
public abstract List<LightTweet> search(String searchType,
List<String> keywords);
} | 180 | 0.788889 | 0.788889 | 10 | 17.1 | 19.24292 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 9 |
fe80b9009df02943ffc31f534ccc45a8722103a7 | 13,675,175,931,539 | 69ac5b84b3241b66820998136385ec4fa4975b31 | /Boggle Solver/src/MyNode.java | bde349aee8ab28357b3b06672452e83f82ea96c5 | [] | no_license | YoussefSherif98/Boggle-Solver | https://github.com/YoussefSherif98/Boggle-Solver | 096848494dc7e44eea9a9484e676a9ba2a1d3903 | c67e98dba8b057c8c2219e91787c6004694381d3 | refs/heads/master | 2022-06-01T20:25:42.445000 | 2020-05-05T09:16:24 | 2020-05-05T09:16:24 | 261,410,226 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class MyNode {
private static final int RADIX = 26;
public boolean value = false;
public MyNode[] next = new MyNode[RADIX];
public void setValue()
{
this.value = true;
}
}
| UTF-8 | Java | 206 | java | MyNode.java | Java | [] | null | [] |
public class MyNode {
private static final int RADIX = 26;
public boolean value = false;
public MyNode[] next = new MyNode[RADIX];
public void setValue()
{
this.value = true;
}
}
| 206 | 0.626214 | 0.616505 | 13 | 13.692307 | 15.127075 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.923077 | false | false | 9 |
e91de79439fb5f361134edf43973263696de5bb0 | 10,402,410,824,723 | 746fdad093efae43b697d706146578eff372b16b | /app/src/main/java/database/DataBase.java | c96c117a18ba40ae4d2aece7084d04e12a0c8ec2 | [] | no_license | Ali-Ai-Dev/ibazar-app | https://github.com/Ali-Ai-Dev/ibazar-app | 65c067f878fe8befcfe6afd629fff16939dd20b6 | a7482cdcdf055d54f13e0dc47b32632e0ceee789 | refs/heads/main | 2023-09-05T13:03:43.642000 | 2021-11-15T22:01:30 | 2021-11-15T22:01:30 | 428,417,905 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package database;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
import com.tnt.ibazaar.Application;
import java.io.File;
import java.util.ArrayList;
import java.util.Set;
import models.Advertisement;
import models.Brand;
import models.Category;
import models.Product;
import models.Staff;
import models.shop.Shop;
import models.shop.ShopInfo;
/**
* Created by omid' on 5/9/2017.
*/
public class DataBase {
private static final String dirsd = Environment.getExternalStorageDirectory().getAbsolutePath();
private static final String dirdb = dirsd + "/android/data/" + Application.getPackageName2();
private static SQLiteDatabase db;
private static void openOrCreate() {
File filedb = new File(dirdb);
filedb.mkdirs();
filedb.setWritable(true);
filedb.setReadable(true);
File db2 = new File(dirdb + "/db.db");
Log.e("dp path", dirdb + " exists? " + db2.exists());
try {
db = SQLiteDatabase.openOrCreateDatabase(dirdb + "/db.db", null);
} catch (Exception e) {
Log.e("db open error", "" + e.getMessage());
}
}
private static long insert(String tableName, String columnNames, ContentValues values) {
if (db == null)
openOrCreate();
return db.insert(tableName, columnNames, values);
}
private static void update(String tableName, ContentValues values, String whereCluase, String[] whereArgs) {
if (db == null)
openOrCreate();
db.update(tableName, values, whereCluase, whereArgs);
}
private static void delete(String tableName, String whereCluase, String[] whereArgs) {
if (db == null)
openOrCreate();
db.delete(tableName, whereCluase, whereArgs);
}
private static Cursor select(String query) {
if (db == null)
openOrCreate();
return db.rawQuery(query, null);
}
private static int getInt(Cursor cursor, String columnName) {
return cursor.getInt(cursor.getColumnIndex(columnName));
}
private static String getString(Cursor cursor, String columnName) {
return cursor.getString(cursor.getColumnIndex(columnName));
}
private static String getColumns(Set<String> strings) {
String columns = "";
if (strings != null)
for (String s : strings)
columns += s;
return columns;
}
// public static String selectLastModifiedCategoryTime() {
// String query = "select max(last_modified) from categories";
// Cursor select = select(query);
// if (select == null || select.moveToFirst() || select.getCount() == 0) {
// return "0";
// }
// return select.getString(0) == null ? "0" : select.getString(0);
// }
// public static void InsertOrUpdateCategory(Category category) {
// if (!isCategoryAvailable(category.getId()))
// insertCategory(category);
// else
// updateCategories(category);
// }
// private static void updateCategories(Category category) {
// ContentValues values = new ContentValues();
//// values.put("code", category.getId());
// values.put("parent", category.getParent());
// values.put("title", category.getTitle());
// values.put("image_url", category.getImage_name());
// values.put("last_modified", category.getLast_modified());
//
// update("categories", values, " id=" + category.getId(), null);
// }
public static void insertCategory(Category category) {
ContentValues values = new ContentValues();
values.put("id", category.getId());
values.put("parent", category.getParent());
values.put("title", category.getTitle());
values.put("image_url", category.getImage_name());
values.put("last_modified", category.getLast_modified());
String columns = getColumns(values.keySet());
insert("categories", columns, values);
}
// private static boolean isCategoryAvailable(int code) {
// Category shop = selectCategory(code);
// return shop != null;
// }
public static Category selectCategory(int id) {
String query = "select * from categories where id = " + id;
ArrayList<Category> shops = select_Category(query);
if (shops != null && shops.size() > 0)
return shops.get(0);
return null;
}
private static ArrayList<Category> select_Category(String query) {
Cursor cursor = select(query);
if (cursor == null)
return null;
if (!cursor.moveToFirst() || cursor.getCount() == 0) {
cursor.close();
return null;
}
ArrayList<Category> data = new ArrayList<>();
while (!cursor.isAfterLast()) {
Category category = new Category();
category.setId(getInt(cursor, "id"));
category.setTitle(getString(cursor, "title"));
category.setParent(getInt(cursor, "parent"));
category.setLast_modified(getString(cursor, "last_modified"));
category.setImage_name(getString(cursor, "image_url"));
data.add(category);
cursor.moveToNext();
}
cursor.close();
return data;
}
public static boolean InsertOrUpdateBrand(Brand brand) {
if (!isBrandAvailable(brand.getId())) {
long l = insertBrand(brand);
return l != -1;
} else
updateBrand(brand);
return true;
}
private static void updateBrand(Brand brand) {
ContentValues values = new ContentValues();
// values.put("id", brand.getId());
values.put("image_url", brand.getImage_name());
values.put("title", brand.getTitle());
update("brands", values, "id=" + brand.getId(), null);
}
private static long insertBrand(Brand brand) {
ContentValues values = new ContentValues();
values.put("id", brand.getId());
values.put("image_url", brand.getImage_name());
values.put("title", brand.getTitle());
String columns = getColumns(values.keySet());
return insert("brands", columns, values);
}
private static boolean isBrandAvailable(int id) {
Brand ad = selectBrand(id);
return ad != null;
}
private static Brand selectBrand(int id) {
String query = "select * from brands where id = " + id;
ArrayList<Brand> ads = select_Brands(query);
if (ads != null && ads.size() > 0)
return ads.get(0);
return null;
}
public static String selectLastModifiedBrandTime() {
return null;
}
public static String selectLastModifiedAdTime() {
return null;
}
public static void InsertOrUpdateAd(Advertisement advertisement) {
if (!isAdAvailable(advertisement.getId()))
insertAd(advertisement);
else
updateAd(advertisement);
}
private static void updateAd(Advertisement advertisement) {
ContentValues values = new ContentValues();
values.put("image_url", advertisement.getImage_name());
values.put("last_modified", advertisement.getLast_modified());
values.put("type", advertisement.getType());
values.put("shop_id", advertisement.getShop_id());
update("ads", values, "id=" + advertisement.getId(), null);
}
private static void insertAd(Advertisement advertisement) {
ContentValues values = new ContentValues();
values.put("id", advertisement.getId());
values.put("image_url", advertisement.getImage_name());
values.put("last_modified", advertisement.getLast_modified());
values.put("type", advertisement.getType());
values.put("shop_id", advertisement.getShop_id());
String columns = getColumns(values.keySet());
insert("ads", columns, values);
}
private static boolean isAdAvailable(int id) {
Advertisement ad = selectAd(id);
return ad != null;
}
private static Advertisement selectAd(int id) {
String query = "select * from ads where id = " + id;
ArrayList<Advertisement> ads = select_Ad(query);
if (ads != null && ads.size() > 0)
return ads.get(0);
return null;
}
private static ArrayList<Advertisement> select_Ad(String query) {
Cursor cursor = select(query);
if (cursor == null)
return null;
if (!cursor.moveToFirst() || cursor.getCount() == 0) {
cursor.close();
return null;
}
ArrayList<Advertisement> data = new ArrayList<>();
while (!cursor.isAfterLast()) {
Advertisement ad = new Advertisement();
ad.setId(getInt(cursor, "id"));
ad.setLast_modified(getString(cursor, "last_modified"));
ad.setImage_name(getString(cursor, "image_url"));
ad.setType(getInt(cursor, "type"));
ad.setShop_id(getInt(cursor, "shop_id"));
data.add(ad);
cursor.moveToNext();
}
cursor.close();
return data;
}
public static ArrayList<Advertisement> selectAds() {
String query = "select * from Ads";
return select_Ads(query);
}
private static ArrayList<Advertisement> select_Ads(String query) {
Cursor cursor = select(query);
if (cursor == null)
return null;
if (!cursor.moveToFirst() || cursor.getCount() == 0) {
cursor.close();
return null;
}
ArrayList<Advertisement> data = new ArrayList<>();
while (!cursor.isAfterLast()) {
Advertisement advertisement = new Advertisement();
advertisement.setId(getInt(cursor, "id"));
advertisement.setType(getInt(cursor, "type"));
advertisement.setImage_name(getString(cursor, "image_url"));
advertisement.setShop_id(getInt(cursor, "shop_id"));
advertisement.setLast_modified(getString(cursor, "last_modified"));
data.add(advertisement);
cursor.moveToNext();
}
cursor.close();
return data;
}
public static void deleteBrands() {
delete("brands", "", null);
}
public static void deleteCategories() {
delete("categories", "", null);
}
public static void deleteAds() {
delete("ads", "", null);
}
public static ArrayList<Brand> selectBrands() {
String query = "select * from brands";
return select_Brands(query);
}
private static ArrayList<Brand> select_Brands(String query) {
Cursor cursor = select(query);
if (cursor == null)
return null;
if (!cursor.moveToFirst() || cursor.getCount() == 0) {
cursor.close();
return null;
}
ArrayList<Brand> data = new ArrayList<>();
while (!cursor.isAfterLast()) {
Brand brand = new Brand();
brand.setId(getInt(cursor, "id"));
brand.setTitle(getString(cursor, "title"));
brand.setImage_name(getString(cursor, "image_url"));
data.add(brand);
cursor.moveToNext();
}
cursor.close();
return data;
}
public static ArrayList<Category> selectCategories() {
String query = "select * from categories";
return select_Category(query);
}
public static ArrayList<Category> selectCategories(int parent) {
String query = "select * from categories where parent=" + parent;
return select_Category(query);
}
public static ArrayList<Product> selectProducts() {
return null;
}
public static ArrayList<Shop> selectShops() {
String query = "select * from shops";
Cursor cursor = select(query);
if (cursor == null || cursor.getCount() < 1 || !cursor.moveToFirst())
return null;
ArrayList<Shop> shops = new ArrayList<>();
while (!cursor.isAfterLast()) {
Shop shop = new Shop();
shop.setId(getInt(cursor, "id"));
shop.setTitle(getString(cursor, "Title"));
shop.setAddress(getString(cursor, "Address"));
shop.setMedal(getInt(cursor, "Medal"));
shop.setScore(Float.parseFloat(getString(cursor, "Score")));
shops.add(shop);
cursor.moveToNext();
}
return shops;
}
public static boolean isShopBookmarked(int shopId) {
String query = "select id from shops where id=" + shopId;
Cursor select = select(query);
return !(select == null || select.getCount() < 1 || !select.moveToFirst());
}
public static void deleteShop(int shop_id) {
delete("shops", "id=" + shop_id, null);
}
public static ArrayList<String> getImageNames(int shop_id) {
String query = "select * from shopImages where shop_id=" + shop_id;
Cursor cursor = select(query);
if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
ArrayList<String> images = new ArrayList<>();
while (!cursor.isAfterLast()) {
images.add(getString(cursor, "img_name"));
cursor.moveToNext();
}
return images;
}
return null;
}
public static void insertImageName(int shop_id, String img_name) {
ContentValues values = new ContentValues();
values.put("shop_id", shop_id);
values.put("img_name", img_name);
insert("shopImages", getColumns(values.keySet()), values);
}
public static void deleteShopImage(int shop_id, String image_name) {
delete("shopImages", "shop_id=" + shop_id + " and img_name='" + image_name + "'", null);
}
public static void insertStaff(Staff staff) {
ContentValues values = new ContentValues();
values.put("name", staff.getName());
values.put("image_name", staff.getImg_name());
values.put("post", staff.getPost());
insert("staff", getColumns(values.keySet()), values);
}
public static void insertShop(ShopInfo shopInfo, int id) {
ContentValues values = new ContentValues();
values.put("id", id);
values.put("RegisterDate", shopInfo.getRegister_date());
values.put("GuildType", shopInfo.getGuild_type());
values.put("Title", shopInfo.getName());
values.put("Address", shopInfo.getAddress());
values.put("Medal", shopInfo.getMedal());
values.put("ImgName", shopInfo.getIcon_url());
values.put("Website", shopInfo.getWebsite());
values.put("Email", shopInfo.getEmail());
values.put("ShopTel", shopInfo.getPhone());
values.put("Score", shopInfo.getScore());
values.put("VoteCount", shopInfo.getVote_count());
values.put("AdminName", shopInfo.getAdmin_name());
values.put("ImgAdmin", shopInfo.getAdmin_image());
values.put("Services", shopInfo.getService_description());
values.put("Open", shopInfo.isOpen());
values.put("LicenseNumber", shopInfo.getLicense_number());
insert("shops", getColumns(values.keySet()), values);
}
public static boolean isProductBookmarked(int id) {
String query = "select id from products where id=" + id;
Cursor select = select(query);
return !(select == null || select.getCount() < 1 || !select.moveToFirst());
}
public static void deleteProduct(int id) {
delete("products", "id=" + id, null);
}
public static void insertProduct(
int id,
String title,
String main_image,
int price,
int discount) {
ContentValues values = new ContentValues();
values.put("id", id);
values.put("title", title);
values.put("main_image", main_image);
values.put("price", price);
values.put("discount", discount);
insert("products", getColumns(values.keySet()), values);
}
}
| UTF-8 | Java | 16,302 | java | DataBase.java | Java | [
{
"context": "p;\nimport models.shop.ShopInfo;\n\n/**\n * Created by omid' on 5/9/2017.\n */\n\npublic class DataBase {\n\n pr",
"end": 497,
"score": 0.9994730949401855,
"start": 493,
"tag": "USERNAME",
"value": "omid"
}
] | null | [] | package database;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
import com.tnt.ibazaar.Application;
import java.io.File;
import java.util.ArrayList;
import java.util.Set;
import models.Advertisement;
import models.Brand;
import models.Category;
import models.Product;
import models.Staff;
import models.shop.Shop;
import models.shop.ShopInfo;
/**
* Created by omid' on 5/9/2017.
*/
public class DataBase {
private static final String dirsd = Environment.getExternalStorageDirectory().getAbsolutePath();
private static final String dirdb = dirsd + "/android/data/" + Application.getPackageName2();
private static SQLiteDatabase db;
private static void openOrCreate() {
File filedb = new File(dirdb);
filedb.mkdirs();
filedb.setWritable(true);
filedb.setReadable(true);
File db2 = new File(dirdb + "/db.db");
Log.e("dp path", dirdb + " exists? " + db2.exists());
try {
db = SQLiteDatabase.openOrCreateDatabase(dirdb + "/db.db", null);
} catch (Exception e) {
Log.e("db open error", "" + e.getMessage());
}
}
private static long insert(String tableName, String columnNames, ContentValues values) {
if (db == null)
openOrCreate();
return db.insert(tableName, columnNames, values);
}
private static void update(String tableName, ContentValues values, String whereCluase, String[] whereArgs) {
if (db == null)
openOrCreate();
db.update(tableName, values, whereCluase, whereArgs);
}
private static void delete(String tableName, String whereCluase, String[] whereArgs) {
if (db == null)
openOrCreate();
db.delete(tableName, whereCluase, whereArgs);
}
private static Cursor select(String query) {
if (db == null)
openOrCreate();
return db.rawQuery(query, null);
}
private static int getInt(Cursor cursor, String columnName) {
return cursor.getInt(cursor.getColumnIndex(columnName));
}
private static String getString(Cursor cursor, String columnName) {
return cursor.getString(cursor.getColumnIndex(columnName));
}
private static String getColumns(Set<String> strings) {
String columns = "";
if (strings != null)
for (String s : strings)
columns += s;
return columns;
}
// public static String selectLastModifiedCategoryTime() {
// String query = "select max(last_modified) from categories";
// Cursor select = select(query);
// if (select == null || select.moveToFirst() || select.getCount() == 0) {
// return "0";
// }
// return select.getString(0) == null ? "0" : select.getString(0);
// }
// public static void InsertOrUpdateCategory(Category category) {
// if (!isCategoryAvailable(category.getId()))
// insertCategory(category);
// else
// updateCategories(category);
// }
// private static void updateCategories(Category category) {
// ContentValues values = new ContentValues();
//// values.put("code", category.getId());
// values.put("parent", category.getParent());
// values.put("title", category.getTitle());
// values.put("image_url", category.getImage_name());
// values.put("last_modified", category.getLast_modified());
//
// update("categories", values, " id=" + category.getId(), null);
// }
public static void insertCategory(Category category) {
ContentValues values = new ContentValues();
values.put("id", category.getId());
values.put("parent", category.getParent());
values.put("title", category.getTitle());
values.put("image_url", category.getImage_name());
values.put("last_modified", category.getLast_modified());
String columns = getColumns(values.keySet());
insert("categories", columns, values);
}
// private static boolean isCategoryAvailable(int code) {
// Category shop = selectCategory(code);
// return shop != null;
// }
public static Category selectCategory(int id) {
String query = "select * from categories where id = " + id;
ArrayList<Category> shops = select_Category(query);
if (shops != null && shops.size() > 0)
return shops.get(0);
return null;
}
private static ArrayList<Category> select_Category(String query) {
Cursor cursor = select(query);
if (cursor == null)
return null;
if (!cursor.moveToFirst() || cursor.getCount() == 0) {
cursor.close();
return null;
}
ArrayList<Category> data = new ArrayList<>();
while (!cursor.isAfterLast()) {
Category category = new Category();
category.setId(getInt(cursor, "id"));
category.setTitle(getString(cursor, "title"));
category.setParent(getInt(cursor, "parent"));
category.setLast_modified(getString(cursor, "last_modified"));
category.setImage_name(getString(cursor, "image_url"));
data.add(category);
cursor.moveToNext();
}
cursor.close();
return data;
}
public static boolean InsertOrUpdateBrand(Brand brand) {
if (!isBrandAvailable(brand.getId())) {
long l = insertBrand(brand);
return l != -1;
} else
updateBrand(brand);
return true;
}
private static void updateBrand(Brand brand) {
ContentValues values = new ContentValues();
// values.put("id", brand.getId());
values.put("image_url", brand.getImage_name());
values.put("title", brand.getTitle());
update("brands", values, "id=" + brand.getId(), null);
}
private static long insertBrand(Brand brand) {
ContentValues values = new ContentValues();
values.put("id", brand.getId());
values.put("image_url", brand.getImage_name());
values.put("title", brand.getTitle());
String columns = getColumns(values.keySet());
return insert("brands", columns, values);
}
private static boolean isBrandAvailable(int id) {
Brand ad = selectBrand(id);
return ad != null;
}
private static Brand selectBrand(int id) {
String query = "select * from brands where id = " + id;
ArrayList<Brand> ads = select_Brands(query);
if (ads != null && ads.size() > 0)
return ads.get(0);
return null;
}
public static String selectLastModifiedBrandTime() {
return null;
}
public static String selectLastModifiedAdTime() {
return null;
}
public static void InsertOrUpdateAd(Advertisement advertisement) {
if (!isAdAvailable(advertisement.getId()))
insertAd(advertisement);
else
updateAd(advertisement);
}
private static void updateAd(Advertisement advertisement) {
ContentValues values = new ContentValues();
values.put("image_url", advertisement.getImage_name());
values.put("last_modified", advertisement.getLast_modified());
values.put("type", advertisement.getType());
values.put("shop_id", advertisement.getShop_id());
update("ads", values, "id=" + advertisement.getId(), null);
}
private static void insertAd(Advertisement advertisement) {
ContentValues values = new ContentValues();
values.put("id", advertisement.getId());
values.put("image_url", advertisement.getImage_name());
values.put("last_modified", advertisement.getLast_modified());
values.put("type", advertisement.getType());
values.put("shop_id", advertisement.getShop_id());
String columns = getColumns(values.keySet());
insert("ads", columns, values);
}
private static boolean isAdAvailable(int id) {
Advertisement ad = selectAd(id);
return ad != null;
}
private static Advertisement selectAd(int id) {
String query = "select * from ads where id = " + id;
ArrayList<Advertisement> ads = select_Ad(query);
if (ads != null && ads.size() > 0)
return ads.get(0);
return null;
}
private static ArrayList<Advertisement> select_Ad(String query) {
Cursor cursor = select(query);
if (cursor == null)
return null;
if (!cursor.moveToFirst() || cursor.getCount() == 0) {
cursor.close();
return null;
}
ArrayList<Advertisement> data = new ArrayList<>();
while (!cursor.isAfterLast()) {
Advertisement ad = new Advertisement();
ad.setId(getInt(cursor, "id"));
ad.setLast_modified(getString(cursor, "last_modified"));
ad.setImage_name(getString(cursor, "image_url"));
ad.setType(getInt(cursor, "type"));
ad.setShop_id(getInt(cursor, "shop_id"));
data.add(ad);
cursor.moveToNext();
}
cursor.close();
return data;
}
public static ArrayList<Advertisement> selectAds() {
String query = "select * from Ads";
return select_Ads(query);
}
private static ArrayList<Advertisement> select_Ads(String query) {
Cursor cursor = select(query);
if (cursor == null)
return null;
if (!cursor.moveToFirst() || cursor.getCount() == 0) {
cursor.close();
return null;
}
ArrayList<Advertisement> data = new ArrayList<>();
while (!cursor.isAfterLast()) {
Advertisement advertisement = new Advertisement();
advertisement.setId(getInt(cursor, "id"));
advertisement.setType(getInt(cursor, "type"));
advertisement.setImage_name(getString(cursor, "image_url"));
advertisement.setShop_id(getInt(cursor, "shop_id"));
advertisement.setLast_modified(getString(cursor, "last_modified"));
data.add(advertisement);
cursor.moveToNext();
}
cursor.close();
return data;
}
public static void deleteBrands() {
delete("brands", "", null);
}
public static void deleteCategories() {
delete("categories", "", null);
}
public static void deleteAds() {
delete("ads", "", null);
}
public static ArrayList<Brand> selectBrands() {
String query = "select * from brands";
return select_Brands(query);
}
private static ArrayList<Brand> select_Brands(String query) {
Cursor cursor = select(query);
if (cursor == null)
return null;
if (!cursor.moveToFirst() || cursor.getCount() == 0) {
cursor.close();
return null;
}
ArrayList<Brand> data = new ArrayList<>();
while (!cursor.isAfterLast()) {
Brand brand = new Brand();
brand.setId(getInt(cursor, "id"));
brand.setTitle(getString(cursor, "title"));
brand.setImage_name(getString(cursor, "image_url"));
data.add(brand);
cursor.moveToNext();
}
cursor.close();
return data;
}
public static ArrayList<Category> selectCategories() {
String query = "select * from categories";
return select_Category(query);
}
public static ArrayList<Category> selectCategories(int parent) {
String query = "select * from categories where parent=" + parent;
return select_Category(query);
}
public static ArrayList<Product> selectProducts() {
return null;
}
public static ArrayList<Shop> selectShops() {
String query = "select * from shops";
Cursor cursor = select(query);
if (cursor == null || cursor.getCount() < 1 || !cursor.moveToFirst())
return null;
ArrayList<Shop> shops = new ArrayList<>();
while (!cursor.isAfterLast()) {
Shop shop = new Shop();
shop.setId(getInt(cursor, "id"));
shop.setTitle(getString(cursor, "Title"));
shop.setAddress(getString(cursor, "Address"));
shop.setMedal(getInt(cursor, "Medal"));
shop.setScore(Float.parseFloat(getString(cursor, "Score")));
shops.add(shop);
cursor.moveToNext();
}
return shops;
}
public static boolean isShopBookmarked(int shopId) {
String query = "select id from shops where id=" + shopId;
Cursor select = select(query);
return !(select == null || select.getCount() < 1 || !select.moveToFirst());
}
public static void deleteShop(int shop_id) {
delete("shops", "id=" + shop_id, null);
}
public static ArrayList<String> getImageNames(int shop_id) {
String query = "select * from shopImages where shop_id=" + shop_id;
Cursor cursor = select(query);
if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
ArrayList<String> images = new ArrayList<>();
while (!cursor.isAfterLast()) {
images.add(getString(cursor, "img_name"));
cursor.moveToNext();
}
return images;
}
return null;
}
public static void insertImageName(int shop_id, String img_name) {
ContentValues values = new ContentValues();
values.put("shop_id", shop_id);
values.put("img_name", img_name);
insert("shopImages", getColumns(values.keySet()), values);
}
public static void deleteShopImage(int shop_id, String image_name) {
delete("shopImages", "shop_id=" + shop_id + " and img_name='" + image_name + "'", null);
}
public static void insertStaff(Staff staff) {
ContentValues values = new ContentValues();
values.put("name", staff.getName());
values.put("image_name", staff.getImg_name());
values.put("post", staff.getPost());
insert("staff", getColumns(values.keySet()), values);
}
public static void insertShop(ShopInfo shopInfo, int id) {
ContentValues values = new ContentValues();
values.put("id", id);
values.put("RegisterDate", shopInfo.getRegister_date());
values.put("GuildType", shopInfo.getGuild_type());
values.put("Title", shopInfo.getName());
values.put("Address", shopInfo.getAddress());
values.put("Medal", shopInfo.getMedal());
values.put("ImgName", shopInfo.getIcon_url());
values.put("Website", shopInfo.getWebsite());
values.put("Email", shopInfo.getEmail());
values.put("ShopTel", shopInfo.getPhone());
values.put("Score", shopInfo.getScore());
values.put("VoteCount", shopInfo.getVote_count());
values.put("AdminName", shopInfo.getAdmin_name());
values.put("ImgAdmin", shopInfo.getAdmin_image());
values.put("Services", shopInfo.getService_description());
values.put("Open", shopInfo.isOpen());
values.put("LicenseNumber", shopInfo.getLicense_number());
insert("shops", getColumns(values.keySet()), values);
}
public static boolean isProductBookmarked(int id) {
String query = "select id from products where id=" + id;
Cursor select = select(query);
return !(select == null || select.getCount() < 1 || !select.moveToFirst());
}
public static void deleteProduct(int id) {
delete("products", "id=" + id, null);
}
public static void insertProduct(
int id,
String title,
String main_image,
int price,
int discount) {
ContentValues values = new ContentValues();
values.put("id", id);
values.put("title", title);
values.put("main_image", main_image);
values.put("price", price);
values.put("discount", discount);
insert("products", getColumns(values.keySet()), values);
}
}
| 16,302 | 0.595019 | 0.59324 | 482 | 32.821575 | 24.678793 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.848548 | false | false | 9 |
d38c6762331036caee255ca149cc28a957bbfc7c | 27,419,071,233,620 | 46f027f52ee1eedc4905e06cbaecbc928c38df79 | /src/main/java/com/ercifenpeixitong/ercifenpeixitong/domain/Role.java | 13c62e1754f06800341ab58a4131ea5afac61b11 | [] | no_license | duanlongjie/ercifenpeixitong | https://github.com/duanlongjie/ercifenpeixitong | 551a4a7d0354ada1f4d5f830263b8250068d0ce7 | 398100441e1adfcb8f843970db9e3a9a6ee368e7 | refs/heads/master | 2020-03-22T03:54:00.469000 | 2018-07-06T02:10:03 | 2018-07-06T02:10:03 | 139,458,985 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ercifenpeixitong.ercifenpeixitong.domain;
import org.hibernate.validator.constraints.EAN;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* 角色和权限是多对多关系
*/
@Entity
@Table(name = "ec_role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String roleName;
@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private List<Permission> permissions =new ArrayList<>();
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", permissions=" + permissions +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<Permission> getPermissions() {
return permissions;
}
public void setPermissions(List<Permission> permissions) {
this.permissions = permissions;
}
}
| UTF-8 | Java | 1,224 | java | Role.java | Java | [] | null | [] | package com.ercifenpeixitong.ercifenpeixitong.domain;
import org.hibernate.validator.constraints.EAN;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* 角色和权限是多对多关系
*/
@Entity
@Table(name = "ec_role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String roleName;
@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private List<Permission> permissions =new ArrayList<>();
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", permissions=" + permissions +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<Permission> getPermissions() {
return permissions;
}
public void setPermissions(List<Permission> permissions) {
this.permissions = permissions;
}
}
| 1,224 | 0.608985 | 0.608985 | 55 | 20.854546 | 19.309364 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.327273 | false | false | 9 |
3d02027dfc246890689368abf068dee656248974 | 21,569,325,814,258 | a89809a46292426d161ee118eb93f8a9aab6128f | /src/main/java/br/com/wellington/desafiocreditas/model/Cliente.java | 415c02f8466f354c98cd26e649db77329e83d91c | [] | no_license | wdivino/desafio-emprestimos | https://github.com/wdivino/desafio-emprestimos | 0ba319d102375d4ac906da82dd007bbc8949a0dc | 8219f864994e8ec05a3fbbc2939ab5249129ed57 | refs/heads/master | 2023-05-03T01:13:11.657000 | 2020-10-30T14:46:46 | 2020-10-30T14:46:46 | 305,853,312 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.wellington.desafiocreditas.model;
import java.math.BigDecimal;
public class Cliente {
private String nome;
private String cpf;
private String localizacao;
private int idade;
private BigDecimal renda;
public boolean comRendaMaiorQue(int rendaLimite) {
return this.renda.compareTo(new BigDecimal(rendaLimite)) > 0;
}
public boolean comRendaMenorOuIgual(int rendaLimite) {
return this.renda.compareTo(new BigDecimal(rendaLimite)) <= 0;
}
public boolean comIdadeMaiorQue(int idadeLimite) {
return this.idade > idadeLimite;
}
public boolean comIdadeMenorQue(int idadeLimite) {
return this.idade < idadeLimite;
}
public boolean resideEm(String localizacao) {
return this.localizacao.toUpperCase().equalsIgnoreCase(localizacao.toUpperCase());
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public void setLocalizacao(String localizacao) {
this.localizacao = localizacao;
}
public void setIdade(int idade) {
this.idade = idade;
}
public void setRenda(BigDecimal renda) {
this.renda = renda;
}
}
| UTF-8 | Java | 1,314 | java | Cliente.java | Java | [
{
"context": "package br.com.wellington.desafiocreditas.model;\n\nimport java.math.BigDecim",
"end": 25,
"score": 0.7458450198173523,
"start": 15,
"tag": "USERNAME",
"value": "wellington"
}
] | null | [] | package br.com.wellington.desafiocreditas.model;
import java.math.BigDecimal;
public class Cliente {
private String nome;
private String cpf;
private String localizacao;
private int idade;
private BigDecimal renda;
public boolean comRendaMaiorQue(int rendaLimite) {
return this.renda.compareTo(new BigDecimal(rendaLimite)) > 0;
}
public boolean comRendaMenorOuIgual(int rendaLimite) {
return this.renda.compareTo(new BigDecimal(rendaLimite)) <= 0;
}
public boolean comIdadeMaiorQue(int idadeLimite) {
return this.idade > idadeLimite;
}
public boolean comIdadeMenorQue(int idadeLimite) {
return this.idade < idadeLimite;
}
public boolean resideEm(String localizacao) {
return this.localizacao.toUpperCase().equalsIgnoreCase(localizacao.toUpperCase());
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public void setLocalizacao(String localizacao) {
this.localizacao = localizacao;
}
public void setIdade(int idade) {
this.idade = idade;
}
public void setRenda(BigDecimal renda) {
this.renda = renda;
}
}
| 1,314 | 0.661339 | 0.659817 | 56 | 22.464285 | 22.589476 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.321429 | false | false | 9 |
044287600e6a2505c759016a668986f9432b4603 | 24,137,716,267,429 | 56ed42bdddeeaa9ff36b6b833534a68d98ff9381 | /src/main/java/com/rain/fabricdemo/handler/FirstSampleHandler.java | 7e3dbc317bb8411342e94264be26f0369094f813 | [] | no_license | SirRainman/fabricdemo-sdk | https://github.com/SirRainman/fabricdemo-sdk | 004955add9f244244e260181ada19a96110d22df | c68325e0202e298fa07ccb03eb02008c6bbf55d5 | refs/heads/master | 2023-02-21T20:02:39.519000 | 2021-01-29T09:24:26 | 2021-01-29T09:24:26 | 302,256,789 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rain.fabricdemo.handler;
import com.rain.fabricdemo.dto.DataItem;
import com.rain.fabricdemo.handler.SimpleStreamDataHandler;
import com.rain.fabricdemo.ledger.QueryLedger;
import org.hyperledger.fabric.gateway.*;
import org.hyperledger.fabric.gateway.impl.GatewayImpl;
import org.hyperledger.fabric.sdk.Channel;
import org.hyperledger.fabric.sdk.Peer;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.LinkedList;
public class FirstSampleHandler extends SimpleStreamDataHandler {
private static final Object lock = new Object();
long searchTimesInOrg1 = 0;
long searchTimesInOrg2 = 0;
// connection.json 里应该配置网络信息
private static final Path NETWORK_CONFIG_PATH = Paths.get("src", "main", "resources", "connection.json");
// 证书的位置
private static final Path credentialPath = Paths.get("src", "main", "resources", "crypto-config",
"peerOrganizations", "org1.example.com", "users", "Admin@org1.example.com", "msp");
private X509Certificate certificate;
private PrivateKey privateKey;
private Wallet wallet;
private Gateway gateway;
private Gateway.Builder builder;
private Network network;
private Channel channel;
private Contract contract;
private Collection<Peer> peerSet;
public FirstSampleHandler() {
try {
this.certificate = readX509Certificate(credentialPath.resolve(Paths.get("signcerts", "Admin@org1.example.com-cert.pem")));
this.privateKey = getPrivateKey(credentialPath.resolve(Paths.get("keystore", "priv_sk")));
// 加载一个钱包,里面有接入网络所需要的identities
this.wallet = Wallets.newInMemoryWallet();
// Path walletDir = Paths.get("wallet");
// Wallet wallet = Wallets.newFileSystemWallet(walletDir);
this.wallet.put("user", Identities.newX509Identity("Org1MSP", certificate, privateKey));
} catch (Exception e) {
System.out.println("读证书错误");
e.printStackTrace();
}
try {
// 设置连接网络所需要的gateway connection配置信息
this.builder = Gateway.createBuilder()
.identity(this.wallet, "user")
.networkConfig(NETWORK_CONFIG_PATH);
// 创建Gateway连接
this.gateway = builder.connect();
// 接入channel
this.network = gateway.getNetwork("mychannel");
this.channel = network.getChannel();
this.contract = network.getContract("mycc");
this.peerSet = channel.getPeers();
} catch (Exception e) {
System.out.println("连接错误");
e.printStackTrace();
}
}
private static X509Certificate readX509Certificate(final Path certificatePath) throws IOException, CertificateException {
try (Reader certificateReader = Files.newBufferedReader(certificatePath, StandardCharsets.UTF_8)) {
return Identities.readX509Certificate(certificateReader);
}
}
private static PrivateKey getPrivateKey(final Path privateKeyPath) throws IOException, InvalidKeyException {
try (Reader privateKeyReader = Files.newBufferedReader(privateKeyPath, StandardCharsets.UTF_8)) {
return Identities.readPrivateKey(privateKeyReader);
}
}
@Override
public void handle(DataItem in) {
Collection<Peer> endorserSet = new LinkedList<>();
// System.out.println("Handle time: " + new Date().toString());
// if (searchTimesInOrg1 < searchTimesInOrg2) {
// searchTimesInOrg1++;
// for (Peer peer : this.peerSet) {
// if (peer.getName().equals("peer0.org1.example.com")) {
// endorserSet.add(peer);
// break;
// }
// }
// } else {
// searchTimesInOrg2++;
// for (Peer peer : this.peerSet) {
// if (peer.getName().equals("peer0.org2.example.com")) {
// endorserSet.add(peer);
// break;
// }
// }
// }
// 只添加peer0.org1.com
for (Peer peer : this.peerSet) {
if (peer.getName().equals("peer0.org1.example.com") || peer.getName().equals("peer0.org2.example.com")) {
endorserSet.add(peer);
//System.out.println(peer.getName());
}
}
switch (in.operation) {
case "query":
QueryLedger.queryInPeers((GatewayImpl) gateway, channel, endorserSet, in.from);
break;
case "Init":
QueryLedger.initInPeers(contract, this.peerSet, ""+System.currentTimeMillis());
break;
default:
}
}
}
| GB18030 | Java | 5,354 | java | FirstSampleHandler.java | Java | [
{
"context": "peerOrganizations\", \"org1.example.com\", \"users\", \"Admin@org1.example.com\", \"msp\");\r\n\r\n private X509Certificate certific",
"end": 1327,
"score": 0.9998791217803955,
"start": 1305,
"tag": "EMAIL",
"value": "Admin@org1.example.com"
},
{
"context": "te(credentialPath.resolve(Paths.get(\"signcerts\", \"Admin@org1.example.com-cert.pem\")));\r\n this.privateKey = getP",
"end": 1818,
"score": 0.9995681047439575,
"start": 1796,
"tag": "EMAIL",
"value": "Admin@org1.example.com"
}
] | null | [] | package com.rain.fabricdemo.handler;
import com.rain.fabricdemo.dto.DataItem;
import com.rain.fabricdemo.handler.SimpleStreamDataHandler;
import com.rain.fabricdemo.ledger.QueryLedger;
import org.hyperledger.fabric.gateway.*;
import org.hyperledger.fabric.gateway.impl.GatewayImpl;
import org.hyperledger.fabric.sdk.Channel;
import org.hyperledger.fabric.sdk.Peer;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.LinkedList;
public class FirstSampleHandler extends SimpleStreamDataHandler {
private static final Object lock = new Object();
long searchTimesInOrg1 = 0;
long searchTimesInOrg2 = 0;
// connection.json 里应该配置网络信息
private static final Path NETWORK_CONFIG_PATH = Paths.get("src", "main", "resources", "connection.json");
// 证书的位置
private static final Path credentialPath = Paths.get("src", "main", "resources", "crypto-config",
"peerOrganizations", "org1.example.com", "users", "<EMAIL>", "msp");
private X509Certificate certificate;
private PrivateKey privateKey;
private Wallet wallet;
private Gateway gateway;
private Gateway.Builder builder;
private Network network;
private Channel channel;
private Contract contract;
private Collection<Peer> peerSet;
public FirstSampleHandler() {
try {
this.certificate = readX509Certificate(credentialPath.resolve(Paths.get("signcerts", "<EMAIL>-cert.pem")));
this.privateKey = getPrivateKey(credentialPath.resolve(Paths.get("keystore", "priv_sk")));
// 加载一个钱包,里面有接入网络所需要的identities
this.wallet = Wallets.newInMemoryWallet();
// Path walletDir = Paths.get("wallet");
// Wallet wallet = Wallets.newFileSystemWallet(walletDir);
this.wallet.put("user", Identities.newX509Identity("Org1MSP", certificate, privateKey));
} catch (Exception e) {
System.out.println("读证书错误");
e.printStackTrace();
}
try {
// 设置连接网络所需要的gateway connection配置信息
this.builder = Gateway.createBuilder()
.identity(this.wallet, "user")
.networkConfig(NETWORK_CONFIG_PATH);
// 创建Gateway连接
this.gateway = builder.connect();
// 接入channel
this.network = gateway.getNetwork("mychannel");
this.channel = network.getChannel();
this.contract = network.getContract("mycc");
this.peerSet = channel.getPeers();
} catch (Exception e) {
System.out.println("连接错误");
e.printStackTrace();
}
}
private static X509Certificate readX509Certificate(final Path certificatePath) throws IOException, CertificateException {
try (Reader certificateReader = Files.newBufferedReader(certificatePath, StandardCharsets.UTF_8)) {
return Identities.readX509Certificate(certificateReader);
}
}
private static PrivateKey getPrivateKey(final Path privateKeyPath) throws IOException, InvalidKeyException {
try (Reader privateKeyReader = Files.newBufferedReader(privateKeyPath, StandardCharsets.UTF_8)) {
return Identities.readPrivateKey(privateKeyReader);
}
}
@Override
public void handle(DataItem in) {
Collection<Peer> endorserSet = new LinkedList<>();
// System.out.println("Handle time: " + new Date().toString());
// if (searchTimesInOrg1 < searchTimesInOrg2) {
// searchTimesInOrg1++;
// for (Peer peer : this.peerSet) {
// if (peer.getName().equals("peer0.org1.example.com")) {
// endorserSet.add(peer);
// break;
// }
// }
// } else {
// searchTimesInOrg2++;
// for (Peer peer : this.peerSet) {
// if (peer.getName().equals("peer0.org2.example.com")) {
// endorserSet.add(peer);
// break;
// }
// }
// }
// 只添加peer0.org1.com
for (Peer peer : this.peerSet) {
if (peer.getName().equals("peer0.org1.example.com") || peer.getName().equals("peer0.org2.example.com")) {
endorserSet.add(peer);
//System.out.println(peer.getName());
}
}
switch (in.operation) {
case "query":
QueryLedger.queryInPeers((GatewayImpl) gateway, channel, endorserSet, in.from);
break;
case "Init":
QueryLedger.initInPeers(contract, this.peerSet, ""+System.currentTimeMillis());
break;
default:
}
}
}
| 5,324 | 0.608879 | 0.600268 | 133 | 37.293232 | 29.932451 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.706767 | false | false | 9 |
4b349cb5f57e9efce6a706938725e207df2a88c7 | 10,471,130,307,476 | fc92946efc6e3a50b2e11e4d56705c1de6aca212 | /DbBase/src/main/java/com/dbbase/log/LogUtil.java | 218c4c71f6ca7cca24ef6a26d9f2b490141b3263 | [] | no_license | leroyBoys/LWeb | https://github.com/leroyBoys/LWeb | 4ddb0a1693d18648101d7d9f29b1faf9f2437f5b | 76733e329947b822fbf8ee653c3571c145cb1295 | refs/heads/master | 2020-03-19T07:41:05.784000 | 2018-07-20T07:08:38 | 2018-07-20T07:08:38 | 136,139,252 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dbbase.log;
/**
* Created by leroy:656515489@qq.com
* 2018/6/19.
*/
public class LogUtil {
public static String getException(Exception e) {
StringBuilder bs = new StringBuilder();
StackTraceElement[] a = e.getStackTrace();
bs.append("\n Message: ").append(e.fillInStackTrace()).append("");
for (int i = 0; i < a.length; i++) {
bs.append("\n ").append(a[i].getClassName()).append("(Line:").append(a[i].getLineNumber()).append(",Method:").append(a[i].getMethodName()).append(")");
}
return bs.toString();
}
public static void log(Class cls,String info){
System.out.println(info);
}
public static void warn(Class cls,String info){
System.out.println(info);
}
public static void error(Class cls,String info){
System.err.println(info);
}
public static void error(Class cls,String info,Exception e){
e.printStackTrace();
System.out.println(info);
}
}
| UTF-8 | Java | 1,005 | java | LogUtil.java | Java | [
{
"context": "package com.dbbase.log;\n\n/**\n * Created by leroy:656515489@qq.com\n * 2018/6/19.\n */\npublic class L",
"end": 48,
"score": 0.9991106986999512,
"start": 43,
"tag": "USERNAME",
"value": "leroy"
},
{
"context": "package com.dbbase.log;\n\n/**\n * Created by leroy:656515489@qq.com\n * 2018/6/19.\n */\npublic class LogUtil {\n publ",
"end": 65,
"score": 0.9952402114868164,
"start": 49,
"tag": "EMAIL",
"value": "656515489@qq.com"
}
] | null | [] | package com.dbbase.log;
/**
* Created by leroy:<EMAIL>
* 2018/6/19.
*/
public class LogUtil {
public static String getException(Exception e) {
StringBuilder bs = new StringBuilder();
StackTraceElement[] a = e.getStackTrace();
bs.append("\n Message: ").append(e.fillInStackTrace()).append("");
for (int i = 0; i < a.length; i++) {
bs.append("\n ").append(a[i].getClassName()).append("(Line:").append(a[i].getLineNumber()).append(",Method:").append(a[i].getMethodName()).append(")");
}
return bs.toString();
}
public static void log(Class cls,String info){
System.out.println(info);
}
public static void warn(Class cls,String info){
System.out.println(info);
}
public static void error(Class cls,String info){
System.err.println(info);
}
public static void error(Class cls,String info,Exception e){
e.printStackTrace();
System.out.println(info);
}
}
| 996 | 0.60796 | 0.591045 | 34 | 28.558823 | 31.738075 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.558824 | false | false | 9 |
fe75ef7ab1ce66af0abdf0b94e2582e01ffbd4d4 | 9,869,834,853,027 | 13161a8c9b9ffd678bd1429a52d341b87bab8739 | /lib/src/main/java/com/csipsimple/ui/calllog/PhoneCallDetailsHelper.java | 333885692eec63a995d8eaf5091030c0d46a3821 | [] | no_license | xujichang/CSipSimple4As | https://github.com/xujichang/CSipSimple4As | 472b0f03b740e99e2e2f5bc6be052176d1496fa6 | 366cd4e13ac7986a65401de45b19add5b04afb1c | refs/heads/master | 2020-05-18T00:21:29.130000 | 2019-05-27T03:12:33 | 2019-05-27T03:12:33 | 184,059,244 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* This file contains relicensed code from som Apache copyright of
* Copyright (C) 2011, The Android Open Source Project
*/
package com.csipsimple.ui.calllog;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.TextView;
import me.xujichang.lib.csipsimple.R;
import com.csipsimple.api.SipUri;
/**
* Helper class to fill in the views in {@link PhoneCallDetailsViews}.
*/
public class PhoneCallDetailsHelper {
/**
* The maximum number of icons will be shown to represent the call types in
* a group.
*/
private static final int MAX_CALL_TYPE_ICONS = 3;
private final Resources mResources;
/**
* The injected current time in milliseconds since the epoch. Used only by
* tests.
*/
private Long mCurrentTimeMillisForTest;
/**
* Creates a new instance of the helper.
* <p>
* Generally you should have a single instance of this helper in any
* context.
*
* @param resources used to look up strings
*/
public PhoneCallDetailsHelper(Resources resources) {
mResources = resources;
}
/** Fills the call details views with content. */
public void setPhoneCallDetails(PhoneCallDetailsViews views, PhoneCallDetails details) {
// Display up to a given number of icons.
views.callTypeIcons.clear();
int count = details.callTypes.length;
for (int index = 0; index < count && index < MAX_CALL_TYPE_ICONS; ++index) {
views.callTypeIcons.add(details.callTypes[index]);
}
views.callTypeIcons.setVisibility(View.VISIBLE);
// Show the total call count only if there are more than the maximum
// number of icons.
Integer callCount;
if (count > MAX_CALL_TYPE_ICONS) {
callCount = count;
} else {
callCount = null;
}
// The date of this call, relative to the current time.
CharSequence dateText =
DateUtils.getRelativeTimeSpanString(details.date,
getCurrentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
// Set the call count and date.
setCallCountAndDate(views, callCount, dateText);
// Display number and display name
CharSequence displayName;
if (!TextUtils.isEmpty(details.name)) {
displayName = details.name;
} else {
// Try to fallback on number treat
if (!TextUtils.isEmpty(details.number)) {
displayName = SipUri.getDisplayedSimpleContact(details.number.toString());
// SipUri.getCanonicalSipContact(details.number.toString(),
// false);
} else {
displayName = mResources.getString(R.string.unknown);
}
if (!TextUtils.isEmpty(details.numberLabel)) {
SpannableString text = new SpannableString(details.numberLabel + " " + displayName);
text.setSpan(new StyleSpan(Typeface.BOLD), 0, details.numberLabel.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
displayName = text;
}
}
views.nameView.setText(displayName);
if (!TextUtils.isEmpty(details.formattedNumber)) {
views.numberView.setText(details.formattedNumber);
} else if (!TextUtils.isEmpty(details.number)) {
views.numberView.setText(details.number);
} else {
// In this case we can assume that display name was set to unknown
views.numberView.setText(displayName);
}
}
/** Sets the text of the header view for the details page of a phone call. */
public void setCallDetailsHeader(TextView nameView, PhoneCallDetails details) {
CharSequence nameText;
final CharSequence displayNumber = details.number;
if (TextUtils.isEmpty(details.name)) {
nameText = displayNumber;
} else {
nameText = details.name;
}
nameView.setText(nameText);
}
public void setCurrentTimeForTest(long currentTimeMillis) {
mCurrentTimeMillisForTest = currentTimeMillis;
}
/**
* Returns the current time in milliseconds since the epoch.
* <p>
* It can be injected in tests using {@link #setCurrentTimeForTest(long)}.
*/
private long getCurrentTimeMillis() {
if (mCurrentTimeMillisForTest == null) {
return System.currentTimeMillis();
} else {
return mCurrentTimeMillisForTest;
}
}
/** Sets the call count and date. */
private void setCallCountAndDate(PhoneCallDetailsViews views, Integer callCount,
CharSequence dateText) {
// Combine the count (if present) and the date.
CharSequence text;
if (callCount != null) {
text = mResources.getString(
R.string.call_log_item_count_and_date, callCount.intValue(), dateText);
} else {
text = dateText;
}
views.callTypeAndDate.setText(text);
}
}
| UTF-8 | Java | 6,340 | java | PhoneCallDetailsHelper.java | Java | [
{
"context": "/**\n * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)\n * This file is part o",
"end": 44,
"score": 0.9979718923568726,
"start": 31,
"tag": "NAME",
"value": "Regis Montoya"
}
] | null | [] | /**
* Copyright (C) 2010-2012 <NAME> (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* This file contains relicensed code from som Apache copyright of
* Copyright (C) 2011, The Android Open Source Project
*/
package com.csipsimple.ui.calllog;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.TextView;
import me.xujichang.lib.csipsimple.R;
import com.csipsimple.api.SipUri;
/**
* Helper class to fill in the views in {@link PhoneCallDetailsViews}.
*/
public class PhoneCallDetailsHelper {
/**
* The maximum number of icons will be shown to represent the call types in
* a group.
*/
private static final int MAX_CALL_TYPE_ICONS = 3;
private final Resources mResources;
/**
* The injected current time in milliseconds since the epoch. Used only by
* tests.
*/
private Long mCurrentTimeMillisForTest;
/**
* Creates a new instance of the helper.
* <p>
* Generally you should have a single instance of this helper in any
* context.
*
* @param resources used to look up strings
*/
public PhoneCallDetailsHelper(Resources resources) {
mResources = resources;
}
/** Fills the call details views with content. */
public void setPhoneCallDetails(PhoneCallDetailsViews views, PhoneCallDetails details) {
// Display up to a given number of icons.
views.callTypeIcons.clear();
int count = details.callTypes.length;
for (int index = 0; index < count && index < MAX_CALL_TYPE_ICONS; ++index) {
views.callTypeIcons.add(details.callTypes[index]);
}
views.callTypeIcons.setVisibility(View.VISIBLE);
// Show the total call count only if there are more than the maximum
// number of icons.
Integer callCount;
if (count > MAX_CALL_TYPE_ICONS) {
callCount = count;
} else {
callCount = null;
}
// The date of this call, relative to the current time.
CharSequence dateText =
DateUtils.getRelativeTimeSpanString(details.date,
getCurrentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
// Set the call count and date.
setCallCountAndDate(views, callCount, dateText);
// Display number and display name
CharSequence displayName;
if (!TextUtils.isEmpty(details.name)) {
displayName = details.name;
} else {
// Try to fallback on number treat
if (!TextUtils.isEmpty(details.number)) {
displayName = SipUri.getDisplayedSimpleContact(details.number.toString());
// SipUri.getCanonicalSipContact(details.number.toString(),
// false);
} else {
displayName = mResources.getString(R.string.unknown);
}
if (!TextUtils.isEmpty(details.numberLabel)) {
SpannableString text = new SpannableString(details.numberLabel + " " + displayName);
text.setSpan(new StyleSpan(Typeface.BOLD), 0, details.numberLabel.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
displayName = text;
}
}
views.nameView.setText(displayName);
if (!TextUtils.isEmpty(details.formattedNumber)) {
views.numberView.setText(details.formattedNumber);
} else if (!TextUtils.isEmpty(details.number)) {
views.numberView.setText(details.number);
} else {
// In this case we can assume that display name was set to unknown
views.numberView.setText(displayName);
}
}
/** Sets the text of the header view for the details page of a phone call. */
public void setCallDetailsHeader(TextView nameView, PhoneCallDetails details) {
CharSequence nameText;
final CharSequence displayNumber = details.number;
if (TextUtils.isEmpty(details.name)) {
nameText = displayNumber;
} else {
nameText = details.name;
}
nameView.setText(nameText);
}
public void setCurrentTimeForTest(long currentTimeMillis) {
mCurrentTimeMillisForTest = currentTimeMillis;
}
/**
* Returns the current time in milliseconds since the epoch.
* <p>
* It can be injected in tests using {@link #setCurrentTimeForTest(long)}.
*/
private long getCurrentTimeMillis() {
if (mCurrentTimeMillisForTest == null) {
return System.currentTimeMillis();
} else {
return mCurrentTimeMillisForTest;
}
}
/** Sets the call count and date. */
private void setCallCountAndDate(PhoneCallDetailsViews views, Integer callCount,
CharSequence dateText) {
// Combine the count (if present) and the date.
CharSequence text;
if (callCount != null) {
text = mResources.getString(
R.string.call_log_item_count_and_date, callCount.intValue(), dateText);
} else {
text = dateText;
}
views.callTypeAndDate.setText(text);
}
}
| 6,333 | 0.640694 | 0.637855 | 177 | 34.81921 | 26.849678 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.412429 | false | false | 9 |
dad6b74fc026d9fa15c68e4b82bbef7f2451c8a8 | 2,267,742,781,657 | 3b22df503168d46d8ab62d203ede5e17b4a511fa | /src/learn/how2j/collection/my_stack/Stack.java | 6ccfbd90cdf1d78a8549985633a5dfb253da095e | [] | no_license | qqins/LearnJava | https://github.com/qqins/LearnJava | 338a7ce89bfab8737cefe6af9e7cc3e17839d6ae | e46e5c2b42c562c4098ad87828945fe590a431ad | refs/heads/master | 2018-09-11T22:59:50.907000 | 2018-07-03T14:08:44 | 2018-07-03T14:08:44 | 107,089,131 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package learn.how2j.collection.my_stack;
public interface Stack {
void push(String str);
String pull();
String peek();
}
| UTF-8 | Java | 134 | java | Stack.java | Java | [] | null | [] | package learn.how2j.collection.my_stack;
public interface Stack {
void push(String str);
String pull();
String peek();
}
| 134 | 0.679105 | 0.671642 | 7 | 18.142857 | 13.075916 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 9 |
34deb5a53850e9a1bbb7b4046f028fa7c49e95d1 | 14,370,960,621,511 | 8d399232f96c1cb22d54b35b77f63620cd1ce4a0 | /src/main/java/com/marcioggs/crackingthecodeinterview/chapter2/exercise1/Solution2.java | 9bdf1660058be3cec6e61d162e91bbf5a72ba86d | [] | no_license | marcioggs/programming-challenges | https://github.com/marcioggs/programming-challenges | 77fddec7e2bd284464d20170caad6053b34f8e16 | 51c8fb8687ac78c7812e4918b3e7d83410d93875 | refs/heads/master | 2023-04-08T01:14:00.811000 | 2023-03-19T08:26:54 | 2023-03-19T08:26:54 | 225,148,616 | 0 | 0 | null | false | 2022-07-24T19:25:48 | 2019-12-01T11:15:54 | 2022-05-22T13:17:49 | 2022-07-24T19:25:28 | 276 | 0 | 0 | 0 | Java | false | false | package com.marcioggs.crackingthecodeinterview.chapter2.exercise1;
import com.marcioggs.crackingthecodeinterview.chapter2.SingleLinkedListNode;
public class Solution2 {
public <T> void removeDuplicates(SingleLinkedListNode<T> root) {
SingleLinkedListNode<T> primary = root;
while (primary != null) {
SingleLinkedListNode<T> secondary = primary;
while (secondary != null && secondary.next != null) {
if (primary.value.equals(secondary.next.value)) {
secondary.next = secondary.next.next;
}
secondary = secondary.next;
}
primary = primary.next;
}
}
} | UTF-8 | Java | 704 | java | Solution2.java | Java | [] | null | [] | package com.marcioggs.crackingthecodeinterview.chapter2.exercise1;
import com.marcioggs.crackingthecodeinterview.chapter2.SingleLinkedListNode;
public class Solution2 {
public <T> void removeDuplicates(SingleLinkedListNode<T> root) {
SingleLinkedListNode<T> primary = root;
while (primary != null) {
SingleLinkedListNode<T> secondary = primary;
while (secondary != null && secondary.next != null) {
if (primary.value.equals(secondary.next.value)) {
secondary.next = secondary.next.next;
}
secondary = secondary.next;
}
primary = primary.next;
}
}
} | 704 | 0.610795 | 0.605114 | 25 | 27.200001 | 27.282228 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.28 | false | false | 9 |
21c67e0d9b3ac6dd35640a131e63473f6763e6ed | 438,086,664,836 | b4f5b1a2b54bf8ec527c8366d3dc79f01076d1ce | /src/main/java/com/github/xiaotong/collegeselection/dao/bean/ViewMajorsInfoBean.java | 4fd2018feec4d28b183d1c89ea368262d6d35942 | [
"MIT",
"Apache-2.0"
] | permissive | Frank17/college-selection | https://github.com/Frank17/college-selection | c4784ce3ea01a09faadb322770dc1d3c860d3ae4 | 72f8ad958ca517076e9ffd804151cc698fc22185 | refs/heads/master | 2023-03-15T08:48:00.260000 | 2021-04-20T02:22:42 | 2021-04-20T02:22:42 | 328,540,716 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.xiaotong.collegeselection.dao.bean;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* 专业介绍视图
*/
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@ToString
public class ViewMajorsInfoBean {
private short mYear;
private String mCode;
private short mCategoryCode;
private String mCategoryName;
private String mName;
private String mMemo;
private String mRequ;
private String subName;
private short subCode;
private String mGoal;
private String mIntro;
private String mClass;
}
| UTF-8 | Java | 654 | java | ViewMajorsInfoBean.java | Java | [
{
"context": "package com.github.xiaotong.collegeselection.dao.bean;\n\nimport lombok.AllArgs",
"end": 27,
"score": 0.8377472758293152,
"start": 19,
"tag": "USERNAME",
"value": "xiaotong"
}
] | null | [] | package com.github.xiaotong.collegeselection.dao.bean;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* 专业介绍视图
*/
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@ToString
public class ViewMajorsInfoBean {
private short mYear;
private String mCode;
private short mCategoryCode;
private String mCategoryName;
private String mName;
private String mMemo;
private String mRequ;
private String subName;
private short subCode;
private String mGoal;
private String mIntro;
private String mClass;
}
| 654 | 0.758567 | 0.758567 | 30 | 20.4 | 12.354756 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 9 |
49be088dd8069f58dfaa78e350fa6a46cb3a1e72 | 7,945,689,503,576 | c51d2d11919184c058140c38719dd2341db3a028 | /src/models/stats/StatModificationList.java | 8c0d71a4704fba723b3101b3ac2b93b974480a96 | [] | no_license | kanye2021/OOP-Game-S16-Iteration2 | https://github.com/kanye2021/OOP-Game-S16-Iteration2 | 7dbc351a46eeef75e2f6cb58f3c12558c7601b52 | e2a28eccf84f9b579a4c67211a1b23afa1fa6a69 | refs/heads/master | 2021-01-10T09:37:24.016000 | 2016-03-14T14:04:49 | 2016-03-14T14:04:49 | 51,951,401 | 0 | 0 | null | false | 2016-03-13T23:12:05 | 2016-02-17T20:03:40 | 2016-03-06T20:57:35 | 2016-03-13T23:12:05 | 7,506 | 0 | 0 | 0 | Java | null | null | package models.stats;
import java.util.ArrayList;
/**
* Created by Bradley on 2/19/16.
*/
public class StatModificationList {
ArrayList<StatModification> modifications = new ArrayList<>();
public StatModificationList(StatModification... modifications) {
for (StatModification modification : modifications) {
this.modifications.add(modification);
}
}
public void applyStats(Stats stats) {
for (StatModification statMod : modifications) {
statMod.apply(stats);
}
}
public void removeStats(Stats stats) {
for (StatModification statMod : modifications) {
statMod.remove(stats);
}
}
public ArrayList<StatModification> getModifications() {
return modifications;
}
}
| UTF-8 | Java | 807 | java | StatModificationList.java | Java | [
{
"context": "s;\n\nimport java.util.ArrayList;\n\n/**\n * Created by Bradley on 2/19/16.\n */\npublic class StatModificationList",
"end": 77,
"score": 0.9991738796234131,
"start": 70,
"tag": "NAME",
"value": "Bradley"
}
] | null | [] | package models.stats;
import java.util.ArrayList;
/**
* Created by Bradley on 2/19/16.
*/
public class StatModificationList {
ArrayList<StatModification> modifications = new ArrayList<>();
public StatModificationList(StatModification... modifications) {
for (StatModification modification : modifications) {
this.modifications.add(modification);
}
}
public void applyStats(Stats stats) {
for (StatModification statMod : modifications) {
statMod.apply(stats);
}
}
public void removeStats(Stats stats) {
for (StatModification statMod : modifications) {
statMod.remove(stats);
}
}
public ArrayList<StatModification> getModifications() {
return modifications;
}
}
| 807 | 0.639405 | 0.633209 | 43 | 17.767443 | 22.442524 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.162791 | false | false | 9 |
7cfdb6d1faeb4e42491782e0f75f0d39e690faa5 | 15,960,098,478,830 | 71e24b89a19901f5b975de7b382b07b73346e58d | /src/main/java/org/sparago/security/question/service/api/SecurityQuestionController.java | ab01a741c1d4633a2a75e5d58c67d7aa47225f7e | [] | no_license | psparago/security-question-service | https://github.com/psparago/security-question-service | fa9033a4a2c91641865895b4110ce01a589a89ff | 0ec87811c447c5112f17feeb841550a0abc9b1f4 | refs/heads/master | 2020-03-26T00:08:55.035000 | 2018-08-10T16:23:28 | 2018-08-10T16:23:28 | 144,308,222 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.sparago.security.question.service.api;
import org.sparago.security.question.service.core.QuestionService;
import org.sparago.security.question.service.exception.IncorrectAnswerException;
import org.sparago.security.question.service.model.SecurityQuestion;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/")
public class SecurityQuestionController {
private final QuestionService questionService;
public SecurityQuestionController(QuestionService questionService) {
this.questionService = questionService;
}
@GetMapping(value = "")
public SecurityQuestion getQuestion(){
return questionService.createQuestion();
}
@PutMapping(value = "")
public SecurityQuestion answerQuestion(@RequestBody SecurityQuestion question) {
if (!questionService.validateAnswer(question)) {
throw new IncorrectAnswerException();
}
return question;
}
}
| UTF-8 | Java | 971 | java | SecurityQuestionController.java | Java | [] | null | [] | package org.sparago.security.question.service.api;
import org.sparago.security.question.service.core.QuestionService;
import org.sparago.security.question.service.exception.IncorrectAnswerException;
import org.sparago.security.question.service.model.SecurityQuestion;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/")
public class SecurityQuestionController {
private final QuestionService questionService;
public SecurityQuestionController(QuestionService questionService) {
this.questionService = questionService;
}
@GetMapping(value = "")
public SecurityQuestion getQuestion(){
return questionService.createQuestion();
}
@PutMapping(value = "")
public SecurityQuestion answerQuestion(@RequestBody SecurityQuestion question) {
if (!questionService.validateAnswer(question)) {
throw new IncorrectAnswerException();
}
return question;
}
}
| 971 | 0.752832 | 0.752832 | 31 | 30.32258 | 27.136913 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.322581 | false | false | 9 |
af990b17fe10b826eece58f4f62aa4034c8c20a8 | 3,882,650,438,755 | ac74d0dfae5830c1b1d675f0b0c5ed5fa0db6435 | /bootprovider/src/main/java/com/qgs/springboot/dubbo/BootProvider.java | a17236a910d1ef6edddd19e18e8c7c93a14990a4 | [] | no_license | qianguisen/springboot-dubbo | https://github.com/qianguisen/springboot-dubbo | 2dab4774756aefacea6a6fd953adb81af3823be4 | da9ec59f6862b87b9aa3cc9c2a229784282ef696 | refs/heads/master | 2020-05-14T23:30:53.711000 | 2019-04-18T02:48:19 | 2019-04-18T02:52:47 | 181,998,082 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.qgs.springboot.dubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration;
@SpringBootApplication
@EnableDubboConfiguration
public class BootProvider {
public static void main(String args[]){
SpringApplication.run(BootProvider.class, args);
}
} | UTF-8 | Java | 405 | java | BootProvider.java | Java | [] | null | [] | package com.qgs.springboot.dubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration;
@SpringBootApplication
@EnableDubboConfiguration
public class BootProvider {
public static void main(String args[]){
SpringApplication.run(BootProvider.class, args);
}
} | 405 | 0.837037 | 0.837037 | 15 | 26.066668 | 24.890337 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 9 |
70ee41e150cb7237aaf53bd49072ef5ee35c69b4 | 28,973,849,390,397 | fb254e0642f8d5aecce8b15fb7ca986150bda231 | /src/main/java/zgdx/xxaq/domain/read/CSVReadService.java | 753f8ff6120092d6e5f711dce9f2b9f4cb42b524 | [] | no_license | 18964198046/dz-domain | https://github.com/18964198046/dz-domain | cd473df2cb7ff91ff04c4b9ef1fb186a1f0842b6 | a86d0dbec9cf66762f97deca7b424eaee0858198 | refs/heads/master | 2020-07-12T11:09:22.293000 | 2019-08-27T22:40:45 | 2019-08-27T22:40:45 | 204,801,999 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package zgdx.xxaq.domain.read;
import au.com.bytecode.opencsv.CSVReader;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import zgdx.xxaq.domain.entity.MonitorDomainEntity;
import zgdx.xxaq.domain.repository.MonitorDomainRepository;
import java.io.FileReader;
import java.util.Collection;
import java.util.stream.Collectors;
@Service
public class CSVReadService implements InitializingBean {
@Value("${csv.isRead}")
private Boolean csvIsRead;
@Value("${csv.filePath}")
private String csvFilePath;
@Autowired
private MonitorDomainRepository monitorDomainRepository;
private void csvRead(String csvFilePath) throws Exception {
try(CSVReader csvReader = new CSVReader(new FileReader(csvFilePath))) {
Collection<MonitorDomainEntity> monitorDomainEntities =
csvReader.readAll().stream().map(strs -> MonitorDomainEntity
.builder().domain(strs[0]).build()).collect(Collectors.toList());
monitorDomainRepository.saveAll(monitorDomainEntities);
}
}
@Override
public void afterPropertiesSet() throws Exception {
if (csvIsRead) {
csvRead(csvFilePath);
}
}
}
| UTF-8 | Java | 1,396 | java | CSVReadService.java | Java | [] | null | [] | package zgdx.xxaq.domain.read;
import au.com.bytecode.opencsv.CSVReader;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import zgdx.xxaq.domain.entity.MonitorDomainEntity;
import zgdx.xxaq.domain.repository.MonitorDomainRepository;
import java.io.FileReader;
import java.util.Collection;
import java.util.stream.Collectors;
@Service
public class CSVReadService implements InitializingBean {
@Value("${csv.isRead}")
private Boolean csvIsRead;
@Value("${csv.filePath}")
private String csvFilePath;
@Autowired
private MonitorDomainRepository monitorDomainRepository;
private void csvRead(String csvFilePath) throws Exception {
try(CSVReader csvReader = new CSVReader(new FileReader(csvFilePath))) {
Collection<MonitorDomainEntity> monitorDomainEntities =
csvReader.readAll().stream().map(strs -> MonitorDomainEntity
.builder().domain(strs[0]).build()).collect(Collectors.toList());
monitorDomainRepository.saveAll(monitorDomainEntities);
}
}
@Override
public void afterPropertiesSet() throws Exception {
if (csvIsRead) {
csvRead(csvFilePath);
}
}
}
| 1,396 | 0.724928 | 0.724212 | 43 | 31.465117 | 26.985224 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.395349 | false | false | 9 |
25569208d5eb059e747b88741c96b68f0df6c4d2 | 10,050,223,482,878 | ed4a4c5c273098c4bc4e7ba1cb0dd2682cced4fb | /src/leetcode/BinaryTreeInorderTraversal.java | e7fdc9a318b18104f319f6ab1051b75a189ad571 | [] | no_license | eko1995/DataStructure | https://github.com/eko1995/DataStructure | 6b1a8e76a115f91a2962962a82786bdd64fe5d8d | 187267793cbf50c0f7dbaee4f0acdd8000675181 | refs/heads/master | 2021-01-01T15:56:01.571000 | 2020-06-23T14:05:28 | 2020-06-23T14:05:28 | 97,731,450 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leetcode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author eko
* @date 2018/10/27 3:20 PM
*/
public class BinaryTreeInorderTraversal {
public static void main(String[] args) {
BinaryTreeInorderTraversal solution = new BinaryTreeInorderTraversal();
TreeNode node = solution.new TreeNode(1);
node.right = solution.new TreeNode(2);
node.right.left = solution.new TreeNode(3);
List<Integer> res = solution.inorderTraversal(node);
System.out.println(res);
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
traversal(root, res);
return res;
}
public void traversal(TreeNode root, List<Integer> list) {
if (root == null) return;
traversal(root.left, list);
list.add(root.val);
traversal(root.right, list);
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}
| UTF-8 | Java | 1,089 | java | BinaryTreeInorderTraversal.java | Java | [
{
"context": "util.List;\nimport java.util.Stack;\n\n/**\n * @author eko\n * @date 2018/10/27 3:20 PM\n */\npublic class Bina",
"end": 113,
"score": 0.9996500015258789,
"start": 110,
"tag": "USERNAME",
"value": "eko"
}
] | null | [] | package leetcode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author eko
* @date 2018/10/27 3:20 PM
*/
public class BinaryTreeInorderTraversal {
public static void main(String[] args) {
BinaryTreeInorderTraversal solution = new BinaryTreeInorderTraversal();
TreeNode node = solution.new TreeNode(1);
node.right = solution.new TreeNode(2);
node.right.left = solution.new TreeNode(3);
List<Integer> res = solution.inorderTraversal(node);
System.out.println(res);
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
traversal(root, res);
return res;
}
public void traversal(TreeNode root, List<Integer> list) {
if (root == null) return;
traversal(root.left, list);
list.add(root.val);
traversal(root.right, list);
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}
| 1,089 | 0.612489 | 0.599633 | 43 | 24.325581 | 19.999676 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581395 | false | false | 9 |
f1818667b3cc3d7a5eeb76fc18db37e3d3f9212b | 13,391,708,066,389 | de15053d4d2ba8f3a2473a6da70deb9557c66a0e | /src/CodingInterviewPatterns/TwoPointers/TwoSumIIInputSorted.java | c2782faacb658f0778ee220af0f89c64e197e200 | [] | no_license | derricknjeru/AlgoDatastructure | https://github.com/derricknjeru/AlgoDatastructure | 4f1fa450d95b54fba513209fb15c4c7805a336ad | a065bbed5781e735cb2e722796625a571961479f | refs/heads/main | 2023-09-01T17:35:37.879000 | 2023-08-23T17:00:19 | 2023-08-23T17:00:19 | 242,182,884 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package CodingInterviewPatterns.TwoPointers;
public class TwoSumIIInputSorted {
public static void main(String[] args) {
Solution solution = new Solution();
int[] numbers1 = {2, 7, 11, 15};
int target1 = 9;
int[] result1 = solution.twoSum(numbers1, target1);
System.out.println("Indices: [" + result1[0] + ", " + result1[1] + "]");
int[] numbers2 = {2, 3, 4};
int target2 = 6;
int[] result2 = solution.twoSum(numbers2, target2);
System.out.println("Indices: [" + result2[0] + ", " + result2[1] + "]");
int[] numbers3 = {-1, 0};
int target3 = -1;
int[] result3 = solution.twoSum(numbers3, target3);
System.out.println("Indices: [" + result3[0] + ", " + result3[1] + "]");
}
/**
* Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
*
* Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
*
* The tests are generated such that there is exactly one solution. You may not use the same element twice.
*
* Your solution must use only constant extra space.
*
*
*
* Example 1:
*
* Input: numbers = [2,7,11,15], target = 9
* Output: [1,2]
* Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
* Example 2:
*
* Input: numbers = [2,3,4], target = 6
* Output: [1,3]
* Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
* Example 3:
*
* Input: numbers = [-1,0], target = -1
* Output: [1,2]
* Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
*
*
* Constraints:
*
* 2 <= numbers.length <= 3 * 104
* -1000 <= numbers[i] <= 1000
* numbers is sorted in non-decreasing order.
* -1000 <= target <= 1000
* The tests are generated such that there is exactly one solution.
*/
/**
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* @return
*/
static class Solution {
public int[] twoSum(int[] numbers, int target) {
int i = 0;
int j = numbers.length - 1;
while (i <= j) {
int possibleTarget = numbers[i] + numbers[j];
if (possibleTarget == target) return new int[]{i + 1, j + 1};
if (possibleTarget > target) j--;
else i++;
}
return new int[0];
}
}
//https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
//https://www.youtube.com/watch?v=cQ1Oz4ckceM
public class Solution2 {
public int[] twoSum(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (nums[l] + nums[r] != target) {
if (nums[l] + nums[r] < target) l++;
else r--;
}
return new int[]{l + 1, r + 1};
}
}
}
| UTF-8 | Java | 3,267 | java | TwoSumIIInputSorted.java | Java | [] | null | [] | package CodingInterviewPatterns.TwoPointers;
public class TwoSumIIInputSorted {
public static void main(String[] args) {
Solution solution = new Solution();
int[] numbers1 = {2, 7, 11, 15};
int target1 = 9;
int[] result1 = solution.twoSum(numbers1, target1);
System.out.println("Indices: [" + result1[0] + ", " + result1[1] + "]");
int[] numbers2 = {2, 3, 4};
int target2 = 6;
int[] result2 = solution.twoSum(numbers2, target2);
System.out.println("Indices: [" + result2[0] + ", " + result2[1] + "]");
int[] numbers3 = {-1, 0};
int target3 = -1;
int[] result3 = solution.twoSum(numbers3, target3);
System.out.println("Indices: [" + result3[0] + ", " + result3[1] + "]");
}
/**
* Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
*
* Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
*
* The tests are generated such that there is exactly one solution. You may not use the same element twice.
*
* Your solution must use only constant extra space.
*
*
*
* Example 1:
*
* Input: numbers = [2,7,11,15], target = 9
* Output: [1,2]
* Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
* Example 2:
*
* Input: numbers = [2,3,4], target = 6
* Output: [1,3]
* Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
* Example 3:
*
* Input: numbers = [-1,0], target = -1
* Output: [1,2]
* Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
*
*
* Constraints:
*
* 2 <= numbers.length <= 3 * 104
* -1000 <= numbers[i] <= 1000
* numbers is sorted in non-decreasing order.
* -1000 <= target <= 1000
* The tests are generated such that there is exactly one solution.
*/
/**
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* @return
*/
static class Solution {
public int[] twoSum(int[] numbers, int target) {
int i = 0;
int j = numbers.length - 1;
while (i <= j) {
int possibleTarget = numbers[i] + numbers[j];
if (possibleTarget == target) return new int[]{i + 1, j + 1};
if (possibleTarget > target) j--;
else i++;
}
return new int[0];
}
}
//https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
//https://www.youtube.com/watch?v=cQ1Oz4ckceM
public class Solution2 {
public int[] twoSum(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (nums[l] + nums[r] != target) {
if (nums[l] + nums[r] < target) l++;
else r--;
}
return new int[]{l + 1, r + 1};
}
}
}
| 3,267 | 0.537802 | 0.496174 | 100 | 31.67 | 37.273598 | 273 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65 | false | false | 9 |
cd0018978178b08aabed26e26562cfb8b1ae6671 | 33,767,032,881,835 | 7b84bb8749a4a1a6896b53a0af1c52e00253a7f6 | /java/in/nit/view/PartPdfView.java | c282bb28e118eb23aab87965f3af5dfd1078089e | [] | no_license | naveenvishwanatham9/myProjectApp | https://github.com/naveenvishwanatham9/myProjectApp | b63c5388b1a6ccfe75b50df3bead6f2df259b421 | 97178d306dec5b2b8e2bfd2d4b8e2d4aabda6529 | refs/heads/master | 2022-12-22T10:33:58.345000 | 2020-03-14T16:35:17 | 2020-03-14T16:35:17 | 244,965,501 | 0 | 0 | null | false | 2022-12-16T15:25:41 | 2020-03-04T17:43:51 | 2020-03-14T16:35:45 | 2022-12-16T15:25:40 | 387 | 0 | 0 | 6 | Java | false | false | package in.nit.view;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import in.nit.model.Part;
public class PartPdfView extends AbstractPdfView{
@Override
protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,
HttpServletRequest request, HttpServletResponse response) throws Exception {
response.addHeader("Content-Disposition", "attachment;filename=Part.Pdf");
Paragraph p=new Paragraph("welcome to part");
document.add(p);
List<Part> list=(List<Part>) model.get("list");
PdfPTable t=new PdfPTable(9);
t.addCell("ID");
t.addCell("CODE");
t.addCell("LENGTH");
t.addCell("WIDTH");
t.addCell("HEIGHT");
t.addCell("COST");
t.addCell("CURRENCY");
t.addCell("UOM");
t.addCell("DESCRIPTION");
for(Part st:list) {
t.addCell(st.getId().toString());
t.addCell(st.getPartCode());
t.addCell(st.getPartLen().toString());
t.addCell(st.getPartWid().toString());
t.addCell(st.getPartHgt().toString());
t.addCell(st.getBaseCost().toString());
t.addCell(st.getBaseCurrency());
t.addCell(st.getUomOb().getUomModel());
t.addCell(st.getNote());
}
document.add(t);
document.add(new Paragraph(new Date().toString()));
}
}
| UTF-8 | Java | 1,567 | java | PartPdfView.java | Java | [] | null | [] | package in.nit.view;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import in.nit.model.Part;
public class PartPdfView extends AbstractPdfView{
@Override
protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,
HttpServletRequest request, HttpServletResponse response) throws Exception {
response.addHeader("Content-Disposition", "attachment;filename=Part.Pdf");
Paragraph p=new Paragraph("welcome to part");
document.add(p);
List<Part> list=(List<Part>) model.get("list");
PdfPTable t=new PdfPTable(9);
t.addCell("ID");
t.addCell("CODE");
t.addCell("LENGTH");
t.addCell("WIDTH");
t.addCell("HEIGHT");
t.addCell("COST");
t.addCell("CURRENCY");
t.addCell("UOM");
t.addCell("DESCRIPTION");
for(Part st:list) {
t.addCell(st.getId().toString());
t.addCell(st.getPartCode());
t.addCell(st.getPartLen().toString());
t.addCell(st.getPartWid().toString());
t.addCell(st.getPartHgt().toString());
t.addCell(st.getBaseCost().toString());
t.addCell(st.getBaseCurrency());
t.addCell(st.getUomOb().getUomModel());
t.addCell(st.getNote());
}
document.add(t);
document.add(new Paragraph(new Date().toString()));
}
}
| 1,567 | 0.717932 | 0.717294 | 56 | 25.982143 | 21.567577 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.303571 | false | false | 9 |
9fb827cb70e526976420b62349015c6a55002788 | 20,993,800,162,155 | 73f9d89146e138622e7ec591e688ba36fa8cc468 | /src/main/java/com/f4w/job/strategy/MiniAppVideoCommentStrategy.java | ddcf6483f9400ab1c36b1194283eb527f260d12c | [] | no_license | 82253452/mass | https://github.com/82253452/mass | b1904b63454056aa3801daf3877c54291dda02d6 | ab774b02d5d3dba9adc04286de28fe81f13ca173 | refs/heads/master | 2023-01-11T17:24:57.618000 | 2020-11-16T03:37:28 | 2020-11-16T03:37:28 | 309,250,749 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.f4w.job.strategy;
import com.f4w.dto.annotation.ArticleType;
import com.f4w.dto.enums.ArticleTypeEnum;
import com.f4w.dto.req.JobInfoReq;
import com.f4w.entity.BusiApp;
import com.f4w.entity.Wxmp;
import com.f4w.job.CommentStrategy;
import com.f4w.utils.JobException;
import org.apache.commons.lang3.RandomUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Optional;
@Component
@DependsOn("springContextUtils")
@ArticleType(ArticleTypeEnum.MINIAPP_VIDEO)
public class MiniAppVideoCommentStrategy extends CommentStrategy {
@Override
public String dealHtml(JobInfoReq jobinfo, BusiApp busiApp, Wxmp wxmp) throws JobException {
String img = imageCoverUpload(busiApp.getAppId(), wxmp.getThumbnail());
String[] miniAppIdArray = jobinfo.getMiniAppId().split(",");
String miniAppId = miniAppIdArray[RandomUtils.nextInt(0, miniAppIdArray.length)];
return "<p>" +
"<a class=\"weapp_text_link\"" +
" style=\"font-size:14px;display:block;width:100%!important;" +
"height: 180px!important;\n" +
"box-shadow: #dddddd 2px 2px 8px;" +
" display:block;\n" +
" border-radius: 8px;" +
" background-color: #f7f7f7;\n" +
" background-image:url("+img+");\n" +
" background-repeat: no-repeat;\n" +
" background-size: 100% 100%;\n" +
" background-position: 0px 23px;\n" +
" color: #888;" +
"\" " +
"data-miniprogram-appid=\""+miniAppId+"\" " +
"data-miniprogram-path=\""+replaceStr(jobinfo.getMiniAppPath(),wxmp.getVideoId())+"\" " +
"data-miniprogram-nickname=\""+busiApp.getNickName()+"\" href=\"\" " +
"data-miniprogram-type=\"text\" " +
"data-miniprogram-servicetype=\"\">" +
busiApp.getNickName() +"(点击播放视频)"+
"</a>" ;
}
@Override
public Wxmp findWxmp(JobInfoReq jobinfo) throws JobException {
Wxmp wxmp = Optional.ofNullable(wxmpMapper.findWxmpByType(0, jobinfo.getColumn())).orElseThrow(() -> new JobException("查询视频为空" + jobinfo.getColumn()));
return wxmp;
}
}
| UTF-8 | Java | 2,510 | java | MiniAppVideoCommentStrategy.java | Java | [] | null | [] | package com.f4w.job.strategy;
import com.f4w.dto.annotation.ArticleType;
import com.f4w.dto.enums.ArticleTypeEnum;
import com.f4w.dto.req.JobInfoReq;
import com.f4w.entity.BusiApp;
import com.f4w.entity.Wxmp;
import com.f4w.job.CommentStrategy;
import com.f4w.utils.JobException;
import org.apache.commons.lang3.RandomUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Optional;
@Component
@DependsOn("springContextUtils")
@ArticleType(ArticleTypeEnum.MINIAPP_VIDEO)
public class MiniAppVideoCommentStrategy extends CommentStrategy {
@Override
public String dealHtml(JobInfoReq jobinfo, BusiApp busiApp, Wxmp wxmp) throws JobException {
String img = imageCoverUpload(busiApp.getAppId(), wxmp.getThumbnail());
String[] miniAppIdArray = jobinfo.getMiniAppId().split(",");
String miniAppId = miniAppIdArray[RandomUtils.nextInt(0, miniAppIdArray.length)];
return "<p>" +
"<a class=\"weapp_text_link\"" +
" style=\"font-size:14px;display:block;width:100%!important;" +
"height: 180px!important;\n" +
"box-shadow: #dddddd 2px 2px 8px;" +
" display:block;\n" +
" border-radius: 8px;" +
" background-color: #f7f7f7;\n" +
" background-image:url("+img+");\n" +
" background-repeat: no-repeat;\n" +
" background-size: 100% 100%;\n" +
" background-position: 0px 23px;\n" +
" color: #888;" +
"\" " +
"data-miniprogram-appid=\""+miniAppId+"\" " +
"data-miniprogram-path=\""+replaceStr(jobinfo.getMiniAppPath(),wxmp.getVideoId())+"\" " +
"data-miniprogram-nickname=\""+busiApp.getNickName()+"\" href=\"\" " +
"data-miniprogram-type=\"text\" " +
"data-miniprogram-servicetype=\"\">" +
busiApp.getNickName() +"(点击播放视频)"+
"</a>" ;
}
@Override
public Wxmp findWxmp(JobInfoReq jobinfo) throws JobException {
Wxmp wxmp = Optional.ofNullable(wxmpMapper.findWxmpByType(0, jobinfo.getColumn())).orElseThrow(() -> new JobException("查询视频为空" + jobinfo.getColumn()));
return wxmp;
}
}
| 2,510 | 0.626511 | 0.611201 | 59 | 41.067795 | 29.194185 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.728814 | false | false | 9 |
12c8689bdc8d4c7760a27425d814d1d32c558040 | 11,038,065,970,677 | d0cf992a4da1dba16dc7da86399cbd3c9bd3d3b4 | /meettooffer/chapter3/PrintDigit.java | 0bc6bcb0965875128950b37666a856ae6d298250 | [
"MIT"
] | permissive | coderRookies/goals-of-offer | https://github.com/coderRookies/goals-of-offer | 917d2f523c9eb8d22b3689b8ca31b429d147ae78 | 94db225ec0e4f85e79bc75710e9df97b316aea38 | refs/heads/master | 2020-05-04T15:44:29.040000 | 2020-02-03T03:25:03 | 2020-02-03T03:25:03 | 179,254,455 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package meettooffer.chapter3;
public class PrintDigit {
public static void main(String[] args) {
int max = 8;
printDigit(max);
}
private static void printDigit(int max) {
if (max <= 0) {
throw new IllegalArgumentException("input can't less than 1");
}
char[] base = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] charbuffer = new char[max];
for (int i = 0; i < charbuffer.length; i++) {
charbuffer[i] = base[0];
}
while (increment(charbuffer, charbuffer.length - 1, base)) {
print(charbuffer);
}
}
private static boolean increment(char[] charbuffer, int index, char[] base) {
charbuffer[index] = base[(charbuffer[index] - 0x2F) % 10];
if (index == 0 && charbuffer[index] == '0') {
return false;
}
if (charbuffer[index] == '0') {
return increment(charbuffer, index - 1, base);
}
return true;
}
private static void print(char[] charbuffer) {
int index = 0;
while (charbuffer[index] == '0' && index != charbuffer.length - 1) {
index++;
}
System.out.println(new String(charbuffer, index, charbuffer.length - index));
}
}
| UTF-8 | Java | 1,354 | java | PrintDigit.java | Java | [] | null | [] | package meettooffer.chapter3;
public class PrintDigit {
public static void main(String[] args) {
int max = 8;
printDigit(max);
}
private static void printDigit(int max) {
if (max <= 0) {
throw new IllegalArgumentException("input can't less than 1");
}
char[] base = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] charbuffer = new char[max];
for (int i = 0; i < charbuffer.length; i++) {
charbuffer[i] = base[0];
}
while (increment(charbuffer, charbuffer.length - 1, base)) {
print(charbuffer);
}
}
private static boolean increment(char[] charbuffer, int index, char[] base) {
charbuffer[index] = base[(charbuffer[index] - 0x2F) % 10];
if (index == 0 && charbuffer[index] == '0') {
return false;
}
if (charbuffer[index] == '0') {
return increment(charbuffer, index - 1, base);
}
return true;
}
private static void print(char[] charbuffer) {
int index = 0;
while (charbuffer[index] == '0' && index != charbuffer.length - 1) {
index++;
}
System.out.println(new String(charbuffer, index, charbuffer.length - index));
}
}
| 1,354 | 0.508124 | 0.487445 | 42 | 30.238094 | 26.48073 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.809524 | false | false | 9 |
2a5d2513f6cfceb419a24058fff5c3a1fa0806a4 | 9,938,554,379,570 | 7f743501d05a61d646111a8c3527f10be1aa3f3d | /springboot-apacheshiro/src/main/java/com/qcl/shiro/service/UserService.java | e435590b81a2c16ed8e4051ba8a162ce12657602 | [
"Apache-2.0"
] | permissive | qichunlin/SpringBootSelf | https://github.com/qichunlin/SpringBootSelf | 6b11f4a5ec86568204ca61357acef8ec1e178f7b | 17d1073710cf46423d32ea0b4cbb086817753fd4 | refs/heads/dev | 2021-11-17T05:29:39.532000 | 2021-11-16T05:19:30 | 2021-11-16T05:19:30 | 192,631,665 | 0 | 1 | null | false | 2021-08-22T11:41:07 | 2019-06-19T00:45:22 | 2021-08-22T02:36:38 | 2021-08-22T11:41:07 | 122,156 | 0 | 0 | 0 | C | false | false | package com.qcl.shiro.service;
import com.qcl.shiro.domain.User;
/**
* UserService
*
* @author legend
* @version 1.0
* @description
* @date 2020/9/21
*/
public interface UserService {
User findByUsername(String username);
}
| UTF-8 | Java | 239 | java | UserService.java | Java | [
{
"context": "iro.domain.User;\n\n/**\n * UserService\n *\n * @author legend\n * @version 1.0\n * @description\n * @date 2020/9/2",
"end": 107,
"score": 0.9982636570930481,
"start": 101,
"tag": "USERNAME",
"value": "legend"
}
] | null | [] | package com.qcl.shiro.service;
import com.qcl.shiro.domain.User;
/**
* UserService
*
* @author legend
* @version 1.0
* @description
* @date 2020/9/21
*/
public interface UserService {
User findByUsername(String username);
}
| 239 | 0.686192 | 0.648536 | 17 | 13.058824 | 13.179622 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.176471 | false | false | 9 |
9547388a313412ec061cd8afceaddea01be33ee2 | 31,396,210,976,268 | 30741eda1606006fb8af1afe1941b91a0d351b83 | /src/main/java/com/example/demo/dao/ZhCategoryTowMapper.java | 67085fabf9ecd0bd173b9fddf51ea890a7f50c20 | [] | no_license | fredomli/demo01 | https://github.com/fredomli/demo01 | 6aad9e2c3e7941e4ed3863cf0418ea9c5a626bc0 | a60ebc1ce82fa3ad83dad5a5be49d4634396b50d | refs/heads/master | 2021-06-29T01:50:32.011000 | 2020-06-24T03:13:19 | 2020-06-24T03:13:19 | 228,140,969 | 0 | 0 | null | false | 2021-06-04T02:22:45 | 2019-12-15T06:47:05 | 2020-06-24T03:13:29 | 2021-06-04T02:22:44 | 242 | 0 | 0 | 1 | Java | false | false | package com.example.demo.dao;
import com.example.demo.entity.ZhCategoryTow;
import java.util.List;
public interface ZhCategoryTowMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table zh_category_tow
*
* @mbg.generated
*/
int deleteByPrimaryKey(Integer bid);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table zh_category_tow
*
* @mbg.generated
*/
int insert(ZhCategoryTow record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table zh_category_tow
*
* @mbg.generated
*/
ZhCategoryTow selectByPrimaryKey(Integer bid);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table zh_category_tow
*
* @mbg.generated
*/
List<ZhCategoryTow> selectAll();
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table zh_category_tow
*
* @mbg.generated
*/
int updateByPrimaryKey(ZhCategoryTow record);
} | UTF-8 | Java | 1,207 | java | ZhCategoryTowMapper.java | Java | [] | null | [] | package com.example.demo.dao;
import com.example.demo.entity.ZhCategoryTow;
import java.util.List;
public interface ZhCategoryTowMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table zh_category_tow
*
* @mbg.generated
*/
int deleteByPrimaryKey(Integer bid);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table zh_category_tow
*
* @mbg.generated
*/
int insert(ZhCategoryTow record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table zh_category_tow
*
* @mbg.generated
*/
ZhCategoryTow selectByPrimaryKey(Integer bid);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table zh_category_tow
*
* @mbg.generated
*/
List<ZhCategoryTow> selectAll();
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table zh_category_tow
*
* @mbg.generated
*/
int updateByPrimaryKey(ZhCategoryTow record);
} | 1,207 | 0.663629 | 0.663629 | 46 | 25.26087 | 23.397728 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.173913 | false | false | 9 |
ab6af89afeea511d8f2af936a9864cf55f73b8a7 | 11,785,390,325,083 | 2d6e56e6f86cb184aaec477f723f42f7a6028957 | /src/com/bky/service/RoomTypeService.java | 0bed553b4795e7ee92139426e51b996083bac192 | [] | no_license | toBearShmily/ssm | https://github.com/toBearShmily/ssm | 862c786406f5289df7e83efcb6b03daf3fa0a9f2 | 99c68d18ae1ecf72b3c2b0100097899b3ba0833e | refs/heads/master | 2020-07-29T22:19:51.636000 | 2017-09-07T05:17:07 | 2017-09-07T05:17:07 | 73,656,674 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bky.service;
import java.util.List;
import com.bky.model.RoomType;
public interface RoomTypeService {
/**
* @author wuxubiao
* mean:dao层方法进行组合完成业务逻辑
* */
String saveRoomType(RoomType roomtype);
Boolean delRoomType(String roomtypeIds);
String upRoomType(RoomType roomtype);
RoomType selByid(Integer roomtypeId);
List<RoomType> getAllRoomType();
}
| UTF-8 | Java | 399 | java | RoomTypeService.java | Java | [
{
"context": "ublic interface RoomTypeService {\n\t/**\n\t * @author wuxubiao\n\t * mean:dao层方法进行组合完成业务逻辑\n\t * */\n\tString saveRoom",
"end": 142,
"score": 0.9992800951004028,
"start": 134,
"tag": "USERNAME",
"value": "wuxubiao"
}
] | null | [] | package com.bky.service;
import java.util.List;
import com.bky.model.RoomType;
public interface RoomTypeService {
/**
* @author wuxubiao
* mean:dao层方法进行组合完成业务逻辑
* */
String saveRoomType(RoomType roomtype);
Boolean delRoomType(String roomtypeIds);
String upRoomType(RoomType roomtype);
RoomType selByid(Integer roomtypeId);
List<RoomType> getAllRoomType();
}
| 399 | 0.766756 | 0.766756 | 17 | 20.941177 | 15.333434 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 9 |
673c44a21fac0e913cc0255df2c2477d8ce7acbc | 28,939,489,700,108 | 57b1551fb898837f72ab3bd9f43cf5a34cb71bde | /src/test/java/com/xz/examscore/services/QuestAbilityLevelScoreServiceTest.java | e4d084a757ad031ef949491bbb45ef8b344b24cc | [] | no_license | ericf1987/xz-exam-score-v2 | https://github.com/ericf1987/xz-exam-score-v2 | 81d04163612b6b7c84a64c1b0e04ca441f34441e | f838f71742e8e99647eb1cbd6f86155dfcefabfc | refs/heads/master | 2021-01-02T08:15:16.216000 | 2017-07-28T02:29:53 | 2017-07-28T02:29:53 | 98,974,106 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xz.examscore.services;
import com.xz.examscore.XzExamScoreV2ApplicationTests;
import com.xz.examscore.bean.Range;
import org.bson.Document;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* @author by fengye on 2017/1/4.
*/
public class QuestAbilityLevelScoreServiceTest extends XzExamScoreV2ApplicationTests {
@Autowired
QuestAbilityLevelScoreService questAbilityLevelScoreService;
@Test
public void testGetTotalScore() throws Exception {
Range range = Range.school("528654bb-3529-4ef2-9d71-5870d3f55d49");
double totalScore = questAbilityLevelScoreService.getTotalScore("430200-3e67c524f149491597279ef6ae31baef", "004_ability", "004", "ability", range);
System.out.println(totalScore);
int count = questAbilityLevelScoreService.getStudentCount("430200-3e67c524f149491597279ef6ae31baef", "006_ability", null, null, range);
System.out.println(count);
List<Document> studentList = questAbilityLevelScoreService.getStudentList("430200-3e67c524f149491597279ef6ae31baef", "006_ability", null, null, range);
System.out.println(studentList.size());
List<Document> list = questAbilityLevelScoreService.filterStudentList("430200-3e67c524f149491597279ef6ae31baef", "006_ability", null, null, range, 0.6d);
System.out.println(list.size());
}
@Test
public void testGetStudentCount() throws Exception {
int count = questAbilityLevelScoreService.getStudentCount("430300-6f2f82b0ea1a4dcca29f692570eabb50",
"008_ability", "008", "ability",
Range.school("002e02d6-c036-4780-85d4-e54e3f1fbf9f"));
System.out.println(count);
}
} | UTF-8 | Java | 1,747 | java | QuestAbilityLevelScoreServiceTest.java | Java | [
{
"context": "owired;\n\nimport java.util.List;\n\n/**\n * @author by fengye on 2017/1/4.\n */\npublic class QuestAbilityLevelSc",
"end": 288,
"score": 0.9989497065544128,
"start": 282,
"tag": "USERNAME",
"value": "fengye"
}
] | null | [] | package com.xz.examscore.services;
import com.xz.examscore.XzExamScoreV2ApplicationTests;
import com.xz.examscore.bean.Range;
import org.bson.Document;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* @author by fengye on 2017/1/4.
*/
public class QuestAbilityLevelScoreServiceTest extends XzExamScoreV2ApplicationTests {
@Autowired
QuestAbilityLevelScoreService questAbilityLevelScoreService;
@Test
public void testGetTotalScore() throws Exception {
Range range = Range.school("528654bb-3529-4ef2-9d71-5870d3f55d49");
double totalScore = questAbilityLevelScoreService.getTotalScore("430200-3e67c524f149491597279ef6ae31baef", "004_ability", "004", "ability", range);
System.out.println(totalScore);
int count = questAbilityLevelScoreService.getStudentCount("430200-3e67c524f149491597279ef6ae31baef", "006_ability", null, null, range);
System.out.println(count);
List<Document> studentList = questAbilityLevelScoreService.getStudentList("430200-3e67c524f149491597279ef6ae31baef", "006_ability", null, null, range);
System.out.println(studentList.size());
List<Document> list = questAbilityLevelScoreService.filterStudentList("430200-3e67c524f149491597279ef6ae31baef", "006_ability", null, null, range, 0.6d);
System.out.println(list.size());
}
@Test
public void testGetStudentCount() throws Exception {
int count = questAbilityLevelScoreService.getStudentCount("430300-6f2f82b0ea1a4dcca29f692570eabb50",
"008_ability", "008", "ability",
Range.school("002e02d6-c036-4780-85d4-e54e3f1fbf9f"));
System.out.println(count);
}
} | 1,747 | 0.742988 | 0.624499 | 39 | 43.820515 | 46.05341 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.025641 | false | false | 9 |
ab5ae0121317b2b11c914881b6f96e3fe4a9e41c | 7,456,063,289,181 | 796f1ce0a883c43d50f08991b17e326ac7ac79a4 | /src/main/java/fr/ritaly/dungeonmaster/champion/inventory/ItemContainer.java | 5679ebe61914a79241d4020fb3c9a7ff2128d76e | [
"Apache-2.0"
] | permissive | TorhamZed/yadmjc | https://github.com/TorhamZed/yadmjc | 64a95a94341dea203096da7aa1d9617b364d122a | 0491b324822b49fb1a3911b75c5d0ba5d05dfbbc | refs/heads/master | 2020-04-01T18:14:58.371000 | 2011-01-16T18:22:44 | 2011-01-16T18:24:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package fr.ritaly.dungeonmaster.champion.inventory;
import java.util.List;
import fr.ritaly.dungeonmaster.event.ChangeListener;
import fr.ritaly.dungeonmaster.item.Item;
/**
* @author <a href="mailto:francois.ritaly@free.fr">Francois RITALY</a>
*/
public interface ItemContainer {
/**
* Retourne le nombre d'objets que cet {@link ItemContainer} peut contenir.
*
* @return un entier positif.
*/
public int getCapacity();
public void addChangeListener(ChangeListener listener);
public void removeChangeListener(ChangeListener listener);
/**
* Retourne le nombre actuel d'objets dans le conteneur.
*
* @return un entier positif ou nul dans l'intervalle [0-capacity].
*/
public int getItemCount();
/**
* Retourne les {@link Item} contenus par cet {@link ItemContainer} sous
* forme de {@link List}.
*
* @return une {@link List} de {@link Item}. Ne retourne jamais null.
*/
public List<Item> getItems();
/**
* Indique si cet {@link ItemContainer} est plein.
*
* @return si cet {@link ItemContainer} est plein.
* @see #getCapacity()
* @see #getItemCount()
*/
public boolean isFull();
/**
* Indique si cet {@link ItemContainer} est vide.
*
* @return si cet {@link ItemContainer} est vide.
* @see #getItemCount()
*/
public boolean isEmpty();
/**
* Retourne un {@link Item} tiré au hasard parmi ceux de cet
* {@link ItemContainer}. Cette méthode ne supprime pas l'objet du
* conteneur.
*
* @return un {@link Item} ou null si le conteneur est vide.
*/
public Item getRandom();
/**
* Tente d'ajouter l'objet donné à cet {@link ItemContainer} et retourne
* l'index auquel a été ajouté l'objet si l'opération a réussi autrement -1.
*
* @param item
* un {@link Item} à ajouter.
* @return un entier représentant l'index auquel a été ajouté l'objet si
* l'opération a réussi autrement -1.
*/
public int add(Item item);
/**
* Supprime tous les objets de cet {@link ItemContainer} et les retourne
* sous forme de {@link List}.
*
* @return une {@link List} de {@link Item}. Ne retourne jamais null.
*/
public List<Item> removeAll();
/**
* Supprime l'objet d'index donné et le retourne.
*
* @param index
* un entier positif ou nul représentant l'index de l'objet à
* retirer.
* @return une instance de {@link Item} ou null s'il n'y a aucun objet à
* l'index donné.
*/
public Item remove(int index);
/**
* Supprime un {@link Item} tiré au hasard parmi ceux de cet
* {@link ItemContainer} et le retourne.
*
* @return un {@link Item} ou null si le conteneur est vide.
*/
public Item removeRandom();
/**
* Tente de supprimer l'objet donné et retourne si l'opération a réussi.
*
* @param item
* une instance de {@link Item} à supprimer du conteneur.
* @return si l'opération a réussi.
*/
public boolean remove(Item item);
public Item set(int index, Item item);
/**
* Retourne le poids total des objets contenus par cet {@link Item}.
*
* @return un float représentant le poids des objets en kilogrammes.
*/
public float getTotalWeight();
} | ISO-8859-1 | Java | 4,001 | java | ItemContainer.java | Java | [
{
"context": "master.item.Item;\n\n/**\n * @author <a href=\"mailto:francois.ritaly@free.fr\">Francois RITALY</a>\n */\npublic interface ItemCon",
"end": 1035,
"score": 0.9999197125434875,
"start": 1012,
"tag": "EMAIL",
"value": "francois.ritaly@free.fr"
},
{
"context": " @author <a href=\"mailto:francois.ritaly@free.fr\">Francois RITALY</a>\n */\npublic interface ItemContainer {\n\n\t/**\n\t ",
"end": 1052,
"score": 0.9998680949211121,
"start": 1037,
"tag": "NAME",
"value": "Francois RITALY"
}
] | null | [] | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package fr.ritaly.dungeonmaster.champion.inventory;
import java.util.List;
import fr.ritaly.dungeonmaster.event.ChangeListener;
import fr.ritaly.dungeonmaster.item.Item;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public interface ItemContainer {
/**
* Retourne le nombre d'objets que cet {@link ItemContainer} peut contenir.
*
* @return un entier positif.
*/
public int getCapacity();
public void addChangeListener(ChangeListener listener);
public void removeChangeListener(ChangeListener listener);
/**
* Retourne le nombre actuel d'objets dans le conteneur.
*
* @return un entier positif ou nul dans l'intervalle [0-capacity].
*/
public int getItemCount();
/**
* Retourne les {@link Item} contenus par cet {@link ItemContainer} sous
* forme de {@link List}.
*
* @return une {@link List} de {@link Item}. Ne retourne jamais null.
*/
public List<Item> getItems();
/**
* Indique si cet {@link ItemContainer} est plein.
*
* @return si cet {@link ItemContainer} est plein.
* @see #getCapacity()
* @see #getItemCount()
*/
public boolean isFull();
/**
* Indique si cet {@link ItemContainer} est vide.
*
* @return si cet {@link ItemContainer} est vide.
* @see #getItemCount()
*/
public boolean isEmpty();
/**
* Retourne un {@link Item} tiré au hasard parmi ceux de cet
* {@link ItemContainer}. Cette méthode ne supprime pas l'objet du
* conteneur.
*
* @return un {@link Item} ou null si le conteneur est vide.
*/
public Item getRandom();
/**
* Tente d'ajouter l'objet donné à cet {@link ItemContainer} et retourne
* l'index auquel a été ajouté l'objet si l'opération a réussi autrement -1.
*
* @param item
* un {@link Item} à ajouter.
* @return un entier représentant l'index auquel a été ajouté l'objet si
* l'opération a réussi autrement -1.
*/
public int add(Item item);
/**
* Supprime tous les objets de cet {@link ItemContainer} et les retourne
* sous forme de {@link List}.
*
* @return une {@link List} de {@link Item}. Ne retourne jamais null.
*/
public List<Item> removeAll();
/**
* Supprime l'objet d'index donné et le retourne.
*
* @param index
* un entier positif ou nul représentant l'index de l'objet à
* retirer.
* @return une instance de {@link Item} ou null s'il n'y a aucun objet à
* l'index donné.
*/
public Item remove(int index);
/**
* Supprime un {@link Item} tiré au hasard parmi ceux de cet
* {@link ItemContainer} et le retourne.
*
* @return un {@link Item} ou null si le conteneur est vide.
*/
public Item removeRandom();
/**
* Tente de supprimer l'objet donné et retourne si l'opération a réussi.
*
* @param item
* une instance de {@link Item} à supprimer du conteneur.
* @return si l'opération a réussi.
*/
public boolean remove(Item item);
public Item set(int index, Item item);
/**
* Retourne le poids total des objets contenus par cet {@link Item}.
*
* @return un float représentant le poids des objets en kilogrammes.
*/
public float getTotalWeight();
} | 3,976 | 0.680514 | 0.678751 | 138 | 27.789856 | 26.466948 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.855072 | false | false | 9 |
62c5c55f8c122851c6adc74401e725682f562aa7 | 14,319,420,980,844 | a4bda58e3f9872f2159d29f8374162ff1c1769f2 | /src/com/biao/abstract_factory/MethodOneA.java | 5569bbe0d79352f71fee51a3dc0f8fe6f6262ef2 | [] | no_license | abiaodev/java-design-patterns | https://github.com/abiaodev/java-design-patterns | aff478a4b2267146eec4368fc8ac7cf233d233f7 | ec398452945e1f286611928cde0c632cf52f4be7 | refs/heads/master | 2022-04-20T18:23:44.526000 | 2022-03-16T16:44:06 | 2022-03-16T16:44:06 | 183,867,623 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.biao.abstract_factory;
import com.biao.Logger;
class MethodOneA implements IMethodOne{
@Override
public void runMethod() {
Logger.LOG("MethodOneA is run");
}
}
| UTF-8 | Java | 194 | java | MethodOneA.java | Java | [] | null | [] | package com.biao.abstract_factory;
import com.biao.Logger;
class MethodOneA implements IMethodOne{
@Override
public void runMethod() {
Logger.LOG("MethodOneA is run");
}
}
| 194 | 0.690722 | 0.690722 | 10 | 18.4 | 15.672907 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 9 |
5a2f4a19d01820fdad45bf557c4cf399c9e82aaa | 14,319,420,980,655 | ac80cccd11075210c4497cc8883b96619139c33b | /src/main/java/com/example/plannerREST/controllers/ActivityController.java | 54ce77780aa9834cfbc9d2318789fa305640fa45 | [] | no_license | rotariucatalin/plannerRest | https://github.com/rotariucatalin/plannerRest | 16a99d4307281dc01da549d981f32fc136135827 | b8dee58ef5d7641484b0b318c6a8a917c0594109 | refs/heads/main | 2023-06-26T06:41:30.018000 | 2021-07-19T10:39:32 | 2021-07-19T10:39:32 | 373,805,594 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.plannerREST.controllers;
import com.example.plannerREST.dto.ActivityDTO;
import com.example.plannerREST.dto.CompanyDTO;
import com.example.plannerREST.entities.AuthRequest;
import com.example.plannerREST.entities.CustomResponse;
import com.example.plannerREST.entities.Permission;
import com.example.plannerREST.exception.ApiRequestException;
import com.example.plannerREST.kafka.Producer;
import com.example.plannerREST.services.ActivityService;
import com.example.plannerREST.services.CompanyService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@RestController
@RequestMapping(value = "/activities")
public class ActivityController {
private Logger logger = LoggerFactory.getLogger(ActivityController.class);
@Autowired
private ActivityService activityService;
@Autowired
private Producer producer;
@Autowired
private CompanyService companyService;
/*
Example of using kafka
@GetMapping("/testKafka/{message}")
public String testKafka(@PathVariable("message") String message) {
Permission permission = new Permission();
permission.setName("test123");
producer.publishMessage(permission);
return "Message is " + message;
}
*/
@PreAuthorize("hasAuthority('View_Activity')")
@GetMapping(value = "/", produces = APPLICATION_JSON_VALUE)
@ApiOperation(
value = "Get all activities",
notes = "Get all activities. You can filter/change the number of companies that are returned",
response = ActivityDTO.class
)
public List<ActivityDTO> getAllActivities(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "5") int size,
@RequestParam(defaultValue = "") String filter) {
return activityService.getAllActivities(page, size, filter);
}
@PreAuthorize("hasAuthority('Add_Activity')")
@GetMapping(value = "/getAllCompanies", produces = APPLICATION_JSON_VALUE)
@ApiOperation(
value = "Getting all companies",
notes = "Getting all companies",
response = CompanyDTO.class
)
public List<CompanyDTO> getAllCompanies() throws ApiRequestException {
try {
return companyService.findAllCompanies();
} catch (Exception e) {
throw new ApiRequestException("Cannot get activity list!");
}
}
@PreAuthorize("hasAuthority('Add_Activity')")
@PostMapping(value = "/addActivity", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
@ApiOperation(
value = "Add new activity",
notes = "Add new activity",
response = CustomResponse.class
)
public CustomResponse saveActivity(@RequestBody ActivityDTO activityDTO) throws ApiRequestException {
try {
activityService.saveActivity(activityDTO);
return new CustomResponse("Activity successfully added", OK);
} catch (Exception e) {
throw new ApiRequestException("Activity could not be added!");
}
}
@PreAuthorize("hasAuthority('Edit_Activity')")
@GetMapping(value = "/editActivity/{id}", produces = APPLICATION_JSON_VALUE)
@ApiOperation(
value = "Edit specific activity",
notes = "Edit specific activity based on specific id",
response = ActivityDTO.class
)
public ActivityDTO editActivity(@PathVariable(value = "id") int id) throws ApiRequestException {
try {
return activityService.getActivity(id);
} catch (Exception e) {
throw new ApiRequestException("Activity not found");
}
}
@PreAuthorize("hasAuthority('Edit_Activity')")
@PutMapping(value = "/updateActivity", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
@ApiOperation(
value = "Update activity",
notes = "Update activity based on specif id",
response = CustomResponse.class
)
public CustomResponse updateActivity(@RequestBody ActivityDTO activityDTO) throws ApiRequestException {
try {
activityService.updateActivity(activityDTO);
return new CustomResponse("Activity successfully updated", OK);
} catch (Exception e) {
throw new ApiRequestException("Activity could not be updated!");
}
}
@PreAuthorize("hasAuthority('Delete_Activity')")
@DeleteMapping(value = "/removeActivity/{id}", produces = APPLICATION_JSON_VALUE)
@ApiOperation(
value = "Delete activity",
notes = "Delete activity based on specific id",
response = ActivityDTO.class
)
public CustomResponse removeActivity(@PathVariable(value = "id") int id) throws ApiRequestException {
try {
activityService.removeActivity(id);
return new CustomResponse("Activity successfully removed", OK);
} catch (Exception e) {
throw new ApiRequestException("Activity could not be deleted!");
}
}
}
| UTF-8 | Java | 5,533 | java | ActivityController.java | Java | [
{
"context": "n = new Permission();\n permission.setName(\"test123\");\n producer.publishMessage(permission);\n ",
"end": 1525,
"score": 0.9972963929176331,
"start": 1518,
"tag": "USERNAME",
"value": "test123"
}
] | null | [] | package com.example.plannerREST.controllers;
import com.example.plannerREST.dto.ActivityDTO;
import com.example.plannerREST.dto.CompanyDTO;
import com.example.plannerREST.entities.AuthRequest;
import com.example.plannerREST.entities.CustomResponse;
import com.example.plannerREST.entities.Permission;
import com.example.plannerREST.exception.ApiRequestException;
import com.example.plannerREST.kafka.Producer;
import com.example.plannerREST.services.ActivityService;
import com.example.plannerREST.services.CompanyService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@RestController
@RequestMapping(value = "/activities")
public class ActivityController {
private Logger logger = LoggerFactory.getLogger(ActivityController.class);
@Autowired
private ActivityService activityService;
@Autowired
private Producer producer;
@Autowired
private CompanyService companyService;
/*
Example of using kafka
@GetMapping("/testKafka/{message}")
public String testKafka(@PathVariable("message") String message) {
Permission permission = new Permission();
permission.setName("test123");
producer.publishMessage(permission);
return "Message is " + message;
}
*/
@PreAuthorize("hasAuthority('View_Activity')")
@GetMapping(value = "/", produces = APPLICATION_JSON_VALUE)
@ApiOperation(
value = "Get all activities",
notes = "Get all activities. You can filter/change the number of companies that are returned",
response = ActivityDTO.class
)
public List<ActivityDTO> getAllActivities(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "5") int size,
@RequestParam(defaultValue = "") String filter) {
return activityService.getAllActivities(page, size, filter);
}
@PreAuthorize("hasAuthority('Add_Activity')")
@GetMapping(value = "/getAllCompanies", produces = APPLICATION_JSON_VALUE)
@ApiOperation(
value = "Getting all companies",
notes = "Getting all companies",
response = CompanyDTO.class
)
public List<CompanyDTO> getAllCompanies() throws ApiRequestException {
try {
return companyService.findAllCompanies();
} catch (Exception e) {
throw new ApiRequestException("Cannot get activity list!");
}
}
@PreAuthorize("hasAuthority('Add_Activity')")
@PostMapping(value = "/addActivity", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
@ApiOperation(
value = "Add new activity",
notes = "Add new activity",
response = CustomResponse.class
)
public CustomResponse saveActivity(@RequestBody ActivityDTO activityDTO) throws ApiRequestException {
try {
activityService.saveActivity(activityDTO);
return new CustomResponse("Activity successfully added", OK);
} catch (Exception e) {
throw new ApiRequestException("Activity could not be added!");
}
}
@PreAuthorize("hasAuthority('Edit_Activity')")
@GetMapping(value = "/editActivity/{id}", produces = APPLICATION_JSON_VALUE)
@ApiOperation(
value = "Edit specific activity",
notes = "Edit specific activity based on specific id",
response = ActivityDTO.class
)
public ActivityDTO editActivity(@PathVariable(value = "id") int id) throws ApiRequestException {
try {
return activityService.getActivity(id);
} catch (Exception e) {
throw new ApiRequestException("Activity not found");
}
}
@PreAuthorize("hasAuthority('Edit_Activity')")
@PutMapping(value = "/updateActivity", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
@ApiOperation(
value = "Update activity",
notes = "Update activity based on specif id",
response = CustomResponse.class
)
public CustomResponse updateActivity(@RequestBody ActivityDTO activityDTO) throws ApiRequestException {
try {
activityService.updateActivity(activityDTO);
return new CustomResponse("Activity successfully updated", OK);
} catch (Exception e) {
throw new ApiRequestException("Activity could not be updated!");
}
}
@PreAuthorize("hasAuthority('Delete_Activity')")
@DeleteMapping(value = "/removeActivity/{id}", produces = APPLICATION_JSON_VALUE)
@ApiOperation(
value = "Delete activity",
notes = "Delete activity based on specific id",
response = ActivityDTO.class
)
public CustomResponse removeActivity(@PathVariable(value = "id") int id) throws ApiRequestException {
try {
activityService.removeActivity(id);
return new CustomResponse("Activity successfully removed", OK);
} catch (Exception e) {
throw new ApiRequestException("Activity could not be deleted!");
}
}
}
| 5,533 | 0.673414 | 0.672149 | 155 | 34.696774 | 30.383648 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.43871 | false | false | 9 |
201f2d3d1a1d0eb2873b81500c9fadba01368048 | 26,920,855,026,171 | 33cd04ab27f727a87e5fafdefbf51db5e3f413fd | /src/main/java/com/steamyao/newcode/web/FeedController.java | 95e3040e88cf592e8e02f1865b9807b8737c59f8 | [
"Apache-2.0"
] | permissive | steamyao/newcode | https://github.com/steamyao/newcode | 5cf7869b0e2e1487829678c6a4de4dd752a0f69b | 9693a62b76d3a90d7027102cf6e4c42caa1492fd | refs/heads/master | 2022-06-28T21:23:02.202000 | 2019-08-14T08:47:23 | 2019-08-14T08:47:23 | 202,309,413 | 0 | 0 | Apache-2.0 | false | 2022-06-21T01:39:57 | 2019-08-14T08:37:25 | 2019-08-14T08:48:28 | 2022-06-21T01:39:54 | 2,051 | 0 | 0 | 3 | CSS | false | false | package com.steamyao.newcode.web;
import com.steamyao.newcode.Utils.JedisAdapter;
import com.steamyao.newcode.Utils.RedisKeyUtil;
import com.steamyao.newcode.dataobject.FeedDO;
import com.steamyao.newcode.model.EntityType;
import com.steamyao.newcode.model.FeedModel;
import com.steamyao.newcode.model.HostHolder;
import com.steamyao.newcode.service.FeedService;
import com.steamyao.newcode.service.FollowService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.ArrayList;
import java.util.List;
/**
* @Package com.steamyao.newcode.web
* @date 2019/8/9 9:58
* @description todo 由于前端页面问题,获取Feed时,不能显示发表问题,只显示评论或关注问题。
*/
@Controller
public class FeedController {
@Autowired
private HostHolder hostHolder;
@Autowired
private FeedService feedService;
@Autowired
private FollowService followService;
@Autowired
private JedisAdapter jedisAdapter;
@GetMapping("/pushfeeds")
public String pushFeeds(Model model){
//todo 没有实现(已解决,feedDO,没有插入ID)
int userId = hostHolder.getUser()!=null? hostHolder.getUser().getId() : 0;
//获取我关注的人的FeedId
//获取我的feed 列表
List<String> feeds = jedisAdapter.lrange(RedisKeyUtil.getTimelineKey(userId), 0, 10);
List<FeedModel> feedList = new ArrayList<>();
//根据我的列表里面的feedId,依次去数据库查询
for(String feed:feeds){
FeedDO feedDO = feedService.getFeedById(Integer.valueOf(feed));
if(feedDO!=null){
//DO -> Model
feedList.add(convertFromDO(feedDO));
}
}
model.addAttribute("feeds", feedList);
return "feeds";
}
@GetMapping("/pullfeeds")
public String pullFeeds(Model model){
int userId = hostHolder.getUser()!=null? hostHolder.getUser().getId() : 0;
List<Integer> followees = new ArrayList<>();;
if(userId!=0){
//获取我关注的人
followees = followService.getFollowees(userId, EntityType.ENTITY_USER,10);
}
//查询我关注的人的动态
List<FeedDO> feeds = feedService.getUserFeeds(Integer.MAX_VALUE, followees, 10);
List<FeedModel> feedList = new ArrayList<>();
//DO -> Model
for (FeedDO feedDO : feeds) {
feedList.add(convertFromDO(feedDO));
}
model.addAttribute("feeds", feedList);
return "feeds";
}
private FeedModel convertFromDO(FeedDO feedDO){
if (feedDO == null){
return null;
}
FeedModel feedModel = new FeedModel();
BeanUtils.copyProperties(feedDO,feedModel);
feedModel.setData(feedDO.getData());
return feedModel;
}
}
| UTF-8 | Java | 3,050 | java | FeedController.java | Java | [] | null | [] | package com.steamyao.newcode.web;
import com.steamyao.newcode.Utils.JedisAdapter;
import com.steamyao.newcode.Utils.RedisKeyUtil;
import com.steamyao.newcode.dataobject.FeedDO;
import com.steamyao.newcode.model.EntityType;
import com.steamyao.newcode.model.FeedModel;
import com.steamyao.newcode.model.HostHolder;
import com.steamyao.newcode.service.FeedService;
import com.steamyao.newcode.service.FollowService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.ArrayList;
import java.util.List;
/**
* @Package com.steamyao.newcode.web
* @date 2019/8/9 9:58
* @description todo 由于前端页面问题,获取Feed时,不能显示发表问题,只显示评论或关注问题。
*/
@Controller
public class FeedController {
@Autowired
private HostHolder hostHolder;
@Autowired
private FeedService feedService;
@Autowired
private FollowService followService;
@Autowired
private JedisAdapter jedisAdapter;
@GetMapping("/pushfeeds")
public String pushFeeds(Model model){
//todo 没有实现(已解决,feedDO,没有插入ID)
int userId = hostHolder.getUser()!=null? hostHolder.getUser().getId() : 0;
//获取我关注的人的FeedId
//获取我的feed 列表
List<String> feeds = jedisAdapter.lrange(RedisKeyUtil.getTimelineKey(userId), 0, 10);
List<FeedModel> feedList = new ArrayList<>();
//根据我的列表里面的feedId,依次去数据库查询
for(String feed:feeds){
FeedDO feedDO = feedService.getFeedById(Integer.valueOf(feed));
if(feedDO!=null){
//DO -> Model
feedList.add(convertFromDO(feedDO));
}
}
model.addAttribute("feeds", feedList);
return "feeds";
}
@GetMapping("/pullfeeds")
public String pullFeeds(Model model){
int userId = hostHolder.getUser()!=null? hostHolder.getUser().getId() : 0;
List<Integer> followees = new ArrayList<>();;
if(userId!=0){
//获取我关注的人
followees = followService.getFollowees(userId, EntityType.ENTITY_USER,10);
}
//查询我关注的人的动态
List<FeedDO> feeds = feedService.getUserFeeds(Integer.MAX_VALUE, followees, 10);
List<FeedModel> feedList = new ArrayList<>();
//DO -> Model
for (FeedDO feedDO : feeds) {
feedList.add(convertFromDO(feedDO));
}
model.addAttribute("feeds", feedList);
return "feeds";
}
private FeedModel convertFromDO(FeedDO feedDO){
if (feedDO == null){
return null;
}
FeedModel feedModel = new FeedModel();
BeanUtils.copyProperties(feedDO,feedModel);
feedModel.setData(feedDO.getData());
return feedModel;
}
}
| 3,050 | 0.67051 | 0.663871 | 87 | 31.896551 | 22.587778 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.586207 | false | false | 9 |
42919129733857521f3bc56c7c4c29425e080e6b | 20,564,303,428,537 | be353524847e07349cc3b87879d4dd862217d4f4 | /src/main/java/com/legwand/nodemonitor/task/PingTask.java | efbfaa95ec90569b8677e815bbd108e4bb29b92f | [
"MIT"
] | permissive | adle11/node-monitor | https://github.com/adle11/node-monitor | 8c278cfb541fd1da14b8dc2a18fa3b2ad1ecb8b8 | c3e4a4422b78b5368d359dbdca2403eaf59f111d | refs/heads/main | 2023-04-23T07:25:45.690000 | 2021-05-11T07:20:53 | 2021-05-11T07:20:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.legwand.nodemonitor.task;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.MessageFormat;
import java.util.logging.Logger;
public class PingTask implements Runnable {
private final static Logger LOG = Logger.getLogger(PingTask.class.getName());
private final int PING_TIMEOUT = 5000;
private final String ipAddress;
private final int port;
public PingTask(String ipAddress, int port) {
this.ipAddress = ipAddress;
this.port = port;
}
@Override
public void run() {
try {
try (Socket soc = new Socket()) {
soc.connect(new InetSocketAddress(ipAddress, port), PING_TIMEOUT);
}
// return true;
LOG.info(MessageFormat.format("{0} is reachable", ipAddress));
} catch (IOException ex) {
// return false;
LOG.info(MessageFormat.format("{0} is NOT reachable", ipAddress));
}
}
}
| UTF-8 | Java | 1,005 | java | PingTask.java | Java | [] | null | [] | package com.legwand.nodemonitor.task;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.MessageFormat;
import java.util.logging.Logger;
public class PingTask implements Runnable {
private final static Logger LOG = Logger.getLogger(PingTask.class.getName());
private final int PING_TIMEOUT = 5000;
private final String ipAddress;
private final int port;
public PingTask(String ipAddress, int port) {
this.ipAddress = ipAddress;
this.port = port;
}
@Override
public void run() {
try {
try (Socket soc = new Socket()) {
soc.connect(new InetSocketAddress(ipAddress, port), PING_TIMEOUT);
}
// return true;
LOG.info(MessageFormat.format("{0} is reachable", ipAddress));
} catch (IOException ex) {
// return false;
LOG.info(MessageFormat.format("{0} is NOT reachable", ipAddress));
}
}
}
| 1,005 | 0.634826 | 0.628856 | 36 | 26.916666 | 23.630695 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false | 9 |
315cd3bd681f44b7bec16e8476b2ee89cd19308a | 11,424,613,027,261 | 92e7a62c54bcf24de97b5d4c1bb15b99f775bed2 | /OpenConcerto/src/org/openconcerto/erp/core/common/ui/IListFilterDatePanel.java | 2919edf282a95bf64b37afaf2a855f92a1a10673 | [] | no_license | trespe/openconcerto | https://github.com/trespe/openconcerto | 4a9c294006187987f64dbf936f167d666e6c5d52 | 6ccd5a7b56cd75350877842998c94434083fb62f | refs/heads/master | 2021-01-13T02:06:29.609000 | 2015-04-10T08:35:31 | 2015-04-10T08:35:31 | 33,717,537 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.common.ui;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JDate;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.ITransformer;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.EventListenerList;
public class IListFilterDatePanel extends JPanel {
private JDate dateDu, dateAu;
private static final String CUSTOM_COMBO_ITEM = "Personnalisée";
private Map<IListe, SQLField> mapList;
// Cache des transformers initiaux
private Map<IListe, ITransformer<SQLSelect, SQLSelect>> mapListTransformer;
// Liste des filtres
private Map<String, Tuple2<Date, Date>> map;
private static LinkedHashMap<String, Tuple2<Date, Date>> mapDefault;
private JComboBox combo;
private EventListenerList listeners = new EventListenerList();
private final PropertyChangeListener listener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
combo.setSelectedItem(CUSTOM_COMBO_ITEM);
fireDateChanged();
}
};
// FIXME Cacher pour ne pas recharger la liste si il n'y a aucune modif
public IListFilterDatePanel(IListe l, SQLField fieldDate) {
this(l, fieldDate, null);
if (l.getRequest() == Configuration.getInstance().getDirectory().getElement(l.getSource().getPrimaryTable()).getListRequest()) {
System.err.println("Attention il ne faut pas utiliser la listrequest par défaut sinon les filtres restes !!!");
Thread.dumpStack();
}
}
public static Map<String, Tuple2<Date, Date>> getDefaultMap() {
if (mapDefault == null) {
initDefaultMap();
}
Map<String, Tuple2<Date, Date>> m = new LinkedHashMap<String, Tuple2<Date, Date>>();
m.putAll(mapDefault);
return m;
}
private static void initDefaultMap() {
mapDefault = new LinkedHashMap<String, Tuple2<Date, Date>>();
// ALL
Date emptyDate = null;
mapDefault.put("Sans filtrage", Tuple2.create(emptyDate, emptyDate));
Calendar c = Calendar.getInstance();
// Année courante
clearTimeSchedule(c);
c.set(Calendar.DATE, 1);
c.set(Calendar.MONTH, 0);
Date d1 = c.getTime();
setEndTimeSchedule(c);
c.set(Calendar.DATE, 31);
c.set(Calendar.MONTH, 11);
Date d2 = c.getTime();
mapDefault.put("Année courante", Tuple2.create(d1, d2));
// Année précedente
clearTimeSchedule(c);
c.set(Calendar.DATE, 1);
c.set(Calendar.MONTH, 0);
c.add(Calendar.YEAR, -1);
Date d3 = c.getTime();
setEndTimeSchedule(c);
c.set(Calendar.DATE, 31);
c.set(Calendar.MONTH, 11);
Date d4 = c.getTime();
mapDefault.put("Année précédente", Tuple2.create(d3, d4));
// Mois courant
c = Calendar.getInstance();
clearTimeSchedule(c);
c.set(Calendar.DATE, 1);
Date d5 = c.getTime();
c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
setEndTimeSchedule(c);
Date d6 = c.getTime();
mapDefault.put("Mois courant", Tuple2.create(d5, d6));
// Mois précédent
c = Calendar.getInstance();
clearTimeSchedule(c);
c.set(Calendar.DATE, 1);
c.add(Calendar.MONTH, -1);
Date d7 = c.getTime();
c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
setEndTimeSchedule(c);
Date d8 = c.getTime();
mapDefault.put("Mois précédent", Tuple2.create(d7, d8));
// semaine courante
c = Calendar.getInstance();
clearTimeSchedule(c);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
Date d9 = c.getTime();
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
setEndTimeSchedule(c);
Date d10 = c.getTime();
mapDefault.put("Semaine courante", Tuple2.create(d9, d10));
// semaine précédente
c = Calendar.getInstance();
clearTimeSchedule(c);
c.add(Calendar.DATE, -7);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
Date d11 = c.getTime();
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
setEndTimeSchedule(c);
Date d12 = c.getTime();
mapDefault.put("Semaine précédente", Tuple2.create(d11, d12));
// Exercice courant
SQLRow rowEx = ComptaPropsConfiguration.getInstanceCompta().getRowSociete().getForeignRow("ID_EXERCICE_COMMON");
Calendar c1 = rowEx.getDate("DATE_DEB");
clearTimeSchedule(c1);
Calendar c2 = rowEx.getDate("DATE_FIN");
setEndTimeSchedule(c2);
final Tuple2<Date, Date> exerciceTuple = Tuple2.create(c1.getTime(), c2.getTime());
if (findItem(exerciceTuple, mapDefault).equals(CUSTOM_COMBO_ITEM)) {
mapDefault.put("Exercice courant", exerciceTuple);
}
// Custom
mapDefault.put(CUSTOM_COMBO_ITEM, null);
}
public static void addDefaultValue(String label, Tuple2<Date, Date> period) {
if (mapDefault == null)
initDefaultMap();
mapDefault.put(label, period);
}
public IListFilterDatePanel(IListe l, SQLField fieldDate, Map<String, Tuple2<Date, Date>> m) {
super(new GridBagLayout());
setOpaque(false);
Map<IListe, SQLField> map = new HashMap<IListe, SQLField>();
map.put(l, fieldDate);
init(map, m);
}
public IListFilterDatePanel(Map<IListe, SQLField> l, Map<String, Tuple2<Date, Date>> m) {
super(new GridBagLayout());
init(l, m);
}
public void init(Map<IListe, SQLField> mapList, Map<String, Tuple2<Date, Date>> m) {
this.setBorder(BorderFactory.createTitledBorder("Période"));
this.mapList = mapList;
this.mapListTransformer = new HashMap<IListe, ITransformer<SQLSelect, SQLSelect>>();
for (IListe l : mapList.keySet()) {
this.mapListTransformer.put(l, l.getRequest().getSelectTransf());
}
this.dateDu = new JDate();
this.dateAu = new JDate();
this.map = m;
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridx = GridBagConstraints.RELATIVE;
c.weightx = 0;
c.fill = GridBagConstraints.NONE;
// Période pédéfini
if (map != null && map.keySet().size() > 0) {
DefaultComboBoxModel model = new DefaultComboBoxModel();
for (String s : this.map.keySet()) {
model.addElement(s);
}
this.combo = new JComboBox(model);
c.weightx = 0;
this.add(combo, c);
combo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String s = (String) combo.getSelectedItem();
setPeriode(map.get(s));
}
});
}
// Filtre
this.add(new JLabel("Du"), c);
c.weightx = 1;
this.add(this.dateDu, c);
c.weightx = 0;
this.add(new JLabel("Au"), c);
c.weightx = 1;
this.add(this.dateAu, c);
this.dateAu.addValueListener(this.listener);
this.dateDu.addValueListener(this.listener);
IListFilterDateStateManager stateManager = new IListFilterDateStateManager(this, getConfigFile(mapList), true);
stateManager.loadState();
}
public void setDateDu(Date d) {
this.dateDu.setValue(d);
}
public void setDateAu(Date d) {
this.dateAu.setValue(d);
}
public Date getFromValue() {
return this.dateDu.getValue();
}
public Date getToValue() {
return this.dateAu.getValue();
}
private static Tuple2<String, Tuple2<Date, Date>> DEFAULT_FILTER = null;
public static void setDefaultFilter(Tuple2<String, Tuple2<Date, Date>> t) {
DEFAULT_FILTER = t;
}
public void setFilterOnDefault() {
if (DEFAULT_FILTER != null) {
if (this.combo != null) {
this.combo.setSelectedItem(DEFAULT_FILTER.get0());
} else {
setPeriode(DEFAULT_FILTER.get1().get0(), DEFAULT_FILTER.get1().get1());
}
}
}
/**
*
* @param t do nothing if t is null
*/
public void setPeriode(Tuple2<Date, Date> t) {
if (t != null) {
setPeriode(t.get0(), t.get1());
}
}
public void setPeriode(Date du, Date au) {
setDateAu(au);
setDateDu(du);
fireDateChanged();
}
public void fireDateChanged() {
System.err.println("FIRE");
if (this.dateAu.getValue() == null && this.dateDu.getValue() == null) {
for (IListe list : this.mapList.keySet()) {
list.getRequest().setSelectTransf(this.mapListTransformer.get(list));
}
} else if (this.dateAu.getValue() == null) {
final Calendar c = Calendar.getInstance();
c.setTime(this.dateDu.getValue());
clearTimeSchedule(c);
for (final IListe list : this.mapList.keySet()) {
final SQLField filterField = this.mapList.get(list);
list.getRequest().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
Where w = new Where(input.getAlias(filterField), ">=", c.getTime());
return setWhere(input, w, mapListTransformer.get(list));
}
});
}
} else if (this.dateDu.getValue() == null) {
final Calendar c = Calendar.getInstance();
c.setTime(this.dateAu.getValue());
setEndTimeSchedule(c);
for (final IListe list : this.mapList.keySet()) {
final SQLField filterField = this.mapList.get(list);
list.getRequest().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
Where w = new Where(input.getAlias(filterField), "<=", c.getTime());
return setWhere(input, w, mapListTransformer.get(list));
}
});
}
} else {
final Calendar c = Calendar.getInstance();
c.setTime(this.dateAu.getValue());
setEndTimeSchedule(c);
final Calendar c2 = Calendar.getInstance();
c2.setTime(this.dateDu.getValue());
clearTimeSchedule(c2);
for (final IListe list : this.mapList.keySet()) {
final SQLField filterField = this.mapList.get(list);
list.getRequest().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
final Where w = new Where(input.getAlias(filterField), c2.getTime(), c.getTime());
return setWhere(input, w, mapListTransformer.get(list));
}
});
}
}
final Tuple2<Date, Date> selectedTuple = Tuple2.create(this.dateDu.getValue(), this.dateAu.getValue());
this.combo.setSelectedItem(findItem(selectedTuple, this.map));
for (PropertyChangeListener l : this.listeners.getListeners(PropertyChangeListener.class)) {
l.propertyChange(new PropertyChangeEvent(this, "valueChanged", null, selectedTuple));
}
}
public void addValueListener(PropertyChangeListener l) {
this.listeners.add(PropertyChangeListener.class, l);
}
public void rmValueListener(PropertyChangeListener l) {
this.listeners.remove(PropertyChangeListener.class, l);
}
private SQLSelect setWhere(SQLSelect input, Where w, ITransformer<SQLSelect, SQLSelect> t) {
if (t != null) {
input = t.transformChecked(input);
}
input.andWhere(w);
return input;
}
public static String findItem(Tuple2<Date, Date> t, Map<String, Tuple2<Date, Date>> mapItem) {
Date d1 = t.get0();
Date d2 = t.get1();
Calendar c1 = getCalendarFromDate(d1);
Calendar c2 = getCalendarFromDate(d2);
for (String label : mapItem.keySet()) {
Tuple2<Date, Date> t2 = mapItem.get(label);
if (t2 != null) {
final Date get0 = t2.get0();
final Date get1 = t2.get1();
Calendar cGet0 = getCalendarFromDate(get0);
Calendar cGet1 = getCalendarFromDate(get1);
if (isDateEquals(c1, cGet0) && isDateEquals(c2, cGet1)) {
return label;
}
}
}
return CUSTOM_COMBO_ITEM;
}
private static Calendar getCalendarFromDate(final Date d) {
Calendar cal = null;
if (d != null) {
cal = Calendar.getInstance();
cal.setTime(d);
}
return cal;
}
public static boolean isDateEquals(Calendar d1, Calendar d2) {
boolean b = false;
if (d1 == null && d2 == null) {
b = true;
} else if (d1 != null && d2 != null) {
b = d1.get(Calendar.DAY_OF_MONTH) == d2.get(Calendar.DAY_OF_MONTH) && d2.get(Calendar.YEAR) == d1.get(Calendar.YEAR) && d1.get(Calendar.MONTH) == d2.get(Calendar.MONTH);
} else {
b = false;
}
return b;
}
private static void clearTimeSchedule(final Calendar c) {
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
}
private static void setEndTimeSchedule(final Calendar c) {
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 59);
}
static private final File getConfigFile(Map<IListe, SQLField> mapList) {
final Configuration conf = Configuration.getInstance();
if (conf == null)
return null;
String name = null;
for (IListe l : mapList.keySet()) {
final File configFile = l.getConfigFile();
if (configFile != null) {
String confName = configFile.getName();
if (name == null) {
name = confName;
} else if (name.compareTo(confName) > 0) {
name = confName;
}
} else {
name = l.getSource().getPrimaryTable().getName();
}
}
return new File(conf.getConfDir(), "DateRanges" + File.separator + name);
}
}
| UTF-8 | Java | 16,913 | java | IListFilterDatePanel.java | Java | [] | null | [] | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.erp.core.common.ui;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JDate;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.ITransformer;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.EventListenerList;
public class IListFilterDatePanel extends JPanel {
private JDate dateDu, dateAu;
private static final String CUSTOM_COMBO_ITEM = "Personnalisée";
private Map<IListe, SQLField> mapList;
// Cache des transformers initiaux
private Map<IListe, ITransformer<SQLSelect, SQLSelect>> mapListTransformer;
// Liste des filtres
private Map<String, Tuple2<Date, Date>> map;
private static LinkedHashMap<String, Tuple2<Date, Date>> mapDefault;
private JComboBox combo;
private EventListenerList listeners = new EventListenerList();
private final PropertyChangeListener listener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
combo.setSelectedItem(CUSTOM_COMBO_ITEM);
fireDateChanged();
}
};
// FIXME Cacher pour ne pas recharger la liste si il n'y a aucune modif
public IListFilterDatePanel(IListe l, SQLField fieldDate) {
this(l, fieldDate, null);
if (l.getRequest() == Configuration.getInstance().getDirectory().getElement(l.getSource().getPrimaryTable()).getListRequest()) {
System.err.println("Attention il ne faut pas utiliser la listrequest par défaut sinon les filtres restes !!!");
Thread.dumpStack();
}
}
public static Map<String, Tuple2<Date, Date>> getDefaultMap() {
if (mapDefault == null) {
initDefaultMap();
}
Map<String, Tuple2<Date, Date>> m = new LinkedHashMap<String, Tuple2<Date, Date>>();
m.putAll(mapDefault);
return m;
}
private static void initDefaultMap() {
mapDefault = new LinkedHashMap<String, Tuple2<Date, Date>>();
// ALL
Date emptyDate = null;
mapDefault.put("Sans filtrage", Tuple2.create(emptyDate, emptyDate));
Calendar c = Calendar.getInstance();
// Année courante
clearTimeSchedule(c);
c.set(Calendar.DATE, 1);
c.set(Calendar.MONTH, 0);
Date d1 = c.getTime();
setEndTimeSchedule(c);
c.set(Calendar.DATE, 31);
c.set(Calendar.MONTH, 11);
Date d2 = c.getTime();
mapDefault.put("Année courante", Tuple2.create(d1, d2));
// Année précedente
clearTimeSchedule(c);
c.set(Calendar.DATE, 1);
c.set(Calendar.MONTH, 0);
c.add(Calendar.YEAR, -1);
Date d3 = c.getTime();
setEndTimeSchedule(c);
c.set(Calendar.DATE, 31);
c.set(Calendar.MONTH, 11);
Date d4 = c.getTime();
mapDefault.put("Année précédente", Tuple2.create(d3, d4));
// Mois courant
c = Calendar.getInstance();
clearTimeSchedule(c);
c.set(Calendar.DATE, 1);
Date d5 = c.getTime();
c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
setEndTimeSchedule(c);
Date d6 = c.getTime();
mapDefault.put("Mois courant", Tuple2.create(d5, d6));
// Mois précédent
c = Calendar.getInstance();
clearTimeSchedule(c);
c.set(Calendar.DATE, 1);
c.add(Calendar.MONTH, -1);
Date d7 = c.getTime();
c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
setEndTimeSchedule(c);
Date d8 = c.getTime();
mapDefault.put("Mois précédent", Tuple2.create(d7, d8));
// semaine courante
c = Calendar.getInstance();
clearTimeSchedule(c);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
Date d9 = c.getTime();
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
setEndTimeSchedule(c);
Date d10 = c.getTime();
mapDefault.put("Semaine courante", Tuple2.create(d9, d10));
// semaine précédente
c = Calendar.getInstance();
clearTimeSchedule(c);
c.add(Calendar.DATE, -7);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
Date d11 = c.getTime();
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
setEndTimeSchedule(c);
Date d12 = c.getTime();
mapDefault.put("Semaine précédente", Tuple2.create(d11, d12));
// Exercice courant
SQLRow rowEx = ComptaPropsConfiguration.getInstanceCompta().getRowSociete().getForeignRow("ID_EXERCICE_COMMON");
Calendar c1 = rowEx.getDate("DATE_DEB");
clearTimeSchedule(c1);
Calendar c2 = rowEx.getDate("DATE_FIN");
setEndTimeSchedule(c2);
final Tuple2<Date, Date> exerciceTuple = Tuple2.create(c1.getTime(), c2.getTime());
if (findItem(exerciceTuple, mapDefault).equals(CUSTOM_COMBO_ITEM)) {
mapDefault.put("Exercice courant", exerciceTuple);
}
// Custom
mapDefault.put(CUSTOM_COMBO_ITEM, null);
}
public static void addDefaultValue(String label, Tuple2<Date, Date> period) {
if (mapDefault == null)
initDefaultMap();
mapDefault.put(label, period);
}
public IListFilterDatePanel(IListe l, SQLField fieldDate, Map<String, Tuple2<Date, Date>> m) {
super(new GridBagLayout());
setOpaque(false);
Map<IListe, SQLField> map = new HashMap<IListe, SQLField>();
map.put(l, fieldDate);
init(map, m);
}
public IListFilterDatePanel(Map<IListe, SQLField> l, Map<String, Tuple2<Date, Date>> m) {
super(new GridBagLayout());
init(l, m);
}
public void init(Map<IListe, SQLField> mapList, Map<String, Tuple2<Date, Date>> m) {
this.setBorder(BorderFactory.createTitledBorder("Période"));
this.mapList = mapList;
this.mapListTransformer = new HashMap<IListe, ITransformer<SQLSelect, SQLSelect>>();
for (IListe l : mapList.keySet()) {
this.mapListTransformer.put(l, l.getRequest().getSelectTransf());
}
this.dateDu = new JDate();
this.dateAu = new JDate();
this.map = m;
GridBagConstraints c = new DefaultGridBagConstraints();
c.gridx = GridBagConstraints.RELATIVE;
c.weightx = 0;
c.fill = GridBagConstraints.NONE;
// Période pédéfini
if (map != null && map.keySet().size() > 0) {
DefaultComboBoxModel model = new DefaultComboBoxModel();
for (String s : this.map.keySet()) {
model.addElement(s);
}
this.combo = new JComboBox(model);
c.weightx = 0;
this.add(combo, c);
combo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String s = (String) combo.getSelectedItem();
setPeriode(map.get(s));
}
});
}
// Filtre
this.add(new JLabel("Du"), c);
c.weightx = 1;
this.add(this.dateDu, c);
c.weightx = 0;
this.add(new JLabel("Au"), c);
c.weightx = 1;
this.add(this.dateAu, c);
this.dateAu.addValueListener(this.listener);
this.dateDu.addValueListener(this.listener);
IListFilterDateStateManager stateManager = new IListFilterDateStateManager(this, getConfigFile(mapList), true);
stateManager.loadState();
}
public void setDateDu(Date d) {
this.dateDu.setValue(d);
}
public void setDateAu(Date d) {
this.dateAu.setValue(d);
}
public Date getFromValue() {
return this.dateDu.getValue();
}
public Date getToValue() {
return this.dateAu.getValue();
}
private static Tuple2<String, Tuple2<Date, Date>> DEFAULT_FILTER = null;
public static void setDefaultFilter(Tuple2<String, Tuple2<Date, Date>> t) {
DEFAULT_FILTER = t;
}
public void setFilterOnDefault() {
if (DEFAULT_FILTER != null) {
if (this.combo != null) {
this.combo.setSelectedItem(DEFAULT_FILTER.get0());
} else {
setPeriode(DEFAULT_FILTER.get1().get0(), DEFAULT_FILTER.get1().get1());
}
}
}
/**
*
* @param t do nothing if t is null
*/
public void setPeriode(Tuple2<Date, Date> t) {
if (t != null) {
setPeriode(t.get0(), t.get1());
}
}
public void setPeriode(Date du, Date au) {
setDateAu(au);
setDateDu(du);
fireDateChanged();
}
public void fireDateChanged() {
System.err.println("FIRE");
if (this.dateAu.getValue() == null && this.dateDu.getValue() == null) {
for (IListe list : this.mapList.keySet()) {
list.getRequest().setSelectTransf(this.mapListTransformer.get(list));
}
} else if (this.dateAu.getValue() == null) {
final Calendar c = Calendar.getInstance();
c.setTime(this.dateDu.getValue());
clearTimeSchedule(c);
for (final IListe list : this.mapList.keySet()) {
final SQLField filterField = this.mapList.get(list);
list.getRequest().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
Where w = new Where(input.getAlias(filterField), ">=", c.getTime());
return setWhere(input, w, mapListTransformer.get(list));
}
});
}
} else if (this.dateDu.getValue() == null) {
final Calendar c = Calendar.getInstance();
c.setTime(this.dateAu.getValue());
setEndTimeSchedule(c);
for (final IListe list : this.mapList.keySet()) {
final SQLField filterField = this.mapList.get(list);
list.getRequest().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
Where w = new Where(input.getAlias(filterField), "<=", c.getTime());
return setWhere(input, w, mapListTransformer.get(list));
}
});
}
} else {
final Calendar c = Calendar.getInstance();
c.setTime(this.dateAu.getValue());
setEndTimeSchedule(c);
final Calendar c2 = Calendar.getInstance();
c2.setTime(this.dateDu.getValue());
clearTimeSchedule(c2);
for (final IListe list : this.mapList.keySet()) {
final SQLField filterField = this.mapList.get(list);
list.getRequest().setSelectTransf(new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
final Where w = new Where(input.getAlias(filterField), c2.getTime(), c.getTime());
return setWhere(input, w, mapListTransformer.get(list));
}
});
}
}
final Tuple2<Date, Date> selectedTuple = Tuple2.create(this.dateDu.getValue(), this.dateAu.getValue());
this.combo.setSelectedItem(findItem(selectedTuple, this.map));
for (PropertyChangeListener l : this.listeners.getListeners(PropertyChangeListener.class)) {
l.propertyChange(new PropertyChangeEvent(this, "valueChanged", null, selectedTuple));
}
}
public void addValueListener(PropertyChangeListener l) {
this.listeners.add(PropertyChangeListener.class, l);
}
public void rmValueListener(PropertyChangeListener l) {
this.listeners.remove(PropertyChangeListener.class, l);
}
private SQLSelect setWhere(SQLSelect input, Where w, ITransformer<SQLSelect, SQLSelect> t) {
if (t != null) {
input = t.transformChecked(input);
}
input.andWhere(w);
return input;
}
public static String findItem(Tuple2<Date, Date> t, Map<String, Tuple2<Date, Date>> mapItem) {
Date d1 = t.get0();
Date d2 = t.get1();
Calendar c1 = getCalendarFromDate(d1);
Calendar c2 = getCalendarFromDate(d2);
for (String label : mapItem.keySet()) {
Tuple2<Date, Date> t2 = mapItem.get(label);
if (t2 != null) {
final Date get0 = t2.get0();
final Date get1 = t2.get1();
Calendar cGet0 = getCalendarFromDate(get0);
Calendar cGet1 = getCalendarFromDate(get1);
if (isDateEquals(c1, cGet0) && isDateEquals(c2, cGet1)) {
return label;
}
}
}
return CUSTOM_COMBO_ITEM;
}
private static Calendar getCalendarFromDate(final Date d) {
Calendar cal = null;
if (d != null) {
cal = Calendar.getInstance();
cal.setTime(d);
}
return cal;
}
public static boolean isDateEquals(Calendar d1, Calendar d2) {
boolean b = false;
if (d1 == null && d2 == null) {
b = true;
} else if (d1 != null && d2 != null) {
b = d1.get(Calendar.DAY_OF_MONTH) == d2.get(Calendar.DAY_OF_MONTH) && d2.get(Calendar.YEAR) == d1.get(Calendar.YEAR) && d1.get(Calendar.MONTH) == d2.get(Calendar.MONTH);
} else {
b = false;
}
return b;
}
private static void clearTimeSchedule(final Calendar c) {
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
}
private static void setEndTimeSchedule(final Calendar c) {
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 59);
}
static private final File getConfigFile(Map<IListe, SQLField> mapList) {
final Configuration conf = Configuration.getInstance();
if (conf == null)
return null;
String name = null;
for (IListe l : mapList.keySet()) {
final File configFile = l.getConfigFile();
if (configFile != null) {
String confName = configFile.getName();
if (name == null) {
name = confName;
} else if (name.compareTo(confName) > 0) {
name = confName;
}
} else {
name = l.getSource().getPrimaryTable().getName();
}
}
return new File(conf.getConfDir(), "DateRanges" + File.separator + name);
}
}
| 16,913 | 0.580867 | 0.571632 | 472 | 33.788136 | 28.167885 | 181 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.79661 | false | false | 9 |
e956c6a0d993442329b242e20f6e4f13518c2660 | 19,035,295,084,295 | 0b2e227b1404c6409fe5586e445a94c03ac9fa6d | /src/main/java/com/qcby/service/ChargeRecordService.java | 5db433a2459be5965850e96c4625fc3a04f4d34a | [] | no_license | yechang1450/TestSpringMAC | https://github.com/yechang1450/TestSpringMAC | 1158addc509851eff853111c97ed188dcc60d706 | 5c03cb7a49dd8b9c75562bfdf05983a220bb5ecb | refs/heads/master | 2023-03-08T12:06:00.090000 | 2021-02-20T11:30:55 | 2021-02-20T11:30:55 | 340,637,596 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.qcby.service;
import com.qcby.entity.ChargeRecord;
import java.util.List;
public interface ChargeRecordService {
List<ChargeRecord> findUserRecord(ChargeRecord chargeRecord, int page, int limit);
int selectCount();
}
| UTF-8 | Java | 241 | java | ChargeRecordService.java | Java | [] | null | [] | package com.qcby.service;
import com.qcby.entity.ChargeRecord;
import java.util.List;
public interface ChargeRecordService {
List<ChargeRecord> findUserRecord(ChargeRecord chargeRecord, int page, int limit);
int selectCount();
}
| 241 | 0.775934 | 0.775934 | 11 | 20.90909 | 25.083332 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 9 |
fe5a7b075030af3c00f4b0df60ef74f35a5e00ba | 19,035,295,084,653 | 0e59323f4311dcc9a34bfab1bcebcfd963d5575f | /src/main/java/org/launchcode/blogz/models/dao/StudentDao.java | 1f406bfc00f808ccb37ef63b27f48be8dee58131 | [] | no_license | harithayelamanchili/Students | https://github.com/harithayelamanchili/Students | 1e59cc11a646fd90b15f6b7fc2d036e34f7ab8a7 | 652390a7c8c25d0fb9c4e97c168b191943c7ca24 | refs/heads/master | 2020-05-23T05:14:44.785000 | 2017-01-16T00:32:18 | 2017-01-16T00:32:18 | 59,496,896 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.launchcode.blogz.models.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.launchcode.blogz.models.Student;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Transactional
@Repository
public interface StudentDao extends CrudRepository<Student, Integer> {
Student findByUid(int uid);
List<Student> findAll();
Student findByUsername(String username);
// TODO - add method signatures as needed
} | UTF-8 | Java | 545 | java | StudentDao.java | Java | [] | null | [] | package org.launchcode.blogz.models.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.launchcode.blogz.models.Student;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Transactional
@Repository
public interface StudentDao extends CrudRepository<Student, Integer> {
Student findByUid(int uid);
List<Student> findAll();
Student findByUsername(String username);
// TODO - add method signatures as needed
} | 545 | 0.750459 | 0.750459 | 22 | 22.863636 | 22.027452 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 9 |
7db9d523c38f8a7a8ee4ab96032299afd1726505 | 30,296,699,322,710 | a1fe0af093dcffc28dd47fd655120e0e0b2a8bea | /proteomics-function/src/cn/ac/dicp/function/db/filter/FastaAccessionFilter.java | 7108c23314a16769c33ca97d08f9ae12f7e487de | [] | no_license | jiaweiM/proteomics | https://github.com/jiaweiM/proteomics | 988e04a5f3c33c1bfc742067a45329a977e9d8cb | 73687d7d3ddf64eb4b6a77f60ddd7b0a07d8cd9e | refs/heads/master | 2018-01-09T19:52:01.391000 | 2016-03-15T00:57:18 | 2016-03-15T00:57:18 | 49,556,273 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**********************************************************
* File:FastaAccessionFilter.java
*
* Author: Jiawei Mao
*
* Created on Feb 23, 2016
*
* Copyright (c) Dalian Institute of Chemical Physics
* Chinese Academy of Sciences
*
* Contact: jiawei@dicp.ac.cn
*
*******************************************************/
package cn.ac.dicp.function.db.filter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import cn.ac.dicp.function.db.DBProtein;
import cn.ac.dicp.function.db.ProteinFilter;
/**
* @author JiaweiMao
* @date Feb 23, 2016 4:36:33 PM
*/
public class FastaAccessionFilter implements ProteinFilter {
private Set<String> iAccSet = new HashSet<>();
private boolean iInvert = false;
/**
* Constructor, takes a single String of a comma separated list of accession
* number.
*
* @param aAcc a comma separated list of accessions.
* @param aInvert boolean to indicate whether to apply the boolean 'NOT'
* operator to the results of the filter.
*/
public FastaAccessionFilter(String aAcc, boolean aInvert) {
String[] tem = aAcc.split(",");
for (String s : tem) {
s = s.trim().intern();
iAccSet.add(s);
}
this.iInvert = aInvert;
}
/**
* Constructor.
*
* @param aAccList accession list
* @param aInvert boolean to indicate whether to apply the boolean 'NOT'
* operator to the results of the filter.
*/
public FastaAccessionFilter(List<String> aAccList, boolean aInvert) {
for (String string : aAccList) {
iAccSet.add(string);
}
this.iInvert = aInvert;
}
public FastaAccessionFilter(List<String> accList) {
this(accList, false);
}
@Override
public boolean passesFilter(DBProtein aProtein) {
boolean result = false;
String acc = aProtein.getHeader().getAccession();
if (iAccSet.contains(acc)) {
result = true;
}
if (iInvert) {
result = !result;
}
return result;
}
@Override
public void setInversion(boolean aInvert) {
this.iInvert = aInvert;
}
}
| UTF-8 | Java | 2,218 | java | FastaAccessionFilter.java | Java | [
{
"context": " File:FastaAccessionFilter.java\r\n *\r\n * Author:\tJiawei Mao \r\n *\r\n * Created on Feb 23,",
"end": 124,
"score": 0.9998157620429993,
"start": 114,
"tag": "NAME",
"value": "Jiawei Mao"
},
{
"context": " *\tChinese Academy of Sciences\r\n * \r\n * Contact: jiawei@dicp.ac.cn \r\n * ",
"end": 334,
"score": 0.9999303817749023,
"start": 317,
"tag": "EMAIL",
"value": "jiawei@dicp.ac.cn"
},
{
"context": "dicp.function.db.ProteinFilter;\r\n\r\n/**\r\n * @author JiaweiMao\r\n * @date Feb 23, 2016 4:36:33 PM\r\n */\r\npublic cl",
"end": 699,
"score": 0.8095157742500305,
"start": 690,
"tag": "USERNAME",
"value": "JiaweiMao"
}
] | null | [] | /**********************************************************
* File:FastaAccessionFilter.java
*
* Author: <NAME>
*
* Created on Feb 23, 2016
*
* Copyright (c) Dalian Institute of Chemical Physics
* Chinese Academy of Sciences
*
* Contact: <EMAIL>
*
*******************************************************/
package cn.ac.dicp.function.db.filter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import cn.ac.dicp.function.db.DBProtein;
import cn.ac.dicp.function.db.ProteinFilter;
/**
* @author JiaweiMao
* @date Feb 23, 2016 4:36:33 PM
*/
public class FastaAccessionFilter implements ProteinFilter {
private Set<String> iAccSet = new HashSet<>();
private boolean iInvert = false;
/**
* Constructor, takes a single String of a comma separated list of accession
* number.
*
* @param aAcc a comma separated list of accessions.
* @param aInvert boolean to indicate whether to apply the boolean 'NOT'
* operator to the results of the filter.
*/
public FastaAccessionFilter(String aAcc, boolean aInvert) {
String[] tem = aAcc.split(",");
for (String s : tem) {
s = s.trim().intern();
iAccSet.add(s);
}
this.iInvert = aInvert;
}
/**
* Constructor.
*
* @param aAccList accession list
* @param aInvert boolean to indicate whether to apply the boolean 'NOT'
* operator to the results of the filter.
*/
public FastaAccessionFilter(List<String> aAccList, boolean aInvert) {
for (String string : aAccList) {
iAccSet.add(string);
}
this.iInvert = aInvert;
}
public FastaAccessionFilter(List<String> accList) {
this(accList, false);
}
@Override
public boolean passesFilter(DBProtein aProtein) {
boolean result = false;
String acc = aProtein.getHeader().getAccession();
if (iAccSet.contains(acc)) {
result = true;
}
if (iInvert) {
result = !result;
}
return result;
}
@Override
public void setInversion(boolean aInvert) {
this.iInvert = aInvert;
}
}
| 2,204 | 0.585212 | 0.577547 | 87 | 23.494253 | 21.810507 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.218391 | false | false | 9 |
04339d3059b6e177787a5eeb189ada03480a7872 | 28,845,000,378,833 | 7edb52d196e80935cd9e09c041437565707ef9f1 | /Miam/src/vue/listeAliment/GaneshRendu.java | f04da1bd1998c0a66a900ed26e2f092028966291 | [] | no_license | michelange2008/miam | https://github.com/michelange2008/miam | 92c0ce4327bacf951612a960d274bbc68a2196d3 | 341999ef8ff259655211f801354b06edaca7a00e | refs/heads/master | 2020-12-24T21:23:01.874000 | 2016-05-26T11:47:30 | 2016-05-26T11:47:30 | 59,744,081 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vue.listeAliment;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import vue.elements.E_FONTPERSO;
import vue.elements.E_TEINTES;
/** Classe de rendu de la table qui définit la couleur, la largeur des colonnes et la hauteur des lignes
*/
@SuppressWarnings("serial")
public class GaneshRendu extends DefaultTableCellRenderer{
public GaneshRendu(JTable jt, Color av){
UIManager.getDefaults().put("Table.alternateRowColor", E_TEINTES.ROUGE.clair());
jt.setForeground(av);
jt.setRowHeight(40);
Font font = E_FONTPERSO.CABIN.getFontPerso(16);
jt.setFont(font);
this.setHorizontalAlignment(SwingConstants.CENTER);
}
} | UTF-8 | Java | 844 | java | GaneshRendu.java | Java | [] | null | [] | package vue.listeAliment;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import vue.elements.E_FONTPERSO;
import vue.elements.E_TEINTES;
/** Classe de rendu de la table qui définit la couleur, la largeur des colonnes et la hauteur des lignes
*/
@SuppressWarnings("serial")
public class GaneshRendu extends DefaultTableCellRenderer{
public GaneshRendu(JTable jt, Color av){
UIManager.getDefaults().put("Table.alternateRowColor", E_TEINTES.ROUGE.clair());
jt.setForeground(av);
jt.setRowHeight(40);
Font font = E_FONTPERSO.CABIN.getFontPerso(16);
jt.setFont(font);
this.setHorizontalAlignment(SwingConstants.CENTER);
}
} | 844 | 0.785291 | 0.780546 | 30 | 27.133333 | 24.655943 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.233333 | false | false | 9 |
7f23b0318366b9f103495d1c42fc57889e4faaad | 28,845,000,381,021 | 19e73519f478fa9e5aecd59a59ff1948d79e1449 | /src/main/java/net/soundvibe/reacto/internal/InternalEvent.java | 009d89529e19d20479ab20c79e472fe7acb6c0a8 | [
"Apache-2.0"
] | permissive | soundvibe/reacto | https://github.com/soundvibe/reacto | 51941abad2f3676e05a7cc4b5bc9c09577a9e1fc | f04243474cca35ed5be129c8908929f209cb1c47 | refs/heads/develop | 2021-04-09T17:40:51.779000 | 2019-02-03T17:38:16 | 2019-02-03T17:38:16 | 51,521,087 | 7 | 4 | Apache-2.0 | false | 2018-11-02T09:28:57 | 2016-02-11T14:47:56 | 2017-07-04T10:18:10 | 2018-11-02T09:28:57 | 593 | 6 | 2 | 1 | Java | false | null | package net.soundvibe.reacto.internal;
import net.soundvibe.reacto.mappers.Mappers;
import net.soundvibe.reacto.types.*;
import net.soundvibe.reacto.utils.Bytes;
import java.util.*;
/**
* @author Linas on 2015.11.13.
*/
public final class InternalEvent {
public static final String COMMAND_ID = "cmdId";
public static final String ERROR_EVENT_NAME = "error";
public final String name;
public final Optional<MetaData> metaData;
public final Optional<byte[]> payload;
public final EventType eventType;
public final Optional<Throwable> error;
InternalEvent(String name, Optional<MetaData> metaData, Optional<byte[]> payload, Optional<Throwable> error, EventType eventType) {
this.name = name;
this.metaData = metaData;
this.payload = payload;
this.eventType = eventType;
this.error = error;
}
private InternalEvent(Throwable error) {
this.name = ERROR_EVENT_NAME;
this.eventType = EventType.ERROR;
this.metaData = Optional.empty();
this.error = Optional.ofNullable(error);
this.payload = this.error.flatMap(Mappers::exceptionToBytes);
}
private InternalEvent(Throwable error, String cmdId) {
this.name = ERROR_EVENT_NAME;
this.eventType = EventType.ERROR;
this.metaData = Optional.of(ofCmd(cmdId));
this.error = Optional.ofNullable(error);
this.payload = this.error.flatMap(Mappers::exceptionToBytes);
}
public Optional<String> commandId() {
return metaData.flatMap(meta -> meta.valueOf(COMMAND_ID));
}
private static MetaData ofCmd(String cmdId) {
return MetaData.of(COMMAND_ID, cmdId);
}
public static InternalEvent onNext(Event event) {
return new InternalEvent(event.name, event.metaData, event.payload, Optional.empty(), EventType.NEXT);
}
public static InternalEvent onNext(Event event, String cmdId) {
return new InternalEvent(event.name, Optional.of(ofCmd(cmdId).concat(event.metaData.orElse(MetaData.empty()))) ,
event.payload, Optional.empty(), EventType.NEXT);
}
public static InternalEvent onError(Throwable throwable) {
return new InternalEvent(throwable);
}
public static InternalEvent onError(Throwable throwable, String cmdId) {
return new InternalEvent(throwable, cmdId);
}
public static InternalEvent onCompleted() {
return new InternalEvent("completed", Optional.empty(), Optional.empty(), Optional.empty(), EventType.COMPLETED);
}
public static InternalEvent onCompleted(String cmdId) {
return new InternalEvent("completed", Optional.of(ofCmd(cmdId)), Optional.empty(), Optional.empty(), EventType.COMPLETED);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InternalEvent internalEvent = (InternalEvent) o;
return Objects.equals(name, internalEvent.name) &&
Objects.equals(metaData, internalEvent.metaData) &&
Bytes.payloadsAreEqual(this.payload, internalEvent.payload) &&
eventType == internalEvent.eventType &&
Objects.equals(error, internalEvent.error);
}
@Override
public int hashCode() {
return Objects.hash(name, metaData, payload.map(Arrays::hashCode).orElse(0), eventType, error);
}
@Override
public String toString() {
return "InternalEvent{" +
"name='" + name + '\'' +
", metaData=" + metaData +
", payload=" + payload +
", eventType=" + eventType +
", error=" + error +
'}';
}
}
| UTF-8 | Java | 3,775 | java | InternalEvent.java | Java | [
{
"context": ".utils.Bytes;\n\nimport java.util.*;\n\n/**\n * @author Linas on 2015.11.13.\n */\n\npublic final class InternalEv",
"end": 205,
"score": 0.7844393253326416,
"start": 200,
"tag": "USERNAME",
"value": "Linas"
}
] | null | [] | package net.soundvibe.reacto.internal;
import net.soundvibe.reacto.mappers.Mappers;
import net.soundvibe.reacto.types.*;
import net.soundvibe.reacto.utils.Bytes;
import java.util.*;
/**
* @author Linas on 2015.11.13.
*/
public final class InternalEvent {
public static final String COMMAND_ID = "cmdId";
public static final String ERROR_EVENT_NAME = "error";
public final String name;
public final Optional<MetaData> metaData;
public final Optional<byte[]> payload;
public final EventType eventType;
public final Optional<Throwable> error;
InternalEvent(String name, Optional<MetaData> metaData, Optional<byte[]> payload, Optional<Throwable> error, EventType eventType) {
this.name = name;
this.metaData = metaData;
this.payload = payload;
this.eventType = eventType;
this.error = error;
}
private InternalEvent(Throwable error) {
this.name = ERROR_EVENT_NAME;
this.eventType = EventType.ERROR;
this.metaData = Optional.empty();
this.error = Optional.ofNullable(error);
this.payload = this.error.flatMap(Mappers::exceptionToBytes);
}
private InternalEvent(Throwable error, String cmdId) {
this.name = ERROR_EVENT_NAME;
this.eventType = EventType.ERROR;
this.metaData = Optional.of(ofCmd(cmdId));
this.error = Optional.ofNullable(error);
this.payload = this.error.flatMap(Mappers::exceptionToBytes);
}
public Optional<String> commandId() {
return metaData.flatMap(meta -> meta.valueOf(COMMAND_ID));
}
private static MetaData ofCmd(String cmdId) {
return MetaData.of(COMMAND_ID, cmdId);
}
public static InternalEvent onNext(Event event) {
return new InternalEvent(event.name, event.metaData, event.payload, Optional.empty(), EventType.NEXT);
}
public static InternalEvent onNext(Event event, String cmdId) {
return new InternalEvent(event.name, Optional.of(ofCmd(cmdId).concat(event.metaData.orElse(MetaData.empty()))) ,
event.payload, Optional.empty(), EventType.NEXT);
}
public static InternalEvent onError(Throwable throwable) {
return new InternalEvent(throwable);
}
public static InternalEvent onError(Throwable throwable, String cmdId) {
return new InternalEvent(throwable, cmdId);
}
public static InternalEvent onCompleted() {
return new InternalEvent("completed", Optional.empty(), Optional.empty(), Optional.empty(), EventType.COMPLETED);
}
public static InternalEvent onCompleted(String cmdId) {
return new InternalEvent("completed", Optional.of(ofCmd(cmdId)), Optional.empty(), Optional.empty(), EventType.COMPLETED);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InternalEvent internalEvent = (InternalEvent) o;
return Objects.equals(name, internalEvent.name) &&
Objects.equals(metaData, internalEvent.metaData) &&
Bytes.payloadsAreEqual(this.payload, internalEvent.payload) &&
eventType == internalEvent.eventType &&
Objects.equals(error, internalEvent.error);
}
@Override
public int hashCode() {
return Objects.hash(name, metaData, payload.map(Arrays::hashCode).orElse(0), eventType, error);
}
@Override
public String toString() {
return "InternalEvent{" +
"name='" + name + '\'' +
", metaData=" + metaData +
", payload=" + payload +
", eventType=" + eventType +
", error=" + error +
'}';
}
}
| 3,775 | 0.646623 | 0.644238 | 109 | 33.633026 | 31.070993 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733945 | false | false | 9 |
7d9fc4165f56cbe5e177d4122684f6ea63171f86 | 8,770,323,244,218 | 55c6652794cfb7701bcd3b2cbd8c355a7aee8e7d | /OU_Spring/src/main/java/org/firstonlineuniversity/constants/QuizConstants.java | ca6f8db43799de726d074451850f3d172425ac5a | [] | no_license | rohitkumarlohiya/mycode | https://github.com/rohitkumarlohiya/mycode | 592c04bac578290d24a82aed1876f16b6826c2aa | 7b5b0bd0b418b795fd150e7a66893bca0fcec1aa | refs/heads/master | 2016-09-18T05:54:02.310000 | 2015-11-26T22:15:54 | 2015-11-26T22:15:54 | 66,782,648 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.firstonlineuniversity.constants;
public class QuizConstants {
public static final int QUES_TYPE_MULTIPLE_CHOICE = 1;
public static final int QUES_TYPE_TRUE_FALSE = 2;
public static final int QUES_TYPE_MULTIPLE_ANSWER = 3;
public static final int QUES_TYPE_FILL_IN_THE_BLANKS = 4;
public static final int QUES_TYPE_MATCHING = 5;
public static final int QUES_TYPE_TEXT_OR_NUMERIC = 6;
public static final String QUIZ_STATUS_STARTED = "1";
public static final String QUIZ_STATUS_IN_PROGRESS = "2";
public static final String QUIZ_STATUS_SUBMITTED = "3";
}
| UTF-8 | Java | 590 | java | QuizConstants.java | Java | [] | null | [] | package org.firstonlineuniversity.constants;
public class QuizConstants {
public static final int QUES_TYPE_MULTIPLE_CHOICE = 1;
public static final int QUES_TYPE_TRUE_FALSE = 2;
public static final int QUES_TYPE_MULTIPLE_ANSWER = 3;
public static final int QUES_TYPE_FILL_IN_THE_BLANKS = 4;
public static final int QUES_TYPE_MATCHING = 5;
public static final int QUES_TYPE_TEXT_OR_NUMERIC = 6;
public static final String QUIZ_STATUS_STARTED = "1";
public static final String QUIZ_STATUS_IN_PROGRESS = "2";
public static final String QUIZ_STATUS_SUBMITTED = "3";
}
| 590 | 0.744068 | 0.728814 | 14 | 40.142857 | 22.07085 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.357143 | false | false | 9 |
1fb2374f1af642a3c32debbdeca08d568a62a84c | 10,144,712,781,767 | 750dd3fab3bb45afec42590716522f7b1bb404ff | /src/Distances/EuclidianCentroidDistance.java | aba74b3be3b53984287c8d17ca45678dd517d1be | [] | no_license | Sunita-Ingle/IR_Project | https://github.com/Sunita-Ingle/IR_Project | c84b436a7223021e5f874d6f9ecd79e0ce7a083b | 73309bb9e3d5afb569f431a055b8907d64f3e6d1 | refs/heads/master | 2020-03-25T01:29:07.049000 | 2017-05-04T16:43:23 | 2017-05-04T16:43:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Distances;
import Categories.Centroid;
import Documents.IDocument;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author online
*/
public class EuclidianCentroidDistance implements ICentroidDistance{
@Override
public double GetSimilarity(IDocument d1, Centroid centroid) throws IOException {
if(d1.getWeightsVector().getLength() != centroid.vector.length) {
try {
throw new Exception("Los vectores de pesos de los documentos deben tener la misma longitud");
} catch (Exception ex) {
Logger.getLogger(EuclidianDistance.class.getName()).log(Level.SEVERE, null, ex);
}
}
double distance = 0;
double w1, w2;
String[] allTerms = d1.getWeightsVector().getAllTerms();
for (int i = 0; i < allTerms.length; i++) {
w1 = d1.getWeightsVector().getWeight(allTerms[i]);
w2 = centroid.vector[i];
distance += Math.pow(Math.abs(w1 - w2), 2);
}
distance = Math.sqrt(distance);
return distance;
}
}
| UTF-8 | Java | 1,330 | java | EuclidianCentroidDistance.java | Java | [
{
"context": "t java.util.logging.Logger;\r\n\r\n/**\r\n *\r\n * @author online\r\n */\r\npublic class EuclidianCentroidDistance implem",
"end": 308,
"score": 0.924336850643158,
"start": 302,
"tag": "USERNAME",
"value": "online"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Distances;
import Categories.Centroid;
import Documents.IDocument;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author online
*/
public class EuclidianCentroidDistance implements ICentroidDistance{
@Override
public double GetSimilarity(IDocument d1, Centroid centroid) throws IOException {
if(d1.getWeightsVector().getLength() != centroid.vector.length) {
try {
throw new Exception("Los vectores de pesos de los documentos deben tener la misma longitud");
} catch (Exception ex) {
Logger.getLogger(EuclidianDistance.class.getName()).log(Level.SEVERE, null, ex);
}
}
double distance = 0;
double w1, w2;
String[] allTerms = d1.getWeightsVector().getAllTerms();
for (int i = 0; i < allTerms.length; i++) {
w1 = d1.getWeightsVector().getWeight(allTerms[i]);
w2 = centroid.vector[i];
distance += Math.pow(Math.abs(w1 - w2), 2);
}
distance = Math.sqrt(distance);
return distance;
}
}
| 1,330 | 0.586466 | 0.576692 | 46 | 26.913044 | 27.46209 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.543478 | false | false | 9 |
5726208d0989185ff96006caf3334de27902213a | 32,753,420,619,809 | f9df7f07283c357c31c915f981e9469bd68559ae | /cdm/zarr/src/test/java/ucar/nc2/iosp/zarr/ZarrTestsCommon.java | 9d37f45a76d278d026a093cd646e382c8f14012d | [
"BSD-3-Clause"
] | permissive | Unidata/netcdf-java | https://github.com/Unidata/netcdf-java | 80faec3c59f24e455cd16ab5538bc70b2ddde681 | 45a7d9323ca9f9826a21a4da82f1988160327251 | refs/heads/maint-5.x | 2023-09-04T06:47:25.666000 | 2023-08-25T20:41:19 | 2023-08-25T20:41:19 | 184,285,250 | 113 | 111 | BSD-3-Clause | false | 2023-09-08T22:05:55 | 2019-04-30T15:15:55 | 2023-08-31T14:22:49 | 2023-09-08T22:05:54 | 1,061,802 | 114 | 60 | 73 | Java | false | false | package ucar.nc2.iosp.zarr;
public class ZarrTestsCommon {
// AWS props
public static final String AWS_BUCKET_NAME = "unidata-zarr-test-data";
public static final String S3_PREFIX = "cdms3:";
public static final String S3_FRAGMENT = "delimiter=/";
// Local stores
public static final String LOCAL_TEST_DATA_PATH = "src/test/data/";
}
| UTF-8 | Java | 348 | java | ZarrTestsCommon.java | Java | [] | null | [] | package ucar.nc2.iosp.zarr;
public class ZarrTestsCommon {
// AWS props
public static final String AWS_BUCKET_NAME = "unidata-zarr-test-data";
public static final String S3_PREFIX = "cdms3:";
public static final String S3_FRAGMENT = "delimiter=/";
// Local stores
public static final String LOCAL_TEST_DATA_PATH = "src/test/data/";
}
| 348 | 0.721264 | 0.70977 | 11 | 30.636364 | 26.084732 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 9 |
e77dda5c7648e398c608c879172ae31b63a633b0 | 1,090,921,726,098 | fc78c1f6df81894493cbe47d7ff3cdc9ab4d6ed2 | /tests/java/net/spanbroek/judith/parser/ExpressionParserTests.java | dc300c007f7d6d511b93c994320dada1a624b586 | [
"MIT"
] | permissive | markspanbroek/judith | https://github.com/markspanbroek/judith | 9da81bc576eb24d51645671495b3405e7b6423be | 76efc81e2287162cd88409505ec31b8cec38f5bc | refs/heads/master | 2021-01-21T05:20:15.274000 | 2014-06-04T20:23:22 | 2014-06-04T20:33:19 | 20,111,264 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.spanbroek.judith.parser;
import net.spanbroek.judith.tree.*;
import net.spanbroek.judith.tree.Boolean;
import net.spanbroek.judith.tree.Number;
import net.spanbroek.parsing.Parser;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ExpressionParserTests {
private Parser parser;
@Before
public void setUp() {
parser = new JudithParser().expression;
}
@Test
public void parsesBooleans() {
assertEquals(new Boolean(true), parser.parse("true"));
assertEquals(new Boolean(false), parser.parse("false"));
}
@Test
public void parsesNumbers() {
assertEquals(new Number(0), parser.parse("0"));
assertEquals(new Number(3), parser.parse("3"));
assertEquals(new Number(42), parser.parse("42"));
assertEquals(new Number(42.31), parser.parse("42.31"));
}
@Test
public void parsesText() {
assertEquals(new Text("foo"), parser.parse("\"foo\""));
assertEquals(new Text("bar'234"), parser.parse("\"bar'234\""));
}
@Test
public void parsesIdentifiers() {
assertEquals(new Reference("foo"), parser.parse("foo"));
assertEquals(new Reference("FOO"), parser.parse("FOO"));
assertEquals(new Reference("12foo"), parser.parse("12foo"));
assertEquals(new Reference("1foo23"), parser.parse("1foo23"));
assertEquals(new Reference("foo'"), parser.parse("foo'"));
assertEquals(new Reference("?foo"), parser.parse("?foo"));
}
@Test
public void parsesBinaryOperations() {
checkParsingOfBinaryOperator("and", "and");
checkParsingOfBinaryOperator("or", "or");
checkParsingOfBinaryOperator("plus", "+");
checkParsingOfBinaryOperator("minus", "-");
checkParsingOfBinaryOperator("equals", "=");
checkParsingOfBinaryOperator("atmost", "<=");
checkParsingOfBinaryOperator("atleast", ">=");
checkParsingOfBinaryOperator("lessthan", "<");
checkParsingOfBinaryOperator("morethan", ">");
checkParsingOfBinaryOperator("colon", ":");
checkParsingOfBinaryOperator("star", "*");
checkParsingOfBinaryOperator("slash", "/");
checkParsingOfBinaryOperator("carrot", "^");
}
@Test
public void parsesPrefixOperations() {
assertEquals(methodCall("a", "minus"), parser.parse("-a"));
assertEquals(methodCall("a", "not"), parser.parse("not a"));
}
@Test
public void parsesMethodCalls() {
assertEquals(
methodCall("callee", "method"),
parser.parse("callee.method"));
assertEquals(
methodCall("callee", "method", "parameter"),
parser.parse("callee.method(parameter)"));
assertEquals(
methodCall("callee", "method", "parameter1", "parameter2"),
parser.parse("callee.method(parameter1, parameter2)"));
}
@Test
public void parsesAlteration() {
ObjectDeclaration[] objects = {new ObjectDeclaration("x", new Number(1))};
Method[] methods = {new Method("y", new String[]{}, new Statement[]{})};
Alteration alteration = new Alteration(new Reference("a"), objects, methods);
assertEquals(alteration, parser.parse("a |[ object x := 1 method y [] ]|"));
}
@Test
public void parsesLambdas() {
Lambda lambda = new Lambda(new String[]{"a", "b"}, methodCall("a", "plus", "b"));
assertEquals(lambda, parser.parse("( a , b -> a+b )"));
}
@Test
public void parsesLambdaBlock() {
Statement[] statements = new Statement[]{new Assignment("a", new Reference("b"))};
LambdaBlock lambda = new LambdaBlock(new String[]{"a", "b"}, statements);
assertEquals(lambda, parser.parse("[ a , b -> a := b ]"));
}
@Test
public void parsesBlock() {
Statement[] statements = new Statement[]{new Assignment("a", new Number(1))};
LambdaBlock lambda = new LambdaBlock(statements);
assertEquals(lambda, parser.parse("[ a := 1 ]"));
}
@Test
public void parsesBraces() {
MethodCall subtraction = methodCall("a", "minus", methodCall("b", "minus", "c"));
assertEquals(subtraction, parser.parse("a-(b-c)"));
}
@Test
public void ignoresWhitespace() {
assertEquals(new Number(1), parser.parse("( 1 )"));
assertEquals(new Number(1), parser.parse("( 1 \n\n)"));
}
@Test
public void ignoresComments() {
assertEquals(new Number(1), parser.parse("( #comment\n 1 #comment\n )"));
}
private void checkParsingOfBinaryOperator(String expectedMethodName, String operator) {
assertEquals(methodCall("a", expectedMethodName, "b"), parser.parse("a " + operator + " b"));
}
private MethodCall methodCall(String callee, String methodName) {
return new MethodCall(new Reference(callee), methodName, new Expression[]{});
}
private MethodCall methodCall(String callee, String methodName, String... parameters) {
Expression[] expressions = new Expression[parameters.length];
for (int i = 0; i < parameters.length; i++) {
expressions[i] = new Reference(parameters[i]);
}
return new MethodCall(new Reference(callee), methodName, expressions);
}
private MethodCall methodCall(String callee, String methodName, Expression parameter) {
return new MethodCall(new Reference(callee), methodName, new Expression[]{parameter});
}
}
| UTF-8 | Java | 5,568 | java | ExpressionParserTests.java | Java | [] | null | [] | package net.spanbroek.judith.parser;
import net.spanbroek.judith.tree.*;
import net.spanbroek.judith.tree.Boolean;
import net.spanbroek.judith.tree.Number;
import net.spanbroek.parsing.Parser;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ExpressionParserTests {
private Parser parser;
@Before
public void setUp() {
parser = new JudithParser().expression;
}
@Test
public void parsesBooleans() {
assertEquals(new Boolean(true), parser.parse("true"));
assertEquals(new Boolean(false), parser.parse("false"));
}
@Test
public void parsesNumbers() {
assertEquals(new Number(0), parser.parse("0"));
assertEquals(new Number(3), parser.parse("3"));
assertEquals(new Number(42), parser.parse("42"));
assertEquals(new Number(42.31), parser.parse("42.31"));
}
@Test
public void parsesText() {
assertEquals(new Text("foo"), parser.parse("\"foo\""));
assertEquals(new Text("bar'234"), parser.parse("\"bar'234\""));
}
@Test
public void parsesIdentifiers() {
assertEquals(new Reference("foo"), parser.parse("foo"));
assertEquals(new Reference("FOO"), parser.parse("FOO"));
assertEquals(new Reference("12foo"), parser.parse("12foo"));
assertEquals(new Reference("1foo23"), parser.parse("1foo23"));
assertEquals(new Reference("foo'"), parser.parse("foo'"));
assertEquals(new Reference("?foo"), parser.parse("?foo"));
}
@Test
public void parsesBinaryOperations() {
checkParsingOfBinaryOperator("and", "and");
checkParsingOfBinaryOperator("or", "or");
checkParsingOfBinaryOperator("plus", "+");
checkParsingOfBinaryOperator("minus", "-");
checkParsingOfBinaryOperator("equals", "=");
checkParsingOfBinaryOperator("atmost", "<=");
checkParsingOfBinaryOperator("atleast", ">=");
checkParsingOfBinaryOperator("lessthan", "<");
checkParsingOfBinaryOperator("morethan", ">");
checkParsingOfBinaryOperator("colon", ":");
checkParsingOfBinaryOperator("star", "*");
checkParsingOfBinaryOperator("slash", "/");
checkParsingOfBinaryOperator("carrot", "^");
}
@Test
public void parsesPrefixOperations() {
assertEquals(methodCall("a", "minus"), parser.parse("-a"));
assertEquals(methodCall("a", "not"), parser.parse("not a"));
}
@Test
public void parsesMethodCalls() {
assertEquals(
methodCall("callee", "method"),
parser.parse("callee.method"));
assertEquals(
methodCall("callee", "method", "parameter"),
parser.parse("callee.method(parameter)"));
assertEquals(
methodCall("callee", "method", "parameter1", "parameter2"),
parser.parse("callee.method(parameter1, parameter2)"));
}
@Test
public void parsesAlteration() {
ObjectDeclaration[] objects = {new ObjectDeclaration("x", new Number(1))};
Method[] methods = {new Method("y", new String[]{}, new Statement[]{})};
Alteration alteration = new Alteration(new Reference("a"), objects, methods);
assertEquals(alteration, parser.parse("a |[ object x := 1 method y [] ]|"));
}
@Test
public void parsesLambdas() {
Lambda lambda = new Lambda(new String[]{"a", "b"}, methodCall("a", "plus", "b"));
assertEquals(lambda, parser.parse("( a , b -> a+b )"));
}
@Test
public void parsesLambdaBlock() {
Statement[] statements = new Statement[]{new Assignment("a", new Reference("b"))};
LambdaBlock lambda = new LambdaBlock(new String[]{"a", "b"}, statements);
assertEquals(lambda, parser.parse("[ a , b -> a := b ]"));
}
@Test
public void parsesBlock() {
Statement[] statements = new Statement[]{new Assignment("a", new Number(1))};
LambdaBlock lambda = new LambdaBlock(statements);
assertEquals(lambda, parser.parse("[ a := 1 ]"));
}
@Test
public void parsesBraces() {
MethodCall subtraction = methodCall("a", "minus", methodCall("b", "minus", "c"));
assertEquals(subtraction, parser.parse("a-(b-c)"));
}
@Test
public void ignoresWhitespace() {
assertEquals(new Number(1), parser.parse("( 1 )"));
assertEquals(new Number(1), parser.parse("( 1 \n\n)"));
}
@Test
public void ignoresComments() {
assertEquals(new Number(1), parser.parse("( #comment\n 1 #comment\n )"));
}
private void checkParsingOfBinaryOperator(String expectedMethodName, String operator) {
assertEquals(methodCall("a", expectedMethodName, "b"), parser.parse("a " + operator + " b"));
}
private MethodCall methodCall(String callee, String methodName) {
return new MethodCall(new Reference(callee), methodName, new Expression[]{});
}
private MethodCall methodCall(String callee, String methodName, String... parameters) {
Expression[] expressions = new Expression[parameters.length];
for (int i = 0; i < parameters.length; i++) {
expressions[i] = new Reference(parameters[i]);
}
return new MethodCall(new Reference(callee), methodName, expressions);
}
private MethodCall methodCall(String callee, String methodName, Expression parameter) {
return new MethodCall(new Reference(callee), methodName, new Expression[]{parameter});
}
}
| 5,568 | 0.622845 | 0.614404 | 151 | 35.874172 | 29.84248 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.006623 | false | false | 9 |
074123c1bff634e1c01a01145fd779ed219dfd61 | 25,056,839,204,888 | 238f51c3f8d35e2a54ce84adbf0a8c9a0f1ffb10 | /ScrabbleServer/src/Game.java | b1220500de8305733519d73636b61a37ef730ca8 | [] | no_license | hoooonoka/ds_pj2 | https://github.com/hoooonoka/ds_pj2 | 2f260ebd424fe36ffab3432fd25761372fa22d99 | 6b32b21f3e451082c8e0e75c5a6540a987c2aed0 | refs/heads/master | 2021-06-26T20:02:13.676000 | 2020-10-08T17:27:05 | 2020-10-08T17:27:05 | 150,282,278 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Game
{
private int gameID;
private List<GameState> states;
private List<String> users;
private List<Operation> operations;
public boolean end=false;
public Game(int id)
{
this.gameID=id;
this.states=new ArrayList<GameState>();
operations=new ArrayList<Operation>();
}
public Game(int id,String[] players)
{
this.gameID=id;
this.users=new ArrayList<String>();
for (int i = 0; i < players.length; i++)
{
this.users.add(players[i]);
}
this.states=new ArrayList<>();
GameState initialState=new GameState(players);
states.add(initialState);
operations=new ArrayList<Operation>();
}
public void initialiseNewGame()
{
String[] players=new String[this.users.size()];
for (int i = 0; i < players.length; i++)
{
players[i]=this.users.get(i);
}
GameState initialState=new GameState(players);
states.add(initialState);
}
public void setUsers(List<String> gamePlayers)
{
this.users=new ArrayList<String>(gamePlayers);
}
public List<String> getUsers()
{
return this.users;
}
public List<GameState> getGameStates()
{
return this.states;
}
public List<Operation> getOperations()
{
return this.operations;
}
public void nextState(Operation operation)
{
GameState state=this.states.get(this.states.size()-1);
GameState newState=new GameState(state);
if(operation.getPass())
{
newState.changeNextTurn();
operations.add(operation);
states.add(newState);
if(this.isFinish())
{
// end game
this.end=true;
}
}
else
{
newState.tryOperate(operation);
newState.changeNextTurn();
operations.add(operation);
states.add(newState);
if(this.isFinish())
{
// end game
this.end=true;
}
}
}
// public void endGame()
// {
// Control.stopGame(this.gameID,this.states.get(this.states.size()-1));
// }
public boolean isFinish()
{
if(operations.size()<users.size())
return false;
for(int i=0;i<users.size();i++)
{
if(!operations.get(operations.size()-i-1).getPass())
return false;
}
return true;
}
public void printGame()
{
FileWriter writer;
try
{
writer = new FileWriter("game"+this.gameID+".txt");
for(int i=0;i<operations.size();i++)
{
writer.write(GameState.printState(states.get(i)));
writer.write(Operation.printOperation(operations.get(i)));
}
writer.write(GameState.printState(states.get(states.size()-1)));
writer.close();
}
catch (IOException e)
{
System.out.println("error occurs when writing game file");
}
}
}
| UTF-8 | Java | 2,657 | java | Game.java | Java | [] | null | [] | import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Game
{
private int gameID;
private List<GameState> states;
private List<String> users;
private List<Operation> operations;
public boolean end=false;
public Game(int id)
{
this.gameID=id;
this.states=new ArrayList<GameState>();
operations=new ArrayList<Operation>();
}
public Game(int id,String[] players)
{
this.gameID=id;
this.users=new ArrayList<String>();
for (int i = 0; i < players.length; i++)
{
this.users.add(players[i]);
}
this.states=new ArrayList<>();
GameState initialState=new GameState(players);
states.add(initialState);
operations=new ArrayList<Operation>();
}
public void initialiseNewGame()
{
String[] players=new String[this.users.size()];
for (int i = 0; i < players.length; i++)
{
players[i]=this.users.get(i);
}
GameState initialState=new GameState(players);
states.add(initialState);
}
public void setUsers(List<String> gamePlayers)
{
this.users=new ArrayList<String>(gamePlayers);
}
public List<String> getUsers()
{
return this.users;
}
public List<GameState> getGameStates()
{
return this.states;
}
public List<Operation> getOperations()
{
return this.operations;
}
public void nextState(Operation operation)
{
GameState state=this.states.get(this.states.size()-1);
GameState newState=new GameState(state);
if(operation.getPass())
{
newState.changeNextTurn();
operations.add(operation);
states.add(newState);
if(this.isFinish())
{
// end game
this.end=true;
}
}
else
{
newState.tryOperate(operation);
newState.changeNextTurn();
operations.add(operation);
states.add(newState);
if(this.isFinish())
{
// end game
this.end=true;
}
}
}
// public void endGame()
// {
// Control.stopGame(this.gameID,this.states.get(this.states.size()-1));
// }
public boolean isFinish()
{
if(operations.size()<users.size())
return false;
for(int i=0;i<users.size();i++)
{
if(!operations.get(operations.size()-i-1).getPass())
return false;
}
return true;
}
public void printGame()
{
FileWriter writer;
try
{
writer = new FileWriter("game"+this.gameID+".txt");
for(int i=0;i<operations.size();i++)
{
writer.write(GameState.printState(states.get(i)));
writer.write(Operation.printOperation(operations.get(i)));
}
writer.write(GameState.printState(states.get(states.size()-1)));
writer.close();
}
catch (IOException e)
{
System.out.println("error occurs when writing game file");
}
}
}
| 2,657 | 0.668047 | 0.665036 | 132 | 19.128788 | 18.038849 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.25 | false | false | 9 |
efaec2f6b6371e47b21e8932a00617dc1eb5036e | 25,752,623,945,743 | e12e25d7eba0873716d19f8de312f48dcd48e11d | /app/src/main/java/com/android/materialpagerdemo/MainActivity.java | daf43381baa33036ea042f8c7d99a6bb1d42f3cd | [] | no_license | Abhishek92/MaterialPagerDemo | https://github.com/Abhishek92/MaterialPagerDemo | 1ef3adbcd66d95679fd54d616aeeb6f78ee78752 | 29a8d3d5f0c104824bfc2976fa36191b1bd04af2 | refs/heads/master | 2021-01-13T00:42:59.941000 | 2015-11-29T16:31:32 | 2015-11-29T16:31:32 | 47,071,048 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.android.materialpagerdemo;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewTreeObserver;
import com.github.florent37.materialviewpager.MaterialViewPager;
import com.github.florent37.materialviewpager.header.HeaderDesign;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private MaterialViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
/*BaseFragment fragment = (BaseFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
List<Fragment> fragments = fragment.getChildFragmentManager().getFragments();
for(int i = 0; i < fragments.size(); i++){
if(fragments.get(i) instanceof RecyclerViewFragment)
new RecyclerViewFragment().setData();
}*/
new RecyclerViewFragment().setData();
}
}
| UTF-8 | Java | 2,361 | java | MainActivity.java | Java | [
{
"context": "android.view.ViewTreeObserver;\n\nimport com.github.florent37.materialviewpager.MaterialViewPager;\nimport com.g",
"end": 570,
"score": 0.9981071949005127,
"start": 561,
"tag": "USERNAME",
"value": "florent37"
},
{
"context": "ialviewpager.MaterialViewPager;\nimport com.github.florent37.materialviewpager.header.HeaderDesign;\n\nimport ja",
"end": 635,
"score": 0.9989404678344727,
"start": 626,
"tag": "USERNAME",
"value": "florent37"
}
] | null | [] | package com.android.materialpagerdemo;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewTreeObserver;
import com.github.florent37.materialviewpager.MaterialViewPager;
import com.github.florent37.materialviewpager.header.HeaderDesign;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private MaterialViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
/*BaseFragment fragment = (BaseFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
List<Fragment> fragments = fragment.getChildFragmentManager().getFragments();
for(int i = 0; i < fragments.size(); i++){
if(fragments.get(i) instanceof RecyclerViewFragment)
new RecyclerViewFragment().setData();
}*/
new RecyclerViewFragment().setData();
}
}
| 2,361 | 0.720457 | 0.716645 | 67 | 34.238808 | 26.790001 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.597015 | false | false | 9 |
a26af4a90b43cf9d3af937295bd4fb6a5c71cf6f | 23,398,981,855,592 | 1acb0bc8047969edd9cd3ca638c2de274b31a8d5 | /src/main/java/com/pachiraframework/watchdog/entity/PingRecord.java | ec337e67014ac86ee011b119cce93257cfc5e5da | [] | no_license | kwang2003/watchdog | https://github.com/kwang2003/watchdog | e0eebe50a1c575801e7ea64fe2d62480ef35b61c | bf3f452bf6c32c74ce7ae50824319467999fd233 | refs/heads/master | 2021-05-03T09:16:57.440000 | 2018-03-12T10:31:16 | 2018-03-12T10:31:16 | 120,572,998 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pachiraframework.watchdog.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author wangxuzheng@aliyun.com
*
*/
@Getter
@Setter
@ToString(callSuper=true)
public class PingRecord extends AbstractRecord {
/**
* 已发送
*/
private Integer sent;
/**
* 已接收
*/
private Integer success;
/**
* 丢失
*/
private Integer lost;
/**
* 最短
*/
private Double min;
/**
* 最长
*/
private Double max;
/**
* 平均
*/
private Double avg;
}
| UTF-8 | Java | 560 | java | PingRecord.java | Java | [
{
"context": "etter;\r\nimport lombok.ToString;\r\n\r\n/**\r\n * @author wangxuzheng@aliyun.com\r\n *\r\n */\r\n@Getter\r\n@Setter\r\n@ToString(callSuper=t",
"end": 160,
"score": 0.999923050403595,
"start": 138,
"tag": "EMAIL",
"value": "wangxuzheng@aliyun.com"
}
] | null | [] | package com.pachiraframework.watchdog.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author <EMAIL>
*
*/
@Getter
@Setter
@ToString(callSuper=true)
public class PingRecord extends AbstractRecord {
/**
* 已发送
*/
private Integer sent;
/**
* 已接收
*/
private Integer success;
/**
* 丢失
*/
private Integer lost;
/**
* 最短
*/
private Double min;
/**
* 最长
*/
private Double max;
/**
* 平均
*/
private Double avg;
}
| 545 | 0.593985 | 0.593985 | 39 | 11.641026 | 11.893733 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.871795 | false | false | 9 |
96331d38fb5ae67fe614ffd979261f74b1a32969 | 996,432,466,667 | 1671a77a70031202ca817a0d9dc06c6fce6b19f3 | /jeesuite-common/src/main/java/com/jeesuite/common/async/RetryTask.java | 26711e7646490a4a90b1eb93ed524803ec8cd5bf | [
"Apache-2.0"
] | permissive | xji1024/jeesuite-libs | https://github.com/xji1024/jeesuite-libs | ce8215ec968eda7a58cf65464a5b54fbb149f0c1 | 7ca22af8d9b4085b7fae2d36004c604d0f5e6cdf | refs/heads/master | 2023-08-28T10:19:34.753000 | 2021-11-06T12:14:30 | 2021-11-06T12:14:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jeesuite.common.async;
import java.util.HashMap;
import java.util.Map;
/**
*
* <br>
* Class Name : RetryTask
*
* @author jiangwei
* @version 1.0.0
* @date 2020年2月18日
*/
public abstract class RetryTask{
private static final String STEP_POINT_KEY = "_stepPoint";
public final long createTime = System.currentTimeMillis();
private final Map<String, Object> contextParams = new HashMap<>(5);
final ExecuteCallback callback;
public RetryTask() {
this.callback = null;
}
public RetryTask(ExecuteCallback callback) {
this.callback = callback;
}
public abstract String traceId();
public abstract boolean process() throws Exception;
public void saveStepPoint(int point){
contextParams.put(STEP_POINT_KEY, point);
}
public int getStepPoint(){
return Integer.parseInt(contextParams.getOrDefault(STEP_POINT_KEY, 0).toString());
}
}
| UTF-8 | Java | 885 | java | RetryTask.java | Java | [
{
"context": "\n * <br>\n * Class Name : RetryTask\n *\n * @author jiangwei\n * @version 1.0.0\n * @date 2020年2月18日\n */\npublic ",
"end": 151,
"score": 0.9995638728141785,
"start": 143,
"tag": "USERNAME",
"value": "jiangwei"
},
{
"context": "k{\n\t\n\tprivate static final String STEP_POINT_KEY = \"_stepPoint\";\n\t\n\tpublic final long createTime = System.curren",
"end": 286,
"score": 0.7495978474617004,
"start": 275,
"tag": "KEY",
"value": "\"_stepPoint"
}
] | null | [] | package com.jeesuite.common.async;
import java.util.HashMap;
import java.util.Map;
/**
*
* <br>
* Class Name : RetryTask
*
* @author jiangwei
* @version 1.0.0
* @date 2020年2月18日
*/
public abstract class RetryTask{
private static final String STEP_POINT_KEY = "_stepPoint";
public final long createTime = System.currentTimeMillis();
private final Map<String, Object> contextParams = new HashMap<>(5);
final ExecuteCallback callback;
public RetryTask() {
this.callback = null;
}
public RetryTask(ExecuteCallback callback) {
this.callback = callback;
}
public abstract String traceId();
public abstract boolean process() throws Exception;
public void saveStepPoint(int point){
contextParams.put(STEP_POINT_KEY, point);
}
public int getStepPoint(){
return Integer.parseInt(contextParams.getOrDefault(STEP_POINT_KEY, 0).toString());
}
}
| 885 | 0.723549 | 0.709898 | 41 | 20.439024 | 21.658152 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.04878 | false | false | 9 |
09a280e8429a63abc78da7be149c97aac148e90a | 14,577,119,059,482 | bf3aea0b4623621f55a330a07562578d2777faaf | /xman/src/main/java/xs/mgr/dao/impl/MenuDaoImpl.java | 8d25762920b3bcd6a375f665cc4c5bbe9b0af3e8 | [] | no_license | amitabhasia/zyz.io | https://github.com/amitabhasia/zyz.io | 3ad32b5504ae04238b995c9343aa6cb53991484e | 1821fd1ba7d399d8a470c3e014d02fad3861da46 | refs/heads/master | 2021-09-02T15:42:52.752000 | 2018-01-03T12:46:48 | 2018-01-03T12:46:48 | 116,131,591 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package xs.mgr.dao.impl;
import org.springframework.stereotype.Repository;
import xs.mgr.dao.MenuDaoI;
import xs.mgr.model.SysMenu;
@Repository("menuDao")
public class MenuDaoImpl extends BaseDaoImpl<SysMenu> implements MenuDaoI {
}
| UTF-8 | Java | 237 | java | MenuDaoImpl.java | Java | [] | null | [] | package xs.mgr.dao.impl;
import org.springframework.stereotype.Repository;
import xs.mgr.dao.MenuDaoI;
import xs.mgr.model.SysMenu;
@Repository("menuDao")
public class MenuDaoImpl extends BaseDaoImpl<SysMenu> implements MenuDaoI {
}
| 237 | 0.801688 | 0.801688 | 11 | 20.545454 | 23.270596 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 9 |
74eae0c99cceee37d391b5efa9d36c178e2e4503 | 6,244,882,482,920 | fa68205e5453a89eddd019a9a8375944ea405d7e | /src/main/java/com/example/demo/dao/UserRepository.java | aa72d07a1de60d3efbca2fc32b1e84d08da55999 | [] | no_license | payalb/MvcActuatorSecurity | https://github.com/payalb/MvcActuatorSecurity | ad21129f96ed4018f9b3e3443036e25235cc62d0 | 68a2598e58bda1d3ed288884545283b911c65ca7 | refs/heads/master | 2021-10-09T04:26:56.820000 | 2018-12-21T06:43:10 | 2018-12-21T06:43:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.dao;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.dto.UserDetail;
public interface UserRepository extends CrudRepository<UserDetail, String>{
}
| UTF-8 | Java | 211 | java | UserRepository.java | Java | [] | null | [] | package com.example.demo.dao;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.dto.UserDetail;
public interface UserRepository extends CrudRepository<UserDetail, String>{
}
| 211 | 0.829384 | 0.829384 | 9 | 22.444445 | 27.524176 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 9 |
e3ced400cd1476b2cb6565c87e99564b2f7d6af6 | 32,521,492,437,612 | c91815da8e87f3d00ecaa919eee77b2a36385949 | /service-user-provide/src/main/java/net/sunwukong/www/user/server/dao/usercenter/write/MobileVersionMapperWrite.java | 4c7e62d0f1c54dcb83724aec4007fe5b599c723c | [] | no_license | yht-817/SpringCloud_Manage | https://github.com/yht-817/SpringCloud_Manage | 3492e3a6b496d01d9a6fb1a88631bda26f87c258 | 6b8d6eb49caeb33a47973ee1b280054294254621 | refs/heads/master | 2020-05-03T19:01:23.532000 | 2019-04-01T03:10:23 | 2019-04-01T03:10:23 | 178,776,579 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.sunwukong.www.user.server.dao.usercenter.write;
import net.sunwukong.www.api.base.BaseMapper;
import net.sunwukong.www.user.server.model.MobileVersion;
public interface MobileVersionMapperWrite extends BaseMapper<MobileVersion> {
} | UTF-8 | Java | 253 | java | MobileVersionMapperWrite.java | Java | [] | null | [] | package net.sunwukong.www.user.server.dao.usercenter.write;
import net.sunwukong.www.api.base.BaseMapper;
import net.sunwukong.www.user.server.model.MobileVersion;
public interface MobileVersionMapperWrite extends BaseMapper<MobileVersion> {
} | 253 | 0.814229 | 0.814229 | 8 | 29.875 | 30.710087 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 9 |
f41e2d7769424ca7a3cbc704a5f4886872f2f9cc | 5,068,061,458,734 | 05e6266d3fe8da055862e14f35c746746bfa4059 | /digispike-home-1/src/main/java/com/digispike/demo/repository/RoleRepository.java | 930c7a92fb9578e2c61803ef5778ba9a6e09b16e | [] | no_license | helloworldtang/basic-dashboard-home | https://github.com/helloworldtang/basic-dashboard-home | faef0761072497fa8b0ef73dc25a8012f52d8faf | 11945fd254849ecb6eade9cdda9c6753d7129321 | refs/heads/master | 2021-01-22T01:48:12.482000 | 2017-09-03T09:06:19 | 2017-09-03T09:06:19 | 102,238,822 | 0 | 0 | null | true | 2017-09-03T03:30:41 | 2017-09-03T03:30:41 | 2017-08-24T06:46:04 | 2017-08-24T06:46:03 | 38 | 0 | 0 | 0 | null | null | null | package com.digispike.demo.repository;
import com.digispike.demo.model.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Set;
/**
* Created by Devon Ravihansa on 8/23/2017.
*/
public interface RoleRepository extends JpaRepository<Role, Long> {
void deleteByIdIn(List<Long> longs);
}
| UTF-8 | Java | 366 | java | RoleRepository.java | Java | [
{
"context": "List;\r\nimport java.util.Set;\r\n\r\n/**\r\n * Created by Devon Ravihansa on 8/23/2017.\r\n */\r\npublic interface RoleReposito",
"end": 229,
"score": 0.9998939633369446,
"start": 214,
"tag": "NAME",
"value": "Devon Ravihansa"
}
] | null | [] | package com.digispike.demo.repository;
import com.digispike.demo.model.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Set;
/**
* Created by <NAME> on 8/23/2017.
*/
public interface RoleRepository extends JpaRepository<Role, Long> {
void deleteByIdIn(List<Long> longs);
}
| 357 | 0.740437 | 0.721311 | 15 | 22.4 | 22.934109 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 9 |
8284b8149ae69804daf17119ad713059a061c88e | 8,564,164,841,734 | 75f0d81197655407fd59ec1dca79243d2aa70be9 | /nd4j-api/src/main/java/org/nd4j/linalg/api/ops/factory/DefaultOpFactory.java | 16a0f3ed027d466426bede75a41c44d8e1b55b9b | [
"Apache-2.0"
] | permissive | noelnamai/nd4j | https://github.com/noelnamai/nd4j | 1a547e9ee5ad08f26d8a84f10af85c6c4278558f | f31d63d95e926c5d8cc93c5d0613f3b3c92e521c | refs/heads/master | 2021-01-22T09:04:35.467000 | 2015-06-05T02:49:29 | 2015-06-05T02:49:29 | 36,916,394 | 2 | 0 | null | true | 2015-06-05T06:37:09 | 2015-06-05T06:37:09 | 2015-06-04T12:44:29 | 2015-06-05T04:13:22 | 111,618 | 0 | 0 | 0 | null | null | null | /*
*
* * Copyright 2015 Skymind,Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*
*/
package org.nd4j.linalg.api.ops.factory;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.Accumulation;
import org.nd4j.linalg.api.ops.LossFunction;
import org.nd4j.linalg.api.ops.Op;
import org.nd4j.linalg.api.ops.TransformOp;
import org.nd4j.linalg.api.ops.impl.accum.*;
import org.nd4j.linalg.api.ops.impl.accum.distances.CosineSimilarity;
import org.nd4j.linalg.api.ops.impl.accum.distances.EuclideanDistance;
import org.nd4j.linalg.api.ops.impl.accum.distances.ManhattanDistance;
import org.nd4j.linalg.api.ops.impl.transforms.*;
import org.nd4j.linalg.factory.Nd4j;
import org.reflections.Reflections;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Default operations factory
*
* @author Adam Gibson
*/
public class DefaultOpFactory implements OpFactory {
private Map<String,Class<? extends Op>> opClazzes;
public DefaultOpFactory() {
opClazzes = new HashMap<>();
Set<Class<? extends Op>> clazzes = new Reflections("org.nd4j").getSubTypesOf(Op.class);
for(Class<? extends Op> clazz : clazzes) {
if(Modifier.isAbstract(clazz.getModifiers()) || clazz.isInterface())
continue;
try {
opClazzes.put(clazz.newInstance().name(),clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Override
public LossFunction createLossFunction(String name, INDArray x, INDArray y) {
Class<? extends Op> clazz = opClazzes.get(name);
try {
Constructor<Op> constructor = (Constructor<Op>) clazz.getDeclaredConstructor(INDArray.class,INDArray.class);
Op create = constructor.newInstance(x,y);
return (LossFunction) create;
} catch (Exception e) {
throw new IllegalArgumentException("Illegal op " + name);
}
}
@Override
public Accumulation createAccum(String name, INDArray x) {
switch (name) {
case "sum":
return new Sum(x);
case "max":
return new Max(x);
case "min":
return new Min(x);
case "norm1":
return new Norm1(x);
case "norm2":
return new Norm2(x);
case "prod":
return new Prod(x);
case "std":
return new StandardDeviation(x);
case "var":
return new Variance(x);
case "euclidean":
return new EuclideanDistance(x);
case "cosine":
return new CosineSimilarity(x);
case "manhattan":
return new ManhattanDistance(x);
default:
throw new IllegalArgumentException("Illegal name " + name);
}
}
@Override
public Accumulation createAccum(String name, INDArray x, INDArray y, INDArray z) {
switch (name) {
case "sum":
return new Sum(x, y, x.length());
case "max":
return new Max(x, y, x.length());
case "min":
return new Min(x, y, x.length());
case "norm1":
return new Norm1(x, y, x.length());
case "norm2":
return new Norm2(x, y, x.length());
case "prod":
return new Prod(x, y, x.length());
case "std":
return new StandardDeviation(x, y, x.length());
case "var":
return new Variance(x, y, x.length());
case "euclidean":
return new EuclideanDistance(x, y, x.length());
case "cosine":
return new CosineSimilarity(x, y, x.length());
case "manhattan":
return new ManhattanDistance(x, y, x.length());
default:
throw new IllegalArgumentException("Illegal name " + name);
}
}
@Override
public Accumulation createAccum(String name, INDArray x, INDArray y) {
switch (name) {
case "sum":
return new Sum(x, y);
case "max":
return new Max(x, y);
case "min":
return new Min(x, y);
case "norm1":
return new Norm1(x, y);
case "norm2":
return new Norm2(x, y);
case "prod":
return new Prod(x, y);
case "std":
return new StandardDeviation(x, y);
case "var":
return new Variance(x, y);
case "euclidean":
return new EuclideanDistance(x, y, x.length());
case "cosine":
return new CosineSimilarity(x, y, x.length());
case "manhattan":
return new ManhattanDistance(x, y, x.length());
default:
throw new IllegalArgumentException("Illegal name " + name);
}
}
@Override
public TransformOp createTransform(String name, INDArray x, INDArray y) {
switch (name) {
case "relu":
return new RectifedLinear(x,0);
case "abs":
return new Abs(x, y);
case "acos":
return new ACos(x, y);
case "asin":
return new ASin(x, y);
case "atan":
return new ATan(x, y);
case "ceil":
return new Ceil(x, y);
case "cos":
return new Cos(x, y);
case "exp":
return new Exp(x, y);
case "floor":
return new Floor(x, y);
case "hardtanh":
return new HardTanh(x, y);
case "identity":
return new Identity(x, y);
case "log":
return new Log(x, y);
case "maxout":
return new MaxOut(x, y);
case "negative":
return new Negative(x, y);
case "pow":
return new Pow(x, y, 2);
case "round":
return new Round(x, y);
case "sigmoid":
return new Sigmoid(x, y);
case "sign":
return new Sign(x, y);
case "sin":
return new Sin(x, y);
case "sqrt":
return new Sqrt(x, y);
case "stabilize":
return new Stabilize(x, y, 1);
case "tanh":
return new Tanh(x, y);
case "softmax":
return new SoftMax(x, y);
default:
throw new IllegalArgumentException("Illegal name " + name);
}
}
@Override
public TransformOp createTransform(String name, INDArray x) {
switch (name) {
case "relu":
return new RectifedLinear(x,0);
case "abs":
return new Abs(x);
case "acos":
return new ACos(x);
case "asin":
return new ASin(x);
case "atan":
return new ATan(x);
case "ceil":
return new Ceil(x);
case "cos":
return new Cos(x);
case "exp":
return new Exp(x);
case "floor":
return new Floor(x);
case "hardtanh":
return new HardTanh(x);
case "identity":
return new Identity(x);
case "log":
return new Log(x);
case "maxout":
return new MaxOut(x);
case "negative":
return new Negative(x);
case "pow":
return new Pow(x, 2);
case "round":
return new Round(x);
case "sigmoid":
return new Sigmoid(x);
case "sign":
return new Sign(x);
case "sin":
return new Sin(x);
case "sqrt":
return new Sqrt(x);
case "stabilize":
return new Stabilize(x, 1);
case "tanh":
return new Tanh(x);
case "softmax":
return new SoftMax(x);
default:
throw new IllegalArgumentException("Illegal name " + name);
}
}
@Override
public TransformOp createTransform(String name, INDArray x, INDArray y, INDArray z) {
switch (name) {
case "relu":
return new RectifedLinear(x,z,0);
case "abs":
return new Abs(x, z);
case "acos":
return new ACos(x, z);
case "asin":
return new ASin(x, z);
case "atan":
return new ATan(x, z);
case "ceil":
return new Ceil(x, z);
case "cos":
return new Cos(x, z);
case "exp":
return new Exp(x, z);
case "floor":
return new Floor(x, z);
case "hardtanh":
return new HardTanh(x, z);
case "identity":
return new Identity(x, z);
case "log":
return new Log(x, z);
case "maxout":
return new MaxOut(x, z);
case "negative":
return new Negative(x, z);
case "pow":
return new Pow(x, z, 2);
case "round":
return new Round(x, z);
case "sigmoid":
return new Sigmoid(x, z);
case "sign":
return new Sign(x, z);
case "sin":
return new Sin(x, z);
case "sqrt":
return new Sqrt(x, z);
case "stabilize":
return new Stabilize(x, z, 1);
case "tanh":
return new Tanh(x, z);
case "softmax":
return new SoftMax(x, z);
default:
throw new IllegalArgumentException("Illegal name " + name);
}
}
protected Class<? extends Op> lookupFunctionByName(String name) {
return opClazzes.get(name);
}
}
| UTF-8 | Java | 11,108 | java | DefaultOpFactory.java | Java | [
{
"context": "\n\n\n/**\n * Default operations factory\n *\n * @author Adam Gibson\n */\npublic class DefaultOpFactory implements OpFa",
"end": 1513,
"score": 0.9997005462646484,
"start": 1502,
"tag": "NAME",
"value": "Adam Gibson"
}
] | null | [] | /*
*
* * Copyright 2015 Skymind,Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*
*/
package org.nd4j.linalg.api.ops.factory;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.Accumulation;
import org.nd4j.linalg.api.ops.LossFunction;
import org.nd4j.linalg.api.ops.Op;
import org.nd4j.linalg.api.ops.TransformOp;
import org.nd4j.linalg.api.ops.impl.accum.*;
import org.nd4j.linalg.api.ops.impl.accum.distances.CosineSimilarity;
import org.nd4j.linalg.api.ops.impl.accum.distances.EuclideanDistance;
import org.nd4j.linalg.api.ops.impl.accum.distances.ManhattanDistance;
import org.nd4j.linalg.api.ops.impl.transforms.*;
import org.nd4j.linalg.factory.Nd4j;
import org.reflections.Reflections;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Default operations factory
*
* @author <NAME>
*/
public class DefaultOpFactory implements OpFactory {
private Map<String,Class<? extends Op>> opClazzes;
public DefaultOpFactory() {
opClazzes = new HashMap<>();
Set<Class<? extends Op>> clazzes = new Reflections("org.nd4j").getSubTypesOf(Op.class);
for(Class<? extends Op> clazz : clazzes) {
if(Modifier.isAbstract(clazz.getModifiers()) || clazz.isInterface())
continue;
try {
opClazzes.put(clazz.newInstance().name(),clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Override
public LossFunction createLossFunction(String name, INDArray x, INDArray y) {
Class<? extends Op> clazz = opClazzes.get(name);
try {
Constructor<Op> constructor = (Constructor<Op>) clazz.getDeclaredConstructor(INDArray.class,INDArray.class);
Op create = constructor.newInstance(x,y);
return (LossFunction) create;
} catch (Exception e) {
throw new IllegalArgumentException("Illegal op " + name);
}
}
@Override
public Accumulation createAccum(String name, INDArray x) {
switch (name) {
case "sum":
return new Sum(x);
case "max":
return new Max(x);
case "min":
return new Min(x);
case "norm1":
return new Norm1(x);
case "norm2":
return new Norm2(x);
case "prod":
return new Prod(x);
case "std":
return new StandardDeviation(x);
case "var":
return new Variance(x);
case "euclidean":
return new EuclideanDistance(x);
case "cosine":
return new CosineSimilarity(x);
case "manhattan":
return new ManhattanDistance(x);
default:
throw new IllegalArgumentException("Illegal name " + name);
}
}
@Override
public Accumulation createAccum(String name, INDArray x, INDArray y, INDArray z) {
switch (name) {
case "sum":
return new Sum(x, y, x.length());
case "max":
return new Max(x, y, x.length());
case "min":
return new Min(x, y, x.length());
case "norm1":
return new Norm1(x, y, x.length());
case "norm2":
return new Norm2(x, y, x.length());
case "prod":
return new Prod(x, y, x.length());
case "std":
return new StandardDeviation(x, y, x.length());
case "var":
return new Variance(x, y, x.length());
case "euclidean":
return new EuclideanDistance(x, y, x.length());
case "cosine":
return new CosineSimilarity(x, y, x.length());
case "manhattan":
return new ManhattanDistance(x, y, x.length());
default:
throw new IllegalArgumentException("Illegal name " + name);
}
}
@Override
public Accumulation createAccum(String name, INDArray x, INDArray y) {
switch (name) {
case "sum":
return new Sum(x, y);
case "max":
return new Max(x, y);
case "min":
return new Min(x, y);
case "norm1":
return new Norm1(x, y);
case "norm2":
return new Norm2(x, y);
case "prod":
return new Prod(x, y);
case "std":
return new StandardDeviation(x, y);
case "var":
return new Variance(x, y);
case "euclidean":
return new EuclideanDistance(x, y, x.length());
case "cosine":
return new CosineSimilarity(x, y, x.length());
case "manhattan":
return new ManhattanDistance(x, y, x.length());
default:
throw new IllegalArgumentException("Illegal name " + name);
}
}
@Override
public TransformOp createTransform(String name, INDArray x, INDArray y) {
switch (name) {
case "relu":
return new RectifedLinear(x,0);
case "abs":
return new Abs(x, y);
case "acos":
return new ACos(x, y);
case "asin":
return new ASin(x, y);
case "atan":
return new ATan(x, y);
case "ceil":
return new Ceil(x, y);
case "cos":
return new Cos(x, y);
case "exp":
return new Exp(x, y);
case "floor":
return new Floor(x, y);
case "hardtanh":
return new HardTanh(x, y);
case "identity":
return new Identity(x, y);
case "log":
return new Log(x, y);
case "maxout":
return new MaxOut(x, y);
case "negative":
return new Negative(x, y);
case "pow":
return new Pow(x, y, 2);
case "round":
return new Round(x, y);
case "sigmoid":
return new Sigmoid(x, y);
case "sign":
return new Sign(x, y);
case "sin":
return new Sin(x, y);
case "sqrt":
return new Sqrt(x, y);
case "stabilize":
return new Stabilize(x, y, 1);
case "tanh":
return new Tanh(x, y);
case "softmax":
return new SoftMax(x, y);
default:
throw new IllegalArgumentException("Illegal name " + name);
}
}
@Override
public TransformOp createTransform(String name, INDArray x) {
switch (name) {
case "relu":
return new RectifedLinear(x,0);
case "abs":
return new Abs(x);
case "acos":
return new ACos(x);
case "asin":
return new ASin(x);
case "atan":
return new ATan(x);
case "ceil":
return new Ceil(x);
case "cos":
return new Cos(x);
case "exp":
return new Exp(x);
case "floor":
return new Floor(x);
case "hardtanh":
return new HardTanh(x);
case "identity":
return new Identity(x);
case "log":
return new Log(x);
case "maxout":
return new MaxOut(x);
case "negative":
return new Negative(x);
case "pow":
return new Pow(x, 2);
case "round":
return new Round(x);
case "sigmoid":
return new Sigmoid(x);
case "sign":
return new Sign(x);
case "sin":
return new Sin(x);
case "sqrt":
return new Sqrt(x);
case "stabilize":
return new Stabilize(x, 1);
case "tanh":
return new Tanh(x);
case "softmax":
return new SoftMax(x);
default:
throw new IllegalArgumentException("Illegal name " + name);
}
}
@Override
public TransformOp createTransform(String name, INDArray x, INDArray y, INDArray z) {
switch (name) {
case "relu":
return new RectifedLinear(x,z,0);
case "abs":
return new Abs(x, z);
case "acos":
return new ACos(x, z);
case "asin":
return new ASin(x, z);
case "atan":
return new ATan(x, z);
case "ceil":
return new Ceil(x, z);
case "cos":
return new Cos(x, z);
case "exp":
return new Exp(x, z);
case "floor":
return new Floor(x, z);
case "hardtanh":
return new HardTanh(x, z);
case "identity":
return new Identity(x, z);
case "log":
return new Log(x, z);
case "maxout":
return new MaxOut(x, z);
case "negative":
return new Negative(x, z);
case "pow":
return new Pow(x, z, 2);
case "round":
return new Round(x, z);
case "sigmoid":
return new Sigmoid(x, z);
case "sign":
return new Sign(x, z);
case "sin":
return new Sin(x, z);
case "sqrt":
return new Sqrt(x, z);
case "stabilize":
return new Stabilize(x, z, 1);
case "tanh":
return new Tanh(x, z);
case "softmax":
return new SoftMax(x, z);
default:
throw new IllegalArgumentException("Illegal name " + name);
}
}
protected Class<? extends Op> lookupFunctionByName(String name) {
return opClazzes.get(name);
}
}
| 11,103 | 0.487306 | 0.483435 | 345 | 31.197102 | 20.00526 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.736232 | false | false | 9 |
a08a008de7c5239ee7a5af38610d85c952234c9a | 10,067,403,358,393 | 9e63967b2a7697f2d1f6aaf0f358fb516152bdc3 | /src/ad05/aufgabe05/test/FloydWarshallTest.java | bec83163b777993ae35344ef9a9f901ab4f850e2 | [] | no_license | swaltz82/ad | https://github.com/swaltz82/ad | 2043210cd9fc48112910c9a909a8bf4ed5599d11 | bb4bcd5617d6dfab630ed5094afec07467cd223a | refs/heads/master | 2015-08-09T04:09:47 | 2014-01-09T08:18:18 | 2014-01-09T08:18:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ad05.aufgabe05.test;
import static org.junit.Assert.*;
import org.junit.Test;
import ad05.aufgabe05.FloydWarshall;
public class FloydWarshallTest {
FloydWarshall fWTest = new FloydWarshall();
double INF = Double.POSITIVE_INFINITY;
double[][] matrix = { { 0, 12, 10, INF, INF },
{ INF, 0, 7, INF, 17 },
{ INF, 7, 0, INF, 5 },
{ INF, 10, 8, 0, INF },
{ 11, INF, INF, 3, 0 }};
double[][] dummy = { { 0, 12, 10, INF, INF },
{ INF, 0, 7, INF, 17 },
{ INF, 7, 0, INF, 5 },
{ INF, 10, 8, 0, INF },
{ 11, INF, INF, 3, 0 }};
int y, x, N = matrix.length;
/**
* Test des FloydWarshall-Algorithmus mit einer selbst erstellten Matrix
*/
@Test
public void test() {
matrix = FloydWarshall.floydWarshall(matrix);
FloydWarshall.printAdjMatrix(dummy);
/**
* Soll-Ergebnismatrix der Kosten
*/
double[][] sollKosten = {
{0.0, 12.0, 10.0, 18.0, 15.0 },
{23.0, 0.0, 7.0, 15.0, 12.0 },
{16.0, 7.0, 0.0, 8.0, 5.0 },
{24.0, 10.0, 8.0, 0.0, 13.0 },
{11.0, 13.0, 11.0, 3.0, 0.0 }
};
/**
* Test auf korrekte Kostenwerte
*/
assertArrayEquals(matrix, sollKosten);
System.out.println();
FloydWarshall.printFWMatrix(matrix);
/**
* Errechnete Pfadmatrix des Algorithmus
*/
int[][] pfad = FloydWarshall.getPathMatrix();
/**
* Soll-Pfadmatrix
*/
int[][] sollPfad = {
{ 0, 0, 0, 4, 2 },
{ 4, 1, 1, 4, 2 },
{ 4, 2, 2, 4, 2 },
{ 4, 3, 3, 3, 2 },
{ 4, 3, 3, 4, 4 }
};
/**
* Test auf korrekte Vorgänger
*/
assertArrayEquals(pfad, sollPfad);
FloydWarshall.printPath();
}
}
| ISO-8859-1 | Java | 1,660 | java | FloydWarshallTest.java | Java | [] | null | [] | package ad05.aufgabe05.test;
import static org.junit.Assert.*;
import org.junit.Test;
import ad05.aufgabe05.FloydWarshall;
public class FloydWarshallTest {
FloydWarshall fWTest = new FloydWarshall();
double INF = Double.POSITIVE_INFINITY;
double[][] matrix = { { 0, 12, 10, INF, INF },
{ INF, 0, 7, INF, 17 },
{ INF, 7, 0, INF, 5 },
{ INF, 10, 8, 0, INF },
{ 11, INF, INF, 3, 0 }};
double[][] dummy = { { 0, 12, 10, INF, INF },
{ INF, 0, 7, INF, 17 },
{ INF, 7, 0, INF, 5 },
{ INF, 10, 8, 0, INF },
{ 11, INF, INF, 3, 0 }};
int y, x, N = matrix.length;
/**
* Test des FloydWarshall-Algorithmus mit einer selbst erstellten Matrix
*/
@Test
public void test() {
matrix = FloydWarshall.floydWarshall(matrix);
FloydWarshall.printAdjMatrix(dummy);
/**
* Soll-Ergebnismatrix der Kosten
*/
double[][] sollKosten = {
{0.0, 12.0, 10.0, 18.0, 15.0 },
{23.0, 0.0, 7.0, 15.0, 12.0 },
{16.0, 7.0, 0.0, 8.0, 5.0 },
{24.0, 10.0, 8.0, 0.0, 13.0 },
{11.0, 13.0, 11.0, 3.0, 0.0 }
};
/**
* Test auf korrekte Kostenwerte
*/
assertArrayEquals(matrix, sollKosten);
System.out.println();
FloydWarshall.printFWMatrix(matrix);
/**
* Errechnete Pfadmatrix des Algorithmus
*/
int[][] pfad = FloydWarshall.getPathMatrix();
/**
* Soll-Pfadmatrix
*/
int[][] sollPfad = {
{ 0, 0, 0, 4, 2 },
{ 4, 1, 1, 4, 2 },
{ 4, 2, 2, 4, 2 },
{ 4, 3, 3, 3, 2 },
{ 4, 3, 3, 4, 4 }
};
/**
* Test auf korrekte Vorgänger
*/
assertArrayEquals(pfad, sollPfad);
FloydWarshall.printPath();
}
}
| 1,660 | 0.536468 | 0.453888 | 84 | 18.75 | 16.980293 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.130952 | false | false | 9 |
05835ed381f9d67e4bb5a8afa04b779fa40def8b | 10,067,403,355,499 | fb02891ae4e835b12e2badfb65d1b2e5f580920e | /src/projekt_ks/DB_connect.java | b7d889ba491a0393417c0f281d5122f04b229778 | [] | no_license | wmp-iie-ist-s-2017-18/projectdb-sikora | https://github.com/wmp-iie-ist-s-2017-18/projectdb-sikora | e9e764ef363f839d443af1042bec861669aad397 | acc75d45ccccab1d41a7f2c0ae47c2ba01aeb22d | refs/heads/master | 2020-05-14T03:24:13.828000 | 2019-06-22T11:30:24 | 2019-06-22T11:30:24 | 181,694,018 | 0 | 0 | null | false | 2019-06-21T15:00:45 | 2019-04-16T13:24:23 | 2019-06-20T22:35:01 | 2019-06-21T15:00:45 | 3,150 | 0 | 0 | 0 | Java | 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 projekt_ks;
/**
*
* @author Karol
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DB_connect {
private static final String Sterownik = "com.mysql.jdbc.Driver";
public Connection DB_connection()
{
try
{
String url = "jdbc:mysql://localhost/database";
String user = "root";
String password = "";
Class.forName(Sterownik);
Connection conn = DriverManager.getConnection(url);
return conn;
}
catch (ClassNotFoundException | SQLException ex)
{
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
return null;
}
} | UTF-8 | Java | 1,098 | java | DB_connect.java | Java | [
{
"context": ".\r\n */\r\npackage projekt_ks;\r\n\r\n/**\r\n *\r\n * @author Karol\r\n */\r\nimport java.sql.Connection;\r\nimport java.sq",
"end": 238,
"score": 0.9994301795959473,
"start": 233,
"tag": "NAME",
"value": "Karol"
}
] | 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 projekt_ks;
/**
*
* @author Karol
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DB_connect {
private static final String Sterownik = "com.mysql.jdbc.Driver";
public Connection DB_connection()
{
try
{
String url = "jdbc:mysql://localhost/database";
String user = "root";
String password = "";
Class.forName(Sterownik);
Connection conn = DriverManager.getConnection(url);
return conn;
}
catch (ClassNotFoundException | SQLException ex)
{
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
return null;
}
} | 1,098 | 0.579235 | 0.578324 | 43 | 23.581396 | 22.395216 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.465116 | false | false | 9 |
5c56837851d3d3063894f144c2ac4b50da0eb062 | 15,264,313,779,987 | da6e0f2c8aa129ea6e1de89d25a512d4271c0564 | /src/main/java/ml/rugal/sshcommon/page/Paginable.java | 286dd43bb851dc7b06e8ed6076ee710ee12f8dc8 | [] | no_license | Rugal/ssh-common | https://github.com/Rugal/ssh-common | 1ea4c2188c6198b692e4052284ab4f571a532334 | fc032ea3fa57a9f58e497f22db031a26ae6b5770 | refs/heads/master | 2020-04-12T07:34:56.334000 | 2017-07-07T17:20:22 | 2017-07-07T17:20:22 | 21,973,857 | 1 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ml.rugal.sshcommon.page;
/**
* Interface of object that is paginable.
*
* @author Rugal Bernstein
*/
public interface Paginable {
/**
* The total number in all pages.
*
* @return
*/
public int getTotalCount();
/**
* Get the total page number of a query. to see total row number divided by page size per page.
*
* @return get total page a query could have.
*/
public int getTotalPage();
public int getPageSize();
public int getPageNo();
/**
* See if this is the first(1) page.
*
* @return true if current page if the first one.
*/
public boolean isFirstPage();
/**
* To see if current page number is equal or greater than last page number.
*
* @return true if current page is equal or greater than last page number.
*/
public boolean isLastPage();
/**
* Get next page number, just return current one if current page is the last one.
*
* @return page number calculated
*/
public int getNextPage();
/**
*
* Get previous page number, if current page is the first one just return current one.
*
* @return page number calculated
*/
public int getPrePage();
}
| UTF-8 | Java | 1,255 | java | Paginable.java | Java | [
{
"context": "terface of object that is paginable.\n *\n * @author Rugal Bernstein\n */\npublic interface Paginable {\n\n /**\n * ",
"end": 109,
"score": 0.9998442530632019,
"start": 94,
"tag": "NAME",
"value": "Rugal Bernstein"
}
] | null | [] | package ml.rugal.sshcommon.page;
/**
* Interface of object that is paginable.
*
* @author <NAME>
*/
public interface Paginable {
/**
* The total number in all pages.
*
* @return
*/
public int getTotalCount();
/**
* Get the total page number of a query. to see total row number divided by page size per page.
*
* @return get total page a query could have.
*/
public int getTotalPage();
public int getPageSize();
public int getPageNo();
/**
* See if this is the first(1) page.
*
* @return true if current page if the first one.
*/
public boolean isFirstPage();
/**
* To see if current page number is equal or greater than last page number.
*
* @return true if current page is equal or greater than last page number.
*/
public boolean isLastPage();
/**
* Get next page number, just return current one if current page is the last one.
*
* @return page number calculated
*/
public int getNextPage();
/**
*
* Get previous page number, if current page is the first one just return current one.
*
* @return page number calculated
*/
public int getPrePage();
}
| 1,246 | 0.606375 | 0.605578 | 56 | 21.410715 | 25.031963 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.196429 | false | false | 9 |
e67e477e1b4bf3aee39c128650fee48bf07fbbde | 31,980,326,500,910 | 56d44a0700826fdbb18f092d8d9a1a67b1467ebc | /Programacion/juegos/marcianos/Disparos.java | a773efa6bd9af010e4b2e47a2c6b700add283dc5 | [] | no_license | noenavarro2/programacion | https://github.com/noenavarro2/programacion | 18c37a6e2ebbc93442fb3dd3173518e60aa72148 | c1ae563a1677628134a6e0b533dded2aebfdfbde | refs/heads/master | 2017-05-10T16:20:45.162000 | 2017-04-25T17:28:24 | 2017-04-25T17:28:24 | 82,582,888 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package marcianos;
import java.awt.Graphics;
import java.awt.Rectangle;
public class Disparos extends Rectangle {
int velX, velY;
public Disparos() {
super((int) Play.nave.getX() + 55, (int) Play.nave.getY() + 15, 10, 10); // int posX, int posY, int ancho, int alto
velX = 5;
velY = 5;
}
public void paint(Graphics g) {
g.drawImage(Play.laser, x, y, width, height, Play.img2);
}
public void actualizar() {
x += velX;
}
} | UTF-8 | Java | 463 | java | Disparos.java | Java | [] | null | [] | package marcianos;
import java.awt.Graphics;
import java.awt.Rectangle;
public class Disparos extends Rectangle {
int velX, velY;
public Disparos() {
super((int) Play.nave.getX() + 55, (int) Play.nave.getY() + 15, 10, 10); // int posX, int posY, int ancho, int alto
velX = 5;
velY = 5;
}
public void paint(Graphics g) {
g.drawImage(Play.laser, x, y, width, height, Play.img2);
}
public void actualizar() {
x += velX;
}
} | 463 | 0.62635 | 0.602592 | 22 | 19.136364 | 26.207729 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.727273 | false | false | 9 |
33c8cdd0005ff98be0c88b972f5509b4ed618e42 | 23,931,557,803,288 | cbf720099161e3109eded01d55e8b7cad8168a96 | /app/src/main/java/com/rd/strivos/cobby/PreCommissioningDBHelper.java | 850d0eeca590e92155c29a19275c4ab42462cb7e | [] | no_license | nandhakumarnk/IBMS | https://github.com/nandhakumarnk/IBMS | 3d5537649bdd6330d90ea613036c8cd550a95550 | 5b598c379cb6af1c95856cbd9828ffdc3c8083bf | refs/heads/master | 2021-01-19T12:14:49.832000 | 2016-12-15T17:54:49 | 2016-12-15T17:54:49 | 54,110,983 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rd.strivos.cobby;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.rd.strivos.cobby.PreCommissioningDBFields.PreCommissioningAdd;
import java.sql.SQLException;
/**
* Created by COBURG DESIGN on 11-02-2016.
*/
public class PreCommissioningDBHelper extends SQLiteOpenHelper {
public PreCommissioningDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "precommissioninglive.db";
private static final String SQL_CREATE_PRECOMMISSIONING = "CREATE TABLE "
+ PreCommissioningAdd.TABLE_NAME + " (" + PreCommissioningAdd._ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PreCommissioningAdd.COLUMN_NAME_SERVICE_ENGINEER_ID + " TEXT," //1
+ PreCommissioningAdd.COLUMN_NAME_SERVICE_ENGINEER_NAME + " TEXT," //2
+ PreCommissioningAdd.COLUMN_NAME_ADDRESS + " TEXT," //3
+ PreCommissioningAdd.COLUMN_NAME_PINCODE + " TEXT," //4
+ PreCommissioningAdd.COLUMN_NAME_DISTRICT + " TEXT," //5
+ PreCommissioningAdd.COLUMN_NAME_CUSTOMER_NAME + " TEXT," //6
+ PreCommissioningAdd.COLUMN_NAME_CUSTOMER_ID + " TEXT," //7
+ PreCommissioningAdd.COLUMN_NAME_ACCOUNT_M_CONTACT_ID + " TEXT," //8
+ PreCommissioningAdd.COLUMN_NAME_ACCOUNT_M_CONTACT_NAME + " TEXT," //9
+ PreCommissioningAdd.COLUMN_NAME_PHONE_NO + " TEXT," //10
+ PreCommissioningAdd.COLUMN_NAME_EMAIL + " TEXT," //11
+ PreCommissioningAdd.COLUMN_NAME_PRODUCT_ID + " TEXT," //12
+ PreCommissioningAdd.COLUMN_NAME_PRODUCT_NAME + " TEXT," //13
+ PreCommissioningAdd.COLUMN_NAME_MACHINE_SL_NO + " TEXT," //14
+ PreCommissioningAdd.COLUMN_NAME_PART_NO + " TEXT," //15
+ PreCommissioningAdd.COLUMN_NAME_EDC + " TEXT," //16
+ PreCommissioningAdd.COLUMN_NAME_YOM + " TEXT," //17
+ PreCommissioningAdd.COLUMN_NAME_REMARKS + " TEXT," //18
+ PreCommissioningAdd.COLUMN_NAME_LAT + " TEXT," //19
+ PreCommissioningAdd.COLUMN_NAME_LON + " TEXT," //20
+ PreCommissioningAdd.COLUMN_NAME_STATUS + " TEXT" + " )"; //21
private static final String SQL_DELETE_PRECOMMISSIONING = "DROP TABLE IF EXISTS "
+ PreCommissioningAdd.TABLE_NAME;
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_PRECOMMISSIONING);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_PRECOMMISSIONING);
onCreate(db);
}
public long insertPreCommissioning(String val1, String val2, String val3, String val4, String val5, String val6, String val7, String val8, String val9, String val10, String val11, String val12, String val13, String val14, String val15, String val16, String val17, String val18, String val19, String val20, String val21) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(PreCommissioningAdd.COLUMN_NAME_SERVICE_ENGINEER_ID, val1);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_SERVICE_ENGINEER_NAME, val2);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_ADDRESS, val3);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_PINCODE, val4);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_DISTRICT, val5);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_CUSTOMER_NAME, val6);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_CUSTOMER_ID, val7);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_ACCOUNT_M_CONTACT_ID, val8);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_ACCOUNT_M_CONTACT_NAME, val9);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_PHONE_NO, val10);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_EMAIL, val11);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_PRODUCT_ID, val12);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_PRODUCT_NAME, val13);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_MACHINE_SL_NO, val14);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_PART_NO, val15);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_EDC, val16);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_YOM, val17);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_REMARKS, val18);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_LAT, val19);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_LON, val20);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_STATUS, val21);
long l = db.insert(PreCommissioningAdd.TABLE_NAME, null, initialValues);
db.close();
return l;
}
public void PreCommissioningStatusUpdate(String val1) {
SQLiteDatabase sqdb = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PreCommissioningAdd.COLUMN_NAME_STATUS, "Y");
System.out.print(val1);
sqdb.update(PreCommissioningAdd.TABLE_NAME, values, "_id=" + val1, null);
}
public Cursor selectPreCommissioning() throws SQLException {
SQLiteDatabase db = this.getWritableDatabase();
String fetch = "SELECT * FROM " + PreCommissioningAdd.TABLE_NAME + " WHERE " + PreCommissioningAdd.COLUMN_NAME_STATUS + " ='N'";
Cursor c = db.rawQuery(fetch, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
}
| UTF-8 | Java | 5,806 | java | PreCommissioningDBHelper.java | Java | [
{
"context": "\n\nimport java.sql.SQLException;\n\n/**\n * Created by COBURG DESIGN on 11-02-2016.\n */\npublic class PreCommissioningD",
"end": 367,
"score": 0.7040764093399048,
"start": 354,
"tag": "NAME",
"value": "COBURG DESIGN"
}
] | null | [] | package com.rd.strivos.cobby;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.rd.strivos.cobby.PreCommissioningDBFields.PreCommissioningAdd;
import java.sql.SQLException;
/**
* Created by <NAME> on 11-02-2016.
*/
public class PreCommissioningDBHelper extends SQLiteOpenHelper {
public PreCommissioningDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "precommissioninglive.db";
private static final String SQL_CREATE_PRECOMMISSIONING = "CREATE TABLE "
+ PreCommissioningAdd.TABLE_NAME + " (" + PreCommissioningAdd._ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PreCommissioningAdd.COLUMN_NAME_SERVICE_ENGINEER_ID + " TEXT," //1
+ PreCommissioningAdd.COLUMN_NAME_SERVICE_ENGINEER_NAME + " TEXT," //2
+ PreCommissioningAdd.COLUMN_NAME_ADDRESS + " TEXT," //3
+ PreCommissioningAdd.COLUMN_NAME_PINCODE + " TEXT," //4
+ PreCommissioningAdd.COLUMN_NAME_DISTRICT + " TEXT," //5
+ PreCommissioningAdd.COLUMN_NAME_CUSTOMER_NAME + " TEXT," //6
+ PreCommissioningAdd.COLUMN_NAME_CUSTOMER_ID + " TEXT," //7
+ PreCommissioningAdd.COLUMN_NAME_ACCOUNT_M_CONTACT_ID + " TEXT," //8
+ PreCommissioningAdd.COLUMN_NAME_ACCOUNT_M_CONTACT_NAME + " TEXT," //9
+ PreCommissioningAdd.COLUMN_NAME_PHONE_NO + " TEXT," //10
+ PreCommissioningAdd.COLUMN_NAME_EMAIL + " TEXT," //11
+ PreCommissioningAdd.COLUMN_NAME_PRODUCT_ID + " TEXT," //12
+ PreCommissioningAdd.COLUMN_NAME_PRODUCT_NAME + " TEXT," //13
+ PreCommissioningAdd.COLUMN_NAME_MACHINE_SL_NO + " TEXT," //14
+ PreCommissioningAdd.COLUMN_NAME_PART_NO + " TEXT," //15
+ PreCommissioningAdd.COLUMN_NAME_EDC + " TEXT," //16
+ PreCommissioningAdd.COLUMN_NAME_YOM + " TEXT," //17
+ PreCommissioningAdd.COLUMN_NAME_REMARKS + " TEXT," //18
+ PreCommissioningAdd.COLUMN_NAME_LAT + " TEXT," //19
+ PreCommissioningAdd.COLUMN_NAME_LON + " TEXT," //20
+ PreCommissioningAdd.COLUMN_NAME_STATUS + " TEXT" + " )"; //21
private static final String SQL_DELETE_PRECOMMISSIONING = "DROP TABLE IF EXISTS "
+ PreCommissioningAdd.TABLE_NAME;
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_PRECOMMISSIONING);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_PRECOMMISSIONING);
onCreate(db);
}
public long insertPreCommissioning(String val1, String val2, String val3, String val4, String val5, String val6, String val7, String val8, String val9, String val10, String val11, String val12, String val13, String val14, String val15, String val16, String val17, String val18, String val19, String val20, String val21) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(PreCommissioningAdd.COLUMN_NAME_SERVICE_ENGINEER_ID, val1);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_SERVICE_ENGINEER_NAME, val2);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_ADDRESS, val3);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_PINCODE, val4);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_DISTRICT, val5);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_CUSTOMER_NAME, val6);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_CUSTOMER_ID, val7);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_ACCOUNT_M_CONTACT_ID, val8);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_ACCOUNT_M_CONTACT_NAME, val9);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_PHONE_NO, val10);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_EMAIL, val11);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_PRODUCT_ID, val12);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_PRODUCT_NAME, val13);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_MACHINE_SL_NO, val14);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_PART_NO, val15);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_EDC, val16);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_YOM, val17);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_REMARKS, val18);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_LAT, val19);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_LON, val20);
initialValues.put(PreCommissioningAdd.COLUMN_NAME_STATUS, val21);
long l = db.insert(PreCommissioningAdd.TABLE_NAME, null, initialValues);
db.close();
return l;
}
public void PreCommissioningStatusUpdate(String val1) {
SQLiteDatabase sqdb = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PreCommissioningAdd.COLUMN_NAME_STATUS, "Y");
System.out.print(val1);
sqdb.update(PreCommissioningAdd.TABLE_NAME, values, "_id=" + val1, null);
}
public Cursor selectPreCommissioning() throws SQLException {
SQLiteDatabase db = this.getWritableDatabase();
String fetch = "SELECT * FROM " + PreCommissioningAdd.TABLE_NAME + " WHERE " + PreCommissioningAdd.COLUMN_NAME_STATUS + " ='N'";
Cursor c = db.rawQuery(fetch, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
}
| 5,799 | 0.689804 | 0.670685 | 112 | 50.839287 | 40.611961 | 325 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 9 |
e9b1756213777a1676fcb11b46a0a79dbb44a214 | 4,260,607,613,391 | 8f87065bc3cb6d96ea2e398a98aacda4fc4bbe43 | /src/Class00000133Worse.java | c75ffe393f91f92f84473636c51110ea3e03ae11 | [] | no_license | fracz/code-quality-benchmark | https://github.com/fracz/code-quality-benchmark | a243d345441582473532f9b013993f77d59e19ae | c23e76fe315f43bea899beabb856e61348c34e09 | refs/heads/master | 2020-04-08T23:40:36.408000 | 2019-07-31T17:54:53 | 2019-07-31T17:54:53 | 159,835,188 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // original filename: 00019772.txt
// before
public class Class00000133Worse {
@Override
public Blob createBlob() throws SQLException {
if (conn != null) {
return conn.createBlob();
}
throw new SQLException("connection not init");
}
}
| UTF-8 | Java | 283 | java | Class00000133Worse.java | Java | [] | null | [] | // original filename: 00019772.txt
// before
public class Class00000133Worse {
@Override
public Blob createBlob() throws SQLException {
if (conn != null) {
return conn.createBlob();
}
throw new SQLException("connection not init");
}
}
| 283 | 0.618375 | 0.561837 | 11 | 24.727272 | 17.555578 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | false | false | 9 |
2864a21a1d5133fb76673591ef5d47fbd715bbb0 | 4,260,607,609,756 | 7821952b534d2c788ca3ed743420b26d6f59097d | /src/com/shelvin/study/datastructure/res/unionfind/UnionFind.java | 07fbc411a1744e7c37d376a8275e7d465ebdd9f2 | [] | no_license | weixianqing/Java-Research | https://github.com/weixianqing/Java-Research | ae5e84a215592718a2b0a40301f7779df6475e63 | 6f2911d20b3ccb34bc5cb0e0980d52e3ffb16b19 | refs/heads/master | 2021-01-19T01:49:45.203000 | 2019-02-20T09:25:56 | 2019-02-20T09:25:56 | 43,347,495 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.shelvin.study.datastructure.res.unionfind;
/**
* Created by shelvin on 22/8/16 at 22:23.
*/
public class UnionFind
{
private int[] id;
private int count;
//as weights for subtree with unequal number of nodes
private int[] weighted;
public UnionFind(int N)
{
count = N;
for (int i = 0; i < count; i++)
{
id[i] = i;
}
for (int i = 0; i < count; i++)
{
weighted[i] = 1;
}
}
public int getCount()
{
return count;
}
public int quickfindFind(int p)
{
return id[p];
}
public void quickfindUnion(int p, int q)
{
int pID = quickfindFind(p);
int qID = quickfindFind(q);
if (pID == qID)
{
return;
}
for (int i = 0; i < count; i++)
{
if (id[i] == pID)
{
id[i] = qID;
}
}
count--;
}
public int quickunionFind(int p)
{
while (id[p] != p)
{
p = id[p];
}
return p;
}
public void quickunionUnion(int p, int q)
{
int pRoot = quickunionFind(p);
int qRoot = quickunionFind(q);
if (pRoot == qRoot)
{
return;
}
id[pRoot] = qRoot;
count--;
}
public void weightedquickunionUnion(int p, int q)
{
int pRoot = quickunionFind(p);
int qRoot = quickfindFind(q);
if (pRoot == qRoot)
{
return;
}
if (weighted[pRoot] > weighted[qRoot])
{
id[qRoot] = pRoot;
weighted[pRoot] += weighted[qRoot];
} else
{
id[pRoot] = qRoot;
weighted[qRoot] += weighted[pRoot];
}
count--;
}
public int optimalFind(int p)
{
//path compression
while (p != id[p])
{
id[p] = id[id[p]];
p = id[p];
}
return p;
}
}
| UTF-8 | Java | 2,054 | java | UnionFind.java | Java | [
{
"context": "dy.datastructure.res.unionfind;\n\n/**\n * Created by shelvin on 22/8/16 at 22:23.\n */\n\npublic class UnionFind\n",
"end": 81,
"score": 0.9996027946472168,
"start": 74,
"tag": "USERNAME",
"value": "shelvin"
}
] | null | [] | package com.shelvin.study.datastructure.res.unionfind;
/**
* Created by shelvin on 22/8/16 at 22:23.
*/
public class UnionFind
{
private int[] id;
private int count;
//as weights for subtree with unequal number of nodes
private int[] weighted;
public UnionFind(int N)
{
count = N;
for (int i = 0; i < count; i++)
{
id[i] = i;
}
for (int i = 0; i < count; i++)
{
weighted[i] = 1;
}
}
public int getCount()
{
return count;
}
public int quickfindFind(int p)
{
return id[p];
}
public void quickfindUnion(int p, int q)
{
int pID = quickfindFind(p);
int qID = quickfindFind(q);
if (pID == qID)
{
return;
}
for (int i = 0; i < count; i++)
{
if (id[i] == pID)
{
id[i] = qID;
}
}
count--;
}
public int quickunionFind(int p)
{
while (id[p] != p)
{
p = id[p];
}
return p;
}
public void quickunionUnion(int p, int q)
{
int pRoot = quickunionFind(p);
int qRoot = quickunionFind(q);
if (pRoot == qRoot)
{
return;
}
id[pRoot] = qRoot;
count--;
}
public void weightedquickunionUnion(int p, int q)
{
int pRoot = quickunionFind(p);
int qRoot = quickfindFind(q);
if (pRoot == qRoot)
{
return;
}
if (weighted[pRoot] > weighted[qRoot])
{
id[qRoot] = pRoot;
weighted[pRoot] += weighted[qRoot];
} else
{
id[pRoot] = qRoot;
weighted[qRoot] += weighted[pRoot];
}
count--;
}
public int optimalFind(int p)
{
//path compression
while (p != id[p])
{
id[p] = id[id[p]];
p = id[p];
}
return p;
}
}
| 2,054 | 0.428919 | 0.42259 | 113 | 17.176991 | 14.900395 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.362832 | false | false | 9 |
629953f7f67f8afc1286aa4e6961c1bae64efb6e | 6,743,098,712,927 | 72a683043e9837ea87094a8cb2bcf07db15212d8 | /src/main/java/com/sap/cisp/xhna/data/executor/forum/stock/GubaPost.java | 792237a64adc0f12df85aac4d8a659a04145706b | [] | no_license | milome/115Hunter | https://github.com/milome/115Hunter | aee179bcc7d18c4cbdbfea3c49a6f4eabaf95844 | 2b6ecf698a488f323d3d77dc477ff75fad43f44a | refs/heads/master | 2020-03-21T04:26:20.046000 | 2018-06-26T08:25:02 | 2018-06-26T08:25:02 | 138,108,225 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sap.cisp.xhna.data.executor.forum.stock;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
public class GubaPost {
private String title;
private String postId;
private String url;
private String author;
private String authorId;
private String content;
private String replyToId;
private String crawlTime;
private String postDate;
private String replyCount;
private String forwardCount;
private String stockName;
private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public GubaPost(String title, String author, String authorId,String url, String content) {
this.title = title;
this.author = author;
this.authorId = authorId;
this.url = url;
this.content = content;
}
public GubaPost() {}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title.replace("\t", " ");
}
public String getId() {
return postId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setId(String id) {
this.postId = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthorId() {
return authorId;
}
public void setAuthorId(String authorId) {
this.authorId = authorId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content.replace("\t", " ");
this.content = content.replace("\n", "\\n");
this.content = content.replace("\r", "\\r");
}
public String getReplyToId() {
return replyToId;
}
public void setReplyToId(String replyToId) {
this.replyToId = replyToId;
}
public String getCrawlTime() {
return crawlTime;
}
public void setCrawlTime(String crawlTime) {
this.crawlTime = crawlTime;
}
public String getPostDate() {
return postDate;
}
public void setPostDate(String postDate) {
this.postDate = postDate;
}
public String getReplyCount()
{
return replyCount;
}
public void setReplyCount(String replyCount)
{
this.replyCount = replyCount;
}
public String getForwardCount()
{
return forwardCount;
}
public void setForwardCount(String forwardCount)
{
this.forwardCount = forwardCount;
}
public String getStockName()
{
return stockName;
}
public void setStockName(String stockName)
{
this.stockName = stockName;
}
@SuppressWarnings("unchecked")
public void save(Map<String, Object> ctx) {
if (crawlTime == null || "".equals(crawlTime)) {
this.crawlTime = sdf.format(Calendar.getInstance().getTime());
}
((List<String>) ctx.get("result")).add(JSON.toJSONString(this));
}
@Override
public String toString() {
return String.format("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s",
postId, title, url, author, authorId,content,replyToId,crawlTime,postDate,replyCount,forwardCount);
}
}
| UTF-8 | Java | 3,472 | java | GubaPost.java | Java | [] | null | [] | package com.sap.cisp.xhna.data.executor.forum.stock;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
public class GubaPost {
private String title;
private String postId;
private String url;
private String author;
private String authorId;
private String content;
private String replyToId;
private String crawlTime;
private String postDate;
private String replyCount;
private String forwardCount;
private String stockName;
private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public GubaPost(String title, String author, String authorId,String url, String content) {
this.title = title;
this.author = author;
this.authorId = authorId;
this.url = url;
this.content = content;
}
public GubaPost() {}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title.replace("\t", " ");
}
public String getId() {
return postId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setId(String id) {
this.postId = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthorId() {
return authorId;
}
public void setAuthorId(String authorId) {
this.authorId = authorId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content.replace("\t", " ");
this.content = content.replace("\n", "\\n");
this.content = content.replace("\r", "\\r");
}
public String getReplyToId() {
return replyToId;
}
public void setReplyToId(String replyToId) {
this.replyToId = replyToId;
}
public String getCrawlTime() {
return crawlTime;
}
public void setCrawlTime(String crawlTime) {
this.crawlTime = crawlTime;
}
public String getPostDate() {
return postDate;
}
public void setPostDate(String postDate) {
this.postDate = postDate;
}
public String getReplyCount()
{
return replyCount;
}
public void setReplyCount(String replyCount)
{
this.replyCount = replyCount;
}
public String getForwardCount()
{
return forwardCount;
}
public void setForwardCount(String forwardCount)
{
this.forwardCount = forwardCount;
}
public String getStockName()
{
return stockName;
}
public void setStockName(String stockName)
{
this.stockName = stockName;
}
@SuppressWarnings("unchecked")
public void save(Map<String, Object> ctx) {
if (crawlTime == null || "".equals(crawlTime)) {
this.crawlTime = sdf.format(Calendar.getInstance().getTime());
}
((List<String>) ctx.get("result")).add(JSON.toJSONString(this));
}
@Override
public String toString() {
return String.format("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s",
postId, title, url, author, authorId,content,replyToId,crawlTime,postDate,replyCount,forwardCount);
}
}
| 3,472 | 0.610023 | 0.610023 | 153 | 21.69281 | 20.557358 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.542484 | false | false | 9 |
d9782364303ccf1319d1ea35111d4e13f6219dfa | 3,693,671,935,232 | 8e8ed9f12fa92aec41e7ef0106e9c710cbd42520 | /user-edge-service/src/main/java/com/me/user/controller/UserController.java | 86a4f1fec3ff60fe72bb8c94b3ec93669d52ac49 | [] | no_license | SavorTheFlavor/microservice | https://github.com/SavorTheFlavor/microservice | 52946c09fc2ae86d0d8542267f9a4f6a4aab5403 | 8e5163b99280a1e9a658dff656eee9ec8e478bcd | refs/heads/master | 2020-04-04T14:05:55.332000 | 2019-01-23T16:13:11 | 2019-01-23T16:13:11 | 155,986,827 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.me.user.controller;
import com.me.user.dto.UserDTO;
import com.me.user.redis.RedisClient;
import com.me.user.thrift.ServiceProvider;
import com.me.user.thrift.UserInfo;
import com.me.user.vo.LoginResponse;
import com.me.user.vo.Response;
import org.apache.commons.lang.StringUtils;
import org.apache.thrift.TException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by Administrator on 2018/12/15.
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private ServiceProvider serviceProvider;
@Autowired
private RedisClient redisClient;
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(){
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public Response login(@RequestParam("username")String username,
@RequestParam("password")String password, HttpServletResponse resp){
UserInfo userInfo = null;
try {
userInfo = serviceProvider.getUserService().getUserByName(username);
} catch (TException e) {
e.printStackTrace();
//if getUserByName method return null, thrift will throw an exception.
return Response.USERNAME_PASSWORD_INVALID;
}
//验证用户
if(userInfo == null){
return Response.USERNAME_PASSWORD_INVALID;
}
if(!userInfo.getPassword().equalsIgnoreCase(password)){
return Response.USERNAME_PASSWORD_INVALID;
}
//生成token
String token = genToken();
//缓存用户
redisClient.set(token, toDTO(userInfo), 3600);
resp.addCookie(new Cookie("token", token));
return new LoginResponse(token);
}
private UserDTO toDTO(UserInfo userInfo) {
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(userInfo, userDTO);
return userDTO;
}
@RequestMapping(value = "/sendVerifyCode", method = RequestMethod.POST)
@ResponseBody
public Response sendVerifyCode(@RequestParam(value="mobile", required = false) String mobile,
@RequestParam(value="email", required = false) String email){
String msg = "your verify code is ";
String code = randomCode("0123456789", 6);
try {
if (StringUtils.isNotBlank(mobile)){
//send verifying code
serviceProvider.getMessageService().sendMobileMessage(mobile, msg + code);
redisClient.set(mobile, code, 500);
}else if(StringUtils.isNotBlank(email)){
//send verifying email
serviceProvider.getMessageService().sendEmailMessage(email, msg + code);
redisClient.set(email, code, 500);
}else{
return Response.SEND_VERIFYCODE_ERROR;
}
}catch (Exception e){
e.printStackTrace();
return new Response("9999", e.getMessage());
}
return Response.SUCCESS;
}
@RequestMapping(value="/register", method = RequestMethod.POST)
@ResponseBody
public Response register(@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam(value="mobile", required = false) String mobile,
@RequestParam(value="email", required = false) String email,
@RequestParam("verifyCode") String verifyCode) {
if(StringUtils.isBlank(mobile) && StringUtils.isBlank(email)){
return Response.MOBILE_OR_EMAIL_REQUIRED;
}
if(StringUtils.isNotBlank(mobile)){
String code = redisClient.get(mobile);
if(!verifyCode.equals(code)){
return Response.VERIFY_CODE_INVALID;
}
}else {
String redisCode = redisClient.get(email);
if(!verifyCode.equals(redisCode)) {
return Response.VERIFY_CODE_INVALID;
}
}
UserInfo userInfo = new UserInfo();
userInfo.setUsername(username);
userInfo.setPassword(password);
userInfo.setMobile(mobile);
userInfo.setEmail(email);
try {
serviceProvider.getUserService().registerUser(userInfo);
} catch (TException e) {
e.printStackTrace();
return Response.exception(e);
}
return Response.SUCCESS;
}
@RequestMapping(value = "/authentication", method = RequestMethod.POST)
@ResponseBody
public UserDTO authentication(@RequestHeader("token") String token){
return redisClient.get(token);
}
private String genToken() {
return randomCode("0123456789qwertyuiopasdfghjklzxcvbnm", 32);
}
private String randomCode(String str, int length) {
StringBuilder sb = new StringBuilder();
for(int i=0; i<length; i++){
sb.append(str.charAt((int)Math.floor(Math.random()*length)));
}
return sb.toString();
}
}
| UTF-8 | Java | 5,444 | java | UserController.java | Java | [
{
"context": "eBody\n public Response register(@RequestParam(\"username\") String username,\n @",
"end": 3510,
"score": 0.8845470547676086,
"start": 3502,
"tag": "USERNAME",
"value": "username"
},
{
"context": "Response register(@RequestParam(\"username\") String username,\n @RequestParam(\"pass",
"end": 3528,
"score": 0.832667350769043,
"start": 3520,
"tag": "USERNAME",
"value": "username"
},
{
"context": " @RequestParam(\"password\") String password,\n @RequestParam(value",
"end": 3600,
"score": 0.5655355453491211,
"start": 3592,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "fo = new UserInfo();\n userInfo.setUsername(username);\n userInfo.setPassword(password);\n ",
"end": 4481,
"score": 0.9955542683601379,
"start": 4473,
"tag": "USERNAME",
"value": "username"
},
{
"context": "tUsername(username);\n userInfo.setPassword(password);\n userInfo.setMobile(mobile);\n use",
"end": 4521,
"score": 0.9988603591918945,
"start": 4513,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "te String genToken() {\n return randomCode(\"0123456789qwertyuiopasdfghjklzxcvbnm\", 32);\n }\n\n private String randomCode(Strin",
"end": 5146,
"score": 0.9871196150779724,
"start": 5110,
"tag": "KEY",
"value": "0123456789qwertyuiopasdfghjklzxcvbnm"
}
] | null | [] | package com.me.user.controller;
import com.me.user.dto.UserDTO;
import com.me.user.redis.RedisClient;
import com.me.user.thrift.ServiceProvider;
import com.me.user.thrift.UserInfo;
import com.me.user.vo.LoginResponse;
import com.me.user.vo.Response;
import org.apache.commons.lang.StringUtils;
import org.apache.thrift.TException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by Administrator on 2018/12/15.
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private ServiceProvider serviceProvider;
@Autowired
private RedisClient redisClient;
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(){
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public Response login(@RequestParam("username")String username,
@RequestParam("password")String password, HttpServletResponse resp){
UserInfo userInfo = null;
try {
userInfo = serviceProvider.getUserService().getUserByName(username);
} catch (TException e) {
e.printStackTrace();
//if getUserByName method return null, thrift will throw an exception.
return Response.USERNAME_PASSWORD_INVALID;
}
//验证用户
if(userInfo == null){
return Response.USERNAME_PASSWORD_INVALID;
}
if(!userInfo.getPassword().equalsIgnoreCase(password)){
return Response.USERNAME_PASSWORD_INVALID;
}
//生成token
String token = genToken();
//缓存用户
redisClient.set(token, toDTO(userInfo), 3600);
resp.addCookie(new Cookie("token", token));
return new LoginResponse(token);
}
private UserDTO toDTO(UserInfo userInfo) {
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(userInfo, userDTO);
return userDTO;
}
@RequestMapping(value = "/sendVerifyCode", method = RequestMethod.POST)
@ResponseBody
public Response sendVerifyCode(@RequestParam(value="mobile", required = false) String mobile,
@RequestParam(value="email", required = false) String email){
String msg = "your verify code is ";
String code = randomCode("0123456789", 6);
try {
if (StringUtils.isNotBlank(mobile)){
//send verifying code
serviceProvider.getMessageService().sendMobileMessage(mobile, msg + code);
redisClient.set(mobile, code, 500);
}else if(StringUtils.isNotBlank(email)){
//send verifying email
serviceProvider.getMessageService().sendEmailMessage(email, msg + code);
redisClient.set(email, code, 500);
}else{
return Response.SEND_VERIFYCODE_ERROR;
}
}catch (Exception e){
e.printStackTrace();
return new Response("9999", e.getMessage());
}
return Response.SUCCESS;
}
@RequestMapping(value="/register", method = RequestMethod.POST)
@ResponseBody
public Response register(@RequestParam("username") String username,
@RequestParam("password") String <PASSWORD>,
@RequestParam(value="mobile", required = false) String mobile,
@RequestParam(value="email", required = false) String email,
@RequestParam("verifyCode") String verifyCode) {
if(StringUtils.isBlank(mobile) && StringUtils.isBlank(email)){
return Response.MOBILE_OR_EMAIL_REQUIRED;
}
if(StringUtils.isNotBlank(mobile)){
String code = redisClient.get(mobile);
if(!verifyCode.equals(code)){
return Response.VERIFY_CODE_INVALID;
}
}else {
String redisCode = redisClient.get(email);
if(!verifyCode.equals(redisCode)) {
return Response.VERIFY_CODE_INVALID;
}
}
UserInfo userInfo = new UserInfo();
userInfo.setUsername(username);
userInfo.setPassword(<PASSWORD>);
userInfo.setMobile(mobile);
userInfo.setEmail(email);
try {
serviceProvider.getUserService().registerUser(userInfo);
} catch (TException e) {
e.printStackTrace();
return Response.exception(e);
}
return Response.SUCCESS;
}
@RequestMapping(value = "/authentication", method = RequestMethod.POST)
@ResponseBody
public UserDTO authentication(@RequestHeader("token") String token){
return redisClient.get(token);
}
private String genToken() {
return randomCode("<KEY>", 32);
}
private String randomCode(String str, int length) {
StringBuilder sb = new StringBuilder();
for(int i=0; i<length; i++){
sb.append(str.charAt((int)Math.floor(Math.random()*length)));
}
return sb.toString();
}
}
| 5,417 | 0.625369 | 0.616888 | 158 | 33.329113 | 25.878597 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.594937 | false | false | 9 |
6c19ff67918d912610ef1f47033c7be44b87e03f | 13,503,377,236,906 | ca030864a3a1c24be6b9d1802c2353da4ca0d441 | /classes7.dex_source_from_JADX/com/facebook/timeline/widget/actionbar/PersonActionBarItemConsumer.java | 07d468cc0ca2f3a8e5c967f5944cc06a3fa3f5f2 | [] | no_license | pxson001/facebook-app | https://github.com/pxson001/facebook-app | 87aa51e29195eeaae69adeb30219547f83a5b7b1 | 640630f078980f9818049625ebc42569c67c69f7 | refs/heads/master | 2020-04-07T20:36:45.758000 | 2018-03-07T09:04:57 | 2018-03-07T09:04:57 | 124,208,458 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook.timeline.widget.actionbar;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
/* compiled from: f4v */
public interface PersonActionBarItemConsumer {
void m18804a(@PersonActionBarItems int i, @StringRes int i2, @DrawableRes int i3, int i4, boolean z, boolean z2);
void m18805a(@PersonActionBarItems int i, @StringRes int i2, @DrawableRes int i3, int i4, boolean z, boolean z2, boolean z3, boolean z4);
}
| UTF-8 | Java | 478 | java | PersonActionBarItemConsumer.java | Java | [] | null | [] | package com.facebook.timeline.widget.actionbar;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
/* compiled from: f4v */
public interface PersonActionBarItemConsumer {
void m18804a(@PersonActionBarItems int i, @StringRes int i2, @DrawableRes int i3, int i4, boolean z, boolean z2);
void m18805a(@PersonActionBarItems int i, @StringRes int i2, @DrawableRes int i3, int i4, boolean z, boolean z2, boolean z3, boolean z4);
}
| 478 | 0.774059 | 0.730126 | 11 | 42.454544 | 45.473995 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.545455 | false | false | 9 |
3188d04263a46ea65ddf7e1344b1cc08facd3c61 | 15,333,033,313,589 | 6bfebb668337b49dd11b187ddd1ccb1fe65d7bf7 | /io/src/main/java/com/io/gastrIO/dao/UserDetailsDao.java | 30fb7181ee5d707913ec762cb1a9359927c1166c | [] | no_license | Broooda/gastrio | https://github.com/Broooda/gastrio | 9271e8901887fce0073f89d52799e7aafda05316 | 8801c2d33fda46bc3909a02d51062daf0e904633 | refs/heads/master | 2021-01-19T18:14:06.533000 | 2014-12-07T01:05:14 | 2014-12-07T01:05:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.io.gastrIO.dao;
import com.io.gastrIO.model.UserDetails;
public interface UserDetailsDao extends GenericDao<UserDetails,Integer> {
}
| UTF-8 | Java | 148 | java | UserDetailsDao.java | Java | [] | null | [] | package com.io.gastrIO.dao;
import com.io.gastrIO.model.UserDetails;
public interface UserDetailsDao extends GenericDao<UserDetails,Integer> {
}
| 148 | 0.810811 | 0.810811 | 7 | 20.142857 | 26.237534 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 9 |
0f94eeffdd0aa0b9adf7954bba2d73bf2651f0d0 | 31,104,153,219,626 | 36a324c4981c65447919eb0e81e0e62b62fd14bc | /src/main/java/com/github/whoisacat/inviter/controller/MainController.java | 5e7f8b368129d8d00a462df09aba08cae35b1c28 | [] | no_license | whoisacat/PissUpInviter | https://github.com/whoisacat/PissUpInviter | 144c2118d993b217dcce6fe9da97666d04639e16 | 360addaca5b7348a266a8153ec35c8666f3a97d5 | refs/heads/master | 2020-07-03T05:26:12.863000 | 2019-08-17T16:10:25 | 2019-08-17T16:10:25 | 201,799,212 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.whoisacat.inviter.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MainController {
private static int i = 0;
@Value("${spring.application.name}")
String appName;
@GetMapping("/")
public String homePage(Model model) {
i++;
model.addAttribute("appName", appName);
model.addAttribute("number", i);
return "home";
}
@GetMapping("/home")
public String homePage_(Model model) {
model.addAttribute("appName", appName);
return "home";
}
} | UTF-8 | Java | 731 | java | MainController.java | Java | [
{
"context": "package com.github.whoisacat.inviter.controller;\n\nimport org.springframework.b",
"end": 28,
"score": 0.9591320157051086,
"start": 19,
"tag": "USERNAME",
"value": "whoisacat"
}
] | null | [] | package com.github.whoisacat.inviter.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MainController {
private static int i = 0;
@Value("${spring.application.name}")
String appName;
@GetMapping("/")
public String homePage(Model model) {
i++;
model.addAttribute("appName", appName);
model.addAttribute("number", i);
return "home";
}
@GetMapping("/home")
public String homePage_(Model model) {
model.addAttribute("appName", appName);
return "home";
}
} | 731 | 0.686731 | 0.685363 | 27 | 26.111111 | 18.941105 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592593 | false | false | 9 |
32993ca9147e1d0ac6b0caa58081f3be3bca9a2a | 24,859,270,729,985 | 9a46b6fa44ed92a0993eaaa4357e2973fdae56b4 | /src/main/java/com/hro/core/cmanager/service/UserInfoService.java | 76462c63957d037b93559fcb1e9501a95a64c137 | [] | no_license | 361754100/cmanager | https://github.com/361754100/cmanager | 9c5ef6029e1d52bb269818d45b74d6aac36d9caf | 4a3d688701648a2d0e46e3ef89eabb4ca506ab93 | refs/heads/master | 2021-04-09T10:36:41.255000 | 2018-05-10T06:43:51 | 2018-05-10T06:43:51 | 125,460,310 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hro.core.cmanager.service;
import com.hro.core.cmanager.controller.response.UserInfoQueryPageResp;
import com.hro.core.cmanager.enums.StateCodeEnum;
import com.hro.core.cmanager.controller.request.UserInfoReq;
import com.hro.core.cmanager.controller.response.CommonResp;
import com.hro.core.cmanager.dao.UserInfoDao;
import com.hro.core.cmanager.dao.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
public class UserInfoService {
@Autowired
private UserInfoDao userInfoDao;
/**
* 添加用户信息
* @param req
* @return
*/
public CommonResp addInfo(UserInfoReq req) {
CommonResp resp = new CommonResp();
resp.setMsg("添加用户信息失败");
UserInfo userInfo = req.getUserInfo();
userInfo.setCreateTime(new Date());
userInfo.setUserId(UUID.randomUUID().toString());
int cnt = userInfoDao.addInfo(userInfo);
if(cnt > 0) {
resp.setCode(StateCodeEnum.SUCCESS.getValue());
resp.setMsg("添加用户信息成功");
}
return resp;
}
/**
* 删除用户信息
* @param req
* @return
*/
public CommonResp delInfo(UserInfoReq req) {
CommonResp resp = new CommonResp();
resp.setMsg("删除用户信息失败");
UserInfo userInfo = req.getUserInfo();
int cnt = userInfoDao.delInfoById(userInfo.getUserId());
if(cnt > 0) {
resp.setCode(StateCodeEnum.SUCCESS.getValue());
resp.setMsg("删除用户信息成功");
}
return resp;
}
/**
* 更新用户信息
* @param req
* @return
*/
public CommonResp updateInfo(UserInfoReq req) {
CommonResp resp = new CommonResp();
resp.setMsg("修改用户信息失败");
UserInfo userInfo = req.getUserInfo();
userInfo.setUpdateTime(new Date());
int cnt = userInfoDao.updateInfo(userInfo);
if(cnt > 0) {
resp.setCode(StateCodeEnum.SUCCESS.getValue());
resp.setMsg("修改用户信息成功");
}
return resp;
}
/**
* 分页查询
* @return
*/
public UserInfoQueryPageResp queryInfoPage(UserInfoReq req) {
UserInfoQueryPageResp resp = new UserInfoQueryPageResp();
int total = userInfoDao.getRecordTotal(null);
List<UserInfo> result = userInfoDao.queryPageRecord(req);
resp.setResult(result);
resp.setTotal(total);
resp.setCode(StateCodeEnum.SUCCESS.getValue());
resp.setPageNum(req.getPageNum());
resp.setPageSize(req.getPageSize());
return resp;
}
}
| UTF-8 | Java | 2,833 | java | UserInfoService.java | Java | [] | null | [] | package com.hro.core.cmanager.service;
import com.hro.core.cmanager.controller.response.UserInfoQueryPageResp;
import com.hro.core.cmanager.enums.StateCodeEnum;
import com.hro.core.cmanager.controller.request.UserInfoReq;
import com.hro.core.cmanager.controller.response.CommonResp;
import com.hro.core.cmanager.dao.UserInfoDao;
import com.hro.core.cmanager.dao.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
public class UserInfoService {
@Autowired
private UserInfoDao userInfoDao;
/**
* 添加用户信息
* @param req
* @return
*/
public CommonResp addInfo(UserInfoReq req) {
CommonResp resp = new CommonResp();
resp.setMsg("添加用户信息失败");
UserInfo userInfo = req.getUserInfo();
userInfo.setCreateTime(new Date());
userInfo.setUserId(UUID.randomUUID().toString());
int cnt = userInfoDao.addInfo(userInfo);
if(cnt > 0) {
resp.setCode(StateCodeEnum.SUCCESS.getValue());
resp.setMsg("添加用户信息成功");
}
return resp;
}
/**
* 删除用户信息
* @param req
* @return
*/
public CommonResp delInfo(UserInfoReq req) {
CommonResp resp = new CommonResp();
resp.setMsg("删除用户信息失败");
UserInfo userInfo = req.getUserInfo();
int cnt = userInfoDao.delInfoById(userInfo.getUserId());
if(cnt > 0) {
resp.setCode(StateCodeEnum.SUCCESS.getValue());
resp.setMsg("删除用户信息成功");
}
return resp;
}
/**
* 更新用户信息
* @param req
* @return
*/
public CommonResp updateInfo(UserInfoReq req) {
CommonResp resp = new CommonResp();
resp.setMsg("修改用户信息失败");
UserInfo userInfo = req.getUserInfo();
userInfo.setUpdateTime(new Date());
int cnt = userInfoDao.updateInfo(userInfo);
if(cnt > 0) {
resp.setCode(StateCodeEnum.SUCCESS.getValue());
resp.setMsg("修改用户信息成功");
}
return resp;
}
/**
* 分页查询
* @return
*/
public UserInfoQueryPageResp queryInfoPage(UserInfoReq req) {
UserInfoQueryPageResp resp = new UserInfoQueryPageResp();
int total = userInfoDao.getRecordTotal(null);
List<UserInfo> result = userInfoDao.queryPageRecord(req);
resp.setResult(result);
resp.setTotal(total);
resp.setCode(StateCodeEnum.SUCCESS.getValue());
resp.setPageNum(req.getPageNum());
resp.setPageSize(req.getPageSize());
return resp;
}
}
| 2,833 | 0.63238 | 0.631266 | 106 | 24.405661 | 21.620562 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.433962 | false | false | 9 |
e4b1ca98adaac08b1c8981eb03d30e6573b3d06e | 24,859,270,733,244 | 196c03e2985017ecb22a4576574aba0713cb8a75 | /src/main/java/com/haulmont/testtask/database/controllers/DoctorsController.java | b25e98a0165ba592cb59944f04cda473cd9c26cf | [] | no_license | sofronovsd/test-task-haulmont-sofronov | https://github.com/sofronovsd/test-task-haulmont-sofronov | 8df470234264765c25b9af227ff5c459a3569031 | 880b79bebd53085448162a6e24fe248236c48ec0 | refs/heads/master | 2021-09-14T08:58:15.128000 | 2018-05-10T20:41:42 | 2018-05-10T20:41:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.haulmont.testtask.database.controllers;
import com.haulmont.testtask.database.dao.DoctorsDAO;
import com.haulmont.testtask.database.entities.DoctorsEntity;
import com.haulmont.testtask.database.entities.DoctorsStatistic;
import java.util.List;
public class DoctorsController {
private static DoctorsDAO doctorsDAO;
public DoctorsController() {
doctorsDAO = new DoctorsDAO();
}
public void persist(DoctorsEntity entity) {
doctorsDAO.openCurrentSessionwithTransaction();
doctorsDAO.persist(entity);
doctorsDAO.closeCurrentSessionwithTransaction();
}
public void update(DoctorsEntity entity) {
doctorsDAO.openCurrentSessionwithTransaction();
doctorsDAO.update(entity);
doctorsDAO.closeCurrentSessionwithTransaction();
}
public DoctorsEntity findById(String id) {
doctorsDAO.openCurrentSession();
DoctorsEntity doctorsEntity = doctorsDAO.findById(id);
doctorsDAO.closeCurrentSession();
return doctorsEntity;
}
public void delete(DoctorsEntity doctorsEntity) {
doctorsDAO.openCurrentSessionwithTransaction();
doctorsDAO.delete(doctorsEntity);
doctorsDAO.closeCurrentSessionwithTransaction();
}
public List<DoctorsEntity> findAll() {
doctorsDAO.openCurrentSession();
List<DoctorsEntity> doctorsEntities = doctorsDAO.findAll();
doctorsDAO.closeCurrentSession();
return doctorsEntities;
}
public void deleteAll() {
doctorsDAO.openCurrentSessionwithTransaction();
doctorsDAO.deleteAll();
doctorsDAO.closeCurrentSessionwithTransaction();
}
public DoctorsDAO doctorsDAO() {
return doctorsDAO;
}
public List<DoctorsStatistic> getStatistic() {
doctorsDAO.openCurrentSession();
List<DoctorsStatistic> doctorsStatistics = doctorsDAO.getStatistic();
doctorsDAO.closeCurrentSession();
return doctorsStatistics;
}
}
| UTF-8 | Java | 2,007 | java | DoctorsController.java | Java | [] | null | [] | package com.haulmont.testtask.database.controllers;
import com.haulmont.testtask.database.dao.DoctorsDAO;
import com.haulmont.testtask.database.entities.DoctorsEntity;
import com.haulmont.testtask.database.entities.DoctorsStatistic;
import java.util.List;
public class DoctorsController {
private static DoctorsDAO doctorsDAO;
public DoctorsController() {
doctorsDAO = new DoctorsDAO();
}
public void persist(DoctorsEntity entity) {
doctorsDAO.openCurrentSessionwithTransaction();
doctorsDAO.persist(entity);
doctorsDAO.closeCurrentSessionwithTransaction();
}
public void update(DoctorsEntity entity) {
doctorsDAO.openCurrentSessionwithTransaction();
doctorsDAO.update(entity);
doctorsDAO.closeCurrentSessionwithTransaction();
}
public DoctorsEntity findById(String id) {
doctorsDAO.openCurrentSession();
DoctorsEntity doctorsEntity = doctorsDAO.findById(id);
doctorsDAO.closeCurrentSession();
return doctorsEntity;
}
public void delete(DoctorsEntity doctorsEntity) {
doctorsDAO.openCurrentSessionwithTransaction();
doctorsDAO.delete(doctorsEntity);
doctorsDAO.closeCurrentSessionwithTransaction();
}
public List<DoctorsEntity> findAll() {
doctorsDAO.openCurrentSession();
List<DoctorsEntity> doctorsEntities = doctorsDAO.findAll();
doctorsDAO.closeCurrentSession();
return doctorsEntities;
}
public void deleteAll() {
doctorsDAO.openCurrentSessionwithTransaction();
doctorsDAO.deleteAll();
doctorsDAO.closeCurrentSessionwithTransaction();
}
public DoctorsDAO doctorsDAO() {
return doctorsDAO;
}
public List<DoctorsStatistic> getStatistic() {
doctorsDAO.openCurrentSession();
List<DoctorsStatistic> doctorsStatistics = doctorsDAO.getStatistic();
doctorsDAO.closeCurrentSession();
return doctorsStatistics;
}
}
| 2,007 | 0.714001 | 0.714001 | 65 | 29.876923 | 22.897436 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.492308 | false | false | 9 |
64f5805e6f67cfbe236be6408117bbf86ab6012a | 6,648,609,380,960 | 447520f40e82a060368a0802a391697bc00be96f | /apks/malware/app98/source/net/sourceforge/zbar/android/ZBarScanner.java | bf20b2e303953e130bcd5714028859d0a30b94e5 | [
"Apache-2.0"
] | permissive | iantal/AndroidPermissions | https://github.com/iantal/AndroidPermissions | 7f3343a9c29d82dbcd4ecd98b3a50ddf8d179465 | d623b732734243590b5f004d167e542e2e2ae249 | refs/heads/master | 2023-07-19T01:29:26.689000 | 2019-09-30T19:01:42 | 2019-09-30T19:01:42 | 107,239,248 | 0 | 0 | Apache-2.0 | false | 2023-07-16T07:41:38 | 2017-10-17T08:22:57 | 2019-09-30T19:01:44 | 2023-07-16T07:41:38 | 1,616,319 | 0 | 0 | 1 | null | false | false | package net.sourceforge.zbar.android;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.google.zxing.client.android.Result;
import com.google.zxing.client.android.ResultHandler;
import com.google.zxing.client.android.ResultHandlerFactory;
import com.qbiki.modules.barcodescanner.BarcodeDescriptionFragment;
import com.qbiki.seattleclouds.App;
import com.qbiki.seattleclouds.FragmentInfo;
import com.qbiki.seattleclouds.SCActivity;
import com.qbiki.util.DialogUtil;
import com.qbiki.util.PlanarYUVLuminanceSource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
public class ZBarScanner
extends SCActivity
{
private static final String TAG = "ZBarScanner";
private static boolean nativeLibsLoaded = true;
private boolean QRCodeEnabled = true;
Camera.AutoFocusCallback autoFocusCB = new Camera.AutoFocusCallback()
{
public void onAutoFocus(boolean paramAnonymousBoolean, Camera paramAnonymousCamera)
{
ZBarScanner.this.autoFocusHandler.postDelayed(ZBarScanner.this.doAutoFocus, 1000L);
}
};
private Handler autoFocusHandler;
private boolean barcodeEnabled = true;
private boolean barcodeScanned = false;
private Runnable doAutoFocus = new Runnable()
{
public void run()
{
if (ZBarScanner.this.previewing) {
ZBarScanner.this.mCamera.autoFocus(ZBarScanner.this.autoFocusCB);
}
}
};
Button doneButton;
private boolean fastScan = false;
private Camera mCamera;
private CameraPreview mPreview;
private boolean needsBarcodeCrop = false;
Camera.PreviewCallback previewCb = new Camera.PreviewCallback()
{
public void onPreviewFrame(byte[] paramAnonymousArrayOfByte, Camera paramAnonymousCamera)
{
paramAnonymousCamera = paramAnonymousCamera.getParameters().getPreviewSize();
Object localObject1 = new Image(paramAnonymousCamera.width, paramAnonymousCamera.height, "Y800");
((Image)localObject1).setData(paramAnonymousArrayOfByte);
if (ZBarScanner.this.scanner.scanImage((Image)localObject1) != 0)
{
localObject1 = ZBarScanner.this.scanner.getResults().iterator();
for (;;)
{
if (((Iterator)localObject1).hasNext())
{
Object localObject2 = (Symbol)((Iterator)localObject1).next();
if ((!ZBarScanner.this.QRCodeEnabled) || (!ZBarScanner.this.barcodeEnabled))
{
int i = 0;
if (((Symbol)localObject2).getType() == 64) {
i = 1;
}
if (((ZBarScanner.this.barcodeEnabled) && (i != 0)) || ((ZBarScanner.this.QRCodeEnabled) && (i == 0))) {}
}
else
{
Object localObject3 = new Result(((Symbol)localObject2).getData());
localObject3 = ResultHandlerFactory.makeResultHandler(ZBarScanner.this, (Result)localObject3);
ZBarScanner.this.scanText.setText(((ResultHandler)localObject3).getDisplayTitle());
ZBarScanner.access$002(ZBarScanner.this, true);
ZBarScanner.access$302(ZBarScanner.this, new Intent());
ZBarScanner.this.resultIntent.putExtra("SCAN_RESULT", ((Symbol)localObject2).getData());
ZBarScanner.this.resultIntent.putExtra("SCAN_RESULT_FORMAT", "" + ((Symbol)localObject2).getType());
if (ZBarScanner.this.previewing)
{
ZBarScanner.access$202(ZBarScanner.this, false);
ZBarScanner.this.mCamera.setPreviewCallback(null);
ZBarScanner.this.mCamera.stopPreview();
}
if (ZBarScanner.this.needsBarcodeCrop) {
localObject3 = ((Symbol)localObject2).getBounds();
}
try
{
localObject3 = new PlanarYUVLuminanceSource(paramAnonymousArrayOfByte, paramAnonymousCamera.width, paramAnonymousCamera.height, localObject3[0], localObject3[1], localObject3[2], localObject3[3], false);
ZBarScanner.this.saveBarcodeImage(((PlanarYUVLuminanceSource)localObject3).renderCroppedGreyscaleBitmap());
ZBarScanner.this.doneButton.setEnabled(true);
ZBarScanner.this.scanButton.setEnabled(true);
if (ZBarScanner.this.fastScan)
{
ZBarScanner.this.releaseCamera();
localObject3 = new Bundle();
((Bundle)localObject3).putString("RAW_DATA", ((Symbol)localObject2).getData());
((Bundle)localObject3).putString("CROP_PATH", ZBarScanner.this.resultIntent.getExtras().getString("BARCODE_CROP"));
localObject2 = App.getPageIntent(new FragmentInfo(BarcodeDescriptionFragment.class.getName(), (Bundle)localObject3), ZBarScanner.this);
ZBarScanner.this.startActivityForResult((Intent)localObject2, 1000);
}
}
catch (Exception localException)
{
for (;;)
{
Log.e("ZBarCodeScanner", "Crop Exception", localException);
}
}
}
}
}
}
}
};
private boolean previewing = true;
private Intent resultIntent;
Button scanButton;
TextView scanText;
ImageScanner scanner;
static
{
try
{
System.loadLibrary("iconv");
}
catch (UnsatisfiedLinkError localUnsatisfiedLinkError1)
{
for (;;)
{
try
{
System.loadLibrary("zbarjni");
return;
}
catch (UnsatisfiedLinkError localUnsatisfiedLinkError2)
{
Log.w("ZBarScanner", "Could not load native library: zbarjni");
nativeLibsLoaded = false;
}
localUnsatisfiedLinkError1 = localUnsatisfiedLinkError1;
Log.w("ZBarScanner", "Could not load native library: iconv");
nativeLibsLoaded = false;
}
}
}
public ZBarScanner() {}
public static Camera getCameraInstance()
{
try
{
Camera localCamera = Camera.open();
return localCamera;
}
catch (Exception localException)
{
Log.e("ZBAR", "Exception", localException);
}
return null;
}
private void releaseCamera()
{
if (this.mCamera != null)
{
this.previewing = false;
this.mCamera.setPreviewCallback(null);
this.mCamera.release();
this.mCamera = null;
}
}
private void saveBarcodeImage(Bitmap paramBitmap)
{
String str = App.getAppProtectedStoragePath() + "/Barcodes";
new File(str).mkdirs();
Object localObject = new SimpleDateFormat("dd-MM-yyyy_HH-mm-ss").format(new Date());
localObject = (String)localObject + ".png";
str = str + "/" + (String)localObject;
try
{
localObject = new FileOutputStream(str);
paramBitmap.compress(Bitmap.CompressFormat.PNG, 90, (OutputStream)localObject);
this.resultIntent.putExtra("BARCODE_CROP", str);
return;
}
catch (Exception paramBitmap) {}
}
protected void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent)
{
if (paramInt1 == 1000) {
finish();
}
super.onActivityResult(paramInt1, paramInt2, paramIntent);
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(2130903240);
setResult(0);
if (!getPackageManager().hasSystemFeature("android.hardware.camera")) {
DialogUtil.showAlert(this, 2131362121, 2131362122, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
ZBarScanner.this.finish();
}
});
}
if (!nativeLibsLoaded)
{
DialogUtil.showAlert(this, 2131361915, 2131362186, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
ZBarScanner.this.finish();
}
});
return;
}
setRequestedOrientation(0);
paramBundle = getIntent().getExtras();
String str;
if (paramBundle != null)
{
this.needsBarcodeCrop = paramBundle.getBoolean("NEED_BARCODE_CROP");
str = paramBundle.getString("SCAN_MODE");
if (str != null)
{
if (!str.equalsIgnoreCase("PRODUCT_MODE")) {
break label332;
}
this.QRCodeEnabled = false;
this.barcodeEnabled = true;
}
}
for (;;)
{
this.fastScan = paramBundle.getBoolean("FAST_SCAN");
this.autoFocusHandler = new Handler();
this.mCamera = getCameraInstance();
this.scanner = new ImageScanner();
this.scanner.setConfig(0, 256, 3);
this.scanner.setConfig(0, 257, 3);
this.mPreview = new CameraPreview(this, this.mCamera, this.previewCb, this.autoFocusCB);
((FrameLayout)findViewById(2131100263)).addView(this.mPreview);
this.scanText = ((TextView)findViewById(2131100264));
this.scanButton = ((Button)findViewById(2131100265));
this.scanButton.setEnabled(false);
this.scanButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
if (ZBarScanner.this.barcodeScanned)
{
ZBarScanner.access$002(ZBarScanner.this, false);
ZBarScanner.this.scanText.setText(2131362119);
ZBarScanner.this.mCamera.setPreviewCallback(ZBarScanner.this.previewCb);
ZBarScanner.this.mCamera.startPreview();
ZBarScanner.access$202(ZBarScanner.this, true);
ZBarScanner.this.mCamera.autoFocus(ZBarScanner.this.autoFocusCB);
ZBarScanner.this.scanButton.setEnabled(false);
}
}
});
this.doneButton = ((Button)findViewById(2131099926));
if (this.fastScan) {
break;
}
this.doneButton.setEnabled(false);
this.doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
ZBarScanner.this.setResult(-1, ZBarScanner.this.resultIntent);
ZBarScanner.this.finish();
}
});
return;
label332:
if (str.equalsIgnoreCase("QR_CODE_MODE"))
{
this.QRCodeEnabled = true;
this.barcodeEnabled = false;
}
}
this.needsBarcodeCrop = true;
this.doneButton.setVisibility(8);
this.scanButton.setVisibility(8);
}
public void onPause()
{
super.onPause();
releaseCamera();
}
}
| UTF-8 | Java | 11,489 | java | ZBarScanner.java | Java | [] | null | [] | package net.sourceforge.zbar.android;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.google.zxing.client.android.Result;
import com.google.zxing.client.android.ResultHandler;
import com.google.zxing.client.android.ResultHandlerFactory;
import com.qbiki.modules.barcodescanner.BarcodeDescriptionFragment;
import com.qbiki.seattleclouds.App;
import com.qbiki.seattleclouds.FragmentInfo;
import com.qbiki.seattleclouds.SCActivity;
import com.qbiki.util.DialogUtil;
import com.qbiki.util.PlanarYUVLuminanceSource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
public class ZBarScanner
extends SCActivity
{
private static final String TAG = "ZBarScanner";
private static boolean nativeLibsLoaded = true;
private boolean QRCodeEnabled = true;
Camera.AutoFocusCallback autoFocusCB = new Camera.AutoFocusCallback()
{
public void onAutoFocus(boolean paramAnonymousBoolean, Camera paramAnonymousCamera)
{
ZBarScanner.this.autoFocusHandler.postDelayed(ZBarScanner.this.doAutoFocus, 1000L);
}
};
private Handler autoFocusHandler;
private boolean barcodeEnabled = true;
private boolean barcodeScanned = false;
private Runnable doAutoFocus = new Runnable()
{
public void run()
{
if (ZBarScanner.this.previewing) {
ZBarScanner.this.mCamera.autoFocus(ZBarScanner.this.autoFocusCB);
}
}
};
Button doneButton;
private boolean fastScan = false;
private Camera mCamera;
private CameraPreview mPreview;
private boolean needsBarcodeCrop = false;
Camera.PreviewCallback previewCb = new Camera.PreviewCallback()
{
public void onPreviewFrame(byte[] paramAnonymousArrayOfByte, Camera paramAnonymousCamera)
{
paramAnonymousCamera = paramAnonymousCamera.getParameters().getPreviewSize();
Object localObject1 = new Image(paramAnonymousCamera.width, paramAnonymousCamera.height, "Y800");
((Image)localObject1).setData(paramAnonymousArrayOfByte);
if (ZBarScanner.this.scanner.scanImage((Image)localObject1) != 0)
{
localObject1 = ZBarScanner.this.scanner.getResults().iterator();
for (;;)
{
if (((Iterator)localObject1).hasNext())
{
Object localObject2 = (Symbol)((Iterator)localObject1).next();
if ((!ZBarScanner.this.QRCodeEnabled) || (!ZBarScanner.this.barcodeEnabled))
{
int i = 0;
if (((Symbol)localObject2).getType() == 64) {
i = 1;
}
if (((ZBarScanner.this.barcodeEnabled) && (i != 0)) || ((ZBarScanner.this.QRCodeEnabled) && (i == 0))) {}
}
else
{
Object localObject3 = new Result(((Symbol)localObject2).getData());
localObject3 = ResultHandlerFactory.makeResultHandler(ZBarScanner.this, (Result)localObject3);
ZBarScanner.this.scanText.setText(((ResultHandler)localObject3).getDisplayTitle());
ZBarScanner.access$002(ZBarScanner.this, true);
ZBarScanner.access$302(ZBarScanner.this, new Intent());
ZBarScanner.this.resultIntent.putExtra("SCAN_RESULT", ((Symbol)localObject2).getData());
ZBarScanner.this.resultIntent.putExtra("SCAN_RESULT_FORMAT", "" + ((Symbol)localObject2).getType());
if (ZBarScanner.this.previewing)
{
ZBarScanner.access$202(ZBarScanner.this, false);
ZBarScanner.this.mCamera.setPreviewCallback(null);
ZBarScanner.this.mCamera.stopPreview();
}
if (ZBarScanner.this.needsBarcodeCrop) {
localObject3 = ((Symbol)localObject2).getBounds();
}
try
{
localObject3 = new PlanarYUVLuminanceSource(paramAnonymousArrayOfByte, paramAnonymousCamera.width, paramAnonymousCamera.height, localObject3[0], localObject3[1], localObject3[2], localObject3[3], false);
ZBarScanner.this.saveBarcodeImage(((PlanarYUVLuminanceSource)localObject3).renderCroppedGreyscaleBitmap());
ZBarScanner.this.doneButton.setEnabled(true);
ZBarScanner.this.scanButton.setEnabled(true);
if (ZBarScanner.this.fastScan)
{
ZBarScanner.this.releaseCamera();
localObject3 = new Bundle();
((Bundle)localObject3).putString("RAW_DATA", ((Symbol)localObject2).getData());
((Bundle)localObject3).putString("CROP_PATH", ZBarScanner.this.resultIntent.getExtras().getString("BARCODE_CROP"));
localObject2 = App.getPageIntent(new FragmentInfo(BarcodeDescriptionFragment.class.getName(), (Bundle)localObject3), ZBarScanner.this);
ZBarScanner.this.startActivityForResult((Intent)localObject2, 1000);
}
}
catch (Exception localException)
{
for (;;)
{
Log.e("ZBarCodeScanner", "Crop Exception", localException);
}
}
}
}
}
}
}
};
private boolean previewing = true;
private Intent resultIntent;
Button scanButton;
TextView scanText;
ImageScanner scanner;
static
{
try
{
System.loadLibrary("iconv");
}
catch (UnsatisfiedLinkError localUnsatisfiedLinkError1)
{
for (;;)
{
try
{
System.loadLibrary("zbarjni");
return;
}
catch (UnsatisfiedLinkError localUnsatisfiedLinkError2)
{
Log.w("ZBarScanner", "Could not load native library: zbarjni");
nativeLibsLoaded = false;
}
localUnsatisfiedLinkError1 = localUnsatisfiedLinkError1;
Log.w("ZBarScanner", "Could not load native library: iconv");
nativeLibsLoaded = false;
}
}
}
public ZBarScanner() {}
public static Camera getCameraInstance()
{
try
{
Camera localCamera = Camera.open();
return localCamera;
}
catch (Exception localException)
{
Log.e("ZBAR", "Exception", localException);
}
return null;
}
private void releaseCamera()
{
if (this.mCamera != null)
{
this.previewing = false;
this.mCamera.setPreviewCallback(null);
this.mCamera.release();
this.mCamera = null;
}
}
private void saveBarcodeImage(Bitmap paramBitmap)
{
String str = App.getAppProtectedStoragePath() + "/Barcodes";
new File(str).mkdirs();
Object localObject = new SimpleDateFormat("dd-MM-yyyy_HH-mm-ss").format(new Date());
localObject = (String)localObject + ".png";
str = str + "/" + (String)localObject;
try
{
localObject = new FileOutputStream(str);
paramBitmap.compress(Bitmap.CompressFormat.PNG, 90, (OutputStream)localObject);
this.resultIntent.putExtra("BARCODE_CROP", str);
return;
}
catch (Exception paramBitmap) {}
}
protected void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent)
{
if (paramInt1 == 1000) {
finish();
}
super.onActivityResult(paramInt1, paramInt2, paramIntent);
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(2130903240);
setResult(0);
if (!getPackageManager().hasSystemFeature("android.hardware.camera")) {
DialogUtil.showAlert(this, 2131362121, 2131362122, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
ZBarScanner.this.finish();
}
});
}
if (!nativeLibsLoaded)
{
DialogUtil.showAlert(this, 2131361915, 2131362186, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
ZBarScanner.this.finish();
}
});
return;
}
setRequestedOrientation(0);
paramBundle = getIntent().getExtras();
String str;
if (paramBundle != null)
{
this.needsBarcodeCrop = paramBundle.getBoolean("NEED_BARCODE_CROP");
str = paramBundle.getString("SCAN_MODE");
if (str != null)
{
if (!str.equalsIgnoreCase("PRODUCT_MODE")) {
break label332;
}
this.QRCodeEnabled = false;
this.barcodeEnabled = true;
}
}
for (;;)
{
this.fastScan = paramBundle.getBoolean("FAST_SCAN");
this.autoFocusHandler = new Handler();
this.mCamera = getCameraInstance();
this.scanner = new ImageScanner();
this.scanner.setConfig(0, 256, 3);
this.scanner.setConfig(0, 257, 3);
this.mPreview = new CameraPreview(this, this.mCamera, this.previewCb, this.autoFocusCB);
((FrameLayout)findViewById(2131100263)).addView(this.mPreview);
this.scanText = ((TextView)findViewById(2131100264));
this.scanButton = ((Button)findViewById(2131100265));
this.scanButton.setEnabled(false);
this.scanButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
if (ZBarScanner.this.barcodeScanned)
{
ZBarScanner.access$002(ZBarScanner.this, false);
ZBarScanner.this.scanText.setText(2131362119);
ZBarScanner.this.mCamera.setPreviewCallback(ZBarScanner.this.previewCb);
ZBarScanner.this.mCamera.startPreview();
ZBarScanner.access$202(ZBarScanner.this, true);
ZBarScanner.this.mCamera.autoFocus(ZBarScanner.this.autoFocusCB);
ZBarScanner.this.scanButton.setEnabled(false);
}
}
});
this.doneButton = ((Button)findViewById(2131099926));
if (this.fastScan) {
break;
}
this.doneButton.setEnabled(false);
this.doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
ZBarScanner.this.setResult(-1, ZBarScanner.this.resultIntent);
ZBarScanner.this.finish();
}
});
return;
label332:
if (str.equalsIgnoreCase("QR_CODE_MODE"))
{
this.QRCodeEnabled = true;
this.barcodeEnabled = false;
}
}
this.needsBarcodeCrop = true;
this.doneButton.setVisibility(8);
this.scanButton.setVisibility(8);
}
public void onPause()
{
super.onPause();
releaseCamera();
}
}
| 11,489 | 0.655322 | 0.637653 | 328 | 34.027439 | 30.122553 | 219 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.704268 | false | false | 9 |