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
unknown
revision_date
unknown
committer_date
unknown
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
unknown
gha_created_at
unknown
gha_updated_at
unknown
gha_pushed_at
unknown
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

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
0
Add dataset card