blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
09391112613596d774dce7412704063444fe8975
10,677,288,698,988
c9e81d2354edf213aa1ee14d8a2f2b5e834adc9d
/common/rabbitmq/src/test/java/arc/nim/common/rabbitmq/BasicRabbitmqTest.java
c176ac8186b4b4a8e8bd7763fc781fa08a43a059
[]
no_license
jauhararifin/nim
https://github.com/jauhararifin/nim
bc35fecd4788437ed8f5c657a70e83ec3d0a2408
1f83d483b2c785b42bea18d1d6e2d5b89fa1be1a
refs/heads/master
2017-12-04T00:10:28.143000
2017-09-10T09:05:10
2017-09-10T09:10:04
94,326,418
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package arc.nim.common.rabbitmq; import arc.nim.common.logging.Logger; import arc.nim.common.logging.LoggerService; import arc.nim.common.queuing.Queue; import arc.nim.common.queuing.QueueConfig; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.util.concurrent.Semaphore; /** * @since 7/18/2017. */ public class BasicRabbitmqTest { private static final Logger logger = LoggerService.getLogger(BasicRabbitmqTest.class); private RabbitmqConfig rabbitmqConfig; private RabbitmqService rabbitmqService; private QueueConfig queueConfig; private Queue<SimpleModel> queue; /** * Initialization of rabbitmq test. Maybe we dont use this test. */ @Before public void initConfig() { rabbitmqConfig = new RabbitmqConfig("localhost", 5672, "guest", "guest", 3L); rabbitmqService = new RabbitmqService(rabbitmqConfig); queueConfig = new QueueConfig("arc.nim.queue.test", true, false, false, SimpleModel.class, null, null); } @Test @Ignore("Its integration test and rabbitmq configuration need to sepcify in initConfig() method.") public void basicPublishTest() throws Exception { queue = rabbitmqService.declareQueue(queueConfig); SimpleModel model = new SimpleModel("val1", 2, true); Semaphore semaphore = new Semaphore(0); queue.addConsumer(object -> { logger.info("Message consumed {}", object); semaphore.release(); }); queue.publish(model); semaphore.acquire(); } }
UTF-8
Java
1,496
java
BasicRabbitmqTest.java
Java
[]
null
[]
package arc.nim.common.rabbitmq; import arc.nim.common.logging.Logger; import arc.nim.common.logging.LoggerService; import arc.nim.common.queuing.Queue; import arc.nim.common.queuing.QueueConfig; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.util.concurrent.Semaphore; /** * @since 7/18/2017. */ public class BasicRabbitmqTest { private static final Logger logger = LoggerService.getLogger(BasicRabbitmqTest.class); private RabbitmqConfig rabbitmqConfig; private RabbitmqService rabbitmqService; private QueueConfig queueConfig; private Queue<SimpleModel> queue; /** * Initialization of rabbitmq test. Maybe we dont use this test. */ @Before public void initConfig() { rabbitmqConfig = new RabbitmqConfig("localhost", 5672, "guest", "guest", 3L); rabbitmqService = new RabbitmqService(rabbitmqConfig); queueConfig = new QueueConfig("arc.nim.queue.test", true, false, false, SimpleModel.class, null, null); } @Test @Ignore("Its integration test and rabbitmq configuration need to sepcify in initConfig() method.") public void basicPublishTest() throws Exception { queue = rabbitmqService.declareQueue(queueConfig); SimpleModel model = new SimpleModel("val1", 2, true); Semaphore semaphore = new Semaphore(0); queue.addConsumer(object -> { logger.info("Message consumed {}", object); semaphore.release(); }); queue.publish(model); semaphore.acquire(); } }
1,496
0.729947
0.71992
51
28.333334
26.19285
100
false
false
0
0
0
0
0
0
0.745098
false
false
1
4c434bed389da6ca67507e1059ab414654ad094e
326,417,559,398
88c198c38b6ebc0b086c5dbbf67d4af9c291cbd0
/app/src/main/java/com/example/stefan/clientsmartrestaurant/sendviciVrste.java
0490c1a3653436147a5c3deb42a14761c561df26
[]
no_license
NeskovicStefan2402/SmartRestaurant
https://github.com/NeskovicStefan2402/SmartRestaurant
aba73016a997a6790edb6841e21bf42f31a782ca
2f380c19a7b7bad2969d9ada9af1eb40422a6060
refs/heads/master
2020-08-14T11:14:47.525000
2019-10-14T22:38:41
2019-10-14T22:38:41
215,157,303
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.stefan.clientsmartrestaurant; import android.content.Intent; import android.content.pm.ActivityInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; import java.util.LinkedList; public class sendviciVrste extends AppCompatActivity { public static String vrsta=""; public static boolean povratak=false; LinkedList<Integer> slike=new LinkedList<>(); LinkedList<String> nazivi=new LinkedList<>(); LinkedList<String> cene=new LinkedList<>(); ListView lView; AdapterArtikal lAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sendvici_vrste); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); ispisiSendvice(); lView = (ListView) findViewById(R.id.androidList); lAdapter = new AdapterArtikal(sendviciVrste.this, nazivi, cene, slike); lView.setAdapter(lAdapter); lView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if(povratak==true){ if(nazivi.get(i).contains("kulenom")){ sendvic.brSendvic=1; }else if(nazivi.get(i).contains("sunkom")){ sendvic.brSendvic=2; }else if(nazivi.get(i).contains("suvim vratom")){ sendvic.brSendvic=3; }else{ sendvic.brSendvic=4; } sendvic.cena=cene.get(i); sendvic.nazSendvic=nazivi.get(i); nazad(); }else{ Porudzbina p=new Porudzbina(); p.setNaziv(nazivi.get(i)); p.setCena(Double.parseDouble(cene.get(i))); p.setKolicina(1); Home.porudzbine.add(p); backSendvic(view); } } }); } public void clickHranaSendvic(View view) { Intent i =new Intent(this,hrana.class); finish(); startActivity(i); } public void clickPiceSendvic(View view) { Intent i =new Intent(this,picePodmeni.class); finish(); startActivity(i); } public void otvoriKorpuSendvic(View view) { Intent i =new Intent(this,korpa.class); finish(); startActivity(i); } public void backSendvic(View view) { Intent i =new Intent(this,Home.class); finish(); startActivity(i); } public void ispisiSendvice(){ ArrayList<Proizvod> proizvodi=meniHrana.hrana(); for (int i=0;i<proizvodi.size();i++){ if(proizvodi.get(i).getPodtip().equals("Sendvic")){ nazivi.add(proizvodi.get(i).getNaziv()); cene.add(String.valueOf(proizvodi.get(i).getCena())); if(proizvodi.get(i).getNaziv().contains("kulenom")){ slike.add(R.drawable.kulen); }else if(proizvodi.get(i).getNaziv().contains("sunkom")){ slike.add(R.drawable.sunka); }else if(proizvodi.get(i).getNaziv().contains("suvim vratom")){ slike.add(R.drawable.suvivrat); }else if(proizvodi.get(i).getNaziv().contains("pecenicom")){ slike.add(R.drawable.pecenica); }else{ slike.add(0);} } } } public void nazad(){ Intent i =new Intent(this,sendvic.class); finish(); startActivity(i); } }
UTF-8
Java
3,903
java
sendviciVrste.java
Java
[ { "context": "package com.example.stefan.clientsmartrestaurant;\n\nimport android.content.In", "end": 26, "score": 0.6812465786933899, "start": 20, "tag": "USERNAME", "value": "stefan" } ]
null
[]
package com.example.stefan.clientsmartrestaurant; import android.content.Intent; import android.content.pm.ActivityInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; import java.util.LinkedList; public class sendviciVrste extends AppCompatActivity { public static String vrsta=""; public static boolean povratak=false; LinkedList<Integer> slike=new LinkedList<>(); LinkedList<String> nazivi=new LinkedList<>(); LinkedList<String> cene=new LinkedList<>(); ListView lView; AdapterArtikal lAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sendvici_vrste); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); ispisiSendvice(); lView = (ListView) findViewById(R.id.androidList); lAdapter = new AdapterArtikal(sendviciVrste.this, nazivi, cene, slike); lView.setAdapter(lAdapter); lView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if(povratak==true){ if(nazivi.get(i).contains("kulenom")){ sendvic.brSendvic=1; }else if(nazivi.get(i).contains("sunkom")){ sendvic.brSendvic=2; }else if(nazivi.get(i).contains("suvim vratom")){ sendvic.brSendvic=3; }else{ sendvic.brSendvic=4; } sendvic.cena=cene.get(i); sendvic.nazSendvic=nazivi.get(i); nazad(); }else{ Porudzbina p=new Porudzbina(); p.setNaziv(nazivi.get(i)); p.setCena(Double.parseDouble(cene.get(i))); p.setKolicina(1); Home.porudzbine.add(p); backSendvic(view); } } }); } public void clickHranaSendvic(View view) { Intent i =new Intent(this,hrana.class); finish(); startActivity(i); } public void clickPiceSendvic(View view) { Intent i =new Intent(this,picePodmeni.class); finish(); startActivity(i); } public void otvoriKorpuSendvic(View view) { Intent i =new Intent(this,korpa.class); finish(); startActivity(i); } public void backSendvic(View view) { Intent i =new Intent(this,Home.class); finish(); startActivity(i); } public void ispisiSendvice(){ ArrayList<Proizvod> proizvodi=meniHrana.hrana(); for (int i=0;i<proizvodi.size();i++){ if(proizvodi.get(i).getPodtip().equals("Sendvic")){ nazivi.add(proizvodi.get(i).getNaziv()); cene.add(String.valueOf(proizvodi.get(i).getCena())); if(proizvodi.get(i).getNaziv().contains("kulenom")){ slike.add(R.drawable.kulen); }else if(proizvodi.get(i).getNaziv().contains("sunkom")){ slike.add(R.drawable.sunka); }else if(proizvodi.get(i).getNaziv().contains("suvim vratom")){ slike.add(R.drawable.suvivrat); }else if(proizvodi.get(i).getNaziv().contains("pecenicom")){ slike.add(R.drawable.pecenica); }else{ slike.add(0);} } } } public void nazad(){ Intent i =new Intent(this,sendvic.class); finish(); startActivity(i); } }
3,903
0.566744
0.564694
111
34.162163
22.325819
91
false
false
0
0
0
0
0
0
0.666667
false
false
1
599fa85bc48b70a775d7a42b120fcb0f7192e90f
19,292,993,111,730
ab6056a5319355caea8029647536f1d16d3fc067
/app/src/main/java/hr/ferit/mahmutaksakalli/scientistbiography/MainActivity.java
57fc2af1e94b9895da755adc9ae6ed7c5058419f
[]
no_license
mahmut-aksakalli/AndroidScientistListApp
https://github.com/mahmut-aksakalli/AndroidScientistListApp
318a3696e1213bbcb26d87f94f01e04b64ed3a0e
67f337353a9b9f989e1214842a171207fd252316
refs/heads/master
2020-03-09T06:44:13.631000
2018-04-08T14:11:46
2018-04-08T14:11:46
128,646,871
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hr.ferit.mahmutaksakalli.scientistbiography; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; import java.util.Random; public class MainActivity extends AppCompatActivity { protected Random r = new Random(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void showShannon(View view){ int quoteNumber = this.r.nextInt(4); String[] quotes = getResources().getStringArray(R.array.shannonQuotes); this.displayToastMessage(quotes[quoteNumber]); } public void showShockley(View view){ int quoteNumber = this.r.nextInt(2); String[] quotes = getResources().getStringArray(R.array.shockleyQuotes); this.displayToastMessage(quotes[quoteNumber]); } public void showGuido(View view){ int quoteNumber = this.r.nextInt(2); String[] quotes = getResources().getStringArray(R.array.guidoQuotes); this.displayToastMessage(quotes[quoteNumber]); } private void displayToastMessage(String Text) { Toast T = Toast.makeText(MainActivity.this, Text, Toast.LENGTH_LONG); T.show(); } }
UTF-8
Java
1,308
java
MainActivity.java
Java
[]
null
[]
package hr.ferit.mahmutaksakalli.scientistbiography; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; import java.util.Random; public class MainActivity extends AppCompatActivity { protected Random r = new Random(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void showShannon(View view){ int quoteNumber = this.r.nextInt(4); String[] quotes = getResources().getStringArray(R.array.shannonQuotes); this.displayToastMessage(quotes[quoteNumber]); } public void showShockley(View view){ int quoteNumber = this.r.nextInt(2); String[] quotes = getResources().getStringArray(R.array.shockleyQuotes); this.displayToastMessage(quotes[quoteNumber]); } public void showGuido(View view){ int quoteNumber = this.r.nextInt(2); String[] quotes = getResources().getStringArray(R.array.guidoQuotes); this.displayToastMessage(quotes[quoteNumber]); } private void displayToastMessage(String Text) { Toast T = Toast.makeText(MainActivity.this, Text, Toast.LENGTH_LONG); T.show(); } }
1,308
0.703364
0.700306
39
32.53846
25.065908
80
false
false
0
0
0
0
0
0
0.564103
false
false
1
dc25d548025fcc294208fd81e3d637ec6581b038
22,462,679,004,185
1f6f1488183ebb73ffb2d34e2f6b8a788388a56c
/guava/src/main/java/com/bluecatcode/common/functions/CheckedBlock.java
541d0417bd44c5ecae405bf1c584072fa3016a8a
[ "Apache-2.0" ]
permissive
pawelprazak/java-extended
https://github.com/pawelprazak/java-extended
962deb84eeadf78210c2787089bb27ea8070022e
0dc5af98c46bfa1baf215c7591684d06ccd10ff5
refs/heads/master
2023-04-25T20:54:25.874000
2021-04-14T12:34:17
2021-04-14T12:34:17
17,541,735
2
3
null
false
2015-04-20T11:21:24
2014-03-08T12:42:03
2015-04-20T11:12:49
2015-04-20T11:21:24
496
1
0
0
Java
null
null
package com.bluecatcode.common.functions; import javax.annotation.Nullable; /** * @param <T> the result type * @see Consumer * @see Effect * @see Function * @see com.google.common.base.Predicate * @see com.google.common.base.Supplier * @see java.util.concurrent.Callable */ public interface CheckedBlock<T, E extends Exception> { /** * Performs this operation returning value. * * @throws E if unable to compute */ @Nullable T execute() throws E; }
UTF-8
Java
492
java
CheckedBlock.java
Java
[]
null
[]
package com.bluecatcode.common.functions; import javax.annotation.Nullable; /** * @param <T> the result type * @see Consumer * @see Effect * @see Function * @see com.google.common.base.Predicate * @see com.google.common.base.Supplier * @see java.util.concurrent.Callable */ public interface CheckedBlock<T, E extends Exception> { /** * Performs this operation returning value. * * @throws E if unable to compute */ @Nullable T execute() throws E; }
492
0.674797
0.674797
23
20.391304
17.188822
55
false
false
0
0
0
0
0
0
0.173913
false
false
1
02718bc64f0c3674b9e1446b1034e1be71673c26
15,882,789,105,255
10b8a3820ff33142bb04da8ba660b05dd6d6a364
/src/main/java/com/vsystem/evento/controller/HomeController.java
0e8dc53ec9e5046c9fe4512af34d81856a9f4988
[]
no_license
helitonVieira/springJspH2CrudUsuario
https://github.com/helitonVieira/springJspH2CrudUsuario
f5e5fe4b27b56197f4e04daae1084a7c3e404433
edcdb510fc8e975b107a2d6d3d4df15ebf65bd3f
refs/heads/master
2023-02-16T16:09:48.889000
2021-01-03T15:25:28
2021-01-03T15:25:28
326,436,240
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vsystem.evento.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.vsystem.evento.model.Usuario; import com.vsystem.evento.repository.UserRespository; @Controller public class HomeController { @Autowired private UserRespository repo; @RequestMapping(value="/home") public String home() { return "usuario"; } @RequestMapping(value="/") @ResponseBody public String Empty() { return "hello home"; } @RequestMapping(value="/getData") public String getData(HttpServletRequest req) { String usuario = req.getParameter("usuario"); String senha = req.getParameter("senha"); HttpSession session = req.getSession(); session.setAttribute("usuario", usuario); session.setAttribute("senha", senha); return "home"; } @RequestMapping(value="/getLoginData") public ModelAndView getLoginData(@RequestParam("usuario") String usuario, @RequestParam("senha") String senha) { ModelAndView mv = new ModelAndView(); mv.addObject("usuario", usuario); mv.addObject("senha", senha); mv.setViewName("home"); return mv; } @RequestMapping(value="/getUserData") public ModelAndView getUserData(Usuario user) { ModelAndView mv = new ModelAndView(); mv.addObject("user", user); mv.setViewName("home"); repo.save(user); return mv; } }
UTF-8
Java
1,701
java
HomeController.java
Java
[]
null
[]
package com.vsystem.evento.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.vsystem.evento.model.Usuario; import com.vsystem.evento.repository.UserRespository; @Controller public class HomeController { @Autowired private UserRespository repo; @RequestMapping(value="/home") public String home() { return "usuario"; } @RequestMapping(value="/") @ResponseBody public String Empty() { return "hello home"; } @RequestMapping(value="/getData") public String getData(HttpServletRequest req) { String usuario = req.getParameter("usuario"); String senha = req.getParameter("senha"); HttpSession session = req.getSession(); session.setAttribute("usuario", usuario); session.setAttribute("senha", senha); return "home"; } @RequestMapping(value="/getLoginData") public ModelAndView getLoginData(@RequestParam("usuario") String usuario, @RequestParam("senha") String senha) { ModelAndView mv = new ModelAndView(); mv.addObject("usuario", usuario); mv.addObject("senha", senha); mv.setViewName("home"); return mv; } @RequestMapping(value="/getUserData") public ModelAndView getUserData(Usuario user) { ModelAndView mv = new ModelAndView(); mv.addObject("user", user); mv.setViewName("home"); repo.save(user); return mv; } }
1,701
0.75779
0.75779
63
26
22.374163
113
false
false
0
0
0
0
0
0
1.634921
false
false
1
0d7c5fc8c7d32b9670315482cdcc374e95e0b3ba
32,830,730,032,799
4659b8b0cc25249b0fe8a5cd9c772734fba4970b
/src/leetcode/算法/回溯/子集_78.java
8a023e63d445bfa0ca711b16b78fe87dc7f4a519
[]
no_license
lzhseu/leetcode-solution
https://github.com/lzhseu/leetcode-solution
5a5ad441f341392220c7b4522b76b91eac025c5b
0d1d11bcf90e4aee9b3dfde29a63144a000500cf
refs/heads/main
2023-03-11T05:40:32.395000
2021-02-20T13:15:40
2021-02-20T13:15:40
304,568,264
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetcode.算法.回溯; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; /** * @author lzh * @date 2020/11/5 10:22 */ public class 子集_78 { /** * 方法一:回溯 * 1ms 99.14% 38.8M 86.17% */ public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> resList = new ArrayList<>(); resList.add(new ArrayList<>()); if(nums == null || nums.length == 0) { return resList; } Deque<Integer> path = new ArrayDeque<>(); helper(resList, path, nums, 0); return resList; } private void helper(List<List<Integer>> resList, Deque<Integer> path, int[] nums, int index) { for(int i = index; i < nums.length; i++) { path.addLast(nums[i]); helper(resList, path, nums, i + 1); resList.add(new ArrayList<>(path)); path.removeLast(); } } /** * 方法二:位运算 * 1ms 38.7M */ public List<List<Integer>> subsets2(int[] nums) { // 方法二:位运算 // 000 001 010 ... 111 // 对于每种情况,判断某位是否为1,是则加入子集 int len; List<List<Integer>> resList = new ArrayList<>(); resList.add(new ArrayList<>()); if(nums == null || (len = nums.length) == 0) { return resList; } List<Integer> subList = new ArrayList<>(); for(int mask = 1; mask < (1 << len); mask++) { subList.clear(); for(int i = 0; i < len; i++) { if((mask & (1 << i)) != 0) { subList.add(nums[i]); } } resList.add(new ArrayList<>(subList)); } return resList; } }
UTF-8
Java
1,842
java
子集_78.java
Java
[ { "context": "util.Deque;\nimport java.util.List;\n\n/**\n * @author lzh\n * @date 2020/11/5 10:22\n */\npublic class 子集_78 {", "end": 148, "score": 0.9996473789215088, "start": 145, "tag": "USERNAME", "value": "lzh" } ]
null
[]
package leetcode.算法.回溯; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; /** * @author lzh * @date 2020/11/5 10:22 */ public class 子集_78 { /** * 方法一:回溯 * 1ms 99.14% 38.8M 86.17% */ public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> resList = new ArrayList<>(); resList.add(new ArrayList<>()); if(nums == null || nums.length == 0) { return resList; } Deque<Integer> path = new ArrayDeque<>(); helper(resList, path, nums, 0); return resList; } private void helper(List<List<Integer>> resList, Deque<Integer> path, int[] nums, int index) { for(int i = index; i < nums.length; i++) { path.addLast(nums[i]); helper(resList, path, nums, i + 1); resList.add(new ArrayList<>(path)); path.removeLast(); } } /** * 方法二:位运算 * 1ms 38.7M */ public List<List<Integer>> subsets2(int[] nums) { // 方法二:位运算 // 000 001 010 ... 111 // 对于每种情况,判断某位是否为1,是则加入子集 int len; List<List<Integer>> resList = new ArrayList<>(); resList.add(new ArrayList<>()); if(nums == null || (len = nums.length) == 0) { return resList; } List<Integer> subList = new ArrayList<>(); for(int mask = 1; mask < (1 << len); mask++) { subList.clear(); for(int i = 0; i < len; i++) { if((mask & (1 << i)) != 0) { subList.add(nums[i]); } } resList.add(new ArrayList<>(subList)); } return resList; } }
1,842
0.488558
0.45881
77
21.701298
20.505346
98
false
false
0
0
0
0
0
0
0.558442
false
false
1
f5cd4fa74bff8d3d22b65412c985aa45159a1cdd
32,796,370,310,147
e51914af4bb63b7bb4a4aea58d8e9565c1ee08fa
/data.structures/src/linkedList/Node.java
b9c2b238e594a77401b0e8ed893c9c278b6d4028
[]
no_license
karlsmarx/Codigos
https://github.com/karlsmarx/Codigos
f5cee658464b79bcb470b25d286a756f52be4b91
9737e47420828b97f334e46b4286636e18a1f402
refs/heads/master
2018-10-22T13:11:55.619000
2018-07-21T19:26:08
2018-07-21T19:26:08
140,084,012
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package linkedList; public class Node { private String element; private Node next; public Node(String s, Node n) { this.element = s; this.next = n; } public String getElement() { return this.element; } public Node getNext() { return this.next; } public void setElement(String e) { element = e; } public void setNext(Node n) { next = n; } }
UTF-8
Java
375
java
Node.java
Java
[]
null
[]
package linkedList; public class Node { private String element; private Node next; public Node(String s, Node n) { this.element = s; this.next = n; } public String getElement() { return this.element; } public Node getNext() { return this.next; } public void setElement(String e) { element = e; } public void setNext(Node n) { next = n; } }
375
0.645333
0.645333
27
12.888889
11.457921
35
false
false
0
0
0
0
0
0
1.444444
false
false
1
c398036102767948ba7e08100ba26d277daa791c
4,904,852,664,714
3342646b08a611adb6bc2ccae33a8b36220f8cde
/app/src/main/java/com/meiji/daily/AddActivity.java
55206984fb42c80dd57214c4739035568e6710a0
[ "Apache-2.0" ]
permissive
xiaozhu0922/Daily-1
https://github.com/xiaozhu0922/Daily-1
f96adaff06926bb1f001eb0956a18cc6b105e44e
3bcd4da1f2c1de209af043aee5b7aa48974a70e2
refs/heads/master
2021-01-20T00:34:53.451000
2017-04-23T12:06:54
2017-04-23T12:06:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.meiji.daily; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.text.TextUtils; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.meiji.daily.bean.ZhuanlanBean; import com.meiji.daily.database.dao.ZhuanlanDao; import com.meiji.daily.utils.Api; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.meiji.daily.mvp.zhuanlan.ZhuanlanModel.TYPE_USERADD; /** * Created by Meiji on 2016/12/1. */ public class AddActivity extends BaseActivity { private ZhuanlanDao zhuanlanDao = new ZhuanlanDao(); private boolean result = false; private MaterialDialog materialDialog; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); materialDialog = new MaterialDialog.Builder(this) .progress(true, 0) .content(R.string.md_loading) .cancelable(true) .build(); materialDialog.show(); Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); if (action.equals(Intent.ACTION_SEND) && type != null) { if (type.equals("text/plain")) { String shareText = intent.getStringExtra(Intent.EXTRA_TEXT); if (!TextUtils.isEmpty(shareText)) { handleSendText(shareText); } } } else { onFinish(getString(R.string.formal_incorrect)); } } private void handleSendText(String shareText) { final String regex = "^.*http.*://zhuanlan.zhihu.com/(.*)$"; final Matcher matcher = Pattern.compile(regex).matcher(shareText); if (matcher.find()) { final String slug = matcher.group(1).toLowerCase(); List<ZhuanlanBean> query = zhuanlanDao.query(TYPE_USERADD); for (ZhuanlanBean bean : query) { if (bean.getSlug().equals(slug)) { onFinish(getString(R.string.has_been_added)); return; } } Api api = RetrofitFactory.getRetrofit().create(Api.class); Call<ZhuanlanBean> call = api.getZhuanlanBean(slug); call.enqueue(new Callback<ZhuanlanBean>() { @Override public void onResponse(Call<ZhuanlanBean> call, Response<ZhuanlanBean> response) { try { ZhuanlanBean bean = response.body(); String type = String.valueOf(TYPE_USERADD); String avatarUrl = bean.getAvatar().getTemplate(); String avatarId = bean.getAvatar().getId(); String name = bean.getName(); String followersCount = String.valueOf(bean.getFollowersCount()); String postsCount = String.valueOf(bean.getPostsCount()); String intro = bean.getIntro(); String slug = bean.getSlug(); result = zhuanlanDao.add(type, avatarUrl, avatarId, name, followersCount, postsCount, intro, slug); } catch (NullPointerException e) { e.printStackTrace(); } if (result) { onFinish("保存成功"); } else { onFinish("保存失败"); } } @Override public void onFailure(Call<ZhuanlanBean> call, Throwable t) { onFinish("保存失败"); } }); } else { onFinish(getString(R.string.incorrect_link)); } } private void onFinish(String message) { materialDialog.dismiss(); Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { finish(); } }, 800); } }
UTF-8
Java
4,330
java
AddActivity.java
Java
[ { "context": "lan.ZhuanlanModel.TYPE_USERADD;\n\n/**\n * Created by Meiji on 2016/12/1.\n */\n\npublic class AddActivity exten", "end": 656, "score": 0.8554105162620544, "start": 651, "tag": "NAME", "value": "Meiji" } ]
null
[]
package com.meiji.daily; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.text.TextUtils; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.meiji.daily.bean.ZhuanlanBean; import com.meiji.daily.database.dao.ZhuanlanDao; import com.meiji.daily.utils.Api; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.meiji.daily.mvp.zhuanlan.ZhuanlanModel.TYPE_USERADD; /** * Created by Meiji on 2016/12/1. */ public class AddActivity extends BaseActivity { private ZhuanlanDao zhuanlanDao = new ZhuanlanDao(); private boolean result = false; private MaterialDialog materialDialog; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); materialDialog = new MaterialDialog.Builder(this) .progress(true, 0) .content(R.string.md_loading) .cancelable(true) .build(); materialDialog.show(); Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); if (action.equals(Intent.ACTION_SEND) && type != null) { if (type.equals("text/plain")) { String shareText = intent.getStringExtra(Intent.EXTRA_TEXT); if (!TextUtils.isEmpty(shareText)) { handleSendText(shareText); } } } else { onFinish(getString(R.string.formal_incorrect)); } } private void handleSendText(String shareText) { final String regex = "^.*http.*://zhuanlan.zhihu.com/(.*)$"; final Matcher matcher = Pattern.compile(regex).matcher(shareText); if (matcher.find()) { final String slug = matcher.group(1).toLowerCase(); List<ZhuanlanBean> query = zhuanlanDao.query(TYPE_USERADD); for (ZhuanlanBean bean : query) { if (bean.getSlug().equals(slug)) { onFinish(getString(R.string.has_been_added)); return; } } Api api = RetrofitFactory.getRetrofit().create(Api.class); Call<ZhuanlanBean> call = api.getZhuanlanBean(slug); call.enqueue(new Callback<ZhuanlanBean>() { @Override public void onResponse(Call<ZhuanlanBean> call, Response<ZhuanlanBean> response) { try { ZhuanlanBean bean = response.body(); String type = String.valueOf(TYPE_USERADD); String avatarUrl = bean.getAvatar().getTemplate(); String avatarId = bean.getAvatar().getId(); String name = bean.getName(); String followersCount = String.valueOf(bean.getFollowersCount()); String postsCount = String.valueOf(bean.getPostsCount()); String intro = bean.getIntro(); String slug = bean.getSlug(); result = zhuanlanDao.add(type, avatarUrl, avatarId, name, followersCount, postsCount, intro, slug); } catch (NullPointerException e) { e.printStackTrace(); } if (result) { onFinish("保存成功"); } else { onFinish("保存失败"); } } @Override public void onFailure(Call<ZhuanlanBean> call, Throwable t) { onFinish("保存失败"); } }); } else { onFinish(getString(R.string.incorrect_link)); } } private void onFinish(String message) { materialDialog.dismiss(); Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { finish(); } }, 800); } }
4,330
0.560381
0.556897
120
34.883335
24.981054
123
false
false
0
0
0
0
0
0
0.591667
false
false
1
d6bfb2d49823452845ed6832e7f0b898cdc26dc8
30,889,404,811,442
c5e497fa77d0c15e7c17193308d151c40c5215c3
/usersystem/src/main/java/team/benchem/usersystem/repository/GroupRepository.java
ee33f5cc4d4d25c5e37dedeecafd7ad96aeef56a
[ "Apache-2.0" ]
permissive
benchem/microserviceframework
https://github.com/benchem/microserviceframework
080bc8991cfd2c5926641478c6429151fc8062f0
2581aa3554641d34855d207775241fa35e5791d5
refs/heads/develop
2020-03-12T03:31:26.026000
2018-05-07T12:56:21
2018-05-07T12:56:21
130,426,128
1
0
Apache-2.0
false
2018-05-07T12:56:22
2018-04-21T00:35:13
2018-05-06T14:48:50
2018-05-07T12:56:22
78
1
0
0
Java
false
null
package team.benchem.usersystem.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import team.benchem.usersystem.entity.Group; import java.util.Optional; @Repository public interface GroupRepository extends JpaRepository<Group, String> { @Query("select g from Group g where (g.groupKey = :groupKey or g.groupName = :groupName) and g.rowId <> :groupId and g.ownerChannelId = :channelId") Group findByOwnerChannelNotExits( @Param("channelId") String channelId, @Param("groupId") String groupId, @Param("groupKey") String groupKey, @Param("groupName") String groupName ); }
UTF-8
Java
820
java
GroupRepository.java
Java
[]
null
[]
package team.benchem.usersystem.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import team.benchem.usersystem.entity.Group; import java.util.Optional; @Repository public interface GroupRepository extends JpaRepository<Group, String> { @Query("select g from Group g where (g.groupKey = :groupKey or g.groupName = :groupName) and g.rowId <> :groupId and g.ownerChannelId = :channelId") Group findByOwnerChannelNotExits( @Param("channelId") String channelId, @Param("groupId") String groupId, @Param("groupKey") String groupKey, @Param("groupName") String groupName ); }
820
0.743902
0.743902
22
36.272728
34.431992
152
false
false
0
0
0
0
0
0
0.545455
false
false
1
c488cbec7c4545d2bea32317df462fcef26e4c99
6,227,702,587,589
9e73e9215d607c78725c1db8f95a7668ae6c31db
/service/service_edu/src/main/java/com/atguigu/eduservice/service/impl/EduVideoServiceImpl.java
4cd15281f40f6549aefe23abc5efa6cc1c6ba4ac
[]
no_license
Hushunkang/guli_parent
https://github.com/Hushunkang/guli_parent
1a3cf6ff82cf48cc169c11165b0c2407810fb41f
4d9ebcb75d5f3f48bcca189c3522b8f34fa4e617
refs/heads/master
2022-07-12T01:29:57.643000
2020-07-20T12:16:16
2020-07-20T12:16:16
253,036,666
6
5
null
false
2022-06-29T18:03:21
2020-04-04T15:48:29
2022-03-25T01:36:55
2022-06-29T18:03:21
242,313
6
4
6
Java
false
false
package com.atguigu.eduservice.service.impl; import com.atguigu.eduservice.client.VodClient; import com.atguigu.eduservice.entity.EduVideo; import com.atguigu.eduservice.mapper.EduVideoMapper; import com.atguigu.eduservice.service.EduVideoService; import com.atguigu.util.R; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; /** * <p> * 课程小节表 服务实现类 * </p> * * @author hskBeginner * @since 2020-04-14 */ @Service @Slf4j public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService { @Autowired private VodClient vodClient; @Override public void removeVideoByCourseId(String courseId) { QueryWrapper<EduVideo> wrapper = new QueryWrapper<>(); wrapper.eq("course_id",courseId); baseMapper.delete(wrapper); } @Override public void deleteVideo(String videoId) {//videoId指的是课程小节ID不是云端视频ID,不要误解了 //根据课程小节ID找到其所对应的云端视频ID EduVideo eduVideo = baseMapper.selectById(videoId); String videoSourceId = eduVideo.getVideoSourceId(); //删除课程小节所对应的云端视频(注意:传统的方式可以给删除云端视频的业务代码写这,但是现在使用微服务调用的方式) //edu这个微服务中的方法调用vod这个微服务中的方法 //用户请求的还是这个edu微服务(独立的进程),但是它远程调用了vod微服务(也是独立的进程) // vodClient.removeVideo("云端视频ID"); if (!StringUtils.isEmpty(videoSourceId)) { R result = vodClient.removeVideo(videoSourceId);//底层原理大概是找对应服务,远程过程调用 if (result.getCode() == 20000) {//表示RPC成功,成功就不会触发hystrix熔断机制 log.info("RPC成功..."); } else { log.info("RPC失败...触发熔断机制..."); log.info("结果为:" + result); } }//说明,vodClient.removeVideo(videoSourceId);执行这个方法的时候如果出现异常了,当前的微服务默认感知不到,原因是因为“独立的进程”,一个进程仅仅只是远程调用了另一个进程 //根据课程小节ID删除课程小节记录 baseMapper.deleteById(videoId); } }
UTF-8
Java
2,671
java
EduVideoServiceImpl.java
Java
[ { "context": ";\n\n/**\n * <p>\n * 课程小节表 服务实现类\n * </p>\n *\n * @author hskBeginner\n * @since 2020-04-14\n */\n@Service\n@Slf4j\npublic c", "end": 661, "score": 0.9996125102043152, "start": 650, "tag": "USERNAME", "value": "hskBeginner" } ]
null
[]
package com.atguigu.eduservice.service.impl; import com.atguigu.eduservice.client.VodClient; import com.atguigu.eduservice.entity.EduVideo; import com.atguigu.eduservice.mapper.EduVideoMapper; import com.atguigu.eduservice.service.EduVideoService; import com.atguigu.util.R; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; /** * <p> * 课程小节表 服务实现类 * </p> * * @author hskBeginner * @since 2020-04-14 */ @Service @Slf4j public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService { @Autowired private VodClient vodClient; @Override public void removeVideoByCourseId(String courseId) { QueryWrapper<EduVideo> wrapper = new QueryWrapper<>(); wrapper.eq("course_id",courseId); baseMapper.delete(wrapper); } @Override public void deleteVideo(String videoId) {//videoId指的是课程小节ID不是云端视频ID,不要误解了 //根据课程小节ID找到其所对应的云端视频ID EduVideo eduVideo = baseMapper.selectById(videoId); String videoSourceId = eduVideo.getVideoSourceId(); //删除课程小节所对应的云端视频(注意:传统的方式可以给删除云端视频的业务代码写这,但是现在使用微服务调用的方式) //edu这个微服务中的方法调用vod这个微服务中的方法 //用户请求的还是这个edu微服务(独立的进程),但是它远程调用了vod微服务(也是独立的进程) // vodClient.removeVideo("云端视频ID"); if (!StringUtils.isEmpty(videoSourceId)) { R result = vodClient.removeVideo(videoSourceId);//底层原理大概是找对应服务,远程过程调用 if (result.getCode() == 20000) {//表示RPC成功,成功就不会触发hystrix熔断机制 log.info("RPC成功..."); } else { log.info("RPC失败...触发熔断机制..."); log.info("结果为:" + result); } }//说明,vodClient.removeVideo(videoSourceId);执行这个方法的时候如果出现异常了,当前的微服务默认感知不到,原因是因为“独立的进程”,一个进程仅仅只是远程调用了另一个进程 //根据课程小节ID删除课程小节记录 baseMapper.deleteById(videoId); } }
2,671
0.710589
0.702923
61
33.213116
27.621038
112
false
false
0
0
0
0
0
0
0.442623
false
false
1
2e9ff99f15ceed3ff9b5d3cf7c028a463478250e
13,056,700,585,410
dc5cc5fe5d0869e7c6111d5e961a9c9a38c450c2
/src/main/java/com/apispringmavenpostgre/resource/UserResource.java
94ea3aad1f612a3bd7eafff4333a65e62719bdde
[]
no_license
EloiBilek/ApiSpringMavenPostgre
https://github.com/EloiBilek/ApiSpringMavenPostgre
893b4fa3fc75b7d4b9f7c5ce9bbb06122e37afa0
1c46fd02f0cbf6298aa6c3081bcfbce86dc51331
refs/heads/master
2022-12-22T05:03:09.815000
2020-04-09T18:25:52
2020-04-09T18:25:52
53,084,254
0
1
null
false
2022-12-16T15:23:34
2016-03-03T21:12:19
2020-04-09T18:25:55
2022-12-16T15:23:30
41
0
0
7
Java
false
false
/** * */ package com.apispringmavenpostgre.resource; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.apispringmavenpostgre.model.entity.User; import com.apispringmavenpostgre.model.service.IUserService; /** * @author eloi.bilek * */ @RestController @RequestMapping("/v1/users") public class UserResource { @Autowired private IUserService userService; // @Autowired // private ApplicationEventPublisher eventPublisher; public UserResource() { super(); } @RequestMapping(method = RequestMethod.GET) public List<User> findAll() { return userService.findAll(); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public User findById(@PathVariable final Long id) { return userService.findById(id); } @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public User create(@RequestBody final User resource, final HttpServletResponse response) { return userService.create(resource); } @RequestMapping(method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) public User update(@RequestBody final User resource, final HttpServletResponse response) { return userService.update(resource); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) public void delete(@PathVariable final Long id, final HttpServletResponse response) { userService.deleteById(id); } }
UTF-8
Java
1,904
java
UserResource.java
Java
[ { "context": "ostgre.model.service.IUserService;\n\n/**\n * @author eloi.bilek\n *\n */\n@RestController\n@RequestMapping(\"/v1/users", "end": 748, "score": 0.9974880218505859, "start": 738, "tag": "USERNAME", "value": "eloi.bilek" } ]
null
[]
/** * */ package com.apispringmavenpostgre.resource; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.apispringmavenpostgre.model.entity.User; import com.apispringmavenpostgre.model.service.IUserService; /** * @author eloi.bilek * */ @RestController @RequestMapping("/v1/users") public class UserResource { @Autowired private IUserService userService; // @Autowired // private ApplicationEventPublisher eventPublisher; public UserResource() { super(); } @RequestMapping(method = RequestMethod.GET) public List<User> findAll() { return userService.findAll(); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public User findById(@PathVariable final Long id) { return userService.findById(id); } @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public User create(@RequestBody final User resource, final HttpServletResponse response) { return userService.create(resource); } @RequestMapping(method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) public User update(@RequestBody final User resource, final HttpServletResponse response) { return userService.update(resource); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) public void delete(@PathVariable final Long id, final HttpServletResponse response) { userService.deleteById(id); } }
1,904
0.790966
0.790441
68
27
26.193848
91
false
false
0
0
0
0
0
0
0.911765
false
false
1
fc32eedb27017541a622cbc21dbd686f63f19e6e
13,597,866,468,395
49c0ba93bd2b8fa0bbb02fc17a1859d35b0c391f
/src/java/game/nwn/readers/Header.java
bab4d804d7dd729160fd92c39998957b5d23fd3d
[ "Apache-2.0" ]
permissive
richcole/ClojureOpenGL
https://github.com/richcole/ClojureOpenGL
afd30c2bda9134b801f1d888c9f26c9e914973cd
b7a7ea42e8ae748e473170b11c674e967c3fe5a9
refs/heads/master
2021-01-22T05:05:22.219000
2015-06-08T02:01:35
2015-06-08T02:01:35
13,376,881
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package game.nwn.readers; public class Header { long zero; long dataOffset; long dataSize; private MdlModel model; public MdlModel getModel() { return model; } public void setModel(MdlModel model) { this.model = model; } }
UTF-8
Java
263
java
Header.java
Java
[]
null
[]
package game.nwn.readers; public class Header { long zero; long dataOffset; long dataSize; private MdlModel model; public MdlModel getModel() { return model; } public void setModel(MdlModel model) { this.model = model; } }
263
0.646388
0.646388
14
17.857143
11.568783
40
false
false
0
0
0
0
0
0
0.5
false
false
1
822b07f6ff868d89f8e859dce7fa3e852b485f0d
13,597,866,466,150
74a56b8e657762f8b03b9b7bcadf74caed868e4b
/src/ej10.java
5f5c35b32145d76643b42f40b6b4fee157decc30
[ "Apache-2.0" ]
permissive
mrtnmmn/JavaPracticeHacktoberfest
https://github.com/mrtnmmn/JavaPracticeHacktoberfest
6b3d3e3053936b64addbd17a01a83be96916c2ec
9c5d93a22391696a59e682bc4d60f43a484b9b05
refs/heads/master
2023-08-23T14:01:44.428000
2021-10-05T12:16:31
2021-10-05T12:16:31
413,803,069
0
0
Apache-2.0
true
2021-10-05T12:11:48
2021-10-05T12:11:47
2021-10-05T12:08:42
2021-10-05T12:10:59
7,079
0
0
0
null
false
false
import java.util.Scanner; public class ej10 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Introduce el número de casas"); System.out.println(calculo(sc.nextInt())); sc.close(); } public static int ladoizquierdo(int n) { n--; int ladoizquierdo = 0; for (; n > 0; n--) { ladoizquierdo = ladoizquierdo + n; } return ladoizquierdo; } public static int ladoderecho(int n, int casastotales) { n++; int ladoderecho = 0; for (; n <= casastotales; n++) { ladoderecho = ladoderecho + n; } return ladoderecho; } public static int calculo(int casastotales) { for (int i = 0; i <= casastotales; i++) { if (ladoizquierdo(i) == ladoderecho(i, casastotales)) { return i; } else { } } return -1; } }
ISO-8859-1
Java
995
java
ej10.java
Java
[]
null
[]
import java.util.Scanner; public class ej10 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Introduce el número de casas"); System.out.println(calculo(sc.nextInt())); sc.close(); } public static int ladoizquierdo(int n) { n--; int ladoizquierdo = 0; for (; n > 0; n--) { ladoizquierdo = ladoizquierdo + n; } return ladoizquierdo; } public static int ladoderecho(int n, int casastotales) { n++; int ladoderecho = 0; for (; n <= casastotales; n++) { ladoderecho = ladoderecho + n; } return ladoderecho; } public static int calculo(int casastotales) { for (int i = 0; i <= casastotales; i++) { if (ladoizquierdo(i) == ladoderecho(i, casastotales)) { return i; } else { } } return -1; } }
995
0.512072
0.50503
48
19.708334
19.878756
67
false
false
0
0
0
0
0
0
0.479167
false
false
1
3967a0135c2e780fba585ef3472ece0067a5605c
15,839,839,393,511
b8abcb055c899387ab2751a284719da710c57611
/msrc/core/com/collabrr/adk/impl/consignment/CollabrrConsignmentManager.java
dd53a0374e4354b5baa30c2ad94607342c1cb484
[]
no_license
ganeshdevp/PW
https://github.com/ganeshdevp/PW
bf92d2434e15eb1e6596c9cdf1154569e0462801
d7065b36d095e7ca9d2679aa9a96db3dc9b8260f
refs/heads/master
2021-01-01T06:56:02.239000
2017-07-18T03:44:46
2017-07-18T03:44:46
97,549,729
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.collabrr.adk.impl.consignment; import com.collabrr.adk.api.consignment.ICollabrrConsignmentManager; import com.collabrr.adk.spi.exception.CollabrrConsignmentManagerException; import com.collabrr.sdk.api.consignment.CollabrrConsignment; import com.vg.pw.container.cache.objects.UserContext; import com.vg.pw.exceptions.DocExException; import com.vg.pw.hbase.store.entity.doctemplate.DocTemplateUtil; import com.vg.pw.logger.DocexLogger; import com.vg.pw.messages.DocExMessagesPW; import com.vg.pw.service.SessionManager; import com.vg.pw.store.HbEntityList; import com.vg.pw.store.StoreManager; import com.vg.pw.store.entity.consignment.ConsignmentPOJO; import com.vg.pw.store.pojo.exception.CollabrrPOJONotFoundException; import com.vg.pw.store.pojo.exception.CollabrrPOJOReadException; public class CollabrrConsignmentManager implements ICollabrrConsignmentManager { private static final DocexLogger LOGGER = new DocexLogger(CollabrrConsignmentManager.class); @Override public CollabrrConsignment getCollabrrConsignment(String consignmentId,boolean supressEvent) throws CollabrrConsignmentManagerException { LOGGER.logInfo("Entering getCollabrrConsignment ..."); try { CollabrrConsignment collabrrConsignment = null; if(consignmentId != null && !consignmentId.trim().equals("")) { ConsignmentPOJO consignmentPOJO = new ConsignmentPOJO(); consignmentPOJO.setRowKey(consignmentId); consignmentPOJO = (ConsignmentPOJO) consignmentPOJO.getCollabrrPOJObject(); collabrrConsignment = CollabrrConsignmentBuilder.buildCollabrrConsignment(consignmentPOJO); } else { throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getErrorMessageCode()); } return collabrrConsignment; } catch(CollabrrConsignmentBuilderException e) { LOGGER.logError("An error occured while trying to build the collabrr consignment instance."); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_GET_FAILED.getMessage(), DocExMessagesPW.API_CONSIGNMENT_GET_FAILED.getErrorMessageCode()); } catch(CollabrrPOJOReadException e) { LOGGER.logError("An error occured while trying to frame the consignment pojo."); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getErrorMessageCode()); } catch (CollabrrPOJONotFoundException e) { LOGGER.logError("An error occured while tyring to fetch the consignment pojo"); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getErrorMessageCode()); } finally { LOGGER.logInfo("Leaving getCollabrrConsignment ..."); } } public void updateConsignmentStatus(CollabrrConsignment collabrrConsignment,String statusCode,String status) throws CollabrrConsignmentManagerException { LOGGER.logInfo("Entering updateConsignmentStatus ..."); try { if(collabrrConsignment == null || collabrrConsignment.getConsignmentId()== null || collabrrConsignment.getConsignmentId().trim().equals("")){ throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getErrorMessageCode()); } if(statusCode == null || statusCode.trim().equals("")){ throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getErrorMessageCode()); } UserContext userContext = SessionManager.getUserContext(); String history = new StringBuilder(status).append(":").append(statusCode).append(":").append(userContext.getUid()).append(":").append(userContext.getUserName()).append(":").append(userContext.getAccId()).append(":").append(userContext.getAccName()).append(":").append(System.currentTimeMillis()).toString(); ConsignmentPOJO consignmentPOJO = new ConsignmentPOJO(); consignmentPOJO.setRowKey(collabrrConsignment.getConsignmentId()); consignmentPOJO.setLstc(statusCode); consignmentPOJO.setLsts(status); consignmentPOJO.setLsti(history); consignmentPOJO.update(); } catch(DocExException e) { LOGGER.logError("An error occured while trying to update the consignment status"); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_FAILED.getMessage(), DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_FAILED.getErrorMessageCode()); } finally { LOGGER.logInfo("Leaving updateConsignmentStatus ..."); } } @Override public void updateConsignmentStatus(String consignmentId, String statusCode) throws CollabrrConsignmentManagerException { LOGGER.logInfo("Entering updateConsignmentStatus ..."); try { if(consignmentId == null || consignmentId.trim().equals("")){ throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getErrorMessageCode()); } if(statusCode == null || statusCode.trim().equals("")){ throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_CODE_EMPTY.getMessage(), DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_CODE_EMPTY.getErrorMessageCode()); } ConsignmentPOJO consignmentPOJO = new ConsignmentPOJO(); consignmentPOJO.setRowKey(consignmentId); consignmentPOJO = (ConsignmentPOJO) consignmentPOJO.getCollabrrPOJObject(); UserContext context = SessionManager.getUserContext(); String completeTid = StoreManager.getInstance().getEntityFactory().getHbEntity(HbEntityList.Template.name()).fetchAccountBasedRowkeyForTheCorrespondingEntity(context, consignmentPOJO.getTid(), consignmentPOJO.getSaid()); String status = DocTemplateUtil.getStatusForStatusCode(context, completeTid, statusCode, HbEntityList.Consignment.name()); if(status == null){ throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_CODE_INVALID.getMessage(), DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_CODE_INVALID.getErrorMessageCode()); } String history = new StringBuilder(status).append(":").append(statusCode).append(":").append(context.getUid()).append(":").append(context.getUserName()).append(":").append(context.getAccId()).append(":").append(context.getAccName()).append(":").append(System.currentTimeMillis()).toString(); consignmentPOJO.setLstc(statusCode); consignmentPOJO.setLsts(status); consignmentPOJO.setLsti(history); consignmentPOJO.update(); } catch(DocExException e) { LOGGER.logError("An error occured while trying to update the consignment status"); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_FAILED.getMessage(), DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_FAILED.getErrorMessageCode()); } catch (CollabrrPOJOReadException e) { LOGGER.logError("An error occured while trying to read the consignment"); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getErrorMessageCode()); } catch (CollabrrPOJONotFoundException e) { LOGGER.logError("An error occured while trying to read the consignment"); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getErrorMessageCode()); } finally { LOGGER.logInfo("Leaving updateConsignmentStatus ..."); } } }
UTF-8
Java
7,645
java
CollabrrConsignmentManager.java
Java
[ { "context": "w ConsignmentPOJO();\n\t\t\tconsignmentPOJO.setRowKey(collabrrConsignment.getConsignmentId());\n\t\t\tconsignmentPOJO.setLstc(statusCode);\n\t\t\tco", "end": 4107, "score": 0.8003678917884827, "start": 4071, "tag": "KEY", "value": "collabrrConsignment.getConsignmentId" } ]
null
[]
package com.collabrr.adk.impl.consignment; import com.collabrr.adk.api.consignment.ICollabrrConsignmentManager; import com.collabrr.adk.spi.exception.CollabrrConsignmentManagerException; import com.collabrr.sdk.api.consignment.CollabrrConsignment; import com.vg.pw.container.cache.objects.UserContext; import com.vg.pw.exceptions.DocExException; import com.vg.pw.hbase.store.entity.doctemplate.DocTemplateUtil; import com.vg.pw.logger.DocexLogger; import com.vg.pw.messages.DocExMessagesPW; import com.vg.pw.service.SessionManager; import com.vg.pw.store.HbEntityList; import com.vg.pw.store.StoreManager; import com.vg.pw.store.entity.consignment.ConsignmentPOJO; import com.vg.pw.store.pojo.exception.CollabrrPOJONotFoundException; import com.vg.pw.store.pojo.exception.CollabrrPOJOReadException; public class CollabrrConsignmentManager implements ICollabrrConsignmentManager { private static final DocexLogger LOGGER = new DocexLogger(CollabrrConsignmentManager.class); @Override public CollabrrConsignment getCollabrrConsignment(String consignmentId,boolean supressEvent) throws CollabrrConsignmentManagerException { LOGGER.logInfo("Entering getCollabrrConsignment ..."); try { CollabrrConsignment collabrrConsignment = null; if(consignmentId != null && !consignmentId.trim().equals("")) { ConsignmentPOJO consignmentPOJO = new ConsignmentPOJO(); consignmentPOJO.setRowKey(consignmentId); consignmentPOJO = (ConsignmentPOJO) consignmentPOJO.getCollabrrPOJObject(); collabrrConsignment = CollabrrConsignmentBuilder.buildCollabrrConsignment(consignmentPOJO); } else { throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getErrorMessageCode()); } return collabrrConsignment; } catch(CollabrrConsignmentBuilderException e) { LOGGER.logError("An error occured while trying to build the collabrr consignment instance."); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_GET_FAILED.getMessage(), DocExMessagesPW.API_CONSIGNMENT_GET_FAILED.getErrorMessageCode()); } catch(CollabrrPOJOReadException e) { LOGGER.logError("An error occured while trying to frame the consignment pojo."); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getErrorMessageCode()); } catch (CollabrrPOJONotFoundException e) { LOGGER.logError("An error occured while tyring to fetch the consignment pojo"); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getErrorMessageCode()); } finally { LOGGER.logInfo("Leaving getCollabrrConsignment ..."); } } public void updateConsignmentStatus(CollabrrConsignment collabrrConsignment,String statusCode,String status) throws CollabrrConsignmentManagerException { LOGGER.logInfo("Entering updateConsignmentStatus ..."); try { if(collabrrConsignment == null || collabrrConsignment.getConsignmentId()== null || collabrrConsignment.getConsignmentId().trim().equals("")){ throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getErrorMessageCode()); } if(statusCode == null || statusCode.trim().equals("")){ throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getErrorMessageCode()); } UserContext userContext = SessionManager.getUserContext(); String history = new StringBuilder(status).append(":").append(statusCode).append(":").append(userContext.getUid()).append(":").append(userContext.getUserName()).append(":").append(userContext.getAccId()).append(":").append(userContext.getAccName()).append(":").append(System.currentTimeMillis()).toString(); ConsignmentPOJO consignmentPOJO = new ConsignmentPOJO(); consignmentPOJO.setRowKey(collabrrConsignment.getConsignmentId()); consignmentPOJO.setLstc(statusCode); consignmentPOJO.setLsts(status); consignmentPOJO.setLsti(history); consignmentPOJO.update(); } catch(DocExException e) { LOGGER.logError("An error occured while trying to update the consignment status"); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_FAILED.getMessage(), DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_FAILED.getErrorMessageCode()); } finally { LOGGER.logInfo("Leaving updateConsignmentStatus ..."); } } @Override public void updateConsignmentStatus(String consignmentId, String statusCode) throws CollabrrConsignmentManagerException { LOGGER.logInfo("Entering updateConsignmentStatus ..."); try { if(consignmentId == null || consignmentId.trim().equals("")){ throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_EMPTY.getErrorMessageCode()); } if(statusCode == null || statusCode.trim().equals("")){ throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_CODE_EMPTY.getMessage(), DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_CODE_EMPTY.getErrorMessageCode()); } ConsignmentPOJO consignmentPOJO = new ConsignmentPOJO(); consignmentPOJO.setRowKey(consignmentId); consignmentPOJO = (ConsignmentPOJO) consignmentPOJO.getCollabrrPOJObject(); UserContext context = SessionManager.getUserContext(); String completeTid = StoreManager.getInstance().getEntityFactory().getHbEntity(HbEntityList.Template.name()).fetchAccountBasedRowkeyForTheCorrespondingEntity(context, consignmentPOJO.getTid(), consignmentPOJO.getSaid()); String status = DocTemplateUtil.getStatusForStatusCode(context, completeTid, statusCode, HbEntityList.Consignment.name()); if(status == null){ throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_CODE_INVALID.getMessage(), DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_CODE_INVALID.getErrorMessageCode()); } String history = new StringBuilder(status).append(":").append(statusCode).append(":").append(context.getUid()).append(":").append(context.getUserName()).append(":").append(context.getAccId()).append(":").append(context.getAccName()).append(":").append(System.currentTimeMillis()).toString(); consignmentPOJO.setLstc(statusCode); consignmentPOJO.setLsts(status); consignmentPOJO.setLsti(history); consignmentPOJO.update(); } catch(DocExException e) { LOGGER.logError("An error occured while trying to update the consignment status"); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_FAILED.getMessage(), DocExMessagesPW.API_UPDATE_CONSIGNMENT_STATUS_FAILED.getErrorMessageCode()); } catch (CollabrrPOJOReadException e) { LOGGER.logError("An error occured while trying to read the consignment"); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getErrorMessageCode()); } catch (CollabrrPOJONotFoundException e) { LOGGER.logError("An error occured while trying to read the consignment"); throw new CollabrrConsignmentManagerException(DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getMessage(), DocExMessagesPW.API_CONSIGNMENT_ID_INVALID.getErrorMessageCode()); } finally { LOGGER.logInfo("Leaving updateConsignmentStatus ..."); } } }
7,645
0.793329
0.793329
135
55.629631
63.399586
310
false
false
0
0
0
0
0
0
2.985185
false
false
1
4ee9706ae60d6bf4bae26260efbc559bd51ab4c9
20,882,130,999,278
202877fbdc4451f4cb4340af8d8711bb2b0d7dd4
/src/hu/eggproject/etelkiszallito/szamlazo/client/mvp/views/afanemek/AfanemekViewFactory.java
1a225855d072d90ac6a530cfb7a953378578f14a
[]
no_license
eggp/piazzaszamlazo
https://github.com/eggp/piazzaszamlazo
608bc52b272cc2601d856667206bc6284c928159
694e8384d5b5b77e04edba8f0236f91823b5269e
refs/heads/master
2015-07-23T00:47:34
2014-05-18T17:08:41
2014-05-18T17:08:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hu.eggproject.etelkiszallito.szamlazo.client.mvp.views.afanemek; import hu.eggproject.etelkiszallito.szamlazo.client.mvp.views.afanemek.lista.AfanemekGridView; import hu.eggproject.etelkiszallito.szamlazo.client.mvp.views.afanemek.uj.AfanemekUjOrModositasView; public class AfanemekViewFactory { private static AfanemekGridView gridView; private static AfanemekUjOrModositasView ujView; // private static AfanemekViewFactory INSTANCE; private AfanemekViewFactory() { } public static AfanemekGridView getGridView() { if (gridView == null) { gridView = new AfanemekGridView(); } return gridView; } public static AfanemekUjOrModositasView getUjOrModositasView() { // if (ujView == null) { // ujView = new AfanemekUjOrModositasView(); // } // return ujView; return new AfanemekUjOrModositasView(); } }
UTF-8
Java
879
java
AfanemekViewFactory.java
Java
[]
null
[]
package hu.eggproject.etelkiszallito.szamlazo.client.mvp.views.afanemek; import hu.eggproject.etelkiszallito.szamlazo.client.mvp.views.afanemek.lista.AfanemekGridView; import hu.eggproject.etelkiszallito.szamlazo.client.mvp.views.afanemek.uj.AfanemekUjOrModositasView; public class AfanemekViewFactory { private static AfanemekGridView gridView; private static AfanemekUjOrModositasView ujView; // private static AfanemekViewFactory INSTANCE; private AfanemekViewFactory() { } public static AfanemekGridView getGridView() { if (gridView == null) { gridView = new AfanemekGridView(); } return gridView; } public static AfanemekUjOrModositasView getUjOrModositasView() { // if (ujView == null) { // ujView = new AfanemekUjOrModositasView(); // } // return ujView; return new AfanemekUjOrModositasView(); } }
879
0.745165
0.745165
30
27.299999
28.58222
100
false
false
0
0
0
0
0
0
1.833333
false
false
1
5b8a3a7bd50310d4424810e3607c5a7420fb96ea
25,907,242,735,930
a65d1d398e29f5f4e8c9fa7cfd9efe7e5e97aad3
/MavenDependencies/src/test/java/com/qa/tests/Entitlement.java
323f8cadbb19708667751b06710ff6365ae8489a
[]
no_license
Cyxteraautomationtest/Fabric-managerAPItests
https://github.com/Cyxteraautomationtest/Fabric-managerAPItests
9f04568889a043fa4dc5db4015bdc2ef22da5603
30e2a57112466725b219004c48473299302129c5
refs/heads/master
2018-10-30T10:45:53.133000
2018-09-13T20:57:16
2018-09-13T20:57:16
144,606,789
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qa.tests; import java.util.List; public class Entitlement { public EntitlementsCustomer customer; public EntitlementsFabric fabric; public EntitlementsLocation location; public EntitlementsProductService productService; public Integer id; public String name; public Boolean enabled; public List<Entitlement> products; }
UTF-8
Java
351
java
Entitlement.java
Java
[]
null
[]
package com.qa.tests; import java.util.List; public class Entitlement { public EntitlementsCustomer customer; public EntitlementsFabric fabric; public EntitlementsLocation location; public EntitlementsProductService productService; public Integer id; public String name; public Boolean enabled; public List<Entitlement> products; }
351
0.80057
0.80057
17
19.647058
15.642857
50
false
false
0
0
0
0
0
0
1.176471
false
false
1
7a5601f2fb436f2045071b644a308310732c3e16
5,927,054,880,183
e7ee51e5129298429bd5f9f96b3cc9a07cfb68de
/scrapper-core-repository-jpa/src/main/java/org/tttamics/scrapper/core/repository/jpa/mappers/JpaCompetitionToCompetitionMapper.java
7b9b553f4a1fdaf079b2a845a63ae39a7d73e28c
[]
no_license
albertsanso/amics-scrapper
https://github.com/albertsanso/amics-scrapper
f549c32b8e8e1deff1c5c9f4206f4efda71e6566
e19c2ab7f180bb3210ce211882bca8ef38102bf1
refs/heads/master
2022-12-23T04:10:06.952000
2020-01-12T17:41:12
2020-01-12T17:41:12
229,612,754
0
0
null
false
2022-12-16T05:10:41
2019-12-22T18:32:42
2020-01-12T17:41:21
2022-12-16T05:10:38
147
0
0
5
Java
false
false
package org.tttamics.scrapper.core.repository.jpa.mappers; import org.tttamics.scrapper.core.domain.model.competition.Competition; import org.tttamics.scrapper.core.domain.model.competition.CompetitionGroup; import org.tttamics.scrapper.core.domain.model.competition.CompetitionId; import org.tttamics.scrapper.core.repository.jpa.model.JpaCompetition; import javax.inject.Named; import java.util.Arrays; import java.util.function.Function; import java.util.stream.Collectors; @Named public class JpaCompetitionToCompetitionMapper implements Function<JpaCompetition, Competition> { @Override public Competition apply(JpaCompetition jpaCompetition) { return Competition.builder(jpaCompetition.getName()) .withId(CompetitionId.of(jpaCompetition.getId())) .withGroups(Arrays.asList(jpaCompetition.getGroups().split(",")) .stream() .map(group -> CompetitionGroup.createCompetitionGroup(group)) .collect(Collectors.toList())) .create(); } }
UTF-8
Java
1,080
java
JpaCompetitionToCompetitionMapper.java
Java
[]
null
[]
package org.tttamics.scrapper.core.repository.jpa.mappers; import org.tttamics.scrapper.core.domain.model.competition.Competition; import org.tttamics.scrapper.core.domain.model.competition.CompetitionGroup; import org.tttamics.scrapper.core.domain.model.competition.CompetitionId; import org.tttamics.scrapper.core.repository.jpa.model.JpaCompetition; import javax.inject.Named; import java.util.Arrays; import java.util.function.Function; import java.util.stream.Collectors; @Named public class JpaCompetitionToCompetitionMapper implements Function<JpaCompetition, Competition> { @Override public Competition apply(JpaCompetition jpaCompetition) { return Competition.builder(jpaCompetition.getName()) .withId(CompetitionId.of(jpaCompetition.getId())) .withGroups(Arrays.asList(jpaCompetition.getGroups().split(",")) .stream() .map(group -> CompetitionGroup.createCompetitionGroup(group)) .collect(Collectors.toList())) .create(); } }
1,080
0.719444
0.719444
26
40.53846
30.931974
97
false
false
0
0
0
0
0
0
0.461538
false
false
1
326eba4ad349abdc91dd262cc5833a6bbfedc469
3,968,549,791,927
e66dd9fcd41f5bf0415034fd44a74af31e33985f
/app/src/main/java/suzykersten/csci/rake/BillActivity.java
48f3a6cb9ff7fd65fcaf0b0edebc23d549175b6f
[]
no_license
suzykersten/Rake
https://github.com/suzykersten/Rake
ef342531094b33eb76abf457a0b6177a135b7f2b
b1278aa977dcd6b96f6534cad3b2ceaa2542b798
refs/heads/master
2021-04-09T15:57:27.781000
2018-10-23T22:56:17
2018-10-23T22:56:17
125,589,840
0
1
null
false
2018-10-23T22:56:18
2018-03-17T02:27:43
2018-04-30T08:25:51
2018-10-23T22:56:18
1,026
1
0
0
Java
false
null
package suzykersten.csci.rake; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.google.gson.Gson; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class BillActivity extends Activity { private SparseArray<String> urls; private DownloadBills dlBills = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bill); //set up every button with the url that should work for them urls = new SparseArray<>(); urls.append( R.id.button_hconres, "https://sskersten.bitbucket.io/json/hconres.json" ); urls.append( R.id.button_hjres, "https://sskersten.bitbucket.io/json/hjres.json" ); urls.append( R.id.button_hr, "https://sskersten.bitbucket.io/json/hr.json" ); urls.append( R.id.button_hres, "https://sskersten.bitbucket.io/json/hres.json" ); urls.append( R.id.button_s, "https://sskersten.bitbucket.io/json/s.json" ); urls.append( R.id.button_sconres, "https://sskersten.bitbucket.io/json/sconres.json" ); urls.append( R.id.button_sjres, "https://sskersten.bitbucket.io/json/sjres.json" ); urls.append( R.id.button_sres, "https://sskersten.bitbucket.io/json/sres.json" ); //setup the onclicks for every button to work for the url needed on each one LinearLayout billUrlButtons = findViewById(R.id.linearLayout_billUrlButtons); //for each child of the billURLButtons layout, set the button on click listener for (int i = 0; i < billUrlButtons.getChildCount(); i++){ billUrlButtons.getChildAt(i).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { updateListViewWithDataFromUrl(view.getId()); } }); } //default by putting out hconres bills updateListViewWithDataFromUrl(R.id.button_hconres); } private void updateListViewWithDataFromUrl(int buttonId){ //Log.i("dlbills", "Trying to access data from " + ) //if we're trying to download data, stop that and exit. if (dlBills != null){ dlBills.cancel(true); dlBills = null; } ListView listView = findViewById(R.id.listView_bills); dlBills = new DownloadBills(urls.get(buttonId), listView); dlBills.execute(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.global, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.help: startActivity(new Intent(this, HelpActivity.class)); return true; } return super.onOptionsItemSelected(item); } } class DownloadBills extends AsyncTask<String, Integer, Bill[]>{ private String stringURL; private ListView listView; public DownloadBills(String stringURL, ListView listView) { this.stringURL = stringURL; this.listView = listView; } @Override protected void onPreExecute() { super.onPreExecute(); } private String readStream(InputStream in){ Scanner s = new Scanner(in).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } @Override protected Bill[] doInBackground(String... strings) { String result = ""; //make a url URL url = null; try { url = new URL(stringURL); } catch (MalformedURLException e) { Log.e("ReadBill", "Bad URL given."); e.printStackTrace(); } //connect to the internet HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Log.e("ReadBill", "Couldn't open http connection."); e.printStackTrace(); } //read in data from the internet try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); result = readStream(in); } catch (IOException e) { Log.e("ReadBill", "Couldn't read data from URL connection"); e.printStackTrace(); } finally { urlConnection.disconnect(); } //convert gotten json to Bills objects Gson gson = new Gson(); return gson.fromJson(result, Bill[].class); } //update the layout with the requested set of bills @Override protected void onPostExecute(Bill[] bills) { listView.setAdapter(new BillAdapter(listView.getContext(), Arrays.asList(bills))); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } } class BillAdapter extends ArrayAdapter<Bill>{ private List<Bill> data; BillAdapter(Context context, List<Bill> data){ super(context, R.layout.activity_bill_listrow, data); this.data = data; } @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { if (convertView == null){ LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.activity_bill_listrow, parent, false); } final Bill bill = data.get(position); setTextOfTextView(convertView, R.id.textView_title, bill.getTitle()); setTextOfTextView(convertView, R.id.textView_date, bill.getActionDate()); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(bill.getLinkToFull())); getContext().startActivity(intent); } }); return convertView; } private void setTextOfTextView(View view, int id, String text){ ((TextView) view.findViewById(id)).setText(text); } }
UTF-8
Java
7,080
java
BillActivity.java
Java
[ { "context": " urls.append( R.id.button_hconres, \"https://sskersten.bitbucket.io/json/hconres.json\" );\n urls.", "end": 1343, "score": 0.829606831073761, "start": 1334, "tag": "USERNAME", "value": "sskersten" }, { "context": " urls.append( R.id.button_hjres, \"https://sskersten.bitbucket.io/json/hjres.json\" );\n urls.", "end": 1446, "score": 0.7587922215461731, "start": 1437, "tag": "USERNAME", "value": "sskersten" }, { "context": " urls.append( R.id.button_hr, \"https://sskersten.bitbucket.io/json/hr.json\" );\n urls.", "end": 1549, "score": 0.8735456466674805, "start": 1540, "tag": "USERNAME", "value": "sskersten" }, { "context": " urls.append( R.id.button_hres, \"https://sskersten.bitbucket.io/json/hres.json\" );\n urls.", "end": 1652, "score": 0.9243309497833252, "start": 1643, "tag": "USERNAME", "value": "sskersten" }, { "context": " urls.append( R.id.button_s, \"https://sskersten.bitbucket.io/json/s.json\" );\n urls.", "end": 1755, "score": 0.7151482701301575, "start": 1746, "tag": "USERNAME", "value": "sskersten" }, { "context": " urls.append( R.id.button_sconres, \"https://sskersten.bitbucket.io/json/sconres.json\" );\n urls.", "end": 1858, "score": 0.9806551933288574, "start": 1849, "tag": "USERNAME", "value": "sskersten" }, { "context": " urls.append( R.id.button_sjres, \"https://sskersten.bitbucket.io/json/sjres.json\" );\n urls.", "end": 1961, "score": 0.9958122372627258, "start": 1952, "tag": "USERNAME", "value": "sskersten" }, { "context": " urls.append( R.id.button_sres, \"https://sskersten.bitbucket.io/json/sres.json\" );\n\n //se", "end": 2064, "score": 0.9953888058662415, "start": 2055, "tag": "USERNAME", "value": "sskersten" } ]
null
[]
package suzykersten.csci.rake; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.google.gson.Gson; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class BillActivity extends Activity { private SparseArray<String> urls; private DownloadBills dlBills = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bill); //set up every button with the url that should work for them urls = new SparseArray<>(); urls.append( R.id.button_hconres, "https://sskersten.bitbucket.io/json/hconres.json" ); urls.append( R.id.button_hjres, "https://sskersten.bitbucket.io/json/hjres.json" ); urls.append( R.id.button_hr, "https://sskersten.bitbucket.io/json/hr.json" ); urls.append( R.id.button_hres, "https://sskersten.bitbucket.io/json/hres.json" ); urls.append( R.id.button_s, "https://sskersten.bitbucket.io/json/s.json" ); urls.append( R.id.button_sconres, "https://sskersten.bitbucket.io/json/sconres.json" ); urls.append( R.id.button_sjres, "https://sskersten.bitbucket.io/json/sjres.json" ); urls.append( R.id.button_sres, "https://sskersten.bitbucket.io/json/sres.json" ); //setup the onclicks for every button to work for the url needed on each one LinearLayout billUrlButtons = findViewById(R.id.linearLayout_billUrlButtons); //for each child of the billURLButtons layout, set the button on click listener for (int i = 0; i < billUrlButtons.getChildCount(); i++){ billUrlButtons.getChildAt(i).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { updateListViewWithDataFromUrl(view.getId()); } }); } //default by putting out hconres bills updateListViewWithDataFromUrl(R.id.button_hconres); } private void updateListViewWithDataFromUrl(int buttonId){ //Log.i("dlbills", "Trying to access data from " + ) //if we're trying to download data, stop that and exit. if (dlBills != null){ dlBills.cancel(true); dlBills = null; } ListView listView = findViewById(R.id.listView_bills); dlBills = new DownloadBills(urls.get(buttonId), listView); dlBills.execute(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.global, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.help: startActivity(new Intent(this, HelpActivity.class)); return true; } return super.onOptionsItemSelected(item); } } class DownloadBills extends AsyncTask<String, Integer, Bill[]>{ private String stringURL; private ListView listView; public DownloadBills(String stringURL, ListView listView) { this.stringURL = stringURL; this.listView = listView; } @Override protected void onPreExecute() { super.onPreExecute(); } private String readStream(InputStream in){ Scanner s = new Scanner(in).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } @Override protected Bill[] doInBackground(String... strings) { String result = ""; //make a url URL url = null; try { url = new URL(stringURL); } catch (MalformedURLException e) { Log.e("ReadBill", "Bad URL given."); e.printStackTrace(); } //connect to the internet HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Log.e("ReadBill", "Couldn't open http connection."); e.printStackTrace(); } //read in data from the internet try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); result = readStream(in); } catch (IOException e) { Log.e("ReadBill", "Couldn't read data from URL connection"); e.printStackTrace(); } finally { urlConnection.disconnect(); } //convert gotten json to Bills objects Gson gson = new Gson(); return gson.fromJson(result, Bill[].class); } //update the layout with the requested set of bills @Override protected void onPostExecute(Bill[] bills) { listView.setAdapter(new BillAdapter(listView.getContext(), Arrays.asList(bills))); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } } class BillAdapter extends ArrayAdapter<Bill>{ private List<Bill> data; BillAdapter(Context context, List<Bill> data){ super(context, R.layout.activity_bill_listrow, data); this.data = data; } @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { if (convertView == null){ LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.activity_bill_listrow, parent, false); } final Bill bill = data.get(position); setTextOfTextView(convertView, R.id.textView_title, bill.getTitle()); setTextOfTextView(convertView, R.id.textView_date, bill.getActionDate()); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(bill.getLinkToFull())); getContext().startActivity(intent); } }); return convertView; } private void setTextOfTextView(View view, int id, String text){ ((TextView) view.findViewById(id)).setText(text); } }
7,080
0.638559
0.638418
212
32.396225
28.172876
118
false
false
0
0
0
0
0
0
0.622642
false
false
1
9244b7fe8998ce7c4e24398d51d36c1bc1d4d2fb
23,699,629,551,474
9e3b0e864d992f831341109545b5a9dda50cbae7
/app/src/main/java/edualison/utexas/cs/gotohell/PlayerNames.java
8c47c727ae336dd0f38bffba6ef1c7a52f10492c
[]
no_license
alisonthemonster/GoToHellScorekeeper
https://github.com/alisonthemonster/GoToHellScorekeeper
c4df1d07c80612ba991647e7d4e893faa63a5c01
8688da0353f2c6badd1121478a350e598c7fd10e
refs/heads/master
2019-04-03T20:37:37.633000
2016-06-11T14:19:58
2016-06-11T14:19:58
42,345,334
4
0
null
false
2016-04-13T20:41:23
2015-09-12T05:02:57
2016-04-12T23:00:13
2016-04-13T20:41:23
333
1
0
0
Java
null
null
package edualison.utexas.cs.gotohell; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputType; import android.view.HapticFeedbackConstants; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class PlayerNames extends AppCompatActivity { private int count; //player count @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_player_names); Intent intent = getIntent(); count = intent.getIntExtra("playerCount", 3); LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout); //set up EditTexts for (int a=0; a<count; a++) { EditText editText = new EditText(this); editText.setHint("Player " + (a + 1)); editText.setId(a + 501); editText.setTextColor(Color.WHITE); editText.setHintTextColor(Color.WHITE); editText.setSingleLine(); editText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); linearLayout.addView(editText); } } //occurs when the submit button is pressed public void createPlayers(View view) { LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout); int count = linearLayout.getChildCount(); Player[] players = new Player[count]; //create players and fill with names for (int a=0; a<count; a++) { EditText currentName = (EditText) linearLayout.getChildAt(a); String name = currentName.getText().toString(); if (name.length()>9) { Toast.makeText(PlayerNames.this, name + "'s name is too long!", Toast.LENGTH_SHORT).show(); return; } if (name.isEmpty()) { Toast.makeText(this, "Please enter player " + (a+1) + "'s name", Toast.LENGTH_LONG).show(); return; } else { //create player object and add it to list Player player = new Player(name); players[a] = player; } } //set next player for each player for (int b=0; b<count-1; b++) { //build the list players[b].nextPlayer = players[b+1]; } //set the last player as the last player players[count-1].nextPlayer = players[0]; players[count-1].isLast = true; //get round count TextView numRounds = (TextView) findViewById(R.id.number_rounds); int roundCount = Integer.parseInt(numRounds.getText().toString()); //create intent Intent intent = new Intent(this, Board.class); intent.putExtra("players", new DataWrapper(players)); intent.putExtra("numRounds", roundCount); startActivity(intent); } public void updateRoundCount(View view) { Button button = (Button) view; TextView numRounds = (TextView) findViewById(R.id.number_rounds); int maxNumOfRounds = 52/count; int currRound = Integer.parseInt(numRounds.getText().toString()); if (button.getText().equals("+")) { if (currRound < maxNumOfRounds) currRound++; else Toast.makeText(this, maxNumOfRounds+" is the maximum number of rounds", Toast.LENGTH_LONG).show(); } else { if (currRound > 1) currRound--; else Toast.makeText(this, "1 is the minimum number of rounds", Toast.LENGTH_LONG).show(); } numRounds.setText(currRound+""); } }
UTF-8
Java
4,024
java
PlayerNames.java
Java
[]
null
[]
package edualison.utexas.cs.gotohell; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputType; import android.view.HapticFeedbackConstants; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class PlayerNames extends AppCompatActivity { private int count; //player count @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_player_names); Intent intent = getIntent(); count = intent.getIntExtra("playerCount", 3); LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout); //set up EditTexts for (int a=0; a<count; a++) { EditText editText = new EditText(this); editText.setHint("Player " + (a + 1)); editText.setId(a + 501); editText.setTextColor(Color.WHITE); editText.setHintTextColor(Color.WHITE); editText.setSingleLine(); editText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); linearLayout.addView(editText); } } //occurs when the submit button is pressed public void createPlayers(View view) { LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout); int count = linearLayout.getChildCount(); Player[] players = new Player[count]; //create players and fill with names for (int a=0; a<count; a++) { EditText currentName = (EditText) linearLayout.getChildAt(a); String name = currentName.getText().toString(); if (name.length()>9) { Toast.makeText(PlayerNames.this, name + "'s name is too long!", Toast.LENGTH_SHORT).show(); return; } if (name.isEmpty()) { Toast.makeText(this, "Please enter player " + (a+1) + "'s name", Toast.LENGTH_LONG).show(); return; } else { //create player object and add it to list Player player = new Player(name); players[a] = player; } } //set next player for each player for (int b=0; b<count-1; b++) { //build the list players[b].nextPlayer = players[b+1]; } //set the last player as the last player players[count-1].nextPlayer = players[0]; players[count-1].isLast = true; //get round count TextView numRounds = (TextView) findViewById(R.id.number_rounds); int roundCount = Integer.parseInt(numRounds.getText().toString()); //create intent Intent intent = new Intent(this, Board.class); intent.putExtra("players", new DataWrapper(players)); intent.putExtra("numRounds", roundCount); startActivity(intent); } public void updateRoundCount(View view) { Button button = (Button) view; TextView numRounds = (TextView) findViewById(R.id.number_rounds); int maxNumOfRounds = 52/count; int currRound = Integer.parseInt(numRounds.getText().toString()); if (button.getText().equals("+")) { if (currRound < maxNumOfRounds) currRound++; else Toast.makeText(this, maxNumOfRounds+" is the maximum number of rounds", Toast.LENGTH_LONG).show(); } else { if (currRound > 1) currRound--; else Toast.makeText(this, "1 is the minimum number of rounds", Toast.LENGTH_LONG).show(); } numRounds.setText(currRound+""); } }
4,024
0.598658
0.593688
104
36.692307
25.065712
114
false
false
0
0
0
0
0
0
0.730769
false
false
1
24114b71b19d3a077386408ba2da8b1733bb2e38
12,317,966,214,988
b8fc82403af3465b0dc3408865f60dfd0738bfbd
/udmp-batch/udmp_batch_agent/src/main/java/cn/com/git/udmp/component/batch/core/agent/TaskExecutor.java
0ec67022388f8bbcf27fae639f78b846cea670d7
[]
no_license
ghj1040110333/udmp
https://github.com/ghj1040110333/udmp
379ba363e00579229a95660673a26344156ccc4c
ab41845e2f59c6a7fbd43c84ca57eea90fb5a7a7
refs/heads/master
2020-04-12T01:00:21.831000
2018-04-22T15:33:57
2018-04-22T15:33:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.com.git.udmp.component.batch.core.agent; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.beanutils.BeanUtils; import cn.com.git.udmp.common.exception.FrameworkException; import cn.com.git.udmp.component.batch.common.constants.CommandEnum; import cn.com.git.udmp.component.batch.common.constants.JobRunStatus; import cn.com.git.udmp.component.batch.common.utils.BalanceUtil; import cn.com.git.udmp.component.batch.common.utils.BalanceUtil.Section; import cn.com.git.udmp.component.batch.context.JobSessionContext; import cn.com.git.udmp.component.batch.core.agent.communicate.AgentCommunicator; import cn.com.git.udmp.component.batch.core.agent.concurrent.WorkExecutorGroup; import cn.com.git.udmp.component.batch.exception.BatchBizException; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; /** * @description 作业执行器 * @author liuliang * @date 2015年2月4日 上午10:23:08 */ public class TaskExecutor implements ITaskExecutor { private JobSessionContext context; private EventExecutorGroup es; private Map<Integer, Future<?>> workMap = new HashMap<Integer, Future<?>>(); private TaskHandler handler; private long timeout = 600; // default timeout setting private String name; private boolean isFinished = false; // 线程的状态收集 /** * <p> * Title:作业执行器 * </p> * <p> * Description: 作业执行器 * </p> * * @param jsContext 上下文对象 */ public TaskExecutor(JobSessionContext jsContext) { init(jsContext); } public TaskExecutor(String name, JobSessionContext jsContext) { this.name = name; init(jsContext); } private void init(JobSessionContext jsContext) { this.context = jsContext; es = new WorkExecutorGroup(getPoolSize()); handler = new TaskHandler(jsContext); } @Override public void startTask() { logger.debug("线程池{}正在启动作业", this.getContext().getJobId()); // TODO 1.获取区间,根据区间分区, long startNum = getStartNum(); long endNum = getEndNum(); long counts = endNum - startNum + 1; logger.debug("线程池大小是:{}", getPoolSize()); logger.debug("需要执行的区间是{}到{}", startNum, endNum); /** * sharding算法 */ List<Section> balanceArray = BalanceUtil.balanceArray(getPoolSize(), startNum, endNum); logger.debug("sharding后的区间集为:{}", balanceArray); handler.setSize(balanceArray.size()); int i = 0; for (Section section : balanceArray) { i++; JobSessionContext jsContext = new JobSessionContext(); // 2.然后新建任务,将分批信息和参数放到jobSessionContext中 try { // TODO bihb-005-使用cglib的beancopier,全系统统一,而且cglib的字节码操作效率最高。 BeanUtils.copyProperties(jsContext, context); jsContext.setExceptionList(new ArrayList<BatchBizException>()); logger.info( "--当前线程:" + Thread.currentThread() + "--**异常列表引用地址:" + jsContext.getExceptionList().toString()); logger.info("------------线程:" + i + "的session-id:" + jsContext.hashCode()); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } jsContext.setStartNum(section.getStartNum()); jsContext.setEndNum(section.getEndNum()); jsContext.setData(context.getData()); // 参数传递 jsContext.setExtension(context.getExtension()); // 对每个执行线程都默认设置上总记录数条件,用于线程回执更新时使用 // report中记录total jsContext.setTotalCnt(counts); logger.debug("即将启动一个线程执行区间{}到{}", section.getStartNum(), section.getEndNum()); IWork work = new Work(i, jsContext, handler); // 将线程控制类future记录下来 final int workId = i; // 这里使用的是netty的线程池,方便为线程添加监听事件 Future<Boolean> future = es.submit(work); addListener(future, workId); // TODO 超时处理 // setTimeoutEvent(submit,jsContext,i); workMap.put(i, future); } logger.info("---------------------开启的线程数量:" + workMap.size()); logger.debug("任务{}的任务实例{}启动完成", context.getJobId(), context.getJobRunId()); } /** * @title * @description 为每个线程添加监听器,监听器负责返回处理和异常处理等 * * @param future * @param workId */ private void addListener(Future<Boolean> future, final int workId) { future.addListener(new GenericFutureListener<Future<Boolean>>() { @Override public void operationComplete(Future<Boolean> future) throws Exception { try { Boolean result = future.get(); // TODO 回执线程池告知此线程已完成 logger.debug("线程{}执行作业结束", Thread.currentThread().getName()); if (result != null && result.booleanValue()) { handler.log(true, workId, null); recycleTaskExecutor(); } } catch (Exception e) { if (e instanceof CancellationException) { } else if (e instanceof ExecutionException) { Throwable cause = e.getCause(); if (cause instanceof BatchBizException) { // 捕捉到批处理应用异常 logger.info("thread-id:" + Thread.currentThread() + "---------------------------------------------------------BatchBizException" + e); handler.log(false, workId, (BatchBizException) cause); } else if (cause instanceof Exception) { logger.info("thread-id:" + Thread.currentThread() + "---------------------------------------------------------Exception" + e); // TODO 将异常抛出给线程池 // e.printStackTrace(); handler.log(false, workId, new BatchBizException(e.getMessage())); } } } } }); } /** * @title * @description 回收执行线程池 * */ private void recycleTaskExecutor() { if (isAllDone()) { logger.debug("当前线程池完成工作,即将回收"); this.shutdown(); } } /** * @title * @description 判断是否任务都已经完成 * * @return */ private boolean isAllDone() { boolean flag = true; //当且仅当线程池数量和分配的线程数量一致时才判断是否都完成,防止只初始化并且只运行完第一个线程的时候就执行了recycleTaskExecutor方法 if (workMap.size() == handler.getSize()) { for (Integer key: workMap.keySet()) { Future f = workMap.get(key); //但凡有一个线程没完成,也不会执行recycleTaskExecutor方法 if(f.isDone()||f.isCancelled()||f.isSuccess()){ continue; }else{ flag = false; logger.debug("线程{}没完成",key); System.out.println(f.isDone()); System.out.println(f.isCancelled()); System.out.println(f.isSuccess()); break; } } }else{ logger.debug("workMap size与handler不匹配"); return false; } return flag; } /** * @description 设置线程超时处理 * * @param submit * @param jsContext * @param threadId */ private void setTimeoutEvent(Future<?> submit, JobSessionContext jsContext, int threadId) { try { // updated by liang on 2016/11/28 对线程进行超时控制,默认600s submit.get(timeout, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.error("任务{}的线程{}执行异常:{}", jsContext.getJobId(), threadId, e); }catch ( ExecutionException e) { logger.error("任务{}的线程{}执行异常:{}", jsContext.getJobId(), threadId, e); } catch (TimeoutException e) { logger.error("任务{}的线程{}执行超时,即将停止当前线程", jsContext.getJobId(), threadId); submit.cancel(true); } } private long getEndNum() { return context.getEndNum(); } private long getStartNum() { return context.getStartNum(); } @Override public void stopTask() { // TODO batch--停止线程,但是也需要同时记录日志,还需要实时与服务器端报告停止进度 logger.debug("停止线程.."); for (int key : workMap.keySet()) { logger.debug("正在停止线程{}", key); workMap.get(key).cancel(true); logger.debug("停止作业..."); } es.shutdownGracefully(); logger.debug("停止线程完成"); reportStopStatus(context); } /** * @description 将停止结束的信息返回给server端 * @param context 任务的上下文参数 */ private void reportStopStatus(JobSessionContext context) { logger.debug("返回任务的执行结果"); AgentCommunicator communicator = new AgentCommunicator(context); // TODO batch--已经处理的结果需要收集 communicator.reportStatus(context.getJobRunId(), JobRunStatus.ABORTED); } @Override public void pauseTask() { // TODO Auto-generated method stub } /** * @description 获取线程池大小 * @author liuliang liuliang@newchinalife.com * @return 线程池大小 */ private int getPoolSize() { return context.getThreadSize(); } public JobSessionContext getContext() { return context; } public void setContext(JobSessionContext context) { this.context = context; } @Override public void executeTask() { logger.debug("当前任务处理的作业ID为{}", context.getJobId()); logger.debug("当前任务处理的作业名称为{}", context.getJobName()); logger.debug("当前任务处理的作业类为{}", context.getJobClazzName()); if (context.getCommand() == CommandEnum.START) { this.startTask(); } else if (context.getCommand() == CommandEnum.ABORT) { this.stopTask(); } else if (context.getCommand() == CommandEnum.PAUSE) { this.pauseTask(); } else { // TODO batch--异常信息需要使用静态变量统一化 logger.error("执行作业时没有找到对应指令{}", context.getCommand()); throw new FrameworkException("执行作业时没有找到对应指令"); } } /** * @description 获取可控线程集合 * @return 可控线程集合 */ public Map<Integer, Future<?>> getWorkMap() { return workMap; } @Override public String toString() { return context.toString(); } @Override public boolean isTerminated() { return es.isTerminated(); } @Override public void shutdown() { if (es.isTerminated() || es.isShutdown()) { logger.debug("线程池{}已关闭", getName()); return; } es.shutdownGracefully(); if (es.isShuttingDown()) { logger.debug("线程池{}正在关闭", getName()); } if (es.isTerminated() || es.isShutdown()) { logger.debug("线程池{}已关闭", getName()); } isFinished = true; } @Override public String getName() { return name; } @Override public boolean isFinished() { return isFinished; } }
UTF-8
Java
13,022
java
TaskExecutor.java
Java
[ { "context": "ureListener;\n\n/**\n * @description 作业执行器\n * @author liuliang\n * @date 2015年2月4日 上午10:23:08\n */\npublic class Ta", "end": 1261, "score": 0.9993897080421448, "start": 1253, "tag": "USERNAME", "value": "liuliang" }, { "context": "hreadId) {\n try {\n // updated by liang on 2016/11/28 对线程进行超时控制,默认600s\n submit", "end": 8110, "score": 0.9982926845550537, "start": 8105, "tag": "USERNAME", "value": "liang" }, { "context": " /**\n * @description 获取线程池大小\n * @author liuliang liuliang@newchinalife.com\n * @return 线程池大小\n ", "end": 9712, "score": 0.9193047881126404, "start": 9704, "tag": "NAME", "value": "liuliang" }, { "context": " * @description 获取线程池大小\n * @author liuliang liuliang@newchinalife.com\n * @return 线程池大小\n */\n private int getP", "end": 9738, "score": 0.9998965263366699, "start": 9713, "tag": "EMAIL", "value": "liuliang@newchinalife.com" } ]
null
[]
package cn.com.git.udmp.component.batch.core.agent; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.beanutils.BeanUtils; import cn.com.git.udmp.common.exception.FrameworkException; import cn.com.git.udmp.component.batch.common.constants.CommandEnum; import cn.com.git.udmp.component.batch.common.constants.JobRunStatus; import cn.com.git.udmp.component.batch.common.utils.BalanceUtil; import cn.com.git.udmp.component.batch.common.utils.BalanceUtil.Section; import cn.com.git.udmp.component.batch.context.JobSessionContext; import cn.com.git.udmp.component.batch.core.agent.communicate.AgentCommunicator; import cn.com.git.udmp.component.batch.core.agent.concurrent.WorkExecutorGroup; import cn.com.git.udmp.component.batch.exception.BatchBizException; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; /** * @description 作业执行器 * @author liuliang * @date 2015年2月4日 上午10:23:08 */ public class TaskExecutor implements ITaskExecutor { private JobSessionContext context; private EventExecutorGroup es; private Map<Integer, Future<?>> workMap = new HashMap<Integer, Future<?>>(); private TaskHandler handler; private long timeout = 600; // default timeout setting private String name; private boolean isFinished = false; // 线程的状态收集 /** * <p> * Title:作业执行器 * </p> * <p> * Description: 作业执行器 * </p> * * @param jsContext 上下文对象 */ public TaskExecutor(JobSessionContext jsContext) { init(jsContext); } public TaskExecutor(String name, JobSessionContext jsContext) { this.name = name; init(jsContext); } private void init(JobSessionContext jsContext) { this.context = jsContext; es = new WorkExecutorGroup(getPoolSize()); handler = new TaskHandler(jsContext); } @Override public void startTask() { logger.debug("线程池{}正在启动作业", this.getContext().getJobId()); // TODO 1.获取区间,根据区间分区, long startNum = getStartNum(); long endNum = getEndNum(); long counts = endNum - startNum + 1; logger.debug("线程池大小是:{}", getPoolSize()); logger.debug("需要执行的区间是{}到{}", startNum, endNum); /** * sharding算法 */ List<Section> balanceArray = BalanceUtil.balanceArray(getPoolSize(), startNum, endNum); logger.debug("sharding后的区间集为:{}", balanceArray); handler.setSize(balanceArray.size()); int i = 0; for (Section section : balanceArray) { i++; JobSessionContext jsContext = new JobSessionContext(); // 2.然后新建任务,将分批信息和参数放到jobSessionContext中 try { // TODO bihb-005-使用cglib的beancopier,全系统统一,而且cglib的字节码操作效率最高。 BeanUtils.copyProperties(jsContext, context); jsContext.setExceptionList(new ArrayList<BatchBizException>()); logger.info( "--当前线程:" + Thread.currentThread() + "--**异常列表引用地址:" + jsContext.getExceptionList().toString()); logger.info("------------线程:" + i + "的session-id:" + jsContext.hashCode()); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } jsContext.setStartNum(section.getStartNum()); jsContext.setEndNum(section.getEndNum()); jsContext.setData(context.getData()); // 参数传递 jsContext.setExtension(context.getExtension()); // 对每个执行线程都默认设置上总记录数条件,用于线程回执更新时使用 // report中记录total jsContext.setTotalCnt(counts); logger.debug("即将启动一个线程执行区间{}到{}", section.getStartNum(), section.getEndNum()); IWork work = new Work(i, jsContext, handler); // 将线程控制类future记录下来 final int workId = i; // 这里使用的是netty的线程池,方便为线程添加监听事件 Future<Boolean> future = es.submit(work); addListener(future, workId); // TODO 超时处理 // setTimeoutEvent(submit,jsContext,i); workMap.put(i, future); } logger.info("---------------------开启的线程数量:" + workMap.size()); logger.debug("任务{}的任务实例{}启动完成", context.getJobId(), context.getJobRunId()); } /** * @title * @description 为每个线程添加监听器,监听器负责返回处理和异常处理等 * * @param future * @param workId */ private void addListener(Future<Boolean> future, final int workId) { future.addListener(new GenericFutureListener<Future<Boolean>>() { @Override public void operationComplete(Future<Boolean> future) throws Exception { try { Boolean result = future.get(); // TODO 回执线程池告知此线程已完成 logger.debug("线程{}执行作业结束", Thread.currentThread().getName()); if (result != null && result.booleanValue()) { handler.log(true, workId, null); recycleTaskExecutor(); } } catch (Exception e) { if (e instanceof CancellationException) { } else if (e instanceof ExecutionException) { Throwable cause = e.getCause(); if (cause instanceof BatchBizException) { // 捕捉到批处理应用异常 logger.info("thread-id:" + Thread.currentThread() + "---------------------------------------------------------BatchBizException" + e); handler.log(false, workId, (BatchBizException) cause); } else if (cause instanceof Exception) { logger.info("thread-id:" + Thread.currentThread() + "---------------------------------------------------------Exception" + e); // TODO 将异常抛出给线程池 // e.printStackTrace(); handler.log(false, workId, new BatchBizException(e.getMessage())); } } } } }); } /** * @title * @description 回收执行线程池 * */ private void recycleTaskExecutor() { if (isAllDone()) { logger.debug("当前线程池完成工作,即将回收"); this.shutdown(); } } /** * @title * @description 判断是否任务都已经完成 * * @return */ private boolean isAllDone() { boolean flag = true; //当且仅当线程池数量和分配的线程数量一致时才判断是否都完成,防止只初始化并且只运行完第一个线程的时候就执行了recycleTaskExecutor方法 if (workMap.size() == handler.getSize()) { for (Integer key: workMap.keySet()) { Future f = workMap.get(key); //但凡有一个线程没完成,也不会执行recycleTaskExecutor方法 if(f.isDone()||f.isCancelled()||f.isSuccess()){ continue; }else{ flag = false; logger.debug("线程{}没完成",key); System.out.println(f.isDone()); System.out.println(f.isCancelled()); System.out.println(f.isSuccess()); break; } } }else{ logger.debug("workMap size与handler不匹配"); return false; } return flag; } /** * @description 设置线程超时处理 * * @param submit * @param jsContext * @param threadId */ private void setTimeoutEvent(Future<?> submit, JobSessionContext jsContext, int threadId) { try { // updated by liang on 2016/11/28 对线程进行超时控制,默认600s submit.get(timeout, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.error("任务{}的线程{}执行异常:{}", jsContext.getJobId(), threadId, e); }catch ( ExecutionException e) { logger.error("任务{}的线程{}执行异常:{}", jsContext.getJobId(), threadId, e); } catch (TimeoutException e) { logger.error("任务{}的线程{}执行超时,即将停止当前线程", jsContext.getJobId(), threadId); submit.cancel(true); } } private long getEndNum() { return context.getEndNum(); } private long getStartNum() { return context.getStartNum(); } @Override public void stopTask() { // TODO batch--停止线程,但是也需要同时记录日志,还需要实时与服务器端报告停止进度 logger.debug("停止线程.."); for (int key : workMap.keySet()) { logger.debug("正在停止线程{}", key); workMap.get(key).cancel(true); logger.debug("停止作业..."); } es.shutdownGracefully(); logger.debug("停止线程完成"); reportStopStatus(context); } /** * @description 将停止结束的信息返回给server端 * @param context 任务的上下文参数 */ private void reportStopStatus(JobSessionContext context) { logger.debug("返回任务的执行结果"); AgentCommunicator communicator = new AgentCommunicator(context); // TODO batch--已经处理的结果需要收集 communicator.reportStatus(context.getJobRunId(), JobRunStatus.ABORTED); } @Override public void pauseTask() { // TODO Auto-generated method stub } /** * @description 获取线程池大小 * @author liuliang <EMAIL> * @return 线程池大小 */ private int getPoolSize() { return context.getThreadSize(); } public JobSessionContext getContext() { return context; } public void setContext(JobSessionContext context) { this.context = context; } @Override public void executeTask() { logger.debug("当前任务处理的作业ID为{}", context.getJobId()); logger.debug("当前任务处理的作业名称为{}", context.getJobName()); logger.debug("当前任务处理的作业类为{}", context.getJobClazzName()); if (context.getCommand() == CommandEnum.START) { this.startTask(); } else if (context.getCommand() == CommandEnum.ABORT) { this.stopTask(); } else if (context.getCommand() == CommandEnum.PAUSE) { this.pauseTask(); } else { // TODO batch--异常信息需要使用静态变量统一化 logger.error("执行作业时没有找到对应指令{}", context.getCommand()); throw new FrameworkException("执行作业时没有找到对应指令"); } } /** * @description 获取可控线程集合 * @return 可控线程集合 */ public Map<Integer, Future<?>> getWorkMap() { return workMap; } @Override public String toString() { return context.toString(); } @Override public boolean isTerminated() { return es.isTerminated(); } @Override public void shutdown() { if (es.isTerminated() || es.isShutdown()) { logger.debug("线程池{}已关闭", getName()); return; } es.shutdownGracefully(); if (es.isShuttingDown()) { logger.debug("线程池{}正在关闭", getName()); } if (es.isTerminated() || es.isShutdown()) { logger.debug("线程池{}已关闭", getName()); } isFinished = true; } @Override public String getName() { return name; } @Override public boolean isFinished() { return isFinished; } }
13,004
0.564945
0.562114
348
32.494251
25.144924
120
false
false
0
0
0
0
0
0
0.563218
false
false
1
30dd4be43a3c33ec20d50ac4ce1f505d2f278d9d
17,712,445,138,996
c64cde4e6e6510cd5f246bebcca06e6a0753a854
/src/main/java/com/dcn/sell/service/OrderService.java
27efe2e30c48819b1f532e6615a0520b52f37354
[]
no_license
382517195/sell
https://github.com/382517195/sell
a646d243033594a5f0fdcc302977c03b81a1f392
c93c980dbadb132207a77e5e65e4f0be10314fe0
refs/heads/master
2020-03-26T08:52:45.167000
2018-08-16T10:29:46
2018-08-16T10:29:46
144,706,090
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dcn.sell.service; import com.dcn.sell.dto.OrderDTO; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; /** * @Description 订单服务接口实现类 * @Author dengchangneng * @Create 2018年8月14日17:30:15 **/ public interface OrderService { /** * @Describe 创建订单 * @param orderDTO * @return */ OrderDTO create(OrderDTO orderDTO); /** * @Describe 根据订单id查询单个订单 * @param orderId 订单id * @return */ OrderDTO findOne(String orderId); /** * @Describe 根据买家openid分页查询订单列表 * @param buyerOpenid 买家openid * @param pageable 分页 * @return */ Page<OrderDTO> findList(String buyerOpenid, Pageable pageable); /** * @Describe 取消订单 * @param orderDTO 订单 * @return */ OrderDTO cancel(OrderDTO orderDTO); /** * @Describe 完结订单 * @param orderDTO * @return */ OrderDTO finish(OrderDTO orderDTO); /** * @Describe 支付订单 * @param orderDTO 订单 * @return */ OrderDTO paid(OrderDTO orderDTO); /** * @Describe 分页查询订单列表 * @param pageable 分页对象 * @return */ Page<OrderDTO> findList(Pageable pageable); }
UTF-8
Java
1,360
java
OrderService.java
Java
[ { "context": "ageable;\n\n/**\n * @Description 订单服务接口实现类\n * @Author dengchangneng\n * @Create 2018年8月14日17:30:15\n **/\npublic interfa", "end": 214, "score": 0.99893718957901, "start": 201, "tag": "USERNAME", "value": "dengchangneng" } ]
null
[]
package com.dcn.sell.service; import com.dcn.sell.dto.OrderDTO; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; /** * @Description 订单服务接口实现类 * @Author dengchangneng * @Create 2018年8月14日17:30:15 **/ public interface OrderService { /** * @Describe 创建订单 * @param orderDTO * @return */ OrderDTO create(OrderDTO orderDTO); /** * @Describe 根据订单id查询单个订单 * @param orderId 订单id * @return */ OrderDTO findOne(String orderId); /** * @Describe 根据买家openid分页查询订单列表 * @param buyerOpenid 买家openid * @param pageable 分页 * @return */ Page<OrderDTO> findList(String buyerOpenid, Pageable pageable); /** * @Describe 取消订单 * @param orderDTO 订单 * @return */ OrderDTO cancel(OrderDTO orderDTO); /** * @Describe 完结订单 * @param orderDTO * @return */ OrderDTO finish(OrderDTO orderDTO); /** * @Describe 支付订单 * @param orderDTO 订单 * @return */ OrderDTO paid(OrderDTO orderDTO); /** * @Describe 分页查询订单列表 * @param pageable 分页对象 * @return */ Page<OrderDTO> findList(Pageable pageable); }
1,360
0.603618
0.592928
65
17.707693
15.055511
67
false
false
0
0
0
0
0
0
0.184615
false
false
1
9374fc50d6842996e17bb2424ea750ee0637fb3e
6,133,213,310,763
cac9897d809bd43f65c50aa3f5865eae53f855a8
/src/com/stone/common/DicApp.java
21f6dcc431ca3c94dd88b6d9f4a7b1095e009bae
[]
no_license
Levifighting/DIC_CN
https://github.com/Levifighting/DIC_CN
e8203d7458217caa579b9c1ebb571b810967d5e6
497bccc6faa223fda3b38befac126e2d7ea07fcd
refs/heads/master
2016-09-03T07:02:15.589000
2015-06-18T07:08:03
2015-06-18T07:08:03
37,643,279
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.stone.common; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import android.app.Application; import android.content.Context; import android.content.res.Resources; import android.util.DisplayMetrics; /* * DicApp为全局上下文,资源访问 * TO DO ... */ public class DicApp extends Application { private static Context mContext; private static Resources mResources; private static DisplayMetrics mDisplayMetrics; private static RequestQueue mQueue; @Override public void onCreate() { // super.onCreate(); mContext = this.getApplicationContext(); mResources = mContext.getResources(); mDisplayMetrics = mResources.getDisplayMetrics(); mQueue = Volley.newRequestQueue(mContext); } public static Context getContext() { return mContext; } public static Resources getRes() { return mResources; } public static DisplayMetrics getDisplayMetrics() { return mDisplayMetrics; } }
GB18030
Java
961
java
DicApp.java
Java
[]
null
[]
package com.stone.common; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import android.app.Application; import android.content.Context; import android.content.res.Resources; import android.util.DisplayMetrics; /* * DicApp为全局上下文,资源访问 * TO DO ... */ public class DicApp extends Application { private static Context mContext; private static Resources mResources; private static DisplayMetrics mDisplayMetrics; private static RequestQueue mQueue; @Override public void onCreate() { // super.onCreate(); mContext = this.getApplicationContext(); mResources = mContext.getResources(); mDisplayMetrics = mResources.getDisplayMetrics(); mQueue = Volley.newRequestQueue(mContext); } public static Context getContext() { return mContext; } public static Resources getRes() { return mResources; } public static DisplayMetrics getDisplayMetrics() { return mDisplayMetrics; } }
961
0.771033
0.771033
41
21.902439
17.43812
51
false
false
0
0
0
0
0
0
1.170732
false
false
1
07038ff4cf1f47561235f4ed474b3274085561e2
21,277,267,993,988
51589087375289bbdb54a858a0c2a7e48c4c55ac
/src/main/java/com/bjrhxq/assember/AppUserInfoAssember.java
6de76289f056682039340466e758b06fe26ad1eb
[]
no_license
scqshine/shine
https://github.com/scqshine/shine
573721ceba9a9d2c5bab413d252aa58a8e585f72
1286110be7604aed1cf007cb3aa46453a2ad5b29
refs/heads/master
2018-11-26T20:27:14.759000
2018-11-08T06:07:47
2018-11-08T06:07:47
146,425,615
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bjrhxq.assember; import com.bjrhxq.dto.AppUserInfoDTO; import com.bjrhxq.entity.AppUserInfoEntity; import java.util.Collections; import java.util.List; /** * @package: com.bjrhxq.assember * @description: HouseDesignAssember实体类和dto转换类 * @author: YixinCapital--shanchangqing * @create: 2018-08-27 15:11 **/ public class AppUserInfoAssember extends RhBaseAssember{ public static AppUserInfoDTO toDto(AppUserInfoEntity appUserInfoEntity){ AppUserInfoDTO appUserInfoDTO = null; if (appUserInfoEntity != null) { appUserInfoDTO=mapObjToTclass(appUserInfoEntity, AppUserInfoDTO.class); } return appUserInfoDTO; } public static List<AppUserInfoDTO> toDtos(List<AppUserInfoEntity> appUserInfoEntityList){ List<AppUserInfoDTO> appUserInfoDTOList = Collections.EMPTY_LIST; appUserInfoEntityList.forEach(appUserInfoEntity-> appUserInfoDTOList.add(mapObjToTclass(appUserInfoEntity,AppUserInfoDTO.class))); return appUserInfoDTOList; } public static AppUserInfoEntity toEntity(AppUserInfoDTO appUserInfoDTO){ AppUserInfoEntity appUserInfoEntity = null; if (appUserInfoDTO != null) { appUserInfoEntity=mapObjToTclass(appUserInfoDTO, AppUserInfoEntity.class); } return appUserInfoEntity; } /** * @desciption :转换成entity集合 * @author: shanchangqing * @param:[appUserInfoDTOList] * @rerutn:java.util.List<com.bjrhxq.entity.AppUserInfoEntity> * @date:2018-08-27 * @time:15:50 */ public static List<AppUserInfoEntity> toEntitys(List<AppUserInfoDTO> appUserInfoDTOList){ List<AppUserInfoEntity> appUserInfoEntityList = Collections.EMPTY_LIST; appUserInfoDTOList.forEach(appUserInfoDTO-> appUserInfoEntityList.add(mapObjToTclass(appUserInfoDTO,AppUserInfoEntity.class))); return appUserInfoEntityList; } }
UTF-8
Java
1,949
java
AppUserInfoAssember.java
Java
[ { "context": "ription: HouseDesignAssember实体类和dto转换类\n * @author: YixinCapital--shanchangqing\n * @create: 2018-08-27 15:11\n **/\n", "end": 275, "score": 0.9296233654022217, "start": 263, "tag": "USERNAME", "value": "YixinCapital" }, { "context": "esignAssember实体类和dto转换类\n * @author: YixinCapital--shanchangqing\n * @create: 2018-08-27 15:11\n **/\npublic class Ap", "end": 290, "score": 0.9364587664604187, "start": 277, "tag": "USERNAME", "value": "shanchangqing" }, { "context": "\n * @desciption :转换成entity集合\n * @author: shanchangqing\n * @param:[appUserInfoDTOList]\n * @reru", "end": 1404, "score": 0.9987850189208984, "start": 1391, "tag": "USERNAME", "value": "shanchangqing" } ]
null
[]
package com.bjrhxq.assember; import com.bjrhxq.dto.AppUserInfoDTO; import com.bjrhxq.entity.AppUserInfoEntity; import java.util.Collections; import java.util.List; /** * @package: com.bjrhxq.assember * @description: HouseDesignAssember实体类和dto转换类 * @author: YixinCapital--shanchangqing * @create: 2018-08-27 15:11 **/ public class AppUserInfoAssember extends RhBaseAssember{ public static AppUserInfoDTO toDto(AppUserInfoEntity appUserInfoEntity){ AppUserInfoDTO appUserInfoDTO = null; if (appUserInfoEntity != null) { appUserInfoDTO=mapObjToTclass(appUserInfoEntity, AppUserInfoDTO.class); } return appUserInfoDTO; } public static List<AppUserInfoDTO> toDtos(List<AppUserInfoEntity> appUserInfoEntityList){ List<AppUserInfoDTO> appUserInfoDTOList = Collections.EMPTY_LIST; appUserInfoEntityList.forEach(appUserInfoEntity-> appUserInfoDTOList.add(mapObjToTclass(appUserInfoEntity,AppUserInfoDTO.class))); return appUserInfoDTOList; } public static AppUserInfoEntity toEntity(AppUserInfoDTO appUserInfoDTO){ AppUserInfoEntity appUserInfoEntity = null; if (appUserInfoDTO != null) { appUserInfoEntity=mapObjToTclass(appUserInfoDTO, AppUserInfoEntity.class); } return appUserInfoEntity; } /** * @desciption :转换成entity集合 * @author: shanchangqing * @param:[appUserInfoDTOList] * @rerutn:java.util.List<com.bjrhxq.entity.AppUserInfoEntity> * @date:2018-08-27 * @time:15:50 */ public static List<AppUserInfoEntity> toEntitys(List<AppUserInfoDTO> appUserInfoDTOList){ List<AppUserInfoEntity> appUserInfoEntityList = Collections.EMPTY_LIST; appUserInfoDTOList.forEach(appUserInfoDTO-> appUserInfoEntityList.add(mapObjToTclass(appUserInfoDTO,AppUserInfoEntity.class))); return appUserInfoEntityList; } }
1,949
0.72987
0.717403
54
34.648148
33.927021
138
false
false
0
0
0
0
0
0
0.388889
false
false
1
3a467e10247af92c5476a0578e9903fb434cf2cb
5,866,925,336,801
402bdcbe56143bd154d0c829be13eea88ea474eb
/apps/stockbroker-demo/src/demos/stockbroker/IBEveF.java
a666d545beddf294d50e689f10591f771632b116
[]
no_license
yqq836438958/open-card-framework
https://github.com/yqq836438958/open-card-framework
2065da8da7f69b756f32229897bffd8303530cae
dc8eb9f298bf29d6a3820c4b9ddc4c11ef930bfe
refs/heads/master
2022-04-11T18:24:42.862000
2020-03-27T18:44:06
2020-03-27T18:44:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * (C) COPYRIGHT INTERNATIONAL BUSINESS MACHINES CORPORATION 1997 - 1999 * ALL RIGHTS RESERVED * IBM Deutschland Entwicklung GmbH, Boeblingen * * Redistribution and use in source (source code) and binary (object code) * forms, with or without modification, are permitted provided that the * following conditions are met: * 1. Redistributed source code must retain the above copyright notice, this * list of conditions and the disclaimer below. * 2. Redistributed object code must reproduce the above copyright notice, * this list of conditions and the disclaimer below in the documentation * and/or other materials provided with the distribution. * 3. The name of IBM may not be used to endorse or promote products derived * from this software or in any other form without specific prior written * permission from IBM. * 4. Redistribution of any modified code must be labeled "Code derived from * the original OpenCard Framework". * * THIS SOFTWARE IS PROVIDED BY IBM "AS IS" FREE OF CHARGE. ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IBM * DOES NOT WARRANT THAT THE FUNCTIONS CONTAINED IN THIS SOFTWARE WILL MEET * THE USER'S REQUIREMENTS OR THAT THE OPERATION OF IT WILL BE UNINTERRUPTED * OR ERROR-FREE. IN NO EVENT, UNLESS REQUIRED BY APPLICABLE LAW, SHALL IBM BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ALSO, IBM IS UNDER NO OBLIGATION TO MAINTAIN, * CORRECT, UPDATE, CHANGE, MODIFY, OR OTHERWISE SUPPORT THIS SOFTWARE. */ package demos.stockbroker; import java.applet.*; import java.awt.*; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.math.BigInteger; import opencard.opt.util.Tag; import opencard.opt.util.TLV; /**************************************************************************** * IBEve is the window which allows to modify the message sent from client * to server in the Internet Broker Demo. * * @author Thomas Schaeck (schaeck@de.ibm.com) * @version $Id: IBEveF.java,v 1.1.1.1 2004/09/09 15:54:34 dirkhusemann Exp $ * * @see IBServer * @see IBClient * @see IBProt ****************************************************************************/ public class IBEveF extends Frame { // GUI part --------------------------------------------------------------- private Label dataLabel, signatureLabel; private TextField dataField0, dataField1, dataField2, dataField3; private TextField signatureField, cardHolderField; private Button sendButton; private Checkbox interceptCheckBox; // Receiver object private IBServerF server = null; /************************************************************************** * Create a new instance. * * @param title - the title of the frame * @param server - the object to which messages are sent **************************************************************************/ public IBEveF(String title, IBServerF server) { super(title); setFont(new Font("Helvetica", Font.BOLD, 16)); this.server = server; GridBagLayout gridBag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setLayout(gridBag); c.weightx = 1.0; c.weighty = 1.0; c.fill = GridBagConstraints.HORIZONTAL; // Add intercept CheckBox interceptCheckBox = new Checkbox("Intercept"); interceptCheckBox.addItemListener( new ItemListener () { public void itemStateChanged(ItemEvent e ) { interceptStateChange(); } }); c.gridx = 0; c.gridy = 0; gridBag.setConstraints(interceptCheckBox, c); add(interceptCheckBox); // Add Label "Data:" Label dataLabel = new Label("Data:", Label.LEFT); c.gridx = 1; c.gridy = 0; gridBag.setConstraints(dataLabel, c); add(dataLabel); // Add Label "Signature:" Label signatureLabel = new Label("Signature:", Label.LEFT); c.gridx = 1; c.gridy = 2; gridBag.setConstraints(signatureLabel, c); add(signatureLabel); // Add TextFields c.weightx = 1.0; c.gridwidth = 1; dataField0 = new TextField("0", 4); dataField0.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { dataField0Change(); } }); c.gridx = 2; c.gridy = 0; gridBag.setConstraints(dataField0, c); add(dataField0); dataField1 = new TextField("0", 4); dataField1.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { dataField1Change(); } }); c.gridx = 3; c.gridy = 0; gridBag.setConstraints(dataField1, c); add(dataField1); dataField2 = new TextField("0", 4); dataField2.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { dataField2Change(); } }); c.gridx = 4; c.gridy = 0; gridBag.setConstraints(dataField2, c); add(dataField2); c.weightx = 1.0; dataField3 = new TextField("0", 4); dataField3.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { dataField3Change(); } }); c.gridx = 5; c.gridy = 0; gridBag.setConstraints(dataField3, c); add(dataField3); // Add card holder TextField cardHolderField = new TextField("-", 16); cardHolderField.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { cardHolderFieldChange(); } }); c.gridx = 2; c.gridy = 1; c.gridwidth = 4; gridBag.setConstraints(cardHolderField, c); add(cardHolderField); // Add signature TextField signatureField = new TextField("0", 16); signatureField.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { signatureFieldChange(); } }); c.gridx = 2; c.gridy = 2; c.gridwidth = 4; gridBag.setConstraints(signatureField, c); add(signatureField); // Add send Button c.weightx = 0.8; sendButton = new Button("Send"); sendButton.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { sendButtonPressed(); } }); c.gridx = 6; c.gridy = 0; c.gridheight = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.BOTH; gridBag.setConstraints(sendButton, c); add(sendButton); setLocation(new Point(0, 255)); setSize(800, 95); show(); } private void setEditable(boolean editable) { dataField0.setEditable(editable); dataField1.setEditable(editable); dataField2.setEditable(editable); dataField3.setEditable(editable); signatureField.setEditable(editable); cardHolderField.setEditable(editable); } // -------------------------------------------------------- End of GUI part // Application logic part ------------------------------------------------- // Message parts private BigInteger signatureBigInt; private int sequenceNumber; private int number; private String price; private String company; private String cardHolder; // Indicates wether intercepted message is encrypted or not private boolean encrypted = true; // Indicates weither we are intercepting messages or not private boolean intercepting = false; // original data received private byte[] data = null; // The following methods are called by the anonymous // GUI AdapterClasses. protected void interceptStateChange() { intercepting = interceptCheckBox.getState(); } protected void dataField0Change() { sequenceNumber = Integer.parseInt(dataField0.getText()); } protected void dataField1Change() { number = Integer.parseInt(dataField1.getText()); } protected void dataField2Change() { price = dataField2.getText(); } protected void dataField3Change() { company = dataField3.getText(); } protected void cardHolderFieldChange() { cardHolder = cardHolderField.getText(); } protected void signatureFieldChange() { signatureBigInt = new BigInteger(signatureField.getText()); } protected void sendButtonPressed() { TLV order = null, signedMessage = null, clearText = null; if (encrypted) { // If the data was encrypted, we send it as it was received. server.processRequestFrom("Client", data); } else { // If the data was not encrypted, we send the (eventually) // modified data fetched from the text fields. sequenceNumber = Integer.parseInt(dataField0.getText()); number = Integer.parseInt(dataField1.getText()); price = dataField2.getText(); company = dataField3.getText(); cardHolder = cardHolderField.getText(); signatureBigInt = new BigInteger(signatureField.getText()); order = new TLV(IBProt.STOCK_ORDER, new TLV(IBProt.NUMBER, (int) number)); order.add(new TLV(IBProt.PRICE, price.getBytes())); order.add(new TLV(IBProt.COMPANY, company.getBytes())); order.add(new TLV(IBProt.SEQUENCE_NUMBER, sequenceNumber)); order.add(new TLV(IBProt.CARD_HOLDER_DATA, cardHolder.getBytes())); signedMessage = new TLV(IBProt.SIGNED_MESSAGE, order); signedMessage.add(new TLV(IBProt.SIGNATURE, signatureBigInt.toByteArray())); clearText = new TLV(IBProt.CLEAR_MESSAGE, signedMessage.toBinary()); server.processRequestFrom("Eve", clearText.toBinary()); } } /************************************************************************** * Process a request coming in from the client. * * @param senderName - The name of the sender of this message * @param data - The message that has been received **************************************************************************/ public void processRequestFrom(String senderName, byte[] data) { this.data = data; if (intercepting) { TLV message = new TLV(data); if (message.tag().equals(IBProt.CLEAR_MESSAGE)) { encrypted = false; TLV signedMessage = new TLV(message.valueAsByteArray()); if (!signedMessage.tag().equals(IBProt.SIGNED_MESSAGE)) { System.err.println("IBEve - panic: SIGNED_MESSAGE tag not found"); System.exit(0); } TLV stockOrder = signedMessage.findTag(IBProt.STOCK_ORDER, null); if (stockOrder == null) { System.err.println("IBEve - panic: STOCK_ORDER tag not found"); System.exit(0); } byte[] order = stockOrder.toBinary(); TLV signature = signedMessage.findTag(IBProt.SIGNATURE, null); if (signature == null) { System.err.println("IBEve - panic: SIGNATURE tag not found"); System.exit(0); } sequenceNumber = (stockOrder.findTag(IBProt.SEQUENCE_NUMBER, null)).valueAsNumber(); number = (stockOrder.findTag(IBProt.NUMBER, null)).valueAsNumber(); price = new String((stockOrder.findTag(IBProt.PRICE, null)).valueAsByteArray()); company = new String((stockOrder.findTag(IBProt.COMPANY, null)).valueAsByteArray()); cardHolder = new String((stockOrder.findTag(IBProt.CARD_HOLDER_DATA, null)).valueAsByteArray()); signatureBigInt = new BigInteger(1, signature.valueAsByteArray()); dataField0.setText(Integer.toString(sequenceNumber)); dataField1.setText(Integer.toString(number)); dataField2.setText(price); dataField3.setText(company); cardHolderField.setText(cardHolder); signatureField.setText(signatureBigInt.toString()); } else { encrypted = true; dataField0.setText("???"); dataField1.setText("???"); dataField2.setText("???"); dataField3.setText("???"); cardHolderField.setText("???"); signatureField.setText("???"); } // TextFields become un-editable if data is encrypted, editable otherwise setEditable(!encrypted); } else { server.processRequestFrom("Client", data); } repaint(); } }
UTF-8
Java
13,113
java
IBEveF.java
Java
[ { "context": " server in the Internet Broker Demo.\r\n*\r\n* @author Thomas Schaeck (schaeck@de.ibm.com)\r\n* @version $Id: IBEveF.jav", "end": 2631, "score": 0.9998323917388916, "start": 2617, "tag": "NAME", "value": "Thomas Schaeck" }, { "context": "ternet Broker Demo.\r\n*\r\n* @author Thomas Schaeck (schaeck@de.ibm.com)\r\n* @version $Id: IBEveF.java,v 1.1.1.1 2004/09/", "end": 2651, "score": 0.9999339580535889, "start": 2633, "tag": "EMAIL", "value": "schaeck@de.ibm.com" } ]
null
[]
/* * (C) COPYRIGHT INTERNATIONAL BUSINESS MACHINES CORPORATION 1997 - 1999 * ALL RIGHTS RESERVED * IBM Deutschland Entwicklung GmbH, Boeblingen * * Redistribution and use in source (source code) and binary (object code) * forms, with or without modification, are permitted provided that the * following conditions are met: * 1. Redistributed source code must retain the above copyright notice, this * list of conditions and the disclaimer below. * 2. Redistributed object code must reproduce the above copyright notice, * this list of conditions and the disclaimer below in the documentation * and/or other materials provided with the distribution. * 3. The name of IBM may not be used to endorse or promote products derived * from this software or in any other form without specific prior written * permission from IBM. * 4. Redistribution of any modified code must be labeled "Code derived from * the original OpenCard Framework". * * THIS SOFTWARE IS PROVIDED BY IBM "AS IS" FREE OF CHARGE. ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IBM * DOES NOT WARRANT THAT THE FUNCTIONS CONTAINED IN THIS SOFTWARE WILL MEET * THE USER'S REQUIREMENTS OR THAT THE OPERATION OF IT WILL BE UNINTERRUPTED * OR ERROR-FREE. IN NO EVENT, UNLESS REQUIRED BY APPLICABLE LAW, SHALL IBM BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ALSO, IBM IS UNDER NO OBLIGATION TO MAINTAIN, * CORRECT, UPDATE, CHANGE, MODIFY, OR OTHERWISE SUPPORT THIS SOFTWARE. */ package demos.stockbroker; import java.applet.*; import java.awt.*; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.math.BigInteger; import opencard.opt.util.Tag; import opencard.opt.util.TLV; /**************************************************************************** * IBEve is the window which allows to modify the message sent from client * to server in the Internet Broker Demo. * * @author <NAME> (<EMAIL>) * @version $Id: IBEveF.java,v 1.1.1.1 2004/09/09 15:54:34 dirkhusemann Exp $ * * @see IBServer * @see IBClient * @see IBProt ****************************************************************************/ public class IBEveF extends Frame { // GUI part --------------------------------------------------------------- private Label dataLabel, signatureLabel; private TextField dataField0, dataField1, dataField2, dataField3; private TextField signatureField, cardHolderField; private Button sendButton; private Checkbox interceptCheckBox; // Receiver object private IBServerF server = null; /************************************************************************** * Create a new instance. * * @param title - the title of the frame * @param server - the object to which messages are sent **************************************************************************/ public IBEveF(String title, IBServerF server) { super(title); setFont(new Font("Helvetica", Font.BOLD, 16)); this.server = server; GridBagLayout gridBag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setLayout(gridBag); c.weightx = 1.0; c.weighty = 1.0; c.fill = GridBagConstraints.HORIZONTAL; // Add intercept CheckBox interceptCheckBox = new Checkbox("Intercept"); interceptCheckBox.addItemListener( new ItemListener () { public void itemStateChanged(ItemEvent e ) { interceptStateChange(); } }); c.gridx = 0; c.gridy = 0; gridBag.setConstraints(interceptCheckBox, c); add(interceptCheckBox); // Add Label "Data:" Label dataLabel = new Label("Data:", Label.LEFT); c.gridx = 1; c.gridy = 0; gridBag.setConstraints(dataLabel, c); add(dataLabel); // Add Label "Signature:" Label signatureLabel = new Label("Signature:", Label.LEFT); c.gridx = 1; c.gridy = 2; gridBag.setConstraints(signatureLabel, c); add(signatureLabel); // Add TextFields c.weightx = 1.0; c.gridwidth = 1; dataField0 = new TextField("0", 4); dataField0.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { dataField0Change(); } }); c.gridx = 2; c.gridy = 0; gridBag.setConstraints(dataField0, c); add(dataField0); dataField1 = new TextField("0", 4); dataField1.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { dataField1Change(); } }); c.gridx = 3; c.gridy = 0; gridBag.setConstraints(dataField1, c); add(dataField1); dataField2 = new TextField("0", 4); dataField2.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { dataField2Change(); } }); c.gridx = 4; c.gridy = 0; gridBag.setConstraints(dataField2, c); add(dataField2); c.weightx = 1.0; dataField3 = new TextField("0", 4); dataField3.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { dataField3Change(); } }); c.gridx = 5; c.gridy = 0; gridBag.setConstraints(dataField3, c); add(dataField3); // Add card holder TextField cardHolderField = new TextField("-", 16); cardHolderField.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { cardHolderFieldChange(); } }); c.gridx = 2; c.gridy = 1; c.gridwidth = 4; gridBag.setConstraints(cardHolderField, c); add(cardHolderField); // Add signature TextField signatureField = new TextField("0", 16); signatureField.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { signatureFieldChange(); } }); c.gridx = 2; c.gridy = 2; c.gridwidth = 4; gridBag.setConstraints(signatureField, c); add(signatureField); // Add send Button c.weightx = 0.8; sendButton = new Button("Send"); sendButton.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e ) { sendButtonPressed(); } }); c.gridx = 6; c.gridy = 0; c.gridheight = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.BOTH; gridBag.setConstraints(sendButton, c); add(sendButton); setLocation(new Point(0, 255)); setSize(800, 95); show(); } private void setEditable(boolean editable) { dataField0.setEditable(editable); dataField1.setEditable(editable); dataField2.setEditable(editable); dataField3.setEditable(editable); signatureField.setEditable(editable); cardHolderField.setEditable(editable); } // -------------------------------------------------------- End of GUI part // Application logic part ------------------------------------------------- // Message parts private BigInteger signatureBigInt; private int sequenceNumber; private int number; private String price; private String company; private String cardHolder; // Indicates wether intercepted message is encrypted or not private boolean encrypted = true; // Indicates weither we are intercepting messages or not private boolean intercepting = false; // original data received private byte[] data = null; // The following methods are called by the anonymous // GUI AdapterClasses. protected void interceptStateChange() { intercepting = interceptCheckBox.getState(); } protected void dataField0Change() { sequenceNumber = Integer.parseInt(dataField0.getText()); } protected void dataField1Change() { number = Integer.parseInt(dataField1.getText()); } protected void dataField2Change() { price = dataField2.getText(); } protected void dataField3Change() { company = dataField3.getText(); } protected void cardHolderFieldChange() { cardHolder = cardHolderField.getText(); } protected void signatureFieldChange() { signatureBigInt = new BigInteger(signatureField.getText()); } protected void sendButtonPressed() { TLV order = null, signedMessage = null, clearText = null; if (encrypted) { // If the data was encrypted, we send it as it was received. server.processRequestFrom("Client", data); } else { // If the data was not encrypted, we send the (eventually) // modified data fetched from the text fields. sequenceNumber = Integer.parseInt(dataField0.getText()); number = Integer.parseInt(dataField1.getText()); price = dataField2.getText(); company = dataField3.getText(); cardHolder = cardHolderField.getText(); signatureBigInt = new BigInteger(signatureField.getText()); order = new TLV(IBProt.STOCK_ORDER, new TLV(IBProt.NUMBER, (int) number)); order.add(new TLV(IBProt.PRICE, price.getBytes())); order.add(new TLV(IBProt.COMPANY, company.getBytes())); order.add(new TLV(IBProt.SEQUENCE_NUMBER, sequenceNumber)); order.add(new TLV(IBProt.CARD_HOLDER_DATA, cardHolder.getBytes())); signedMessage = new TLV(IBProt.SIGNED_MESSAGE, order); signedMessage.add(new TLV(IBProt.SIGNATURE, signatureBigInt.toByteArray())); clearText = new TLV(IBProt.CLEAR_MESSAGE, signedMessage.toBinary()); server.processRequestFrom("Eve", clearText.toBinary()); } } /************************************************************************** * Process a request coming in from the client. * * @param senderName - The name of the sender of this message * @param data - The message that has been received **************************************************************************/ public void processRequestFrom(String senderName, byte[] data) { this.data = data; if (intercepting) { TLV message = new TLV(data); if (message.tag().equals(IBProt.CLEAR_MESSAGE)) { encrypted = false; TLV signedMessage = new TLV(message.valueAsByteArray()); if (!signedMessage.tag().equals(IBProt.SIGNED_MESSAGE)) { System.err.println("IBEve - panic: SIGNED_MESSAGE tag not found"); System.exit(0); } TLV stockOrder = signedMessage.findTag(IBProt.STOCK_ORDER, null); if (stockOrder == null) { System.err.println("IBEve - panic: STOCK_ORDER tag not found"); System.exit(0); } byte[] order = stockOrder.toBinary(); TLV signature = signedMessage.findTag(IBProt.SIGNATURE, null); if (signature == null) { System.err.println("IBEve - panic: SIGNATURE tag not found"); System.exit(0); } sequenceNumber = (stockOrder.findTag(IBProt.SEQUENCE_NUMBER, null)).valueAsNumber(); number = (stockOrder.findTag(IBProt.NUMBER, null)).valueAsNumber(); price = new String((stockOrder.findTag(IBProt.PRICE, null)).valueAsByteArray()); company = new String((stockOrder.findTag(IBProt.COMPANY, null)).valueAsByteArray()); cardHolder = new String((stockOrder.findTag(IBProt.CARD_HOLDER_DATA, null)).valueAsByteArray()); signatureBigInt = new BigInteger(1, signature.valueAsByteArray()); dataField0.setText(Integer.toString(sequenceNumber)); dataField1.setText(Integer.toString(number)); dataField2.setText(price); dataField3.setText(company); cardHolderField.setText(cardHolder); signatureField.setText(signatureBigInt.toString()); } else { encrypted = true; dataField0.setText("???"); dataField1.setText("???"); dataField2.setText("???"); dataField3.setText("???"); cardHolderField.setText("???"); signatureField.setText("???"); } // TextFields become un-editable if data is encrypted, editable otherwise setEditable(!encrypted); } else { server.processRequestFrom("Client", data); } repaint(); } }
13,094
0.621368
0.610768
378
32.690475
26.913185
109
false
false
0
0
0
0
0
0
0.693122
false
false
1
bdf9e334c76afc469be077cb3aa2f82628598f69
1,511,828,526,424
6e44e10f515e7048e675ca530e58521b1dc2d911
/app/src/main/java/com/teamcube/rubricscube/Views/YellowFaceInputView.java
6ab4abdc0e44a0206624fd79f4feb5d343058304
[]
no_license
matthewWatson571/RubricsCube
https://github.com/matthewWatson571/RubricsCube
d4d741d126ff48be9cfbebe0d5a542c9ca0798a9
a1ef2643d8707b8289ef33f9d85dd60e6c5e1986
refs/heads/master
2020-07-17T20:56:36.206000
2016-11-28T14:10:40
2016-11-28T14:10:40
73,925,210
0
0
null
false
2016-11-27T22:38:42
2016-11-16T13:57:58
2016-11-16T14:38:06
2016-11-27T22:36:50
15,186
0
0
0
Java
null
null
package com.teamcube.rubricscube.Views; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.widget.Button; import android.widget.LinearLayout; import com.teamcube.rubricscube.R; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import static com.teamcube.rubricscube.Views.UserCubeInputView.D1; import static com.teamcube.rubricscube.Views.UserCubeInputView.D2; import static com.teamcube.rubricscube.Views.UserCubeInputView.D3; import static com.teamcube.rubricscube.Views.UserCubeInputView.D4; import static com.teamcube.rubricscube.Views.UserCubeInputView.D6; import static com.teamcube.rubricscube.Views.UserCubeInputView.D7; import static com.teamcube.rubricscube.Views.UserCubeInputView.D8; import static com.teamcube.rubricscube.Views.UserCubeInputView.D9; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow45Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow46Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow47Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow48Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow50Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow51Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow52Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow53Count; /** * Created by matthewsturgill on 11/20/16. */ public class YellowFaceInputView extends LinearLayout { private Context context; //Yellow @Bind(R.id.yellow01) Button yellow01; @Bind(R.id.yellow02) Button yellow02; @Bind(R.id.yellow03) Button yellow03; @Bind(R.id.yellow04) Button yellow04; @Bind(R.id.yellow05) Button yellow05; @Bind(R.id.yellow06) Button yellow06; @Bind(R.id.yellow07) Button yellow07; @Bind(R.id.yellow08) Button yellow08; @Bind(R.id.yellow09) Button yellow09; //Buttons for transitions @Bind(R.id.yellowTransitionToRed) Button yellowTransitionToRed; @Bind(R.id.yellowTransitionToBlue) Button yellowTransitionToBlue; @Bind(R.id.yellowTransitionToGreen) Button yellowTransitionToGreen; @Bind(R.id.yellowTransitionToOrange) Button yellowTransitionToOrange; public YellowFaceInputView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } @Override protected void onFinishInflate() { super.onFinishInflate(); ButterKnife.bind(this); //On inflate populates colors from expanded input switch (yellow45Count) { //orange case 0: yellow01.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow01.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow01.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow01.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow01.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow01.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow01.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow46Count) { //orange case 0: yellow02.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow02.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow02.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow02.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow02.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow02.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow02.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow47Count) { //orange case 0: yellow03.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow03.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow03.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow03.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow03.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow03.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow03.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow48Count) { //orange case 0: yellow04.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow04.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow04.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow04.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow04.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow04.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow04.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow50Count) { //orange case 0: yellow06.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow06.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow06.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow06.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow06.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow06.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow06.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow51Count) { //orange case 0: yellow07.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow07.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow07.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow07.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow07.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow07.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow07.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow52Count) { //orange case 0: yellow08.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow08.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow08.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow08.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow08.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow08.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow08.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow53Count) { //orange case 0: yellow09.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow09.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow09.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow09.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow09.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow09.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow09.setBackgroundColor(Color.argb(255, 191, 191, 191)); } } @OnClick(R.id.yellow01) public void yellow01() { yellow45Count++; if (yellow45Count < 6) { switch (yellow45Count) { //orange case 0: yellow01.setBackgroundColor(Color.argb(255, 255, 149, 0)); D1 = "F"; break; //green case 1: yellow01.setBackgroundColor(Color.argb(255, 41, 198, 60)); D1 = "R"; break; //white case 2: yellow01.setBackgroundColor(Color.argb(255, 255, 255, 255)); D1 = "U"; break; //red case 3: yellow01.setBackgroundColor(Color.argb(255, 255, 40, 40)); D1 = "B"; break; //blue case 4: yellow01.setBackgroundColor(Color.argb(255, 0, 0, 255)); D1 = "L"; break; //yellow case 5: yellow01.setBackgroundColor(Color.argb(255, 246, 255, 0)); D1 = "D"; break; } } else { yellow45Count = -1; yellow01.setBackgroundColor(Color.argb(255, 191, 191, 191)); D1 = ""; } } @OnClick(R.id.yellow02) public void yellow02() { yellow46Count++; if (yellow46Count < 6) { switch (yellow46Count) { //orange case 0: yellow02.setBackgroundColor(Color.argb(255, 255, 149, 0)); D2 = "F"; break; //green case 1: yellow02.setBackgroundColor(Color.argb(255, 41, 198, 60)); D2 = "R"; break; //white case 2: yellow02.setBackgroundColor(Color.argb(255, 255, 255, 255)); D2 = "U"; break; //red case 3: yellow02.setBackgroundColor(Color.argb(255, 255, 40, 40)); D2 = "B"; break; //blue case 4: yellow02.setBackgroundColor(Color.argb(255, 0, 0, 255)); D2 = "L"; break; //yellow case 5: yellow02.setBackgroundColor(Color.argb(255, 246, 255, 0)); D2 = "D"; break; } } else { yellow46Count = -1; yellow02.setBackgroundColor(Color.argb(255, 191, 191, 191)); D2 = ""; } } @OnClick(R.id.yellow03) public void yellow03() { yellow47Count++; if (yellow47Count < 6) { switch (yellow47Count) { //orange case 0: yellow03.setBackgroundColor(Color.argb(255, 255, 149, 0)); D3 = "F"; break; //green case 1: yellow03.setBackgroundColor(Color.argb(255, 41, 198, 60)); D3 = "R"; break; //white case 2: yellow03.setBackgroundColor(Color.argb(255, 255, 255, 255)); D3 = "U"; break; //red case 3: yellow03.setBackgroundColor(Color.argb(255, 255, 40, 40)); D3 = "B"; break; //blue case 4: yellow03.setBackgroundColor(Color.argb(255, 0, 0, 255)); D3 = "L"; break; //yellow case 5: yellow03.setBackgroundColor(Color.argb(255, 246, 255, 0)); D3 = "D"; break; } } else { yellow47Count = -1; yellow03.setBackgroundColor(Color.argb(255, 191, 191, 191)); D3 = ""; } } @OnClick(R.id.yellow04) public void yellow04() { yellow48Count++; if (yellow48Count < 6) { switch (yellow48Count) { //orange case 0: yellow04.setBackgroundColor(Color.argb(255, 255, 149, 0)); D4 = "F"; break; //green case 1: yellow04.setBackgroundColor(Color.argb(255, 41, 198, 60)); D4 = "R"; break; //white case 2: yellow04.setBackgroundColor(Color.argb(255, 255, 255, 255)); D4 = "U"; break; //red case 3: yellow04.setBackgroundColor(Color.argb(255, 255, 40, 40)); D4 = "B"; break; //blue case 4: yellow04.setBackgroundColor(Color.argb(255, 0, 0, 255)); D4 = "L"; break; //yellow case 5: yellow04.setBackgroundColor(Color.argb(255, 246, 255, 0)); D4 = "D"; break; } } else { yellow48Count = -1; yellow04.setBackgroundColor(Color.argb(255, 191, 191, 191)); D4 = ""; } } @OnClick(R.id.yellow05) public void yellow05() { //Finalized in UserCubeinputView; } @OnClick(R.id.yellow06) public void yellow06() { yellow50Count++; if (yellow50Count < 6) { switch (yellow50Count) { //orange case 0: yellow06.setBackgroundColor(Color.argb(255, 255, 149, 0)); D6 = "F"; break; //green case 1: yellow06.setBackgroundColor(Color.argb(255, 41, 198, 60)); D6 = "R"; break; //white case 2: yellow06.setBackgroundColor(Color.argb(255, 255, 255, 255)); D6 = "U"; break; //red case 3: yellow06.setBackgroundColor(Color.argb(255, 255, 40, 40)); D6 = "B"; break; //blue case 4: yellow06.setBackgroundColor(Color.argb(255, 0, 0, 255)); D6 = "L"; break; //yellow case 5: yellow06.setBackgroundColor(Color.argb(255, 246, 255, 0)); D6 = "D"; break; } } else { yellow50Count = -1; yellow06.setBackgroundColor(Color.argb(255, 191, 191, 191)); D6 = ""; } } @OnClick(R.id.yellow07) public void yellow07() { yellow51Count++; if (yellow51Count < 6) { switch (yellow51Count) { //orange case 0: yellow07.setBackgroundColor(Color.argb(255, 255, 149, 0)); D7 = "F"; break; //green case 1: yellow07.setBackgroundColor(Color.argb(255, 41, 198, 60)); D7 = "R"; break; //white case 2: yellow07.setBackgroundColor(Color.argb(255, 255, 255, 255)); D7 = "U"; break; //red case 3: yellow07.setBackgroundColor(Color.argb(255, 255, 40, 40)); D7 = "B"; break; //blue case 4: yellow07.setBackgroundColor(Color.argb(255, 0, 0, 255)); D7 = "L"; break; //yellow case 5: yellow07.setBackgroundColor(Color.argb(255, 246, 255, 0)); D7 = "D"; break; } } else { yellow51Count = -1; yellow07.setBackgroundColor(Color.argb(255, 191, 191, 191)); D7 = ""; } } @OnClick(R.id.yellow08) public void yellow08() { yellow52Count++; if (yellow52Count < 6) { switch (yellow52Count) { //orange case 0: yellow08.setBackgroundColor(Color.argb(255, 255, 149, 0)); D8 = "F"; break; //green case 1: yellow08.setBackgroundColor(Color.argb(255, 41, 198, 60)); D8 = "R"; break; //white case 2: yellow08.setBackgroundColor(Color.argb(255, 255, 255, 255)); D8 = "U"; break; //red case 3: yellow08.setBackgroundColor(Color.argb(255, 255, 40, 40)); D8 = "B"; break; //blue case 4: yellow08.setBackgroundColor(Color.argb(255, 0, 0, 255)); D8 = "L"; break; //yellow case 5: yellow08.setBackgroundColor(Color.argb(255, 246, 255, 0)); D8 = "D"; break; } } else { yellow52Count = -1; yellow08.setBackgroundColor(Color.argb(255, 191, 191, 191)); D8 = ""; } } @OnClick(R.id.yellow09) public void yellow09() { yellow53Count++; if (yellow53Count < 6) { switch (yellow53Count) { //orange case 0: yellow09.setBackgroundColor(Color.argb(255, 255, 149, 0)); D9 = "F"; break; //green case 1: yellow09.setBackgroundColor(Color.argb(255, 41, 198, 60)); D9 = "R"; break; //white case 2: yellow09.setBackgroundColor(Color.argb(255, 255, 255, 255)); D9 = "U"; break; //red case 3: yellow09.setBackgroundColor(Color.argb(255, 255, 40, 40)); D9 = "B"; break; //blue case 4: yellow09.setBackgroundColor(Color.argb(255, 0, 0, 255)); D9 = "L"; break; //yellow case 5: yellow09.setBackgroundColor(Color.argb(255, 246, 255, 0)); D9 = "D"; break; } } else { yellow53Count = -1; yellow09.setBackgroundColor(Color.argb(255, 191, 191, 191)); D9 = ""; } } //Transition buttons // @OnClick(R.id.yellowTransitionToBlue) // public void yellowTransitionToBlue(){ // Flow flow = RubricsCubeApplication.getMainFlow(); // History newHistory = flow.getHistory().buildUpon() // .push(new BlueFaceInputStage()) // .build(); // flow.setHistory(newHistory, Flow.Direction.REPLACE); // } // // @OnClick(R.id.yellowTransitionToGreen) // public void yellowTransitionToGreen(){ // Flow flow = RubricsCubeApplication.getMainFlow(); // History newHistory = flow.getHistory().buildUpon() // .push(new GreenFaceInputStage()) // .build(); // flow.setHistory(newHistory, Flow.Direction.REPLACE); // } // // @OnClick(R.id.yellowTransitionToRed) // public void yellowTransitionToRed(){ // Flow flow = RubricsCubeApplication.getMainFlow(); // History newHistory = flow.getHistory().buildUpon() // .push(new RedFaceInputStage()) // .build(); // flow.setHistory(newHistory, Flow.Direction.REPLACE); // } // // @OnClick(R.id.yellowTransitionToOrange) // public void yellowTransitionToOrange(){ // Flow flow = RubricsCubeApplication.getMainFlow(); // History newHistory = flow.getHistory().buildUpon() // .push(new OrangeFaceInputStage()) // .build(); // flow.setHistory(newHistory, Flow.Direction.REPLACE); // } }
UTF-8
Java
23,479
java
YellowFaceInputView.java
Java
[ { "context": "serCubeInputView.yellow53Count;\n\n/**\n * Created by matthewsturgill on 11/20/16.\n */\n\npublic class YellowFaceInputVie", "end": 1521, "score": 0.9983917474746704, "start": 1506, "tag": "USERNAME", "value": "matthewsturgill" } ]
null
[]
package com.teamcube.rubricscube.Views; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.widget.Button; import android.widget.LinearLayout; import com.teamcube.rubricscube.R; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import static com.teamcube.rubricscube.Views.UserCubeInputView.D1; import static com.teamcube.rubricscube.Views.UserCubeInputView.D2; import static com.teamcube.rubricscube.Views.UserCubeInputView.D3; import static com.teamcube.rubricscube.Views.UserCubeInputView.D4; import static com.teamcube.rubricscube.Views.UserCubeInputView.D6; import static com.teamcube.rubricscube.Views.UserCubeInputView.D7; import static com.teamcube.rubricscube.Views.UserCubeInputView.D8; import static com.teamcube.rubricscube.Views.UserCubeInputView.D9; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow45Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow46Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow47Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow48Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow50Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow51Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow52Count; import static com.teamcube.rubricscube.Views.UserCubeInputView.yellow53Count; /** * Created by matthewsturgill on 11/20/16. */ public class YellowFaceInputView extends LinearLayout { private Context context; //Yellow @Bind(R.id.yellow01) Button yellow01; @Bind(R.id.yellow02) Button yellow02; @Bind(R.id.yellow03) Button yellow03; @Bind(R.id.yellow04) Button yellow04; @Bind(R.id.yellow05) Button yellow05; @Bind(R.id.yellow06) Button yellow06; @Bind(R.id.yellow07) Button yellow07; @Bind(R.id.yellow08) Button yellow08; @Bind(R.id.yellow09) Button yellow09; //Buttons for transitions @Bind(R.id.yellowTransitionToRed) Button yellowTransitionToRed; @Bind(R.id.yellowTransitionToBlue) Button yellowTransitionToBlue; @Bind(R.id.yellowTransitionToGreen) Button yellowTransitionToGreen; @Bind(R.id.yellowTransitionToOrange) Button yellowTransitionToOrange; public YellowFaceInputView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } @Override protected void onFinishInflate() { super.onFinishInflate(); ButterKnife.bind(this); //On inflate populates colors from expanded input switch (yellow45Count) { //orange case 0: yellow01.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow01.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow01.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow01.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow01.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow01.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow01.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow46Count) { //orange case 0: yellow02.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow02.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow02.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow02.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow02.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow02.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow02.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow47Count) { //orange case 0: yellow03.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow03.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow03.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow03.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow03.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow03.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow03.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow48Count) { //orange case 0: yellow04.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow04.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow04.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow04.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow04.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow04.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow04.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow50Count) { //orange case 0: yellow06.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow06.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow06.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow06.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow06.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow06.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow06.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow51Count) { //orange case 0: yellow07.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow07.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow07.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow07.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow07.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow07.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow07.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow52Count) { //orange case 0: yellow08.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow08.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow08.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow08.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow08.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow08.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow08.setBackgroundColor(Color.argb(255, 191, 191, 191)); } switch (yellow53Count) { //orange case 0: yellow09.setBackgroundColor(Color.argb(255, 255, 149, 0)); break; //green case 1: yellow09.setBackgroundColor(Color.argb(255, 41, 198, 60)); break; //white case 2: yellow09.setBackgroundColor(Color.argb(255, 255, 255, 255)); break; //red case 3: yellow09.setBackgroundColor(Color.argb(255, 255, 40, 40)); break; //blue case 4: yellow09.setBackgroundColor(Color.argb(255, 0, 0, 255)); break; //yellow case 5: yellow09.setBackgroundColor(Color.argb(255, 246, 255, 0)); break; default: yellow09.setBackgroundColor(Color.argb(255, 191, 191, 191)); } } @OnClick(R.id.yellow01) public void yellow01() { yellow45Count++; if (yellow45Count < 6) { switch (yellow45Count) { //orange case 0: yellow01.setBackgroundColor(Color.argb(255, 255, 149, 0)); D1 = "F"; break; //green case 1: yellow01.setBackgroundColor(Color.argb(255, 41, 198, 60)); D1 = "R"; break; //white case 2: yellow01.setBackgroundColor(Color.argb(255, 255, 255, 255)); D1 = "U"; break; //red case 3: yellow01.setBackgroundColor(Color.argb(255, 255, 40, 40)); D1 = "B"; break; //blue case 4: yellow01.setBackgroundColor(Color.argb(255, 0, 0, 255)); D1 = "L"; break; //yellow case 5: yellow01.setBackgroundColor(Color.argb(255, 246, 255, 0)); D1 = "D"; break; } } else { yellow45Count = -1; yellow01.setBackgroundColor(Color.argb(255, 191, 191, 191)); D1 = ""; } } @OnClick(R.id.yellow02) public void yellow02() { yellow46Count++; if (yellow46Count < 6) { switch (yellow46Count) { //orange case 0: yellow02.setBackgroundColor(Color.argb(255, 255, 149, 0)); D2 = "F"; break; //green case 1: yellow02.setBackgroundColor(Color.argb(255, 41, 198, 60)); D2 = "R"; break; //white case 2: yellow02.setBackgroundColor(Color.argb(255, 255, 255, 255)); D2 = "U"; break; //red case 3: yellow02.setBackgroundColor(Color.argb(255, 255, 40, 40)); D2 = "B"; break; //blue case 4: yellow02.setBackgroundColor(Color.argb(255, 0, 0, 255)); D2 = "L"; break; //yellow case 5: yellow02.setBackgroundColor(Color.argb(255, 246, 255, 0)); D2 = "D"; break; } } else { yellow46Count = -1; yellow02.setBackgroundColor(Color.argb(255, 191, 191, 191)); D2 = ""; } } @OnClick(R.id.yellow03) public void yellow03() { yellow47Count++; if (yellow47Count < 6) { switch (yellow47Count) { //orange case 0: yellow03.setBackgroundColor(Color.argb(255, 255, 149, 0)); D3 = "F"; break; //green case 1: yellow03.setBackgroundColor(Color.argb(255, 41, 198, 60)); D3 = "R"; break; //white case 2: yellow03.setBackgroundColor(Color.argb(255, 255, 255, 255)); D3 = "U"; break; //red case 3: yellow03.setBackgroundColor(Color.argb(255, 255, 40, 40)); D3 = "B"; break; //blue case 4: yellow03.setBackgroundColor(Color.argb(255, 0, 0, 255)); D3 = "L"; break; //yellow case 5: yellow03.setBackgroundColor(Color.argb(255, 246, 255, 0)); D3 = "D"; break; } } else { yellow47Count = -1; yellow03.setBackgroundColor(Color.argb(255, 191, 191, 191)); D3 = ""; } } @OnClick(R.id.yellow04) public void yellow04() { yellow48Count++; if (yellow48Count < 6) { switch (yellow48Count) { //orange case 0: yellow04.setBackgroundColor(Color.argb(255, 255, 149, 0)); D4 = "F"; break; //green case 1: yellow04.setBackgroundColor(Color.argb(255, 41, 198, 60)); D4 = "R"; break; //white case 2: yellow04.setBackgroundColor(Color.argb(255, 255, 255, 255)); D4 = "U"; break; //red case 3: yellow04.setBackgroundColor(Color.argb(255, 255, 40, 40)); D4 = "B"; break; //blue case 4: yellow04.setBackgroundColor(Color.argb(255, 0, 0, 255)); D4 = "L"; break; //yellow case 5: yellow04.setBackgroundColor(Color.argb(255, 246, 255, 0)); D4 = "D"; break; } } else { yellow48Count = -1; yellow04.setBackgroundColor(Color.argb(255, 191, 191, 191)); D4 = ""; } } @OnClick(R.id.yellow05) public void yellow05() { //Finalized in UserCubeinputView; } @OnClick(R.id.yellow06) public void yellow06() { yellow50Count++; if (yellow50Count < 6) { switch (yellow50Count) { //orange case 0: yellow06.setBackgroundColor(Color.argb(255, 255, 149, 0)); D6 = "F"; break; //green case 1: yellow06.setBackgroundColor(Color.argb(255, 41, 198, 60)); D6 = "R"; break; //white case 2: yellow06.setBackgroundColor(Color.argb(255, 255, 255, 255)); D6 = "U"; break; //red case 3: yellow06.setBackgroundColor(Color.argb(255, 255, 40, 40)); D6 = "B"; break; //blue case 4: yellow06.setBackgroundColor(Color.argb(255, 0, 0, 255)); D6 = "L"; break; //yellow case 5: yellow06.setBackgroundColor(Color.argb(255, 246, 255, 0)); D6 = "D"; break; } } else { yellow50Count = -1; yellow06.setBackgroundColor(Color.argb(255, 191, 191, 191)); D6 = ""; } } @OnClick(R.id.yellow07) public void yellow07() { yellow51Count++; if (yellow51Count < 6) { switch (yellow51Count) { //orange case 0: yellow07.setBackgroundColor(Color.argb(255, 255, 149, 0)); D7 = "F"; break; //green case 1: yellow07.setBackgroundColor(Color.argb(255, 41, 198, 60)); D7 = "R"; break; //white case 2: yellow07.setBackgroundColor(Color.argb(255, 255, 255, 255)); D7 = "U"; break; //red case 3: yellow07.setBackgroundColor(Color.argb(255, 255, 40, 40)); D7 = "B"; break; //blue case 4: yellow07.setBackgroundColor(Color.argb(255, 0, 0, 255)); D7 = "L"; break; //yellow case 5: yellow07.setBackgroundColor(Color.argb(255, 246, 255, 0)); D7 = "D"; break; } } else { yellow51Count = -1; yellow07.setBackgroundColor(Color.argb(255, 191, 191, 191)); D7 = ""; } } @OnClick(R.id.yellow08) public void yellow08() { yellow52Count++; if (yellow52Count < 6) { switch (yellow52Count) { //orange case 0: yellow08.setBackgroundColor(Color.argb(255, 255, 149, 0)); D8 = "F"; break; //green case 1: yellow08.setBackgroundColor(Color.argb(255, 41, 198, 60)); D8 = "R"; break; //white case 2: yellow08.setBackgroundColor(Color.argb(255, 255, 255, 255)); D8 = "U"; break; //red case 3: yellow08.setBackgroundColor(Color.argb(255, 255, 40, 40)); D8 = "B"; break; //blue case 4: yellow08.setBackgroundColor(Color.argb(255, 0, 0, 255)); D8 = "L"; break; //yellow case 5: yellow08.setBackgroundColor(Color.argb(255, 246, 255, 0)); D8 = "D"; break; } } else { yellow52Count = -1; yellow08.setBackgroundColor(Color.argb(255, 191, 191, 191)); D8 = ""; } } @OnClick(R.id.yellow09) public void yellow09() { yellow53Count++; if (yellow53Count < 6) { switch (yellow53Count) { //orange case 0: yellow09.setBackgroundColor(Color.argb(255, 255, 149, 0)); D9 = "F"; break; //green case 1: yellow09.setBackgroundColor(Color.argb(255, 41, 198, 60)); D9 = "R"; break; //white case 2: yellow09.setBackgroundColor(Color.argb(255, 255, 255, 255)); D9 = "U"; break; //red case 3: yellow09.setBackgroundColor(Color.argb(255, 255, 40, 40)); D9 = "B"; break; //blue case 4: yellow09.setBackgroundColor(Color.argb(255, 0, 0, 255)); D9 = "L"; break; //yellow case 5: yellow09.setBackgroundColor(Color.argb(255, 246, 255, 0)); D9 = "D"; break; } } else { yellow53Count = -1; yellow09.setBackgroundColor(Color.argb(255, 191, 191, 191)); D9 = ""; } } //Transition buttons // @OnClick(R.id.yellowTransitionToBlue) // public void yellowTransitionToBlue(){ // Flow flow = RubricsCubeApplication.getMainFlow(); // History newHistory = flow.getHistory().buildUpon() // .push(new BlueFaceInputStage()) // .build(); // flow.setHistory(newHistory, Flow.Direction.REPLACE); // } // // @OnClick(R.id.yellowTransitionToGreen) // public void yellowTransitionToGreen(){ // Flow flow = RubricsCubeApplication.getMainFlow(); // History newHistory = flow.getHistory().buildUpon() // .push(new GreenFaceInputStage()) // .build(); // flow.setHistory(newHistory, Flow.Direction.REPLACE); // } // // @OnClick(R.id.yellowTransitionToRed) // public void yellowTransitionToRed(){ // Flow flow = RubricsCubeApplication.getMainFlow(); // History newHistory = flow.getHistory().buildUpon() // .push(new RedFaceInputStage()) // .build(); // flow.setHistory(newHistory, Flow.Direction.REPLACE); // } // // @OnClick(R.id.yellowTransitionToOrange) // public void yellowTransitionToOrange(){ // Flow flow = RubricsCubeApplication.getMainFlow(); // History newHistory = flow.getHistory().buildUpon() // .push(new OrangeFaceInputStage()) // .build(); // flow.setHistory(newHistory, Flow.Direction.REPLACE); // } }
23,479
0.458367
0.384855
705
32.303547
22.527369
80
false
false
0
0
0
0
0
0
0.963121
false
false
1
7a79ca429fa6305d17f67a323dd5b13c54b92740
15,307,263,450,847
f68723eaf238de57c0c057b49cb956dedd8e4a60
/AndroidNetInf/src/android/netinf/node/services/http/HttpSearchService.java
d4c4d0ab9627574a4b4509eba4002cb76d385eed
[ "Apache-2.0" ]
permissive
lhc180/android-netinf
https://github.com/lhc180/android-netinf
9e8043f7d62d250064ab83359953b866f9b7c97b
56650b80bededc9e41f5680c17df409f856f9c33
refs/heads/master
2021-01-21T02:30:46.963000
2013-06-18T14:16:06
2013-06-18T14:16:06
10,912,036
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package android.netinf.node.services.http; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.RandomStringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.netinf.common.Metadata; import android.netinf.common.Ndo; import android.netinf.common.NetInfException; import android.netinf.messages.Search; import android.netinf.messages.SearchResponse; import android.netinf.node.search.SearchService; import android.util.Log; public class HttpSearchService implements SearchService { public static final String TAG = HttpSearchService.class.getSimpleName(); public static final int TIMEOUT = 1000; @Override public SearchResponse perform(Search search) { Log.i(TAG, "HTTP SEARCH " + search); // HTTP Client HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT); HttpConnectionParams.setSoTimeout(params, TIMEOUT); HttpClient client = new DefaultHttpClient(params); Set<Ndo> results = new LinkedHashSet<Ndo>(); for (String peer : HttpCommon.getPeers()) { try { HttpResponse response = client.execute(createSearch(peer, search)); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { results.addAll(parse(response)); } else { Log.e(TAG, "SEARCH to " + peer + " failed: " + status); } } catch (ClientProtocolException e) { Log.e(TAG, "SEARCH to " + peer + " failed", e); } catch (UnsupportedEncodingException e) { Log.e(TAG, "SEARCH to " + peer + " failed", e); } catch (IOException e) { Log.e(TAG, "SEARCH to " + peer + " failed", e); } catch (NetInfException e) { Log.e(TAG, "SEARCH to " + peer + " failed", e); } } return new SearchResponse.Builder(search).addResults(results).build(); } private HttpPost createSearch(String peer, Search search) throws UnsupportedEncodingException { HttpPost post = new HttpPost(peer + "/netinfproto/search"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); StringBuilder builder = new StringBuilder(); builder.append("?msgid="); builder.append(RandomStringUtils.randomAlphanumeric(20)); builder.append("&tokens="); builder.append(createTokens(search.getTokens())); HttpEntity entity = new StringEntity(builder.toString(), "UTF-8"); post.setEntity(entity); return post; } private String createTokens(Set<String> tokens) { StringBuilder builder = new StringBuilder(); for (String token : tokens) { builder.append(token); builder.append(" "); } return builder.toString().trim(); } private Set<Ndo> parse(HttpResponse response) throws NetInfException { Set<Ndo> ndos = new LinkedHashSet<Ndo>(); // Get Results HttpEntity entity = HttpCommon.getEntity(response); InputStream content = HttpCommon.getContent(entity); String json = HttpCommon.getJson(content); JSONObject jo = HttpCommon.parseJson(json); JSONArray results = null; try { results = jo.getJSONArray("results"); Log.d(TAG, results.toString(4)); } catch (JSONException e) { throw new NetInfException("Failed to parse results", e); } // Results to NDO(s) for (int i = 0; i < results.length(); i++) { try { JSONObject result = results.getJSONObject(i); String algorithm = getAlgorithm(result); String hash = getHash(result); String metadata = getMetadata(result); Ndo ndo = new Ndo.Builder(algorithm, hash).metadata(new Metadata(metadata)).build(); ndos.add(ndo); } catch (JSONException e) { Log.w(TAG, "Failed to parse result", e); } } return ndos; } private String getAlgorithm(JSONObject jo) throws JSONException { String ni = jo.getString("ni"); Pattern pattern = Pattern.compile("/(.*?);"); Matcher matcher = pattern.matcher(ni); if (matcher.find()) { return matcher.group(1); } else { throw new JSONException("Failed to parse hash algorithm"); } } private String getHash(JSONObject jo) throws JSONException { String ni = jo.getString("ni"); Pattern pattern = Pattern.compile(";(.*?)$"); Matcher matcher = pattern.matcher(ni); if (matcher.find()) { return matcher.group(1); } else { throw new JSONException("Failed to parse hash"); } } private String getMetadata(JSONObject jo) throws JSONException { String metadata = jo.getString("metadata"); return metadata.toString(); } }
UTF-8
Java
5,844
java
HttpSearchService.java
Java
[]
null
[]
package android.netinf.node.services.http; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.RandomStringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.netinf.common.Metadata; import android.netinf.common.Ndo; import android.netinf.common.NetInfException; import android.netinf.messages.Search; import android.netinf.messages.SearchResponse; import android.netinf.node.search.SearchService; import android.util.Log; public class HttpSearchService implements SearchService { public static final String TAG = HttpSearchService.class.getSimpleName(); public static final int TIMEOUT = 1000; @Override public SearchResponse perform(Search search) { Log.i(TAG, "HTTP SEARCH " + search); // HTTP Client HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT); HttpConnectionParams.setSoTimeout(params, TIMEOUT); HttpClient client = new DefaultHttpClient(params); Set<Ndo> results = new LinkedHashSet<Ndo>(); for (String peer : HttpCommon.getPeers()) { try { HttpResponse response = client.execute(createSearch(peer, search)); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { results.addAll(parse(response)); } else { Log.e(TAG, "SEARCH to " + peer + " failed: " + status); } } catch (ClientProtocolException e) { Log.e(TAG, "SEARCH to " + peer + " failed", e); } catch (UnsupportedEncodingException e) { Log.e(TAG, "SEARCH to " + peer + " failed", e); } catch (IOException e) { Log.e(TAG, "SEARCH to " + peer + " failed", e); } catch (NetInfException e) { Log.e(TAG, "SEARCH to " + peer + " failed", e); } } return new SearchResponse.Builder(search).addResults(results).build(); } private HttpPost createSearch(String peer, Search search) throws UnsupportedEncodingException { HttpPost post = new HttpPost(peer + "/netinfproto/search"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); StringBuilder builder = new StringBuilder(); builder.append("?msgid="); builder.append(RandomStringUtils.randomAlphanumeric(20)); builder.append("&tokens="); builder.append(createTokens(search.getTokens())); HttpEntity entity = new StringEntity(builder.toString(), "UTF-8"); post.setEntity(entity); return post; } private String createTokens(Set<String> tokens) { StringBuilder builder = new StringBuilder(); for (String token : tokens) { builder.append(token); builder.append(" "); } return builder.toString().trim(); } private Set<Ndo> parse(HttpResponse response) throws NetInfException { Set<Ndo> ndos = new LinkedHashSet<Ndo>(); // Get Results HttpEntity entity = HttpCommon.getEntity(response); InputStream content = HttpCommon.getContent(entity); String json = HttpCommon.getJson(content); JSONObject jo = HttpCommon.parseJson(json); JSONArray results = null; try { results = jo.getJSONArray("results"); Log.d(TAG, results.toString(4)); } catch (JSONException e) { throw new NetInfException("Failed to parse results", e); } // Results to NDO(s) for (int i = 0; i < results.length(); i++) { try { JSONObject result = results.getJSONObject(i); String algorithm = getAlgorithm(result); String hash = getHash(result); String metadata = getMetadata(result); Ndo ndo = new Ndo.Builder(algorithm, hash).metadata(new Metadata(metadata)).build(); ndos.add(ndo); } catch (JSONException e) { Log.w(TAG, "Failed to parse result", e); } } return ndos; } private String getAlgorithm(JSONObject jo) throws JSONException { String ni = jo.getString("ni"); Pattern pattern = Pattern.compile("/(.*?);"); Matcher matcher = pattern.matcher(ni); if (matcher.find()) { return matcher.group(1); } else { throw new JSONException("Failed to parse hash algorithm"); } } private String getHash(JSONObject jo) throws JSONException { String ni = jo.getString("ni"); Pattern pattern = Pattern.compile(";(.*?)$"); Matcher matcher = pattern.matcher(ni); if (matcher.find()) { return matcher.group(1); } else { throw new JSONException("Failed to parse hash"); } } private String getMetadata(JSONObject jo) throws JSONException { String metadata = jo.getString("metadata"); return metadata.toString(); } }
5,844
0.630048
0.627995
168
33.785713
24.584921
100
false
false
0
0
0
0
0
0
0.684524
false
false
1
a6f238316f9942df587a4bb27bb12063a3641f93
20,538,533,616,492
35a0ced02ee16bf0fe59adba0488e716c26e5cfb
/src/main/java/vn/com/multiplechoice/business/service/impl/UserRequestServiceImpl.java
5faa1eae178b5aa9e8d0f9a1a0b3ff56b7c278ba
[]
no_license
AnhNguyen92/NganHangTracNghiem
https://github.com/AnhNguyen92/NganHangTracNghiem
5b2fc6adbc48808c2f40592970786a9fddd364d5
fd48a6a6f884e4fb4287e6e9a8df57121ca0ff5e
refs/heads/master
2022-10-25T15:42:24.539000
2022-10-05T04:18:29
2022-10-05T04:18:29
245,146,205
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package vn.com.multiplechoice.business.service.impl; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import vn.com.multiplechoice.business.service.AbstractService; import vn.com.multiplechoice.business.service.UserRequestService; import vn.com.multiplechoice.dao.criteria.UserRequestCriteria; import vn.com.multiplechoice.dao.model.UserRequest; import vn.com.multiplechoice.dao.repository.UserRequestRepository; @Service @Transactional public class UserRequestServiceImpl extends AbstractService<UserRequest, Long> implements UserRequestService { private EntityManager em; private UserRequestRepository userRequestRepository; @Autowired public UserRequestServiceImpl(EntityManager em, UserRequestRepository userRequestRepository) { super(userRequestRepository); this.userRequestRepository = userRequestRepository; this.em = em; } @Override public List<UserRequest> findAll(UserRequestCriteria criteria) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<UserRequest> criteriaQuery = cb.createQuery(UserRequest.class); Root<UserRequest> root = criteriaQuery.from(UserRequest.class); List<Predicate> predicates = new ArrayList<>(); Predicate onStartPredicate = cb.greaterThanOrEqualTo(root.get("createDate"), criteria.getDateRange().getFromDate()); Predicate onEndPredicate = cb.lessThanOrEqualTo(root.get("createDate"), criteria.getDateRange().getToDate()); predicates.add(onStartPredicate); predicates.add(onEndPredicate); if (criteria.getStatus() != null) { Predicate statusPredicate = cb.equal(root.get("status"), criteria.getStatus()); predicates.add(statusPredicate); } criteriaQuery.where(cb.and(predicates.toArray(new Predicate[0]))); TypedQuery<UserRequest> query = em.createQuery(criteriaQuery); return query.getResultList(); } }
UTF-8
Java
2,224
java
UserRequestServiceImpl.java
Java
[]
null
[]
package vn.com.multiplechoice.business.service.impl; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import vn.com.multiplechoice.business.service.AbstractService; import vn.com.multiplechoice.business.service.UserRequestService; import vn.com.multiplechoice.dao.criteria.UserRequestCriteria; import vn.com.multiplechoice.dao.model.UserRequest; import vn.com.multiplechoice.dao.repository.UserRequestRepository; @Service @Transactional public class UserRequestServiceImpl extends AbstractService<UserRequest, Long> implements UserRequestService { private EntityManager em; private UserRequestRepository userRequestRepository; @Autowired public UserRequestServiceImpl(EntityManager em, UserRequestRepository userRequestRepository) { super(userRequestRepository); this.userRequestRepository = userRequestRepository; this.em = em; } @Override public List<UserRequest> findAll(UserRequestCriteria criteria) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<UserRequest> criteriaQuery = cb.createQuery(UserRequest.class); Root<UserRequest> root = criteriaQuery.from(UserRequest.class); List<Predicate> predicates = new ArrayList<>(); Predicate onStartPredicate = cb.greaterThanOrEqualTo(root.get("createDate"), criteria.getDateRange().getFromDate()); Predicate onEndPredicate = cb.lessThanOrEqualTo(root.get("createDate"), criteria.getDateRange().getToDate()); predicates.add(onStartPredicate); predicates.add(onEndPredicate); if (criteria.getStatus() != null) { Predicate statusPredicate = cb.equal(root.get("status"), criteria.getStatus()); predicates.add(statusPredicate); } criteriaQuery.where(cb.and(predicates.toArray(new Predicate[0]))); TypedQuery<UserRequest> query = em.createQuery(criteriaQuery); return query.getResultList(); } }
2,224
0.814748
0.814299
57
38.017544
29.300316
111
false
false
0
0
0
0
0
0
1.596491
false
false
1
29fea424fd5829cd3ab53565eb04125eccaa5fff
23,313,082,487,590
b38ae840f80cad6cde835bf3f5d6547d2cf5913d
/app/src/main/java/com/example/dell/attendit/Adapters/ScheduleAdapter.java
339c561fb7d9d5b39401e95e143b1d4cb4560379
[]
no_license
anjnerajat/AttendIt
https://github.com/anjnerajat/AttendIt
900762640e005e8340fcb6cace0291137d88e0b9
19033cb787fc8552247f76120a4745df3c6b1b62
refs/heads/master
2021-01-21T22:22:01.842000
2017-09-09T14:23:59
2017-09-09T14:23:59
102,153,625
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.dell.attendit.Adapters; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.example.dell.attendit.Classes.CircleDisplay; import com.example.dell.attendit.Classes.ExtraDB; import com.example.dell.attendit.Classes.Subject; import com.example.dell.attendit.Classes.SubjectsDB; import com.example.dell.attendit.Classes.Timetable; import com.example.dell.attendit.Classes.TimetableDB; import com.example.dell.attendit.R; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class ScheduleAdapter extends RecyclerView.Adapter<ScheduleAdapter.MyViewHolder>{ private List<Subject> eventslist = new ArrayList<>(); public List<Timetable> todayslist = new ArrayList<>(); Context context; ScheduleAdapter mAdapter; RecyclerView recyclerView; SubjectsDB subjectsDB; TimetableDB timetableDB; ExtraDB extraDB; private int expandedPosition = -1; public class MyViewHolder extends RecyclerView.ViewHolder{ public TextView title, present, total, absent, cancelled; public ImageView absentButton, presentButton, cancelButton, statusImage; public CircleDisplay mCircleDisplay; public RelativeLayout expandablePanel; public MyViewHolder(View view){ super(view); title=(TextView)view.findViewById(R.id.subject_title); present=(TextView)view.findViewById(R.id.present); total=(TextView)view.findViewById(R.id.total); absent=(TextView)view.findViewById(R.id.absent); cancelled=(TextView)view.findViewById(R.id.cancelled); //percentage=(TextView)view.findViewById(R.id.percentage); presentButton = (ImageView)view.findViewById(R.id.presentButton); absentButton = (ImageView)view.findViewById(R.id.absentButton); cancelButton = (ImageView)view.findViewById(R.id.cancelButton); statusImage = (ImageView)view.findViewById(R.id.statusImage); mCircleDisplay = (CircleDisplay)view.findViewById(R.id.circleDisplay); expandablePanel = (RelativeLayout)view.findViewById(R.id.expandablePanel); } } public ScheduleAdapter(List<Subject> eventslist,Context context,RecyclerView recyclerView){ this.eventslist=eventslist; this.context=context; this.recyclerView=recyclerView; subjectsDB=new SubjectsDB(context); } public MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType){ View itemView= LayoutInflater.from(parent.getContext()).inflate(R.layout.schedule_list_row, parent, false); return new MyViewHolder(itemView); } public void onBindViewHolder(final MyViewHolder holder, final int position) { final Subject movie = eventslist.get(position); holder.title.setText(movie.getName()); holder.present.setText("Present=" + movie.getPresent() + ""); holder.total.setText("Total=" + movie.getTotal() + ""); holder.absent.setText("Absent=" + movie.getAbsent() + ""); holder.cancelled.setText("Cancel=" + movie.getCancelled() + ""); if(movie.getStatus() == 0){ holder.statusImage.setImageResource(R.drawable.roundedinfobutton); } else if(movie.getStatus() == 1){ holder.statusImage.setImageResource(R.drawable.checkmarkbutton); } else if(movie.getStatus() == 2){ holder.statusImage.setImageResource(R.drawable.deletebutton); } else if(movie.getStatus() == 3){ holder.statusImage.setImageResource(R.drawable.disabled); } //holder.percentage.setText(String.format("Percentage = %02.1f", movie.getPercentage() )); if (position == expandedPosition) { holder.expandablePanel.setVisibility(View.VISIBLE); holder.statusImage.setVisibility(View.GONE); } else { holder.expandablePanel.setVisibility(View.GONE); holder.statusImage.setVisibility(View.VISIBLE); } holder.statusImage.setOnClickListener( new ImageView.OnClickListener() { public void onClick(View view) { // Check for an expanded view, collapse if you find one if (expandedPosition >= 0) { int prev = expandedPosition; notifyItemChanged(prev); } // Set the current position to "expanded" expandedPosition = position; notifyItemChanged(expandedPosition); //Toast.makeText(context, "Clicked: ", Toast.LENGTH_SHORT).show(); } } ); holder.presentButton.setOnClickListener( new ImageView.OnClickListener() { public void onClick(View view) { //subjectsDB.isPresent(movie.getName()); subjectsDB.setStatus(movie.getName(), 1); setUpSubjectList(); } } ); holder.absentButton.setOnClickListener( new ImageView.OnClickListener(){ public void onClick(View view){ //subjectsDB.isAbsent(movie.getName()); subjectsDB.setStatus(movie.getName(), 2); setUpSubjectList(); } } ); holder.cancelButton.setOnClickListener( new ImageView.OnClickListener() { public void onClick(View view) { //subjectsDB.isCancel(movie.getName()); subjectsDB.setStatus(movie.getName(), 3); setUpSubjectList(); } } ); holder.mCircleDisplay.setAnimDuration(0); holder.mCircleDisplay.setValueWidthPercent(25f); holder.mCircleDisplay.setFormatDigits(1); holder.mCircleDisplay.setDimAlpha(100); if(movie.getPercentage()<movie.getMinimum()){ holder.mCircleDisplay.setColor(Color.rgb(227,0,34)); } else{ holder.mCircleDisplay.setColor(Color.rgb(70,210,70)); } holder.mCircleDisplay.setTouchEnabled(false); holder.mCircleDisplay.setUnit("%"); holder.mCircleDisplay.setStepSize(20.0f); holder.mCircleDisplay.setTextSize(15.0f); holder.mCircleDisplay.showValue((float)movie.getPercentage(), 100f, true); } /* public void deleteSubject(final String name){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set dialog message alertDialogBuilder .setCancelable(true).setMessage("Are you sure you want to delete " + name + "?") .setPositiveButton("DELETE", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { subjectsDB.deleteSubject(name); setUpSubjectList(); } }) .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } public void editSubject(final String name, int minimum){ LayoutInflater li = LayoutInflater.from(context); View promptsView = li.inflate(R.layout.edit_subject_prompt, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setView(promptsView); final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput); final SeekBar seekBar = (SeekBar) promptsView.findViewById(R.id.minimum_seekbar); final TextView seekvalue = (TextView) promptsView.findViewById(R.id.minimum_seek_value); userInput.setText(name); seekvalue.setText(minimum+"%"); seekBar.setProgress(minimum); seekBar.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener(){ int value = 0; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { value = progress; seekvalue.setText(value+"%"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { seekvalue.setText(value+"%"); } } ); // set dialog message alertDialogBuilder .setCancelable(true).setTitle("Edit Subject") .setPositiveButton("EDIT", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String addedSubjectName; if (!userInput.getText().toString().equals("") || seekBar.getProgress()==0) { addedSubjectName = userInput.getText().toString(); if(!subjectsDB.isSubjectPresent(addedSubjectName) || addedSubjectName.equals(name)){ subjectsDB.editSubject(name,addedSubjectName,seekBar.getProgress()); setUpSubjectList(); //workshopList = subjectsDB.getAllSubjects(); //mAdapter.notifyDataSetChanged(); } else{ Toast.makeText(context, addedSubjectName + " already in Subjects list", Toast.LENGTH_SHORT).show(); } //workshopList.add(new Subject(addedSubjectName, seekBar.getProgress())); //mAdapter.notifyDataSetChanged(); } else{ Toast.makeText(context,"Required feilds missing", Toast.LENGTH_SHORT).show(); } } }) .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } */ public void setUpSubjectList(){ Calendar calendar = Calendar.getInstance(); subjectsDB = new SubjectsDB(context); timetableDB = new TimetableDB(context); extraDB = new ExtraDB(context); int day = calendar.get(Calendar.DAY_OF_WEEK); switch (day) { case Calendar.SUNDAY: todayslist = timetableDB.getAllTimeTable("sunday"); break; case Calendar.MONDAY: todayslist = timetableDB.getAllTimeTable("monday"); break; case Calendar.TUESDAY: todayslist = timetableDB.getAllTimeTable("tuesday"); break; case Calendar.WEDNESDAY: todayslist = timetableDB.getAllTimeTable("wednesday"); break; case Calendar.THURSDAY: todayslist = timetableDB.getAllTimeTable("thursday"); break; case Calendar.FRIDAY: todayslist = timetableDB.getAllTimeTable("friday"); break; case Calendar.SATURDAY: todayslist = timetableDB.getAllTimeTable("saturday"); break; } eventslist = new ArrayList<>(); for(int i=0; i<todayslist.size(); i++){ Timetable timetable = todayslist.get(i); Subject subject = subjectsDB.getSubjectDetails(timetable.getName()); eventslist.add(subject); } if(extraDB.numberOfRows() != 0){ List<Timetable> extrasList = extraDB.getAllExtras(); for(int i=0; i<extrasList.size(); i++){ Timetable extra = extrasList.get(i); Subject subject = subjectsDB.getSubjectDetails(extra.getName()); eventslist.add(subject); } } mAdapter= new ScheduleAdapter(eventslist,context,recyclerView); recyclerView.setAdapter(mAdapter); } public int getItemCount(){ return eventslist.size(); } }
UTF-8
Java
14,204
java
ScheduleAdapter.java
Java
[]
null
[]
package com.example.dell.attendit.Adapters; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.example.dell.attendit.Classes.CircleDisplay; import com.example.dell.attendit.Classes.ExtraDB; import com.example.dell.attendit.Classes.Subject; import com.example.dell.attendit.Classes.SubjectsDB; import com.example.dell.attendit.Classes.Timetable; import com.example.dell.attendit.Classes.TimetableDB; import com.example.dell.attendit.R; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class ScheduleAdapter extends RecyclerView.Adapter<ScheduleAdapter.MyViewHolder>{ private List<Subject> eventslist = new ArrayList<>(); public List<Timetable> todayslist = new ArrayList<>(); Context context; ScheduleAdapter mAdapter; RecyclerView recyclerView; SubjectsDB subjectsDB; TimetableDB timetableDB; ExtraDB extraDB; private int expandedPosition = -1; public class MyViewHolder extends RecyclerView.ViewHolder{ public TextView title, present, total, absent, cancelled; public ImageView absentButton, presentButton, cancelButton, statusImage; public CircleDisplay mCircleDisplay; public RelativeLayout expandablePanel; public MyViewHolder(View view){ super(view); title=(TextView)view.findViewById(R.id.subject_title); present=(TextView)view.findViewById(R.id.present); total=(TextView)view.findViewById(R.id.total); absent=(TextView)view.findViewById(R.id.absent); cancelled=(TextView)view.findViewById(R.id.cancelled); //percentage=(TextView)view.findViewById(R.id.percentage); presentButton = (ImageView)view.findViewById(R.id.presentButton); absentButton = (ImageView)view.findViewById(R.id.absentButton); cancelButton = (ImageView)view.findViewById(R.id.cancelButton); statusImage = (ImageView)view.findViewById(R.id.statusImage); mCircleDisplay = (CircleDisplay)view.findViewById(R.id.circleDisplay); expandablePanel = (RelativeLayout)view.findViewById(R.id.expandablePanel); } } public ScheduleAdapter(List<Subject> eventslist,Context context,RecyclerView recyclerView){ this.eventslist=eventslist; this.context=context; this.recyclerView=recyclerView; subjectsDB=new SubjectsDB(context); } public MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType){ View itemView= LayoutInflater.from(parent.getContext()).inflate(R.layout.schedule_list_row, parent, false); return new MyViewHolder(itemView); } public void onBindViewHolder(final MyViewHolder holder, final int position) { final Subject movie = eventslist.get(position); holder.title.setText(movie.getName()); holder.present.setText("Present=" + movie.getPresent() + ""); holder.total.setText("Total=" + movie.getTotal() + ""); holder.absent.setText("Absent=" + movie.getAbsent() + ""); holder.cancelled.setText("Cancel=" + movie.getCancelled() + ""); if(movie.getStatus() == 0){ holder.statusImage.setImageResource(R.drawable.roundedinfobutton); } else if(movie.getStatus() == 1){ holder.statusImage.setImageResource(R.drawable.checkmarkbutton); } else if(movie.getStatus() == 2){ holder.statusImage.setImageResource(R.drawable.deletebutton); } else if(movie.getStatus() == 3){ holder.statusImage.setImageResource(R.drawable.disabled); } //holder.percentage.setText(String.format("Percentage = %02.1f", movie.getPercentage() )); if (position == expandedPosition) { holder.expandablePanel.setVisibility(View.VISIBLE); holder.statusImage.setVisibility(View.GONE); } else { holder.expandablePanel.setVisibility(View.GONE); holder.statusImage.setVisibility(View.VISIBLE); } holder.statusImage.setOnClickListener( new ImageView.OnClickListener() { public void onClick(View view) { // Check for an expanded view, collapse if you find one if (expandedPosition >= 0) { int prev = expandedPosition; notifyItemChanged(prev); } // Set the current position to "expanded" expandedPosition = position; notifyItemChanged(expandedPosition); //Toast.makeText(context, "Clicked: ", Toast.LENGTH_SHORT).show(); } } ); holder.presentButton.setOnClickListener( new ImageView.OnClickListener() { public void onClick(View view) { //subjectsDB.isPresent(movie.getName()); subjectsDB.setStatus(movie.getName(), 1); setUpSubjectList(); } } ); holder.absentButton.setOnClickListener( new ImageView.OnClickListener(){ public void onClick(View view){ //subjectsDB.isAbsent(movie.getName()); subjectsDB.setStatus(movie.getName(), 2); setUpSubjectList(); } } ); holder.cancelButton.setOnClickListener( new ImageView.OnClickListener() { public void onClick(View view) { //subjectsDB.isCancel(movie.getName()); subjectsDB.setStatus(movie.getName(), 3); setUpSubjectList(); } } ); holder.mCircleDisplay.setAnimDuration(0); holder.mCircleDisplay.setValueWidthPercent(25f); holder.mCircleDisplay.setFormatDigits(1); holder.mCircleDisplay.setDimAlpha(100); if(movie.getPercentage()<movie.getMinimum()){ holder.mCircleDisplay.setColor(Color.rgb(227,0,34)); } else{ holder.mCircleDisplay.setColor(Color.rgb(70,210,70)); } holder.mCircleDisplay.setTouchEnabled(false); holder.mCircleDisplay.setUnit("%"); holder.mCircleDisplay.setStepSize(20.0f); holder.mCircleDisplay.setTextSize(15.0f); holder.mCircleDisplay.showValue((float)movie.getPercentage(), 100f, true); } /* public void deleteSubject(final String name){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set dialog message alertDialogBuilder .setCancelable(true).setMessage("Are you sure you want to delete " + name + "?") .setPositiveButton("DELETE", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { subjectsDB.deleteSubject(name); setUpSubjectList(); } }) .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } public void editSubject(final String name, int minimum){ LayoutInflater li = LayoutInflater.from(context); View promptsView = li.inflate(R.layout.edit_subject_prompt, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setView(promptsView); final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput); final SeekBar seekBar = (SeekBar) promptsView.findViewById(R.id.minimum_seekbar); final TextView seekvalue = (TextView) promptsView.findViewById(R.id.minimum_seek_value); userInput.setText(name); seekvalue.setText(minimum+"%"); seekBar.setProgress(minimum); seekBar.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener(){ int value = 0; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { value = progress; seekvalue.setText(value+"%"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { seekvalue.setText(value+"%"); } } ); // set dialog message alertDialogBuilder .setCancelable(true).setTitle("Edit Subject") .setPositiveButton("EDIT", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String addedSubjectName; if (!userInput.getText().toString().equals("") || seekBar.getProgress()==0) { addedSubjectName = userInput.getText().toString(); if(!subjectsDB.isSubjectPresent(addedSubjectName) || addedSubjectName.equals(name)){ subjectsDB.editSubject(name,addedSubjectName,seekBar.getProgress()); setUpSubjectList(); //workshopList = subjectsDB.getAllSubjects(); //mAdapter.notifyDataSetChanged(); } else{ Toast.makeText(context, addedSubjectName + " already in Subjects list", Toast.LENGTH_SHORT).show(); } //workshopList.add(new Subject(addedSubjectName, seekBar.getProgress())); //mAdapter.notifyDataSetChanged(); } else{ Toast.makeText(context,"Required feilds missing", Toast.LENGTH_SHORT).show(); } } }) .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } */ public void setUpSubjectList(){ Calendar calendar = Calendar.getInstance(); subjectsDB = new SubjectsDB(context); timetableDB = new TimetableDB(context); extraDB = new ExtraDB(context); int day = calendar.get(Calendar.DAY_OF_WEEK); switch (day) { case Calendar.SUNDAY: todayslist = timetableDB.getAllTimeTable("sunday"); break; case Calendar.MONDAY: todayslist = timetableDB.getAllTimeTable("monday"); break; case Calendar.TUESDAY: todayslist = timetableDB.getAllTimeTable("tuesday"); break; case Calendar.WEDNESDAY: todayslist = timetableDB.getAllTimeTable("wednesday"); break; case Calendar.THURSDAY: todayslist = timetableDB.getAllTimeTable("thursday"); break; case Calendar.FRIDAY: todayslist = timetableDB.getAllTimeTable("friday"); break; case Calendar.SATURDAY: todayslist = timetableDB.getAllTimeTable("saturday"); break; } eventslist = new ArrayList<>(); for(int i=0; i<todayslist.size(); i++){ Timetable timetable = todayslist.get(i); Subject subject = subjectsDB.getSubjectDetails(timetable.getName()); eventslist.add(subject); } if(extraDB.numberOfRows() != 0){ List<Timetable> extrasList = extraDB.getAllExtras(); for(int i=0; i<extrasList.size(); i++){ Timetable extra = extrasList.get(i); Subject subject = subjectsDB.getSubjectDetails(extra.getName()); eventslist.add(subject); } } mAdapter= new ScheduleAdapter(eventslist,context,recyclerView); recyclerView.setAdapter(mAdapter); } public int getItemCount(){ return eventslist.size(); } }
14,204
0.571952
0.568572
341
40.651028
27.681868
139
false
false
0
0
0
0
0
0
0.668622
false
false
1
d1c8ffdb1551ec9c59d865884a3f9ea427147c77
4,587,025,090,469
99ff3b822f583a46a3f6dd8dada43a4d6f5087a6
/IdeaProjects/Java_02042017/GenericsSelfStudy/src/WildCard/Gen.java
4eb488d096d37a69894a6ed54edc909bccc2c161
[]
no_license
arsv2017/MyFirstJavaProject
https://github.com/arsv2017/MyFirstJavaProject
5740273de339854177c2a408f0afc023673f8908
56dc4b13bbb8ac518f7fcbc79e6b06913ab1079f
refs/heads/master
2019-06-15T13:55:02.382000
2017-07-09T01:48:25
2017-07-09T01:48:25
97,117,974
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package WildCard; /** * Created by SynMobUsr on 7/5/2017. */ public class Gen<T> { T object; Gen(T object){ this.object=object; } public void test(Gen<? extends A> object){ System.out.println("That works"); } }
UTF-8
Java
252
java
Gen.java
Java
[ { "context": "package WildCard;\n\n/**\n * Created by SynMobUsr on 7/5/2017.\n */\npublic class Gen<T> {\n\n T obj", "end": 46, "score": 0.999692976474762, "start": 37, "tag": "USERNAME", "value": "SynMobUsr" } ]
null
[]
package WildCard; /** * Created by SynMobUsr on 7/5/2017. */ public class Gen<T> { T object; Gen(T object){ this.object=object; } public void test(Gen<? extends A> object){ System.out.println("That works"); } }
252
0.575397
0.551587
25
8.96
13.295052
42
false
false
0
0
0
0
0
0
0.16
false
false
1
9cf10ccabd7f83ad42cd511760518a636449134e
24,292,335,036,214
89902669ca38ec2411f362c846c6a2be2f89412c
/course_android/DBottomSheet/app/src/main/java/better/dbottomsheet/CollectDialog.java
85169abca4bf1f92c6df71fab41a5aa29e243baa
[]
no_license
471448446/DAndroid
https://github.com/471448446/DAndroid
23e31881db0ac0396cdde2714c60c67d4aa9593e
20c557e5859a89979f8d841dabac84f22d20e0a7
refs/heads/master
2023-06-07T22:08:40.515000
2023-06-07T08:35:19
2023-06-07T08:35:19
65,447,030
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package better.dbottomsheet; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; /** * Created by better on 16/8/31. */ public class CollectDialog extends DialogFragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.diaog_collect,container,false); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog); } @Override public void onStart() { super.onStart(); Log.d("Better","re="+getResources().getDisplayMetrics().widthPixels); Log.d("Better","de="+getMetrics(getActivity()).widthPixels); getDialog().getWindow().setLayout(getResources().getDisplayMetrics().widthPixels,getDialog().getWindow().getAttributes().height); } public DisplayMetrics getMetrics(Context context) { DisplayMetrics outMetrics = new DisplayMetrics(); ((WindowManager)context.getSystemService("window")).getDefaultDisplay().getMetrics(outMetrics); return outMetrics; } }
UTF-8
Java
1,523
java
CollectDialog.java
Java
[ { "context": "ort android.view.WindowManager;\n\n/**\n * Created by better on 16/8/31.\n */\npublic class CollectDialog extend", "end": 392, "score": 0.9978575110435486, "start": 386, "tag": "USERNAME", "value": "better" } ]
null
[]
package better.dbottomsheet; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; /** * Created by better on 16/8/31. */ public class CollectDialog extends DialogFragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.diaog_collect,container,false); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog); } @Override public void onStart() { super.onStart(); Log.d("Better","re="+getResources().getDisplayMetrics().widthPixels); Log.d("Better","de="+getMetrics(getActivity()).widthPixels); getDialog().getWindow().setLayout(getResources().getDisplayMetrics().widthPixels,getDialog().getWindow().getAttributes().height); } public DisplayMetrics getMetrics(Context context) { DisplayMetrics outMetrics = new DisplayMetrics(); ((WindowManager)context.getSystemService("window")).getDefaultDisplay().getMetrics(outMetrics); return outMetrics; } }
1,523
0.736047
0.732108
42
35.261906
33.232986
137
false
false
0
0
0
0
0
0
0.690476
false
false
1
e84689155e466e45454164c33737428af3d404e2
24,292,335,037,610
a1ec5dfba0b49f641adacea8fdecd677e45a61b8
/CH09_Static/src/staticMethod/App.java
28e24a6ffc6dd1e766e58b468e4a5f3365b8c93b
[ "MIT" ]
permissive
Taewoo-cho/java-study
https://github.com/Taewoo-cho/java-study
899aa30033ef3f11ce9b2a472bd2be6274e252ce
398d3acd186c5565bf41989b3a8fc67fedd67ac3
refs/heads/main
2023-08-31T06:19:17.532000
2021-10-21T07:11:01
2021-10-21T07:11:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package staticMethod; public class App { public static void main(String[] args) { // 스테틱 메소드 getCount 사용 //final String CAT_COUNT = "고양이 숫자: %d\n"; // String.format은 printf를 사용하는 문자열로 리턴된다. String catCount =String.format("고양이 숫자: %d\n", Cat.getCount()); System.out.println(catCount); Cat cat1 = new Cat("마틸다"); Cat cat2 = new Cat("라이언"); Cat cat3 = new Cat("울버린"); System.out.println(cat1); System.out.println(cat2); System.out.println(cat3); catCount = String.format("고양이 숫자: %d\n", Cat.getCount()); System.out.println(catCount); int x = add(1,1); System.out.println(x); // static 메모리에 한번 할당하면 프로그램이 종료될 때 해제되는 것 } private static int add(int a, int b) { // TODO Auto-generated method stub return a+b; } }
UTF-8
Java
913
java
App.java
Java
[]
null
[]
package staticMethod; public class App { public static void main(String[] args) { // 스테틱 메소드 getCount 사용 //final String CAT_COUNT = "고양이 숫자: %d\n"; // String.format은 printf를 사용하는 문자열로 리턴된다. String catCount =String.format("고양이 숫자: %d\n", Cat.getCount()); System.out.println(catCount); Cat cat1 = new Cat("마틸다"); Cat cat2 = new Cat("라이언"); Cat cat3 = new Cat("울버린"); System.out.println(cat1); System.out.println(cat2); System.out.println(cat3); catCount = String.format("고양이 숫자: %d\n", Cat.getCount()); System.out.println(catCount); int x = add(1,1); System.out.println(x); // static 메모리에 한번 할당하면 프로그램이 종료될 때 해제되는 것 } private static int add(int a, int b) { // TODO Auto-generated method stub return a+b; } }
913
0.637775
0.627426
38
19.342106
18.185125
65
false
false
0
0
0
0
0
0
1.921053
false
false
1
5af21945fff85f43908892ee75391330fa8a633b
2,379,411,897,145
4d318bd0a9de39acf6c5f25dc8e353651d473857
/Blatt12/src/SphereGame/Game.java
4889024a03648a3ec7c7e2573cc9a04358eeffee
[]
no_license
pheenyx/EiS2013_Group76
https://github.com/pheenyx/EiS2013_Group76
d3c23bd8568e3bf41624e11023740a16d593d00b
291681c11e271288c8ec5c03b3b9f4e8a8ef22f9
refs/heads/master
2020-04-06T05:35:54.489000
2013-07-13T16:20:41
2013-07-13T16:20:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Main class of the sphere game. * * Nothing special. * * @author j-frost * */ public class Game { /** * @param args * no meaning */ public static void main(String... args) { new SphereFrame(); } }
UTF-8
Java
236
java
Game.java
Java
[ { "context": "phere game.\n * \n * Nothing special.\n * \n * @author j-frost\n * \n */\npublic class Game {\n\n\t/**\n\t * @param args", "end": 85, "score": 0.9986732602119446, "start": 78, "tag": "USERNAME", "value": "j-frost" } ]
null
[]
/** * Main class of the sphere game. * * Nothing special. * * @author j-frost * */ public class Game { /** * @param args * no meaning */ public static void main(String... args) { new SphereFrame(); } }
236
0.538136
0.538136
19
11.421053
12.036418
42
false
false
0
0
0
0
0
0
0.473684
false
false
1
30775f30fac213d8561424daf2419edb04753290
9,577,777,089,189
a2a3c39696876793fd9921f2a3ca28d2d4f0d4e8
/workspace/src/main/java/com/optum/gcm/model/ProviderDetails.java
ea694e123fcca8af4fdc22b50ec3a16dd5ca8fc2
[]
no_license
losthere/Projects
https://github.com/losthere/Projects
5a2395e9641b65df8cd8b3841a7a4ba124af06d8
5fadb9cba69961a477f0f529be5a023ba0a4884f
refs/heads/master
2022-12-26T02:26:05.968000
2020-01-07T05:19:00
2020-01-07T05:19:00
232,247,565
0
0
null
false
2022-12-16T10:37:24
2020-01-07T05:14:20
2020-01-07T05:22:14
2022-12-16T10:37:20
3,119
0
0
9
JavaScript
false
false
package com.optum.gcm.model; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; public class ProviderDetails { private SchedulingInventory schedulingInventory; private String address; private String phone; private String fax; private String userId; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public SchedulingInventory getSchedulingInventory() { return schedulingInventory; } public void setSchedulingInventory(SchedulingInventory schedulingInventory) { this.schedulingInventory = schedulingInventory; } @Override public String toString () { return ToStringBuilder.reflectionToString(this,ToStringStyle.SHORT_PREFIX_STYLE); } }
UTF-8
Java
1,132
java
ProviderDetails.java
Java
[]
null
[]
package com.optum.gcm.model; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; public class ProviderDetails { private SchedulingInventory schedulingInventory; private String address; private String phone; private String fax; private String userId; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public SchedulingInventory getSchedulingInventory() { return schedulingInventory; } public void setSchedulingInventory(SchedulingInventory schedulingInventory) { this.schedulingInventory = schedulingInventory; } @Override public String toString () { return ToStringBuilder.reflectionToString(this,ToStringStyle.SHORT_PREFIX_STYLE); } }
1,132
0.75
0.748233
59
18.186441
20.489332
86
false
false
0
0
0
0
0
0
1.169492
false
false
1
d589ee457c3f8baceae5dc973b8a7c6ffddee703
9,577,777,092,332
709ea5889870e69ff94c33ef223e78c9cdaf4d8a
/src/videos_source_code/methods/pass_by_value/PassByVal.java
ee0516ca2f8c8e4fdc7ee038b38e22510ff22c59
[]
no_license
CodingNomads/online-java-fundamentals
https://github.com/CodingNomads/online-java-fundamentals
02a820ae9274626a18cc5cb638efcf102a615178
370e189605428510b5620ce3e36458189ce80c25
refs/heads/master
2023-02-23T04:50:50.070000
2023-02-14T22:43:37
2023-02-14T22:43:37
165,717,600
4
20
null
false
2023-02-14T22:43:38
2019-01-14T19:01:27
2022-10-26T13:29:15
2023-02-14T22:43:37
1,045
1
8
0
Java
false
false
package videos_source_code.methods.pass_by_value; /** * Created by ryandesmond - https://codingnomads.co */ public class PassByVal { public static void main(String[] args) { double a = 12; double b = 14; System.out.println("before a:" + a); System.out.println("before b:" + b); someOtherMethod(a, b); System.out.println("before a:" + a); System.out.println("before b:" + b); } public static void someOtherMethod(double a, double b){ a = a * 10; System.out.println(a); b = b * 20; System.out.println(b); } }
UTF-8
Java
619
java
PassByVal.java
Java
[ { "context": "rce_code.methods.pass_by_value;\n\n/**\n * Created by ryandesmond - https://codingnomads.co\n */\npublic class PassBy", "end": 80, "score": 0.9996148347854614, "start": 69, "tag": "USERNAME", "value": "ryandesmond" } ]
null
[]
package videos_source_code.methods.pass_by_value; /** * Created by ryandesmond - https://codingnomads.co */ public class PassByVal { public static void main(String[] args) { double a = 12; double b = 14; System.out.println("before a:" + a); System.out.println("before b:" + b); someOtherMethod(a, b); System.out.println("before a:" + a); System.out.println("before b:" + b); } public static void someOtherMethod(double a, double b){ a = a * 10; System.out.println(a); b = b * 20; System.out.println(b); } }
619
0.562197
0.549273
27
21.925926
19.453508
59
false
false
0
0
0
0
0
0
0.518519
false
false
1
e8fea63d0f430870cda5d3f4646d547333f12919
6,811,818,154,295
d1ea5077c83cb2e93fe69e3d19a2e26efe894a0e
/src/main/java/com/rograndec/feijiayun/chain/business/finance/receivablepayment/receivable/service/CollectMoneyService.java
37b44a0daa1ab9d988e0835722e5d7829bb41a4c
[]
no_license
Catfeeds/rog-backend
https://github.com/Catfeeds/rog-backend
e89da5a3bf184e4636169e7492a97dfd0deef2a1
109670cfec6cbe326b751e93e49811f07045e531
refs/heads/master
2020-04-05T17:36:50.097000
2018-10-22T16:23:55
2018-10-22T16:23:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rograndec.feijiayun.chain.business.finance.receivablepayment.receivable.service; import com.rograndec.feijiayun.chain.business.basic.user.entity.User; import com.rograndec.feijiayun.chain.business.finance.receivablepayment.receivable.vo.*; import com.rograndec.feijiayun.chain.common.Page; import com.rograndec.feijiayun.chain.common.SelectBeanWithCode; import com.rograndec.feijiayun.chain.common.SelectThreeBean; import com.rograndec.feijiayun.chain.common.vo.DraftCacheVO; import com.rograndec.feijiayun.chain.common.vo.UserVO; import java.io.OutputStream; import java.util.List; public interface CollectMoneyService { Page getReceivePage(Page page, RequestReceivePageVO requestReceivePageVO, UserVO loginUser); ReceiveFormVO getReceiveDetail(Long id); Page getReceiveUpdateRecord(Page page,RequestModifyPageVO requestModifyPageVO, UserVO loginUser); void export(OutputStream output, ReceiveFormVO receiveFormVO, UserVO loginUser); String addOrUpdateReceiveDetail(ReceiveFormVO receiveFormVO, UserVO loginUser) throws Exception; void sterilisation(List<Long> list, UserVO loginUser) throws Exception; List<DraftCacheVO> getDraftCacheVO(UserVO userVO, Long companyId, Integer companyType); DraftCacheVO<String> saveDraftCache(UserVO userVO, DraftCacheVO<String> cache); void removeDraftCach(Long enterpriseId, String codePrefix, String redisKeyValue, Long companyId, Integer companyType); List<User> getReceivableManNameSelector(UserVO loginUser, String param); List<SelectBeanWithCode> getPayCompanyCodeSelector(Integer companyType, UserVO loginUser, String param); String getPayCompanyName(Integer companyType, UserVO loginUser, Long id); List<SelectThreeBean> getBankSelector(UserVO loginUser); Page getReceivableDocuments(Page page, RequestReceivableDocuments requestReceivableDocuments, UserVO loginUser); List<ReceiveUpdateRecordVO> getUpdateRecordWithNoPage(Long id); void exportUpdateRecord(OutputStream output, List<ReceiveUpdateRecordVO> list, UserVO loginUser); }
UTF-8
Java
2,072
java
CollectMoneyService.java
Java
[]
null
[]
package com.rograndec.feijiayun.chain.business.finance.receivablepayment.receivable.service; import com.rograndec.feijiayun.chain.business.basic.user.entity.User; import com.rograndec.feijiayun.chain.business.finance.receivablepayment.receivable.vo.*; import com.rograndec.feijiayun.chain.common.Page; import com.rograndec.feijiayun.chain.common.SelectBeanWithCode; import com.rograndec.feijiayun.chain.common.SelectThreeBean; import com.rograndec.feijiayun.chain.common.vo.DraftCacheVO; import com.rograndec.feijiayun.chain.common.vo.UserVO; import java.io.OutputStream; import java.util.List; public interface CollectMoneyService { Page getReceivePage(Page page, RequestReceivePageVO requestReceivePageVO, UserVO loginUser); ReceiveFormVO getReceiveDetail(Long id); Page getReceiveUpdateRecord(Page page,RequestModifyPageVO requestModifyPageVO, UserVO loginUser); void export(OutputStream output, ReceiveFormVO receiveFormVO, UserVO loginUser); String addOrUpdateReceiveDetail(ReceiveFormVO receiveFormVO, UserVO loginUser) throws Exception; void sterilisation(List<Long> list, UserVO loginUser) throws Exception; List<DraftCacheVO> getDraftCacheVO(UserVO userVO, Long companyId, Integer companyType); DraftCacheVO<String> saveDraftCache(UserVO userVO, DraftCacheVO<String> cache); void removeDraftCach(Long enterpriseId, String codePrefix, String redisKeyValue, Long companyId, Integer companyType); List<User> getReceivableManNameSelector(UserVO loginUser, String param); List<SelectBeanWithCode> getPayCompanyCodeSelector(Integer companyType, UserVO loginUser, String param); String getPayCompanyName(Integer companyType, UserVO loginUser, Long id); List<SelectThreeBean> getBankSelector(UserVO loginUser); Page getReceivableDocuments(Page page, RequestReceivableDocuments requestReceivableDocuments, UserVO loginUser); List<ReceiveUpdateRecordVO> getUpdateRecordWithNoPage(Long id); void exportUpdateRecord(OutputStream output, List<ReceiveUpdateRecordVO> list, UserVO loginUser); }
2,072
0.823359
0.823359
47
43.085106
41.800861
122
false
false
0
0
0
0
0
0
1.06383
false
false
1
697b783ce39486911c933aaa4ec9c554ea055bce
28,853,590,325,128
d417004e8e156e182a081450fdda4289a5e2e4dd
/SharpInU/src/main/java/com/sharpinu/service/admin/IOurPracticeCategoryAdminService.java
347661ff60e361fd590ae8c5a7f4e3fbfe92723d
[]
no_license
minhnhat2006/java
https://github.com/minhnhat2006/java
bca1f9f1807d1b37f8ff349c00f38fdab924f6ca
ce9bebd49d43ee76311e88f55d5b4c4d036730f2
refs/heads/master
2020-07-01T17:25:33.730000
2016-01-29T08:09:46
2016-01-29T08:09:46
50,648,289
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sharpinu.service.admin; import java.util.List; import org.springframework.data.domain.Page; import com.sharpinu.persist.domain.OurPracticeCategory; import com.sharpinu.service.IBaseService; import com.sharpinu.web.form.admin.OurPracticeCategoryForm; /** * * @author nhatnguyen * */ public interface IOurPracticeCategoryAdminService extends IBaseService { String saveOurPracticeCategoryForm(OurPracticeCategoryForm ourPracticeCategoryForm); /** * Find categories with pageIndex criteria * * @param pageIndex * @return */ Page<OurPracticeCategory> getOurPracticeCategoryPageInfo(int pageIndex); /** * Find categories with pageIndex criteria * * @param pageIndex * @param categories * @return */ List<OurPracticeCategory> findOurPracticeCategoryViewBean(int pageIndex, Page<OurPracticeCategory> categories); /** * Find all categories * * @return */ public List<OurPracticeCategory> findAll(); /** * Find one ourPracticeCategory by id * * @return */ public OurPracticeCategory findById(Integer id); }
UTF-8
Java
1,074
java
IOurPracticeCategoryAdminService.java
Java
[ { "context": "admin.OurPracticeCategoryForm;\n\n/**\n * \n * @author nhatnguyen\n *\n */\npublic interface IOurPracticeCategoryAdmin", "end": 295, "score": 0.999611496925354, "start": 285, "tag": "USERNAME", "value": "nhatnguyen" } ]
null
[]
package com.sharpinu.service.admin; import java.util.List; import org.springframework.data.domain.Page; import com.sharpinu.persist.domain.OurPracticeCategory; import com.sharpinu.service.IBaseService; import com.sharpinu.web.form.admin.OurPracticeCategoryForm; /** * * @author nhatnguyen * */ public interface IOurPracticeCategoryAdminService extends IBaseService { String saveOurPracticeCategoryForm(OurPracticeCategoryForm ourPracticeCategoryForm); /** * Find categories with pageIndex criteria * * @param pageIndex * @return */ Page<OurPracticeCategory> getOurPracticeCategoryPageInfo(int pageIndex); /** * Find categories with pageIndex criteria * * @param pageIndex * @param categories * @return */ List<OurPracticeCategory> findOurPracticeCategoryViewBean(int pageIndex, Page<OurPracticeCategory> categories); /** * Find all categories * * @return */ public List<OurPracticeCategory> findAll(); /** * Find one ourPracticeCategory by id * * @return */ public OurPracticeCategory findById(Integer id); }
1,074
0.75419
0.75419
50
20.48
25.899992
112
false
false
0
0
0
0
0
0
0.8
false
false
1
8ffb405b62e43e755a101de9a8d1affc7c2efe07
28,853,590,325,855
916110cdfe1320600edc8cd01a910ee556884a5f
/42-test-ivanmetla-1Test-test/src/ua/cn/testIvanmetla1/test/AboutFragmentTest.java
7d38b01cbf009f4a79bb976498825e556489e16a
[]
no_license
metlaivan/42-test-ivanmetla-1
https://github.com/metlaivan/42-test-ivanmetla-1
3d44b2a73d253ea610441d05e5c5fd01d31e0dec
90dc6e05c674e621c0ad1dd19631ac31cb68a4dd
refs/heads/master
2019-07-15T20:57:54.419000
2014-04-30T15:51:38
2014-04-30T15:51:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ua.cn.testIvanmetla1.test; import ua.cn._42_test_ivanmetla_1.ui.MainActivity; import ua.cn.testIvanmetla1.R; import android.test.ActivityInstrumentationTestCase2; import android.test.ViewAsserts; import android.widget.TextView; public class AboutFragmentTest extends ActivityInstrumentationTestCase2<MainActivity> { private MainActivity mActivity; private TextView mTvAbout; public AboutFragmentTest() { super(MainActivity.class); } /* * (non-Javadoc) * * @see android.test.ActivityInstrumentationTestCase2#setUp() */ @Override protected void setUp() throws Exception { mActivity = getActivity(); mTvAbout = (TextView) mActivity.findViewById(R.id.tvAbout); super.setUp(); } /* * (non-Javadoc) * * @see android.test.ActivityInstrumentationTestCase2#tearDown() */ @Override protected void tearDown() throws Exception { super.tearDown(); } public void testForNUllActivity() { assertNotNull(mActivity); } public void testLvFriendsVisible() { ViewAsserts.assertOnScreen(mTvAbout.getRootView(), mTvAbout); } }
UTF-8
Java
1,070
java
AboutFragmentTest.java
Java
[]
null
[]
package ua.cn.testIvanmetla1.test; import ua.cn._42_test_ivanmetla_1.ui.MainActivity; import ua.cn.testIvanmetla1.R; import android.test.ActivityInstrumentationTestCase2; import android.test.ViewAsserts; import android.widget.TextView; public class AboutFragmentTest extends ActivityInstrumentationTestCase2<MainActivity> { private MainActivity mActivity; private TextView mTvAbout; public AboutFragmentTest() { super(MainActivity.class); } /* * (non-Javadoc) * * @see android.test.ActivityInstrumentationTestCase2#setUp() */ @Override protected void setUp() throws Exception { mActivity = getActivity(); mTvAbout = (TextView) mActivity.findViewById(R.id.tvAbout); super.setUp(); } /* * (non-Javadoc) * * @see android.test.ActivityInstrumentationTestCase2#tearDown() */ @Override protected void tearDown() throws Exception { super.tearDown(); } public void testForNUllActivity() { assertNotNull(mActivity); } public void testLvFriendsVisible() { ViewAsserts.assertOnScreen(mTvAbout.getRootView(), mTvAbout); } }
1,070
0.753271
0.74486
48
21.291666
20.481657
65
false
false
0
0
0
0
0
0
1.166667
false
false
1
41e0220c3c18ce42ee73935dd7d81970b017c035
31,628,139,168,953
ad6434dc113e22e64f0709c95099babe6b2cc854
/src/DesignCompressedStringIterator/DesignCompressedStringIterator.java
dfc58fb96ef814d8b213c33369c8bc26c3ea8a52
[]
no_license
shiyanch/Leetcode_Java
https://github.com/shiyanch/Leetcode_Java
f8b7807fbbc0174d45127b65b7b48d836887983c
20df421f44b1907af6528578baf53efddfee48b1
refs/heads/master
2023-05-28T00:40:30.569000
2023-05-17T03:51:34
2023-05-17T03:51:34
48,945,641
9
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package DesignCompressedStringIterator; import java.util.LinkedList; import java.util.Queue; /** * 604. Design Compressed String Iterator * * Design and implement a data structure for a compressed string iterator. * It should support the following operations: next and hasNext. * * The given compressed string will be in the form of each letter * followed by a positive integer representing the number of this letter * existing in the original uncompressed string. * * next() - if the original string still has uncompressed characters, * return the next letter; Otherwise return a white space. * * hasNext() - Judge whether there is any letter needs to be uncompressed. */ public class DesignCompressedStringIterator { Queue<int[]> queue = new LinkedList<>(); public DesignCompressedStringIterator(String compressedString) { int i = 0; int n = compressedString.length(); while (i < n) { int j = i+1; while (j < n && compressedString.charAt(j) - 'A' < 0) { j++; } queue.add(new int[] { compressedString.charAt(i) - 'A', Integer.parseInt(compressedString.substring(i+1, j)) }); i = j; } } public char next() { if (queue.isEmpty()) { return ' '; } int[] top = queue.peek(); if (--top[1] == 0) { queue.poll(); } return (char) ('A' + top[0]); } public boolean hasNext() { return !queue.isEmpty(); } }
UTF-8
Java
1,582
java
DesignCompressedStringIterator.java
Java
[]
null
[]
package DesignCompressedStringIterator; import java.util.LinkedList; import java.util.Queue; /** * 604. Design Compressed String Iterator * * Design and implement a data structure for a compressed string iterator. * It should support the following operations: next and hasNext. * * The given compressed string will be in the form of each letter * followed by a positive integer representing the number of this letter * existing in the original uncompressed string. * * next() - if the original string still has uncompressed characters, * return the next letter; Otherwise return a white space. * * hasNext() - Judge whether there is any letter needs to be uncompressed. */ public class DesignCompressedStringIterator { Queue<int[]> queue = new LinkedList<>(); public DesignCompressedStringIterator(String compressedString) { int i = 0; int n = compressedString.length(); while (i < n) { int j = i+1; while (j < n && compressedString.charAt(j) - 'A' < 0) { j++; } queue.add(new int[] { compressedString.charAt(i) - 'A', Integer.parseInt(compressedString.substring(i+1, j)) }); i = j; } } public char next() { if (queue.isEmpty()) { return ' '; } int[] top = queue.peek(); if (--top[1] == 0) { queue.poll(); } return (char) ('A' + top[0]); } public boolean hasNext() { return !queue.isEmpty(); } }
1,582
0.587863
0.581542
53
28.849056
23.75456
74
false
false
0
0
0
0
0
0
0.358491
false
false
1
46a5f3b61a36723fa7e476a80a9ca6b4e2e2f105
2,508,260,955,956
f95a0db5f32cbbbe9323a87c5e21b19e3a3df21a
/2012/Shuhei, Kita/application.windows32/source/CodeAttribute.java
039622820498e140a506e48e7fb87094815d7afb
[]
no_license
MarinY/Prefix_automaton
https://github.com/MarinY/Prefix_automaton
5ebe5cdb940a047790aebefa0e4b3675d9db4250
ee9bb69d9dba958850d5937483ca51feca3145b9
refs/heads/master
2020-02-26T16:46:07.282000
2014-02-06T08:02:24
2014-02-06T08:02:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * コードアトリビュートクラス。 * メソッドの実際の処理に関する情報保持。 */ import java.util.*; public class CodeAttribute{ public int ID; private String method_name; private Byte[] code_length = new Byte[4]; private Byte[] code; private String[] invoke; private VMCode[] mnemonic; private Byte[] code_set; //命令セット private int max_stack; private int max_local; private int max_memory; private boolean view = true; private int x = -1; private int y = -1; private int hue = 0; private int alpha = 0; private static int LOOP = 0; private static int IF = 1; private static int GO = 2; private static double BIAS = 0.0; private int maxJump = 0; private int[][] jump; private int jumpTotal; private static double LOOP_BIAS; //CONSTRACOR CodeAttribute(String mName, Byte[] bytes, int id){ method_name = mName; ID = id; int index = 0; //max_stack //max_locals max_stack = ByteFunc.getInt(bytes[index++], bytes[index++]); max_local = ByteFunc.getInt(bytes[index++], bytes[index++]); //System.out.println("max:"+max_stack+"_ "+max_local); max_memory = max_stack + max_local; //code_length code_length[0] = bytes[index++]; code_length[1] = bytes[index++]; code_length[2] = bytes[index++]; code_length[3] = bytes[index++]; //code int clength = ByteFunc.getInt(code_length); code = new Byte[clength]; for(int i=0; i<clength; i++){ code[i] = bytes[index++]; } //set nimonic List<VMCode> ls = new ArrayList<VMCode>(); //命令セット List<Byte> ls1 = new ArrayList<Byte>(); index = 0; while(index < code.length){ VMCode mnemo = new VMCode(code[index], index); ls1.add(code[index]); index++; int count = 0; while(count < mnemo.getNum()){ mnemo.addBytes(code[index++]); count++; } //kind ///IF if( (153<=mnemo.getBinary()&&mnemo.getBinary()<=166) || (198<=mnemo.getBinary()&&mnemo.getBinary()<=199) ){ int d1 = ByteFunc.getInt(mnemo.getBytes()); if(d1 > Math.pow(2,15)){ d1 -= (int)Math.pow(2,16); } //get max if(maxJump>d1) maxJump = d1; mnemo.setJump( d1 + mnemo.getIndex() ); } ///GO_TO else if(mnemo.getBinary()==167 || mnemo.getBinary()==200){ int d2 = 31; if(mnemo.getBinary()==167) d2 = 15; int d1 = ByteFunc.getInt(mnemo.getBytes()); if(d1 > Math.pow(2,d2)){ d1 -= (int)Math.pow(2,d2+1); } //get max if(maxJump>d1) maxJump = d1; mnemo.setJump( d1 + mnemo.getIndex() ); } // ls.add(mnemo); } mnemonic = ls.toArray(new VMCode[0]); code_set = ls1.toArray(new Byte[0]); //jump set setJump(); //printJump(); } ///constract --END ---- //METHOD public static void setBias(double bias){ LOOP_BIAS = bias; } ///print public void print(){ System.out.println("------------------------"); System.out.println(ID+": "+method_name); for(int i=0; i<mnemonic.length; i++){ mnemonic[i].print(); } } //SETTER public static void setBIAS(double b){ BIAS += b; if(BIAS >1) BIAS = 1.0; else if(BIAS < 0) BIAS = 0.0; } public void setView(boolean b){ view = b; } //set (x,y) public void setXY(int X, int Y){ x = X; y = Y; //set mnemonic XY int D = 0; int dis = 10; int r = 4; List<Integer> next = new ArrayList<Integer>(); for(int i=0; i<mnemonic.length; i++){ //IF end int n = next.indexOf(new Integer(mnemonic[i].getIndex())); if( n >-1){ D -= dis; next.remove(n); } //IF start if(mnemonic[i].isIF()){ D += dis; next.add(mnemonic[i].getJump()); } mnemonic[i].setXY(X+D ,Y+r*i); } } private void setJump(){ List<VMCode> loops = new ArrayList<VMCode>(); for(int i=0; i<mnemonic.length; i++){ VMCode vc = mnemonic[i]; if(vc.isLOOP()){ int max_deep = 0; int index = -1; for(int l=0; l<loops.size(); l++){ //this mnemonic > loops[m] if(vc.getIndex()>loops.get(l).getIndex() && loops.get(l).getIndex()>vc.getJump()){ if(max_deep < loops.get(l).getDeep()){ max_deep = loops.get(l).getDeep(); index = l; } } } vc.setDeep(1+max_deep); if(index != -1) loops.remove(index); loops.add(vc); } } jump = new int[loops.size()][2]; for(int i=0; i<loops.size(); i++){ int index1 = 0; for(int j=0; j<mnemonic.length; j++){ if(loops.get(i).getIndex() == mnemonic[j].getIndex()) index1 = j; } jump[i][0] = loops.get(i).getDeep(); jump[i][1] = index1 - this.getJumpIndex(loops.get(i)); } jumpTotal = 0; for(int i=0; i<jump.length; i++){ jumpTotal += (jump[i][0]*2-1)*jump[i][1]; } } /////GETTER //get ID public int getID(){ return ID; } //get invoke public String[] getInvoke(){ List<String> list = new ArrayList<String>(); for(int i=0; i<mnemonic.length; i++){ if(mnemonic[i].isINVOKE()){ list.add(mnemonic[i].getInvoke()); } } return list.toArray(new String[0]); } //get invoke class public String[] getInvokeClass(){ List<String> list = new ArrayList<String>(); for(int i=0; i<mnemonic.length; i++){ if(mnemonic[i].isINVOKE()){ list.add(mnemonic[i].getInvokeClass()); } } return list.toArray(new String[0]); } //get x public int getX(){ return x; } //get y public int getY(){ return y; } //get method_name public String getName(){ return method_name; } //get code[] public Byte[] getCode(){ return code; } public VMCode[] getMnemonic(){ return mnemonic; } public Byte[] getCodeSet(){ return code_set; } ///get jump index public int getJumpIndex(VMCode mnemo){ for(int i=0; i<mnemonic.length; i++){ if(mnemonic[i].getIndex() == mnemo.getJump()){ return i; } } return -1; } //get max_stack public int getMaxStack(){ return max_stack; } //get max_local public int getMaxLocal(){ return max_local; } //get max_memory public int getMaxMemory(){ return max_memory; } //get view public boolean isView(){ return view; } //get max jump private int getMaxJump(){ return -1*maxJump; } //get jump total private int getJumpTotal(){ return jumpTotal; } //print jump public void printJump(){ for(int i=0; i<jump.length; i++) System.out.println(Arrays.toString(jump[i])); } //CodeAttribute edit distance /* * バイト列の編集距離 */ public int edit(CodeAttribute code1){ //return ByteFunc.edit(code, code1.getCode()); Byte[] bytes1 = code; Byte[] bytes2 = code1.getCode(); int len1=bytes1.length,len2=bytes2.length; int[][] row = new int[len1+1][len2+1]; int i,j; int result; for(i=0;i<len1+1;i++) row[i][0] = i; for(i=0;i<len2+1;i++) row[0][i] = i; for(i=1;i<=len1;++i){ for(j=1;j<=len2;++j){ row[i][j] = Math.min(Math.min( (Integer)(row[i-1][j-1]) + ((bytes1[i-1]==bytes2[j-1])?0:1) , // replace (Integer)(row[i][j-1]) + 1), // delete (Integer)(row[i-1][j]) + 1); // insert } } result=(Integer)(row[len1][len2]); //result += structureEdit(code1.getStructure()) * (bytes1.length+bytes2.length) * BIAS; //return result; return result + (int)(LOOP_BIAS * Math.abs(this.getMaxJump() - code1.getMaxJump())); } //CodeAttribute edit distance /* * 命令バイト列の編集距離(引数を省く) */ public int edit_codeSet(CodeAttribute code1){ //return ByteFunc.edit(code, code1.getCode()); Byte[] bytes1 = code_set; Byte[] bytes2 = code1.getCodeSet(); int len1=bytes1.length,len2=bytes2.length; int[][] row = new int[len1+1][len2+1]; int i,j; int result; for(i=0;i<len1+1;i++) row[i][0] = i; for(i=0;i<len2+1;i++) row[0][i] = i; for(i=1;i<=len1;++i){ for(j=1;j<=len2;++j){ row[i][j] = Math.min(Math.min( (Integer)(row[i-1][j-1]) + ((bytes1[i-1]==bytes2[j-1])?0:1) , // replace (Integer)(row[i][j-1]) + 1), // delete (Integer)(row[i-1][j]) + 1); // insert } } result=(Integer)(row[len1][len2]); //result += structureEdit(code1.getStructure()) * (bytes1.length+bytes2.length) * BIAS; //return result; return result + (int)(LOOP_BIAS * Math.abs(jumpTotal - code1.getJumpTotal())); } //set invoke cp_Index public void setInvoke(CPInfo[] cp, int num){ for(int i=0; i<mnemonic.length; i++){ mnemonic[i].setInvoke(cp, num); } } }
UTF-8
Java
8,451
java
CodeAttribute.java
Java
[]
null
[]
/* * コードアトリビュートクラス。 * メソッドの実際の処理に関する情報保持。 */ import java.util.*; public class CodeAttribute{ public int ID; private String method_name; private Byte[] code_length = new Byte[4]; private Byte[] code; private String[] invoke; private VMCode[] mnemonic; private Byte[] code_set; //命令セット private int max_stack; private int max_local; private int max_memory; private boolean view = true; private int x = -1; private int y = -1; private int hue = 0; private int alpha = 0; private static int LOOP = 0; private static int IF = 1; private static int GO = 2; private static double BIAS = 0.0; private int maxJump = 0; private int[][] jump; private int jumpTotal; private static double LOOP_BIAS; //CONSTRACOR CodeAttribute(String mName, Byte[] bytes, int id){ method_name = mName; ID = id; int index = 0; //max_stack //max_locals max_stack = ByteFunc.getInt(bytes[index++], bytes[index++]); max_local = ByteFunc.getInt(bytes[index++], bytes[index++]); //System.out.println("max:"+max_stack+"_ "+max_local); max_memory = max_stack + max_local; //code_length code_length[0] = bytes[index++]; code_length[1] = bytes[index++]; code_length[2] = bytes[index++]; code_length[3] = bytes[index++]; //code int clength = ByteFunc.getInt(code_length); code = new Byte[clength]; for(int i=0; i<clength; i++){ code[i] = bytes[index++]; } //set nimonic List<VMCode> ls = new ArrayList<VMCode>(); //命令セット List<Byte> ls1 = new ArrayList<Byte>(); index = 0; while(index < code.length){ VMCode mnemo = new VMCode(code[index], index); ls1.add(code[index]); index++; int count = 0; while(count < mnemo.getNum()){ mnemo.addBytes(code[index++]); count++; } //kind ///IF if( (153<=mnemo.getBinary()&&mnemo.getBinary()<=166) || (198<=mnemo.getBinary()&&mnemo.getBinary()<=199) ){ int d1 = ByteFunc.getInt(mnemo.getBytes()); if(d1 > Math.pow(2,15)){ d1 -= (int)Math.pow(2,16); } //get max if(maxJump>d1) maxJump = d1; mnemo.setJump( d1 + mnemo.getIndex() ); } ///GO_TO else if(mnemo.getBinary()==167 || mnemo.getBinary()==200){ int d2 = 31; if(mnemo.getBinary()==167) d2 = 15; int d1 = ByteFunc.getInt(mnemo.getBytes()); if(d1 > Math.pow(2,d2)){ d1 -= (int)Math.pow(2,d2+1); } //get max if(maxJump>d1) maxJump = d1; mnemo.setJump( d1 + mnemo.getIndex() ); } // ls.add(mnemo); } mnemonic = ls.toArray(new VMCode[0]); code_set = ls1.toArray(new Byte[0]); //jump set setJump(); //printJump(); } ///constract --END ---- //METHOD public static void setBias(double bias){ LOOP_BIAS = bias; } ///print public void print(){ System.out.println("------------------------"); System.out.println(ID+": "+method_name); for(int i=0; i<mnemonic.length; i++){ mnemonic[i].print(); } } //SETTER public static void setBIAS(double b){ BIAS += b; if(BIAS >1) BIAS = 1.0; else if(BIAS < 0) BIAS = 0.0; } public void setView(boolean b){ view = b; } //set (x,y) public void setXY(int X, int Y){ x = X; y = Y; //set mnemonic XY int D = 0; int dis = 10; int r = 4; List<Integer> next = new ArrayList<Integer>(); for(int i=0; i<mnemonic.length; i++){ //IF end int n = next.indexOf(new Integer(mnemonic[i].getIndex())); if( n >-1){ D -= dis; next.remove(n); } //IF start if(mnemonic[i].isIF()){ D += dis; next.add(mnemonic[i].getJump()); } mnemonic[i].setXY(X+D ,Y+r*i); } } private void setJump(){ List<VMCode> loops = new ArrayList<VMCode>(); for(int i=0; i<mnemonic.length; i++){ VMCode vc = mnemonic[i]; if(vc.isLOOP()){ int max_deep = 0; int index = -1; for(int l=0; l<loops.size(); l++){ //this mnemonic > loops[m] if(vc.getIndex()>loops.get(l).getIndex() && loops.get(l).getIndex()>vc.getJump()){ if(max_deep < loops.get(l).getDeep()){ max_deep = loops.get(l).getDeep(); index = l; } } } vc.setDeep(1+max_deep); if(index != -1) loops.remove(index); loops.add(vc); } } jump = new int[loops.size()][2]; for(int i=0; i<loops.size(); i++){ int index1 = 0; for(int j=0; j<mnemonic.length; j++){ if(loops.get(i).getIndex() == mnemonic[j].getIndex()) index1 = j; } jump[i][0] = loops.get(i).getDeep(); jump[i][1] = index1 - this.getJumpIndex(loops.get(i)); } jumpTotal = 0; for(int i=0; i<jump.length; i++){ jumpTotal += (jump[i][0]*2-1)*jump[i][1]; } } /////GETTER //get ID public int getID(){ return ID; } //get invoke public String[] getInvoke(){ List<String> list = new ArrayList<String>(); for(int i=0; i<mnemonic.length; i++){ if(mnemonic[i].isINVOKE()){ list.add(mnemonic[i].getInvoke()); } } return list.toArray(new String[0]); } //get invoke class public String[] getInvokeClass(){ List<String> list = new ArrayList<String>(); for(int i=0; i<mnemonic.length; i++){ if(mnemonic[i].isINVOKE()){ list.add(mnemonic[i].getInvokeClass()); } } return list.toArray(new String[0]); } //get x public int getX(){ return x; } //get y public int getY(){ return y; } //get method_name public String getName(){ return method_name; } //get code[] public Byte[] getCode(){ return code; } public VMCode[] getMnemonic(){ return mnemonic; } public Byte[] getCodeSet(){ return code_set; } ///get jump index public int getJumpIndex(VMCode mnemo){ for(int i=0; i<mnemonic.length; i++){ if(mnemonic[i].getIndex() == mnemo.getJump()){ return i; } } return -1; } //get max_stack public int getMaxStack(){ return max_stack; } //get max_local public int getMaxLocal(){ return max_local; } //get max_memory public int getMaxMemory(){ return max_memory; } //get view public boolean isView(){ return view; } //get max jump private int getMaxJump(){ return -1*maxJump; } //get jump total private int getJumpTotal(){ return jumpTotal; } //print jump public void printJump(){ for(int i=0; i<jump.length; i++) System.out.println(Arrays.toString(jump[i])); } //CodeAttribute edit distance /* * バイト列の編集距離 */ public int edit(CodeAttribute code1){ //return ByteFunc.edit(code, code1.getCode()); Byte[] bytes1 = code; Byte[] bytes2 = code1.getCode(); int len1=bytes1.length,len2=bytes2.length; int[][] row = new int[len1+1][len2+1]; int i,j; int result; for(i=0;i<len1+1;i++) row[i][0] = i; for(i=0;i<len2+1;i++) row[0][i] = i; for(i=1;i<=len1;++i){ for(j=1;j<=len2;++j){ row[i][j] = Math.min(Math.min( (Integer)(row[i-1][j-1]) + ((bytes1[i-1]==bytes2[j-1])?0:1) , // replace (Integer)(row[i][j-1]) + 1), // delete (Integer)(row[i-1][j]) + 1); // insert } } result=(Integer)(row[len1][len2]); //result += structureEdit(code1.getStructure()) * (bytes1.length+bytes2.length) * BIAS; //return result; return result + (int)(LOOP_BIAS * Math.abs(this.getMaxJump() - code1.getMaxJump())); } //CodeAttribute edit distance /* * 命令バイト列の編集距離(引数を省く) */ public int edit_codeSet(CodeAttribute code1){ //return ByteFunc.edit(code, code1.getCode()); Byte[] bytes1 = code_set; Byte[] bytes2 = code1.getCodeSet(); int len1=bytes1.length,len2=bytes2.length; int[][] row = new int[len1+1][len2+1]; int i,j; int result; for(i=0;i<len1+1;i++) row[i][0] = i; for(i=0;i<len2+1;i++) row[0][i] = i; for(i=1;i<=len1;++i){ for(j=1;j<=len2;++j){ row[i][j] = Math.min(Math.min( (Integer)(row[i-1][j-1]) + ((bytes1[i-1]==bytes2[j-1])?0:1) , // replace (Integer)(row[i][j-1]) + 1), // delete (Integer)(row[i-1][j]) + 1); // insert } } result=(Integer)(row[len1][len2]); //result += structureEdit(code1.getStructure()) * (bytes1.length+bytes2.length) * BIAS; //return result; return result + (int)(LOOP_BIAS * Math.abs(jumpTotal - code1.getJumpTotal())); } //set invoke cp_Index public void setInvoke(CPInfo[] cp, int num){ for(int i=0; i<mnemonic.length; i++){ mnemonic[i].setInvoke(cp, num); } } }
8,451
0.582722
0.558296
353
22.541077
18.150587
110
false
false
0
0
0
0
0
0
2.770538
false
false
1
b8261a297dc05723eaf3259efea71fd0e2ccffd0
26,860,725,508,526
df0d7feea9763c08a6395c536125b3d1b9bf0d63
/src/main/ui/ScheduleTable.java
dcb903d5f2d2056b367b57c84bd0d7e7089e323e
[]
no_license
TheAMIZZguy/Uni-Schedule-Maker
https://github.com/TheAMIZZguy/Uni-Schedule-Maker
ad59ecf8259a750f7acd7d29a47323f6364759a6
7d9d12895c0d468d4d3abce6e890460d3796a43c
refs/heads/master
2023-04-09T22:26:32.266000
2021-04-21T00:08:53
2021-04-21T00:08:53
359,983,467
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ui; import model.Scheduler; import javax.swing.table.AbstractTableModel; //Converts a scheduler object into a human viewable table public class ScheduleTable extends AbstractTableModel { private String[] columnNames = {"", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}; String[][] data = new String[2 * 14][6]; //MODIFIES: this //EFFECTS: fills a table with the schedule data public ScheduleTable(Scheduler schedule, String num) { columnNames[0] = num; //this.data = schedule.getSchedule(); for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { if (i % 2 == 0 && j == 0) { this.data[i][0] = (String.valueOf(i / 2 + 7) + ":00"); } else if (j != 0) { data[i][j] = schedule.getSchedule()[i][j - 1]; } } } } //getters public int getColumnCount() { return columnNames.length; } public int getRowCount() { return data.length; } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } //EFFECTS: makes the table uneditable public boolean isCellEditable(int row, int col) { return false; } }
UTF-8
Java
1,379
java
ScheduleTable.java
Java
[]
null
[]
package ui; import model.Scheduler; import javax.swing.table.AbstractTableModel; //Converts a scheduler object into a human viewable table public class ScheduleTable extends AbstractTableModel { private String[] columnNames = {"", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}; String[][] data = new String[2 * 14][6]; //MODIFIES: this //EFFECTS: fills a table with the schedule data public ScheduleTable(Scheduler schedule, String num) { columnNames[0] = num; //this.data = schedule.getSchedule(); for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { if (i % 2 == 0 && j == 0) { this.data[i][0] = (String.valueOf(i / 2 + 7) + ":00"); } else if (j != 0) { data[i][j] = schedule.getSchedule()[i][j - 1]; } } } } //getters public int getColumnCount() { return columnNames.length; } public int getRowCount() { return data.length; } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } //EFFECTS: makes the table uneditable public boolean isCellEditable(int row, int col) { return false; } }
1,379
0.55475
0.542422
51
26.039215
23.668428
96
false
false
0
0
0
0
0
0
0.509804
false
false
1
a074382a4b65d9ef3eafdb1b6f55f2df6d3c8cb8
30,313,879,197,440
7b573e48714f19d228d02c2a2f93c874f5ba9371
/excelSfm/src/main/java/com/kraftlabs/excelsfm/Adapters/LeadCommentAdapter.java
75f5ae2c246f05baaab6a645708b6b737e7ccece
[]
no_license
jef4tech/ExcelMirror
https://github.com/jef4tech/ExcelMirror
547178a18e6370102f5d5227bab0ed63f774e710
75ea2c3b4a1262a3707c0e064114951fb47bca57
refs/heads/master
2020-07-06T03:38:26.598000
2019-08-19T12:04:15
2019-08-19T12:04:15
202,876,097
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kraftlabs.excelsfm.Adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.kraftlabs.excelsfm.Util.PrefUtils; import com.kraftlabs.excelsfm.R; import com.kraftlabs.excelsfm.Models.Comment; import com.kraftlabs.excelsfm.Db.LeadCommentDB; import java.util.ArrayList; /** * Created by ashik on 14/7/17. */ public class LeadCommentAdapter extends RecyclerView.Adapter<LeadCommentAdapter.MyViewHolder> { private static final String TAG = "LeadCommentFragment"; int mUserId; private Context context; private ArrayList<Comment> leadComments = new ArrayList<>(); private LeadCommentDB leadCommentDB; public LeadCommentAdapter(Context context, int mUserId, ArrayList<Comment> leadComments) { this.context = context; this.mUserId = mUserId; this.leadComments = leadComments; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View iteView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment, parent, false); return new MyViewHolder(iteView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { final Comment leadComment = leadComments.get(position); int userId = PrefUtils.getCurrentUser(context).getUserId(); holder.txtTaskPercentage.setVisibility(View.GONE); int createdUser = leadComment.getCreatedUserId(); holder.txtCreatedUser.setText(leadComment.getCreatedBy()); holder.txtComment.setText(leadComment.getComment()); holder.txtDate.setText(leadComment.getDate().toString()); if (userId != leadComment.getCreatedUserId()) {//from Server holder.ivProfileMe.setVisibility(View.GONE); holder.ivProfileOther.setVisibility(View.VISIBLE); holder.imgSended.setVisibility(View.GONE); holder.txtComment.setGravity(Gravity.LEFT); holder.rlStatus.setGravity(Gravity.LEFT); } else { holder.ivProfileMe.setVisibility(View.VISIBLE);//from app holder.ivProfileOther.setVisibility(View.GONE); holder.rltvText.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT); if (leadComment.getServerId() == 0) { holder.imgSended.setVisibility(View.GONE); } else { holder.imgSended.setVisibility(View.VISIBLE); } } } @Override public int getItemCount() { return leadComments.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { public TextView txtComment, txtCreatedUser, txtDate, txtStatus, txtTaskPercentage; public RelativeLayout rltvText, rlStatus; public ImageView ivProfileMe, ivProfileOther, imgSended; public MyViewHolder(View view) { super(view); txtComment = (TextView) view.findViewById(R.id.txtComment); txtCreatedUser = (TextView) view.findViewById(R.id.txtCreatedUser); txtDate = (TextView) view.findViewById(R.id.txtDate); txtTaskPercentage = (TextView) view.findViewById(R.id.txtTaskPercentage); txtStatus = (TextView) view.findViewById(R.id.txtStatus); ivProfileMe = (ImageView) view.findViewById(R.id.ivProfileMe); ivProfileOther = (ImageView) view.findViewById(R.id.ivProfileOther); imgSended = (ImageView) view.findViewById(R.id.imgSended); rlStatus = (RelativeLayout) view.findViewById(R.id.rlStatus); rltvText = (RelativeLayout) view.findViewById(R.id.rltvText); } } }
UTF-8
Java
3,897
java
LeadCommentAdapter.java
Java
[ { "context": "B;\n\nimport java.util.ArrayList;\n\n/**\n * Created by ashik on 14/7/17.\n */\n\npublic class LeadCommentAdapter ", "end": 573, "score": 0.9994945526123047, "start": 568, "tag": "USERNAME", "value": "ashik" } ]
null
[]
package com.kraftlabs.excelsfm.Adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.kraftlabs.excelsfm.Util.PrefUtils; import com.kraftlabs.excelsfm.R; import com.kraftlabs.excelsfm.Models.Comment; import com.kraftlabs.excelsfm.Db.LeadCommentDB; import java.util.ArrayList; /** * Created by ashik on 14/7/17. */ public class LeadCommentAdapter extends RecyclerView.Adapter<LeadCommentAdapter.MyViewHolder> { private static final String TAG = "LeadCommentFragment"; int mUserId; private Context context; private ArrayList<Comment> leadComments = new ArrayList<>(); private LeadCommentDB leadCommentDB; public LeadCommentAdapter(Context context, int mUserId, ArrayList<Comment> leadComments) { this.context = context; this.mUserId = mUserId; this.leadComments = leadComments; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View iteView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment, parent, false); return new MyViewHolder(iteView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { final Comment leadComment = leadComments.get(position); int userId = PrefUtils.getCurrentUser(context).getUserId(); holder.txtTaskPercentage.setVisibility(View.GONE); int createdUser = leadComment.getCreatedUserId(); holder.txtCreatedUser.setText(leadComment.getCreatedBy()); holder.txtComment.setText(leadComment.getComment()); holder.txtDate.setText(leadComment.getDate().toString()); if (userId != leadComment.getCreatedUserId()) {//from Server holder.ivProfileMe.setVisibility(View.GONE); holder.ivProfileOther.setVisibility(View.VISIBLE); holder.imgSended.setVisibility(View.GONE); holder.txtComment.setGravity(Gravity.LEFT); holder.rlStatus.setGravity(Gravity.LEFT); } else { holder.ivProfileMe.setVisibility(View.VISIBLE);//from app holder.ivProfileOther.setVisibility(View.GONE); holder.rltvText.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT); if (leadComment.getServerId() == 0) { holder.imgSended.setVisibility(View.GONE); } else { holder.imgSended.setVisibility(View.VISIBLE); } } } @Override public int getItemCount() { return leadComments.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { public TextView txtComment, txtCreatedUser, txtDate, txtStatus, txtTaskPercentage; public RelativeLayout rltvText, rlStatus; public ImageView ivProfileMe, ivProfileOther, imgSended; public MyViewHolder(View view) { super(view); txtComment = (TextView) view.findViewById(R.id.txtComment); txtCreatedUser = (TextView) view.findViewById(R.id.txtCreatedUser); txtDate = (TextView) view.findViewById(R.id.txtDate); txtTaskPercentage = (TextView) view.findViewById(R.id.txtTaskPercentage); txtStatus = (TextView) view.findViewById(R.id.txtStatus); ivProfileMe = (ImageView) view.findViewById(R.id.ivProfileMe); ivProfileOther = (ImageView) view.findViewById(R.id.ivProfileOther); imgSended = (ImageView) view.findViewById(R.id.imgSended); rlStatus = (RelativeLayout) view.findViewById(R.id.rlStatus); rltvText = (RelativeLayout) view.findViewById(R.id.rltvText); } } }
3,897
0.694637
0.692841
106
35.764153
29.50873
110
false
false
0
0
0
0
0
0
0.669811
false
false
1
c3d2eac626bc83cc586c4d4c545fed2b1d9ed71d
4,200,478,040,799
7b8f43953072b30a2cf22fc4b875c5f663018b05
/src/Interview_bit/src/Spiral_matrix_I.java
7e2ca98cf586ddcdc3528a1d46fa76a72ca44b51
[]
no_license
rituAgr/Miscellaneous
https://github.com/rituAgr/Miscellaneous
e8e6d568735132428d8277996a0ac6787904d249
771d315b1c1d0ad4f69b1e2ff5967ad71c928afe
refs/heads/master
2018-01-06T21:05:14.430000
2017-02-05T06:02:04
2017-02-05T06:02:04
70,351,037
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Interview_bit.src; import java.util.ArrayList; //reading element from matrix of any order in spiral order public class Spiral_matrix_I { public static void main(String[] args) { int count =1; int num=1; ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>(); for(int i=0;i<3;i++) { matrix.add(new ArrayList<Integer>()); ArrayList<Integer> row = matrix.get(i); while(count<=3) { row.add(num++); count++; } count=1; } ArrayList<Integer> spiral_traverse=spiralOrder(matrix); System.out.println(matrix.toString()); System.out.println("Spiral traversing result \n"+spiral_traverse.toString()); } public static ArrayList<Integer> spiralOrder(final ArrayList<ArrayList<Integer>> a) { ArrayList<Integer> result = new ArrayList<Integer>(); int dir=0, L=0, T=0; int B=a.size()-1; int R=a.get(0).size()-1; int i; while(L<=R&&T<=B) { if(dir==0) { for(i=L;i<=R;i++) result.add(a.get(T).get(i)); T++; } else if(dir==1) { for(i=T;i<=B;i++) result.add(a.get(i).get(R)); R--; } else if(dir==2) { for(i=R;i>=L;i--) result.add(a.get(B).get(i)); B--; } else if(dir==3) { for(i=B;i>=T;i--) result.add(a.get(i).get(L)); L++; } dir=(dir+1)%4; } // Populate result; return result; } }
UTF-8
Java
1,305
java
Spiral_matrix_I.java
Java
[]
null
[]
package Interview_bit.src; import java.util.ArrayList; //reading element from matrix of any order in spiral order public class Spiral_matrix_I { public static void main(String[] args) { int count =1; int num=1; ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>(); for(int i=0;i<3;i++) { matrix.add(new ArrayList<Integer>()); ArrayList<Integer> row = matrix.get(i); while(count<=3) { row.add(num++); count++; } count=1; } ArrayList<Integer> spiral_traverse=spiralOrder(matrix); System.out.println(matrix.toString()); System.out.println("Spiral traversing result \n"+spiral_traverse.toString()); } public static ArrayList<Integer> spiralOrder(final ArrayList<ArrayList<Integer>> a) { ArrayList<Integer> result = new ArrayList<Integer>(); int dir=0, L=0, T=0; int B=a.size()-1; int R=a.get(0).size()-1; int i; while(L<=R&&T<=B) { if(dir==0) { for(i=L;i<=R;i++) result.add(a.get(T).get(i)); T++; } else if(dir==1) { for(i=T;i<=B;i++) result.add(a.get(i).get(R)); R--; } else if(dir==2) { for(i=R;i>=L;i--) result.add(a.get(B).get(i)); B--; } else if(dir==3) { for(i=B;i>=T;i--) result.add(a.get(i).get(L)); L++; } dir=(dir+1)%4; } // Populate result; return result; } }
1,305
0.609195
0.595402
64
19.390625
19.660093
85
false
false
0
0
0
0
0
0
2.40625
false
false
1
fe26c56ed29573e42e5e4949ed8983725bc680ac
2,542,620,695,823
4de8b6a518376460437be04a1d824c3f1aa3273c
/src/main/java/com/pydyun/ims/service/impl/UserCodeNumServiceImpl.java
3cfff3ef4703f80eff2a4ddf0e150c8219aaf64b
[]
no_license
txy1996/ims
https://github.com/txy1996/ims
db0da11f72f07d85322cecef43476009e92a24ee
c0e75173199c9f4ab84b54bd5eead3add98d720a
refs/heads/master
2020-04-20T19:38:19.227000
2019-02-04T09:59:33
2019-02-04T09:59:33
169,049,155
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pydyun.ims.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.pydyun.ims.dao.UserCodeNumDAO; import com.pydyun.ims.model.UserCodeNum; import com.pydyun.ims.service.UserCodeNumService; @Service public class UserCodeNumServiceImpl implements UserCodeNumService{ @Resource private UserCodeNumDAO userCodeNumDAO; @Override public void insertUserCodeNum(UserCodeNum userCodeNum) { // TODO Auto-generated method stub userCodeNumDAO.insertUserCodeNum(userCodeNum); } @Override public UserCodeNum select() { // TODO Auto-generated method stub return userCodeNumDAO.selectCode(); } }
UTF-8
Java
662
java
UserCodeNumServiceImpl.java
Java
[]
null
[]
package com.pydyun.ims.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.pydyun.ims.dao.UserCodeNumDAO; import com.pydyun.ims.model.UserCodeNum; import com.pydyun.ims.service.UserCodeNumService; @Service public class UserCodeNumServiceImpl implements UserCodeNumService{ @Resource private UserCodeNumDAO userCodeNumDAO; @Override public void insertUserCodeNum(UserCodeNum userCodeNum) { // TODO Auto-generated method stub userCodeNumDAO.insertUserCodeNum(userCodeNum); } @Override public UserCodeNum select() { // TODO Auto-generated method stub return userCodeNumDAO.selectCode(); } }
662
0.811178
0.811178
25
25.48
20.607027
66
false
false
0
0
0
0
0
0
1
false
false
1
5396eb3275033b8a1556ac669cd07419a09f0ecc
6,665,789,264,212
3e423ecf7b24079fbcbd43b03552b5c0d44773bf
/app/src/main/java/com/mkuech/spotifystreamer_stage2/TopTracksFragment.java
ddf57b0adfaab6a6ee63b2c00caf0566eef7a90a
[]
no_license
mkuech/spotifystage2
https://github.com/mkuech/spotifystage2
a0659af8360884671ed87bef8faba13b6471bc1a
b0806c1de5f12e7d26e8e6ee01a5cfa877be28f3
refs/heads/master
2016-03-30T21:16:21.449000
2015-09-07T04:17:23
2015-09-07T04:17:23
38,947,336
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mkuech.spotifystreamer_stage2; import android.app.Activity; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.util.ArrayMap; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; import com.mkuech.spotifystreamer_stage2.model.TrackParcelable; import java.util.Locale; import kaaes.spotify.webapi.android.SpotifyApi; import kaaes.spotify.webapi.android.SpotifyService; import kaaes.spotify.webapi.android.models.Track; import kaaes.spotify.webapi.android.models.Tracks; import retrofit.RetrofitError; public class TopTracksFragment extends Fragment { public static final String TAG = TopTracksFragment.class.getSimpleName(); public static final String FRAG_TAG = "toptracks"; private String mArtistId; private ListView mList; private BaseAdapter mAdapter; private TrackParcelable[] mResults; private RequestManager mRm; private View mProgress; private View mEmpty; private boolean mIsLoading = true; private TopTracksTask mTask; private TrackSelectionListener mTrackSelectionListener; public static TopTracksFragment newInstance(String artistId) { TopTracksFragment frag = new TopTracksFragment(); Bundle args = new Bundle(); args.putString(SpotifyInfo.ARG_ARTIST_ID, artistId); frag.setArguments(args); return frag; } public TopTracksFragment() { } @Override public void onAttach(Activity activity) { super.onAttach(activity); mRm = Glide.with(activity); if( activity instanceof TrackSelectionListener ) mTrackSelectionListener = (TrackSelectionListener) activity; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { setArtistId(getArguments().getString(SpotifyInfo.ARG_ARTIST_ID)); } else { mIsLoading = false; } //Let's retain this so we don't interrupt our AsyncTask on configuration changes, but // be sure to reinstantiate anything with a reference to Context setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_top_tracks, container, false); mList = (ListView) view.findViewById(android.R.id.list); mProgress = view.findViewById(R.id.loading); mEmpty = view.findViewById(android.R.id.empty); mAdapter = new TopTracksAdapter(getActivity()); mList.setAdapter(mAdapter); mList.setEmptyView(mEmpty); mList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if( mTrackSelectionListener != null ) mTrackSelectionListener.chooseTrack(mResults, position); } }); updateProgressVisibility(); return view; } private void updateProgressVisibility() { if (mProgress == null || mEmpty == null || mProgress == null ) return; if (mIsLoading) { mEmpty.setVisibility(View.GONE); mProgress.setVisibility(View.VISIBLE); } else { mProgress.setVisibility(View.GONE); } } public void setArtistId(String artistId) { if( artistId.equals(mArtistId) ) return; mArtistId = artistId; mIsLoading = true; updateProgressVisibility(); resetTask(); //Use the user's default locale's country code, or US if missing for some reason String country = Locale.getDefault().getCountry(); if ("".equals(country)) country = Locale.US.getCountry(); Log.d(TAG, "About to launch mTask"); mTask.execute(mArtistId, country); } private void resetTask() { if( mTask != null && !mTask.isCancelled() ) mTask.cancel(true); mTask = new TopTracksTask(getActivity().getResources().getDimensionPixelSize(R.dimen.thumbnail_width)); } @Override public void onDetach() { super.onDetach(); mTrackSelectionListener = null; } @Override public void onDestroy() { if( mTask != null ) { mTask.cancel(true); mTask = null; } super.onDestroy(); } private class TopTracksAdapter extends BaseAdapter { private LayoutInflater mInflater; public TopTracksAdapter(Context context) { mInflater = LayoutInflater.from(context); } @Override public int getCount() { return mResults == null ? 0 : mResults.length; } @Override public TrackParcelable getItem(int position) { return mResults == null ? null : mResults[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; ViewHolder holder; TrackParcelable trackParcelable = getItem(position); if (convertView != null) { view = convertView; holder = (ViewHolder) view.getTag(); } else { view = mInflater.inflate(R.layout.item_top_track, parent, false); holder = new ViewHolder(); holder.thumbnail = (ImageView) view.findViewById(R.id.thumbnail); holder.track = (TextView) view.findViewById(android.R.id.text1); holder.album = (TextView) view.findViewById(android.R.id.text2); view.setTag(holder); } holder.track.setText(trackParcelable.getName()); holder.album.setText(trackParcelable.getAlbumName()); Drawable placeholder = new ColorDrawable(getResources().getColor(R.color.colorAccent)); if( !TextUtils.isEmpty(trackParcelable.getAlbumArt()) ) { mRm.load(trackParcelable.getAlbumArt()) .placeholder(placeholder) .error(placeholder) .crossFade() .into(holder.thumbnail); } else { holder.thumbnail.setImageResource(R.drawable.missing_image); } return view; } } private class TopTracksTask extends AsyncTask<String, Void, TrackParcelable[]> { private SpotifyService mSpotifyService; private ArrayMap<String, Object> mSpotifyOptions; private String mArtistId; private int mMinWidth; private String mCountryCode; TopTracksTask (int minWidth) { mMinWidth = minWidth; SpotifyApi api = new SpotifyApi(); mSpotifyService = api.getService(); mSpotifyOptions = new ArrayMap<String, Object>(); } @Override protected TrackParcelable[] doInBackground(String... params) { mArtistId = params[0]; mCountryCode = params[1]; mSpotifyOptions.put(SpotifyService.COUNTRY, mCountryCode); Log.d(TAG, "doInBackground"); int tries = 0; TrackParcelable[] trackParcelables = null; boolean hasError = false; do { hasError = false; try { Log.d(TAG, "About to issue request"); Tracks tracks = mSpotifyService.getArtistTopTrack(mArtistId, mSpotifyOptions); Log.d(TAG, "We have some results"); int size = tracks.tracks.size(); trackParcelables = new TrackParcelable[size]; Track track; String albumArt; for( int sc = 0; sc < size; sc++ ) { track = tracks.tracks.get(sc); if (track.album.images != null && track.album.images.size() > 0) { //the images start out larger and get smaller, so find something a little more // efficient to load at this thumbnail size int imageIndex = 0; for (int i = 1; i < track.album.images.size(); i++) { if (track.album.images.get(i).width >= mMinWidth) imageIndex = i; } albumArt = track.album.images.get(imageIndex).url; } else { albumArt = null; } String artistName = null; if( track.artists != null ) { for( int ac = 0; ac < track.artists.size() && artistName == null; ac++ ) { if( mArtistId.equals(track.artists.get(ac).id) ) artistName = track.artists.get(ac).name; } } trackParcelables[sc] = new TrackParcelable( track.id, track.name, track.duration_ms, track.preview_url, mArtistId, artistName, track.album.name, albumArt ); } } catch (RetrofitError e) { hasError = true; Log.e(TAG, "Error while retrieving top tracks", e); } } while( !isCancelled() && tries++ < 3 && trackParcelables == null ); if( hasError ) { //if there's still an error after 3 tries, return null and we'll know we can alert // the user there's trouble return null; } //if there wasn't an error, at least return an empty result so we know there truly are // no results and it wasn't some other problem that caused no results to show if( trackParcelables == null ) trackParcelables = new TrackParcelable[0]; return trackParcelables; } @Override protected void onPostExecute(TrackParcelable[] trackParcelables) { mIsLoading = false; updateProgressVisibility(); mResults = trackParcelables; if( mAdapter != null ) mAdapter.notifyDataSetChanged(); Log.d(TAG, "Found some results: " + mResults.length); } @Override protected void onCancelled() { mIsLoading = false; updateProgressVisibility(); super.onCancelled(); } } private static class ViewHolder { public ImageView thumbnail; public TextView track; public TextView album; } public interface TrackSelectionListener { public void chooseTrack(TrackParcelable[] tracks, int selection); } }
UTF-8
Java
11,870
java
TopTracksFragment.java
Java
[]
null
[]
package com.mkuech.spotifystreamer_stage2; import android.app.Activity; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.util.ArrayMap; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; import com.mkuech.spotifystreamer_stage2.model.TrackParcelable; import java.util.Locale; import kaaes.spotify.webapi.android.SpotifyApi; import kaaes.spotify.webapi.android.SpotifyService; import kaaes.spotify.webapi.android.models.Track; import kaaes.spotify.webapi.android.models.Tracks; import retrofit.RetrofitError; public class TopTracksFragment extends Fragment { public static final String TAG = TopTracksFragment.class.getSimpleName(); public static final String FRAG_TAG = "toptracks"; private String mArtistId; private ListView mList; private BaseAdapter mAdapter; private TrackParcelable[] mResults; private RequestManager mRm; private View mProgress; private View mEmpty; private boolean mIsLoading = true; private TopTracksTask mTask; private TrackSelectionListener mTrackSelectionListener; public static TopTracksFragment newInstance(String artistId) { TopTracksFragment frag = new TopTracksFragment(); Bundle args = new Bundle(); args.putString(SpotifyInfo.ARG_ARTIST_ID, artistId); frag.setArguments(args); return frag; } public TopTracksFragment() { } @Override public void onAttach(Activity activity) { super.onAttach(activity); mRm = Glide.with(activity); if( activity instanceof TrackSelectionListener ) mTrackSelectionListener = (TrackSelectionListener) activity; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { setArtistId(getArguments().getString(SpotifyInfo.ARG_ARTIST_ID)); } else { mIsLoading = false; } //Let's retain this so we don't interrupt our AsyncTask on configuration changes, but // be sure to reinstantiate anything with a reference to Context setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_top_tracks, container, false); mList = (ListView) view.findViewById(android.R.id.list); mProgress = view.findViewById(R.id.loading); mEmpty = view.findViewById(android.R.id.empty); mAdapter = new TopTracksAdapter(getActivity()); mList.setAdapter(mAdapter); mList.setEmptyView(mEmpty); mList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if( mTrackSelectionListener != null ) mTrackSelectionListener.chooseTrack(mResults, position); } }); updateProgressVisibility(); return view; } private void updateProgressVisibility() { if (mProgress == null || mEmpty == null || mProgress == null ) return; if (mIsLoading) { mEmpty.setVisibility(View.GONE); mProgress.setVisibility(View.VISIBLE); } else { mProgress.setVisibility(View.GONE); } } public void setArtistId(String artistId) { if( artistId.equals(mArtistId) ) return; mArtistId = artistId; mIsLoading = true; updateProgressVisibility(); resetTask(); //Use the user's default locale's country code, or US if missing for some reason String country = Locale.getDefault().getCountry(); if ("".equals(country)) country = Locale.US.getCountry(); Log.d(TAG, "About to launch mTask"); mTask.execute(mArtistId, country); } private void resetTask() { if( mTask != null && !mTask.isCancelled() ) mTask.cancel(true); mTask = new TopTracksTask(getActivity().getResources().getDimensionPixelSize(R.dimen.thumbnail_width)); } @Override public void onDetach() { super.onDetach(); mTrackSelectionListener = null; } @Override public void onDestroy() { if( mTask != null ) { mTask.cancel(true); mTask = null; } super.onDestroy(); } private class TopTracksAdapter extends BaseAdapter { private LayoutInflater mInflater; public TopTracksAdapter(Context context) { mInflater = LayoutInflater.from(context); } @Override public int getCount() { return mResults == null ? 0 : mResults.length; } @Override public TrackParcelable getItem(int position) { return mResults == null ? null : mResults[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; ViewHolder holder; TrackParcelable trackParcelable = getItem(position); if (convertView != null) { view = convertView; holder = (ViewHolder) view.getTag(); } else { view = mInflater.inflate(R.layout.item_top_track, parent, false); holder = new ViewHolder(); holder.thumbnail = (ImageView) view.findViewById(R.id.thumbnail); holder.track = (TextView) view.findViewById(android.R.id.text1); holder.album = (TextView) view.findViewById(android.R.id.text2); view.setTag(holder); } holder.track.setText(trackParcelable.getName()); holder.album.setText(trackParcelable.getAlbumName()); Drawable placeholder = new ColorDrawable(getResources().getColor(R.color.colorAccent)); if( !TextUtils.isEmpty(trackParcelable.getAlbumArt()) ) { mRm.load(trackParcelable.getAlbumArt()) .placeholder(placeholder) .error(placeholder) .crossFade() .into(holder.thumbnail); } else { holder.thumbnail.setImageResource(R.drawable.missing_image); } return view; } } private class TopTracksTask extends AsyncTask<String, Void, TrackParcelable[]> { private SpotifyService mSpotifyService; private ArrayMap<String, Object> mSpotifyOptions; private String mArtistId; private int mMinWidth; private String mCountryCode; TopTracksTask (int minWidth) { mMinWidth = minWidth; SpotifyApi api = new SpotifyApi(); mSpotifyService = api.getService(); mSpotifyOptions = new ArrayMap<String, Object>(); } @Override protected TrackParcelable[] doInBackground(String... params) { mArtistId = params[0]; mCountryCode = params[1]; mSpotifyOptions.put(SpotifyService.COUNTRY, mCountryCode); Log.d(TAG, "doInBackground"); int tries = 0; TrackParcelable[] trackParcelables = null; boolean hasError = false; do { hasError = false; try { Log.d(TAG, "About to issue request"); Tracks tracks = mSpotifyService.getArtistTopTrack(mArtistId, mSpotifyOptions); Log.d(TAG, "We have some results"); int size = tracks.tracks.size(); trackParcelables = new TrackParcelable[size]; Track track; String albumArt; for( int sc = 0; sc < size; sc++ ) { track = tracks.tracks.get(sc); if (track.album.images != null && track.album.images.size() > 0) { //the images start out larger and get smaller, so find something a little more // efficient to load at this thumbnail size int imageIndex = 0; for (int i = 1; i < track.album.images.size(); i++) { if (track.album.images.get(i).width >= mMinWidth) imageIndex = i; } albumArt = track.album.images.get(imageIndex).url; } else { albumArt = null; } String artistName = null; if( track.artists != null ) { for( int ac = 0; ac < track.artists.size() && artistName == null; ac++ ) { if( mArtistId.equals(track.artists.get(ac).id) ) artistName = track.artists.get(ac).name; } } trackParcelables[sc] = new TrackParcelable( track.id, track.name, track.duration_ms, track.preview_url, mArtistId, artistName, track.album.name, albumArt ); } } catch (RetrofitError e) { hasError = true; Log.e(TAG, "Error while retrieving top tracks", e); } } while( !isCancelled() && tries++ < 3 && trackParcelables == null ); if( hasError ) { //if there's still an error after 3 tries, return null and we'll know we can alert // the user there's trouble return null; } //if there wasn't an error, at least return an empty result so we know there truly are // no results and it wasn't some other problem that caused no results to show if( trackParcelables == null ) trackParcelables = new TrackParcelable[0]; return trackParcelables; } @Override protected void onPostExecute(TrackParcelable[] trackParcelables) { mIsLoading = false; updateProgressVisibility(); mResults = trackParcelables; if( mAdapter != null ) mAdapter.notifyDataSetChanged(); Log.d(TAG, "Found some results: " + mResults.length); } @Override protected void onCancelled() { mIsLoading = false; updateProgressVisibility(); super.onCancelled(); } } private static class ViewHolder { public ImageView thumbnail; public TextView track; public TextView album; } public interface TrackSelectionListener { public void chooseTrack(TrackParcelable[] tracks, int selection); } }
11,870
0.573547
0.57203
333
34.648647
25.668123
111
false
false
0
0
0
0
0
0
0.615616
false
false
1
f1f886747f3187e063c9a3b4865be1e80000ee92
11,261,404,316,289
ae30922295d5dd6b7b678bf4e37a1f1833be9a85
/src/main/java/com/wxh/leetcode/done/Leetcode400.java
5806e6faf00d1a44e6081eceb70819d4e6a8c312
[]
no_license
wxh646121331/test
https://github.com/wxh646121331/test
56cabf682aca76262ddad175a8a39b3c543a0999
ca32a6a3103dc18a8ef66244a8346b47be090317
refs/heads/master
2022-07-02T03:20:38.823000
2021-12-01T09:19:23
2021-12-01T09:19:23
190,356,507
1
0
null
false
2022-06-17T02:46:54
2019-06-05T08:29:37
2021-12-01T09:19:33
2022-06-17T02:46:51
4,671
1
0
3
Java
false
false
package com.wxh.leetcode.done; /** * @author wuxinhong * @date 2021/11/30 3:11 下午 */ public class Leetcode400 { public int findNthDigit(int n) { int zone = findZone(n); for(int i=1; i<zone; i++){ int count = 9 * i * pow(i-1); n = n - count; } // 计算剩余的数 int a = (n-1) / zone; int b = (n-1) % zone; int c = pow(zone-1) + a; int[] arr = new int[zone]; int index = 0; int i = zone; while (i > 0){ int d = pow(i-1); arr[index++] = c / d; c = c % d; i--; } return arr[b]; } /** * 找到所属几位数区间 * @param n * @return */ private int findZone(int n){ int i=1; long m = n; while (true){ long count = 9L * i * pow(i-1); m = m-count; if(m > 0){ i++; }else { break; } } return i; } private int pow(int n){ int res=1; for(int i=0; i<n; i++){ res *= 10; } return res; } public static void main(String[] args) { Leetcode400 leetcode400 = new Leetcode400(); System.out.println(leetcode400.findNthDigit(11)); } }
UTF-8
Java
1,355
java
Leetcode400.java
Java
[ { "context": "package com.wxh.leetcode.done;\n\n/**\n * @author wuxinhong\n * @date 2021/11/30 3:11 下午\n */\npublic class Leet", "end": 56, "score": 0.9986686110496521, "start": 47, "tag": "USERNAME", "value": "wuxinhong" } ]
null
[]
package com.wxh.leetcode.done; /** * @author wuxinhong * @date 2021/11/30 3:11 下午 */ public class Leetcode400 { public int findNthDigit(int n) { int zone = findZone(n); for(int i=1; i<zone; i++){ int count = 9 * i * pow(i-1); n = n - count; } // 计算剩余的数 int a = (n-1) / zone; int b = (n-1) % zone; int c = pow(zone-1) + a; int[] arr = new int[zone]; int index = 0; int i = zone; while (i > 0){ int d = pow(i-1); arr[index++] = c / d; c = c % d; i--; } return arr[b]; } /** * 找到所属几位数区间 * @param n * @return */ private int findZone(int n){ int i=1; long m = n; while (true){ long count = 9L * i * pow(i-1); m = m-count; if(m > 0){ i++; }else { break; } } return i; } private int pow(int n){ int res=1; for(int i=0; i<n; i++){ res *= 10; } return res; } public static void main(String[] args) { Leetcode400 leetcode400 = new Leetcode400(); System.out.println(leetcode400.findNthDigit(11)); } }
1,355
0.402725
0.36866
62
20.306452
12.878575
57
false
false
0
0
0
0
0
0
0.5
false
false
1
8cfe3d6d67d4c4e6b30e78eb6a15c0dc3562d0d4
8,134,668,113,418
fed65be3f8999aff8ff762457a1b87b3d4b094b9
/Work/Owfar/owfar-core/core/src/main/java/com/owfar/core/db/dao_impl/StickersGroupDaoImpl.java
5a2cfd9467350de82d3c4c402321639b92c54e66
[]
no_license
Raylyan/owfar-mobile-android
https://github.com/Raylyan/owfar-mobile-android
7d8281566240d9be61437593357cf5fd89e47b77
57b7779ad9d701184c020a7a38d3a8b9991ad16c
refs/heads/master
2017-11-26T03:48:48.994000
2016-07-11T08:58:31
2016-07-11T08:58:31
54,887,024
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.owfar.core.db.dao_impl; import com.j256.ormlite.dao.BaseDaoImpl; import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.support.ConnectionSource; import com.owfar.core.models.users.Media; import com.owfar.core.models.users.Sticker; import com.owfar.core.models.users.StickersGroup; import java.sql.SQLException; public class StickersGroupDaoImpl extends BaseDaoImpl<StickersGroup, Long> { private StickerDaoImpl stickerDao; private MediaDaoImpl mediaDao; //region Constructors public StickersGroupDaoImpl(ConnectionSource connectionSource, Class<StickersGroup> dataClass) throws SQLException { super(connectionSource, dataClass); stickerDao = DaoManager.createDao(connectionSource, Sticker.class); mediaDao = DaoManager.createDao(connectionSource, Media.class); } //endregion @Override public CreateOrUpdateStatus createOrUpdate(StickersGroup data) throws SQLException { if (data != null) { if (data.getStickers() != null) for (Sticker sticker : data.getStickers()) if (sticker != null) { sticker.setStickersGroup(data); stickerDao.createOrUpdate(sticker); } if (data.getPhoto() != null) mediaDao.createOrUpdate(data.getPhoto()); } return super.createOrUpdate(data); } }
UTF-8
Java
1,409
java
StickersGroupDaoImpl.java
Java
[]
null
[]
package com.owfar.core.db.dao_impl; import com.j256.ormlite.dao.BaseDaoImpl; import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.support.ConnectionSource; import com.owfar.core.models.users.Media; import com.owfar.core.models.users.Sticker; import com.owfar.core.models.users.StickersGroup; import java.sql.SQLException; public class StickersGroupDaoImpl extends BaseDaoImpl<StickersGroup, Long> { private StickerDaoImpl stickerDao; private MediaDaoImpl mediaDao; //region Constructors public StickersGroupDaoImpl(ConnectionSource connectionSource, Class<StickersGroup> dataClass) throws SQLException { super(connectionSource, dataClass); stickerDao = DaoManager.createDao(connectionSource, Sticker.class); mediaDao = DaoManager.createDao(connectionSource, Media.class); } //endregion @Override public CreateOrUpdateStatus createOrUpdate(StickersGroup data) throws SQLException { if (data != null) { if (data.getStickers() != null) for (Sticker sticker : data.getStickers()) if (sticker != null) { sticker.setStickersGroup(data); stickerDao.createOrUpdate(sticker); } if (data.getPhoto() != null) mediaDao.createOrUpdate(data.getPhoto()); } return super.createOrUpdate(data); } }
1,409
0.686302
0.679915
38
36.105263
28.70429
120
false
false
0
0
0
0
0
0
0.578947
false
false
1
50e1e4976ee93e75c5e5c0058c3d575dca88f148
21,440,476,743,127
773a886cdde905094d40d40387f4e12204f32f19
/rxphoto/src/main/java/sino/android/rxphoto/RxPhoto.java
b3ce1ed388e23af9f77573ea42eaa57c1809e7ba
[]
no_license
RxSino/RxPhotoX
https://github.com/RxSino/RxPhotoX
c6b5be159c09bc283f2afec5f1c4832f3ce0a060
5b4219188b405d4ac4879c8465c6fb3accf8507b
refs/heads/master
2022-06-19T21:52:59.590000
2020-05-13T06:18:08
2020-05-13T06:18:08
258,907,877
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sino.android.rxphoto; import android.net.Uri; public class RxPhoto { private String path; private Uri uri; public RxPhoto(String path, Uri uri) { this.path = path; this.uri = uri; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Uri getUri() { return uri; } public void setUri(Uri uri) { this.uri = uri; } }
UTF-8
Java
476
java
RxPhoto.java
Java
[]
null
[]
package sino.android.rxphoto; import android.net.Uri; public class RxPhoto { private String path; private Uri uri; public RxPhoto(String path, Uri uri) { this.path = path; this.uri = uri; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Uri getUri() { return uri; } public void setUri(Uri uri) { this.uri = uri; } }
476
0.560924
0.560924
30
14.866667
13.111657
42
false
false
0
0
0
0
0
0
0.366667
false
false
1
fbefa6563a00567a2499e9226e2c6f7c4d0f2142
8,890,582,370,042
b482d201acdaf9540673079a8c9bdd8d050dfaf0
/src/main/java/com/example/WebsocketManager.java
04a1d08558c45417f3a97564ee2c9b21e0289d09
[]
no_license
bugdealer/client-vn
https://github.com/bugdealer/client-vn
749a33d8e509bcb86b394d6795e76cbba3810b3d
1a97206af27c8c3dcc3520b907d7de6877ffa1a7
refs/heads/master
2020-12-30T13:28:52.448000
2017-05-14T06:24:45
2017-05-14T06:24:45
91,224,088
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example; public class WebsocketManager { }
UTF-8
Java
57
java
WebsocketManager.java
Java
[]
null
[]
package com.example; public class WebsocketManager { }
57
0.77193
0.77193
5
10.4
12.815616
31
false
false
0
0
0
0
0
0
0.2
false
false
1
43c8f28e881c1215b1a37dc1ace63b17ee321255
25,598,005,142,802
20345bdc861ea09a1da1aa5c97b421364c5960b0
/src/main/java/com/service/climatic/proveedor/AccuweatherProveedor.java
b7cca34dd7316e7eace0614d94d86ee5f6d4c64e
[]
no_license
Wlanez/climatic
https://github.com/Wlanez/climatic
aab234163c3480e4decf756e2ee773569075eb84
b5e1646d7d4a4ab5bb6c4420034549d9c37fae7b
refs/heads/master
2020-03-21T08:22:20.212000
2019-03-12T14:44:07
2019-03-12T14:44:07
138,338,887
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.service.climatic.proveedor; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.service.climatic.web.ClimaDTO; import com.service.climatic.web.ForecastDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriTemplate; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; public class AccuweatherProveedor implements ApiProveedor{ private static final Logger logger = LoggerFactory.getLogger(AccuweatherProveedor.class); @Value("${key.accuweather}") String accuweatherKey; static final String TEMPERATURA = "Temperature"; static final String VALUE = "Value"; RestTemplate restTemplate = new RestTemplate(); private static final String CLIMA_ACTUAL_URL = "http://dataservice.accuweather.com/currentconditions/v1/{ciudad}?apikey={key}"; private static final String PRONOSTICO_CLIMA_URL = "http://dataservice.accuweather.com/forecasts/v1/daily/5day/{city}?apikey={key}"; // Usuarios gratuitos: Solo me permite buscar cinco dias @Override public ClimaDTO getClima(String ciudad, String unidadGrado) { logger.info("Clima de {}", ciudad); try { URI url = new UriTemplate(CLIMA_ACTUAL_URL).expand(ciudadCache.get(ciudad), accuweatherKey); RequestEntity request = RequestEntity.get(url).accept(MediaType.APPLICATION_JSON).build(); ResponseEntity<String> exchange = this.restTemplate .exchange(request, String.class); return clima(exchange.getBody(), ciudad, unidadGrado); } catch (IOException e) { logger.error(e.getMessage()); } return new ClimaDTO(); } private ClimaDTO clima(String body, String ciudad, String unidadGrado) throws IOException{ ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(body); ClimaDTO climaDTO = new ClimaDTO(); climaDTO.setDescripcion(root.findPath("WeatherText").asText()); if("ce".equals(unidadGrado)){ climaDTO.setTemperaturaActual(root.findPath(TEMPERATURA).findPath("Metric").findPath(VALUE).asText()); }else{ climaDTO.setTemperaturaActual(root.findPath(TEMPERATURA).findPath("Imperial").findPath(VALUE).asText()); } climaPronostico(climaDTO,ciudad,unidadGrado); return climaDTO; } private ClimaDTO climaPronostico(ClimaDTO climaDTO, String ciudad, String unidadGrado) throws IOException { StringBuilder urlUnit = new StringBuilder(PRONOSTICO_CLIMA_URL); if("ce".equals(unidadGrado)){ urlUnit.append("&metric=true"); } URI url = new UriTemplate(urlUnit.toString()).expand(ciudadCache.get(ciudad), accuweatherKey); RequestEntity request = RequestEntity.get(url).accept(MediaType.APPLICATION_JSON).build(); ResponseEntity<String> exchange = this.restTemplate .exchange(request, String.class); ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree( exchange.getBody()); ArrayList<ForecastDTO> forecastList = new ArrayList<>(); Iterator<JsonNode> dailyForecastsIter = root.findPath("DailyForecasts").elements(); while (dailyForecastsIter.hasNext()) { JsonNode dailyForecast = dailyForecastsIter.next(); ForecastDTO forecastDTO = new ForecastDTO(); forecastDTO.setTemperaturaMin(dailyForecast.findPath(TEMPERATURA).findPath("Minimum").findPath(VALUE).toString()); forecastDTO.setTemperaturaMax(dailyForecast.findPath(TEMPERATURA).findPath("Maximum").findPath(VALUE).toString()); forecastDTO.setDescripcion(dailyForecast.findPath("Headline").findPath("Text").toString()); forecastList.add(forecastDTO); } climaDTO.setForecast(forecastList); return climaDTO; } //En teoria se debe obtener los ID de ciudad de accuweather para ingresarlo a un cache con limite de tiempo private static HashMap<String, String> ciudadCache = new HashMap<>(); static{ ciudadCache.put("Bogota/Colombia","107487"); //accuweather city ID ciudadCache.put("Buenos Aires/Argentina","7894"); // ciudadCache.put("Santiago/Chile","7894"); // } }
UTF-8
Java
4,842
java
AccuweatherProveedor.java
Java
[]
null
[]
package com.service.climatic.proveedor; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.service.climatic.web.ClimaDTO; import com.service.climatic.web.ForecastDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriTemplate; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; public class AccuweatherProveedor implements ApiProveedor{ private static final Logger logger = LoggerFactory.getLogger(AccuweatherProveedor.class); @Value("${key.accuweather}") String accuweatherKey; static final String TEMPERATURA = "Temperature"; static final String VALUE = "Value"; RestTemplate restTemplate = new RestTemplate(); private static final String CLIMA_ACTUAL_URL = "http://dataservice.accuweather.com/currentconditions/v1/{ciudad}?apikey={key}"; private static final String PRONOSTICO_CLIMA_URL = "http://dataservice.accuweather.com/forecasts/v1/daily/5day/{city}?apikey={key}"; // Usuarios gratuitos: Solo me permite buscar cinco dias @Override public ClimaDTO getClima(String ciudad, String unidadGrado) { logger.info("Clima de {}", ciudad); try { URI url = new UriTemplate(CLIMA_ACTUAL_URL).expand(ciudadCache.get(ciudad), accuweatherKey); RequestEntity request = RequestEntity.get(url).accept(MediaType.APPLICATION_JSON).build(); ResponseEntity<String> exchange = this.restTemplate .exchange(request, String.class); return clima(exchange.getBody(), ciudad, unidadGrado); } catch (IOException e) { logger.error(e.getMessage()); } return new ClimaDTO(); } private ClimaDTO clima(String body, String ciudad, String unidadGrado) throws IOException{ ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(body); ClimaDTO climaDTO = new ClimaDTO(); climaDTO.setDescripcion(root.findPath("WeatherText").asText()); if("ce".equals(unidadGrado)){ climaDTO.setTemperaturaActual(root.findPath(TEMPERATURA).findPath("Metric").findPath(VALUE).asText()); }else{ climaDTO.setTemperaturaActual(root.findPath(TEMPERATURA).findPath("Imperial").findPath(VALUE).asText()); } climaPronostico(climaDTO,ciudad,unidadGrado); return climaDTO; } private ClimaDTO climaPronostico(ClimaDTO climaDTO, String ciudad, String unidadGrado) throws IOException { StringBuilder urlUnit = new StringBuilder(PRONOSTICO_CLIMA_URL); if("ce".equals(unidadGrado)){ urlUnit.append("&metric=true"); } URI url = new UriTemplate(urlUnit.toString()).expand(ciudadCache.get(ciudad), accuweatherKey); RequestEntity request = RequestEntity.get(url).accept(MediaType.APPLICATION_JSON).build(); ResponseEntity<String> exchange = this.restTemplate .exchange(request, String.class); ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree( exchange.getBody()); ArrayList<ForecastDTO> forecastList = new ArrayList<>(); Iterator<JsonNode> dailyForecastsIter = root.findPath("DailyForecasts").elements(); while (dailyForecastsIter.hasNext()) { JsonNode dailyForecast = dailyForecastsIter.next(); ForecastDTO forecastDTO = new ForecastDTO(); forecastDTO.setTemperaturaMin(dailyForecast.findPath(TEMPERATURA).findPath("Minimum").findPath(VALUE).toString()); forecastDTO.setTemperaturaMax(dailyForecast.findPath(TEMPERATURA).findPath("Maximum").findPath(VALUE).toString()); forecastDTO.setDescripcion(dailyForecast.findPath("Headline").findPath("Text").toString()); forecastList.add(forecastDTO); } climaDTO.setForecast(forecastList); return climaDTO; } //En teoria se debe obtener los ID de ciudad de accuweather para ingresarlo a un cache con limite de tiempo private static HashMap<String, String> ciudadCache = new HashMap<>(); static{ ciudadCache.put("Bogota/Colombia","107487"); //accuweather city ID ciudadCache.put("Buenos Aires/Argentina","7894"); // ciudadCache.put("Santiago/Chile","7894"); // } }
4,842
0.681743
0.677819
129
35.534885
36.120178
150
false
false
0
0
0
0
0
0
0.612403
false
false
1
23894306c9e7afa69367a56a2f1bc64e9f482eb1
18,133,351,946,519
710eb6c2c8ee5bc7ef54320efc37f09bf621c97d
/proerp/src/main/java/com/protostar/billingnstock/purchase/services/UploadSupplierMasterServletTask.java
72d9134c569e1944184d0feae0858e09ae863de4
[]
no_license
ProtostarConsulting/proerp
https://github.com/ProtostarConsulting/proerp
6fe531aab7cc236028fdb9de95f93aa9ad841738
979553b793a85ec2bcc1d014c69b7cfcaff5cd7f
refs/heads/master
2018-10-22T18:40:03.472000
2018-10-22T14:10:01
2018-10-22T14:10:01
64,774,914
0
0
null
false
2018-08-16T15:06:16
2016-08-02T16:48:31
2018-08-16T14:02:06
2018-08-16T15:06:16
180,011
0
0
0
JavaScript
false
null
package com.protostar.billingnstock.purchase.services; import static com.googlecode.objectify.ObjectifyService.ofy; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.channels.Channels; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; import com.google.appengine.api.NamespaceManager; import com.google.appengine.api.taskqueue.DeferredTask; import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.appengine.tools.cloudstorage.GcsInputChannel; import com.google.appengine.tools.cloudstorage.GcsService; import com.google.appengine.tools.cloudstorage.GcsServiceFactory; import com.google.appengine.tools.cloudstorage.RetryParams; import com.googlecode.objectify.Key; import com.protostar.billingnstock.account.entities.AccountEntity; import com.protostar.billingnstock.account.entities.AccountGroupEntity; import com.protostar.billingnstock.crm.services.UploadCustomerServletTask; import com.protostar.billingnstock.cust.services.CustomerService; import com.protostar.billingnstock.purchase.entities.SupplierEntity; import com.protostar.billingnstock.tax.entities.GSTRegistration; import com.protostar.billingnstock.user.entities.BusinessEntity; import com.protostar.billingnstock.user.entities.UserEntity; import com.protostar.billingnstock.user.services.UserService; import com.protostar.billnstock.entity.Address; import com.protostar.billnstock.until.data.Constants; import com.protostar.billnstock.until.data.EntityUtil; import com.protostar.billnstock.until.data.SequenceGeneratorShardedService; import com.protostar.billnstock.until.data.WebUtil; import com.protostar.billnstock.until.data.Constants.AccountingAccountType; public class UploadSupplierMasterServletTask implements DeferredTask { private final static long serialVersionUID = 1L; private final static Logger logger = Logger.getLogger(UploadCustomerServletTask.class.getName()); private GcsFilename gcsFile; private Long businessId; public UploadSupplierMasterServletTask() { } public UploadSupplierMasterServletTask(Long businessId, GcsFilename gcsFile) { this.setBusinessId(businessId); this.gcsFile = gcsFile; } @Override public void run() { NamespaceManager.set(getBusinessId().toString()); CustomerService customerService = new CustomerService(); BusinessEntity businessEntity = customerService.getBusinessById(getBusinessId()); logger.info("WebUtil.getCurrentUser(): " + WebUtil.getCurrentUser()); final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder() .initialRetryDelayMillis(10).retryMaxAttempts(10).totalRetryPeriodMillis(15000).build()); GcsInputChannel readChannel = gcsService.openPrefetchingReadChannel(gcsFile, 0, Constants.DOCUMENT_DEFAULT_MAX_SIZE); ByteArrayOutputStream ops = new ByteArrayOutputStream(); try { WebUtil.copy(Channels.newInputStream(readChannel), ops); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String fileContent = ops.toString(); String[] supList = fileContent.split("\n"); logger.info("custList.length: " + supList.length); int startItemNumber = 1; if (supList.length > 1) { SequenceGeneratorShardedService sequenceGenService = new SequenceGeneratorShardedService( EntityUtil.getBusinessRawKey(businessEntity), Constants.SUPPLIER_NO_COUNTER, "Supplier Counter"); startItemNumber = sequenceGenService.getNextSequenceNumber(); if ((supList.length - 2) > 0) sequenceGenService.incrementBy(supList.length - 2); // -2 because one is already increased by getNextSequenceNumber() above and one // for column header row } Date todaysDate = new Date(); List<SupplierEntity> supplierList = new ArrayList<SupplierEntity>(); for (int row = 1; row < supList.length; row++) { String suppFName = "NA", suppLName = "NA", mobileNo = "9999999999", email = "na@dummy.com", line1 = "NA", pin = "NA", country = "NA", panNo = "NA", tags = "NA", state = "NA", city = "NA"; try { String[] split = supList[row].split(","); if (split == null || split.length < 4) { continue; } ////// Below check for duplicate supplier names . SupplierEntity supplierMasterItem = null; List<SupplierEntity> duplicateSuppliers = ofy().load().type(SupplierEntity.class) .ancestor(Key.create(BusinessEntity.class, getBusinessId())) .filter("supplierNameFullIndex", split[1].trim().toLowerCase()).list(); if (duplicateSuppliers != null && !duplicateSuppliers.isEmpty()) { supplierMasterItem = duplicateSuppliers.get(0); } else { supplierMasterItem = new SupplierEntity(); } Address supplierAddress = new Address(); supplierMasterItem.setBusiness(businessEntity); supplierMasterItem.setCreatedDate(todaysDate); supplierMasterItem.setSupplierName(split[1]); if (StringUtils.isNotBlank(split[2])) { suppFName = split[2]; } supplierMasterItem.setContactFName(suppFName); if (StringUtils.isNotBlank(split[3])) { suppLName = split[3]; } supplierMasterItem.setContactLName(suppLName); if (split.length >= 4) { if (StringUtils.isNotBlank(split[4].trim())) { mobileNo = split[4].replaceAll("\\s+", ""); } supplierMasterItem.setMobile(mobileNo); } if (split.length > 5) { if (StringUtils.isNotBlank(split[5])) { email = split[5].trim(); } supplierMasterItem.setEmail(email); } if (split.length > 6) { if (StringUtils.isNotBlank(split[6])) { line1 = split[6].replaceAll(Constants.CSV_COMMA_TEMP_CHAR_SEQUENCE, ","); } supplierAddress.setLine1(line1); } if (split.length > 7) { if (StringUtils.isNotBlank(split[7])) { city = split[7]; } supplierAddress.setCity(city); } if (split.length > 8) { if (StringUtils.isNotBlank(split[8])) { state = split[8]; } supplierAddress.setState(state); } if (split.length > 9) { if (StringUtils.isNotBlank(split[9])) { country = split[9]; } supplierAddress.setCountry(country); } if (split.length > 10) { if (StringUtils.isNotBlank(split[10])) { pin = split[10]; } supplierAddress.setPin(pin); } if (split.length > 11) { if (StringUtils.isNotBlank(split[11])) { panNo = split[11]; } supplierMasterItem.setPanNo(panNo); } if (split.length > 12) { // GST No is 15 chars long if (StringUtils.isNotBlank(split[12]) && split[12].trim().length() == 15) { List<GSTRegistration> list = new ArrayList<GSTRegistration>(); GSTRegistration gstRegistration = new GSTRegistration(); gstRegistration.setGstNo(split[12].trim()); list.add(gstRegistration); supplierMasterItem.setGstRegistrations(list); } } if (split.length > 13) { if (StringUtils.isNotBlank(split[13])) { tags = split[13]; } supplierMasterItem.setTags(tags); } supplierMasterItem.setAddress(supplierAddress); // ss.addSupplier(supplierMasterItem); supplierMasterItem.setItemNumber(startItemNumber++); supplierList.add(supplierMasterItem); if ((row % Constants.ENTITY_PROCESSING_FLUSH_SIZE) == 0) { insertAndFlushSuppliers(supplierList, businessEntity); } } catch (Exception e) { logger.warning(e.getMessage()); e.printStackTrace(); } } insertAndFlushSuppliers(supplierList, businessEntity); logger.info("Finished Uploading Customer..!!"); } private void insertAndFlushSuppliers(List<SupplierEntity> supplierList, BusinessEntity businessEntity) { if (supplierList.size() == 0) return; ofy().save().entities(supplierList).now(); List<AccountEntity> supplierAccounts = new ArrayList<AccountEntity>(supplierList.size()); AccountGroupEntity payableAccount = ofy().load().type(AccountGroupEntity.class).ancestor(businessEntity) .filter("defaultAccountPayableGroup", true).first().now(); for (SupplierEntity supplierEntity : supplierList) { AccountEntity accountEntity = new AccountEntity(); accountEntity.setBusiness(businessEntity); accountEntity.setAccountName(supplierEntity.getSupplierName()); accountEntity.setAccountType(AccountingAccountType.REAL); accountEntity.setAccountGroup(payableAccount); } ofy().save().entities(supplierAccounts).now(); supplierList.clear(); supplierAccounts.clear(); } public Long getBusinessId() { return businessId; } public void setBusinessId(Long businessId) { this.businessId = businessId; } }
UTF-8
Java
8,885
java
UploadSupplierMasterServletTask.java
Java
[ { "context": "ppLName = \"NA\", mobileNo = \"9999999999\", email = \"na@dummy.com\", line1 = \"NA\",\r\n\t\t\t\t\tpin = \"NA\", country = \"NA\",", "end": 4086, "score": 0.9999153017997742, "start": 4074, "tag": "EMAIL", "value": "na@dummy.com" } ]
null
[]
package com.protostar.billingnstock.purchase.services; import static com.googlecode.objectify.ObjectifyService.ofy; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.channels.Channels; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; import com.google.appengine.api.NamespaceManager; import com.google.appengine.api.taskqueue.DeferredTask; import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.appengine.tools.cloudstorage.GcsInputChannel; import com.google.appengine.tools.cloudstorage.GcsService; import com.google.appengine.tools.cloudstorage.GcsServiceFactory; import com.google.appengine.tools.cloudstorage.RetryParams; import com.googlecode.objectify.Key; import com.protostar.billingnstock.account.entities.AccountEntity; import com.protostar.billingnstock.account.entities.AccountGroupEntity; import com.protostar.billingnstock.crm.services.UploadCustomerServletTask; import com.protostar.billingnstock.cust.services.CustomerService; import com.protostar.billingnstock.purchase.entities.SupplierEntity; import com.protostar.billingnstock.tax.entities.GSTRegistration; import com.protostar.billingnstock.user.entities.BusinessEntity; import com.protostar.billingnstock.user.entities.UserEntity; import com.protostar.billingnstock.user.services.UserService; import com.protostar.billnstock.entity.Address; import com.protostar.billnstock.until.data.Constants; import com.protostar.billnstock.until.data.EntityUtil; import com.protostar.billnstock.until.data.SequenceGeneratorShardedService; import com.protostar.billnstock.until.data.WebUtil; import com.protostar.billnstock.until.data.Constants.AccountingAccountType; public class UploadSupplierMasterServletTask implements DeferredTask { private final static long serialVersionUID = 1L; private final static Logger logger = Logger.getLogger(UploadCustomerServletTask.class.getName()); private GcsFilename gcsFile; private Long businessId; public UploadSupplierMasterServletTask() { } public UploadSupplierMasterServletTask(Long businessId, GcsFilename gcsFile) { this.setBusinessId(businessId); this.gcsFile = gcsFile; } @Override public void run() { NamespaceManager.set(getBusinessId().toString()); CustomerService customerService = new CustomerService(); BusinessEntity businessEntity = customerService.getBusinessById(getBusinessId()); logger.info("WebUtil.getCurrentUser(): " + WebUtil.getCurrentUser()); final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder() .initialRetryDelayMillis(10).retryMaxAttempts(10).totalRetryPeriodMillis(15000).build()); GcsInputChannel readChannel = gcsService.openPrefetchingReadChannel(gcsFile, 0, Constants.DOCUMENT_DEFAULT_MAX_SIZE); ByteArrayOutputStream ops = new ByteArrayOutputStream(); try { WebUtil.copy(Channels.newInputStream(readChannel), ops); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String fileContent = ops.toString(); String[] supList = fileContent.split("\n"); logger.info("custList.length: " + supList.length); int startItemNumber = 1; if (supList.length > 1) { SequenceGeneratorShardedService sequenceGenService = new SequenceGeneratorShardedService( EntityUtil.getBusinessRawKey(businessEntity), Constants.SUPPLIER_NO_COUNTER, "Supplier Counter"); startItemNumber = sequenceGenService.getNextSequenceNumber(); if ((supList.length - 2) > 0) sequenceGenService.incrementBy(supList.length - 2); // -2 because one is already increased by getNextSequenceNumber() above and one // for column header row } Date todaysDate = new Date(); List<SupplierEntity> supplierList = new ArrayList<SupplierEntity>(); for (int row = 1; row < supList.length; row++) { String suppFName = "NA", suppLName = "NA", mobileNo = "9999999999", email = "<EMAIL>", line1 = "NA", pin = "NA", country = "NA", panNo = "NA", tags = "NA", state = "NA", city = "NA"; try { String[] split = supList[row].split(","); if (split == null || split.length < 4) { continue; } ////// Below check for duplicate supplier names . SupplierEntity supplierMasterItem = null; List<SupplierEntity> duplicateSuppliers = ofy().load().type(SupplierEntity.class) .ancestor(Key.create(BusinessEntity.class, getBusinessId())) .filter("supplierNameFullIndex", split[1].trim().toLowerCase()).list(); if (duplicateSuppliers != null && !duplicateSuppliers.isEmpty()) { supplierMasterItem = duplicateSuppliers.get(0); } else { supplierMasterItem = new SupplierEntity(); } Address supplierAddress = new Address(); supplierMasterItem.setBusiness(businessEntity); supplierMasterItem.setCreatedDate(todaysDate); supplierMasterItem.setSupplierName(split[1]); if (StringUtils.isNotBlank(split[2])) { suppFName = split[2]; } supplierMasterItem.setContactFName(suppFName); if (StringUtils.isNotBlank(split[3])) { suppLName = split[3]; } supplierMasterItem.setContactLName(suppLName); if (split.length >= 4) { if (StringUtils.isNotBlank(split[4].trim())) { mobileNo = split[4].replaceAll("\\s+", ""); } supplierMasterItem.setMobile(mobileNo); } if (split.length > 5) { if (StringUtils.isNotBlank(split[5])) { email = split[5].trim(); } supplierMasterItem.setEmail(email); } if (split.length > 6) { if (StringUtils.isNotBlank(split[6])) { line1 = split[6].replaceAll(Constants.CSV_COMMA_TEMP_CHAR_SEQUENCE, ","); } supplierAddress.setLine1(line1); } if (split.length > 7) { if (StringUtils.isNotBlank(split[7])) { city = split[7]; } supplierAddress.setCity(city); } if (split.length > 8) { if (StringUtils.isNotBlank(split[8])) { state = split[8]; } supplierAddress.setState(state); } if (split.length > 9) { if (StringUtils.isNotBlank(split[9])) { country = split[9]; } supplierAddress.setCountry(country); } if (split.length > 10) { if (StringUtils.isNotBlank(split[10])) { pin = split[10]; } supplierAddress.setPin(pin); } if (split.length > 11) { if (StringUtils.isNotBlank(split[11])) { panNo = split[11]; } supplierMasterItem.setPanNo(panNo); } if (split.length > 12) { // GST No is 15 chars long if (StringUtils.isNotBlank(split[12]) && split[12].trim().length() == 15) { List<GSTRegistration> list = new ArrayList<GSTRegistration>(); GSTRegistration gstRegistration = new GSTRegistration(); gstRegistration.setGstNo(split[12].trim()); list.add(gstRegistration); supplierMasterItem.setGstRegistrations(list); } } if (split.length > 13) { if (StringUtils.isNotBlank(split[13])) { tags = split[13]; } supplierMasterItem.setTags(tags); } supplierMasterItem.setAddress(supplierAddress); // ss.addSupplier(supplierMasterItem); supplierMasterItem.setItemNumber(startItemNumber++); supplierList.add(supplierMasterItem); if ((row % Constants.ENTITY_PROCESSING_FLUSH_SIZE) == 0) { insertAndFlushSuppliers(supplierList, businessEntity); } } catch (Exception e) { logger.warning(e.getMessage()); e.printStackTrace(); } } insertAndFlushSuppliers(supplierList, businessEntity); logger.info("Finished Uploading Customer..!!"); } private void insertAndFlushSuppliers(List<SupplierEntity> supplierList, BusinessEntity businessEntity) { if (supplierList.size() == 0) return; ofy().save().entities(supplierList).now(); List<AccountEntity> supplierAccounts = new ArrayList<AccountEntity>(supplierList.size()); AccountGroupEntity payableAccount = ofy().load().type(AccountGroupEntity.class).ancestor(businessEntity) .filter("defaultAccountPayableGroup", true).first().now(); for (SupplierEntity supplierEntity : supplierList) { AccountEntity accountEntity = new AccountEntity(); accountEntity.setBusiness(businessEntity); accountEntity.setAccountName(supplierEntity.getSupplierName()); accountEntity.setAccountType(AccountingAccountType.REAL); accountEntity.setAccountGroup(payableAccount); } ofy().save().entities(supplierAccounts).now(); supplierList.clear(); supplierAccounts.clear(); } public Long getBusinessId() { return businessId; } public void setBusinessId(Long businessId) { this.businessId = businessId; } }
8,880
0.710186
0.699719
237
35.49789
26.907972
108
false
false
0
0
0
0
0
0
3.28692
false
false
1
85d1f6b8c5c4faeb04392e295547822f4aac6418
14,396,730,401,378
6c3bcd219fb04c04ea68c1bde6c9679eacd659f2
/src/main/java/cl/samtech/ot/service/RevisionService.java
20ff6babe491aea16fc17cd0b7d61125bdec3c85
[]
no_license
guillermoj09/ot
https://github.com/guillermoj09/ot
40ab76e789827ba5b379a313ef3189fb10671009
ad1b7e94a73d3e9ab65e2eb33bfb9c6ba39e676f
refs/heads/main
2023-03-18T11:53:02.169000
2021-03-17T06:24:16
2021-03-17T06:24:16
348,599,929
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cl.samtech.ot.service; public class RevisionService { }
UTF-8
Java
66
java
RevisionService.java
Java
[]
null
[]
package cl.samtech.ot.service; public class RevisionService { }
66
0.772727
0.772727
5
12.2
14.538225
30
false
false
0
0
0
0
0
0
0.2
false
false
1
75bde8c07630ee04c03d38a4d829b0d5724078b7
20,212,116,097,761
880f67da9cfb0d953481c3894b8c77aebf037278
/src/main/java/com/pctf/algorithm/swardtooffer/FindNumsAppearOnceSolution.java
8a6657e2ea19fb37545ad70e210ca9247705f7c2
[]
no_license
Switcherman/datastructures
https://github.com/Switcherman/datastructures
7ab85deb77d8543c701e1126c507ec142899f2b5
db72c72340ed5cdf3aa5dac6083edad33601d194
refs/heads/master
2021-07-10T03:19:13.620000
2019-03-01T06:42:21
2019-03-01T06:42:21
140,062,453
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pctf.algorithm.swardtooffer; import java.util.HashMap; import java.util.Map; /** * 题目描述 * 一个整型数组里除了两个数字之外,其他的数字都出现了偶数次。请写程序找出这两个只出现一次的数字。 */ public class FindNumsAppearOnceSolution { public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) { if(array == null || array.length ==0) { return; } if(array.length == 1) { num1[0] = array[0]; } Map<Integer, Integer> map = new HashMap<>(); for(int i : array) { if(map.containsKey(i)) { map.put(i, map.get(i) + 1); } else { map.put(i, 1); } } int[] a = new int[array.length]; int i = 0; for(Map.Entry<Integer, Integer> e : map.entrySet()) { if(e.getValue() == 1) { a[i++] = e.getKey(); } } num1[0] = a[0]; num2[0] = a[1]; } }
UTF-8
Java
1,044
java
FindNumsAppearOnceSolution.java
Java
[]
null
[]
package com.pctf.algorithm.swardtooffer; import java.util.HashMap; import java.util.Map; /** * 题目描述 * 一个整型数组里除了两个数字之外,其他的数字都出现了偶数次。请写程序找出这两个只出现一次的数字。 */ public class FindNumsAppearOnceSolution { public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) { if(array == null || array.length ==0) { return; } if(array.length == 1) { num1[0] = array[0]; } Map<Integer, Integer> map = new HashMap<>(); for(int i : array) { if(map.containsKey(i)) { map.put(i, map.get(i) + 1); } else { map.put(i, 1); } } int[] a = new int[array.length]; int i = 0; for(Map.Entry<Integer, Integer> e : map.entrySet()) { if(e.getValue() == 1) { a[i++] = e.getKey(); } } num1[0] = a[0]; num2[0] = a[1]; } }
1,044
0.473461
0.455414
37
24.459459
18.447287
74
false
false
0
0
0
0
0
0
0.567568
false
false
1
a888d2283bd025c6ac2946e2c0bcc9ba5f5ec1fc
24,103,356,522,665
884ec78c42895794232988af4d192f632c2263ed
/app/src/main/java/com/yamankod/webservice_6_kiyisahil/MainActivity.java
a490a145600c1b2187cc653fbf8f65ca23ca2c49
[]
no_license
muratYamann/WebService_6_kiyiSahil
https://github.com/muratYamann/WebService_6_kiyiSahil
9f611862e6133634ddf325ed1a0de2e24ea10a8d
7fd402cc0e761028af7bde0051d07d781501e9a8
refs/heads/master
2021-06-08T11:29:38.472000
2016-12-03T17:40:26
2016-12-03T17:40:26
75,489,797
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yamankod.webservice_6_kiyisahil; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { private static final String METHOD_NAME = "sydbKordinatBilgileri"; private static final String NAMESPACE = "http://kegm.gov.tr/DD/MobilWebService.asmx"; private static final String SOAP_ACTION = "http://kegm.gov.tr/DD/MobilWebService.asmx/sydbKordinatBilgileri"; private static final String URL = "http://servis.kiyiemniyeti.gov.tr/MobilWebService.asmx"; TextView view ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); view = (TextView) findViewById(R.id.text); fetchSoap soap = new fetchSoap(); soap.execute("dbjjd"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public class fetchSoap extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... params) { return getObject(); } @Override protected void onPostExecute(String result) { view.setText("a "+result); super.onPostExecute(result); } } public String getObject() { String s = ""; SoapObject istek = new SoapObject(NAMESPACE, METHOD_NAME); istek.addProperty("KullaniciAdi", "KULL_MOBIL_ISLEM_LER"); istek.addProperty("KullaniciSifresi", "SIFRE_MOBIL_ISLEM_LER"); istek.addProperty("MMSI", 0); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(istek); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.debug = true; try { androidHttpTransport.call(SOAP_ACTION, envelope); SoapObject response = (SoapObject) envelope.getResponse(); System.out.println("aaa "+response.toString()); s = ""+response.toString(); }catch(Exception exception){ System.out.println("ee "+exception.getMessage()); } return s; } }
UTF-8
Java
2,409
java
MainActivity.java
Java
[]
null
[]
package com.yamankod.webservice_6_kiyisahil; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { private static final String METHOD_NAME = "sydbKordinatBilgileri"; private static final String NAMESPACE = "http://kegm.gov.tr/DD/MobilWebService.asmx"; private static final String SOAP_ACTION = "http://kegm.gov.tr/DD/MobilWebService.asmx/sydbKordinatBilgileri"; private static final String URL = "http://servis.kiyiemniyeti.gov.tr/MobilWebService.asmx"; TextView view ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); view = (TextView) findViewById(R.id.text); fetchSoap soap = new fetchSoap(); soap.execute("dbjjd"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public class fetchSoap extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... params) { return getObject(); } @Override protected void onPostExecute(String result) { view.setText("a "+result); super.onPostExecute(result); } } public String getObject() { String s = ""; SoapObject istek = new SoapObject(NAMESPACE, METHOD_NAME); istek.addProperty("KullaniciAdi", "KULL_MOBIL_ISLEM_LER"); istek.addProperty("KullaniciSifresi", "SIFRE_MOBIL_ISLEM_LER"); istek.addProperty("MMSI", 0); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(istek); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.debug = true; try { androidHttpTransport.call(SOAP_ACTION, envelope); SoapObject response = (SoapObject) envelope.getResponse(); System.out.println("aaa "+response.toString()); s = ""+response.toString(); }catch(Exception exception){ System.out.println("ee "+exception.getMessage()); } return s; } }
2,409
0.726443
0.723122
80
29.112499
25.473513
110
false
false
0
0
0
0
0
0
1.75
false
false
1
b94c85715423f6bc57cfea00494f2ace833038b2
14,912,126,461,592
cee7246538b1e7c720d2a1845f576d58d8bb69ff
/src/main/java/com/zzl/baby/common/consts/StatusCode.java
d6ccc7d2c746977c5ee7b78814d50cd95d6c3e00
[]
no_license
zhenglu1989/baby-java
https://github.com/zhenglu1989/baby-java
05f67fedb3df874da2f0784d0e10e78024ca8ad8
612ad4c8f302f1a5c759abd2627ec0dea3095c27
refs/heads/master
2021-01-10T01:47:59.738000
2015-11-11T03:43:56
2015-11-11T03:43:56
45,914,390
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zzl.baby.common.consts; /** * <p> * Title: 状态码常量 * </p> * <p> * <p> * Description: 状态码常量 * </p> * </p> * <p> * Create Time: 下午1:10:05 * @version 1.0 */ public class StatusCode { // 业务处理成功 public static final int GLOBAL_SUCCESS = 1; // 业务处理失败 public static final int GLOBAL_FAIL = 0; // session过期 public static final int SESSION_TIMEOUT = -2; // 不是有效的json格式 public static final int STATUS_INVALID_JSON = 1001; // 不是有效的参数 public static final int STATUS_INVALID_PARAMS = 1002; // 文件删除失败 public static final int STATUS_FILE_DELETE_FAIL = 1003; // 数据库记录不存在 public static final int STATUS_NOT_EXIST = 1004; // 权限不足 public static final int STATUS_LACK_AUTHORITY = 1005; // 文件操作失败 public static final int STATUS_FILE_ERROR = 1006; // 数据库记录已存在 public static final int STATUS_DB_EXIST = 1007; }
UTF-8
Java
1,057
java
StatusCode.java
Java
[]
null
[]
package com.zzl.baby.common.consts; /** * <p> * Title: 状态码常量 * </p> * <p> * <p> * Description: 状态码常量 * </p> * </p> * <p> * Create Time: 下午1:10:05 * @version 1.0 */ public class StatusCode { // 业务处理成功 public static final int GLOBAL_SUCCESS = 1; // 业务处理失败 public static final int GLOBAL_FAIL = 0; // session过期 public static final int SESSION_TIMEOUT = -2; // 不是有效的json格式 public static final int STATUS_INVALID_JSON = 1001; // 不是有效的参数 public static final int STATUS_INVALID_PARAMS = 1002; // 文件删除失败 public static final int STATUS_FILE_DELETE_FAIL = 1003; // 数据库记录不存在 public static final int STATUS_NOT_EXIST = 1004; // 权限不足 public static final int STATUS_LACK_AUTHORITY = 1005; // 文件操作失败 public static final int STATUS_FILE_ERROR = 1006; // 数据库记录已存在 public static final int STATUS_DB_EXIST = 1007; }
1,057
0.618839
0.577218
46
18.847826
19.281628
59
false
false
0
0
0
0
0
0
0.23913
false
false
1
40b929f5b12cac727b8787dd0d10a374c447cfc6
687,194,786,351
474b4acbff53cbf31d380987e4b442e004535492
/src/yaruliy/data/build/RConfig.java
28e63a5b104cdba975ea6e0fba854ff36f144dfe
[]
no_license
YaRuliY/imdg
https://github.com/YaRuliY/imdg
3b788c39607193463df2102ff047465155fbf6ff
cace6f30d70aca3346cb62604402297399911593
refs/heads/master
2020-07-08T22:41:39.771000
2017-06-12T21:33:07
2017-06-12T21:33:07
74,020,218
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package yaruliy.data.build; import java.util.ArrayList; import java.util.HashMap; public class RConfig{ public int regionElementsCount = 0; public HashMap<String, Integer> joinKeyDistributionLaw = new HashMap<>(); public HashMap<Integer, ArrayList<Integer>> objectSizeDistributionLaw = new HashMap<>(); String[] names = {"Jonh", "Sam", "Dean", "Tom", "Piter", "Natan", "Jenna", "Sophia", "Jack", "Kelly", "Robert"}; String alpfa = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public RConfig(){} public RConfig(HashMap<String, Integer> jkd, HashMap<Integer, ArrayList<Integer>> osdl, int rec){ this.joinKeyDistributionLaw = jkd; this.objectSizeDistributionLaw = osdl; this.regionElementsCount = rec; } }
UTF-8
Java
772
java
RConfig.java
Java
[ { "context": "tionLaw = new HashMap<>();\n String[] names = {\"Jonh\", \"Sam\", \"Dean\", \"Tom\", \"Piter\", \"Natan\", \"Jenna\"", "end": 343, "score": 0.9997918605804443, "start": 339, "tag": "NAME", "value": "Jonh" }, { "context": "= new HashMap<>();\n String[] names = {\"Jonh\", \"Sam\", \"Dean\", \"Tom\", \"Piter\", \"Natan\", \"Jenna\", \"Soph", "end": 350, "score": 0.999597430229187, "start": 347, "tag": "NAME", "value": "Sam" }, { "context": "ashMap<>();\n String[] names = {\"Jonh\", \"Sam\", \"Dean\", \"Tom\", \"Piter\", \"Natan\", \"Jenna\", \"Sophia\", \"Ja", "end": 358, "score": 0.9996698498725891, "start": 354, "tag": "NAME", "value": "Dean" }, { "context": "();\n String[] names = {\"Jonh\", \"Sam\", \"Dean\", \"Tom\", \"Piter\", \"Natan\", \"Jenna\", \"Sophia\", \"Jack\", \"K", "end": 365, "score": 0.9996751546859741, "start": 362, "tag": "NAME", "value": "Tom" }, { "context": " String[] names = {\"Jonh\", \"Sam\", \"Dean\", \"Tom\", \"Piter\", \"Natan\", \"Jenna\", \"Sophia\", \"Jack\", \"Kelly\", \"R", "end": 374, "score": 0.9996324777603149, "start": 369, "tag": "NAME", "value": "Piter" }, { "context": " names = {\"Jonh\", \"Sam\", \"Dean\", \"Tom\", \"Piter\", \"Natan\", \"Jenna\", \"Sophia\", \"Jack\", \"Kelly\", \"Robert\"};\n", "end": 383, "score": 0.9996939897537231, "start": 378, "tag": "NAME", "value": "Natan" }, { "context": "{\"Jonh\", \"Sam\", \"Dean\", \"Tom\", \"Piter\", \"Natan\", \"Jenna\", \"Sophia\", \"Jack\", \"Kelly\", \"Robert\"};\n Strin", "end": 392, "score": 0.9997357726097107, "start": 387, "tag": "NAME", "value": "Jenna" }, { "context": "\"Sam\", \"Dean\", \"Tom\", \"Piter\", \"Natan\", \"Jenna\", \"Sophia\", \"Jack\", \"Kelly\", \"Robert\"};\n String alpfa = ", "end": 402, "score": 0.9996991753578186, "start": 396, "tag": "NAME", "value": "Sophia" }, { "context": "an\", \"Tom\", \"Piter\", \"Natan\", \"Jenna\", \"Sophia\", \"Jack\", \"Kelly\", \"Robert\"};\n String alpfa = \"_abcdef", "end": 410, "score": 0.9997289180755615, "start": 406, "tag": "NAME", "value": "Jack" }, { "context": "m\", \"Piter\", \"Natan\", \"Jenna\", \"Sophia\", \"Jack\", \"Kelly\", \"Robert\"};\n String alpfa = \"_abcdefghijklmno", "end": 419, "score": 0.9996292591094971, "start": 414, "tag": "NAME", "value": "Kelly" }, { "context": "r\", \"Natan\", \"Jenna\", \"Sophia\", \"Jack\", \"Kelly\", \"Robert\"};\n String alpfa = \"_abcdefghijklmnopqrstuvwxy", "end": 429, "score": 0.9996761679649353, "start": 423, "tag": "NAME", "value": "Robert" } ]
null
[]
package yaruliy.data.build; import java.util.ArrayList; import java.util.HashMap; public class RConfig{ public int regionElementsCount = 0; public HashMap<String, Integer> joinKeyDistributionLaw = new HashMap<>(); public HashMap<Integer, ArrayList<Integer>> objectSizeDistributionLaw = new HashMap<>(); String[] names = {"Jonh", "Sam", "Dean", "Tom", "Piter", "Natan", "Jenna", "Sophia", "Jack", "Kelly", "Robert"}; String alpfa = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public RConfig(){} public RConfig(HashMap<String, Integer> jkd, HashMap<Integer, ArrayList<Integer>> osdl, int rec){ this.joinKeyDistributionLaw = jkd; this.objectSizeDistributionLaw = osdl; this.regionElementsCount = rec; } }
772
0.704663
0.703368
18
41.944443
34.93084
116
false
false
0
0
0
0
0
0
1.5
false
false
1
9abe03126646c1fc5ac28eb3928f22d9b06a5a73
9,131,100,481,174
d6d4456b55da744d676f506d147521c8ec63b01f
/Library/src/main/java/com/bingzer/android/dbv/sqlite/SQLiteBuilder.java
0824ad239caf8b1afc9f181b81c0fc8ce7452b5d
[ "Apache-2.0" ]
permissive
fuycadw/DbQuery
https://github.com/fuycadw/DbQuery
57a01d876e9f82f81557ac38ccde999a33a17e6c
c59317e31372cab2ff05586e18305bcaaa77917b
refs/heads/master
2020-12-24T17:17:01.370000
2013-08-30T16:01:05
2013-08-30T16:01:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright 2013 Ricky Tobing * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance insert the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bingzer.android.dbv.sqlite; import android.content.Context; import com.bingzer.android.dbv.IDatabase; /** * <code>IDatabase.Builder</code> implementations. * Always, always, always use this as your <code>IDatabase.Builder</code> * * @since 1.0 * @author Ricky Tobing * @see IDatabase.Builder */ public abstract class SQLiteBuilder implements IDatabase.Builder { /** * Returns the GOD-object <code>context</code>. * You should return your <code>ApplicationContext</code> here * <code> * <pre> * ... * public Context getContext(){ * return getApplicationContext(); * } * ... * </pre> * </code> * @return context */ public abstract Context getContext(); /** * Called when database is about to open. * You should define all the table models here * * @param database the instance of the database * @param modeling the modeling object used to model the database */ @Override public abstract void onModelCreate(IDatabase database, IDatabase.Modeling modeling); ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// /** * Called when upgrade from oldVersion to newVersion * * @param database the database * @param oldVersion the old version * @param newVersion the new version * @return If true is returned, the code will continue * on {@link #onModelCreate(com.bingzer.android.dbv.IDatabase, com.bingzer.android.dbv.IDatabase.Modeling)} */ @Override public boolean onUpgrade(IDatabase database, int oldVersion, int newVersion) { return false; } /** * Called when downgrading from oldVersion to newVersion * * @param database the database * @param oldVersion the old version * @param newVersion the new version * @return If true is returned, the code will continue * on {@link #onModelCreate(com.bingzer.android.dbv.IDatabase, com.bingzer.android.dbv.IDatabase.Modeling)} */ @Override public boolean onDowngrade(IDatabase database, int oldVersion, int newVersion) { return false; } /** * Called after everything gets called * * @param database the instance of the database */ @Override public void onReady(IDatabase database) { // do nothing } /** * Called when any error is encountered. * * @param error the error */ @Override public void onError(Throwable error) { throw new Error(error); } /////////////////////////////////////////////////////////////////////////////////////////////// /** * Convenient class to use if you don't need to model your database at all. * This class is really convenient if you have a pre-loaded database * <code> * <pre> * Context context = ... * IDatabase db = DbQuery.getDatabase("Test"); * * db.open(version, new SQLiteBuilder.WithoutModeling(context)); * </pre> * </code> */ public static final class WithoutModeling extends SQLiteBuilder { Context context; /** * Supply the context here. * You should always use <code>ApplicationContext</code> * here whenever possible * @param context the context */ public WithoutModeling(Context context){ this.context = context; } @Override public Context getContext() { return context; } @Override public void onModelCreate(IDatabase database, IDatabase.Modeling modeling) { // do nothing } } }
UTF-8
Java
4,392
java
SQLiteBuilder.java
Java
[ { "context": "/**\n * Copyright 2013 Ricky Tobing\n *\n * Licensed under the Apache License, Version ", "end": 34, "score": 0.9998753666877747, "start": 22, "tag": "NAME", "value": "Ricky Tobing" }, { "context": "atabase.Builder</code>\n *\n * @since 1.0\n * @author Ricky Tobing\n * @see IDatabase.Builder\n */\npublic abstract cla", "end": 889, "score": 0.9998830556869507, "start": 877, "tag": "NAME", "value": "Ricky Tobing" } ]
null
[]
/** * Copyright 2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance insert the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bingzer.android.dbv.sqlite; import android.content.Context; import com.bingzer.android.dbv.IDatabase; /** * <code>IDatabase.Builder</code> implementations. * Always, always, always use this as your <code>IDatabase.Builder</code> * * @since 1.0 * @author <NAME> * @see IDatabase.Builder */ public abstract class SQLiteBuilder implements IDatabase.Builder { /** * Returns the GOD-object <code>context</code>. * You should return your <code>ApplicationContext</code> here * <code> * <pre> * ... * public Context getContext(){ * return getApplicationContext(); * } * ... * </pre> * </code> * @return context */ public abstract Context getContext(); /** * Called when database is about to open. * You should define all the table models here * * @param database the instance of the database * @param modeling the modeling object used to model the database */ @Override public abstract void onModelCreate(IDatabase database, IDatabase.Modeling modeling); ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// /** * Called when upgrade from oldVersion to newVersion * * @param database the database * @param oldVersion the old version * @param newVersion the new version * @return If true is returned, the code will continue * on {@link #onModelCreate(com.bingzer.android.dbv.IDatabase, com.bingzer.android.dbv.IDatabase.Modeling)} */ @Override public boolean onUpgrade(IDatabase database, int oldVersion, int newVersion) { return false; } /** * Called when downgrading from oldVersion to newVersion * * @param database the database * @param oldVersion the old version * @param newVersion the new version * @return If true is returned, the code will continue * on {@link #onModelCreate(com.bingzer.android.dbv.IDatabase, com.bingzer.android.dbv.IDatabase.Modeling)} */ @Override public boolean onDowngrade(IDatabase database, int oldVersion, int newVersion) { return false; } /** * Called after everything gets called * * @param database the instance of the database */ @Override public void onReady(IDatabase database) { // do nothing } /** * Called when any error is encountered. * * @param error the error */ @Override public void onError(Throwable error) { throw new Error(error); } /////////////////////////////////////////////////////////////////////////////////////////////// /** * Convenient class to use if you don't need to model your database at all. * This class is really convenient if you have a pre-loaded database * <code> * <pre> * Context context = ... * IDatabase db = DbQuery.getDatabase("Test"); * * db.open(version, new SQLiteBuilder.WithoutModeling(context)); * </pre> * </code> */ public static final class WithoutModeling extends SQLiteBuilder { Context context; /** * Supply the context here. * You should always use <code>ApplicationContext</code> * here whenever possible * @param context the context */ public WithoutModeling(Context context){ this.context = context; } @Override public Context getContext() { return context; } @Override public void onModelCreate(IDatabase database, IDatabase.Modeling modeling) { // do nothing } } }
4,380
0.600182
0.597905
150
28.280001
26.98447
111
false
false
0
0
0
0
97
0.022086
0.213333
false
false
1
ebf262626b957af3c4f1061ca71915fb4db58148
14,680,198,260,897
be7dcf0fe68630d8cd8c0edf658452aa8ed7bb27
/binary-api-wrapper/src/main/java/com/binary/api/models/responses/MarketSpecific.java
33d7711d8469380027d9de94b33edabdc98831c2
[]
no_license
binary-com/java-api-wrapper
https://github.com/binary-com/java-api-wrapper
8b24315d7bf538e2ab166e384c0520f9a94714b2
7111de0af9334de292ac389a3dff1adc05afb0aa
refs/heads/dev
2021-01-01T16:48:44.685000
2017-11-16T05:28:01
2017-11-16T05:28:01
97,928,119
4
12
null
false
2018-02-27T13:58:27
2017-07-21T09:01:44
2017-07-25T04:34:07
2017-11-16T05:28:02
394
0
5
1
Java
false
null
package com.binary.api.models.responses; import com.google.gson.annotations.SerializedName; import java.math.BigDecimal; /** * @author Morteza Tavanarad * @version 1.0.0 * @since 8/4/2017 */ public class MarketSpecific { @SerializedName("name") private String name; @SerializedName("turnover_limit") private BigDecimal turnoverLimit; @SerializedName("payout_limit") private BigDecimal payoutLimit; @SerializedName("profile_name") private String profileName; public String getName() { return name; } public BigDecimal getTurnoverLimit() { return turnoverLimit; } public BigDecimal getPayoutLimit() { return payoutLimit; } public String getProfileName() { return profileName; } }
UTF-8
Java
789
java
MarketSpecific.java
Java
[ { "context": "ame;\n\nimport java.math.BigDecimal;\n\n/**\n * @author Morteza Tavanarad\n * @version 1.0.0\n * @since 8/4/2017\n */\npublic c", "end": 156, "score": 0.9998896718025208, "start": 139, "tag": "NAME", "value": "Morteza Tavanarad" } ]
null
[]
package com.binary.api.models.responses; import com.google.gson.annotations.SerializedName; import java.math.BigDecimal; /** * @author <NAME> * @version 1.0.0 * @since 8/4/2017 */ public class MarketSpecific { @SerializedName("name") private String name; @SerializedName("turnover_limit") private BigDecimal turnoverLimit; @SerializedName("payout_limit") private BigDecimal payoutLimit; @SerializedName("profile_name") private String profileName; public String getName() { return name; } public BigDecimal getTurnoverLimit() { return turnoverLimit; } public BigDecimal getPayoutLimit() { return payoutLimit; } public String getProfileName() { return profileName; } }
778
0.676806
0.665399
41
18.243902
15.982888
50
false
false
0
0
0
0
0
0
0.268293
false
false
1
2c820bf0bf1873f76474e9894d29591ae69ab4a4
20,031,727,513,858
820280ea1ffdc2d2a503fff50bf9cd7fea9f1656
/chaosblade-box-service/src/main/java/com/alibaba/chaosblade/box/service/impl/ExperimentWriteServiceImpl.java
ec12c61d800e258a6c61be47a65a98de1ba8dc81
[ "Apache-2.0" ]
permissive
chaosblade-io/chaosbox
https://github.com/chaosblade-io/chaosbox
fa888086bcd8bdb1405adba768955887f693bcba
897673d541ee68067e5ce0991e5f778e8044dfd9
refs/heads/main
2023-03-21T04:48:00.754000
2022-10-31T08:39:50
2022-10-31T08:39:50
335,221,546
7
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alibaba.chaosblade.box.service.impl; import com.alibaba.chaosblade.box.common.commands.CommandBus; import com.alibaba.chaosblade.box.common.common.domain.Response; import com.alibaba.chaosblade.box.common.common.domain.experiment.ExperimentRunResult; import com.alibaba.chaosblade.box.common.common.domain.user.ChaosUser; import com.alibaba.chaosblade.box.common.infrastructure.constant.ChangelogTypes; import com.alibaba.chaosblade.box.common.infrastructure.constant.ChangelogTypes.*; import com.alibaba.chaosblade.box.common.infrastructure.domain.experiment.flow.ExperimentActivityInfo; import com.alibaba.chaosblade.box.common.infrastructure.domain.experiment.request.*; import com.alibaba.chaosblade.box.common.infrastructure.domain.experiment.response.ExperimentInit; import com.alibaba.chaosblade.box.common.infrastructure.exception.ChaosException; import com.alibaba.chaosblade.box.dao.command.ExperimentExecutionCommand; import com.alibaba.chaosblade.box.dao.infrastructure.monitor.trace.Trackers; import com.alibaba.chaosblade.box.common.infrastructure.util.ChangeLogExecutor; import com.alibaba.chaosblade.box.dao.infrastructure.experiment.request.ExperimentCreateRequest; import com.alibaba.chaosblade.box.dao.infrastructure.experiment.request.ExperimentDefinitionRequest; import com.alibaba.chaosblade.box.dao.infrastructure.experiment.request.ExperimentUpdateRequest; import com.alibaba.chaosblade.box.service.ExperimentWriteService; import com.alibaba.chaosblade.box.service.command.experiment.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * @author haibin.lhb * * */ @Service public class ExperimentWriteServiceImpl implements ExperimentWriteService { @Autowired private CommandBus commandBus; @Autowired private Trackers trackers; @Override public Response<ExperimentRunResult> runExperiment(ChaosUser user, ExperimentRunRequest experimentRunRequest) throws ChaosException { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentExecutionCommand.class, experimentRunRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentTaskOperation(ChangeActionType.RUN, ChangeOperatorType.USER, user, experimentRunRequest.getExperimentId(), experimentRunResultResponse.getResult().getTaskId()); } }); } @Override public Response<String> createExperiment(ExperimentCreateRequest experimentCreateRequest) throws ChaosException { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentCreateCommand.class, experimentCreateRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentOperation(ChangeActionType.ADD, ChangeOperatorType.USER, experimentCreateRequest.getUser(), experimentRunResultResponse.getResult(), null); } }); } @Override public Response<Boolean> updateExperiment(ExperimentUpdateRequest experimentUpdateRequest) throws ChaosException { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentUpdateCommand.class, experimentUpdateRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentOperation(ChangelogTypes.ChangeActionType.Update, ChangeOperatorType.USER, experimentUpdateRequest.getUser(), experimentUpdateRequest.getExperimentId(), null); } }); } @Override public Response<Boolean> updateExperimentBasicInfo(ChaosUser user, ExperimentUpdateRequest experimentUpdateRequest) throws ChaosException { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentUpdateCommand.class, experimentUpdateRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentOperation(ChangeActionType.Update, ChangeOperatorType.USER, experimentUpdateRequest.getUser(), experimentUpdateRequest.getExperimentId(), null); } }); } @Override public Response<String> cloneExperiment(ExperimentCloneRequest experimentCloneRequest) { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentCloneCommand.class, experimentCloneRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentOperation(ChangeActionType.ADD, ChangeOperatorType.USER, experimentCloneRequest.getUser(), experimentRunResultResponse.getResult(), null); } }); } @Override public Response<Void> deleteExperiment(ExperimentDeleteRequest experimentDeleteRequest) { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentDeleteCommand.class, experimentDeleteRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentOperation(ChangeActionType.ADD, ChangeOperatorType.USER, experimentDeleteRequest.getUser(), experimentDeleteRequest.getExperimentId(), null); } }); } @Override public Response<Void> updateExperimentDefinition(ExperimentDefinitionRequest flowDefinitionCreateRequest) { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentDefinitionUpdateCommand.class, flowDefinitionCreateRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentOperation(ChangeActionType.Update, ChangeOperatorType.USER, flowDefinitionCreateRequest.getUser(), flowDefinitionCreateRequest.getExperimentId(), null); } }); } @Override public Response<Map<String, List<ExperimentActivityInfo>>> initMiniFlowByAppCode( InitMiniFlowRequest initMiniFlowRequest) { return commandBus.syncRun(InitMiniFlowByAppCodeCommand.class, initMiniFlowRequest); } @Override public Response<Boolean> updateExperimentForOpenApi(ExperimentUpdateRequest updateRequest) { return commandBus.syncRun(ExperimentUpdateForOpenApiCommand.class, updateRequest); } @Override public Response<ExperimentRunResult> preCheckExperiment(ChaosUser user, ExperimentRunRequest experimentRunRequest) throws ChaosException { return commandBus.syncRun(ExperimentExecutionCommand.class, experimentRunRequest); } @Override public Response<ExperimentInit> initExperimentByAppCode(InitMiniFlowRequest initMiniFlowRequest) { commandBus.syncRun(InitMiniFlowByAppCodeCommand.class, initMiniFlowRequest); return null; } @Override public Response<Boolean> updateExperimentHost(ExperimentHostUpdateRequest experimentHostUpdateRequest) throws ChaosException { return commandBus.syncRun(ExperimentUpdateHostCommand.class, experimentHostUpdateRequest); } }
UTF-8
Java
7,811
java
ExperimentWriteServiceImpl.java
Java
[ { "context": "a.util.List;\nimport java.util.Map;\n\n/**\n * @author haibin.lhb\n *\n *\n */\n@Service\npublic class ExperimentWriteSe", "end": 1706, "score": 0.9991953372955322, "start": 1696, "tag": "USERNAME", "value": "haibin.lhb" } ]
null
[]
package com.alibaba.chaosblade.box.service.impl; import com.alibaba.chaosblade.box.common.commands.CommandBus; import com.alibaba.chaosblade.box.common.common.domain.Response; import com.alibaba.chaosblade.box.common.common.domain.experiment.ExperimentRunResult; import com.alibaba.chaosblade.box.common.common.domain.user.ChaosUser; import com.alibaba.chaosblade.box.common.infrastructure.constant.ChangelogTypes; import com.alibaba.chaosblade.box.common.infrastructure.constant.ChangelogTypes.*; import com.alibaba.chaosblade.box.common.infrastructure.domain.experiment.flow.ExperimentActivityInfo; import com.alibaba.chaosblade.box.common.infrastructure.domain.experiment.request.*; import com.alibaba.chaosblade.box.common.infrastructure.domain.experiment.response.ExperimentInit; import com.alibaba.chaosblade.box.common.infrastructure.exception.ChaosException; import com.alibaba.chaosblade.box.dao.command.ExperimentExecutionCommand; import com.alibaba.chaosblade.box.dao.infrastructure.monitor.trace.Trackers; import com.alibaba.chaosblade.box.common.infrastructure.util.ChangeLogExecutor; import com.alibaba.chaosblade.box.dao.infrastructure.experiment.request.ExperimentCreateRequest; import com.alibaba.chaosblade.box.dao.infrastructure.experiment.request.ExperimentDefinitionRequest; import com.alibaba.chaosblade.box.dao.infrastructure.experiment.request.ExperimentUpdateRequest; import com.alibaba.chaosblade.box.service.ExperimentWriteService; import com.alibaba.chaosblade.box.service.command.experiment.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * @author haibin.lhb * * */ @Service public class ExperimentWriteServiceImpl implements ExperimentWriteService { @Autowired private CommandBus commandBus; @Autowired private Trackers trackers; @Override public Response<ExperimentRunResult> runExperiment(ChaosUser user, ExperimentRunRequest experimentRunRequest) throws ChaosException { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentExecutionCommand.class, experimentRunRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentTaskOperation(ChangeActionType.RUN, ChangeOperatorType.USER, user, experimentRunRequest.getExperimentId(), experimentRunResultResponse.getResult().getTaskId()); } }); } @Override public Response<String> createExperiment(ExperimentCreateRequest experimentCreateRequest) throws ChaosException { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentCreateCommand.class, experimentCreateRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentOperation(ChangeActionType.ADD, ChangeOperatorType.USER, experimentCreateRequest.getUser(), experimentRunResultResponse.getResult(), null); } }); } @Override public Response<Boolean> updateExperiment(ExperimentUpdateRequest experimentUpdateRequest) throws ChaosException { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentUpdateCommand.class, experimentUpdateRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentOperation(ChangelogTypes.ChangeActionType.Update, ChangeOperatorType.USER, experimentUpdateRequest.getUser(), experimentUpdateRequest.getExperimentId(), null); } }); } @Override public Response<Boolean> updateExperimentBasicInfo(ChaosUser user, ExperimentUpdateRequest experimentUpdateRequest) throws ChaosException { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentUpdateCommand.class, experimentUpdateRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentOperation(ChangeActionType.Update, ChangeOperatorType.USER, experimentUpdateRequest.getUser(), experimentUpdateRequest.getExperimentId(), null); } }); } @Override public Response<String> cloneExperiment(ExperimentCloneRequest experimentCloneRequest) { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentCloneCommand.class, experimentCloneRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentOperation(ChangeActionType.ADD, ChangeOperatorType.USER, experimentCloneRequest.getUser(), experimentRunResultResponse.getResult(), null); } }); } @Override public Response<Void> deleteExperiment(ExperimentDeleteRequest experimentDeleteRequest) { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentDeleteCommand.class, experimentDeleteRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentOperation(ChangeActionType.ADD, ChangeOperatorType.USER, experimentDeleteRequest.getUser(), experimentDeleteRequest.getExperimentId(), null); } }); } @Override public Response<Void> updateExperimentDefinition(ExperimentDefinitionRequest flowDefinitionCreateRequest) { return ChangeLogExecutor.executeWithChangeLog( () -> commandBus.syncRun(ExperimentDefinitionUpdateCommand.class, flowDefinitionCreateRequest), experimentRunResultResponse -> { if (experimentRunResultResponse.isSuccess()) { trackers.trackExperimentOperation(ChangeActionType.Update, ChangeOperatorType.USER, flowDefinitionCreateRequest.getUser(), flowDefinitionCreateRequest.getExperimentId(), null); } }); } @Override public Response<Map<String, List<ExperimentActivityInfo>>> initMiniFlowByAppCode( InitMiniFlowRequest initMiniFlowRequest) { return commandBus.syncRun(InitMiniFlowByAppCodeCommand.class, initMiniFlowRequest); } @Override public Response<Boolean> updateExperimentForOpenApi(ExperimentUpdateRequest updateRequest) { return commandBus.syncRun(ExperimentUpdateForOpenApiCommand.class, updateRequest); } @Override public Response<ExperimentRunResult> preCheckExperiment(ChaosUser user, ExperimentRunRequest experimentRunRequest) throws ChaosException { return commandBus.syncRun(ExperimentExecutionCommand.class, experimentRunRequest); } @Override public Response<ExperimentInit> initExperimentByAppCode(InitMiniFlowRequest initMiniFlowRequest) { commandBus.syncRun(InitMiniFlowByAppCodeCommand.class, initMiniFlowRequest); return null; } @Override public Response<Boolean> updateExperimentHost(ExperimentHostUpdateRequest experimentHostUpdateRequest) throws ChaosException { return commandBus.syncRun(ExperimentUpdateHostCommand.class, experimentHostUpdateRequest); } }
7,811
0.71937
0.71937
162
47.216049
37.768581
130
false
false
0
0
0
0
0
0
0.592593
false
false
1
ba95405d219718723dd8a43a46ab769f576ad2fe
4,904,852,683,492
9ed8a2123411a542419f45d6eb97437c849427fe
/src/io/teugen/test/authenticator/server/data/DBObject.java
60451667af2bfdd0737d5edbbc6648009ba3e027
[]
no_license
teugen/Authenticator
https://github.com/teugen/Authenticator
fb6d7cc4e10239013461b31cfc292a7d534f50c3
fa5fa14e169e3957c019d747d03a5978a0ee1fb4
refs/heads/master
2016-09-12T13:49:29.248000
2016-05-31T12:06:23
2016-05-31T12:06:23
56,925,862
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.teugen.test.authenticator.server.data; /** * @author teugen */ public interface DBObject { int getId(); String getName(); }
UTF-8
Java
146
java
DBObject.java
Java
[ { "context": "en.test.authenticator.server.data;\n\n/**\n * @author teugen\n */\npublic interface DBObject {\n int getId();\n", "end": 72, "score": 0.9994991421699524, "start": 66, "tag": "USERNAME", "value": "teugen" } ]
null
[]
package io.teugen.test.authenticator.server.data; /** * @author teugen */ public interface DBObject { int getId(); String getName(); }
146
0.671233
0.671233
9
15.222222
15.090672
49
false
false
0
0
0
0
0
0
0.333333
false
false
1
64a78c7e706615a82d2fd18c07388a8418e0eafa
30,803,505,510,307
4e9e23efae1a06feec2000d8b5d8e1426ab4fda1
/src/main/java/pers/cy/speedkillsystem/service/OrderService.java
cec418ff2dd7e7dabd9900e7de14aca40281ae86
[]
no_license
NULL2048/Speed-Kill-System
https://github.com/NULL2048/Speed-Kill-System
0ef6764c8f88f60801d7655b4062cf6adb2c6436
c106865e4ec3698ba7a2e7ed17f7e6fbc1057424
refs/heads/master
2022-06-27T14:49:22.873000
2020-04-24T03:26:14
2020-04-24T03:26:14
235,563,924
2
0
null
false
2022-06-17T02:49:28
2020-01-22T11:57:39
2020-04-24T03:26:28
2022-06-17T02:49:27
4,934
0
0
1
Java
false
false
package pers.cy.speedkillsystem.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pers.cy.speedkillsystem.dao.GoodsDao; import pers.cy.speedkillsystem.dao.OrderDao; import pers.cy.speedkillsystem.domain.OrderInfo; import pers.cy.speedkillsystem.domain.SksOrder; import pers.cy.speedkillsystem.domain.SksUser; import pers.cy.speedkillsystem.redis.OrderKey; import pers.cy.speedkillsystem.redis.RedisService; import pers.cy.speedkillsystem.vo.GoodsVo; import java.util.Date; import java.util.List; @Service public class OrderService { @Autowired private OrderDao orderDao; @Autowired private RedisService redisService; /** * 通过用户ID和商品ID获得秒杀订单 可以用来判断是否已经秒杀 * @param userId * @param goodsId * @return */ public SksOrder getSpeedKillOrderByUserIdGoodsId(long userId, long goodsId) { // return orderDao.getSpeedKillOrderByUserIdGoodsId(userId, goodsId); // 查缓存中有没有 return redisService.get(OrderKey.getSpeedKillOrderByUidGid, "" + userId + "_" + goodsId, SksOrder.class); } /** * 创建商品订单和秒杀订单操作 * 也是一个原子操作,要添加事务 * @param user * @param goods * @return */ @Transactional public OrderInfo createOrder(SksUser user, GoodsVo goods) { // 创建商品订单 OrderInfo orderInfo = new OrderInfo(); orderInfo.setCreateDate(new Date()); orderInfo.setDeliveryAddrId(0L); orderInfo.setGoodsCount(1); orderInfo.setGoodsId(goods.getId()); orderInfo.setGoodsName(goods.getGoodsName()); orderInfo.setGoodsPrice(goods.getSksPrice()); orderInfo.setOrderChannel(1); // 订单状态,0新建未支付,1已支付,2已发货,3已收货,4已退款,5已完成 orderInfo.setStatus(0); orderInfo.setUserId(user.getId()); orderDao.insertOrder(orderInfo); // 创建秒杀订单 SksOrder sksOrder = new SksOrder(); sksOrder.setGoodsId(goods.getId()); sksOrder.setOrderId(orderInfo.getId()); sksOrder.setUserId(user.getId()); // 写入数据库 orderDao.insertSksOrder(sksOrder); // 写入缓存,方便下次直接从缓存查找 redisService.set(OrderKey.getSpeedKillOrderByUidGid, "" + user.getId() + "_" + goods.getId(), sksOrder); // 返回商品订单 return orderInfo; } public OrderInfo getOrderById(long orderId) { return orderDao.getOrderById(orderId); } }
UTF-8
Java
2,743
java
OrderService.java
Java
[]
null
[]
package pers.cy.speedkillsystem.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pers.cy.speedkillsystem.dao.GoodsDao; import pers.cy.speedkillsystem.dao.OrderDao; import pers.cy.speedkillsystem.domain.OrderInfo; import pers.cy.speedkillsystem.domain.SksOrder; import pers.cy.speedkillsystem.domain.SksUser; import pers.cy.speedkillsystem.redis.OrderKey; import pers.cy.speedkillsystem.redis.RedisService; import pers.cy.speedkillsystem.vo.GoodsVo; import java.util.Date; import java.util.List; @Service public class OrderService { @Autowired private OrderDao orderDao; @Autowired private RedisService redisService; /** * 通过用户ID和商品ID获得秒杀订单 可以用来判断是否已经秒杀 * @param userId * @param goodsId * @return */ public SksOrder getSpeedKillOrderByUserIdGoodsId(long userId, long goodsId) { // return orderDao.getSpeedKillOrderByUserIdGoodsId(userId, goodsId); // 查缓存中有没有 return redisService.get(OrderKey.getSpeedKillOrderByUidGid, "" + userId + "_" + goodsId, SksOrder.class); } /** * 创建商品订单和秒杀订单操作 * 也是一个原子操作,要添加事务 * @param user * @param goods * @return */ @Transactional public OrderInfo createOrder(SksUser user, GoodsVo goods) { // 创建商品订单 OrderInfo orderInfo = new OrderInfo(); orderInfo.setCreateDate(new Date()); orderInfo.setDeliveryAddrId(0L); orderInfo.setGoodsCount(1); orderInfo.setGoodsId(goods.getId()); orderInfo.setGoodsName(goods.getGoodsName()); orderInfo.setGoodsPrice(goods.getSksPrice()); orderInfo.setOrderChannel(1); // 订单状态,0新建未支付,1已支付,2已发货,3已收货,4已退款,5已完成 orderInfo.setStatus(0); orderInfo.setUserId(user.getId()); orderDao.insertOrder(orderInfo); // 创建秒杀订单 SksOrder sksOrder = new SksOrder(); sksOrder.setGoodsId(goods.getId()); sksOrder.setOrderId(orderInfo.getId()); sksOrder.setUserId(user.getId()); // 写入数据库 orderDao.insertSksOrder(sksOrder); // 写入缓存,方便下次直接从缓存查找 redisService.set(OrderKey.getSpeedKillOrderByUidGid, "" + user.getId() + "_" + goods.getId(), sksOrder); // 返回商品订单 return orderInfo; } public OrderInfo getOrderById(long orderId) { return orderDao.getOrderById(orderId); } }
2,743
0.689988
0.685967
80
30.0875
24.02821
113
false
false
0
0
0
0
0
0
0.55
false
false
1
37edb1d008a3fe0c7369aca9be16d6d8c9d356ea
12,824,772,398,773
c30f1f54e762d0682fe22e7f067a4757dc1f2831
/src/main/java/server/sport/repository/UserResponsibilityRepository.java
e1876a28b52b41ff339f1114727170a600ec3476
[]
no_license
dprzygocka/Sport-Website
https://github.com/dprzygocka/Sport-Website
3acf7d5d5f4f8a25c6d61c43821e1eef1fc7c6ca
ae3306dfdf5090a33ffd1a6b57627c609c1009f4
refs/heads/master
2023-02-08T11:22:14.860000
2020-12-15T10:31:10
2020-12-15T10:31:10
305,304,293
0
1
null
false
2020-11-02T17:55:22
2020-10-19T07:49:37
2020-11-01T20:41:31
2020-11-02T17:55:22
190
0
0
0
Java
false
false
package server.sport.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; import server.sport.model.UserResponsibility; import server.sport.model.UserResponsibilityPK; public interface UserResponsibilityRepository extends JpaRepository<UserResponsibility, UserResponsibilityPK> { @Transactional @Modifying @Query(value = "UPDATE dbo.user_responsibilities SET user_id = ?1 WHERE responsibility_id = ?2 AND activity_id=?3", nativeQuery = true) int saveUserResponsibilityForActivity(int user_id, int responsibility_id, int activity_id); @Transactional @Modifying @Query(value = "INSERT INTO dbo.user_responsibilities (responsibility_id, activity_id) VALUES (?,?)", nativeQuery = true) int saveResponsibilityForActivity(int responsibility_id, int activity_id); }
UTF-8
Java
992
java
UserResponsibilityRepository.java
Java
[]
null
[]
package server.sport.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; import server.sport.model.UserResponsibility; import server.sport.model.UserResponsibilityPK; public interface UserResponsibilityRepository extends JpaRepository<UserResponsibility, UserResponsibilityPK> { @Transactional @Modifying @Query(value = "UPDATE dbo.user_responsibilities SET user_id = ?1 WHERE responsibility_id = ?2 AND activity_id=?3", nativeQuery = true) int saveUserResponsibilityForActivity(int user_id, int responsibility_id, int activity_id); @Transactional @Modifying @Query(value = "INSERT INTO dbo.user_responsibilities (responsibility_id, activity_id) VALUES (?,?)", nativeQuery = true) int saveResponsibilityForActivity(int responsibility_id, int activity_id); }
992
0.800403
0.797379
20
48.599998
42.01833
139
false
false
0
0
0
0
0
0
0.85
false
false
1
8c3e4b07f0252c0ed5161ddf9299eb0db42364aa
5,626,407,176,645
f2f4bfe8c3d2b7d35969ee172a435817316e559a
/annotation/src/main/java/com/hnq/study/main/Application.java
845b642de7c2afb9dfa66b001bfce6006da7866b
[]
no_license
nengqiang/test
https://github.com/nengqiang/test
d866422a79ad59d6fcaad5d95514d5899656bdf4
ebde4531f3a08675cc62e5f643c3f4107eb6b970
refs/heads/master
2022-10-08T04:25:33.743000
2022-09-28T06:26:41
2022-09-28T06:26:41
198,964,566
0
0
null
false
2021-08-23T21:16:17
2019-07-26T07:01:07
2020-10-14T12:33:15
2021-08-23T21:16:17
9,221
0
0
7
Java
false
false
package com.hnq.study.main; import com.hnq.study.check.UserCheck; import com.hnq.study.factory.UserFactory; import com.hnq.study.model.User; /** * @author henengqiang * @date 2019/03/07 */ public class Application { public static void main(String[] args) { testInitAnnotation(); testValidateAnnotation(); } private static void testInitAnnotation() { User user = null; System.out.println(checkUserNull(user)); user = new User("Bob", "male"); System.out.println(checkUserNull(user)); } private static User checkUserNull(User user) { if (user == null) { return UserFactory.create(); } return user; } private static void testValidateAnnotation() { User user = new User(); user.setName("Candy"); user.setGender("female"); System.out.println(UserCheck.check(user)); User u = new User(); u.setName("Hamburger"); u.setGender("male"); System.out.println(UserCheck.check(u)); User us = new User(); us.setName("奥巴马"); us.setGender("男"); System.out.println(UserCheck.check(us)); } }
UTF-8
Java
1,205
java
Application.java
Java
[ { "context": ";\nimport com.hnq.study.model.User;\n\n/**\n * @author henengqiang\n * @date 2019/03/07\n */\npublic class Application ", "end": 169, "score": 0.8850987553596497, "start": 158, "tag": "USERNAME", "value": "henengqiang" }, { "context": "n(checkUserNull(user));\n\n user = new User(\"Bob\", \"male\");\n System.out.println(checkUserNu", "end": 489, "score": 0.9774575233459473, "start": 486, "tag": "NAME", "value": "Bob" }, { "context": " User user = new User();\n user.setName(\"Candy\");\n user.setGender(\"female\");\n Syst", "end": 826, "score": 0.9995431900024414, "start": 821, "tag": "NAME", "value": "Candy" }, { "context": "\n\n User u = new User();\n u.setName(\"Hamburger\");\n u.setGender(\"male\");\n System.ou", "end": 973, "score": 0.9995226860046387, "start": 964, "tag": "NAME", "value": "Hamburger" }, { "context": " User us = new User();\n us.setName(\"奥巴马\");\n us.setGender(\"男\");\n System.out.", "end": 1108, "score": 0.9994659423828125, "start": 1105, "tag": "NAME", "value": "奥巴马" } ]
null
[]
package com.hnq.study.main; import com.hnq.study.check.UserCheck; import com.hnq.study.factory.UserFactory; import com.hnq.study.model.User; /** * @author henengqiang * @date 2019/03/07 */ public class Application { public static void main(String[] args) { testInitAnnotation(); testValidateAnnotation(); } private static void testInitAnnotation() { User user = null; System.out.println(checkUserNull(user)); user = new User("Bob", "male"); System.out.println(checkUserNull(user)); } private static User checkUserNull(User user) { if (user == null) { return UserFactory.create(); } return user; } private static void testValidateAnnotation() { User user = new User(); user.setName("Candy"); user.setGender("female"); System.out.println(UserCheck.check(user)); User u = new User(); u.setName("Hamburger"); u.setGender("male"); System.out.println(UserCheck.check(u)); User us = new User(); us.setName("奥巴马"); us.setGender("男"); System.out.println(UserCheck.check(us)); } }
1,205
0.595656
0.588972
51
22.470589
17.669462
50
false
false
0
0
0
0
0
0
0.490196
false
false
1
dd84d1aea7f972ac3f1346b9b6498f0ef1b3e66c
7,009,386,627,691
de8b0df4fa2f0eb54a58b6f52682d07e3d2f1045
/Bean/src/main/java/cc/iyayu/basis/mapper/SystemUserRoleMapper.java
b90580c2c6ca202ecfb65172f39fc9a0a4f51f7b
[ "Apache-2.0" ]
permissive
iyayu/IyyBasis
https://github.com/iyayu/IyyBasis
5a5cdbfa2f934f17d4c771bebe4c2e4ae532d9a4
6f1fbc49d2b90d4e5ad023ef2648ca203fc0a993
refs/heads/master
2021-05-09T23:06:01.443000
2018-01-24T15:04:02
2018-01-24T15:04:02
118,771,446
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package cc.iyayu.basis.mapper; import cc.iyayu.basis.vo.SystemUserRoleVO; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author iyayu (613163851@qq.com) * @version 1.0 * <p> * Description: 用户角色操作接口 * 主要用于操作 'system_user_role'表 查看和添加对应的信息等操作 */ public interface SystemUserRoleMapper { /** * 获取用户角色 * * @param systemUserRoleVO 用户角色视图对象 * @return 返回用户角色集合 * @throws Exception */ List<SystemUserRoleVO> listSystemUserRole(SystemUserRoleVO systemUserRoleVO) throws Exception; /** * 获取所有数据量 * * @param userRoleVO 用户角色视图对象 * @return 成功返回数据量 * @throws Exception */ Integer getCount(SystemUserRoleVO userRoleVO) throws Exception; /** * 获取总数据量(根据id) * * @param id 主键 * @return 成功返回数据量 * @throws Exception */ Integer getCountById(@Param(value = "id") String id) throws Exception; /** * 通过id获取角色权限信息 * * @param systemUserRoleId 系统角色id * @return 成功返回对象, 失败返回null或属性为null * @throws Exception */ SystemUserRoleVO getSystemUserRoleAndPermissionBySystemUserRoleId(@Param(value = "systemUserRoleId") String systemUserRoleId) throws Exception; /** * 通过id更新系统用户角色信息(包括更新信息和是否禁用) * * @param systemUserRoleVO 用户角色视图对象 * @return 成功返回1 失败返回0或null * @throws Exception */ Integer updateSystemUserRoleById(SystemUserRoleVO systemUserRoleVO) throws Exception; /** * 删除系统用户角色 * * @param systemUserRoleId 系统用户角色id * @return 成功返回1 失败返回0或null * @throws Exception */ Integer deleteSystemUserRoleById(@Param(value = "systemUserRoleId") String systemUserRoleId) throws Exception; /** * 添加系统用户角色 * * @param systemUserRoleVO 系统角色id * @return 成功返回1 失败返回0或null * @throws Exception */ Integer insertSystemUserRoleById(SystemUserRoleVO systemUserRoleVO) throws Exception; }
UTF-8
Java
2,344
java
SystemUserRoleMapper.java
Java
[ { "context": "ons.Param;\n\nimport java.util.List;\n\n/**\n * @author iyayu (613163851@qq.com)\n * @version 1.0\n * <p>\n * Desc", "end": 164, "score": 0.9987663626670837, "start": 159, "tag": "USERNAME", "value": "iyayu" }, { "context": "m;\n\nimport java.util.List;\n\n/**\n * @author iyayu (613163851@qq.com)\n * @version 1.0\n * <p>\n * Description: 用户角色操作接口\n", "end": 182, "score": 0.9998595118522644, "start": 166, "tag": "EMAIL", "value": "613163851@qq.com" } ]
null
[]
package cc.iyayu.basis.mapper; import cc.iyayu.basis.vo.SystemUserRoleVO; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author iyayu (<EMAIL>) * @version 1.0 * <p> * Description: 用户角色操作接口 * 主要用于操作 'system_user_role'表 查看和添加对应的信息等操作 */ public interface SystemUserRoleMapper { /** * 获取用户角色 * * @param systemUserRoleVO 用户角色视图对象 * @return 返回用户角色集合 * @throws Exception */ List<SystemUserRoleVO> listSystemUserRole(SystemUserRoleVO systemUserRoleVO) throws Exception; /** * 获取所有数据量 * * @param userRoleVO 用户角色视图对象 * @return 成功返回数据量 * @throws Exception */ Integer getCount(SystemUserRoleVO userRoleVO) throws Exception; /** * 获取总数据量(根据id) * * @param id 主键 * @return 成功返回数据量 * @throws Exception */ Integer getCountById(@Param(value = "id") String id) throws Exception; /** * 通过id获取角色权限信息 * * @param systemUserRoleId 系统角色id * @return 成功返回对象, 失败返回null或属性为null * @throws Exception */ SystemUserRoleVO getSystemUserRoleAndPermissionBySystemUserRoleId(@Param(value = "systemUserRoleId") String systemUserRoleId) throws Exception; /** * 通过id更新系统用户角色信息(包括更新信息和是否禁用) * * @param systemUserRoleVO 用户角色视图对象 * @return 成功返回1 失败返回0或null * @throws Exception */ Integer updateSystemUserRoleById(SystemUserRoleVO systemUserRoleVO) throws Exception; /** * 删除系统用户角色 * * @param systemUserRoleId 系统用户角色id * @return 成功返回1 失败返回0或null * @throws Exception */ Integer deleteSystemUserRoleById(@Param(value = "systemUserRoleId") String systemUserRoleId) throws Exception; /** * 添加系统用户角色 * * @param systemUserRoleVO 系统角色id * @return 成功返回1 失败返回0或null * @throws Exception */ Integer insertSystemUserRoleById(SystemUserRoleVO systemUserRoleVO) throws Exception; }
2,335
0.667353
0.658599
79
23.582279
27.292419
147
false
false
0
0
0
0
0
0
0.151899
false
false
1
5b91a7a5c1e1c828c4d546d5658d04d0f4c991d9
19,078,244,791,519
861da17768263e48fa11c8e6af10eef91d7c0ccd
/src/pearl/C01Q06.java
fa9f2f82db178d7a6c9e68e1b74fe50a5edfedf7
[]
no_license
RogerTsang/pearl
https://github.com/RogerTsang/pearl
a7a3798277c74796cb7ea8046c41f371c9e6c5b7
fbeffbea493b93d3da9e0d8e0b02a3357339d427
refs/heads/master
2016-09-16T15:40:08.337000
2016-09-08T14:21:43
2016-09-08T14:21:43
64,185,738
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pearl; public class C01Q06 { /* * I will group up 4 bit as a group * [00 01 02 03] [04 05 06 07] * represent 0 represent 1 * * set(): would increment within a bit group * clr(): would decrement within a bit group * test():would decrement and return true if bit group > 0 * otherwise return false */ }
UTF-8
Java
339
java
C01Q06.java
Java
[]
null
[]
package pearl; public class C01Q06 { /* * I will group up 4 bit as a group * [00 01 02 03] [04 05 06 07] * represent 0 represent 1 * * set(): would increment within a bit group * clr(): would decrement within a bit group * test():would decrement and return true if bit group > 0 * otherwise return false */ }
339
0.634218
0.563422
14
23.214285
18.617115
59
false
false
0
0
0
0
0
0
0.785714
false
false
1
732de32abd708a1d3c5cf6e0b73b751df7d81e61
30,133,490,551,692
104b4af82606dac7491bde829f8d5011134c1bb3
/rotate_Right.java
6ed687c360868653800b2b737ad33c05988b32be
[]
no_license
ruchisahu/leetcode
https://github.com/ruchisahu/leetcode
1aa59c2a5cb78a161b4877bd7f1883b9f5920fa4
345c10dd17e27842d3a63088c340170cb6afebbc
refs/heads/master
2020-03-07T18:59:27.460000
2018-08-07T19:01:48
2018-08-07T19:01:48
127,658,705
0
0
null
false
2018-05-09T05:38:35
2018-04-01T18:14:37
2018-05-02T18:45:50
2018-05-09T05:38:35
109
0
0
0
Java
false
null
/*Given a linked list, rotate the list to the right by k places, where k is non-negative. Example 1: Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL */ class rotate_Right { public static ListNode rotateRight(ListNode head, int k) { if(head==null) return null; if(k==0)return head; ListNode temp = head; int count = 0; while (temp != null) { count++; temp = temp.next; } if(k>count) { k=k%count; if(k==0)return head; } ListNode head1= reverseBetween(head, 1, count); ListNode head2= reverseBetween(head1, 1, k); ListNode head3= reverseBetween(head2, k+1, count); return head3; } public static ListNode reverseBetween(ListNode head, int m, int n) { if(m==n) return head; ListNode prev = null; ListNode first = new ListNode(0); ListNode second = new ListNode(0); int i=0; ListNode p = head; while(p!=null){ i++; if(i==m-1){ prev = p; } if(i==m){ first.next = p; } if(i==n){ second.next = p.next; p.next = null; } p= p.next; } if(first.next == null) return head; // reverse list [m, n] ListNode p1 = first.next; ListNode p2 = p1.next; p1.next = second.next; while(p1!=null && p2!=null){ ListNode t = p2.next; p2.next = p1; p1 = p2; p2 = t; } if(prev!=null) prev.next = p1; else return p1; return head; } public static void main(String[] arg) { ListNode evenList = ListFactory.createEvenNodeList(); ListNode result = rotateRight( evenList,2 ) ; Print.printListNode( result ); } }
UTF-8
Java
2,248
java
rotate_Right.java
Java
[]
null
[]
/*Given a linked list, rotate the list to the right by k places, where k is non-negative. Example 1: Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL */ class rotate_Right { public static ListNode rotateRight(ListNode head, int k) { if(head==null) return null; if(k==0)return head; ListNode temp = head; int count = 0; while (temp != null) { count++; temp = temp.next; } if(k>count) { k=k%count; if(k==0)return head; } ListNode head1= reverseBetween(head, 1, count); ListNode head2= reverseBetween(head1, 1, k); ListNode head3= reverseBetween(head2, k+1, count); return head3; } public static ListNode reverseBetween(ListNode head, int m, int n) { if(m==n) return head; ListNode prev = null; ListNode first = new ListNode(0); ListNode second = new ListNode(0); int i=0; ListNode p = head; while(p!=null){ i++; if(i==m-1){ prev = p; } if(i==m){ first.next = p; } if(i==n){ second.next = p.next; p.next = null; } p= p.next; } if(first.next == null) return head; // reverse list [m, n] ListNode p1 = first.next; ListNode p2 = p1.next; p1.next = second.next; while(p1!=null && p2!=null){ ListNode t = p2.next; p2.next = p1; p1 = p2; p2 = t; } if(prev!=null) prev.next = p1; else return p1; return head; } public static void main(String[] arg) { ListNode evenList = ListFactory.createEvenNodeList(); ListNode result = rotateRight( evenList,2 ) ; Print.printListNode( result ); } }
2,248
0.450623
0.426157
96
22.416666
17.060961
89
false
false
0
0
0
0
0
0
0.541667
false
false
1
7d8de68a23e9272b25eb20911981e348115b4691
13,967,233,710,668
befc19f32a4af79d0380feee658ce1eab404f7a9
/app/src/main/java/com/dos/md/afbcs/v/AccTypeEvaluator.java
12af254bf79ff7cd0643194166e793c20d3a6167
[]
no_license
cervy/Base
https://github.com/cervy/Base
5cea24767a5f128491991cf2d1514b8d8277206d
cc922828c4af1949b3ff8a6af2fd0a089a7d1b9f
refs/heads/master
2020-04-06T06:05:10.020000
2017-09-22T04:14:51
2017-09-22T04:14:51
55,704,060
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dos.md.afbcs.v; import android.animation.TypeEvaluator; /** * Created by SongNick on 15/9/7. */ public class AccTypeEvaluator implements TypeEvaluator<Float>{ @Override public Float evaluate(float fraction, Float startValue, Float endValue) { return fraction * (endValue - startValue); } }
UTF-8
Java
327
java
AccTypeEvaluator.java
Java
[ { "context": "ndroid.animation.TypeEvaluator;\n\n/**\n * Created by SongNick on 15/9/7.\n */\npublic class AccTypeEvaluator impl", "end": 96, "score": 0.7020188570022583, "start": 88, "tag": "USERNAME", "value": "SongNick" } ]
null
[]
package com.dos.md.afbcs.v; import android.animation.TypeEvaluator; /** * Created by SongNick on 15/9/7. */ public class AccTypeEvaluator implements TypeEvaluator<Float>{ @Override public Float evaluate(float fraction, Float startValue, Float endValue) { return fraction * (endValue - startValue); } }
327
0.715596
0.703364
15
20.866667
24.891409
77
false
false
0
0
0
0
0
0
0.333333
false
false
1
2555dd2d8838f8d64a4fde7c2b3ff8640c23e1f0
28,518,582,911,969
fe5a077b8d265f92a8bc3a55a22e74caf76c5148
/Client.java
3044e7af80acec10d0b2c7a8bbdea04db496c989
[]
no_license
Marina00Matta/-GroupChat-UI-
https://github.com/Marina00Matta/-GroupChat-UI-
55a5290b0395f7dfef06bb7419415af7d787c33d
2ca60c846e3337836a9466e148cac24444557cfb
refs/heads/master
2020-12-18T10:05:38.273000
2020-01-21T21:36:15
2020-01-21T21:36:15
235,341,391
0
1
null
false
2020-01-21T21:36:16
2020-01-21T12:49:39
2020-01-21T13:04:57
2020-01-21T21:36:16
7
0
1
0
Java
false
false
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.net.*; public class Client extends JFrame { Socket s; DataInputStream dis; PrintStream ps; JTextArea ta; String name; //JButton b; public Client () { this.setLayout(new FlowLayout()); ta=new JTextArea(30,50); ta.setEditable(false); JScrollPane sp = new JScrollPane(ta); JTextField tf = new JTextField(40); JButton b = new JButton("send"); add(sp); add(tf); add(b); name=JOptionPane.showInputDialog(this,"Enter Name"); try { s = new Socket(InetAddress.getLocalHost(),5005); dis = new DataInputStream(s.getInputStream()); ps = new PrintStream(s.getOutputStream()); } catch(IOException e) { System.out.println("cant connect"); } Thread read = new Thread(new Runnable() { public void run() { String data = null; while (true){ try { data = dis.readLine(); System.out.println(data); } catch (IOException ex) { try { ps.close(); dis.close(); s.close(); } catch (IOException e) { e.printStackTrace(); } finally { JOptionPane.showMessageDialog(Client.this,"sorry server is out"); } break; } Client.this.ta.append(data+"\n"); } } }); read.start(); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (!(tf.getText().equals(""))) { try { String s =name +" : " +tf.getText(); ps.println(s); tf.setText(""); } catch(Exception e) { System.out.println("cant send"); } } /*if (!(tf.getText().equals(""))) ta.append(tf.getText()+"\n"); tf.setText("");*/ } }); this.setDefaultCloseOperation(this.EXIT_ON_CLOSE); } /*try { c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String rm =dis.readLine(); ta.append(rm+"\n"); } catch(Exception e) { System.out.println("no message"); } try { ps.close(); dis.close(); s.close(); } catch(Exception e) { e.printStackTrace(); }*/ public static void main ( String[] args) { Client c=new Client(); c.setSize(800,1000); c.setResizable(false); c.setVisible(true); //new Client(); } }
UTF-8
Java
2,722
java
Client.java
Java
[]
null
[]
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.net.*; public class Client extends JFrame { Socket s; DataInputStream dis; PrintStream ps; JTextArea ta; String name; //JButton b; public Client () { this.setLayout(new FlowLayout()); ta=new JTextArea(30,50); ta.setEditable(false); JScrollPane sp = new JScrollPane(ta); JTextField tf = new JTextField(40); JButton b = new JButton("send"); add(sp); add(tf); add(b); name=JOptionPane.showInputDialog(this,"Enter Name"); try { s = new Socket(InetAddress.getLocalHost(),5005); dis = new DataInputStream(s.getInputStream()); ps = new PrintStream(s.getOutputStream()); } catch(IOException e) { System.out.println("cant connect"); } Thread read = new Thread(new Runnable() { public void run() { String data = null; while (true){ try { data = dis.readLine(); System.out.println(data); } catch (IOException ex) { try { ps.close(); dis.close(); s.close(); } catch (IOException e) { e.printStackTrace(); } finally { JOptionPane.showMessageDialog(Client.this,"sorry server is out"); } break; } Client.this.ta.append(data+"\n"); } } }); read.start(); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (!(tf.getText().equals(""))) { try { String s =name +" : " +tf.getText(); ps.println(s); tf.setText(""); } catch(Exception e) { System.out.println("cant send"); } } /*if (!(tf.getText().equals(""))) ta.append(tf.getText()+"\n"); tf.setText("");*/ } }); this.setDefaultCloseOperation(this.EXIT_ON_CLOSE); } /*try { c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String rm =dis.readLine(); ta.append(rm+"\n"); } catch(Exception e) { System.out.println("no message"); } try { ps.close(); dis.close(); s.close(); } catch(Exception e) { e.printStackTrace(); }*/ public static void main ( String[] args) { Client c=new Client(); c.setSize(800,1000); c.setResizable(false); c.setVisible(true); //new Client(); } }
2,722
0.49155
0.485305
130
18.923077
16.11097
74
false
false
0
0
0
0
0
0
3.107692
false
false
1
d3905fcdf4f0fad2fff811ab6c1b974488ca11c5
11,046,655,955,588
28aded1ee58a7e1b31717cae803238f2f627c338
/Core Java/CoreJavaA2/q6.java
e36d2e60f7163ae39c2ab3369c221ae2d495853c
[]
no_license
manirathore1999/ManiRathore_Assignments
https://github.com/manirathore1999/ManiRathore_Assignments
4a2eead26b9a55729fd87db3c7b2a93028809de4
eabd2ce556e82c8d4e6d20ff0f9b14ef34108987
refs/heads/main
2023-08-02T02:38:03.961000
2021-10-01T08:54:38
2021-10-01T08:54:38
384,222,823
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package CoreJavaA2; public class q6 { public static void main(String[] args) { // TODO Auto-generated method stub Persistence p=new FilePersistence(); p.persist(); Persistence p1=new DatabasePersistence(); p1.persist(); } } abstract class Persistence { abstract void persist(); } class FilePersistence extends Persistence { void persist() { System.out.println("This is the persist method of FilePersistence class"); } } class DatabasePersistence extends Persistence { void persist() { System.out.println("This is the persist method of DatabasePersistence class"); } }
UTF-8
Java
648
java
q6.java
Java
[]
null
[]
package CoreJavaA2; public class q6 { public static void main(String[] args) { // TODO Auto-generated method stub Persistence p=new FilePersistence(); p.persist(); Persistence p1=new DatabasePersistence(); p1.persist(); } } abstract class Persistence { abstract void persist(); } class FilePersistence extends Persistence { void persist() { System.out.println("This is the persist method of FilePersistence class"); } } class DatabasePersistence extends Persistence { void persist() { System.out.println("This is the persist method of DatabasePersistence class"); } }
648
0.675926
0.669753
33
17.636364
21.687614
80
false
false
0
0
0
0
0
0
0.848485
false
false
1
1fa9d8a845e49055bc3f931d1a78b7d7bb5907fa
6,545,530,211,581
bc74ef546983061cd4e01ef4e3b3c0399555ce49
/app/src/main/java/com/example/instagram/Activities/HomeActivity.java
2a2b043f2642098683095978a3101fffc3ad2d4a
[ "Apache-2.0" ]
permissive
timsoetan/Instagram
https://github.com/timsoetan/Instagram
554f082a898d69a6898d568170552a8c4c65f5ec
ad7f1875ab4fc590de0d47fab2c905c07067fdea
refs/heads/master
2020-06-17T12:28:16.918000
2019-07-13T00:36:06
2019-07-13T00:36:06
195,924,728
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.instagram.Activities; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.internal.BottomNavigationItemView; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import com.example.instagram.Fragments.EmptyFragment; import com.example.instagram.Fragments.PostFragment; import com.example.instagram.Fragments.TimelineFragment; import com.example.instagram.Model.Post; import com.example.instagram.R; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseUser; import java.util.List; public class HomeActivity extends AppCompatActivity { private BottomNavigationItemView user; private BottomNavigationView bottomNavigationView; FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); Window window = this.getWindow(); // clear FLAG_TRANSLUCENT_STATUS flag: window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); // finally change the color window.setStatusBarColor(this.getResources().getColor(R.color.ig_status_bar)); fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(R.id.centerView, new TimelineFragment()); transaction.addToBackStack(null); transaction.commit(); // Find references for the views bottomNavigationView = findViewById(R.id.bottomNavViewBar); user = findViewById(R.id.navUser); // Set up the navigation bar to switch between fragments bottomNavigationView.setOnNavigationItemSelectedListener( new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { Fragment fragment; FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); switch (menuItem.getItemId()) { case R.id.navHome: fragment = new TimelineFragment(); break; case R.id.navSearch: fragment = new EmptyFragment(); break; case R.id.navPost: fragment = new PostFragment(); break; case R.id.navHeart: fragment = new EmptyFragment(); break; case R.id.navUser: fragment = new EmptyFragment(); break; default: fragment = new TimelineFragment(); break; } fragmentManager.beginTransaction().replace(R.id.centerView, fragment).commit(); return true; } }); // Set up the user profile button to log out on long click user.setLongClickable(true); user.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { AlertDialog.Builder alert = new AlertDialog.Builder( HomeActivity.this); alert.setTitle("Log Out"); alert.setIcon(R.drawable.ic_alert); alert.setMessage("Are you sure you want to log out?"); alert.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ParseUser.logOut(); final Intent intent = new Intent(HomeActivity.this, LoginActivity.class); startActivity(intent); finish(); dialog.dismiss(); } }); alert.setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); return true; } }); final Post.Query postsQuery = new Post.Query(); postsQuery.getTop().withUser(); postsQuery.findInBackground(new FindCallback<Post>() { @Override public void done(List<Post> objects, ParseException e) { if (e == null) { for (int i = 0; i < objects.size(); i++) { Log.d("HomeActivity", "Post[" + i + "]" + objects.get(i).getDescription() + "\nusername = " + objects.get(i).getUser().getUsername()); } } else { e.printStackTrace(); } } }); } }
UTF-8
Java
6,009
java
HomeActivity.java
Java
[]
null
[]
package com.example.instagram.Activities; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.internal.BottomNavigationItemView; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import com.example.instagram.Fragments.EmptyFragment; import com.example.instagram.Fragments.PostFragment; import com.example.instagram.Fragments.TimelineFragment; import com.example.instagram.Model.Post; import com.example.instagram.R; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseUser; import java.util.List; public class HomeActivity extends AppCompatActivity { private BottomNavigationItemView user; private BottomNavigationView bottomNavigationView; FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); Window window = this.getWindow(); // clear FLAG_TRANSLUCENT_STATUS flag: window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); // finally change the color window.setStatusBarColor(this.getResources().getColor(R.color.ig_status_bar)); fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(R.id.centerView, new TimelineFragment()); transaction.addToBackStack(null); transaction.commit(); // Find references for the views bottomNavigationView = findViewById(R.id.bottomNavViewBar); user = findViewById(R.id.navUser); // Set up the navigation bar to switch between fragments bottomNavigationView.setOnNavigationItemSelectedListener( new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { Fragment fragment; FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); switch (menuItem.getItemId()) { case R.id.navHome: fragment = new TimelineFragment(); break; case R.id.navSearch: fragment = new EmptyFragment(); break; case R.id.navPost: fragment = new PostFragment(); break; case R.id.navHeart: fragment = new EmptyFragment(); break; case R.id.navUser: fragment = new EmptyFragment(); break; default: fragment = new TimelineFragment(); break; } fragmentManager.beginTransaction().replace(R.id.centerView, fragment).commit(); return true; } }); // Set up the user profile button to log out on long click user.setLongClickable(true); user.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { AlertDialog.Builder alert = new AlertDialog.Builder( HomeActivity.this); alert.setTitle("Log Out"); alert.setIcon(R.drawable.ic_alert); alert.setMessage("Are you sure you want to log out?"); alert.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ParseUser.logOut(); final Intent intent = new Intent(HomeActivity.this, LoginActivity.class); startActivity(intent); finish(); dialog.dismiss(); } }); alert.setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); return true; } }); final Post.Query postsQuery = new Post.Query(); postsQuery.getTop().withUser(); postsQuery.findInBackground(new FindCallback<Post>() { @Override public void done(List<Post> objects, ParseException e) { if (e == null) { for (int i = 0; i < objects.size(); i++) { Log.d("HomeActivity", "Post[" + i + "]" + objects.get(i).getDescription() + "\nusername = " + objects.get(i).getUser().getUsername()); } } else { e.printStackTrace(); } } }); } }
6,009
0.56432
0.563322
153
38.281044
25.690073
103
false
false
0
0
0
0
0
0
0.594771
false
false
1
7c02ccc83f939ff7f1da85525cafe5bb59b8e2c0
6,545,530,213,370
a31b9b2bea576c88bb87538261ea10c64c731421
/app/src/main/java/org/ascebuffalo/asce/DayScheduleFragment.java
d56178da9853ae85c69f212fc84bedb2aad24fd4
[]
no_license
tSquaredd/ASCE-Android
https://github.com/tSquaredd/ASCE-Android
1fae53cb766b550807dd2ae6e87512dc162ac04a
fa8059ab8e0df05ea86d3bb7908a58d1aa2ce52a
refs/heads/master
2021-09-06T11:17:00.920000
2018-02-05T23:04:25
2018-02-05T23:04:25
110,017,992
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.ascebuffalo.asce; import android.app.ActivityOptions; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.app.Fragment; import android.support.v4.view.ViewCompat; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.transition.TransitionInflater; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import Adapters.ScheduleEventAdapter; import Objects.ScheduleEvent; /** * A simple {@link Fragment} subclass. */ public class DayScheduleFragment extends Fragment implements ScheduleEventAdapter.ScheduleEventOnClickHandler{ RecyclerView mRecyclerView; ScheduleEventAdapter mAdapter; ArrayList<ScheduleEvent> mEventList; public DayScheduleFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_friday_schedule, container, false); mRecyclerView = (RecyclerView)rootView.findViewById(R.id.rv_friday_schedule); mEventList = new ArrayList<ScheduleEvent>(); Bundle args = getArguments(); mEventList = args.getParcelableArrayList("events"); LinearLayoutManager manager = new LinearLayoutManager(this.getContext()); mRecyclerView.setLayoutManager(manager); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration( mRecyclerView.getContext(), manager.getOrientation() ); mRecyclerView.addItemDecoration(dividerItemDecoration); mRecyclerView.setHasFixedSize(false); mAdapter = new ScheduleEventAdapter(mEventList, this); mRecyclerView.setAdapter(mAdapter); // Inflate the layout for this fragment return rootView; } @Override public void onClick(ScheduleEvent event, int position, View v) { Context context = getContext(); Class destinationClass = EventDetailsActivity.class; // Prepare transition Fragment currentFragment = this; currentFragment.setSharedElementReturnTransition(TransitionInflater.from(getContext()) .inflateTransition(R.transition.default_transition)); currentFragment.setExitTransition(TransitionInflater.from(getContext()) .inflateTransition(android.R.transition.no_transition)); Intent intent = new Intent(context, destinationClass); intent.putExtra("event", event); intent.putExtra("transition_name", "transition" + position); // ActivityOptionsCompat options = ActivityOptionsCompat // .makeSceneTransitionAnimation(getActivity(), // v, // "transition_event_name" // ); startActivity(intent); } }
UTF-8
Java
3,225
java
DayScheduleFragment.java
Java
[]
null
[]
package org.ascebuffalo.asce; import android.app.ActivityOptions; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.app.Fragment; import android.support.v4.view.ViewCompat; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.transition.TransitionInflater; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import Adapters.ScheduleEventAdapter; import Objects.ScheduleEvent; /** * A simple {@link Fragment} subclass. */ public class DayScheduleFragment extends Fragment implements ScheduleEventAdapter.ScheduleEventOnClickHandler{ RecyclerView mRecyclerView; ScheduleEventAdapter mAdapter; ArrayList<ScheduleEvent> mEventList; public DayScheduleFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_friday_schedule, container, false); mRecyclerView = (RecyclerView)rootView.findViewById(R.id.rv_friday_schedule); mEventList = new ArrayList<ScheduleEvent>(); Bundle args = getArguments(); mEventList = args.getParcelableArrayList("events"); LinearLayoutManager manager = new LinearLayoutManager(this.getContext()); mRecyclerView.setLayoutManager(manager); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration( mRecyclerView.getContext(), manager.getOrientation() ); mRecyclerView.addItemDecoration(dividerItemDecoration); mRecyclerView.setHasFixedSize(false); mAdapter = new ScheduleEventAdapter(mEventList, this); mRecyclerView.setAdapter(mAdapter); // Inflate the layout for this fragment return rootView; } @Override public void onClick(ScheduleEvent event, int position, View v) { Context context = getContext(); Class destinationClass = EventDetailsActivity.class; // Prepare transition Fragment currentFragment = this; currentFragment.setSharedElementReturnTransition(TransitionInflater.from(getContext()) .inflateTransition(R.transition.default_transition)); currentFragment.setExitTransition(TransitionInflater.from(getContext()) .inflateTransition(android.R.transition.no_transition)); Intent intent = new Intent(context, destinationClass); intent.putExtra("event", event); intent.putExtra("transition_name", "transition" + position); // ActivityOptionsCompat options = ActivityOptionsCompat // .makeSceneTransitionAnimation(getActivity(), // v, // "transition_event_name" // ); startActivity(intent); } }
3,225
0.710698
0.708837
107
29.140186
26.698893
94
false
false
0
0
0
0
0
0
0.551402
false
false
1
c88d94b486a1822695017734e9595c85f4e55ea3
11,897,059,465,355
028c967526deb3ca62ed069a07bdc8ddf8f44d0b
/JAVA/tbk-backoffice-promociones-jobs-ejecuta-dth-tc/src/main/java/com/tbk/bach/transacciones/dto/ResumenDiarioDTO.java
90bf29b56607e23ec7c089fa81f4d2fcbf9b0d2f
[]
no_license
r3ing/bkp-all
https://github.com/r3ing/bkp-all
629fb5d44b3bcfe0b45f5fb505734465532707ce
12383ab7578dffa1b220dc51b00e157034fc529d
refs/heads/master
2020-06-23T14:28:45.206000
2019-07-24T21:21:06
2019-07-24T21:21:06
198,489,600
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tbk.bach.transacciones.dto; public class ResumenDiarioDTO { private int montoAcumulado; private int cantidadDeTransaccionesProcesadas; private int cantidadDeTarjetasProcesadas; public int getMontoAcumulado() { return montoAcumulado; } public void setMontoAcumulado(int montoAcumulado) { this.montoAcumulado = montoAcumulado; } public int getCantidadDeTransaccionesProcesadas() { return cantidadDeTransaccionesProcesadas; } public void setCantidadDeTransaccionesProcesadas(int cantidadDeTransaccionesProcesadas) { this.cantidadDeTransaccionesProcesadas = cantidadDeTransaccionesProcesadas; } public int getCantidadDeTarjetasProcesadas() { return cantidadDeTarjetasProcesadas; } public void setCantidadDeTarjetasProcesadas(int cantidadDeTarjetasProcesadas) { this.cantidadDeTarjetasProcesadas = cantidadDeTarjetasProcesadas; } }
UTF-8
Java
875
java
ResumenDiarioDTO.java
Java
[]
null
[]
package com.tbk.bach.transacciones.dto; public class ResumenDiarioDTO { private int montoAcumulado; private int cantidadDeTransaccionesProcesadas; private int cantidadDeTarjetasProcesadas; public int getMontoAcumulado() { return montoAcumulado; } public void setMontoAcumulado(int montoAcumulado) { this.montoAcumulado = montoAcumulado; } public int getCantidadDeTransaccionesProcesadas() { return cantidadDeTransaccionesProcesadas; } public void setCantidadDeTransaccionesProcesadas(int cantidadDeTransaccionesProcesadas) { this.cantidadDeTransaccionesProcesadas = cantidadDeTransaccionesProcesadas; } public int getCantidadDeTarjetasProcesadas() { return cantidadDeTarjetasProcesadas; } public void setCantidadDeTarjetasProcesadas(int cantidadDeTarjetasProcesadas) { this.cantidadDeTarjetasProcesadas = cantidadDeTarjetasProcesadas; } }
875
0.833143
0.833143
33
25.515152
27.410595
90
false
false
0
0
0
0
0
0
1.121212
false
false
1
76d927c8c463db6de828eff6b3ddbe020d5b8cd9
11,897,059,463,819
7f48e1e713a513fff36851300f17152d2eaf159f
/plugins/transforms/mongodb/src/main/java/org/apache/hop/pipeline/transforms/mongodbinput/MongoDbInputDialog.java
e8c101824249dd9b0bbac7f14bda79064b063455
[ "Apache-2.0", "CC-BY-SA-3.0", "CC-BY-SA-4.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
HiromuHota/incubator-hop
https://github.com/HiromuHota/incubator-hop
af414f7a25e1c79a1eecbbd8d44e5730c9d542a5
2b159a8477c1e509401f3626940d4b1f700f2584
refs/heads/web
2023-04-03T13:09:31.957000
2021-04-04T23:44:11
2021-04-04T23:44:11
311,226,935
2
1
Apache-2.0
true
2021-03-01T01:11:28
2020-11-09T04:50:08
2021-02-25T05:35:52
2021-03-01T01:11:27
79,672
1
0
1
Java
false
false
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hop.pipeline.transforms.mongodbinput; import org.apache.commons.lang.StringUtils; import org.apache.hop.core.Const; import org.apache.hop.core.Props; import org.apache.hop.core.exception.HopException; import org.apache.hop.core.row.value.ValueMetaFactory; import org.apache.hop.core.variables.IVariables; import org.apache.hop.i18n.BaseMessages; import org.apache.hop.metadata.api.IHopMetadataProvider; import org.apache.hop.mongo.metadata.MongoDbConnection; import org.apache.hop.mongo.wrapper.MongoClientWrapper; import org.apache.hop.mongo.wrapper.field.MongoField; import org.apache.hop.mongo.wrapper.field.MongodbInputDiscoverFieldsImpl; import org.apache.hop.pipeline.Pipeline; import org.apache.hop.pipeline.PipelineMeta; import org.apache.hop.pipeline.PipelinePreviewFactory; import org.apache.hop.pipeline.transform.BaseTransformMeta; import org.apache.hop.pipeline.transform.ITransformDialog; import org.apache.hop.ui.core.PropsUi; import org.apache.hop.ui.core.dialog.EnterNumberDialog; import org.apache.hop.ui.core.dialog.EnterTextDialog; import org.apache.hop.ui.core.dialog.ErrorDialog; import org.apache.hop.ui.core.dialog.PreviewRowsDialog; import org.apache.hop.ui.core.dialog.ShowMessageDialog; import org.apache.hop.ui.core.widget.ColumnInfo; import org.apache.hop.ui.core.widget.MetaSelectionLine; import org.apache.hop.ui.core.widget.StyledTextComp; import org.apache.hop.ui.core.widget.TableView; import org.apache.hop.ui.core.widget.TextVar; import org.apache.hop.ui.pipeline.dialog.PipelinePreviewProgressDialog; import org.apache.hop.ui.pipeline.transform.BaseTransformDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class MongoDbInputDialog extends BaseTransformDialog implements ITransformDialog { private static Class<?> PKG = MongoDbInputMeta.class; // For i18n - Translator private MetaSelectionLine<MongoDbConnection> wConnection; private TextVar wFieldsName; private CCombo wCollection; private TextVar wJsonField; private StyledTextComp wJsonQuery; private Label wlJsonQuery; private Button wbQueryIsPipeline; private Button wbOutputAsJson; private TableView wFields; private Button wbExecuteForEachRow; private final MongoDbInputMeta input; public MongoDbInputDialog( Shell parent, IVariables variables, Object in, PipelineMeta tr, String sname) { super(parent, variables, (BaseTransformMeta) in, tr, sname); input = (MongoDbInputMeta) in; } @Override public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN); props.setLook(shell); setShellImage(shell, input); ModifyListener lsMod = e -> input.setChanged(); changed = input.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.Shell.Title")); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Some buttons wOk = new Button(shell, SWT.PUSH); wOk.setText(BaseMessages.getString(PKG, "System.Button.OK")); wOk.addListener(SWT.Selection, e -> ok()); wPreview = new Button(shell, SWT.PUSH); wPreview.setText(BaseMessages.getString(PKG, "System.Button.Preview")); wPreview.addListener(SWT.Selection, e -> preview()); wCancel = new Button(shell, SWT.PUSH); wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); wCancel.addListener(SWT.Selection, e -> cancel()); setButtonPositions(new Button[] {wOk, wPreview, wCancel}, margin, null); // TransformName line wlTransformName = new Label(shell, SWT.RIGHT); wlTransformName.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.TransformName.Label")); props.setLook(wlTransformName); fdlTransformName = new FormData(); fdlTransformName.left = new FormAttachment(0, 0); fdlTransformName.right = new FormAttachment(middle, -margin); fdlTransformName.top = new FormAttachment(0, margin); wlTransformName.setLayoutData(fdlTransformName); wTransformName = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wTransformName.setText(transformName); props.setLook(wTransformName); wTransformName.addModifyListener(lsMod); fdTransformName = new FormData(); fdTransformName.left = new FormAttachment(middle, 0); fdTransformName.top = new FormAttachment(0, margin); fdTransformName.right = new FormAttachment(100, 0); wTransformName.setLayoutData(fdTransformName); Control lastControl = wTransformName; CTabFolder wTabFolder = new CTabFolder(shell, SWT.BORDER); props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB); // Input options tab ----- CTabItem wInputOptionsTab = new CTabItem(wTabFolder, SWT.NONE); wInputOptionsTab.setText( BaseMessages.getString(PKG, "MongoDbInputDialog.InputOptionsTab.TabTitle")); Composite wInputOptionsComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wInputOptionsComp); FormLayout inputLayout = new FormLayout(); inputLayout.marginWidth = 3; inputLayout.marginHeight = 3; wInputOptionsComp.setLayout(inputLayout); // The connection to use... // wConnection = new MetaSelectionLine<>( variables, metadataProvider, MongoDbConnection.class, wInputOptionsComp, SWT.NONE, BaseMessages.getString(PKG, "MongoDbInputDialog.ConnectionName.Label"), BaseMessages.getString(PKG, "MongoDbInputDialog.ConnectionName.Tooltip")); FormData fdConnection = new FormData(); fdConnection.left = new FormAttachment(0, 0); fdConnection.right = new FormAttachment(100, 0); fdConnection.top = new FormAttachment(0, 0); wConnection.setLayoutData(fdConnection); lastControl = wConnection; try { wConnection.fillItems(); } catch (HopException e) { new ErrorDialog(shell, "Error", "Error loading list of MongoDB connection names", e); } // Collection input ... // Label wlCollection = new Label(wInputOptionsComp, SWT.RIGHT); wlCollection.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.Collection.Label")); props.setLook(wlCollection); FormData fdlCollection = new FormData(); fdlCollection.left = new FormAttachment(0, 0); fdlCollection.right = new FormAttachment(middle, -margin); fdlCollection.top = new FormAttachment(lastControl, margin); wlCollection.setLayoutData(fdlCollection); Button wbGetCollections = new Button(wInputOptionsComp, SWT.PUSH | SWT.CENTER); props.setLook(wbGetCollections); wbGetCollections.setText( BaseMessages.getString(PKG, "MongoDbInputDialog.GetCollections.Button")); FormData fd = new FormData(); fd.right = new FormAttachment(100, 0); fd.top = new FormAttachment(lastControl, 0); wbGetCollections.setLayoutData(fd); wbGetCollections.addListener(SWT.Selection, e -> getCollectionNames()); wCollection = new CCombo(wInputOptionsComp, SWT.BORDER); props.setLook(wCollection); wCollection.addModifyListener(lsMod); FormData fdCollection = new FormData(); fdCollection.left = new FormAttachment(middle, 0); fdCollection.top = new FormAttachment(lastControl, margin); fdCollection.right = new FormAttachment(wbGetCollections, 0); wCollection.setLayoutData(fdCollection); lastControl = wCollection; wCollection.addListener(SWT.Selection, e -> updateQueryTitleInfo()); wCollection.addListener(SWT.FocusOut, e -> updateQueryTitleInfo()); fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(100, 0); wInputOptionsComp.setLayoutData(fd); wInputOptionsComp.layout(); wInputOptionsTab.setControl(wInputOptionsComp); // Query tab ----- CTabItem wMongoQueryTab = new CTabItem(wTabFolder, SWT.NONE); wMongoQueryTab.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.QueryTab.TabTitle")); Composite wQueryComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wQueryComp); FormLayout queryLayout = new FormLayout(); queryLayout.marginWidth = 3; queryLayout.marginHeight = 3; wQueryComp.setLayout(queryLayout); // fields input ... // Label wlFieldsName = new Label(wQueryComp, SWT.RIGHT); wlFieldsName.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.FieldsName.Label")); props.setLook(wlFieldsName); FormData fdlFieldsName = new FormData(); fdlFieldsName.left = new FormAttachment(0, 0); fdlFieldsName.right = new FormAttachment(middle, -margin); fdlFieldsName.bottom = new FormAttachment(100, -margin); wlFieldsName.setLayoutData(fdlFieldsName); wFieldsName = new TextVar(variables, wQueryComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wFieldsName); wFieldsName.addModifyListener(lsMod); FormData fdFieldsName = new FormData(); fdFieldsName.left = new FormAttachment(middle, 0); fdFieldsName.bottom = new FormAttachment(100, -margin); fdFieldsName.right = new FormAttachment(100, 0); wFieldsName.setLayoutData(fdFieldsName); lastControl = wFieldsName; Label executeForEachRLab = new Label(wQueryComp, SWT.RIGHT); executeForEachRLab.setText( BaseMessages.getString(PKG, "MongoDbInputDialog.ExecuteForEachRow.Label")); props.setLook(executeForEachRLab); fd = new FormData(); fd.left = new FormAttachment(0, -margin); fd.bottom = new FormAttachment(lastControl, -2 * margin); fd.right = new FormAttachment(middle, -margin); executeForEachRLab.setLayoutData(fd); wbExecuteForEachRow = new Button(wQueryComp, SWT.CHECK); props.setLook(wbExecuteForEachRow); fd = new FormData(); fd.left = new FormAttachment(middle, 0); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(executeForEachRLab, 0, SWT.CENTER); wbExecuteForEachRow.setLayoutData(fd); lastControl = executeForEachRLab; Label queryIsPipelineL = new Label(wQueryComp, SWT.RIGHT); queryIsPipelineL.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.Pipeline.Label")); props.setLook(queryIsPipelineL); fd = new FormData(); fd.bottom = new FormAttachment(lastControl, -2 * margin); fd.left = new FormAttachment(0, -margin); fd.right = new FormAttachment(middle, -margin); queryIsPipelineL.setLayoutData(fd); wbQueryIsPipeline = new Button(wQueryComp, SWT.CHECK); props.setLook(wbQueryIsPipeline); fd = new FormData(); fd.top = new FormAttachment(queryIsPipelineL, 0, SWT.CENTER); fd.left = new FormAttachment(middle, 0); fd.right = new FormAttachment(100, 0); wbQueryIsPipeline.setLayoutData(fd); wbQueryIsPipeline.addListener(SWT.Selection, e -> updateQueryTitleInfo()); lastControl = queryIsPipelineL; // JSON Query input ... // wlJsonQuery = new Label(wQueryComp, SWT.NONE); wlJsonQuery.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.JsonQuery.Label")); props.setLook(wlJsonQuery); FormData fdlJsonQuery = new FormData(); fdlJsonQuery.left = new FormAttachment(0, 0); fdlJsonQuery.right = new FormAttachment(100, -margin); fdlJsonQuery.top = new FormAttachment(0, margin); wlJsonQuery.setLayoutData(fdlJsonQuery); wJsonQuery = new StyledTextComp( variables, wQueryComp, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); props.setLook(wJsonQuery, PropsUi.WIDGET_STYLE_FIXED); wJsonQuery.addModifyListener(lsMod); /* * wJsonQuery = new TextVar( variables, wQueryComp, SWT.SINGLE | SWT.LEFT | * SWT.BORDER); props.setLook(wJsonQuery); * wJsonQuery.addModifyListener(lsMod); */ FormData fdJsonQuery = new FormData(); fdJsonQuery.left = new FormAttachment(0, 0); fdJsonQuery.top = new FormAttachment(wlJsonQuery, margin); fdJsonQuery.right = new FormAttachment(100, -2 * margin); fdJsonQuery.bottom = new FormAttachment(lastControl, -2 * margin); // wJsonQuery.setLayoutData(fdJsonQuery); wJsonQuery.setLayoutData(fdJsonQuery); // lastControl = wJsonQuery; lastControl = wJsonQuery; fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(100, 0); wQueryComp.setLayoutData(fd); wQueryComp.layout(); wMongoQueryTab.setControl(wQueryComp); // fields tab ----- CTabItem wMongoFieldsTab = new CTabItem(wTabFolder, SWT.NONE); wMongoFieldsTab.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.FieldsTab.TabTitle")); Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wFieldsComp); FormLayout fieldsLayout = new FormLayout(); fieldsLayout.marginWidth = 3; fieldsLayout.marginHeight = 3; wFieldsComp.setLayout(fieldsLayout); // Output as Json check box Label outputJLab = new Label(wFieldsComp, SWT.RIGHT); outputJLab.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.OutputJson.Label")); props.setLook(outputJLab); fd = new FormData(); fd.top = new FormAttachment(0, 0); fd.left = new FormAttachment(0, 0); fd.right = new FormAttachment(middle, -2 * margin); outputJLab.setLayoutData(fd); wbOutputAsJson = new Button(wFieldsComp, SWT.CHECK); props.setLook(wbOutputAsJson); fd = new FormData(); fd.top = new FormAttachment(outputJLab, 0, SWT.CENTER); fd.left = new FormAttachment(middle, 0); fd.right = new FormAttachment(100, 0); wbOutputAsJson.setLayoutData(fd); wbOutputAsJson.addListener( SWT.Selection, e -> { input.setChanged(); wGet.setEnabled(!wbOutputAsJson.getSelection()); wJsonField.setEnabled(wbOutputAsJson.getSelection()); }); lastControl = wbOutputAsJson; // JsonField input ... // Label wlJsonField = new Label(wFieldsComp, SWT.RIGHT); wlJsonField.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.JsonField.Label")); props.setLook(wlJsonField); FormData fdlJsonField = new FormData(); fdlJsonField.left = new FormAttachment(0, 0); fdlJsonField.right = new FormAttachment(middle, -margin); fdlJsonField.top = new FormAttachment(lastControl, 2 * margin); wlJsonField.setLayoutData(fdlJsonField); wJsonField = new TextVar(variables, wFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wJsonField); wJsonField.addModifyListener(lsMod); FormData fdJsonField = new FormData(); fdJsonField.left = new FormAttachment(middle, 0); fdJsonField.top = new FormAttachment(lastControl, margin); fdJsonField.right = new FormAttachment(100, 0); wJsonField.setLayoutData(fdJsonField); lastControl = wJsonField; // get fields button wGet = new Button(wFieldsComp, SWT.PUSH); wGet.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.Button.GetFields")); props.setLook(wGet); fd = new FormData(); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(100, 0); wGet.setLayoutData(fd); wGet.addListener( SWT.Selection, e -> { // populate table from schema MongoDbInputMeta newMeta = (MongoDbInputMeta) input.clone(); getFields(newMeta); }); // fields stuff final ColumnInfo[] colinf = new ColumnInfo[] { new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.FIELD_NAME"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.FIELD_PATH"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.FIELD_TYPE"), ColumnInfo.COLUMN_TYPE_CCOMBO, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.FIELD_INDEXED"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.SAMPLE_ARRAYINFO"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.SAMPLE_PERCENTAGE"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.SAMPLE_DISPARATE_TYPES"), ColumnInfo.COLUMN_TYPE_TEXT, false), }; colinf[2].setComboValues(ValueMetaFactory.getAllValueMetaNames()); colinf[4].setReadOnly(true); colinf[5].setReadOnly(true); colinf[6].setReadOnly(true); wFields = new TableView( variables, wFieldsComp, SWT.FULL_SELECTION | SWT.MULTI, colinf, 1, lsMod, props); fd = new FormData(); fd.top = new FormAttachment(lastControl, margin * 2); fd.bottom = new FormAttachment(wGet, -margin * 2); fd.left = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); wFields.setLayoutData(fd); fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(100, 0); wFieldsComp.setLayoutData(fd); wFieldsComp.layout(); wMongoFieldsTab.setControl(wFieldsComp); // -------------- fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(wTransformName, margin); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(wOk, -2 * margin); wTabFolder.setLayoutData(fd); // Add listeners lsDef = new SelectionAdapter() { @Override public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wTransformName.addSelectionListener(lsDef); wCollection.addSelectionListener(lsDef); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { @Override public void shellClosed(ShellEvent e) { cancel(); } }); getData(input); input.setChanged(changed); wTabFolder.setSelection(0); // Set the shell size, based upon previous time... setSize(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return transformName; } /** Copy information from the meta-data input to the dialog fields. */ public void getData(MongoDbInputMeta meta) { wConnection.setText(Const.NVL(meta.getConnectionName(), "")); wFieldsName.setText(Const.NVL(meta.getFieldsName(), "")); wCollection.setText(Const.NVL(meta.getCollection(), "")); wJsonField.setText(Const.NVL(meta.getJsonFieldName(), "")); wJsonQuery.setText(Const.NVL(meta.getJsonQuery(), "")); wbQueryIsPipeline.setSelection(meta.isQueryIsPipeline()); wbOutputAsJson.setSelection(meta.isOutputJson()); wbExecuteForEachRow.setSelection(meta.getExecuteForEachIncomingRow()); refreshFields(meta.getMongoFields()); wJsonField.setEnabled(meta.isOutputJson()); wGet.setEnabled(!meta.isOutputJson()); updateQueryTitleInfo(); wTransformName.selectAll(); } private void updateQueryTitleInfo() { if (wbQueryIsPipeline.getSelection()) { wlJsonQuery.setText( BaseMessages.getString(PKG, "MongoDbInputDialog.JsonQuery.Label2") + ": db." + Const.NVL(wCollection.getText(), "n/a") + ".aggregate(..."); wFieldsName.setEnabled(false); } else { wlJsonQuery.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.JsonQuery.Label")); wFieldsName.setEnabled(true); } } private void cancel() { transformName = null; input.setChanged(changed); dispose(); } private void getInfo(MongoDbInputMeta meta) { meta.setConnectionName(wConnection.getText()); meta.setFieldsName(wFieldsName.getText()); meta.setCollection(wCollection.getText()); meta.setJsonFieldName(wJsonField.getText()); meta.setJsonQuery(wJsonQuery.getText()); meta.setOutputJson(wbOutputAsJson.getSelection()); meta.setQueryIsPipeline(wbQueryIsPipeline.getSelection()); meta.setExecuteForEachIncomingRow(wbExecuteForEachRow.getSelection()); int numNonEmpty = wFields.nrNonEmpty(); if (numNonEmpty > 0) { List<MongoField> outputFields = new ArrayList<>(); for (int i = 0; i < numNonEmpty; i++) { TableItem item = wFields.getNonEmpty(i); MongoField newField = new MongoField(); newField.fieldName = item.getText(1).trim(); newField.fieldPath = item.getText(2).trim(); newField.hopType = item.getText(3).trim(); if (!StringUtils.isEmpty(item.getText(4))) { newField.indexedValues = MongoDbInputData.indexedValsList(item.getText(4).trim()); } outputFields.add(newField); } meta.setMongoFields(outputFields); } } private void ok() { if (StringUtils.isEmpty(wTransformName.getText())) { return; } transformName = wTransformName.getText(); // return value getInfo(input); dispose(); } public boolean isTableDisposed() { return wFields.isDisposed(); } private void refreshFields( List<MongoField> fields) { if (fields == null) { return; } wFields.clearAll(); for (MongoField f : fields) { TableItem item = new TableItem(wFields.table, SWT.NONE); updateTableItem(item, f); } wFields.removeEmptyRows(); wFields.setRowNums(); wFields.optWidth(true); } public void updateFieldTableFields(List<MongoField> fields) { Map<String, MongoField> fieldMap = new HashMap<>(fields.size()); for (MongoField field : fields) { fieldMap.put(field.fieldName, field); } int index = 0; List<Integer> indicesToRemove = new ArrayList<>(); for (TableItem tableItem : wFields.getTable().getItems()) { String name = tableItem.getText(1); MongoField mongoField = fieldMap.remove(name); if (mongoField == null) { // Value does not exist in incoming fields list and exists in table, remove old value from // table indicesToRemove.add(index); } else { // Value exists in incoming fields list and in table, update entry updateTableItem(tableItem, mongoField); } index++; } int[] indicesArray = new int[indicesToRemove.size()]; for (int i = 0; i < indicesArray.length; i++) { indicesArray[i] = indicesToRemove.get(i); } for (MongoField mongoField : fieldMap.values()) { TableItem item = new TableItem(wFields.table, SWT.NONE); updateTableItem(item, mongoField); } wFields.setRowNums(); wFields.remove(indicesArray); wFields.removeEmptyRows(); wFields.setRowNums(); wFields.optWidth(true); } private void updateTableItem(TableItem tableItem, MongoField mongoField) { if (!StringUtils.isEmpty(mongoField.fieldName)) { tableItem.setText(1, mongoField.fieldName); } if (!StringUtils.isEmpty(mongoField.fieldPath)) { tableItem.setText(2, mongoField.fieldPath); } if (!StringUtils.isEmpty(mongoField.hopType)) { tableItem.setText(3, mongoField.hopType); } if (mongoField.indexedValues != null && mongoField.indexedValues.size() > 0) { tableItem.setText(4, MongoDbInputData.indexedValsList(mongoField.indexedValues)); } if (!StringUtils.isEmpty(mongoField.arrayIndexInfo)) { tableItem.setText(5, mongoField.arrayIndexInfo); } if (!StringUtils.isEmpty(mongoField.occurrenceFraction)) { tableItem.setText(6, mongoField.occurrenceFraction); } if (mongoField.disparateTypes) { tableItem.setText(7, "Y"); } } private boolean checkForUnresolved(MongoDbInputMeta meta, String title) { String query = variables.resolve(meta.getJsonQuery()); boolean notOk = (query.contains("${") || query.contains("?{")); if (notOk) { ShowMessageDialog smd = new ShowMessageDialog( shell, SWT.ICON_WARNING | SWT.OK, title, BaseMessages.getString( PKG, "MongoDbInputDialog.Warning.Message.MongoQueryContainsUnresolvedVarsFieldSubs")); smd.open(); } return !notOk; } // Used to catch exceptions from discoverFields calls that come through the callback public void handleNotificationException(Exception exception) { new ErrorDialog( shell, transformName, BaseMessages.getString(PKG, "MongoDbInputDialog.ErrorMessage.ErrorDuringSampling"), exception); } private void getFields(MongoDbInputMeta meta) { if (!StringUtils.isEmpty(wConnection.getText()) && !StringUtils.isEmpty(wCollection.getText())) { EnterNumberDialog end = new EnterNumberDialog( shell, 100, BaseMessages.getString(PKG, "MongoDbInputDialog.SampleDocuments.Title"), BaseMessages.getString(PKG, "MongoDbInputDialog.SampleDocuments.Message")); int samples = end.open(); if (samples > 0) { getInfo(meta); // Turn off execute for each incoming row (if set). // Query is still going to // be stuffed if the user has specified field replacement (i.e. // ?{...}) in the query string boolean current = meta.getExecuteForEachIncomingRow(); meta.setExecuteForEachIncomingRow(false); if (!checkForUnresolved( meta, BaseMessages.getString( PKG, "MongoDbInputDialog.Warning.Message.MongoQueryContainsUnresolvedVarsFieldSubs.SamplingTitle"))) { return; } try { discoverFields(meta, variables, samples, metadataProvider); meta.setExecuteForEachIncomingRow(current); refreshFields(meta.getMongoFields()); } catch (HopException e) { new ErrorDialog( shell, transformName, BaseMessages.getString(PKG, "MongoDbInputDialog.ErrorMessage.ErrorDuringSampling"), e); } } } else { // pop up an error dialog String missingConDetails = ""; if (StringUtils.isEmpty(wConnection.getText())) { missingConDetails += " connection name"; } if (StringUtils.isEmpty(wCollection.getText())) { missingConDetails += " collection"; } ShowMessageDialog smd = new ShowMessageDialog( shell, SWT.ICON_WARNING | SWT.OK, BaseMessages.getString( PKG, "MongoDbInputDialog.ErrorMessage.MissingConnectionDetails.Title"), BaseMessages.getString( PKG, "MongoDbInputDialog.ErrorMessage.MissingConnectionDetails", missingConDetails)); smd.open(); } } // Preview the data private void preview() { // Create the XML input transform MongoDbInputMeta oneMeta = new MongoDbInputMeta(); getInfo(oneMeta); // Turn off execute for each incoming row (if set). Query is still going to // be stuffed if the user has specified field replacement (i.e. ?{...}) in // the query string oneMeta.setExecuteForEachIncomingRow(false); if (!checkForUnresolved( oneMeta, BaseMessages.getString( PKG, "MongoDbInputDialog.Warning.Message.MongoQueryContainsUnresolvedVarsFieldSubs.PreviewTitle"))) { return; } PipelineMeta previewMeta = PipelinePreviewFactory.generatePreviewPipeline( metadataProvider, oneMeta, wTransformName.getText()); EnterNumberDialog numberDialog = new EnterNumberDialog( shell, props.getDefaultPreviewSize(), BaseMessages.getString(PKG, "MongoDbInputDialog.PreviewSize.DialogTitle"), BaseMessages.getString(PKG, "MongoDbInputDialog.PreviewSize.DialogMessage")); int previewSize = numberDialog.open(); if (previewSize > 0) { PipelinePreviewProgressDialog progressDialog = new PipelinePreviewProgressDialog( shell, variables, previewMeta, new String[] {wTransformName.getText()}, new int[] {previewSize}); progressDialog.open(); Pipeline pipeline = progressDialog.getPipeline(); String loggingText = progressDialog.getLoggingText(); if (!progressDialog.isCancelled()) { if (pipeline.getResult() != null && pipeline.getResult().getNrErrors() > 0) { EnterTextDialog etd = new EnterTextDialog( shell, BaseMessages.getString(PKG, "System.Dialog.PreviewError.Title"), BaseMessages.getString(PKG, "System.Dialog.PreviewError.Message"), loggingText, true); etd.setReadOnly(); etd.open(); } } PreviewRowsDialog prd = new PreviewRowsDialog( shell, variables, SWT.NONE, wTransformName.getText(), progressDialog.getPreviewRowsMeta(wTransformName.getText()), progressDialog.getPreviewRows(wTransformName.getText()), loggingText); prd.open(); } } private void getCollectionNames() { try { String connectionName = variables.resolve(wConnection.getText()); String current = wCollection.getText(); wCollection.removeAll(); MongoDbConnection connection = metadataProvider.getSerializer(MongoDbConnection.class).load(connectionName); String databaseName = variables.resolve(connection.getDbName()); if (!StringUtils.isEmpty(connectionName)) { final MongoDbInputMeta meta = new MongoDbInputMeta(); getInfo(meta); try { MongoClientWrapper wrapper = connection.createWrapper(variables, log); Set<String> collections; try { collections = wrapper.getCollectionsNames(databaseName); } finally { wrapper.dispose(); } for (String c : collections) { wCollection.add(c); } } catch (Exception e) { logError( BaseMessages.getString(PKG, "MongoDbInputDialog.ErrorMessage.UnableToConnect"), e); new ErrorDialog( shell, BaseMessages.getString(PKG, "MongoDbInputDialog.ErrorMessage.UnableToConnect"), BaseMessages.getString(PKG, "MongoDbInputDialog.ErrorMessage.UnableToConnect"), e); } } else { // popup some feedback String missingConnDetails = ""; if (StringUtils.isEmpty(connectionName)) { missingConnDetails += "connection name"; } ShowMessageDialog smd = new ShowMessageDialog( shell, SWT.ICON_WARNING | SWT.OK, BaseMessages.getString( PKG, "MongoDbInputDialog.ErrorMessage.MissingConnectionDetails.Title"), BaseMessages.getString( PKG, "MongoDbInputDialog.ErrorMessage.MissingConnectionDetails", missingConnDetails)); smd.open(); } if (!StringUtils.isEmpty(current)) { wCollection.setText(current); } } catch (Exception e) { new ErrorDialog(shell, "Error", "Error getting collections", e); } } public static boolean discoverFields( final MongoDbInputMeta meta, final IVariables variables, final int docsToSample, IHopMetadataProvider metadataProvider) throws HopException { String connectionName = variables.resolve(meta.getConnectionName()); try { MongoDbConnection connection = metadataProvider.getSerializer(MongoDbConnection.class).load(connectionName); if (connection == null) { throw new HopException("Unable to find connection " + connectionName); } String collection = variables.resolve(meta.getCollection()); String query = variables.resolve(meta.getJsonQuery()); String fields = variables.resolve(meta.getFieldsName()); int numDocsToSample = docsToSample; if (numDocsToSample < 1) { numDocsToSample = 100; // default } MongodbInputDiscoverFieldsImpl discoverFields = new MongodbInputDiscoverFieldsImpl(); List<MongoField> discoveredFields = discoverFields .discoverFields( variables, connection, collection, query, fields, meta.isQueryIsPipeline(), numDocsToSample, meta); // return true if query resulted in documents being returned and fields // getting extracted if (discoveredFields.size() > 0) { meta.setMongoFields(discoveredFields); return true; } } catch (Exception e) { if (e instanceof HopException) { throw (HopException) e; } else { throw new HopException("Unable to discover fields from MongoDB", e); } } return false; } }
UTF-8
Java
35,640
java
MongoDbInputDialog.java
Java
[]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hop.pipeline.transforms.mongodbinput; import org.apache.commons.lang.StringUtils; import org.apache.hop.core.Const; import org.apache.hop.core.Props; import org.apache.hop.core.exception.HopException; import org.apache.hop.core.row.value.ValueMetaFactory; import org.apache.hop.core.variables.IVariables; import org.apache.hop.i18n.BaseMessages; import org.apache.hop.metadata.api.IHopMetadataProvider; import org.apache.hop.mongo.metadata.MongoDbConnection; import org.apache.hop.mongo.wrapper.MongoClientWrapper; import org.apache.hop.mongo.wrapper.field.MongoField; import org.apache.hop.mongo.wrapper.field.MongodbInputDiscoverFieldsImpl; import org.apache.hop.pipeline.Pipeline; import org.apache.hop.pipeline.PipelineMeta; import org.apache.hop.pipeline.PipelinePreviewFactory; import org.apache.hop.pipeline.transform.BaseTransformMeta; import org.apache.hop.pipeline.transform.ITransformDialog; import org.apache.hop.ui.core.PropsUi; import org.apache.hop.ui.core.dialog.EnterNumberDialog; import org.apache.hop.ui.core.dialog.EnterTextDialog; import org.apache.hop.ui.core.dialog.ErrorDialog; import org.apache.hop.ui.core.dialog.PreviewRowsDialog; import org.apache.hop.ui.core.dialog.ShowMessageDialog; import org.apache.hop.ui.core.widget.ColumnInfo; import org.apache.hop.ui.core.widget.MetaSelectionLine; import org.apache.hop.ui.core.widget.StyledTextComp; import org.apache.hop.ui.core.widget.TableView; import org.apache.hop.ui.core.widget.TextVar; import org.apache.hop.ui.pipeline.dialog.PipelinePreviewProgressDialog; import org.apache.hop.ui.pipeline.transform.BaseTransformDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class MongoDbInputDialog extends BaseTransformDialog implements ITransformDialog { private static Class<?> PKG = MongoDbInputMeta.class; // For i18n - Translator private MetaSelectionLine<MongoDbConnection> wConnection; private TextVar wFieldsName; private CCombo wCollection; private TextVar wJsonField; private StyledTextComp wJsonQuery; private Label wlJsonQuery; private Button wbQueryIsPipeline; private Button wbOutputAsJson; private TableView wFields; private Button wbExecuteForEachRow; private final MongoDbInputMeta input; public MongoDbInputDialog( Shell parent, IVariables variables, Object in, PipelineMeta tr, String sname) { super(parent, variables, (BaseTransformMeta) in, tr, sname); input = (MongoDbInputMeta) in; } @Override public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN); props.setLook(shell); setShellImage(shell, input); ModifyListener lsMod = e -> input.setChanged(); changed = input.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.Shell.Title")); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Some buttons wOk = new Button(shell, SWT.PUSH); wOk.setText(BaseMessages.getString(PKG, "System.Button.OK")); wOk.addListener(SWT.Selection, e -> ok()); wPreview = new Button(shell, SWT.PUSH); wPreview.setText(BaseMessages.getString(PKG, "System.Button.Preview")); wPreview.addListener(SWT.Selection, e -> preview()); wCancel = new Button(shell, SWT.PUSH); wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); wCancel.addListener(SWT.Selection, e -> cancel()); setButtonPositions(new Button[] {wOk, wPreview, wCancel}, margin, null); // TransformName line wlTransformName = new Label(shell, SWT.RIGHT); wlTransformName.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.TransformName.Label")); props.setLook(wlTransformName); fdlTransformName = new FormData(); fdlTransformName.left = new FormAttachment(0, 0); fdlTransformName.right = new FormAttachment(middle, -margin); fdlTransformName.top = new FormAttachment(0, margin); wlTransformName.setLayoutData(fdlTransformName); wTransformName = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wTransformName.setText(transformName); props.setLook(wTransformName); wTransformName.addModifyListener(lsMod); fdTransformName = new FormData(); fdTransformName.left = new FormAttachment(middle, 0); fdTransformName.top = new FormAttachment(0, margin); fdTransformName.right = new FormAttachment(100, 0); wTransformName.setLayoutData(fdTransformName); Control lastControl = wTransformName; CTabFolder wTabFolder = new CTabFolder(shell, SWT.BORDER); props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB); // Input options tab ----- CTabItem wInputOptionsTab = new CTabItem(wTabFolder, SWT.NONE); wInputOptionsTab.setText( BaseMessages.getString(PKG, "MongoDbInputDialog.InputOptionsTab.TabTitle")); Composite wInputOptionsComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wInputOptionsComp); FormLayout inputLayout = new FormLayout(); inputLayout.marginWidth = 3; inputLayout.marginHeight = 3; wInputOptionsComp.setLayout(inputLayout); // The connection to use... // wConnection = new MetaSelectionLine<>( variables, metadataProvider, MongoDbConnection.class, wInputOptionsComp, SWT.NONE, BaseMessages.getString(PKG, "MongoDbInputDialog.ConnectionName.Label"), BaseMessages.getString(PKG, "MongoDbInputDialog.ConnectionName.Tooltip")); FormData fdConnection = new FormData(); fdConnection.left = new FormAttachment(0, 0); fdConnection.right = new FormAttachment(100, 0); fdConnection.top = new FormAttachment(0, 0); wConnection.setLayoutData(fdConnection); lastControl = wConnection; try { wConnection.fillItems(); } catch (HopException e) { new ErrorDialog(shell, "Error", "Error loading list of MongoDB connection names", e); } // Collection input ... // Label wlCollection = new Label(wInputOptionsComp, SWT.RIGHT); wlCollection.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.Collection.Label")); props.setLook(wlCollection); FormData fdlCollection = new FormData(); fdlCollection.left = new FormAttachment(0, 0); fdlCollection.right = new FormAttachment(middle, -margin); fdlCollection.top = new FormAttachment(lastControl, margin); wlCollection.setLayoutData(fdlCollection); Button wbGetCollections = new Button(wInputOptionsComp, SWT.PUSH | SWT.CENTER); props.setLook(wbGetCollections); wbGetCollections.setText( BaseMessages.getString(PKG, "MongoDbInputDialog.GetCollections.Button")); FormData fd = new FormData(); fd.right = new FormAttachment(100, 0); fd.top = new FormAttachment(lastControl, 0); wbGetCollections.setLayoutData(fd); wbGetCollections.addListener(SWT.Selection, e -> getCollectionNames()); wCollection = new CCombo(wInputOptionsComp, SWT.BORDER); props.setLook(wCollection); wCollection.addModifyListener(lsMod); FormData fdCollection = new FormData(); fdCollection.left = new FormAttachment(middle, 0); fdCollection.top = new FormAttachment(lastControl, margin); fdCollection.right = new FormAttachment(wbGetCollections, 0); wCollection.setLayoutData(fdCollection); lastControl = wCollection; wCollection.addListener(SWT.Selection, e -> updateQueryTitleInfo()); wCollection.addListener(SWT.FocusOut, e -> updateQueryTitleInfo()); fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(100, 0); wInputOptionsComp.setLayoutData(fd); wInputOptionsComp.layout(); wInputOptionsTab.setControl(wInputOptionsComp); // Query tab ----- CTabItem wMongoQueryTab = new CTabItem(wTabFolder, SWT.NONE); wMongoQueryTab.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.QueryTab.TabTitle")); Composite wQueryComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wQueryComp); FormLayout queryLayout = new FormLayout(); queryLayout.marginWidth = 3; queryLayout.marginHeight = 3; wQueryComp.setLayout(queryLayout); // fields input ... // Label wlFieldsName = new Label(wQueryComp, SWT.RIGHT); wlFieldsName.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.FieldsName.Label")); props.setLook(wlFieldsName); FormData fdlFieldsName = new FormData(); fdlFieldsName.left = new FormAttachment(0, 0); fdlFieldsName.right = new FormAttachment(middle, -margin); fdlFieldsName.bottom = new FormAttachment(100, -margin); wlFieldsName.setLayoutData(fdlFieldsName); wFieldsName = new TextVar(variables, wQueryComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wFieldsName); wFieldsName.addModifyListener(lsMod); FormData fdFieldsName = new FormData(); fdFieldsName.left = new FormAttachment(middle, 0); fdFieldsName.bottom = new FormAttachment(100, -margin); fdFieldsName.right = new FormAttachment(100, 0); wFieldsName.setLayoutData(fdFieldsName); lastControl = wFieldsName; Label executeForEachRLab = new Label(wQueryComp, SWT.RIGHT); executeForEachRLab.setText( BaseMessages.getString(PKG, "MongoDbInputDialog.ExecuteForEachRow.Label")); props.setLook(executeForEachRLab); fd = new FormData(); fd.left = new FormAttachment(0, -margin); fd.bottom = new FormAttachment(lastControl, -2 * margin); fd.right = new FormAttachment(middle, -margin); executeForEachRLab.setLayoutData(fd); wbExecuteForEachRow = new Button(wQueryComp, SWT.CHECK); props.setLook(wbExecuteForEachRow); fd = new FormData(); fd.left = new FormAttachment(middle, 0); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(executeForEachRLab, 0, SWT.CENTER); wbExecuteForEachRow.setLayoutData(fd); lastControl = executeForEachRLab; Label queryIsPipelineL = new Label(wQueryComp, SWT.RIGHT); queryIsPipelineL.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.Pipeline.Label")); props.setLook(queryIsPipelineL); fd = new FormData(); fd.bottom = new FormAttachment(lastControl, -2 * margin); fd.left = new FormAttachment(0, -margin); fd.right = new FormAttachment(middle, -margin); queryIsPipelineL.setLayoutData(fd); wbQueryIsPipeline = new Button(wQueryComp, SWT.CHECK); props.setLook(wbQueryIsPipeline); fd = new FormData(); fd.top = new FormAttachment(queryIsPipelineL, 0, SWT.CENTER); fd.left = new FormAttachment(middle, 0); fd.right = new FormAttachment(100, 0); wbQueryIsPipeline.setLayoutData(fd); wbQueryIsPipeline.addListener(SWT.Selection, e -> updateQueryTitleInfo()); lastControl = queryIsPipelineL; // JSON Query input ... // wlJsonQuery = new Label(wQueryComp, SWT.NONE); wlJsonQuery.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.JsonQuery.Label")); props.setLook(wlJsonQuery); FormData fdlJsonQuery = new FormData(); fdlJsonQuery.left = new FormAttachment(0, 0); fdlJsonQuery.right = new FormAttachment(100, -margin); fdlJsonQuery.top = new FormAttachment(0, margin); wlJsonQuery.setLayoutData(fdlJsonQuery); wJsonQuery = new StyledTextComp( variables, wQueryComp, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); props.setLook(wJsonQuery, PropsUi.WIDGET_STYLE_FIXED); wJsonQuery.addModifyListener(lsMod); /* * wJsonQuery = new TextVar( variables, wQueryComp, SWT.SINGLE | SWT.LEFT | * SWT.BORDER); props.setLook(wJsonQuery); * wJsonQuery.addModifyListener(lsMod); */ FormData fdJsonQuery = new FormData(); fdJsonQuery.left = new FormAttachment(0, 0); fdJsonQuery.top = new FormAttachment(wlJsonQuery, margin); fdJsonQuery.right = new FormAttachment(100, -2 * margin); fdJsonQuery.bottom = new FormAttachment(lastControl, -2 * margin); // wJsonQuery.setLayoutData(fdJsonQuery); wJsonQuery.setLayoutData(fdJsonQuery); // lastControl = wJsonQuery; lastControl = wJsonQuery; fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(100, 0); wQueryComp.setLayoutData(fd); wQueryComp.layout(); wMongoQueryTab.setControl(wQueryComp); // fields tab ----- CTabItem wMongoFieldsTab = new CTabItem(wTabFolder, SWT.NONE); wMongoFieldsTab.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.FieldsTab.TabTitle")); Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wFieldsComp); FormLayout fieldsLayout = new FormLayout(); fieldsLayout.marginWidth = 3; fieldsLayout.marginHeight = 3; wFieldsComp.setLayout(fieldsLayout); // Output as Json check box Label outputJLab = new Label(wFieldsComp, SWT.RIGHT); outputJLab.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.OutputJson.Label")); props.setLook(outputJLab); fd = new FormData(); fd.top = new FormAttachment(0, 0); fd.left = new FormAttachment(0, 0); fd.right = new FormAttachment(middle, -2 * margin); outputJLab.setLayoutData(fd); wbOutputAsJson = new Button(wFieldsComp, SWT.CHECK); props.setLook(wbOutputAsJson); fd = new FormData(); fd.top = new FormAttachment(outputJLab, 0, SWT.CENTER); fd.left = new FormAttachment(middle, 0); fd.right = new FormAttachment(100, 0); wbOutputAsJson.setLayoutData(fd); wbOutputAsJson.addListener( SWT.Selection, e -> { input.setChanged(); wGet.setEnabled(!wbOutputAsJson.getSelection()); wJsonField.setEnabled(wbOutputAsJson.getSelection()); }); lastControl = wbOutputAsJson; // JsonField input ... // Label wlJsonField = new Label(wFieldsComp, SWT.RIGHT); wlJsonField.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.JsonField.Label")); props.setLook(wlJsonField); FormData fdlJsonField = new FormData(); fdlJsonField.left = new FormAttachment(0, 0); fdlJsonField.right = new FormAttachment(middle, -margin); fdlJsonField.top = new FormAttachment(lastControl, 2 * margin); wlJsonField.setLayoutData(fdlJsonField); wJsonField = new TextVar(variables, wFieldsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wJsonField); wJsonField.addModifyListener(lsMod); FormData fdJsonField = new FormData(); fdJsonField.left = new FormAttachment(middle, 0); fdJsonField.top = new FormAttachment(lastControl, margin); fdJsonField.right = new FormAttachment(100, 0); wJsonField.setLayoutData(fdJsonField); lastControl = wJsonField; // get fields button wGet = new Button(wFieldsComp, SWT.PUSH); wGet.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.Button.GetFields")); props.setLook(wGet); fd = new FormData(); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(100, 0); wGet.setLayoutData(fd); wGet.addListener( SWT.Selection, e -> { // populate table from schema MongoDbInputMeta newMeta = (MongoDbInputMeta) input.clone(); getFields(newMeta); }); // fields stuff final ColumnInfo[] colinf = new ColumnInfo[] { new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.FIELD_NAME"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.FIELD_PATH"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.FIELD_TYPE"), ColumnInfo.COLUMN_TYPE_CCOMBO, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.FIELD_INDEXED"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.SAMPLE_ARRAYINFO"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.SAMPLE_PERCENTAGE"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbInputDialog.Fields.SAMPLE_DISPARATE_TYPES"), ColumnInfo.COLUMN_TYPE_TEXT, false), }; colinf[2].setComboValues(ValueMetaFactory.getAllValueMetaNames()); colinf[4].setReadOnly(true); colinf[5].setReadOnly(true); colinf[6].setReadOnly(true); wFields = new TableView( variables, wFieldsComp, SWT.FULL_SELECTION | SWT.MULTI, colinf, 1, lsMod, props); fd = new FormData(); fd.top = new FormAttachment(lastControl, margin * 2); fd.bottom = new FormAttachment(wGet, -margin * 2); fd.left = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); wFields.setLayoutData(fd); fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(100, 0); wFieldsComp.setLayoutData(fd); wFieldsComp.layout(); wMongoFieldsTab.setControl(wFieldsComp); // -------------- fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(wTransformName, margin); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(wOk, -2 * margin); wTabFolder.setLayoutData(fd); // Add listeners lsDef = new SelectionAdapter() { @Override public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wTransformName.addSelectionListener(lsDef); wCollection.addSelectionListener(lsDef); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { @Override public void shellClosed(ShellEvent e) { cancel(); } }); getData(input); input.setChanged(changed); wTabFolder.setSelection(0); // Set the shell size, based upon previous time... setSize(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return transformName; } /** Copy information from the meta-data input to the dialog fields. */ public void getData(MongoDbInputMeta meta) { wConnection.setText(Const.NVL(meta.getConnectionName(), "")); wFieldsName.setText(Const.NVL(meta.getFieldsName(), "")); wCollection.setText(Const.NVL(meta.getCollection(), "")); wJsonField.setText(Const.NVL(meta.getJsonFieldName(), "")); wJsonQuery.setText(Const.NVL(meta.getJsonQuery(), "")); wbQueryIsPipeline.setSelection(meta.isQueryIsPipeline()); wbOutputAsJson.setSelection(meta.isOutputJson()); wbExecuteForEachRow.setSelection(meta.getExecuteForEachIncomingRow()); refreshFields(meta.getMongoFields()); wJsonField.setEnabled(meta.isOutputJson()); wGet.setEnabled(!meta.isOutputJson()); updateQueryTitleInfo(); wTransformName.selectAll(); } private void updateQueryTitleInfo() { if (wbQueryIsPipeline.getSelection()) { wlJsonQuery.setText( BaseMessages.getString(PKG, "MongoDbInputDialog.JsonQuery.Label2") + ": db." + Const.NVL(wCollection.getText(), "n/a") + ".aggregate(..."); wFieldsName.setEnabled(false); } else { wlJsonQuery.setText(BaseMessages.getString(PKG, "MongoDbInputDialog.JsonQuery.Label")); wFieldsName.setEnabled(true); } } private void cancel() { transformName = null; input.setChanged(changed); dispose(); } private void getInfo(MongoDbInputMeta meta) { meta.setConnectionName(wConnection.getText()); meta.setFieldsName(wFieldsName.getText()); meta.setCollection(wCollection.getText()); meta.setJsonFieldName(wJsonField.getText()); meta.setJsonQuery(wJsonQuery.getText()); meta.setOutputJson(wbOutputAsJson.getSelection()); meta.setQueryIsPipeline(wbQueryIsPipeline.getSelection()); meta.setExecuteForEachIncomingRow(wbExecuteForEachRow.getSelection()); int numNonEmpty = wFields.nrNonEmpty(); if (numNonEmpty > 0) { List<MongoField> outputFields = new ArrayList<>(); for (int i = 0; i < numNonEmpty; i++) { TableItem item = wFields.getNonEmpty(i); MongoField newField = new MongoField(); newField.fieldName = item.getText(1).trim(); newField.fieldPath = item.getText(2).trim(); newField.hopType = item.getText(3).trim(); if (!StringUtils.isEmpty(item.getText(4))) { newField.indexedValues = MongoDbInputData.indexedValsList(item.getText(4).trim()); } outputFields.add(newField); } meta.setMongoFields(outputFields); } } private void ok() { if (StringUtils.isEmpty(wTransformName.getText())) { return; } transformName = wTransformName.getText(); // return value getInfo(input); dispose(); } public boolean isTableDisposed() { return wFields.isDisposed(); } private void refreshFields( List<MongoField> fields) { if (fields == null) { return; } wFields.clearAll(); for (MongoField f : fields) { TableItem item = new TableItem(wFields.table, SWT.NONE); updateTableItem(item, f); } wFields.removeEmptyRows(); wFields.setRowNums(); wFields.optWidth(true); } public void updateFieldTableFields(List<MongoField> fields) { Map<String, MongoField> fieldMap = new HashMap<>(fields.size()); for (MongoField field : fields) { fieldMap.put(field.fieldName, field); } int index = 0; List<Integer> indicesToRemove = new ArrayList<>(); for (TableItem tableItem : wFields.getTable().getItems()) { String name = tableItem.getText(1); MongoField mongoField = fieldMap.remove(name); if (mongoField == null) { // Value does not exist in incoming fields list and exists in table, remove old value from // table indicesToRemove.add(index); } else { // Value exists in incoming fields list and in table, update entry updateTableItem(tableItem, mongoField); } index++; } int[] indicesArray = new int[indicesToRemove.size()]; for (int i = 0; i < indicesArray.length; i++) { indicesArray[i] = indicesToRemove.get(i); } for (MongoField mongoField : fieldMap.values()) { TableItem item = new TableItem(wFields.table, SWT.NONE); updateTableItem(item, mongoField); } wFields.setRowNums(); wFields.remove(indicesArray); wFields.removeEmptyRows(); wFields.setRowNums(); wFields.optWidth(true); } private void updateTableItem(TableItem tableItem, MongoField mongoField) { if (!StringUtils.isEmpty(mongoField.fieldName)) { tableItem.setText(1, mongoField.fieldName); } if (!StringUtils.isEmpty(mongoField.fieldPath)) { tableItem.setText(2, mongoField.fieldPath); } if (!StringUtils.isEmpty(mongoField.hopType)) { tableItem.setText(3, mongoField.hopType); } if (mongoField.indexedValues != null && mongoField.indexedValues.size() > 0) { tableItem.setText(4, MongoDbInputData.indexedValsList(mongoField.indexedValues)); } if (!StringUtils.isEmpty(mongoField.arrayIndexInfo)) { tableItem.setText(5, mongoField.arrayIndexInfo); } if (!StringUtils.isEmpty(mongoField.occurrenceFraction)) { tableItem.setText(6, mongoField.occurrenceFraction); } if (mongoField.disparateTypes) { tableItem.setText(7, "Y"); } } private boolean checkForUnresolved(MongoDbInputMeta meta, String title) { String query = variables.resolve(meta.getJsonQuery()); boolean notOk = (query.contains("${") || query.contains("?{")); if (notOk) { ShowMessageDialog smd = new ShowMessageDialog( shell, SWT.ICON_WARNING | SWT.OK, title, BaseMessages.getString( PKG, "MongoDbInputDialog.Warning.Message.MongoQueryContainsUnresolvedVarsFieldSubs")); smd.open(); } return !notOk; } // Used to catch exceptions from discoverFields calls that come through the callback public void handleNotificationException(Exception exception) { new ErrorDialog( shell, transformName, BaseMessages.getString(PKG, "MongoDbInputDialog.ErrorMessage.ErrorDuringSampling"), exception); } private void getFields(MongoDbInputMeta meta) { if (!StringUtils.isEmpty(wConnection.getText()) && !StringUtils.isEmpty(wCollection.getText())) { EnterNumberDialog end = new EnterNumberDialog( shell, 100, BaseMessages.getString(PKG, "MongoDbInputDialog.SampleDocuments.Title"), BaseMessages.getString(PKG, "MongoDbInputDialog.SampleDocuments.Message")); int samples = end.open(); if (samples > 0) { getInfo(meta); // Turn off execute for each incoming row (if set). // Query is still going to // be stuffed if the user has specified field replacement (i.e. // ?{...}) in the query string boolean current = meta.getExecuteForEachIncomingRow(); meta.setExecuteForEachIncomingRow(false); if (!checkForUnresolved( meta, BaseMessages.getString( PKG, "MongoDbInputDialog.Warning.Message.MongoQueryContainsUnresolvedVarsFieldSubs.SamplingTitle"))) { return; } try { discoverFields(meta, variables, samples, metadataProvider); meta.setExecuteForEachIncomingRow(current); refreshFields(meta.getMongoFields()); } catch (HopException e) { new ErrorDialog( shell, transformName, BaseMessages.getString(PKG, "MongoDbInputDialog.ErrorMessage.ErrorDuringSampling"), e); } } } else { // pop up an error dialog String missingConDetails = ""; if (StringUtils.isEmpty(wConnection.getText())) { missingConDetails += " connection name"; } if (StringUtils.isEmpty(wCollection.getText())) { missingConDetails += " collection"; } ShowMessageDialog smd = new ShowMessageDialog( shell, SWT.ICON_WARNING | SWT.OK, BaseMessages.getString( PKG, "MongoDbInputDialog.ErrorMessage.MissingConnectionDetails.Title"), BaseMessages.getString( PKG, "MongoDbInputDialog.ErrorMessage.MissingConnectionDetails", missingConDetails)); smd.open(); } } // Preview the data private void preview() { // Create the XML input transform MongoDbInputMeta oneMeta = new MongoDbInputMeta(); getInfo(oneMeta); // Turn off execute for each incoming row (if set). Query is still going to // be stuffed if the user has specified field replacement (i.e. ?{...}) in // the query string oneMeta.setExecuteForEachIncomingRow(false); if (!checkForUnresolved( oneMeta, BaseMessages.getString( PKG, "MongoDbInputDialog.Warning.Message.MongoQueryContainsUnresolvedVarsFieldSubs.PreviewTitle"))) { return; } PipelineMeta previewMeta = PipelinePreviewFactory.generatePreviewPipeline( metadataProvider, oneMeta, wTransformName.getText()); EnterNumberDialog numberDialog = new EnterNumberDialog( shell, props.getDefaultPreviewSize(), BaseMessages.getString(PKG, "MongoDbInputDialog.PreviewSize.DialogTitle"), BaseMessages.getString(PKG, "MongoDbInputDialog.PreviewSize.DialogMessage")); int previewSize = numberDialog.open(); if (previewSize > 0) { PipelinePreviewProgressDialog progressDialog = new PipelinePreviewProgressDialog( shell, variables, previewMeta, new String[] {wTransformName.getText()}, new int[] {previewSize}); progressDialog.open(); Pipeline pipeline = progressDialog.getPipeline(); String loggingText = progressDialog.getLoggingText(); if (!progressDialog.isCancelled()) { if (pipeline.getResult() != null && pipeline.getResult().getNrErrors() > 0) { EnterTextDialog etd = new EnterTextDialog( shell, BaseMessages.getString(PKG, "System.Dialog.PreviewError.Title"), BaseMessages.getString(PKG, "System.Dialog.PreviewError.Message"), loggingText, true); etd.setReadOnly(); etd.open(); } } PreviewRowsDialog prd = new PreviewRowsDialog( shell, variables, SWT.NONE, wTransformName.getText(), progressDialog.getPreviewRowsMeta(wTransformName.getText()), progressDialog.getPreviewRows(wTransformName.getText()), loggingText); prd.open(); } } private void getCollectionNames() { try { String connectionName = variables.resolve(wConnection.getText()); String current = wCollection.getText(); wCollection.removeAll(); MongoDbConnection connection = metadataProvider.getSerializer(MongoDbConnection.class).load(connectionName); String databaseName = variables.resolve(connection.getDbName()); if (!StringUtils.isEmpty(connectionName)) { final MongoDbInputMeta meta = new MongoDbInputMeta(); getInfo(meta); try { MongoClientWrapper wrapper = connection.createWrapper(variables, log); Set<String> collections; try { collections = wrapper.getCollectionsNames(databaseName); } finally { wrapper.dispose(); } for (String c : collections) { wCollection.add(c); } } catch (Exception e) { logError( BaseMessages.getString(PKG, "MongoDbInputDialog.ErrorMessage.UnableToConnect"), e); new ErrorDialog( shell, BaseMessages.getString(PKG, "MongoDbInputDialog.ErrorMessage.UnableToConnect"), BaseMessages.getString(PKG, "MongoDbInputDialog.ErrorMessage.UnableToConnect"), e); } } else { // popup some feedback String missingConnDetails = ""; if (StringUtils.isEmpty(connectionName)) { missingConnDetails += "connection name"; } ShowMessageDialog smd = new ShowMessageDialog( shell, SWT.ICON_WARNING | SWT.OK, BaseMessages.getString( PKG, "MongoDbInputDialog.ErrorMessage.MissingConnectionDetails.Title"), BaseMessages.getString( PKG, "MongoDbInputDialog.ErrorMessage.MissingConnectionDetails", missingConnDetails)); smd.open(); } if (!StringUtils.isEmpty(current)) { wCollection.setText(current); } } catch (Exception e) { new ErrorDialog(shell, "Error", "Error getting collections", e); } } public static boolean discoverFields( final MongoDbInputMeta meta, final IVariables variables, final int docsToSample, IHopMetadataProvider metadataProvider) throws HopException { String connectionName = variables.resolve(meta.getConnectionName()); try { MongoDbConnection connection = metadataProvider.getSerializer(MongoDbConnection.class).load(connectionName); if (connection == null) { throw new HopException("Unable to find connection " + connectionName); } String collection = variables.resolve(meta.getCollection()); String query = variables.resolve(meta.getJsonQuery()); String fields = variables.resolve(meta.getFieldsName()); int numDocsToSample = docsToSample; if (numDocsToSample < 1) { numDocsToSample = 100; // default } MongodbInputDiscoverFieldsImpl discoverFields = new MongodbInputDiscoverFieldsImpl(); List<MongoField> discoveredFields = discoverFields .discoverFields( variables, connection, collection, query, fields, meta.isQueryIsPipeline(), numDocsToSample, meta); // return true if query resulted in documents being returned and fields // getting extracted if (discoveredFields.size() > 0) { meta.setMongoFields(discoveredFields); return true; } } catch (Exception e) { if (e instanceof HopException) { throw (HopException) e; } else { throw new HopException("Unable to discover fields from MongoDB", e); } } return false; } }
35,640
0.675309
0.669781
982
35.293278
24.863037
113
false
false
0
0
0
0
0
0
0.849287
false
false
1
194b371aa350c88af3925a397a7658420f3e48f7
31,370,441,196,473
7122b8e82c021b0971149c655ecd7560aa445e28
/todo1-kardex/src/test/java/co/com/todo1/kardex/abstracts/ASvcTest.java
6b313a20fe67ac1315909ecb82d65e6743cbe925
[]
no_license
nano871022/Stefanini_todo1
https://github.com/nano871022/Stefanini_todo1
6d90eca7ee8c78d363f4376700fec64404682a84
a6d70290e2a9c8704bdc72251861c21ce2a12ce8
refs/heads/master
2022-04-30T06:31:39.678000
2020-02-27T03:20:45
2020-02-27T03:20:45
242,801,139
0
0
null
false
2022-03-31T19:02:37
2020-02-24T17:39:27
2020-02-27T03:20:48
2022-03-31T19:02:37
36,410
0
0
7
Java
false
false
package co.com.todo1.kardex.abstracts; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.boot.test.context.SpringBootTest; import co.com.todo1.kardex.pojo.MovementResponsePOJO; import co.com.todo1.kardex.pojo.ProductResponsePOJO; import co.com.todo1.utils.utils.I18n; @SpringBootTest public class ASvcTest { @Test public void testErrorReturnByException() { ASvc svc = Mockito.mock(ASvc.class); String errMessage = "Err call method"; Exception ex = new Exception(errMessage); Mockito.doCallRealMethod().when(svc).errorReturn(ex, ProductResponsePOJO.class); ProductResponsePOJO result = svc.errorReturn(ex, ProductResponsePOJO.class); assertEquals(errMessage,result.getStatus()); } @Test public void testErrorReturnByMessageString() { ASvc svc = Mockito.mock(ASvc.class); String errMessage = "Err call method"; Mockito.doCallRealMethod().when(svc).errorReturn(errMessage, MovementResponsePOJO.class); MovementResponsePOJO result = svc.errorReturn(errMessage, MovementResponsePOJO.class); assertEquals(errMessage,result.getStatus()); } @Test public void testI18n() { ASvc svc = Mockito.mock(ASvc.class); String messageOut = "mensaje test"; I18n i18n = Mockito.mock(I18n.class); Mockito.doReturn(i18n).when(svc).i18n(); Mockito.doReturn(messageOut).when(i18n).get(Mockito.any()); Mockito.doCallRealMethod().when(svc).i18n(Mockito.any()); String result = svc.i18n("err.message.test"); assertEquals(messageOut,result); Mockito.verify(i18n,Mockito.times(1)).get(Mockito.any()); Mockito.verify(svc,Mockito.times(1)).i18n(); } }
UTF-8
Java
1,710
java
ASvcTest.java
Java
[]
null
[]
package co.com.todo1.kardex.abstracts; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.boot.test.context.SpringBootTest; import co.com.todo1.kardex.pojo.MovementResponsePOJO; import co.com.todo1.kardex.pojo.ProductResponsePOJO; import co.com.todo1.utils.utils.I18n; @SpringBootTest public class ASvcTest { @Test public void testErrorReturnByException() { ASvc svc = Mockito.mock(ASvc.class); String errMessage = "Err call method"; Exception ex = new Exception(errMessage); Mockito.doCallRealMethod().when(svc).errorReturn(ex, ProductResponsePOJO.class); ProductResponsePOJO result = svc.errorReturn(ex, ProductResponsePOJO.class); assertEquals(errMessage,result.getStatus()); } @Test public void testErrorReturnByMessageString() { ASvc svc = Mockito.mock(ASvc.class); String errMessage = "Err call method"; Mockito.doCallRealMethod().when(svc).errorReturn(errMessage, MovementResponsePOJO.class); MovementResponsePOJO result = svc.errorReturn(errMessage, MovementResponsePOJO.class); assertEquals(errMessage,result.getStatus()); } @Test public void testI18n() { ASvc svc = Mockito.mock(ASvc.class); String messageOut = "mensaje test"; I18n i18n = Mockito.mock(I18n.class); Mockito.doReturn(i18n).when(svc).i18n(); Mockito.doReturn(messageOut).when(i18n).get(Mockito.any()); Mockito.doCallRealMethod().when(svc).i18n(Mockito.any()); String result = svc.i18n("err.message.test"); assertEquals(messageOut,result); Mockito.verify(i18n,Mockito.times(1)).get(Mockito.any()); Mockito.verify(svc,Mockito.times(1)).i18n(); } }
1,710
0.753801
0.736257
58
28.482759
26.003475
91
false
false
0
0
0
0
0
0
1.896552
false
false
1
31236f3219e865c33f2c8eacd91f3ca09c473b8b
18,270,790,944,323
8be3384c85f9eb401a76ef65a00b5cda1cc16002
/app/src/main/java/com/yulia/milich/chess/TheChessGame.java
28497752aed7f91970ec7623bc8d4a2a3c04638e
[]
no_license
yuliamilich/android_chess_game
https://github.com/yuliamilich/android_chess_game
af3409ca394f899ec7a5102bcbebe100c00da9cd
02b5fa53654330bdfda49850f1ceaeb2fb04df5d
refs/heads/master
2020-04-03T02:05:12.743000
2019-06-02T18:16:23
2019-06-02T18:16:23
154,946,545
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yulia.milich.chess; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Layout; import android.util.TypedValue; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; public class TheChessGame extends AppCompatActivity implements View.OnClickListener { private ImageButton board[][] = new ImageButton[8][8]; private ChessManager cM; private ImageView[][] fallenFiguresWhite = new ImageView[2][8]; private ImageView[][] fallenFiguresBlack = new ImageView[2][8]; private TextView whiteWon, blackWon; private TextView whiteTurn, blackTurn; private TextView checkBlack, checkWhite; private String whiteName, blackName; private String promotionFigure = "queen"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_the_chess_game); whiteName = (String) getIntent().getStringExtra("playerWhiteStr"); blackName = (String) getIntent().getStringExtra("playerBlackStr"); whiteWon = (TextView) findViewById(R.id.whiteWon); blackWon = (TextView) findViewById(R.id.blackWon); blackTurn = (TextView) findViewById(R.id.waitOrMoveBlack); whiteTurn = (TextView) findViewById(R.id.waitOrMoveWhite); checkBlack = (TextView) findViewById(R.id.checkBlack); checkWhite = (TextView) findViewById(R.id.checkWhite); cM = new ChessManager(this); cM.users = new DBUsers(this); cM.sqdb = cM.users.getWritableDatabase(); createScrollingListsForFallen(); createBoard(); cM.setBeginningBoard(); // placing the figures in the right place for the beginning of the game ImageButton restart = (ImageButton) findViewById(R.id.restart); restart.setOnClickListener(this); ImageButton restart2 = (ImageButton) findViewById(R.id.restart2); restart2.setOnClickListener(this); } public void onClick(View v) { switch (v.getId()) { case R.id.restart: cM.setBeginningBoard(); break; case R.id.restart2: cM.setBeginningBoard(); break; case 1000: promotionFigure = "bishop"; //promotionFigureChosen = true; break; case 2000: promotionFigure = "knight"; break; case 3000: promotionFigure = "queen"; break; case 4000: promotionFigure = "rook"; break; default: cM.click(v.getId()); } } public ImageButton[][] getBoard() { return board; } public ImageView[][] getFallenFiguresBlack() { return fallenFiguresBlack; } public ImageView[][] getFallenFiguresWhite() { return fallenFiguresWhite; } public TextView getBlackWon() { return blackWon; } public TextView getWhiteWon() { return whiteWon; } public TextView getCheckBlack() { return checkBlack; } public TextView getCheckWhite() { return checkWhite; } public TextView getBlackTurn() { return blackTurn; } public TextView getWhiteTurn() { return whiteTurn; } public String getBlackName() { return blackName; } public String getWhiteName() { return whiteName; } public String getPromotionFigure() { return promotionFigure; } public void createBoard() { TableLayout l1 = (TableLayout) findViewById(R.id.chessBoard); TableRow rows[] = new TableRow[8]; int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 35, getResources().getDisplayMetrics()); int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 35, getResources().getDisplayMetrics()); for (int i = 0; i < 8; i++) { rows[i] = new TableRow(this); // creating the rows in the TableLayout for (int j = 0; j < 8; j++) { board[i][j] = new ImageButton(this); // creating the button and setting an id board[i][j].setId(i * 10 + j); board[i][j].setTag(""); // setting a tag - the tag represents the figure that is placed on the button board[i][j].setLayoutParams(new TableRow.LayoutParams(width, height)); // setting the size of the button board[i][j].setScaleType(ImageView.ScaleType.CENTER_CROP); // that way the image on the button is in the right size board[i][j].setOnClickListener(this); rows[i].addView(board[i][j]); } l1.addView(rows[i]); } cM.clearBoardBackground(); cM.setBeginningBoard(); cM.reset(); } public void createScrollingListsForFallen() { TableLayout fallenBlack = (TableLayout) findViewById(R.id.fallenBlack); TableLayout fallenWhite = (TableLayout) findViewById(R.id.fallenWhite); TableRow rowWhite[] = new TableRow[2]; TableRow rowBlack[] = new TableRow[2]; int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 35, getResources().getDisplayMetrics()); int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 35, getResources().getDisplayMetrics()); for (int i = 0; i < 2; i++) { rowWhite[i] = new TableRow(this); rowBlack[i] = new TableRow(this); for (int j = 0; j < 8; j++) { this.fallenFiguresWhite[i][j] = new ImageView(this); this.fallenFiguresBlack[i][j] = new ImageView(this); //i don't think this is useful this.fallenFiguresWhite[i][j].setId(100 + i * 10 + j); this.fallenFiguresBlack[i][j].setId(200 + i * 10 + j); this.fallenFiguresWhite[i][j].setScaleType(ImageView.ScaleType.CENTER_CROP); this.fallenFiguresBlack[i][j].setScaleType(ImageView.ScaleType.CENTER_CROP); this.fallenFiguresWhite[i][j].setLayoutParams(new TableRow.LayoutParams(width, height)); this.fallenFiguresBlack[i][j].setLayoutParams(new TableRow.LayoutParams(width, height)); rowWhite[i].addView(this.fallenFiguresWhite[i][j]); rowBlack[i].addView(this.fallenFiguresBlack[i][j]); } fallenWhite.addView(rowWhite[i]); fallenBlack.addView(rowBlack[i]); } } public void winner(String title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(TheChessGame.this); builder.setCancelable(true); builder.setTitle(title); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setMessage(message); builder.show(); } public void promotion(final String color, final int position) { ImageView[] images = new ImageView[4]; AlertDialog.Builder builder = new AlertDialog.Builder(TheChessGame.this); builder.setCancelable(true); builder.setTitle("pick a figure"); for (int i = 0; i < images.length; i++) { images[i] = new ImageView(this); } if (color.equals("black")) { images[0].setImageResource(R.mipmap.bishop_black); images[1].setImageResource(R.mipmap.knight_black); images[2].setImageResource(R.mipmap.queen_black); images[3].setImageResource(R.mipmap.rook_black); } else { images[0].setImageResource(R.mipmap.bishop_white); images[1].setImageResource(R.mipmap.knight_white); images[2].setImageResource(R.mipmap.queen_white); images[3].setImageResource(R.mipmap.rook_white); } TableLayout tl = new TableLayout(this); TableRow tr = new TableRow(this); for (int i = 0; i < images.length; i++) { images[i].setId((i + 1) * 1000); images[i].setOnClickListener(this); tr.addView(images[i]); } tl.addView(tr); builder.setMessage("choose a figure"); builder.setView(tl); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { cM.promotionPartTwo(color, position); dialog.cancel(); } }); builder.show(); } //menu @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_all, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { //when selcting option in the menu // main --> go to menu //music --> stop/play music //instraction --> go to instraction // call --> go to phone call int id = item.getItemId(); Intent intent = null; switch (id) { case R.id.music: if (MainMenu.isPlaying) MainMenu.musicService.pause(); else MainMenu.musicService.resume(); MainMenu.isPlaying = !MainMenu.isPlaying; break; case R.id.manu_main: intent = new Intent(this, MainMenu.class); startActivity(intent); finish(); break; case R.id.call: intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "")); startActivity(intent); break; case R.id.exit: finish(); //System.exit(0); break; } return true; } }
UTF-8
Java
10,631
java
TheChessGame.java
Java
[]
null
[]
package com.yulia.milich.chess; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Layout; import android.util.TypedValue; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; public class TheChessGame extends AppCompatActivity implements View.OnClickListener { private ImageButton board[][] = new ImageButton[8][8]; private ChessManager cM; private ImageView[][] fallenFiguresWhite = new ImageView[2][8]; private ImageView[][] fallenFiguresBlack = new ImageView[2][8]; private TextView whiteWon, blackWon; private TextView whiteTurn, blackTurn; private TextView checkBlack, checkWhite; private String whiteName, blackName; private String promotionFigure = "queen"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_the_chess_game); whiteName = (String) getIntent().getStringExtra("playerWhiteStr"); blackName = (String) getIntent().getStringExtra("playerBlackStr"); whiteWon = (TextView) findViewById(R.id.whiteWon); blackWon = (TextView) findViewById(R.id.blackWon); blackTurn = (TextView) findViewById(R.id.waitOrMoveBlack); whiteTurn = (TextView) findViewById(R.id.waitOrMoveWhite); checkBlack = (TextView) findViewById(R.id.checkBlack); checkWhite = (TextView) findViewById(R.id.checkWhite); cM = new ChessManager(this); cM.users = new DBUsers(this); cM.sqdb = cM.users.getWritableDatabase(); createScrollingListsForFallen(); createBoard(); cM.setBeginningBoard(); // placing the figures in the right place for the beginning of the game ImageButton restart = (ImageButton) findViewById(R.id.restart); restart.setOnClickListener(this); ImageButton restart2 = (ImageButton) findViewById(R.id.restart2); restart2.setOnClickListener(this); } public void onClick(View v) { switch (v.getId()) { case R.id.restart: cM.setBeginningBoard(); break; case R.id.restart2: cM.setBeginningBoard(); break; case 1000: promotionFigure = "bishop"; //promotionFigureChosen = true; break; case 2000: promotionFigure = "knight"; break; case 3000: promotionFigure = "queen"; break; case 4000: promotionFigure = "rook"; break; default: cM.click(v.getId()); } } public ImageButton[][] getBoard() { return board; } public ImageView[][] getFallenFiguresBlack() { return fallenFiguresBlack; } public ImageView[][] getFallenFiguresWhite() { return fallenFiguresWhite; } public TextView getBlackWon() { return blackWon; } public TextView getWhiteWon() { return whiteWon; } public TextView getCheckBlack() { return checkBlack; } public TextView getCheckWhite() { return checkWhite; } public TextView getBlackTurn() { return blackTurn; } public TextView getWhiteTurn() { return whiteTurn; } public String getBlackName() { return blackName; } public String getWhiteName() { return whiteName; } public String getPromotionFigure() { return promotionFigure; } public void createBoard() { TableLayout l1 = (TableLayout) findViewById(R.id.chessBoard); TableRow rows[] = new TableRow[8]; int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 35, getResources().getDisplayMetrics()); int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 35, getResources().getDisplayMetrics()); for (int i = 0; i < 8; i++) { rows[i] = new TableRow(this); // creating the rows in the TableLayout for (int j = 0; j < 8; j++) { board[i][j] = new ImageButton(this); // creating the button and setting an id board[i][j].setId(i * 10 + j); board[i][j].setTag(""); // setting a tag - the tag represents the figure that is placed on the button board[i][j].setLayoutParams(new TableRow.LayoutParams(width, height)); // setting the size of the button board[i][j].setScaleType(ImageView.ScaleType.CENTER_CROP); // that way the image on the button is in the right size board[i][j].setOnClickListener(this); rows[i].addView(board[i][j]); } l1.addView(rows[i]); } cM.clearBoardBackground(); cM.setBeginningBoard(); cM.reset(); } public void createScrollingListsForFallen() { TableLayout fallenBlack = (TableLayout) findViewById(R.id.fallenBlack); TableLayout fallenWhite = (TableLayout) findViewById(R.id.fallenWhite); TableRow rowWhite[] = new TableRow[2]; TableRow rowBlack[] = new TableRow[2]; int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 35, getResources().getDisplayMetrics()); int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 35, getResources().getDisplayMetrics()); for (int i = 0; i < 2; i++) { rowWhite[i] = new TableRow(this); rowBlack[i] = new TableRow(this); for (int j = 0; j < 8; j++) { this.fallenFiguresWhite[i][j] = new ImageView(this); this.fallenFiguresBlack[i][j] = new ImageView(this); //i don't think this is useful this.fallenFiguresWhite[i][j].setId(100 + i * 10 + j); this.fallenFiguresBlack[i][j].setId(200 + i * 10 + j); this.fallenFiguresWhite[i][j].setScaleType(ImageView.ScaleType.CENTER_CROP); this.fallenFiguresBlack[i][j].setScaleType(ImageView.ScaleType.CENTER_CROP); this.fallenFiguresWhite[i][j].setLayoutParams(new TableRow.LayoutParams(width, height)); this.fallenFiguresBlack[i][j].setLayoutParams(new TableRow.LayoutParams(width, height)); rowWhite[i].addView(this.fallenFiguresWhite[i][j]); rowBlack[i].addView(this.fallenFiguresBlack[i][j]); } fallenWhite.addView(rowWhite[i]); fallenBlack.addView(rowBlack[i]); } } public void winner(String title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(TheChessGame.this); builder.setCancelable(true); builder.setTitle(title); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setMessage(message); builder.show(); } public void promotion(final String color, final int position) { ImageView[] images = new ImageView[4]; AlertDialog.Builder builder = new AlertDialog.Builder(TheChessGame.this); builder.setCancelable(true); builder.setTitle("pick a figure"); for (int i = 0; i < images.length; i++) { images[i] = new ImageView(this); } if (color.equals("black")) { images[0].setImageResource(R.mipmap.bishop_black); images[1].setImageResource(R.mipmap.knight_black); images[2].setImageResource(R.mipmap.queen_black); images[3].setImageResource(R.mipmap.rook_black); } else { images[0].setImageResource(R.mipmap.bishop_white); images[1].setImageResource(R.mipmap.knight_white); images[2].setImageResource(R.mipmap.queen_white); images[3].setImageResource(R.mipmap.rook_white); } TableLayout tl = new TableLayout(this); TableRow tr = new TableRow(this); for (int i = 0; i < images.length; i++) { images[i].setId((i + 1) * 1000); images[i].setOnClickListener(this); tr.addView(images[i]); } tl.addView(tr); builder.setMessage("choose a figure"); builder.setView(tl); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { cM.promotionPartTwo(color, position); dialog.cancel(); } }); builder.show(); } //menu @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_all, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { //when selcting option in the menu // main --> go to menu //music --> stop/play music //instraction --> go to instraction // call --> go to phone call int id = item.getItemId(); Intent intent = null; switch (id) { case R.id.music: if (MainMenu.isPlaying) MainMenu.musicService.pause(); else MainMenu.musicService.resume(); MainMenu.isPlaying = !MainMenu.isPlaying; break; case R.id.manu_main: intent = new Intent(this, MainMenu.class); startActivity(intent); finish(); break; case R.id.call: intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "")); startActivity(intent); break; case R.id.exit: finish(); //System.exit(0); break; } return true; } }
10,631
0.600132
0.592795
316
32.642406
27.847265
131
false
false
0
0
0
0
0
0
0.639241
false
false
1
2a536e5d432dc1df245fa70a06f1553245bdcfec
18,330,920,476,831
3ae5e9d5ef90a35b9e5cd72eb786f7544837ba8a
/18_listview显示复杂页面/src/com/cmcc/listview2/MainActivity.java
41c4a3400672055fa7ce1139ab8a093fd3c397a8
[ "MIT" ]
permissive
scoldfield/android
https://github.com/scoldfield/android
36b08c821cf13f56d925153859c061c95962b809
bd8b7bf2a5e4f264e611bf4184c4cb3ffa89361c
refs/heads/master
2021-01-20T22:18:57.946000
2016-07-18T01:16:18
2016-07-18T01:16:18
63,559,931
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cmcc.listview2; import java.util.zip.Inflater; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //[1]获取我们需要的控件 ListView lv = (ListView) findViewById(R.id.lv); //[3]为ListView设置adapter lv.setAdapter(new MyAdapter()); } //[2]定义listview的数据适配器 //只需要实现getCount()和getView()两个方法即可 class MyAdapter extends BaseAdapter{ @Override public int getCount() { return 6; //显示6条新闻 } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { /* * 新闻布局中即有文本部分,也有图片部分,分别需要TextView和ImageView两个View来实现, * 而getView()方法中只能返回一个View,因此我们通过将这两个View放到一个layout布局中, * 然后将这个layout布局转换成View返回即可。 * 这个布局的名字开发中一般起名为item,放在layout文件夹中 */ //[1]想办法把我们定义的layout布局item转变成一个View对象 View view; if(convertView == null) { /* * [2]inflate()方法,俗称打气筒,可以把布局layout资源转换成一个view对象 * resource是我们自定义的布局文件 * root 是view的viewGroup,现阶段不使用 */ //获取打气筒的方法一: // view = View.inflate(getApplicationContext(), R.layout.item, null); //获取打气筒的方法二: // view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, null); //获取打气筒的方法三: LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.item, null); }else { //复用历史缓存对象convertView view = convertView; } return view; } } }
GB18030
Java
3,008
java
MainActivity.java
Java
[]
null
[]
package com.cmcc.listview2; import java.util.zip.Inflater; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //[1]获取我们需要的控件 ListView lv = (ListView) findViewById(R.id.lv); //[3]为ListView设置adapter lv.setAdapter(new MyAdapter()); } //[2]定义listview的数据适配器 //只需要实现getCount()和getView()两个方法即可 class MyAdapter extends BaseAdapter{ @Override public int getCount() { return 6; //显示6条新闻 } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { /* * 新闻布局中即有文本部分,也有图片部分,分别需要TextView和ImageView两个View来实现, * 而getView()方法中只能返回一个View,因此我们通过将这两个View放到一个layout布局中, * 然后将这个layout布局转换成View返回即可。 * 这个布局的名字开发中一般起名为item,放在layout文件夹中 */ //[1]想办法把我们定义的layout布局item转变成一个View对象 View view; if(convertView == null) { /* * [2]inflate()方法,俗称打气筒,可以把布局layout资源转换成一个view对象 * resource是我们自定义的布局文件 * root 是view的viewGroup,现阶段不使用 */ //获取打气筒的方法一: // view = View.inflate(getApplicationContext(), R.layout.item, null); //获取打气筒的方法二: // view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, null); //获取打气筒的方法三: LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.item, null); }else { //复用历史缓存对象convertView view = convertView; } return view; } } }
3,008
0.542453
0.538915
85
27.929411
21.929184
101
false
false
0
0
0
0
0
0
0.364706
false
false
1
b9b00ce1e71709aeaa69a56c342309a31ff83a3e
33,569,464,394,321
0ddc847a483dddfe96e5d4b088edeb8191708bd1
/de.egladil.mkm.service/src/main/java/de/egladil/mkm/service/validation/PropertiesFieldNamesMapper.java
acd770e6f4d8b3485e49feda51b8dd27b26de92d
[]
no_license
heike2718/de.egladil.mkmanufaktur
https://github.com/heike2718/de.egladil.mkmanufaktur
652542f9d43a7450366eb685d57eeb75c5b1ed83
64c9b81560c1c76491fcfeba5f43acf3bfe4ccb4
refs/heads/master
2017-04-03T02:32:59.417000
2017-01-29T06:18:54
2017-01-29T06:18:54
57,961,673
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//===================================================== // Projekt: de.egladil.mkm.service // (c) Heike Winkelvoß //===================================================== package de.egladil.mkm.service.validation; import java.util.HashMap; import java.util.Map; /** * PropertiesFieldNamesMapper */ public class PropertiesFieldNamesMapper { /** * Erzeugt eine Instanz von PropertiesFieldNamesMapper */ public PropertiesFieldNamesMapper() { // TODO Generierter Code } public static Map<String, String> getFieldnameMapForCredentials() { Map<String, String> result = new HashMap<>(); result.put("username", "username"); result.put("password", "password"); return result; } public static Map<String, String> getLabelMapForCredentials() { Map<String, String> result = new HashMap<>(); result.put("username", "Benutzername"); result.put("password", "Passwort"); return result; } }
UTF-8
Java
913
java
PropertiesFieldNamesMapper.java
Java
[ { "context": "========\n// Projekt: de.egladil.mkm.service\n// (c) Heike Winkelvoß\n//===============================================", "end": 113, "score": 0.9998671412467957, "start": 98, "tag": "NAME", "value": "Heike Winkelvoß" }, { "context": "sult = new HashMap<>();\n\t\tresult.put(\"username\", \"username\");\n\t\tresult.put(\"password\", \"password\");\n\t\treturn", "end": 633, "score": 0.9990931749343872, "start": 625, "tag": "USERNAME", "value": "username" }, { "context": "username\", \"username\");\n\t\tresult.put(\"password\", \"password\");\n\t\treturn result;\n\t}\n\n\tpublic static Map<String", "end": 671, "score": 0.9992300271987915, "start": 663, "tag": "PASSWORD", "value": "password" }, { "context": "sult = new HashMap<>();\n\t\tresult.put(\"username\", \"Benutzername\");\n\t\tresult.put(\"password\", \"Passwort\");\n\t\treturn", "end": 847, "score": 0.999232828617096, "start": 835, "tag": "USERNAME", "value": "Benutzername" }, { "context": "name\", \"Benutzername\");\n\t\tresult.put(\"password\", \"Passwort\");\n\t\treturn result;\n\t}\n\n}\n", "end": 885, "score": 0.996220052242279, "start": 877, "tag": "PASSWORD", "value": "Passwort" } ]
null
[]
//===================================================== // Projekt: de.egladil.mkm.service // (c) <NAME> //===================================================== package de.egladil.mkm.service.validation; import java.util.HashMap; import java.util.Map; /** * PropertiesFieldNamesMapper */ public class PropertiesFieldNamesMapper { /** * Erzeugt eine Instanz von PropertiesFieldNamesMapper */ public PropertiesFieldNamesMapper() { // TODO Generierter Code } public static Map<String, String> getFieldnameMapForCredentials() { Map<String, String> result = new HashMap<>(); result.put("username", "username"); result.put("password", "<PASSWORD>"); return result; } public static Map<String, String> getLabelMapForCredentials() { Map<String, String> result = new HashMap<>(); result.put("username", "Benutzername"); result.put("password", "<PASSWORD>"); return result; } }
907
0.629386
0.629386
38
23
21.512543
68
false
false
0
0
0
0
65
0.071272
1.210526
false
false
1
f2df916568c9ab431a882f95c25fd78c77c628ae
16,630,113,384,124
3055ff039310f7fd1cb28c405e8659fe4b579410
/apac/core/amwaydamintegration/src/com/amway/integration/dam/service/impl/AmwayDamEventQueueServiceImpl.java
6c83e3cdbd36d7df45095bad695d2a6f75525ccb
[]
no_license
AmwayKOR/lynx-korea
https://github.com/AmwayKOR/lynx-korea
93222f5a3138a972fbcafec40ae6aaa6a1005b3d
cef1c32f6bf5718fdf9294e12e188decd2269476
refs/heads/master
2021-04-27T16:50:18.440000
2018-02-21T07:41:35
2018-02-21T07:41:35
122,305,108
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amway.integration.dam.service.impl; import static com.amway.integration.dam.constants.AmwayDamConstants.DEFAULT_LIMIT; import de.hybris.platform.servicelayer.dto.converter.Converter; import de.hybris.platform.servicelayer.model.ModelService; import java.util.List; import java.util.function.Predicate; import org.springframework.beans.factory.annotation.Autowired; import com.amway.integration.dam.dao.AmwayDamQueueDao; import com.amway.integration.dam.data.AmwayDamEventData; import com.amway.integration.dam.model.AmwayDamQueueEntryModel; import com.amway.integration.dam.service.AmwayDamQueueService; import com.amway.core.annotations.AmwayBean; @AmwayBean(ext="amwaydamintegration",docs="https://jira.amway.com:8444/display/HC/amwaydamintegration") public class AmwayDamEventQueueServiceImpl implements AmwayDamQueueService { @Autowired private ModelService modelService; @Autowired private AmwayDamQueueDao amwayDamQueueDao; @Autowired private Predicate<AmwayDamEventData> amwayDamEventDataPredicate; @Autowired private Converter<AmwayDamEventData, AmwayDamQueueEntryModel> amwayDamQueueEntryReverseConverter; @Override public void registerEvents(List<AmwayDamEventData> events) { //@formatter:off events.stream() .filter(amwayDamEventDataPredicate) .forEach(this::createDamEventModel); //@formatter:on } @Override public List<AmwayDamQueueEntryModel> getEvents(Integer limit) { int count = (limit == null) ? DEFAULT_LIMIT : limit; return amwayDamQueueDao.findEvents(count); } private void createDamEventModel(AmwayDamEventData eventData) { AmwayDamQueueEntryModel eventModel = modelService.create(AmwayDamQueueEntryModel.class); amwayDamQueueEntryReverseConverter.convert(eventData, eventModel); modelService.save(eventModel); } }
UTF-8
Java
1,801
java
AmwayDamEventQueueServiceImpl.java
Java
[]
null
[]
package com.amway.integration.dam.service.impl; import static com.amway.integration.dam.constants.AmwayDamConstants.DEFAULT_LIMIT; import de.hybris.platform.servicelayer.dto.converter.Converter; import de.hybris.platform.servicelayer.model.ModelService; import java.util.List; import java.util.function.Predicate; import org.springframework.beans.factory.annotation.Autowired; import com.amway.integration.dam.dao.AmwayDamQueueDao; import com.amway.integration.dam.data.AmwayDamEventData; import com.amway.integration.dam.model.AmwayDamQueueEntryModel; import com.amway.integration.dam.service.AmwayDamQueueService; import com.amway.core.annotations.AmwayBean; @AmwayBean(ext="amwaydamintegration",docs="https://jira.amway.com:8444/display/HC/amwaydamintegration") public class AmwayDamEventQueueServiceImpl implements AmwayDamQueueService { @Autowired private ModelService modelService; @Autowired private AmwayDamQueueDao amwayDamQueueDao; @Autowired private Predicate<AmwayDamEventData> amwayDamEventDataPredicate; @Autowired private Converter<AmwayDamEventData, AmwayDamQueueEntryModel> amwayDamQueueEntryReverseConverter; @Override public void registerEvents(List<AmwayDamEventData> events) { //@formatter:off events.stream() .filter(amwayDamEventDataPredicate) .forEach(this::createDamEventModel); //@formatter:on } @Override public List<AmwayDamQueueEntryModel> getEvents(Integer limit) { int count = (limit == null) ? DEFAULT_LIMIT : limit; return amwayDamQueueDao.findEvents(count); } private void createDamEventModel(AmwayDamEventData eventData) { AmwayDamQueueEntryModel eventModel = modelService.create(AmwayDamQueueEntryModel.class); amwayDamQueueEntryReverseConverter.convert(eventData, eventModel); modelService.save(eventModel); } }
1,801
0.825097
0.822876
54
32.351852
30.019226
103
false
false
0
0
0
0
0
0
1.259259
false
false
1
e8cdaf79eaaa197f4c9c035535545afbed792367
21,105,469,296,982
b69b973337fc3b69a587a686690fa3206db38af0
/NoSQL basic,fundamentals - Morning/spring-boot-couchbase-example/spring-boot-couchbase-example/src/main/java/com/example/au/couchbasedemo/repository/BlogRepository.java
86c88783d998d4e688004fa2b00b026f595bf8c3
[]
no_license
adityalath-accolite/SAU-2021-Jan-Batch-Bangalore
https://github.com/adityalath-accolite/SAU-2021-Jan-Batch-Bangalore
65bb177418a788a9e19050154b4954e928c9712c
9f91fd142043b02cc0f67dadb7ccd245ce171d49
refs/heads/main
2023-03-16T03:39:49.281000
2021-02-03T17:03:02
2021-02-03T17:03:02
327,599,446
1
0
null
true
2021-01-07T12:03:07
2021-01-07T12:02:52
2021-01-06T12:26:15
2021-01-06T10:55:09
2
0
0
0
null
false
false
package com.example.au.couchbasedemo.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.example.au.couchbasedemo.model.Blogs; public interface BlogRepository extends CrudRepository<Blogs, String> { Blogs findByAuthor(String author); List<Blogs> deleteBytopicAndAuthor(String title, String author); //Blogs getByTags(List<String> tags); }
UTF-8
Java
408
java
BlogRepository.java
Java
[]
null
[]
package com.example.au.couchbasedemo.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.example.au.couchbasedemo.model.Blogs; public interface BlogRepository extends CrudRepository<Blogs, String> { Blogs findByAuthor(String author); List<Blogs> deleteBytopicAndAuthor(String title, String author); //Blogs getByTags(List<String> tags); }
408
0.796569
0.796569
17
23.058823
25.862694
71
false
false
0
0
0
0
0
0
0.882353
false
false
1
df238298bfd6580b2d4af432ef1686663cf44520
25,933,012,584,103
219ed5c622f0656d1da3e9004c8b066d2c1c40dd
/Dawai/app/src/main/java/com/example/rbf/dawa_i/Page1.java
a5c2f535659b22d2dd1bd8bb60fdfa6d2383ac94
[]
no_license
Ramzi98/Dawai
https://github.com/Ramzi98/Dawai
ab0ed4f68875a49425ce960f17874033fc7e6ebf
42050f491fb530626a88c62459ec30362c49e076
refs/heads/master
2021-08-18T18:15:22.559000
2020-10-02T14:05:05
2020-10-02T14:05:05
227,090,253
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.rbf.dawa_i; import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton; import com.oguzdev.circularfloatingactionmenu.library.FloatingActionMenu; import com.oguzdev.circularfloatingactionmenu.library.SubActionButton; /** * Created by ramzi on 09/03/18. */ public class Page1 extends AppCompatActivity { private DrawerLayout mDrawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_2); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); final ActionBar actionbar = getSupportActionBar(); actionbar.setDisplayHomeAsUpEnabled(true); actionbar.setHomeAsUpIndicator(R.drawable.ic_menu); mDrawerLayout = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { // set item as selected to persist highlight //menuItem.setChecked(true); // close drawer when item is tapped mDrawerLayout.closeDrawers(); switch (menuItem.getItemId()) { case R.id.profil: Toast.makeText(Page1.this,"Profil Button clicked",Toast.LENGTH_SHORT).show(); return true; case R.id.aj_medic: Intent intent1= new Intent(Page1.this,Add_medicaments.class); startActivity(intent1); return true; case R.id.aj_mes: Intent intent3= new Intent(Page1.this,Add_mesure.class); startActivity(intent3); return true; case R.id.mod_tra: Toast.makeText(Page1.this,"Modifier Traitment Button clicked",Toast.LENGTH_SHORT).show(); return true; case R.id.list_medic: Intent intent4= new Intent(Page1.this,List_medic.class); startActivity(intent4); return true; case R.id.list_mesure: Toast.makeText(Page1.this,"List Mesure Button clicked",Toast.LENGTH_SHORT).show(); return true; case R.id.medecins: Toast.makeText(Page1.this,"Medcins Button clicked",Toast.LENGTH_SHORT).show(); return true; case R.id.rdv: Toast.makeText(Page1.this,"RDV Button clicked",Toast.LENGTH_SHORT).show(); return true; case R.id.parametre: Toast.makeText(Page1.this,"Paramatre Button clicked",Toast.LENGTH_SHORT).show(); Intent intent2= new Intent(Page1.this,Setting.class); startActivity(intent2); return true; case R.id.apropos: Toast.makeText(Page1.this,"A Propos Button clicked",Toast.LENGTH_SHORT).show(); return true; } // Add code here to update the UI based on the item selected // For example, swap UI fragments here return true; } }); mDrawerLayout.addDrawerListener( new DrawerLayout.DrawerListener() { @Override public void onDrawerSlide(View drawerView, float slideOffset) { // Respond when the drawer's position changes } @Override public void onDrawerOpened(View drawerView) { // Respond when the drawer is opened } @Override public void onDrawerClosed(View drawerView) { // Respond when the drawer is closed } @Override public void onDrawerStateChanged(int newState) { // Respond when the drawer motion state changes } } ); //// --------------------------------------Floating button -----------------------------------------------------///// ImageView icon = new ImageView(this); // Create an icon icon.setImageResource(R.drawable.add_btn2); FloatingActionButton actionButton = new FloatingActionButton.Builder(this) .setContentView(icon) .build(); SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this); ImageView itemIcon1 = new ImageView(this); itemIcon1.setImageResource(R.drawable.ic_edit_black_24dp); SubActionButton button1 = itemBuilder.setContentView(itemIcon1).build(); ImageView itemIcon2 = new ImageView(this); itemIcon2.setImageResource(R.drawable.add_btn2); SubActionButton button2 = itemBuilder.setContentView(itemIcon2).build(); ImageView itemIcon3 = new ImageView(this); itemIcon3.setImageResource(R.drawable.ic_list_black_24dp); SubActionButton button3 = itemBuilder.setContentView(itemIcon3).build(); final FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(this) .addSubActionView(button1) .addSubActionView(button2) .addSubActionView(button3) .attachTo(actionButton) .build(); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(Page1.this,"button1 clicked",Toast.LENGTH_SHORT).show(); actionMenu.close(true); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(Page1.this,"button2 clicked",Toast.LENGTH_SHORT).show(); actionMenu.close(true); Intent intent1= new Intent(Page1.this,Add_medicaments.class); startActivity(intent1); } }); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(Page1.this,"button3 clicked",Toast.LENGTH_SHORT).show(); actionMenu.close(true); } }); //// --------------------------------------Floatin button -----------------------------------------------------///// } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mDrawerLayout.openDrawer(GravityCompat.START); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { finish(); } }
UTF-8
Java
8,284
java
Page1.java
Java
[ { "context": "nmenu.library.SubActionButton;\n\n\n/**\n * Created by ramzi on 09/03/18.\n */\n\npublic class Page1 extends AppC", "end": 803, "score": 0.999578595161438, "start": 798, "tag": "USERNAME", "value": "ramzi" } ]
null
[]
package com.example.rbf.dawa_i; import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton; import com.oguzdev.circularfloatingactionmenu.library.FloatingActionMenu; import com.oguzdev.circularfloatingactionmenu.library.SubActionButton; /** * Created by ramzi on 09/03/18. */ public class Page1 extends AppCompatActivity { private DrawerLayout mDrawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_2); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); final ActionBar actionbar = getSupportActionBar(); actionbar.setDisplayHomeAsUpEnabled(true); actionbar.setHomeAsUpIndicator(R.drawable.ic_menu); mDrawerLayout = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { // set item as selected to persist highlight //menuItem.setChecked(true); // close drawer when item is tapped mDrawerLayout.closeDrawers(); switch (menuItem.getItemId()) { case R.id.profil: Toast.makeText(Page1.this,"Profil Button clicked",Toast.LENGTH_SHORT).show(); return true; case R.id.aj_medic: Intent intent1= new Intent(Page1.this,Add_medicaments.class); startActivity(intent1); return true; case R.id.aj_mes: Intent intent3= new Intent(Page1.this,Add_mesure.class); startActivity(intent3); return true; case R.id.mod_tra: Toast.makeText(Page1.this,"Modifier Traitment Button clicked",Toast.LENGTH_SHORT).show(); return true; case R.id.list_medic: Intent intent4= new Intent(Page1.this,List_medic.class); startActivity(intent4); return true; case R.id.list_mesure: Toast.makeText(Page1.this,"List Mesure Button clicked",Toast.LENGTH_SHORT).show(); return true; case R.id.medecins: Toast.makeText(Page1.this,"Medcins Button clicked",Toast.LENGTH_SHORT).show(); return true; case R.id.rdv: Toast.makeText(Page1.this,"RDV Button clicked",Toast.LENGTH_SHORT).show(); return true; case R.id.parametre: Toast.makeText(Page1.this,"Paramatre Button clicked",Toast.LENGTH_SHORT).show(); Intent intent2= new Intent(Page1.this,Setting.class); startActivity(intent2); return true; case R.id.apropos: Toast.makeText(Page1.this,"A Propos Button clicked",Toast.LENGTH_SHORT).show(); return true; } // Add code here to update the UI based on the item selected // For example, swap UI fragments here return true; } }); mDrawerLayout.addDrawerListener( new DrawerLayout.DrawerListener() { @Override public void onDrawerSlide(View drawerView, float slideOffset) { // Respond when the drawer's position changes } @Override public void onDrawerOpened(View drawerView) { // Respond when the drawer is opened } @Override public void onDrawerClosed(View drawerView) { // Respond when the drawer is closed } @Override public void onDrawerStateChanged(int newState) { // Respond when the drawer motion state changes } } ); //// --------------------------------------Floating button -----------------------------------------------------///// ImageView icon = new ImageView(this); // Create an icon icon.setImageResource(R.drawable.add_btn2); FloatingActionButton actionButton = new FloatingActionButton.Builder(this) .setContentView(icon) .build(); SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this); ImageView itemIcon1 = new ImageView(this); itemIcon1.setImageResource(R.drawable.ic_edit_black_24dp); SubActionButton button1 = itemBuilder.setContentView(itemIcon1).build(); ImageView itemIcon2 = new ImageView(this); itemIcon2.setImageResource(R.drawable.add_btn2); SubActionButton button2 = itemBuilder.setContentView(itemIcon2).build(); ImageView itemIcon3 = new ImageView(this); itemIcon3.setImageResource(R.drawable.ic_list_black_24dp); SubActionButton button3 = itemBuilder.setContentView(itemIcon3).build(); final FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(this) .addSubActionView(button1) .addSubActionView(button2) .addSubActionView(button3) .attachTo(actionButton) .build(); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(Page1.this,"button1 clicked",Toast.LENGTH_SHORT).show(); actionMenu.close(true); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(Page1.this,"button2 clicked",Toast.LENGTH_SHORT).show(); actionMenu.close(true); Intent intent1= new Intent(Page1.this,Add_medicaments.class); startActivity(intent1); } }); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(Page1.this,"button3 clicked",Toast.LENGTH_SHORT).show(); actionMenu.close(true); } }); //// --------------------------------------Floatin button -----------------------------------------------------///// } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mDrawerLayout.openDrawer(GravityCompat.START); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { finish(); } }
8,284
0.535369
0.527523
210
38.44762
30.576517
124
false
false
0
0
0
0
0
0
0.542857
false
false
1
a337ab7f71cdbcb848e4bec633dcba00689c5499
20,461,224,243,500
9a6ea6087367965359d644665b8d244982d1b8b6
/src/main/java/X/C12780j2.java
71f11b20657d842dd344be47979ec1f3c92020e7
[]
no_license
technocode/com.wa_2.21.2
https://github.com/technocode/com.wa_2.21.2
a3dd842758ff54f207f1640531374d3da132b1d2
3c4b6f3c7bdef7c1523c06d5bd9a90b83acc80f9
refs/heads/master
2023-02-12T11:20:28.666000
2021-01-14T10:22:21
2021-01-14T10:22:21
329,578,591
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package X; import android.view.View; import android.widget.AdapterView; import androidx.appcompat.app.AlertController$RecycleListView; /* renamed from: X.0j2 reason: invalid class name and case insensitive filesystem */ public class C12780j2 implements AdapterView.OnItemClickListener { public final /* synthetic */ AnonymousClass0MC A00; public final /* synthetic */ AlertController$RecycleListView A01; public final /* synthetic */ C12810j6 A02; public C12780j2(AnonymousClass0MC r1, AlertController$RecycleListView alertController$RecycleListView, C12810j6 r3) { this.A00 = r1; this.A01 = alertController$RecycleListView; this.A02 = r3; } @Override // android.widget.AdapterView.OnItemClickListener public void onItemClick(AdapterView adapterView, View view, int i, long j) { AnonymousClass0MC r2 = this.A00; boolean[] zArr = r2.A0N; if (zArr != null) { zArr[i] = this.A01.isItemChecked(i); } r2.A09.onClick(this.A02.A0Z, i, this.A01.isItemChecked(i)); } }
UTF-8
Java
1,073
java
C12780j2.java
Java
[]
null
[]
package X; import android.view.View; import android.widget.AdapterView; import androidx.appcompat.app.AlertController$RecycleListView; /* renamed from: X.0j2 reason: invalid class name and case insensitive filesystem */ public class C12780j2 implements AdapterView.OnItemClickListener { public final /* synthetic */ AnonymousClass0MC A00; public final /* synthetic */ AlertController$RecycleListView A01; public final /* synthetic */ C12810j6 A02; public C12780j2(AnonymousClass0MC r1, AlertController$RecycleListView alertController$RecycleListView, C12810j6 r3) { this.A00 = r1; this.A01 = alertController$RecycleListView; this.A02 = r3; } @Override // android.widget.AdapterView.OnItemClickListener public void onItemClick(AdapterView adapterView, View view, int i, long j) { AnonymousClass0MC r2 = this.A00; boolean[] zArr = r2.A0N; if (zArr != null) { zArr[i] = this.A01.isItemChecked(i); } r2.A09.onClick(this.A02.A0Z, i, this.A01.isItemChecked(i)); } }
1,073
0.702703
0.646785
28
37.32143
31.089794
121
false
false
0
0
0
0
0
0
0.75
false
false
1
fba458c1cb0ffc38da8813c420da2ea0cd7282b7
20,727,512,213,122
16b13b858bee8cea1e5475c42d95621b05029a4c
/src/main/java/com/strandls/observation/es/util/RabbitMQConsumer.java
3874304da3e3e81020ed289f8c5d2605b4fa185b
[ "Apache-2.0" ]
permissive
strandls/biodiv-observation
https://github.com/strandls/biodiv-observation
abc3238236fd6e70aa162552fa498c72ce20fc68
c28b5b100f53cf4915ae99e72dce711af81ab6e9
refs/heads/master
2023-01-11T02:01:39.183000
2023-01-03T08:32:13
2023-01-03T08:32:13
196,522,249
1
4
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.strandls.observation.es.util; import javax.inject.Inject; import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.Channel; import com.rabbitmq.client.DeliverCallback; /** * @author Abhishek Rudra * */ public class RabbitMQConsumer { private final static String OBSERVATION_QUEUE = "observationQueue"; @Inject private ESUpdate esUpdate; @Inject private Channel channel; public void elasticUpdate() throws Exception { DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); BasicProperties properties = delivery.getProperties(); String updateType = properties.getType(); System.out.println("----[RABBIT MQ CONSUMER]---"); System.out.println("consuming observation Id :" + message); System.out.println("Updating :" + updateType); ESUpdateThread updateThread = new ESUpdateThread(esUpdate, message); Thread thread = new Thread(updateThread); thread.start(); }; channel.basicConsume(OBSERVATION_QUEUE, true, deliverCallback, consumerTag -> { }); } }
UTF-8
Java
1,109
java
RabbitMQConsumer.java
Java
[ { "context": "m.rabbitmq.client.DeliverCallback;\n\n/**\n * @author Abhishek Rudra\n *\n */\npublic class RabbitMQConsumer {\n\n\tprivate ", "end": 243, "score": 0.999886691570282, "start": 229, "tag": "NAME", "value": "Abhishek Rudra" } ]
null
[]
/** * */ package com.strandls.observation.es.util; import javax.inject.Inject; import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.Channel; import com.rabbitmq.client.DeliverCallback; /** * @author <NAME> * */ public class RabbitMQConsumer { private final static String OBSERVATION_QUEUE = "observationQueue"; @Inject private ESUpdate esUpdate; @Inject private Channel channel; public void elasticUpdate() throws Exception { DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); BasicProperties properties = delivery.getProperties(); String updateType = properties.getType(); System.out.println("----[RABBIT MQ CONSUMER]---"); System.out.println("consuming observation Id :" + message); System.out.println("Updating :" + updateType); ESUpdateThread updateThread = new ESUpdateThread(esUpdate, message); Thread thread = new Thread(updateThread); thread.start(); }; channel.basicConsume(OBSERVATION_QUEUE, true, deliverCallback, consumerTag -> { }); } }
1,101
0.731289
0.730388
44
24.204546
25.137423
81
false
false
0
0
0
0
0
0
1.522727
false
false
1
e8098940fbcd64a3be00dcb495450c829ab4b364
26,482,768,388,871
0f99ba5e89a78e5db44db0b53c0ce5e8354b7243
/app/src/main/java/com/s16/dhammadroid/utils/MediaPlayerImpl.java
c70e8bc7579a37b724757075e87c8bfb5c944e7c
[]
no_license
soeminnminn/NineNaWin
https://github.com/soeminnminn/NineNaWin
10c7430e2b837e3a67f74332b536bf6cae37169f
cd3170598adc2d504a0dfe283393b54bd5225539
refs/heads/master
2021-08-08T01:18:21.738000
2017-09-12T05:37:11
2017-09-12T05:37:11
10,729,693
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.s16.dhammadroid.utils; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Handler; import android.os.ParcelFileDescriptor; import android.widget.SeekBar; import android.widget.TextView; public class MediaPlayerImpl { private final String mZeroDuration = String.format("%02d:%02d", 0, 0); private final Context mContext; private MediaPlayer mMediaPlayer; private final SeekBar mSeekPlayer; private final TextView mTxtPlayerStart; private final TextView mTxtPlayerEnd; private boolean mIsPrepared; private long mUiThreadId; private Handler mHandler = new Handler(); private MediaPlayerEventListener mEventListener; public interface MediaPlayerEventListener { public void onProgressChanged(MediaPlayer mp, int progress, boolean fromUser); public void onCompletion(MediaPlayer mp); } private Runnable mUpdateTimeTask = new Runnable() { public void run() { int currentDuration = mMediaPlayer.getCurrentPosition(); mSeekPlayer.setProgress(currentDuration); mHandler.postDelayed(this, 100); } }; public MediaPlayerImpl(Context context, SeekBar seekbar, TextView position, TextView duration) { mContext = context; mSeekPlayer = seekbar; mTxtPlayerStart = position; mTxtPlayerEnd = duration; mUiThreadId = Thread.currentThread().getId(); } protected Context getContext() { return mContext; } public void setMediaPlayerEventListener(MediaPlayerEventListener listener) { mEventListener = listener; } public MediaPlayerImpl prepare(File audioFile) { if (mMediaPlayer == null) { mMediaPlayer = new MediaPlayer(); } try { ParcelFileDescriptor afd = ParcelFileDescriptor.open(audioFile, ParcelFileDescriptor.MODE_READ_ONLY); mMediaPlayer.reset(); mMediaPlayer.setDataSource(afd.getFileDescriptor()); mMediaPlayer.prepare(); mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mIsPrepared = true; int duration = mMediaPlayer.getDuration(); mSeekPlayer.setMax(duration); mTxtPlayerStart.setText(mZeroDuration); mTxtPlayerEnd.setText(millisecondsToTimeString(duration, false)); } }); mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { performCompletion(mp); } }); } catch (IOException e) { e.printStackTrace(); } mSeekPlayer.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mUpdateTimeTask); if (mMediaPlayer != null) { mMediaPlayer.seekTo(seekBar.getProgress()); updateProgressBar(); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mUpdateTimeTask); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mTxtPlayerStart.setText(millisecondsToTimeString(progress, false)); performProgressChanged(progress, fromUser); } }); return this; } public MediaPlayerImpl prepare(Uri audioUri) { if (mMediaPlayer == null) { mMediaPlayer = new MediaPlayer(); } try { mMediaPlayer.reset(); //mMediaPlayer.setDataSource(getContext(), audioUri); mMediaPlayer.setDataSource(audioUri.toString()); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.prepareAsync(); mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mIsPrepared = true; int duration = mMediaPlayer.getDuration(); mSeekPlayer.setMax(duration); mTxtPlayerStart.setText(mZeroDuration); mTxtPlayerEnd.setText(millisecondsToTimeString(duration, false)); } }); mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { performCompletion(mp); } }); mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { mSeekPlayer.setSecondaryProgress(percent); } }); } catch (IOException e) { e.printStackTrace(); } mSeekPlayer.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mUpdateTimeTask); if (mMediaPlayer != null) { mMediaPlayer.seekTo(seekBar.getProgress()); updateProgressBar(); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mUpdateTimeTask); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mTxtPlayerStart.setText(millisecondsToTimeString(progress, false)); performProgressChanged(progress, fromUser); } }); return this; } public boolean isPlaying() { return mMediaPlayer != null && mIsPrepared && mMediaPlayer.isPlaying(); } public boolean isPaused() { return mMediaPlayer != null && mIsPrepared && !mMediaPlayer.isPlaying(); } public void start() { if (mMediaPlayer != null) { if (!mIsPrepared) { new Handler().postDelayed(new Runnable() { @Override public void run() { start(); } }, 200); } else if (!mMediaPlayer.isPlaying()) { mMediaPlayer.start(); updateProgressBar(); } } } public void pause() { if (mMediaPlayer != null && mIsPrepared && mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); } } public void stop() { if (mIsPrepared) { mHandler.removeCallbacks(mUpdateTimeTask); if (mMediaPlayer != null) { if (mMediaPlayer.isPlaying()) { mMediaPlayer.stop(); } mMediaPlayer.release(); mIsPrepared = false; mMediaPlayer = null; } mSeekPlayer.setProgress(0); mTxtPlayerStart.setText(mZeroDuration); mTxtPlayerEnd.setText(mZeroDuration); } } public void destroy() { if (mIsPrepared) { mHandler.removeCallbacks(mUpdateTimeTask); if (mMediaPlayer != null) { if (mMediaPlayer.isPlaying()) { mMediaPlayer.stop(); } mMediaPlayer.release(); mIsPrepared = false; } } } private void performCompletion(MediaPlayer mp) { mHandler.removeCallbacks(mUpdateTimeTask); mSeekPlayer.setProgress(0); mTxtPlayerStart.setText(mZeroDuration); if (mEventListener != null) { mEventListener.onCompletion(mp); } } private void performProgressChanged(int progress, boolean fromUser) { if (mEventListener != null) { mEventListener.onProgressChanged(mMediaPlayer, progress, fromUser); } } protected void updateProgressBar() { mHandler.postDelayed(mUpdateTimeTask, 100); } protected void runOnUiThread(Runnable runnable, boolean checkThread) { if (getContext() instanceof Activity) { if (checkThread) { if (Thread.currentThread().getId() != mUiThreadId) { ((Activity)getContext()).runOnUiThread(runnable); } else { runnable.run(); } } else { ((Activity)getContext()).runOnUiThread(runnable); } } } protected String millisecondsToTimeString(int millis, boolean overHours) { if (overHours) { return String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); } else { return String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millis), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); } } }
UTF-8
Java
8,404
java
MediaPlayerImpl.java
Java
[]
null
[]
package com.s16.dhammadroid.utils; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Handler; import android.os.ParcelFileDescriptor; import android.widget.SeekBar; import android.widget.TextView; public class MediaPlayerImpl { private final String mZeroDuration = String.format("%02d:%02d", 0, 0); private final Context mContext; private MediaPlayer mMediaPlayer; private final SeekBar mSeekPlayer; private final TextView mTxtPlayerStart; private final TextView mTxtPlayerEnd; private boolean mIsPrepared; private long mUiThreadId; private Handler mHandler = new Handler(); private MediaPlayerEventListener mEventListener; public interface MediaPlayerEventListener { public void onProgressChanged(MediaPlayer mp, int progress, boolean fromUser); public void onCompletion(MediaPlayer mp); } private Runnable mUpdateTimeTask = new Runnable() { public void run() { int currentDuration = mMediaPlayer.getCurrentPosition(); mSeekPlayer.setProgress(currentDuration); mHandler.postDelayed(this, 100); } }; public MediaPlayerImpl(Context context, SeekBar seekbar, TextView position, TextView duration) { mContext = context; mSeekPlayer = seekbar; mTxtPlayerStart = position; mTxtPlayerEnd = duration; mUiThreadId = Thread.currentThread().getId(); } protected Context getContext() { return mContext; } public void setMediaPlayerEventListener(MediaPlayerEventListener listener) { mEventListener = listener; } public MediaPlayerImpl prepare(File audioFile) { if (mMediaPlayer == null) { mMediaPlayer = new MediaPlayer(); } try { ParcelFileDescriptor afd = ParcelFileDescriptor.open(audioFile, ParcelFileDescriptor.MODE_READ_ONLY); mMediaPlayer.reset(); mMediaPlayer.setDataSource(afd.getFileDescriptor()); mMediaPlayer.prepare(); mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mIsPrepared = true; int duration = mMediaPlayer.getDuration(); mSeekPlayer.setMax(duration); mTxtPlayerStart.setText(mZeroDuration); mTxtPlayerEnd.setText(millisecondsToTimeString(duration, false)); } }); mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { performCompletion(mp); } }); } catch (IOException e) { e.printStackTrace(); } mSeekPlayer.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mUpdateTimeTask); if (mMediaPlayer != null) { mMediaPlayer.seekTo(seekBar.getProgress()); updateProgressBar(); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mUpdateTimeTask); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mTxtPlayerStart.setText(millisecondsToTimeString(progress, false)); performProgressChanged(progress, fromUser); } }); return this; } public MediaPlayerImpl prepare(Uri audioUri) { if (mMediaPlayer == null) { mMediaPlayer = new MediaPlayer(); } try { mMediaPlayer.reset(); //mMediaPlayer.setDataSource(getContext(), audioUri); mMediaPlayer.setDataSource(audioUri.toString()); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.prepareAsync(); mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mIsPrepared = true; int duration = mMediaPlayer.getDuration(); mSeekPlayer.setMax(duration); mTxtPlayerStart.setText(mZeroDuration); mTxtPlayerEnd.setText(millisecondsToTimeString(duration, false)); } }); mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { performCompletion(mp); } }); mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { mSeekPlayer.setSecondaryProgress(percent); } }); } catch (IOException e) { e.printStackTrace(); } mSeekPlayer.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mUpdateTimeTask); if (mMediaPlayer != null) { mMediaPlayer.seekTo(seekBar.getProgress()); updateProgressBar(); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mUpdateTimeTask); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mTxtPlayerStart.setText(millisecondsToTimeString(progress, false)); performProgressChanged(progress, fromUser); } }); return this; } public boolean isPlaying() { return mMediaPlayer != null && mIsPrepared && mMediaPlayer.isPlaying(); } public boolean isPaused() { return mMediaPlayer != null && mIsPrepared && !mMediaPlayer.isPlaying(); } public void start() { if (mMediaPlayer != null) { if (!mIsPrepared) { new Handler().postDelayed(new Runnable() { @Override public void run() { start(); } }, 200); } else if (!mMediaPlayer.isPlaying()) { mMediaPlayer.start(); updateProgressBar(); } } } public void pause() { if (mMediaPlayer != null && mIsPrepared && mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); } } public void stop() { if (mIsPrepared) { mHandler.removeCallbacks(mUpdateTimeTask); if (mMediaPlayer != null) { if (mMediaPlayer.isPlaying()) { mMediaPlayer.stop(); } mMediaPlayer.release(); mIsPrepared = false; mMediaPlayer = null; } mSeekPlayer.setProgress(0); mTxtPlayerStart.setText(mZeroDuration); mTxtPlayerEnd.setText(mZeroDuration); } } public void destroy() { if (mIsPrepared) { mHandler.removeCallbacks(mUpdateTimeTask); if (mMediaPlayer != null) { if (mMediaPlayer.isPlaying()) { mMediaPlayer.stop(); } mMediaPlayer.release(); mIsPrepared = false; } } } private void performCompletion(MediaPlayer mp) { mHandler.removeCallbacks(mUpdateTimeTask); mSeekPlayer.setProgress(0); mTxtPlayerStart.setText(mZeroDuration); if (mEventListener != null) { mEventListener.onCompletion(mp); } } private void performProgressChanged(int progress, boolean fromUser) { if (mEventListener != null) { mEventListener.onProgressChanged(mMediaPlayer, progress, fromUser); } } protected void updateProgressBar() { mHandler.postDelayed(mUpdateTimeTask, 100); } protected void runOnUiThread(Runnable runnable, boolean checkThread) { if (getContext() instanceof Activity) { if (checkThread) { if (Thread.currentThread().getId() != mUiThreadId) { ((Activity)getContext()).runOnUiThread(runnable); } else { runnable.run(); } } else { ((Activity)getContext()).runOnUiThread(runnable); } } } protected String millisecondsToTimeString(int millis, boolean overHours) { if (overHours) { return String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); } else { return String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millis), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); } } }
8,404
0.693003
0.689553
292
27.780823
25.962828
125
false
false
0
0
0
0
0
0
2.445205
false
false
1
dd46e4c1e9ba55410888834ff62ed8d306369310
26,482,768,388,641
9d583eeb78d4b41285ea7e4e917247994decd4bb
/admin-user/src/main/java/com/admin/user/entity/SysRoleInterfaceEntity.java
4ef4e253fecbe5a112b0b28e1ef4fc12e394f1cc
[ "MIT" ]
permissive
NewGreenHand/fast-admin-end
https://github.com/NewGreenHand/fast-admin-end
a4828819334457034344f996ab3cd044071cad01
ff0b1992eac71b1656cc50c246e8cac321e4289d
refs/heads/master
2021-06-29T00:08:20.428000
2020-10-16T13:42:13
2020-10-16T13:42:13
161,360,088
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.admin.user.entity; import com.admin.core.basic.AbstractEntity; import org.hibernate.annotations.DynamicInsert; import javax.persistence.*; import java.io.Serializable; /** * 权限角色部门. * * @author fei * @since 2018/10/14 */ @Entity @DynamicInsert @Table(name = "sys_role_interface", schema = "fastAdmin") public class SysRoleInterfaceEntity extends AbstractEntity implements Serializable { private static final long serialVersionUID = -1707634470264551472L; /** 菜单(权限)表ID */ private Long pid; /** 角色表ID */ private Long rid; /** 菜单(权限) */ private SysInterfaceEntity permission; /** 角色 */ private SysRoleEntity role; @Basic @Column(name = "pid") public Long getPid() { return pid; } public void setPid(Long pid) { this.pid = pid; } @Basic @Column(name = "rid") public Long getRid() { return rid; } public void setRid(Long rid) { this.rid = rid; } @ManyToOne @JoinColumn(name = "pid", referencedColumnName = "id", updatable = false, insertable = false) public SysInterfaceEntity getPermission() { return permission; } public void setPermission(SysInterfaceEntity permission) { this.permission = permission; } @ManyToOne @JoinColumn(name = "rid", referencedColumnName = "id", updatable = false, insertable = false) public SysRoleEntity getRole() { return role; } public void setRole(SysRoleEntity role) { this.role = role; } }
UTF-8
Java
1,495
java
SysRoleInterfaceEntity.java
Java
[ { "context": "ava.io.Serializable;\n\n/**\n * 权限角色部门.\n *\n * @author fei\n * @since 2018/10/14\n */\n@Entity\n@DynamicInsert\n@", "end": 215, "score": 0.9985545873641968, "start": 212, "tag": "USERNAME", "value": "fei" } ]
null
[]
package com.admin.user.entity; import com.admin.core.basic.AbstractEntity; import org.hibernate.annotations.DynamicInsert; import javax.persistence.*; import java.io.Serializable; /** * 权限角色部门. * * @author fei * @since 2018/10/14 */ @Entity @DynamicInsert @Table(name = "sys_role_interface", schema = "fastAdmin") public class SysRoleInterfaceEntity extends AbstractEntity implements Serializable { private static final long serialVersionUID = -1707634470264551472L; /** 菜单(权限)表ID */ private Long pid; /** 角色表ID */ private Long rid; /** 菜单(权限) */ private SysInterfaceEntity permission; /** 角色 */ private SysRoleEntity role; @Basic @Column(name = "pid") public Long getPid() { return pid; } public void setPid(Long pid) { this.pid = pid; } @Basic @Column(name = "rid") public Long getRid() { return rid; } public void setRid(Long rid) { this.rid = rid; } @ManyToOne @JoinColumn(name = "pid", referencedColumnName = "id", updatable = false, insertable = false) public SysInterfaceEntity getPermission() { return permission; } public void setPermission(SysInterfaceEntity permission) { this.permission = permission; } @ManyToOne @JoinColumn(name = "rid", referencedColumnName = "id", updatable = false, insertable = false) public SysRoleEntity getRole() { return role; } public void setRole(SysRoleEntity role) { this.role = role; } }
1,495
0.685556
0.666897
69
19.971014
22.158175
95
false
false
0
0
0
0
0
0
0.362319
false
false
1
cc9fa4677072418fc708b1a3182b70f2d54fb3a6
31,954,556,733,452
f276644da06079cdd6c018b7e7ffa374df5d8c3e
/sboot-integration-luckydraw/src/main/java/com/bugjc/cj/service/impl/LogicServiceImpl.java
13753b0f5a5b53d7a4e5450a32c23e01b8f8ec7d
[]
no_license
bugjc/sboot-integration-samples
https://github.com/bugjc/sboot-integration-samples
058146cf2105dd0c1e91fb21726b2e9c0643acfd
83cba00b5bcaa136c555fe1a1af0e5bad13c13a8
refs/heads/master
2018-11-07T17:36:31.681000
2018-10-08T02:57:47
2018-10-08T02:57:47
121,110,885
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bugjc.cj.service.impl; import cn.hutool.core.lang.Singleton; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.bugjc.cj.component.DrawRedisResult; import com.bugjc.cj.service.LogicService; import com.bugjc.cj.core.util.IdWorker; import com.bugjc.cj.core.util.LuckyDrawQueueUtil; import com.bugjc.cj.core.util.MyCache; import com.bugjc.cj.core.dto.Result; import com.bugjc.cj.core.dto.ResultGenerator; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import javax.annotation.Resource; /** * @Auther: qingyang * @Date: 2018/6/6 09:24 * @Description: */ @Slf4j @Service public class LogicServiceImpl implements LogicService { @Resource private StringRedisTemplate stringRedisTemplate; @Resource private DrawRedisResult drawRedisResult; @Override public Result luckyDraw(String userId) { log.info("用户["+userId+"]加入抽奖队列"); String key = "LuckyDraw:"+userId; if (MyCache.userRequestLimit(key)){ log.info("请求频次限制,用户编号:"+userId); } //构建任务参数 String queryId = IdWorker.getNextId(); JSONObject result = new JSONObject(){{ put("userId",userId); put("queryId",queryId); }}; //加入队列 // LuckyDrawQueueUtil luckyDrawQueueUtil = Singleton.get(LuckyDrawQueueUtil.class); // luckyDrawQueueUtil.getLuckyDrawQueue().offer(result); //快速返回受理结果 return ResultGenerator.genSuccessResult(result); } @Override public Result queryLuckDraw(String queryId) { log.info("查询抽奖结果..."); String json = drawRedisResult.getQueryResult(queryId); if (json == null){ return new Result().setCode(1); } return JSON.parseObject(json,Result.class); } }
UTF-8
Java
1,979
java
LogicServiceImpl.java
Java
[ { "context": "import javax.annotation.Resource;\n\n/**\n * @Auther: qingyang\n * @Date: 2018/6/6 09:24\n * @Description:\n */\n@Sl", "end": 654, "score": 0.9995840191841125, "start": 646, "tag": "USERNAME", "value": "qingyang" }, { "context": "fo(\"用户[\"+userId+\"]加入抽奖队列\");\n String key = \"LuckyDraw:\"+userId;\n if (MyCache.userRequestLimit(key)){\n ", "end": 1042, "score": 0.9905378222465515, "start": 1024, "tag": "KEY", "value": "LuckyDraw:\"+userId" } ]
null
[]
package com.bugjc.cj.service.impl; import cn.hutool.core.lang.Singleton; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.bugjc.cj.component.DrawRedisResult; import com.bugjc.cj.service.LogicService; import com.bugjc.cj.core.util.IdWorker; import com.bugjc.cj.core.util.LuckyDrawQueueUtil; import com.bugjc.cj.core.util.MyCache; import com.bugjc.cj.core.dto.Result; import com.bugjc.cj.core.dto.ResultGenerator; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import javax.annotation.Resource; /** * @Auther: qingyang * @Date: 2018/6/6 09:24 * @Description: */ @Slf4j @Service public class LogicServiceImpl implements LogicService { @Resource private StringRedisTemplate stringRedisTemplate; @Resource private DrawRedisResult drawRedisResult; @Override public Result luckyDraw(String userId) { log.info("用户["+userId+"]加入抽奖队列"); String key = "LuckyDraw:"+userId; if (MyCache.userRequestLimit(key)){ log.info("请求频次限制,用户编号:"+userId); } //构建任务参数 String queryId = IdWorker.getNextId(); JSONObject result = new JSONObject(){{ put("userId",userId); put("queryId",queryId); }}; //加入队列 // LuckyDrawQueueUtil luckyDrawQueueUtil = Singleton.get(LuckyDrawQueueUtil.class); // luckyDrawQueueUtil.getLuckyDrawQueue().offer(result); //快速返回受理结果 return ResultGenerator.genSuccessResult(result); } @Override public Result queryLuckDraw(String queryId) { log.info("查询抽奖结果..."); String json = drawRedisResult.getQueryResult(queryId); if (json == null){ return new Result().setCode(1); } return JSON.parseObject(json,Result.class); } }
1,979
0.687467
0.680063
65
28.092308
20.936331
90
false
false
0
0
0
0
0
0
0.523077
false
false
1
11be489238b5f131155db56f15d832deb0e1f6c4
9,062,381,042,255
20e8c4d3909cbd3077d842ed12e59cb9db24ba3b
/keconnection/keconnection-tarif/src/main/java/ru/complitex/keconnection/tarif/menu/TarifMenu.java
179d15625eecf4fa84b4947587e93215f8e340e6
[]
no_license
complitex/complitex
https://github.com/complitex/complitex
26f194d082691e560219ef1af20e7f86ba5aabf5
c3c2b5b4c3fc19eebab947bfba6705ee63e4efa5
refs/heads/master
2022-05-21T18:25:22.187000
2022-04-16T08:57:25
2022-04-16T08:57:25
22,946,928
1
0
null
false
2021-03-23T04:50:23
2014-08-14T08:35:19
2021-03-23T04:49:42
2021-03-22T23:42:45
27,729
0
0
0
Java
false
false
package ru.complitex.keconnection.tarif.menu; import com.google.common.collect.ImmutableList; import org.apache.wicket.Page; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.request.mapper.parameter.PageParameters; import ru.complitex.common.strategy.IStrategy; import ru.complitex.common.strategy.StrategyFactory; import ru.complitex.common.util.EjbBeanLocator; import ru.complitex.template.web.security.SecurityRole; import ru.complitex.template.web.template.ITemplateLink; import ru.complitex.template.web.template.ResourceTemplateMenu; import java.util.List; import java.util.Locale; /** * * @author Artem */ @AuthorizeInstantiation(SecurityRole.ADMIN_MODULE_EDIT) public class TarifMenu extends ResourceTemplateMenu { private IStrategy getStrategy(String entity) { return EjbBeanLocator.getBean(StrategyFactory.class).getStrategy(entity); } @Override public List<ITemplateLink> getTemplateLinks(Locale locale) { return ImmutableList.<ITemplateLink>of( new ITemplateLink() { static final String TARIF_GROUP_ENTITY = "tarif_group"; @Override public String getLabel(Locale locale) { return getStrategy(TARIF_GROUP_ENTITY).getPluralEntityLabel(locale); } @Override public Class<? extends Page> getPage() { return getStrategy(TARIF_GROUP_ENTITY).getListPage(); } @Override public PageParameters getParameters() { return getStrategy(TARIF_GROUP_ENTITY).getListPageParams(); } @Override public String getTagId() { return "tarif_group_item"; } }, new ITemplateLink() { static final String TARIF_ENTITY = "tarif"; @Override public String getLabel(Locale locale) { return getStrategy(TARIF_ENTITY).getPluralEntityLabel(locale); } @Override public Class<? extends Page> getPage() { return getStrategy(TARIF_ENTITY).getListPage(); } @Override public PageParameters getParameters() { return getStrategy(TARIF_ENTITY).getListPageParams(); } @Override public String getTagId() { return "tarif_item"; } }); } @Override public String getTagId() { return "tarif_menu"; } }
UTF-8
Java
2,888
java
TarifMenu.java
Java
[ { "context": ".List;\nimport java.util.Locale;\n\n/**\n *\n * @author Artem\n */\n@AuthorizeInstantiation(SecurityRole.ADMIN_MO", "end": 691, "score": 0.9989960789680481, "start": 686, "tag": "NAME", "value": "Artem" } ]
null
[]
package ru.complitex.keconnection.tarif.menu; import com.google.common.collect.ImmutableList; import org.apache.wicket.Page; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.request.mapper.parameter.PageParameters; import ru.complitex.common.strategy.IStrategy; import ru.complitex.common.strategy.StrategyFactory; import ru.complitex.common.util.EjbBeanLocator; import ru.complitex.template.web.security.SecurityRole; import ru.complitex.template.web.template.ITemplateLink; import ru.complitex.template.web.template.ResourceTemplateMenu; import java.util.List; import java.util.Locale; /** * * @author Artem */ @AuthorizeInstantiation(SecurityRole.ADMIN_MODULE_EDIT) public class TarifMenu extends ResourceTemplateMenu { private IStrategy getStrategy(String entity) { return EjbBeanLocator.getBean(StrategyFactory.class).getStrategy(entity); } @Override public List<ITemplateLink> getTemplateLinks(Locale locale) { return ImmutableList.<ITemplateLink>of( new ITemplateLink() { static final String TARIF_GROUP_ENTITY = "tarif_group"; @Override public String getLabel(Locale locale) { return getStrategy(TARIF_GROUP_ENTITY).getPluralEntityLabel(locale); } @Override public Class<? extends Page> getPage() { return getStrategy(TARIF_GROUP_ENTITY).getListPage(); } @Override public PageParameters getParameters() { return getStrategy(TARIF_GROUP_ENTITY).getListPageParams(); } @Override public String getTagId() { return "tarif_group_item"; } }, new ITemplateLink() { static final String TARIF_ENTITY = "tarif"; @Override public String getLabel(Locale locale) { return getStrategy(TARIF_ENTITY).getPluralEntityLabel(locale); } @Override public Class<? extends Page> getPage() { return getStrategy(TARIF_ENTITY).getListPage(); } @Override public PageParameters getParameters() { return getStrategy(TARIF_ENTITY).getListPageParams(); } @Override public String getTagId() { return "tarif_item"; } }); } @Override public String getTagId() { return "tarif_menu"; } }
2,888
0.56856
0.56856
85
32.976471
26.884054
100
false
false
0
0
0
0
0
0
0.317647
false
false
1
9618b07361b8e5231aceb3e2e3921328633752d9
26,723,286,556,277
48a751e77337b426a59da7de9b9bac20e01087e3
/src/test/java/algorithms/compGeometry/clustering/twopointcorrelation/FindClustersTest.java
791438004db3c8ea14981e5da1afd5966979692f
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
tectronics/two-point-correlation
https://github.com/tectronics/two-point-correlation
2dc4de759560297e414cf5160f544c25f7aa62b2
b16cc6d2b30a52e188d2b1dd93bb930aaa2ce0c0
refs/heads/master
2018-01-11T14:54:12.773000
2015-03-10T03:31:21
2015-03-10T03:31:21
46,474,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package algorithms.compGeometry.clustering.twopointcorrelation; import algorithms.compGeometry.clustering.twopointcorrelation.RandomClusterAndBackgroundGenerator.CLUSTER_SEPARATION; import algorithms.curves.GEVYFit; import algorithms.misc.HistogramHolder; import algorithms.util.ResourceFinder; import java.security.SecureRandom; import java.util.logging.Logger; /** * @author nichole */ public class FindClustersTest extends BaseTwoPointTest { boolean debug = false; boolean writeToTmpData = false; protected Logger log = Logger.getLogger(this.getClass().getSimpleName()); public void testFindClustersStats() throws Exception { log.info("testFindClustersStats()"); float xmin = 0; float xmax = 300; float ymin = 0; float ymax = 300; TwoPointCorrelationPlotter plotter = new TwoPointCorrelationPlotter(xmin, xmax, ymin, ymax); //SecureRandom srr = SecureRandom.getInstance("SHA1PRNG"); //srr.setSeed(System.currentTimeMillis()); //long seed = srr.nextLong(); long seed = System.currentTimeMillis(); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); //seed = 1387775326745l; sr.setSeed(-2384802679227907254l); log.info("SEED=" + seed); // a long running test to calculate and print the stats of fits // for sparse, moderate, and densely populated backgrounds, // all with the same number of clusters and cluster points, though // randomly distributed. int nSwitches = 3; int nIterPerBackground = 3; AxisIndexer indexer = null; int count = 0; for (int ii = 0; ii < nIterPerBackground; ii++) { for (int i = 0; i < nSwitches; i++) { try { switch(i) { case 0: //~100 indexer = createIndexerWithRandomPoints(sr, xmin, xmax, ymin, ymax, //10, 100, 110, 100.0f); 3, 33, 33, 0.1f); break; case 1: //~1000 indexer = createIndexerWithRandomPoints(sr, xmin, xmax, ymin, ymax, 3, 33, 33, 10f); break; case 2: // 100*100 indexer = createIndexerWithRandomPoints(sr, xmin, xmax, ymin, ymax, 3, 30, 60, 100.0f); break; case 3: { int[] clusterNumbers = new int[]{1000, 300, 100}; int nBackgroundPoints = 10000; CLUSTER_SEPARATION clusterSeparation = CLUSTER_SEPARATION.LARGE; indexer = createIndexerWithRandomPoints(sr, xmin, xmax, ymin, ymax, clusterNumbers, nBackgroundPoints, clusterSeparation); break; } default: { int[] clusterNumbers = new int[]{1000, 300, 100}; int nBackgroundPoints = 100000; CLUSTER_SEPARATION clusterSeparation = CLUSTER_SEPARATION.LARGE; indexer = generator.createIndexerWithRandomPoints(sr, xmin, xmax, ymin, ymax, clusterNumbers, nBackgroundPoints, clusterSeparation); break; } } //TODO: consider reverting this code... and adding the ability to plot to the // performance metrics log.info(" " + count + " (" + indexer.nXY + " points) ... "); if (writeToTmpData) { // write to tmpdata if need to use in tests improve fits, histogram etc String str = String.valueOf(count); while (str.length() < 3) { str = "0" + str; } String fileNamePostfix = "_clusters_" + str + ".dat"; String fileName = CreateClusterDataTest.indexerFileNamePrefix + fileNamePostfix; String filePath = ResourceFinder.getAFilePathInTmpData(fileName); CreateClusterDataTest.writeIndexer(filePath, indexer); } log.info(" " + count + " (" + indexer.nXY + " points) ... "); long t0 = System.currentTimeMillis(); TwoPointCorrelation twoPtC = new TwoPointCorrelation(indexer); //twoPtC.setDebug(true); if (i == 4) { //twoPtC.setAllowRefinement(); } twoPtC.logPerformanceMetrics(); //twoPtC.useFindMethodForDataWithoutBackgroundPoints(); twoPtC.calculateBackground(); //twoPtC.setBackground(0.2f, 0.1f); twoPtC.findClusters(); long t1 = (System.currentTimeMillis() - t0)/1000; log.info(i + ") ====> total RT(sec) = " + t1 + " nPoints=" + indexer.getNumberOfPoints()); String plotLabel = ""; TwoPointVoidStats stats = (TwoPointVoidStats)twoPtC.backgroundStats; if (twoPtC.backgroundStats != null && (twoPtC.backgroundStats instanceof TwoPointVoidStats)) { HistogramHolder histogram = stats.statsHistogram; GEVYFit bestFit = stats.bestFit; if (bestFit != null) { // label needs: x10, peak, mean/peak, median/mean and x80/median plotLabel = String.format( "(%d %d) k=%.4f s=%.4f m=%.4f chSq=%.6f chst=%.1f", i, ii, bestFit.getK(), bestFit.getSigma(), bestFit.getMu(), bestFit.getChiSqSum(), bestFit.getChiSqStatistic() ); if (debug) { log.info(plotLabel + " findVoid sampling=" + stats.getSampling().name()); } } } plotter.addPlot(twoPtC, plotLabel); plotter.writeFile(); } catch(Throwable e) { log.severe(e.getMessage()); } count++; } } log.info("\n start computing stats for all sets"); count = 0; log.info("SEED=" + seed); } }
UTF-8
Java
7,131
java
FindClustersTest.java
Java
[ { "context": ";\nimport java.util.logging.Logger;\n\n/**\n * @author nichole\n */\npublic class FindClustersTest extends BaseTwo", "end": 387, "score": 0.7223116755485535, "start": 380, "tag": "NAME", "value": "nichole" } ]
null
[]
package algorithms.compGeometry.clustering.twopointcorrelation; import algorithms.compGeometry.clustering.twopointcorrelation.RandomClusterAndBackgroundGenerator.CLUSTER_SEPARATION; import algorithms.curves.GEVYFit; import algorithms.misc.HistogramHolder; import algorithms.util.ResourceFinder; import java.security.SecureRandom; import java.util.logging.Logger; /** * @author nichole */ public class FindClustersTest extends BaseTwoPointTest { boolean debug = false; boolean writeToTmpData = false; protected Logger log = Logger.getLogger(this.getClass().getSimpleName()); public void testFindClustersStats() throws Exception { log.info("testFindClustersStats()"); float xmin = 0; float xmax = 300; float ymin = 0; float ymax = 300; TwoPointCorrelationPlotter plotter = new TwoPointCorrelationPlotter(xmin, xmax, ymin, ymax); //SecureRandom srr = SecureRandom.getInstance("SHA1PRNG"); //srr.setSeed(System.currentTimeMillis()); //long seed = srr.nextLong(); long seed = System.currentTimeMillis(); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); //seed = 1387775326745l; sr.setSeed(-2384802679227907254l); log.info("SEED=" + seed); // a long running test to calculate and print the stats of fits // for sparse, moderate, and densely populated backgrounds, // all with the same number of clusters and cluster points, though // randomly distributed. int nSwitches = 3; int nIterPerBackground = 3; AxisIndexer indexer = null; int count = 0; for (int ii = 0; ii < nIterPerBackground; ii++) { for (int i = 0; i < nSwitches; i++) { try { switch(i) { case 0: //~100 indexer = createIndexerWithRandomPoints(sr, xmin, xmax, ymin, ymax, //10, 100, 110, 100.0f); 3, 33, 33, 0.1f); break; case 1: //~1000 indexer = createIndexerWithRandomPoints(sr, xmin, xmax, ymin, ymax, 3, 33, 33, 10f); break; case 2: // 100*100 indexer = createIndexerWithRandomPoints(sr, xmin, xmax, ymin, ymax, 3, 30, 60, 100.0f); break; case 3: { int[] clusterNumbers = new int[]{1000, 300, 100}; int nBackgroundPoints = 10000; CLUSTER_SEPARATION clusterSeparation = CLUSTER_SEPARATION.LARGE; indexer = createIndexerWithRandomPoints(sr, xmin, xmax, ymin, ymax, clusterNumbers, nBackgroundPoints, clusterSeparation); break; } default: { int[] clusterNumbers = new int[]{1000, 300, 100}; int nBackgroundPoints = 100000; CLUSTER_SEPARATION clusterSeparation = CLUSTER_SEPARATION.LARGE; indexer = generator.createIndexerWithRandomPoints(sr, xmin, xmax, ymin, ymax, clusterNumbers, nBackgroundPoints, clusterSeparation); break; } } //TODO: consider reverting this code... and adding the ability to plot to the // performance metrics log.info(" " + count + " (" + indexer.nXY + " points) ... "); if (writeToTmpData) { // write to tmpdata if need to use in tests improve fits, histogram etc String str = String.valueOf(count); while (str.length() < 3) { str = "0" + str; } String fileNamePostfix = "_clusters_" + str + ".dat"; String fileName = CreateClusterDataTest.indexerFileNamePrefix + fileNamePostfix; String filePath = ResourceFinder.getAFilePathInTmpData(fileName); CreateClusterDataTest.writeIndexer(filePath, indexer); } log.info(" " + count + " (" + indexer.nXY + " points) ... "); long t0 = System.currentTimeMillis(); TwoPointCorrelation twoPtC = new TwoPointCorrelation(indexer); //twoPtC.setDebug(true); if (i == 4) { //twoPtC.setAllowRefinement(); } twoPtC.logPerformanceMetrics(); //twoPtC.useFindMethodForDataWithoutBackgroundPoints(); twoPtC.calculateBackground(); //twoPtC.setBackground(0.2f, 0.1f); twoPtC.findClusters(); long t1 = (System.currentTimeMillis() - t0)/1000; log.info(i + ") ====> total RT(sec) = " + t1 + " nPoints=" + indexer.getNumberOfPoints()); String plotLabel = ""; TwoPointVoidStats stats = (TwoPointVoidStats)twoPtC.backgroundStats; if (twoPtC.backgroundStats != null && (twoPtC.backgroundStats instanceof TwoPointVoidStats)) { HistogramHolder histogram = stats.statsHistogram; GEVYFit bestFit = stats.bestFit; if (bestFit != null) { // label needs: x10, peak, mean/peak, median/mean and x80/median plotLabel = String.format( "(%d %d) k=%.4f s=%.4f m=%.4f chSq=%.6f chst=%.1f", i, ii, bestFit.getK(), bestFit.getSigma(), bestFit.getMu(), bestFit.getChiSqSum(), bestFit.getChiSqStatistic() ); if (debug) { log.info(plotLabel + " findVoid sampling=" + stats.getSampling().name()); } } } plotter.addPlot(twoPtC, plotLabel); plotter.writeFile(); } catch(Throwable e) { log.severe(e.getMessage()); } count++; } } log.info("\n start computing stats for all sets"); count = 0; log.info("SEED=" + seed); } }
7,131
0.46978
0.448044
178
39.061798
30.698271
117
false
false
0
0
0
0
0
0
0.825843
false
false
1
fdd79db7f403176e185d7341c876d02a22adc7e4
33,200,097,240,164
5f55c7fcecee8887e73b25ab38f6a476244da002
/ccdb2/src/main/java/com/shop/util/ccdb2/CCDB2UpdateIndexInterface.java
1a68f4dee3cdc87565369df2111cc8b3b20d9b85
[]
no_license
BillTheBest/sccache
https://github.com/BillTheBest/sccache
8c7f42fa18a57c1e781bb631b79ab2fd29e181bd
48483ae932641e95de2efa10ac2ded10dd877d9e
refs/heads/master
2020-12-27T15:35:49.526000
2011-09-02T07:09:59
2011-09-02T07:09:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2008-2009 SHOP.COM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.shop.util.ccdb2; /** * <br> * * @author Jordan Zimmerman */ interface CCDB2UpdateIndexInterface { /** * Used internally to update the index size * * @param key key * @param add true if being added, false otherwise */ public void updateIndexSize(String key, boolean add); }
UTF-8
Java
928
java
CCDB2UpdateIndexInterface.java
Java
[ { "context": "m.shop.util.ccdb2;\r\n\r\n/**\r\n * <br>\r\n *\r\n * @author Jordan Zimmerman\r\n */\r\ninterface CCDB2UpdateIndexInterface\r\n{\r\n\t/*", "end": 688, "score": 0.999790370464325, "start": 672, "tag": "NAME", "value": "Jordan Zimmerman" } ]
null
[]
/* * Copyright 2008-2009 SHOP.COM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.shop.util.ccdb2; /** * <br> * * @author <NAME> */ interface CCDB2UpdateIndexInterface { /** * Used internally to update the index size * * @param key key * @param add true if being added, false otherwise */ public void updateIndexSize(String key, boolean add); }
918
0.697198
0.682112
32
27.0625
26.356852
75
false
false
0
0
0
0
0
0
0.5
false
false
1
e58ac1264b4daf695323165ad9b8b39293c179f5
25,546,465,523,151
ead3ffd9e3959d790eed4d663fb623c27f1f2954
/WayBill/src/main/java/cn/fxtech/pfatwebsite/services/impl/MDorderpartService.java
9e55db0360f852dc054d93458ba5fc7528b36046
[]
no_license
fXStudio/WayBill
https://github.com/fXStudio/WayBill
9e0303f6887c794137b909d64947c0c314ab8278
d02099582c7e366d4461e9660b4785b6af57aa5d
refs/heads/master
2020-05-20T20:46:15.786000
2017-12-25T02:25:24
2017-12-25T02:25:24
84,520,999
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.fxtech.pfatwebsite.services.impl; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import cn.fxtech.pfatwebsite.mappers.MDorderpartMapper; import cn.fxtech.pfatwebsite.messages.FeedBackMessage; import cn.fxtech.pfatwebsite.models.MDorderpart; import cn.fxtech.pfatwebsite.models.MDpartinfo; import cn.fxtech.pfatwebsite.services.IMDorderpartService; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.entity.Example.Criteria; @Repository final class MDorderpartService implements IMDorderpartService { private Logger log = Logger.getLogger(MDorderpartService.class); private @Autowired MDorderpartMapper orderpartMapper; @Override public List<MDorderpart> findRecords(String orderid) { Example condition = new Example(MDorderpart.class); Criteria criteria = condition.createCriteria(); criteria.andEqualTo("orderid", orderid); condition.setOrderByClause("partno"); return orderpartMapper.selectByExample(condition); } @Override public FeedBackMessage del(Integer id) { return new FeedBackMessage(orderpartMapper.deleteByPrimaryKey(id) > 0); } @Override public Object addOrUpdate(Integer orderId, MDpartinfo[] items) { try { for (MDpartinfo item : items) { MDorderpart part = new MDorderpart(); part.setOrderid(orderId); part.setPartno(item.getCqadno()); part.setPkgcount(1); part.setPkgquantity(item.getCquantity()); part.setTotalcount(item.getCquantity()); part.setPartdesc(item.getCdesc()); part.setIsscan(item.getIsscan()); orderpartMapper.insertRecord(part); } return new FeedBackMessage(true); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } return new FeedBackMessage(false, "保存失败,请联系系统管理员"); } @Override public Object update(MDorderpart item) { if (item.getId() == 0) { return new FeedBackMessage(orderpartMapper.insertRecord(item) > 0, "新增失败,请联系系统管理员"); } return new FeedBackMessage(orderpartMapper.updateByPrimaryKey(item) > 0, "修改失败,请联系系统管理员"); } @Override public List<MDorderpart> findScanRecords(String orderid) { return orderpartMapper.findScanRecords(orderid); } }
UTF-8
Java
2,412
java
MDorderpartService.java
Java
[]
null
[]
package cn.fxtech.pfatwebsite.services.impl; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import cn.fxtech.pfatwebsite.mappers.MDorderpartMapper; import cn.fxtech.pfatwebsite.messages.FeedBackMessage; import cn.fxtech.pfatwebsite.models.MDorderpart; import cn.fxtech.pfatwebsite.models.MDpartinfo; import cn.fxtech.pfatwebsite.services.IMDorderpartService; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.entity.Example.Criteria; @Repository final class MDorderpartService implements IMDorderpartService { private Logger log = Logger.getLogger(MDorderpartService.class); private @Autowired MDorderpartMapper orderpartMapper; @Override public List<MDorderpart> findRecords(String orderid) { Example condition = new Example(MDorderpart.class); Criteria criteria = condition.createCriteria(); criteria.andEqualTo("orderid", orderid); condition.setOrderByClause("partno"); return orderpartMapper.selectByExample(condition); } @Override public FeedBackMessage del(Integer id) { return new FeedBackMessage(orderpartMapper.deleteByPrimaryKey(id) > 0); } @Override public Object addOrUpdate(Integer orderId, MDpartinfo[] items) { try { for (MDpartinfo item : items) { MDorderpart part = new MDorderpart(); part.setOrderid(orderId); part.setPartno(item.getCqadno()); part.setPkgcount(1); part.setPkgquantity(item.getCquantity()); part.setTotalcount(item.getCquantity()); part.setPartdesc(item.getCdesc()); part.setIsscan(item.getIsscan()); orderpartMapper.insertRecord(part); } return new FeedBackMessage(true); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } return new FeedBackMessage(false, "保存失败,请联系系统管理员"); } @Override public Object update(MDorderpart item) { if (item.getId() == 0) { return new FeedBackMessage(orderpartMapper.insertRecord(item) > 0, "新增失败,请联系系统管理员"); } return new FeedBackMessage(orderpartMapper.updateByPrimaryKey(item) > 0, "修改失败,请联系系统管理员"); } @Override public List<MDorderpart> findScanRecords(String orderid) { return orderpartMapper.findScanRecords(orderid); } }
2,412
0.746787
0.744216
73
29.972603
24.424316
92
false
false
0
0
0
0
0
0
1.917808
false
false
1
7544882a293dca6d0d6b277770229e4ba49dbb47
30,099,130,850,403
faab5bccac31c54c753f7826ba3484f7cdd56c58
/trunck/AP99/AP99-arap/AP99-arap-api/src/main/java/com/ebao/ap99/arap/constant/BizTransactionSubmitType.java
be3db6c4b0ff002a4734be137570e472978388a8
[]
no_license
semaxu/peakre
https://github.com/semaxu/peakre
19e99d83e54ef815f8e2e480f29ad65569136fbd
c64ed4d4af93dc2015846a613f493e17b8c6d1e9
refs/heads/master
2021-01-23T12:11:50.815000
2016-07-13T05:55:47
2016-07-13T05:55:47
62,941,992
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ebao.ap99.arap.constant; public enum BizTransactionSubmitType { NORMAL(1), SPECIAL_SUBMIT(2); private Integer value; private BizTransactionSubmitType(Integer value){ this.value = value; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } }
UTF-8
Java
330
java
BizTransactionSubmitType.java
Java
[]
null
[]
package com.ebao.ap99.arap.constant; public enum BizTransactionSubmitType { NORMAL(1), SPECIAL_SUBMIT(2); private Integer value; private BizTransactionSubmitType(Integer value){ this.value = value; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } }
330
0.718182
0.706061
21
14.714286
15.362734
49
false
false
0
0
0
0
0
0
1.190476
false
false
1
639c654a366eed253a1a08eafe6d97d9c76957de
25,838,523,301,654
535adb072fce09527b1ddbd9eeb5f9f63abce9d0
/experiment/src/main/java/zemberek/morphology/old_analysis/tr/TurkishSentenceAnalyzer.java
0690fb4bd2356dd9a32afa3759ae0cacd8f75667
[ "Apache-2.0" ]
permissive
kuzeygh/zemberek-nlp
https://github.com/kuzeygh/zemberek-nlp
8e47f115f8dfb05140022ab7953beb1d42362bef
978e1173342a0fe2d0af79258e84cf3e9795a165
refs/heads/master
2020-03-20T19:59:07.588000
2018-06-16T21:13:58
2018-06-16T21:13:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package zemberek.morphology.old_analysis.tr; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import java.io.File; import java.io.IOException; import java.util.List; import zemberek.core.io.Files; import zemberek.core.text.TextUtil; import zemberek.morphology.old_ambiguity.TurkishMorphDisambiguator; import zemberek.morphology.old_ambiguity.Z3MarkovModelDisambiguator; import zemberek.morphology.old_analysis.SentenceAnalysis; import zemberek.morphology.old_analysis.WordAnalysis; import zemberek.tokenization.TurkishTokenizer; public class TurkishSentenceAnalyzer { private TurkishMorphology turkishMorphology; private TurkishMorphDisambiguator disambiguator; private TurkishTokenizer lexer = TurkishTokenizer.DEFAULT; /** * Generates a TurkishSentenceAnalyzer from a resource directory. * Resource directory needs to have dictionary and disambiguator model files. * * @param dataDir directory with dictionary and model files. */ public TurkishSentenceAnalyzer(File dataDir) throws IOException { if (!dataDir.isDirectory()) { throw new IllegalArgumentException(dataDir + " is not a directory."); } if (!dataDir.exists()) { throw new IllegalArgumentException(dataDir + " Directory does not exist"); } List<File> dicFiles = Files.crawlDirectory(dataDir, false, Files.extensionFilter("dict")); System.out.println("Loading Dictionaries:" + dicFiles.toString()); if (dicFiles.size() == 0) { throw new IllegalArgumentException( "At least one dictionary file is required. (with txt extension)"); } turkishMorphology = TurkishMorphology.builder() .addTextDictionaries(dicFiles.toArray(new File[dicFiles.size()])).build(); System.out.println("Morph Parser Generated."); File rootSmoothLm = new File(dataDir, "root-lm.z3.slm"); File igSmoothLm = new File(dataDir, "ig-lm.z3.slm"); if (!rootSmoothLm.exists()) { throw new IllegalArgumentException("Cannot find root model in " + dataDir); } if (!igSmoothLm.exists()) { throw new IllegalArgumentException("Cannot find suffix model in " + dataDir); } disambiguator = new Z3MarkovModelDisambiguator(rootSmoothLm, igSmoothLm); System.out.println("Morph Disambiguator Generated."); } public TurkishSentenceAnalyzer( TurkishMorphology turkishMorphology, TurkishMorphDisambiguator disambiguator) { this.turkishMorphology = turkishMorphology; this.disambiguator = disambiguator; } public SentenceAnalysis analyze(String sentence) { SentenceAnalysis sentenceParse = new SentenceAnalysis(); String preprocessed = preProcess(sentence); for (String s : Splitter.on(" ").omitEmptyStrings().trimResults().split(preprocessed)) { List<WordAnalysis> parses = turkishMorphology.analyze(s); sentenceParse.addParse(s, parses); } return sentenceParse; } public void disambiguate(SentenceAnalysis parseResult) { disambiguator.disambiguate(parseResult); } public String preProcess(String str) { String quotesHyphensNormalized = TextUtil.normalizeQuotesHyphens(str); return Joiner.on(" ").join(lexer.tokenizeToStrings(quotesHyphensNormalized)); } /** * Returns the best parse of a sentence. * * @param sentence sentence * @return best parse. */ public List<WordAnalysis> bestParse(String sentence) { SentenceAnalysis parse = analyze(sentence); disambiguate(parse); List<WordAnalysis> bestParse = Lists.newArrayListWithCapacity(parse.size()); for (SentenceAnalysis.Entry entry : parse) { bestParse.add(entry.parses.get(0)); } return bestParse; } }
UTF-8
Java
3,723
java
TurkishSentenceAnalyzer.java
Java
[]
null
[]
package zemberek.morphology.old_analysis.tr; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import java.io.File; import java.io.IOException; import java.util.List; import zemberek.core.io.Files; import zemberek.core.text.TextUtil; import zemberek.morphology.old_ambiguity.TurkishMorphDisambiguator; import zemberek.morphology.old_ambiguity.Z3MarkovModelDisambiguator; import zemberek.morphology.old_analysis.SentenceAnalysis; import zemberek.morphology.old_analysis.WordAnalysis; import zemberek.tokenization.TurkishTokenizer; public class TurkishSentenceAnalyzer { private TurkishMorphology turkishMorphology; private TurkishMorphDisambiguator disambiguator; private TurkishTokenizer lexer = TurkishTokenizer.DEFAULT; /** * Generates a TurkishSentenceAnalyzer from a resource directory. * Resource directory needs to have dictionary and disambiguator model files. * * @param dataDir directory with dictionary and model files. */ public TurkishSentenceAnalyzer(File dataDir) throws IOException { if (!dataDir.isDirectory()) { throw new IllegalArgumentException(dataDir + " is not a directory."); } if (!dataDir.exists()) { throw new IllegalArgumentException(dataDir + " Directory does not exist"); } List<File> dicFiles = Files.crawlDirectory(dataDir, false, Files.extensionFilter("dict")); System.out.println("Loading Dictionaries:" + dicFiles.toString()); if (dicFiles.size() == 0) { throw new IllegalArgumentException( "At least one dictionary file is required. (with txt extension)"); } turkishMorphology = TurkishMorphology.builder() .addTextDictionaries(dicFiles.toArray(new File[dicFiles.size()])).build(); System.out.println("Morph Parser Generated."); File rootSmoothLm = new File(dataDir, "root-lm.z3.slm"); File igSmoothLm = new File(dataDir, "ig-lm.z3.slm"); if (!rootSmoothLm.exists()) { throw new IllegalArgumentException("Cannot find root model in " + dataDir); } if (!igSmoothLm.exists()) { throw new IllegalArgumentException("Cannot find suffix model in " + dataDir); } disambiguator = new Z3MarkovModelDisambiguator(rootSmoothLm, igSmoothLm); System.out.println("Morph Disambiguator Generated."); } public TurkishSentenceAnalyzer( TurkishMorphology turkishMorphology, TurkishMorphDisambiguator disambiguator) { this.turkishMorphology = turkishMorphology; this.disambiguator = disambiguator; } public SentenceAnalysis analyze(String sentence) { SentenceAnalysis sentenceParse = new SentenceAnalysis(); String preprocessed = preProcess(sentence); for (String s : Splitter.on(" ").omitEmptyStrings().trimResults().split(preprocessed)) { List<WordAnalysis> parses = turkishMorphology.analyze(s); sentenceParse.addParse(s, parses); } return sentenceParse; } public void disambiguate(SentenceAnalysis parseResult) { disambiguator.disambiguate(parseResult); } public String preProcess(String str) { String quotesHyphensNormalized = TextUtil.normalizeQuotesHyphens(str); return Joiner.on(" ").join(lexer.tokenizeToStrings(quotesHyphensNormalized)); } /** * Returns the best parse of a sentence. * * @param sentence sentence * @return best parse. */ public List<WordAnalysis> bestParse(String sentence) { SentenceAnalysis parse = analyze(sentence); disambiguate(parse); List<WordAnalysis> bestParse = Lists.newArrayListWithCapacity(parse.size()); for (SentenceAnalysis.Entry entry : parse) { bestParse.add(entry.parses.get(0)); } return bestParse; } }
3,723
0.73892
0.737309
100
36.209999
27.487196
94
false
false
0
0
0
0
0
0
0.52
false
false
1
d1641bb181ce30c33d2ce456e17fda66905d942b
19,104,014,579,191
58dc785b86f1cf50cb57fd62a958b29fa424c3e4
/src/test/tdl/Model.java
0332a7bd006d5efc5d5f2906c0b7896fc2c7a830
[]
no_license
EssexUniversityMCTS/essex-aihack
https://github.com/EssexUniversityMCTS/essex-aihack
267cbfc30477ae451f464a441c1c7762a10d4d54
db7b3b6bf95475b9934d6bde09739449b31813f4
refs/heads/master
2021-01-09T06:50:56.825000
2016-04-19T16:13:20
2016-04-19T16:13:20
53,842,569
1
1
null
true
2016-03-14T11:46:23
2016-03-14T09:19:41
2016-03-14T09:19:42
2016-03-14T11:46:22
20,884
0
0
0
Java
null
null
package test.tdl; import utilities.JEasyFrame; import utilities.StatSummary; import java.util.Random; import java.util.Arrays; import java.util.Scanner; import java.io.FileReader; public class Model { public double gamma = 1.0; public double lambda = 0.5; // alpha is the learning rate public double alpha = 0.1; public int nSuccess = 0; public int nSteps = 0; public int size = 15; public double epsilon = 0.1; double[] steps; double[] err; // this field is set and used to control // animation delay (to make it slow at first then speed up) int iteration; // rewards for non-goal, goal state public double[] rewards = {-1, 0}; public int[][] maze; public StatSummary run(int nEpisodes) throws Exception { StatSummary ss = new StatSummary(); steps = new double[nEpisodes]; err = new double[nEpisodes]; for (int i = 0; i < nEpisodes; i++) { iteration = i; double res = episode(); steps[i] = res; err[i] = valDiff(); ss.add(res); // System.out.println(i + "\t " + res); if (view != null) { Thread.sleep(delay(10)); } } return ss; } public void makeMaze() { maze = new int[size][size]; // try and read in a file try { FileReader f = new FileReader("c:/multimod/tdl/data/maze1.txt"); Scanner sc = new Scanner(f); for (int i=0; i<size; i++) { String s = sc.nextLine(); for (int j=0; j<s.length(); j++) { if (s.charAt(j) == 'M') maze[j][i] = 1; } } } catch(Exception e) { System.out.println("Unable to find maze file"); e.printStackTrace(); } } private double valDiff() { double err = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { err += Math.abs(v[i][j] + (Math.abs(i - goal[0]) + Math.abs(j - goal[1]))); } } return err / (size * size); } public void selfEval() throws Exception { int[] state = new int[2]; StatSummary ss = new StatSummary(); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { state[0] = i; state[1] = j; int cost = episode(state); ss.add(cost); // System.out.format("%d, %d, -> %d (v = %2.2f)\n", i, j, cost, v[i][j]); } } System.out.println(ss); } public void resetValues() { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { v[i][j] = 0; } } nSteps = 0; nSuccess = 0; } long delay(int i) throws Exception { return (i > 2 ? 50 : 200); } public void makeView() { view = new View(this, v); new JEasyFrame(view, "Grid View"); eview = new View(this, e); JEasyFrame el = new JEasyFrame(eview, "Eligibility"); el.setLocation(460, 0); } static Random r = new Random(); static int defaultSize = 15; // value table public double[][] v; // eligibility trace double[][] e; public int[] state; View view, eview; int maxIts = 2 * size * size; public int[] goal; // int[] state; int[][] actions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; public Model() { this(defaultSize); } public Model(int size) { this.size = size; v = new double[size][size]; e = new double[size][size]; state = new int[2]; goal = new int[]{size / 2, size / 2}; // cheat(); } public int episode() throws Exception { return episode(randState()); } public int episode(int[] state) throws Exception { // run an episode for a maximum number of iterations // int[] nextState; // copyState(state, prevState); this.state = state; // copyState(state, this.state); resetTrace(); for (int i = 0; i < maxIts; i++) { if (atGoal(state)) { nSuccess++; return i; } int[] action = getAction(state); int[] nextState = act(state, action); nSteps++; updateView(); double reward = atGoal(state) ? rewards[1] : rewards[0]; double delta = reward + gamma * value(nextState) - value(state); // System.out.println(value(prevState) + "\t " + value(state)); // update accumulating eligibility trace e[state[0]][state[1]]++; // updateValue(prevState, delta); // now update the states and traces // updateVE(); for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { v[j][k] += alpha * delta * e[j][k]; e[j][k] = e[j][k] * gamma * lambda; } } copyState(nextState, state); } return 2 * maxIts; } protected void resetTrace() { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { e[j][k] = 0; } } } // public void updateValue(int[] s, double delta) { // // v[s[0]][s[1]] += rate * delta; // } // private void updateView() throws Exception { if (view != null) { view.repaint(); eview.repaint(); // do the first iterations nice and slow if (iteration <= 2) Thread.sleep(100); } } protected void copyState(int[] a, int[] b) { b[0] = a[0]; b[1] = a[1]; } public boolean atGoal(int[] s) { return Arrays.equals(s, goal); } public int[] randState() { int[] s = new int[]{r.nextInt(size), r.nextInt(size)}; if (legal(s)) return s; else return randState(); } public int[] getAction(int[] state) { // consider all states that this action could lead to if (r.nextDouble() < epsilon) { return randLegalAction(state); } int best = 0; double bestScore = eval(state, actions[0]); for (int i = 1; i < actions.length; i++) { // apply the action and see what happens double score = eval(state, actions[i]); if (score > bestScore) { bestScore = score; best = i; } } return actions[best]; } public int[] randLegalAction(int[] s) { int[] act = actions[r.nextInt(actions.length)]; int[] next = act(s, act); if (legal(next)) { return act; } else { return randLegalAction(s); } } public double eval(int[] s, int[] a) { int[] next = act(s, a); if (!legal(next)) { // System.out.println("Illegal move attempt"); return Double.NEGATIVE_INFINITY; } double score = r.nextDouble() * 0.0001 + value(next); // System.out.println("Score: " + score); return score; } public boolean legal(int[] s) { return maze == null || maze[s[0]][s[1]] == 0; } public boolean legal(int i, int j) { return maze == null || maze[i][j] == 0; } public double value(int[] s) { if (atGoal(s)) { return 1; } else { return v[s[0]][s[1]]; } } public int[] act(int[] s, int[] a) { int[] ns = new int[s.length]; for (int i = 0; i < s.length; i++) { ns[i] = ((s[i] + a[i]) + size) % size; } return ns; } public void cheat() { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { v[i][j] = -(Math.abs(i - goal[0]) + Math.abs(j - goal[1])); } } } }
UTF-8
Java
8,148
java
Model.java
Java
[]
null
[]
package test.tdl; import utilities.JEasyFrame; import utilities.StatSummary; import java.util.Random; import java.util.Arrays; import java.util.Scanner; import java.io.FileReader; public class Model { public double gamma = 1.0; public double lambda = 0.5; // alpha is the learning rate public double alpha = 0.1; public int nSuccess = 0; public int nSteps = 0; public int size = 15; public double epsilon = 0.1; double[] steps; double[] err; // this field is set and used to control // animation delay (to make it slow at first then speed up) int iteration; // rewards for non-goal, goal state public double[] rewards = {-1, 0}; public int[][] maze; public StatSummary run(int nEpisodes) throws Exception { StatSummary ss = new StatSummary(); steps = new double[nEpisodes]; err = new double[nEpisodes]; for (int i = 0; i < nEpisodes; i++) { iteration = i; double res = episode(); steps[i] = res; err[i] = valDiff(); ss.add(res); // System.out.println(i + "\t " + res); if (view != null) { Thread.sleep(delay(10)); } } return ss; } public void makeMaze() { maze = new int[size][size]; // try and read in a file try { FileReader f = new FileReader("c:/multimod/tdl/data/maze1.txt"); Scanner sc = new Scanner(f); for (int i=0; i<size; i++) { String s = sc.nextLine(); for (int j=0; j<s.length(); j++) { if (s.charAt(j) == 'M') maze[j][i] = 1; } } } catch(Exception e) { System.out.println("Unable to find maze file"); e.printStackTrace(); } } private double valDiff() { double err = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { err += Math.abs(v[i][j] + (Math.abs(i - goal[0]) + Math.abs(j - goal[1]))); } } return err / (size * size); } public void selfEval() throws Exception { int[] state = new int[2]; StatSummary ss = new StatSummary(); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { state[0] = i; state[1] = j; int cost = episode(state); ss.add(cost); // System.out.format("%d, %d, -> %d (v = %2.2f)\n", i, j, cost, v[i][j]); } } System.out.println(ss); } public void resetValues() { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { v[i][j] = 0; } } nSteps = 0; nSuccess = 0; } long delay(int i) throws Exception { return (i > 2 ? 50 : 200); } public void makeView() { view = new View(this, v); new JEasyFrame(view, "Grid View"); eview = new View(this, e); JEasyFrame el = new JEasyFrame(eview, "Eligibility"); el.setLocation(460, 0); } static Random r = new Random(); static int defaultSize = 15; // value table public double[][] v; // eligibility trace double[][] e; public int[] state; View view, eview; int maxIts = 2 * size * size; public int[] goal; // int[] state; int[][] actions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; public Model() { this(defaultSize); } public Model(int size) { this.size = size; v = new double[size][size]; e = new double[size][size]; state = new int[2]; goal = new int[]{size / 2, size / 2}; // cheat(); } public int episode() throws Exception { return episode(randState()); } public int episode(int[] state) throws Exception { // run an episode for a maximum number of iterations // int[] nextState; // copyState(state, prevState); this.state = state; // copyState(state, this.state); resetTrace(); for (int i = 0; i < maxIts; i++) { if (atGoal(state)) { nSuccess++; return i; } int[] action = getAction(state); int[] nextState = act(state, action); nSteps++; updateView(); double reward = atGoal(state) ? rewards[1] : rewards[0]; double delta = reward + gamma * value(nextState) - value(state); // System.out.println(value(prevState) + "\t " + value(state)); // update accumulating eligibility trace e[state[0]][state[1]]++; // updateValue(prevState, delta); // now update the states and traces // updateVE(); for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { v[j][k] += alpha * delta * e[j][k]; e[j][k] = e[j][k] * gamma * lambda; } } copyState(nextState, state); } return 2 * maxIts; } protected void resetTrace() { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { e[j][k] = 0; } } } // public void updateValue(int[] s, double delta) { // // v[s[0]][s[1]] += rate * delta; // } // private void updateView() throws Exception { if (view != null) { view.repaint(); eview.repaint(); // do the first iterations nice and slow if (iteration <= 2) Thread.sleep(100); } } protected void copyState(int[] a, int[] b) { b[0] = a[0]; b[1] = a[1]; } public boolean atGoal(int[] s) { return Arrays.equals(s, goal); } public int[] randState() { int[] s = new int[]{r.nextInt(size), r.nextInt(size)}; if (legal(s)) return s; else return randState(); } public int[] getAction(int[] state) { // consider all states that this action could lead to if (r.nextDouble() < epsilon) { return randLegalAction(state); } int best = 0; double bestScore = eval(state, actions[0]); for (int i = 1; i < actions.length; i++) { // apply the action and see what happens double score = eval(state, actions[i]); if (score > bestScore) { bestScore = score; best = i; } } return actions[best]; } public int[] randLegalAction(int[] s) { int[] act = actions[r.nextInt(actions.length)]; int[] next = act(s, act); if (legal(next)) { return act; } else { return randLegalAction(s); } } public double eval(int[] s, int[] a) { int[] next = act(s, a); if (!legal(next)) { // System.out.println("Illegal move attempt"); return Double.NEGATIVE_INFINITY; } double score = r.nextDouble() * 0.0001 + value(next); // System.out.println("Score: " + score); return score; } public boolean legal(int[] s) { return maze == null || maze[s[0]][s[1]] == 0; } public boolean legal(int i, int j) { return maze == null || maze[i][j] == 0; } public double value(int[] s) { if (atGoal(s)) { return 1; } else { return v[s[0]][s[1]]; } } public int[] act(int[] s, int[] a) { int[] ns = new int[s.length]; for (int i = 0; i < s.length; i++) { ns[i] = ((s[i] + a[i]) + size) % size; } return ns; } public void cheat() { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { v[i][j] = -(Math.abs(i - goal[0]) + Math.abs(j - goal[1])); } } } }
8,148
0.464163
0.451522
299
26.250835
18.979675
89
false
false
0
0
0
0
0
0
0.702341
false
false
1
a8f8561f10739ac8974969983be4b3a35ace1422
12,635,793,853,711
6928eab9a131f2964602c3aec967e72c571262e6
/src/br/edu/ufcg/atal/miniteste06/Aresta.java
0e17ac1090822716020cbe72fdae0d89408b5e23
[]
no_license
vitorma/Bellman-Ford
https://github.com/vitorma/Bellman-Ford
e937fd24611fd55ec685e0f11731db0ad240382f
ce3ed2ce8e22565fc7643ac103fd57efa095f201
refs/heads/master
2016-09-06T15:40:09.045000
2012-10-31T14:48:30
2012-10-31T14:48:30
6,412,637
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Aresta.java * * Copyright 2012 Vitor Morato Almeida. * * This file is part of Bellman-Ford. * * Bellman-Ford is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MySeries is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Bellman-Ford. If not, see <http://www.gnu.org/licenses/>. */ package br.edu.ufcg.atal.miniteste06; public class Aresta { private No origem; private No destino; private double bandwidth; private double delay; public No getOrigem() { return origem; } public void setOrigem(No origem) { this.origem = origem; } public No getDestino() { return destino; } public void setDestino(No destino) { this.destino = destino; } public double getBandwidth() { return bandwidth; } public void setBandwidth(double bandwidth) { this.bandwidth = bandwidth; } public double getDelay() { return delay; } public void setDelay(double delay) { this.delay = delay; } }
UTF-8
Java
1,467
java
Aresta.java
Java
[ { "context": "/*\r\n * Aresta.java\r\n *\r\n * Copyright 2012 Vitor Morato Almeida.\r\n *\r\n * This file is part of Bellman-Ford.\r\n *", "end": 66, "score": 0.9997445940971375, "start": 46, "tag": "NAME", "value": "Vitor Morato Almeida" } ]
null
[]
/* * Aresta.java * * Copyright 2012 <NAME>. * * This file is part of Bellman-Ford. * * Bellman-Ford is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MySeries is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Bellman-Ford. If not, see <http://www.gnu.org/licenses/>. */ package br.edu.ufcg.atal.miniteste06; public class Aresta { private No origem; private No destino; private double bandwidth; private double delay; public No getOrigem() { return origem; } public void setOrigem(No origem) { this.origem = origem; } public No getDestino() { return destino; } public void setDestino(No destino) { this.destino = destino; } public double getBandwidth() { return bandwidth; } public void setBandwidth(double bandwidth) { this.bandwidth = bandwidth; } public double getDelay() { return delay; } public void setDelay(double delay) { this.delay = delay; } }
1,453
0.67621
0.671438
62
21.693548
23.209835
74
false
false
0
0
0
0
0
0
0.870968
false
false
1
23bf019fcd88128446832aeef1f76df165eece85
730,144,440,763
7b625331de9c6c0e17012cfba3844c074e77a320
/earlyWarningMonintoring/src/main/java/com/cetccity/operationcenter/webframework/urbansign/service/UrbanComponentService.java
15729713a1ccb1839d446672a4e6229aaecde596
[]
no_license
bellmit/hxc
https://github.com/bellmit/hxc
367e4dbf594dfdd357c0dd834c73b3bdf4110dc9
207ea79b99cc823acf829fbc0131df02e4743811
refs/heads/master
2023-07-18T18:45:44.289000
2019-08-07T08:55:29
2019-08-07T08:55:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cetccity.operationcenter.webframework.urbansign.service; import com.cetccity.operationcenter.webframework.core.frame.basicmodel.NameDataModel; import com.cetccity.operationcenter.webframework.core.frame.basicmodel.NameValueModel; import com.cetccity.operationcenter.webframework.urbansign.api.model.HeatMap; import java.io.IOException; import java.util.List; import java.util.Map; public interface UrbanComponentService { NameValueModel leftOne(String street); NameValueModel leftTwo(); List<NameValueModel> leftThree(String street); NameDataModel rigthOne(String street); List<NameValueModel> rigthTwo(String street)throws IOException; Map rigthThree(String street); HeatMap componentNumGradientLoadMap(String street); Map componentNumGradientTip(String id); }
UTF-8
Java
817
java
UrbanComponentService.java
Java
[]
null
[]
package com.cetccity.operationcenter.webframework.urbansign.service; import com.cetccity.operationcenter.webframework.core.frame.basicmodel.NameDataModel; import com.cetccity.operationcenter.webframework.core.frame.basicmodel.NameValueModel; import com.cetccity.operationcenter.webframework.urbansign.api.model.HeatMap; import java.io.IOException; import java.util.List; import java.util.Map; public interface UrbanComponentService { NameValueModel leftOne(String street); NameValueModel leftTwo(); List<NameValueModel> leftThree(String street); NameDataModel rigthOne(String street); List<NameValueModel> rigthTwo(String street)throws IOException; Map rigthThree(String street); HeatMap componentNumGradientLoadMap(String street); Map componentNumGradientTip(String id); }
817
0.810282
0.810282
28
28.178572
29.022224
86
false
false
0
0
0
0
0
0
0.535714
false
false
1
f531371d161636204eb05ad295ba152244c7521a
32,959,579,055,622
11a52de5c35156390a51b781a167944e378922f6
/src/main/java/edu/umd/enpm614/sample/aspect/log/LoggingAspect.java
d6dd4d6fca7c82b29f4099dd09039598d274c02d
[]
no_license
SoftwareTesting-Maintenance/sample-di-aop
https://github.com/SoftwareTesting-Maintenance/sample-di-aop
bf135470d91740579404e00bc99da940ccb94918
f1888b4e5ac8ffe376a76d5f0f799170f0d4b131
refs/heads/master
2022-02-21T15:43:49.494000
2022-02-18T02:38:34
2022-02-18T02:38:34
242,896,718
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.umd.enpm614.sample.aspect.log; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.springframework.stereotype.Component; import org.aspectj.lang.annotation.Aspect; @Aspect @Component public class LoggingAspect { @Around("within(edu.umd.enpm614.sample.*) && execution(public * do*(..))") public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { StringBuilder sb = new StringBuilder("Profile time for "); long startTime = System.nanoTime(); Object value = joinPoint.proceed(); sb.append(joinPoint.getSignature().getDeclaringTypeName()) .append(".") .append(joinPoint.getSignature().getName()) .append(" is ").append((System.nanoTime() - startTime)/1000000) .append(" ms"); System.out.println(sb.toString()); return value; } }
UTF-8
Java
933
java
LoggingAspect.java
Java
[]
null
[]
package edu.umd.enpm614.sample.aspect.log; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.springframework.stereotype.Component; import org.aspectj.lang.annotation.Aspect; @Aspect @Component public class LoggingAspect { @Around("within(edu.umd.enpm614.sample.*) && execution(public * do*(..))") public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { StringBuilder sb = new StringBuilder("Profile time for "); long startTime = System.nanoTime(); Object value = joinPoint.proceed(); sb.append(joinPoint.getSignature().getDeclaringTypeName()) .append(".") .append(joinPoint.getSignature().getName()) .append(" is ").append((System.nanoTime() - startTime)/1000000) .append(" ms"); System.out.println(sb.toString()); return value; } }
933
0.66881
0.654877
24
37.875
25.236073
84
false
false
0
0
0
0
0
0
0.458333
false
false
1
c5d97a4cb18885f8ddfb3ba162efcc2b2b3b2436
13,048,110,709,647
0ef305c925bfb8bc7feae176b78ad0b0f1751873
/StratServer/src/stratserver/mapgen/MapGen.java
62b4f0a680dfa259ca649e358d519526f85b3a0f
[]
no_license
drakemithras/ElAlkBead
https://github.com/drakemithras/ElAlkBead
ba8d1e575b429700e216b17ee9510e078d107dde
c531fe71c61c939412ab4759e8176933aaf610e2
refs/heads/master
2020-03-18T12:46:33.137000
2018-06-22T15:11:06
2018-06-22T15:11:06
134,743,402
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package stratserver.mapgen; import java.io.File; import java.util.List; import java.util.Random; import strat.objects.Battleground; import strat.objects.Constants; import strat.objects.Tile; import strat.objects.Unit; import stratserver.xml.XmlReader; /** * A kezdeti térkép generálását végző osztály * @author Ahkriin */ public class MapGen { private static Battleground bg; private static Tile[][] map; public static Battleground generate(){ map = new Tile[Constants.MAP_Y_SIZE][Constants.MAP_X_SIZE]; for (int idy = 0; idy < map.length; ++idy){ for (int idx = 0; idx < map[idy].length; ++idx){ map[idy][idx] = new Tile(); } } for (int idy = 0; idy < map.length; ++idy){ for (int idx = 5; idx < map[idy].length-5; ++idx){ Random r = new Random(); if (r.nextInt(100)<10){ map[idy][idx] = new Tile(false, 1); } } } List<Unit> units = XmlReader.readXml(new File("Game_units.xml")); int offset = 0; for (Unit unit : units){ map[0+offset][0] = unit; map[map.length-1-offset][0] = unit; unit.setPlayerTwoOwned(true); map[0+offset][map[0].length-1] = unit; map[map.length-1-offset][map[0].length-1] = unit; ++offset; } return new Battleground(map); } }
UTF-8
Java
1,697
java
MapGen.java
Java
[ { "context": "ezdeti térkép generálását végző osztály\n * @author Ahkriin\n */\npublic class MapGen {\n private static Batt", "end": 507, "score": 0.9981350898742676, "start": 500, "tag": "NAME", "value": "Ahkriin" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package stratserver.mapgen; import java.io.File; import java.util.List; import java.util.Random; import strat.objects.Battleground; import strat.objects.Constants; import strat.objects.Tile; import strat.objects.Unit; import stratserver.xml.XmlReader; /** * A kezdeti térkép generálását végző osztály * @author Ahkriin */ public class MapGen { private static Battleground bg; private static Tile[][] map; public static Battleground generate(){ map = new Tile[Constants.MAP_Y_SIZE][Constants.MAP_X_SIZE]; for (int idy = 0; idy < map.length; ++idy){ for (int idx = 0; idx < map[idy].length; ++idx){ map[idy][idx] = new Tile(); } } for (int idy = 0; idy < map.length; ++idy){ for (int idx = 5; idx < map[idy].length-5; ++idx){ Random r = new Random(); if (r.nextInt(100)<10){ map[idy][idx] = new Tile(false, 1); } } } List<Unit> units = XmlReader.readXml(new File("Game_units.xml")); int offset = 0; for (Unit unit : units){ map[0+offset][0] = unit; map[map.length-1-offset][0] = unit; unit.setPlayerTwoOwned(true); map[0+offset][map[0].length-1] = unit; map[map.length-1-offset][map[0].length-1] = unit; ++offset; } return new Battleground(map); } }
1,697
0.555358
0.542333
56
29.160715
20.826475
79
false
false
0
0
0
0
0
0
0.642857
false
false
1
9db07ec2d176e3ad63d377cff52d1ce1a5384660
4,063,039,064,872
8d35cef53e6f8e027f327e5335cc5889d5ba111d
/src/main/java/heigvd/bda/labs/utils/PRInputFormat.java
1e61d1cc903cf71e2c53a29805fac02794fa3eb4
[]
no_license
ice-blaze/PageRankBitcoin
https://github.com/ice-blaze/PageRankBitcoin
6728204bc2f34083777894bebc130d7b95013e73
897e0285957dab93c1035abd818ac6bb79c92834
refs/heads/master
2021-01-01T16:25:08.999000
2015-01-16T06:57:14
2015-01-16T06:57:14
28,786,846
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package heigvd.bda.labs.utils; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.sound.midi.SysexMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; public class PRInputFormat extends FileInputFormat<BitcoinAddress, BitcoinAddress> { static class PRRecordReader extends RecordReader<BitcoinAddress, BitcoinAddress> { FSDataInputStream reader; BitcoinAddress currentKey = new BitcoinAddress(); BitcoinAddress currentValue = new BitcoinAddress(); long byteRead = 0; long start = 0; long end = 0; static final Log LOG = LogFactory.getLog(PRRecordReader.class); @Override public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException, InterruptedException { FileSplit split = (FileSplit) genericSplit; Configuration job = context.getConfiguration(); final Path file = split.getPath(); FileSystem fs = file.getFileSystem(job); this.reader = fs.open(split.getPath()); this.start = split.getStart(); long rem = this.start % 40L; if (rem != 0) this.start -= rem; long size = split.getLength(); rem = size % 40L; if (rem != 0) size -= rem; this.end = this.start + size; this.reader.seek(this.start); LOG.info(String.format("PRRecordReader.initialize(), start: %d", this.start)); LOG.info(String.format("PRRecordReader.initialize(), end: %d", this.end)); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { if (this.start + this.byteRead >= this.end) return false; byte[] key = new byte[BitcoinAddress.SIZE]; byte[] value = new byte[BitcoinAddress.SIZE]; boolean eof = this.reader.read(key) < BitcoinAddress.SIZE || this.reader.read(value) < BitcoinAddress.SIZE; if (eof) { this.currentKey = null; this.currentValue = null; return false; } else { this.byteRead += 2 * BitcoinAddress.SIZE; this.currentKey.set(key); this.currentValue.set(value); return true; } } @Override public BitcoinAddress getCurrentKey() throws IOException, InterruptedException { return this.currentKey; } @Override public BitcoinAddress getCurrentValue() throws IOException, InterruptedException { return this.currentValue; } @Override public float getProgress() throws IOException, InterruptedException { if (this.start + this.byteRead >= this.end) return 1.0f; return (float)this.byteRead / (float)(this.end - this.start); } @Override public void close() throws IOException { this.reader.close(); this.currentKey = null; this.currentValue = null; } } @Override public RecordReader<BitcoinAddress, BitcoinAddress> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { // List<InputSplit> splits = super.getSplits(context); return new PRRecordReader(); } }
UTF-8
Java
3,770
java
PRInputFormat.java
Java
[]
null
[]
package heigvd.bda.labs.utils; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.sound.midi.SysexMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; public class PRInputFormat extends FileInputFormat<BitcoinAddress, BitcoinAddress> { static class PRRecordReader extends RecordReader<BitcoinAddress, BitcoinAddress> { FSDataInputStream reader; BitcoinAddress currentKey = new BitcoinAddress(); BitcoinAddress currentValue = new BitcoinAddress(); long byteRead = 0; long start = 0; long end = 0; static final Log LOG = LogFactory.getLog(PRRecordReader.class); @Override public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException, InterruptedException { FileSplit split = (FileSplit) genericSplit; Configuration job = context.getConfiguration(); final Path file = split.getPath(); FileSystem fs = file.getFileSystem(job); this.reader = fs.open(split.getPath()); this.start = split.getStart(); long rem = this.start % 40L; if (rem != 0) this.start -= rem; long size = split.getLength(); rem = size % 40L; if (rem != 0) size -= rem; this.end = this.start + size; this.reader.seek(this.start); LOG.info(String.format("PRRecordReader.initialize(), start: %d", this.start)); LOG.info(String.format("PRRecordReader.initialize(), end: %d", this.end)); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { if (this.start + this.byteRead >= this.end) return false; byte[] key = new byte[BitcoinAddress.SIZE]; byte[] value = new byte[BitcoinAddress.SIZE]; boolean eof = this.reader.read(key) < BitcoinAddress.SIZE || this.reader.read(value) < BitcoinAddress.SIZE; if (eof) { this.currentKey = null; this.currentValue = null; return false; } else { this.byteRead += 2 * BitcoinAddress.SIZE; this.currentKey.set(key); this.currentValue.set(value); return true; } } @Override public BitcoinAddress getCurrentKey() throws IOException, InterruptedException { return this.currentKey; } @Override public BitcoinAddress getCurrentValue() throws IOException, InterruptedException { return this.currentValue; } @Override public float getProgress() throws IOException, InterruptedException { if (this.start + this.byteRead >= this.end) return 1.0f; return (float)this.byteRead / (float)(this.end - this.start); } @Override public void close() throws IOException { this.reader.close(); this.currentKey = null; this.currentValue = null; } } @Override public RecordReader<BitcoinAddress, BitcoinAddress> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { // List<InputSplit> splits = super.getSplits(context); return new PRRecordReader(); } }
3,770
0.71061
0.707427
117
31.222221
28.398901
160
false
false
0
0
0
0
0
0
2.008547
false
false
1
28c9eb9d15fa8c83e6b57dc271ac6040113391f3
7,541,962,631,730
ab46235debbfd19f0ac5a9ff142b301eb9fb2f1c
/codefights/centuryFromYear.java
4cc6b2051088743ff4240d9439cda8a3b77472e7
[]
no_license
BalaS13/-JAVA-algorithm
https://github.com/BalaS13/-JAVA-algorithm
9e2b34ba0b16ae7adb745a27f0289fef0f08bc74
1d72fd78b9cdcffe1fd367a7732473e5c3516334
refs/heads/master
2021-12-17T17:35:04.164000
2017-09-21T15:44:40
2017-09-21T15:44:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc. Example For year = 1905, the output should be centuryFromYear(year) = 20; For year = 1700, the output should be centuryFromYear(year) = 17. Input/Output [time limit] 3000ms (java) [input] integer year A positive integer, designating the year. Guaranteed constraints: 1 ¡Â year ¡Â 2005. [output] integer The number of the century the year is in. */ public class centuryFromYear { int centuryFromYear(int year) { int result = 0; if( (year >= 1) && (year <= 2005) ){ if((year%100) == 0 ){ result = (year / 100); } else { result = ((year / 100)+1); } } return result; } }
WINDOWS-1252
Java
829
java
centuryFromYear.java
Java
[]
null
[]
/* Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc. Example For year = 1905, the output should be centuryFromYear(year) = 20; For year = 1700, the output should be centuryFromYear(year) = 17. Input/Output [time limit] 3000ms (java) [input] integer year A positive integer, designating the year. Guaranteed constraints: 1 ¡Â year ¡Â 2005. [output] integer The number of the century the year is in. */ public class centuryFromYear { int centuryFromYear(int year) { int result = 0; if( (year >= 1) && (year <= 2005) ){ if((year%100) == 0 ){ result = (year / 100); } else { result = ((year / 100)+1); } } return result; } }
829
0.646061
0.587879
36
21.916666
31.58795
186
false
false
0
0
0
0
0
0
0.583333
false
false
1
bb44c2b295855677d676f9aa038f74902deedd02
5,574,867,586,158
65b37f2e88087ca53071c28e94620d4e9e48da4a
/src/main/java/top/flyfire/weibo/observer/http/response/ReponseBuilder.java
67d084f4f107295b967355f2e7f506741249d55b
[]
no_license
dev-lluo/weibo-observer
https://github.com/dev-lluo/weibo-observer
a8b10f444a16d5b718d8cc01dbf861ad8b12fd82
c334e89c613855accfe2b8d89189067b12b3524d
refs/heads/master
2018-03-24T04:09:52.410000
2017-04-08T00:55:50
2017-04-08T00:55:50
86,708,999
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package top.flyfire.weibo.observer.http.response; import com.google.common.base.Optional; import java.util.Map; /** * Created by shyy_work on 2017/4/7. */ public interface ReponseBuilder<R,M> { R build(Optional<M> msg,Map extra); }
UTF-8
Java
243
java
ReponseBuilder.java
Java
[ { "context": "ptional;\n\nimport java.util.Map;\n\n/**\n * Created by shyy_work on 2017/4/7.\n */\npublic interface ReponseBuilder<", "end": 142, "score": 0.9996076822280884, "start": 133, "tag": "USERNAME", "value": "shyy_work" } ]
null
[]
package top.flyfire.weibo.observer.http.response; import com.google.common.base.Optional; import java.util.Map; /** * Created by shyy_work on 2017/4/7. */ public interface ReponseBuilder<R,M> { R build(Optional<M> msg,Map extra); }
243
0.716049
0.691358
14
16.357143
18.702969
49
false
false
0
0
0
0
0
0
0.428571
false
false
1
19db4dce7af224c7800aca5b866694e8ae4e764b
6,055,903,932,793
a839bdbe703b9081f1417d4a7538c7aca79c23a2
/app/src/main/java/com/ucuxin/ucuxin/tec/api/ShareAPI.java
9af9a06f284ea4500f952bd499e15295f59ebfa2
[]
no_license
13302864582/baifen_teacher_app
https://github.com/13302864582/baifen_teacher_app
8463cdd82dd1afd60beea0b9605eb8e2ff85acaf
9e8aa8c05ecdf31094674923f64e1caa9f5d0685
refs/heads/master
2020-07-09T11:04:21.537000
2019-08-27T06:12:37
2019-08-27T06:12:37
202,825,528
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ucuxin.ucuxin.tec.api; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSON; import com.android.volley.RequestQueue; import com.ucuxin.ucuxin.tec.base.BaseActivity; import com.ucuxin.ucuxin.tec.config.AppConfig; import com.ucuxin.ucuxin.tec.http.volley.VolleyRequestClientAPI; /** * 分享api * * @author sky * */ public class ShareAPI extends VolleyRequestClientAPI { /** * 我要分享 * * @param queue * @param taskid * @param kpoint * @param remark * @param sndfile * @param listener * @param requestCode */ public void wantToShare(RequestQueue queue, final BaseActivity listener, final int requestCode) { // http://www.welearn.com:8080/api/teacher/gopromotinos Map<String, Object> subParams = new HashMap<String, Object>(); String dataStr = JSON.toJSONString(subParams); requestHttpActivity(queue, HTTP_METHOD_POST, AppConfig.GO_URL + "teacher/gopromotinos", dataStr, listener, requestCode); } /** * 我的分享 * * @param queue * @param pagenum * @param pagecount * @param listener * @param requestCode */ public void myShareList(RequestQueue queue, int pagenum, int pagecount, final BaseActivity listener, final int requestCode) { // http://www.welearn.com:8080/api/teacher/mypromotinos Map<String, Object> subParams = new HashMap<String, Object>(); subParams.put("pagenum", pagenum); subParams.put("pagecount", pagecount); String dataStr = JSON.toJSONString(subParams); requestHttpActivity(queue, HTTP_METHOD_POST, AppConfig.GO_URL + "teacher/mypromotions", dataStr, listener, requestCode); } }
UTF-8
Java
1,633
java
ShareAPI.java
Java
[ { "context": "lleyRequestClientAPI;\n\n/**\n * 分享api\n * \n * @author sky\n *\n */\npublic class ShareAPI extends VolleyReques", "end": 351, "score": 0.9976004362106323, "start": 348, "tag": "USERNAME", "value": "sky" } ]
null
[]
package com.ucuxin.ucuxin.tec.api; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSON; import com.android.volley.RequestQueue; import com.ucuxin.ucuxin.tec.base.BaseActivity; import com.ucuxin.ucuxin.tec.config.AppConfig; import com.ucuxin.ucuxin.tec.http.volley.VolleyRequestClientAPI; /** * 分享api * * @author sky * */ public class ShareAPI extends VolleyRequestClientAPI { /** * 我要分享 * * @param queue * @param taskid * @param kpoint * @param remark * @param sndfile * @param listener * @param requestCode */ public void wantToShare(RequestQueue queue, final BaseActivity listener, final int requestCode) { // http://www.welearn.com:8080/api/teacher/gopromotinos Map<String, Object> subParams = new HashMap<String, Object>(); String dataStr = JSON.toJSONString(subParams); requestHttpActivity(queue, HTTP_METHOD_POST, AppConfig.GO_URL + "teacher/gopromotinos", dataStr, listener, requestCode); } /** * 我的分享 * * @param queue * @param pagenum * @param pagecount * @param listener * @param requestCode */ public void myShareList(RequestQueue queue, int pagenum, int pagecount, final BaseActivity listener, final int requestCode) { // http://www.welearn.com:8080/api/teacher/mypromotinos Map<String, Object> subParams = new HashMap<String, Object>(); subParams.put("pagenum", pagenum); subParams.put("pagecount", pagecount); String dataStr = JSON.toJSONString(subParams); requestHttpActivity(queue, HTTP_METHOD_POST, AppConfig.GO_URL + "teacher/mypromotions", dataStr, listener, requestCode); } }
1,633
0.726596
0.721637
61
25.442623
28.038921
108
false
false
0
0
0
0
0
0
1.52459
false
false
1
7134af3e7f0e1456c5a3e04ad34e62b8ceba90cb
20,959,440,408,815
afdfbb344b1f31fb49d9d71844855d84525751c4
/test/content/http/HTTPHeaderTest.java
5908b561147ff161809de61bd35bc7afa7851114
[]
no_license
OlexSMK/firstWebServer
https://github.com/OlexSMK/firstWebServer
91f2426064436fca6ab2be6382fcac4cb4f786b3
588735e8259ec7d610352d3758002f02a48325fb
refs/heads/master
2020-04-02T22:58:22.712000
2018-10-26T14:56:49
2018-10-26T14:56:49
154,843,935
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package content.http; import junit.framework.Assert; import org.junit.Test; import java.util.ArrayList; public class HTTPHeaderTest { @Test public void initialStateTest(){ HTTPHeader test = new HTTPHeader(); Assert.assertTrue("Not init yet",test.invalidContent()); Assert.assertEquals("Nothing generate",null,test.generate()); } @Test public void validHeaderTest(){ ArrayList<String> validHeader = new ArrayList<String>(); validHeader.add("HTTP/1.1"); validHeader.add("Data: Test"); HTTPHeader test = new HTTPHeader(); test.parse(validHeader); Assert.assertFalse("Header now valid",test.invalidContent()); Assert.assertEquals("Generated header = inital",validHeader,test.generate()); test.invalidate(); Assert.assertTrue("Header invalidated",test.invalidContent()); Assert.assertEquals("No header after invalidation",null,test.generate()); validHeader.remove(1); test.parse(validHeader); Assert.assertFalse("Header valid again",test.invalidContent()); Assert.assertEquals("Generated header = initial again",validHeader,test.generate()); } @Test public void invalidHeaderTest(){ ArrayList<String> wrongHeader = new ArrayList<String>(); wrongHeader.add("NOT A VERSION"); HTTPHeader test = new HTTPHeader(); test.parse(wrongHeader); Assert.assertTrue("Invalid header",test.invalidContent()); Assert.assertEquals("No header for invalid",null,test.generate()); } @Test public void endOfHeaderTest(){ Assert.assertFalse("More data expected",HTTPHeader.isEndOfHeader("HTTP/1.1")); Assert.assertTrue("Is is end",HTTPHeader.isEndOfHeader("")); } }
UTF-8
Java
1,844
java
HTTPHeaderTest.java
Java
[]
null
[]
package content.http; import junit.framework.Assert; import org.junit.Test; import java.util.ArrayList; public class HTTPHeaderTest { @Test public void initialStateTest(){ HTTPHeader test = new HTTPHeader(); Assert.assertTrue("Not init yet",test.invalidContent()); Assert.assertEquals("Nothing generate",null,test.generate()); } @Test public void validHeaderTest(){ ArrayList<String> validHeader = new ArrayList<String>(); validHeader.add("HTTP/1.1"); validHeader.add("Data: Test"); HTTPHeader test = new HTTPHeader(); test.parse(validHeader); Assert.assertFalse("Header now valid",test.invalidContent()); Assert.assertEquals("Generated header = inital",validHeader,test.generate()); test.invalidate(); Assert.assertTrue("Header invalidated",test.invalidContent()); Assert.assertEquals("No header after invalidation",null,test.generate()); validHeader.remove(1); test.parse(validHeader); Assert.assertFalse("Header valid again",test.invalidContent()); Assert.assertEquals("Generated header = initial again",validHeader,test.generate()); } @Test public void invalidHeaderTest(){ ArrayList<String> wrongHeader = new ArrayList<String>(); wrongHeader.add("NOT A VERSION"); HTTPHeader test = new HTTPHeader(); test.parse(wrongHeader); Assert.assertTrue("Invalid header",test.invalidContent()); Assert.assertEquals("No header for invalid",null,test.generate()); } @Test public void endOfHeaderTest(){ Assert.assertFalse("More data expected",HTTPHeader.isEndOfHeader("HTTP/1.1")); Assert.assertTrue("Is is end",HTTPHeader.isEndOfHeader("")); } }
1,844
0.649132
0.646421
50
34.880001
27.673553
92
false
false
0
0
0
0
0
0
0.92
false
false
1