blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
59eab4f0d12736184f82cde7de8a398f578a23dc
14c0c196dad3e37769e78dd7068053b4fb1101c2
/benchmark/src/main/java/org/bluir/core/Core.java
d8541eb6c095f7b7938ad3abb0994d9c8d5d5dea
[]
no_license
benjaminLedel/broccoli_replicationkit
e5d8d2f13e54151c22805d7fda5334a03a43854e
37a6f936a72b85b26ef98b9813ddfb453162408d
refs/heads/master
2022-12-24T16:49:45.995615
2020-09-24T23:58:23
2020-09-24T23:58:23
296,275,740
0
0
null
null
null
null
UTF-8
Java
false
false
5,550
java
package org.bluir.core; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import de.broccoli.BLAlgorithm; import de.broccoli.context.BroccoliContext; import de.broccoli.utils.indri.IndriUtil; import org.bluir.evaluation.Evaluation; import org.bluir.extraction.FactExtractor; import org.bluir.extraction.QueryExtractor; import org.eclipse.core.runtime.CoreException; public class Core implements BLAlgorithm { private final String indriBinPath = BroccoliContext.getInstance().getIndriPath(); private final String docsLocation = BroccoliContext.getInstance().getWorkDir() + BroccoliContext.getInstance().getSeparator() + "BLUIR" + BroccoliContext.getInstance().getSeparator() + "docs"; private final String indexLocation = BroccoliContext.getInstance().getWorkDir() + BroccoliContext.getInstance().getSeparator() + "BLUIR" + BroccoliContext.getInstance().getSeparator() + "index"; private final String queryFilePath = BroccoliContext.getInstance().getWorkDir() + BroccoliContext.getInstance().getSeparator() + "BLUIR" + BroccoliContext.getInstance().getSeparator() + "query"; private final String parameterFilePath = BroccoliContext.getInstance().getWorkDir() + BroccoliContext.getInstance().getSeparator() + "BLUIR" + BroccoliContext.getInstance().getSeparator() + "parameter.xml"; private final String indriQueryResult = BroccoliContext.getInstance().getWorkDir() + BroccoliContext.getInstance().getSeparator() + "BLUIR" + BroccoliContext.getInstance().getSeparator() +"indriQueryResult"; private final String workDir = BroccoliContext.getInstance().getWorkDir() + BroccoliContext.getInstance().getSeparator() + "BLUIR"; private int topN = BroccoliContext.getInstance().getTopN(); public void run() { File workspace = new File(workDir); workspace.mkdirs(); if (!createQueryIndex()) return; if (!createDocs()) return; if (!index()) return; if (!retrieve()) return; if (!evaluation()) return; System.out.println("finished"); } boolean createQueryIndex() { System.out.print("create query..."); try { int repoSize = QueryExtractor.extractSumDesField(queryFilePath); System.out.println(repoSize + " created successfully :-)"); } catch (IOException e) { e.printStackTrace(); } return true; } boolean createDocs() { try { System.out.print("create docs..."); if (!FactExtractor.extractEclipseFacts(BroccoliContext.getInstance().getSourceCodeDir(), docsLocation)) return false; int fileCount = BroccoliContext.getInstance().getContextVar("fileCount"); System.out.println(fileCount + " file processed!"); topN = fileCount; } catch (IOException | CoreException e) { e.printStackTrace(); return false; } catch (Exception e) { System.err.println("Error occurs when we're creating docs folder!"); e.printStackTrace(); return false; } return true; } boolean index() { try { System.out.print("Create indexes...."); // index Dir ���� ����. File indexDir = new File(indexLocation); if (!indexDir.exists()) if (!indexDir.mkdirs()) throw new Exception(); IndriUtil.createParametersFile(parameterFilePath,indexLocation,docsLocation); // program command String command = indriBinPath + "IndriBuildIndex\" " + parameterFilePath; // execute command BufferedWriter bw = new BufferedWriter(new FileWriter(this.workDir + BroccoliContext.getInstance().getSeparator() + "IndexLog.txt")); Process p = Runtime.getRuntime().exec(command); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { bw.write(line + "\n"); } p.waitFor(); bw.close(); // executeIndexCommand(command); System.out.println("successfully Done!"); } catch (IOException e) { e.printStackTrace(); System.err.println("Error occurs while we're working with file IO"); return false; } catch (Exception e) { e.printStackTrace(); System.err.println("Error occurs while we're working with process"); System.err.println("Stopping Execution...."); return false; } return true; } boolean retrieve() { System.out.print("Retrieval is in progress..."); BufferedWriter bw = null; try { String command = indriBinPath + "IndriRunQuery\" " + queryFilePath + " -count=" + topN + " -index=" + indexLocation + " -trecFormat=true -rule=method:tfidf,k1:1.0,b:0.3"; bw = new BufferedWriter(new FileWriter(this.indriQueryResult)); Process p = Runtime.getRuntime().exec(command); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { bw.write(line); bw.newLine(); } p.waitFor(); System.out.println("Done!"); } catch (IOException e1) { System.out.println("Problems with result file io"); return false; } catch (Exception e) { e.printStackTrace(); return false; } finally { try { bw.close(); } catch (IOException e) { e.printStackTrace(); System.out.println("Problems in closing results file after writing."); return false; } } return true; } boolean evaluation() { try { System.out.print("Evaluating...."); new Evaluation().evaluate(); System.out.println("Done!"); } catch (Exception e) { e.printStackTrace(); return false; } return true; } }
47d8630fc35123c2ae173fd8abdecf69e1259c99
25da7be8f51431080e5e8dd54ca2cdc89cb178f4
/main/java/com/example/sneakerup/controllers/RegistrationController.java
0bf260f8e1925e79e7d0b7291716569e00fb926a
[]
no_license
andreippsq/SneakerUp
c5dff874b14b110f656475067c56c47f4493ef8d
679c66ba13a27d3e62499ea892f6ef6b45b9a873
refs/heads/main
2023-05-02T16:17:23.072013
2021-05-16T18:40:53
2021-05-16T18:40:53
359,242,850
0
0
null
null
null
null
UTF-8
Java
false
false
1,216
java
package com.example.sneakerup.controllers; import com.example.sneakerup.other.User; import com.example.sneakerup.services.UserService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import java.sql.SQLException; @Controller public class RegistrationController { private final UserService userService = new UserService(); @GetMapping(value = "/register") public String showForm(Model model){ User user = new User(); model.addAttribute("user", user); return "register_form"; } @PostMapping(value = "/register") public String submitForm(@ModelAttribute("user") User user) throws SQLException, ClassNotFoundException { if(userService.userExists(user.getUsername())){ return "register_form"; } else userService.addUser(user.getName(), user.getUsername(), user.getEmail(), user.getPassword(), user.getAddress(), user.getTelephone()); return "register_success"; } }
6c47850db073ead19c168efe63a553e093fdaf30
71a3429d1e18fd3c83b7e08c07cee2c56e3cc15d
/Sum.java
3c460f380621995608f30383dcb436425cefabe9
[]
no_license
tesla32586974/-offer-
fce144e7538fff52e6a3098de3093a522c966152
2e7dd926ba0dde87bac438427fc9dd97ded92c06
refs/heads/master
2020-03-10T07:33:09.335639
2018-04-13T09:27:20
2018-04-13T09:27:20
129,265,067
0
0
null
null
null
null
UTF-8
Java
false
false
229
java
package algorithm; public class Sum { public int Add(int num1,int num2) { int num3 = num1 ^ num2; int num4 = (num1 & num2)<<1; if(num4 !=0 ) return Add(num3, num4); return num3; } }
88d7c3beb2e7284fe0622ef081c92d047062e43a
9cfba70490d5f6060f9a91a5b1ad11f40ada00b8
/src/main/java/com/ppx/cloud/repository/category/KnowledgeCategoryServiceImpl.java
333b85a22db5f039059c8e8a67f40739f99d5ed7
[]
no_license
mark-person/repository
a7b2c446cd76b0351164e01c08558d4000e0f618
ae12b98adfcdee7847237530ab0ad3f64abba838
refs/heads/master
2020-04-25T08:36:08.482838
2019-12-19T10:04:33
2019-12-19T10:04:33
172,652,726
0
0
null
null
null
null
UTF-8
Java
false
false
795
java
package com.ppx.cloud.repository.category; import java.util.List; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.stereotype.Service; import com.ppx.cloud.common.jdbc.MyDaoSupport; @Service public class KnowledgeCategoryServiceImpl extends MyDaoSupport implements KnowledgeCategoryService { public List<KnowledgeCategory> list() { String sql = "select cat_id, concat((select cat_name from repo_knowledge_category where cat_id = c.parent_id), '-', cat_name) cat_name " + "from repo_knowledge_category c where c.parent_id != 0 order by c.parent_id, c.cat_prio"; List<KnowledgeCategory> list = getJdbcTemplate().query(sql, BeanPropertyRowMapper.newInstance(KnowledgeCategory.class)); return list; } }
a6363cce23b0f783e56270f3ec2539b3dc1acf77
90d1144087e2b31e3b1a4284d36cd9714cbb4bc7
/MultiNdkDemo/src/main/java/com/xinghai/androidndkdemo/MainActivity.java
17a6d8f715cb2768fd4d6bb13da52d8695afc5eb
[ "Apache-2.0" ]
permissive
yuanbaoyu/AndroidNdkDemo
f47cd30f7dce6f29f693c703edb686c33c74a234
88f22b4d383a5b023afd209884c7ab4d0669c977
refs/heads/master
2020-03-18T09:04:53.629819
2018-05-25T06:39:50
2018-05-25T06:39:50
134,543,906
4
2
null
null
null
null
UTF-8
Java
false
false
538
java
package com.xinghai.androidndkdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.xinghai.multi.JniUtil; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = findViewById(R.id.sample_text); tv.setText(JniUtil.stringFromOne() + "\n" + JniUtil.stringFromTwo()); } }
5c9a75f4c9c2bc76d702d4c5af27f54d848b25c0
d3969992a540007afec9c24db8cb98725cbd92e0
/src/com/imc/imctools/controllers/BackdateProductController.java
4551dc74266fd060fa465f68824d65517f513891
[]
no_license
adrianfurukawa/JavaToolsProject
173d0409998708daae66edce3c3e43c5f4cc4f03
b256cf5f532de6480e9e267bb5c928059cc35364
refs/heads/master
2021-01-22T07:35:36.560034
2017-02-13T14:45:20
2017-02-13T14:45:20
81,835,362
0
0
null
null
null
null
UTF-8
Java
false
false
10,592
java
package com.imc.imctools.controllers; import com.imc.imctools.pojo.ClientPOJO; import com.imc.imctools.pojo.MemberPOJO; import com.imc.imctools.pojo.ProductPOJO; import com.imc.imctools.tools.Libs; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zul.*; import org.zkoss.zul.event.PagingEvent; import java.text.SimpleDateFormat; import java.util.List; /** * Created by faizal on 2/13/14. */ @SuppressWarnings("serial") public class BackdateProductController extends Window { private Logger log = LoggerFactory.getLogger(BackdateProductController.class); private Listbox lbClients; private Listbox lbProducts; private Paging pgClients; private Bandbox bbClient; private Bandbox bbProduct; private Datebox dCurrentStartDate; private Datebox dNewStartDate; private String whereClients; private String whereProducts; public void onCreate() { initComponents(); populateClients(0, pgClients.getPageSize()); } private void initComponents() { lbClients = (Listbox) getFellow("lbClients"); lbProducts = (Listbox) getFellow("lbProducts"); pgClients = (Paging) getFellow("pgClients"); bbClient = (Bandbox) getFellow("bbClient"); bbProduct = (Bandbox) getFellow("bbProduct"); dCurrentStartDate = (Datebox) getFellow("dCurrentStartDate"); dNewStartDate = (Datebox) getFellow("dNewStartDate"); pgClients.addEventListener("onPaging", new EventListener() { @Override public void onEvent(Event event) throws Exception { PagingEvent evt = (PagingEvent) event; populateClients(evt.getActivePage()*pgClients.getPageSize(), pgClients.getPageSize()); } }); } private void populateClients(int offset, int limit) { lbClients.getItems().clear(); Session s = Libs.sfDB.openSession(); try { String q0 = "select count(*) "; String q1 = "select " + "hinsid, hinsname, hinsdesc1 "; String q2 = "from idnhltpf.dbo.hltins "; String q3 = ""; String q4 = "order by hinsname asc "; if (!Libs.nn(whereClients).isEmpty()) { if (q3.isEmpty()) q3 += "where (" + whereClients + ") "; else q3 += "and (" + whereClients + ") "; } Integer rc = (Integer) s.createSQLQuery(q0 + q2 + q3).uniqueResult(); pgClients.setTotalSize(rc); List<Object[]> l = s.createSQLQuery(q1 + q2 + q3 + q4).setFirstResult(offset).setMaxResults(limit).list(); for (Object[] o : l) { ClientPOJO e = new ClientPOJO(); e.setClientId(Libs.nn(o[0]).trim()); e.setClientName(Libs.nn(o[1]).trim()); Listitem li = new Listitem(); li.setValue(e); li.appendChild(new Listcell(e.getClientId())); li.appendChild(new Listcell(e.getClientName())); li.appendChild(new Listcell(Libs.nn(o[2]).trim())); lbClients.appendChild(li); } } catch (Exception ex) { log.error("populateClients", ex); } finally { s.close(); } } private void populateProducts() { ClientPOJO clientPOJO = (ClientPOJO) bbClient.getAttribute("e"); lbProducts.getItems().clear(); Session s = Libs.sfDB.openSession(); try { String q1 = "select " + "hhdrpono, hhdryy, hhdrname, " + "(convert(varchar,hhdrsdtyy)+'-'+convert(varchar,hhdrsdtmm)+'-'+convert(varchar,hhdrsdtdd)) as sdt, " + "(convert(varchar,hhdredtyy)+'-'+convert(varchar,hhdredtmm)+'-'+convert(varchar,hhdredtdd)) as edt, " + "(convert(varchar,hhdrmdtyy)+'-'+convert(varchar,hhdrmdtmm)+'-'+convert(varchar,hhdrmdtdd)) as mdt, " + "(convert(varchar,hhdradtyy)+'-'+convert(varchar,hhdradtmm)+'-'+convert(varchar,hhdradtdd)) as adt "; String q2 = "from " + "idnhltpf.dbo.hlthdr "; String q3 = ""; String q4 = "order by hhdryy desc, hhdrname asc "; if (clientPOJO!=null) { q3 = "where hhdrinsid='" + clientPOJO.getClientId() + "' "; } if (whereProducts!=null) { if (!q3.isEmpty()) q3 += "and (" + whereProducts + ") "; else q3 += "where (" + whereProducts + ") "; } List<Object[]> l = s.createSQLQuery(q1 + q2 + q3 + q4).list(); for (Object[] o : l) { ProductPOJO e = new ProductPOJO(); e.setClientPOJO(clientPOJO); e.setProductId(Libs.nn(o[0])); e.setProductYear(Libs.nn(o[1])); e.setProductName(Libs.nn(o[2])); e.setStartingDate(new SimpleDateFormat("yyyy-MM-dd").parse(Libs.nn(o[3]))); e.setEffectiveDate(new SimpleDateFormat("yyyy-MM-dd").parse(Libs.nn(o[4]))); e.setMatureDate(new SimpleDateFormat("yyyy-MM-dd").parse(Libs.nn(o[5]))); Listitem li = new Listitem(); li.setValue(e); li.appendChild(new Listcell(e.getProductYear())); li.appendChild(new Listcell(e.getProductId())); li.appendChild(new Listcell(e.getProductName())); lbProducts.appendChild(li); } } catch (Exception ex) { log.error("populateProducts", ex); } finally { s.close(); } } public void clientSelected() { if (lbClients.getSelectedCount()==1) { ClientPOJO clientPOJO = lbClients.getSelectedItem().getValue(); bbClient.setText(clientPOJO.getClientName()); bbClient.setAttribute("e", clientPOJO); populateProducts(); bbClient.close(); } } public void quickSearchClients() { Textbox tQuickSearchClients = (Textbox) getFellow("tQuickSearchClients"); if (!tQuickSearchClients.getText().isEmpty()) { whereClients = "hinsname like '%" + tQuickSearchClients.getText() + "%' "; populateClients(0, pgClients.getPageSize()); pgClients.setActivePage(0); } else { refreshClients(); } } public void refreshClients() { whereClients = null; populateClients(0, pgClients.getPageSize()); } public void productSelected() { if (lbProducts.getSelectedCount()==1) { ProductPOJO productPOJO = lbProducts.getSelectedItem().getValue(); bbProduct.setText(productPOJO.getProductName()); bbProduct.setAttribute("e", productPOJO); Session s = Libs.sfDB.openSession(); try { String q = "select " + "hhdrsdtyy, hhdrsdtmm, hhdrsdtdd " + "from idnhltpf.dbo.hlthdr " + "where " + "hhdryy=" + productPOJO.getProductYear() + " " + "and hhdrpono=" + productPOJO.getProductId() + " "; Object[] o = (Object[]) s.createSQLQuery(q).uniqueResult(); if (o!=null) { String sdt = Libs.nn(o[0]) + "-" + Libs.nn(o[1]) + "-" + Libs.nn(o[2]); dCurrentStartDate.setValue(new SimpleDateFormat("yyyy-MM-dd").parse(sdt)); dNewStartDate.setValue(new SimpleDateFormat("yyyy-MM-dd").parse(sdt)); } } catch (Exception ex) { log.error("productSelected", ex); } finally { s.close(); } bbProduct.close(); } } public void quickSearchProducts() { Textbox tQuickSearchProducts = (Textbox) getFellow("tQuickSearchProducts"); if (!tQuickSearchProducts.getText().isEmpty()) { whereProducts = "hhdrname like '%" + tQuickSearchProducts.getText() + "%' or " + "convert(varchar,hhdrpono) like '%" + tQuickSearchProducts.getText() + "%' "; populateProducts(); } else { refreshProducts(); } } public void refreshProducts() { whereProducts = null; populateProducts(); } public void backdateProduct() { if (dNewStartDate.getText().isEmpty()) { Messagebox.show("Please input value to New Start Date", "Error", Messagebox.OK, Messagebox.ERROR); } else { if (Messagebox.show("Product and Dummy start date will be changed. Proceed?", "Confirmation", Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION, Messagebox.CANCEL)==Messagebox.OK) { ProductPOJO productPOJO = (ProductPOJO) bbProduct.getAttribute("e"); String sdt = new SimpleDateFormat("yyyy-MM-dd").format(dNewStartDate.getValue()); String q = "update [DB] " + "set " + "hhdrsdtyy=" + sdt.substring(0, 4) + ", " + "hhdrsdtmm=" + sdt.substring(5, 7) + ", " + "hhdrsdtdd=" + sdt.substring(8) + " " + "where " + "hhdryy=" + productPOJO.getProductYear() + " " + "and hhdrpono=" + productPOJO.getProductId() + " "; if (Libs.executeUpdate(q.replace("[DB]", "idnhltpf.dbo.hlthdr"), Libs.DB)) { q = "update [DB] " + "set " + "hdt2sdtyy=" + sdt.substring(0, 4) + ", " + "hdt2sdtmm=" + sdt.substring(5, 7) + ", " + "hdt2sdtdd=" + sdt.substring(8) + " " + "where " + "hdt2yy=" + productPOJO.getProductYear() + " " + "and hdt2pono=" + productPOJO.getProductId() + " " + "and hdt2idxno>90000 " + "and hdt2ctr=0 "; if (Libs.executeUpdate(q.replace("[DB]", "idnhltpf.dbo.hltdt2"), Libs.DB)) { Messagebox.show("Product Start Date has been changed", "Information", Messagebox.OK, Messagebox.INFORMATION); } } } } } }
f2c240b471765c7f9d06b8e8b0c4dad95a85e44a
6891eb2524b57128a17fd5bc0a0cfd0f485048c4
/src/com/mcxtzhang/algorithm/leetcode/array/Test581.java
33dae77b70766a03cafd784cef9ba98d05d1a5bc
[ "MIT" ]
permissive
mcxtzhang/TJ-notes
d6a0594405ff5ffea0ea7b2c505300e47a25fe12
9454937b53403c70007ba9e0d32c3df61da8bac3
refs/heads/master
2020-05-23T08:01:53.213842
2019-01-22T09:39:44
2019-01-22T09:39:44
80,487,759
2
0
null
null
null
null
UTF-8
Java
false
false
2,998
java
package com.mcxtzhang.algorithm.leetcode.array; import java.util.Arrays; /** * Intro: 581. Shortest Unsorted Continuous Subarray * Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. You need to find the shortest such subarray and output its length. Example 1: Input: [2, 6, 4, 8, 10, 9, 15] Output: 5 Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. Note: Then length of the input array is in range [1, 10,000]. The input array may contain duplicates, so ascending order here means <=. * Author: zhangxutong * E-mail: [email protected] * Home Page: http://blog.csdn.net/zxt0601 * Created: 2017/10/30. * History: */ public class Test581 { public static void main(String[] args) { int[] nums = new int[]{1, 3, 2, 2, 2}; new Solution().findUnsortedSubarray(nums); } static class Solution { public int findUnsortedSubarray(int[] nums) { //用一个 o N的空间,存放数组备份,排序,寻找头尾第一处不一样的地方,相减得到结果 int[] copy = nums.clone(); Arrays.sort(copy); int begin = -1 ; for(int i=0;i<nums.length;i++){ if(nums[i] != copy[i]){ begin = i; break; } } //有序 if(begin == -1) return 0; int end = begin+1; for(int i=nums.length-1; i>=end ;i--){ if(nums[i] != copy[i]){ end = i; break; } } return end - begin +1; } } // class Solution {//考虑只有一组数字逆序,即 1 2 4 3 5 6 , 这样 begin 是 2, end是3 pass // public int findUnsortedSubarray(int[] nums) { // //头尾两个指针,分别遍历, 尾指针的结束条件要是头指针的位置。 记录两个index,相减 得到结果 // int begin = -1; // for(int i=0;i<nums.length-1;i++){ // if(nums[i]> nums[i+1]){ // //要考虑重复的数字,比如 1 2 2 3 2 2 // while(i!=0 && nums[i] == nums[i-1]){ // i--; // } // begin = i; // break; // } // } // //本身已经有序 // if(begin==-1 )return 0; // int end = -1; // for(int i=nums.length-1;i>begin;i--){ // if(nums[i-1]>nums[i]){ // //要考虑重复的数字,比如 1 2 2 3 2 2 // while(i!=nums.length-1 && nums[i] == nums[i+1]){ // i++; // } // end = i; // break; // } // } // return end-begin+1; // } // } }
e04303b36961e00653087931f56ca1bb9e338b24
7bc0e996c31dccee472ef7503d75a2b9bc40b2e3
/SpookyShoots/src/com/me/TeamName/LoadContent.java
cc5cde1f1ab63a2c7cdafd42a49c976b7fce5e00
[]
no_license
Nathisgreen/SpookyShoots
c090661b0838f003f4cc3dc84cd013b655139430
2f438b1ad45618770a0bccd205e1f052fbc0cd64
refs/heads/master
2021-01-22T05:21:01.360647
2014-01-19T19:59:23
2014-01-19T19:59:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
719
java
package com.me.TeamName; import com.me.TeamName.Engine.ContentManager; import com.me.TeamName.Engine.Scene; import com.me.TeamName.Engine.SceneManager; public class LoadContent { public LoadContent(){ ContentManager.addFont("testFont", "data/fonts/AldoTheApache_20.fnt", "data/fonts/AldoTheApache_20.png", true); ContentManager.loadAtlas("data/Atlas/pack0/pack0.pack"); GameScene gameScene = new GameScene(); ShopScene shopScene = new ShopScene(); ShopBuyScene shopBuyScene = new ShopBuyScene(); //Quick test Scene SceneManager.addScene(gameScene); SceneManager.addScene(shopScene); SceneManager.addScene(shopBuyScene); SceneManager.switchScene("GameScene"); } }
151964490b210c086327e757d2dce2fddb6373c5
bfc1b4c27b78919df995cac44920e9763cc0f18e
/JElevator-JasonController/src/java/org/intranet/elevator/MorningTrafficElevatorSimulator.java
f16684fd5c8da1299f52cb37b1a3a7f88178c6e1
[]
no_license
ssardina-agts/elevator-JASON
06e38bceccb819f8d60dfe54ce36ff1958001add
78156162be40aa3392122c7552188fd93294eaf0
refs/heads/master
2020-12-08T07:47:45.511249
2014-11-26T20:57:50
2014-11-26T20:57:50
232,929,103
0
0
null
null
null
null
UTF-8
Java
false
false
3,622
java
/* * Copyright 2003 Neil McKellar and Chris Dailey * All rights reserved. */ package org.intranet.elevator; import java.util.Random; import org.intranet.elevator.model.Floor; import org.intranet.elevator.model.operate.Building; import org.intranet.elevator.model.operate.Person; import org.intranet.elevator.model.operate.controller.MetaController; import org.intranet.sim.Model; import org.intranet.sim.Simulator; import org.intranet.sim.event.Event; import org.intranet.ui.FloatParameter; import org.intranet.ui.IntegerParameter; import org.intranet.ui.LongParameter; /** * @author Neil McKellar and Chris Dailey * */ public class MorningTrafficElevatorSimulator extends Simulator { private IntegerParameter floorsParameter; private IntegerParameter carsParameter; private IntegerParameter ridersParameter; private FloatParameter durationParameter; private IntegerParameter stdDeviationParameter; private LongParameter seedParameter; private Building building; public MorningTrafficElevatorSimulator() { super(); floorsParameter = new IntegerParameter("Number of Floors",10); parameters.add(floorsParameter); carsParameter = new IntegerParameter("Number of Elevators",3); parameters.add(carsParameter); ridersParameter = new IntegerParameter("Number of People per Floor", 20); parameters.add(ridersParameter); durationParameter = new FloatParameter("Rider insertion time (hours)",1.0f); parameters.add(durationParameter); stdDeviationParameter = new IntegerParameter("Standard Deviation", 1); parameters.add(stdDeviationParameter); seedParameter = new LongParameter("Random seed", 635359); parameters.add(seedParameter); } public void initializeModel() { int numFloors = floorsParameter.getIntegerValue(); int numCars = carsParameter.getIntegerValue(); int numRiders = ridersParameter.getIntegerValue(); float duration = durationParameter.getFloatValue(); double durationInMs = duration * 3600.0 * 1000.0; int stdDeviation = stdDeviationParameter.getIntegerValue(); long seed = seedParameter.getLongValue(); building = new Building(getEventQueue(), numFloors, numCars, new MetaController()); // starting floor is the ground floor Floor startingFloor = building.getFloor(0); Random rand = new Random(seed); for (int i = 1; i < numFloors; i++) { final Floor destFloor = building.getFloor(i); for (int j = 0; j < numRiders; j++) { final Person person = building.createPerson(startingFloor); // time to insert // Convert a gaussian[-1, 1] to a gaussian[0, 1] double gaussian = (getGaussian(rand, stdDeviation) + 1) / 2; // Apply gaussian value to the duration (in hours) // and convert to milliseconds long insertTime = (long)(gaussian * durationInMs); // insertion event for destination at time Event event = new Event(insertTime) { public void perform() { person.setDestination(destFloor); } }; getEventQueue().addEvent(event); } } } public final Model getModel() { return building; } public String getDescription() { return "Morning Traffic Rider Insertion"; } public Simulator duplicate() { return new MorningTrafficElevatorSimulator(); } private static double getGaussian(Random rand, int stddev) { while (true) { double gaussian = rand.nextGaussian()/stddev; if (gaussian >= -1.0 && gaussian <= 1.0) return gaussian; } } }
752720efeef2178c03194774b224b920ce0856a8
30324f9737119ac5ea7827f530793f8cea19a004
/org.openntf.xpt.core/src/org/openntf/xpt/core/utils/NotesObjectRecycler.java
b694a2f2fbd8c7eb8c332a517512a0e943d8ece0
[ "LicenseRef-scancode-jdom", "ICU", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
OpenNTF/XPagesToolkit
270dbd2a58e8ecd9157e256ab476c476fb5082ef
570af080d2704b53b483350a4022ac7240348e20
refs/heads/master
2023-08-04T20:39:38.526068
2021-04-06T09:25:01
2021-04-06T09:25:01
10,921,208
2
5
Apache-2.0
2023-07-25T17:22:55
2013-06-24T21:50:26
Java
UTF-8
Java
false
false
1,367
java
/** * Copyright 2014, WebGate Consulting AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.openntf.xpt.core.utils; import java.util.ArrayList; import java.util.List; import org.openntf.xpt.core.utils.logging.LoggerFactory; import lotus.domino.Base; public class NotesObjectRecycler { public static void recycle(Base... recyclingObjects) { for (Base torecycle : recyclingObjects) { if (torecycle != null) { try { torecycle.recycle(); } catch (Exception ex) { LoggerFactory.logError(NotesObjectRecycler.class, "Error during recyle", ex); } } } } public static void recycleAll(List<?> all) { List<Base> toRecyle = new ArrayList(all.size()); for (Object obj:all) { if(obj instanceof Base) { toRecyle.add((Base)obj); } } recycle(toRecyle.toArray(new Base[toRecyle.size()])); } }
f5117f622daaa45809001c3cbaf7eded8bdf4a4e
8269775a1fca3d4980b557aebd3fe298d8093e93
/src/it/mbcraft/command_server/engine/core_commands/StopCommand.java
254360e9b93b8474a89d9a5fdd5f546dfa3c5c78
[ "MIT" ]
permissive
mbcraft/JavaCommandServer
a739e5cf47ac3a376ba18f30ed8781bc1d7b2cad
cc9e8959acbccd22db07c49f8286f4a26c1a371d
refs/heads/master
2021-01-01T03:49:48.296500
2016-04-23T09:42:22
2016-04-23T09:42:22
56,910,989
0
0
null
null
null
null
UTF-8
Java
false
false
841
java
/* * * Copyright MBCRAFT di Marco Bagnaresi - © 2013-2016 * All rights reserved - Tutti i diritti riservati * * Mail : info [ at ] mbcraft [ dot ] it * Web : http://www.mbcraft.it * */ package it.mbcraft.command_server.engine.core_commands; import it.mbcraft.command_server.engine.AbstractCommand; import it.mbcraft.command_server.engine.CommandServer; import it.mbcraft.command_server.engine.ExecutionException; /** * * @author Marco Bagnaresi <[email protected]> */ public class StopCommand extends AbstractCommand { @Override protected void executeImpl() throws ExecutionException { System.out.print("Stopping command server ..."); executionLog.append("COMMAND SERVER STOPPED."); CommandServer.getInstance().stop(); System.out.println("done!"); } }
9875dc5f9c20cf719f9d87d92b9f2bab9e25cb96
14e7c41ffc898dcb30005141ed4d1f20a1eecbca
/umeng_community_library/src/main/java/com/umeng/comm/ui/presenter/impl/AtMeFeedPresenter.java
793081a33f861c8060bfae0730ab8678ba32f504
[]
no_license
ljyao/CampusMoment
55eb4da815750ed7d9ba29161622901409ea8920
2a94c94485c961535e169df5200e95e7f626a5ac
refs/heads/master
2021-01-21T04:44:46.491538
2016-06-02T14:07:24
2016-06-02T14:07:24
50,668,406
0
0
null
null
null
null
UTF-8
Java
false
false
1,677
java
/* * The MIT License (MIT) * * Copyright (c) 2014-2015 Umeng, Inc * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.umeng.comm.ui.presenter.impl; import com.umeng.comm.ui.mvpview.MvpFeedView; /** * 消息通知 Presenter * * @author mrsimple */ public class AtMeFeedPresenter extends FeedListPresenter { public AtMeFeedPresenter(MvpFeedView view) { super(view); } @Override public void loadDataFromServer() { mCommunitySDK.fetchBeAtFeeds(0, mRefreshListener); } @Override public void loadDataFromDB() { } @Override public void loadFeedsFromDB(String uid) { } }
ce3ae077dc3ae3bc02db69ba069ca0b618e42397
7c462adab2fde7af3025c0e82faaa17f22af7384
/src/main/java/com/google/common/io/CharSequenceReader.java
38cb959866861746d62a8133ebab74b5f69fa44e
[]
no_license
jbock-java/guava
10690bc67cf1057332cbb27e683472b476bbb004
1a42ba97cb814a9ddf3a6692df9211e563b3bedf
refs/heads/master
2022-07-28T07:45:35.385779
2021-12-25T13:19:58
2021-12-25T13:19:58
424,536,360
0
0
null
null
null
null
UTF-8
Java
false
false
4,667
java
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * 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.google.common.io; import java.io.IOException; import java.io.Reader; import java.nio.CharBuffer; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import static java.util.Objects.requireNonNull; /** * A {@link Reader} that reads the characters in a {@link CharSequence}. Like {@code StringReader}, * but works with any {@link CharSequence}. * * @author Colin Decker */ // TODO(cgdecker): make this public? as a type, or a method in CharStreams? final class CharSequenceReader extends Reader { private CharSequence seq; private int pos; private int mark; /** Creates a new reader wrapping the given character sequence. */ public CharSequenceReader(CharSequence seq) { this.seq = checkNotNull(seq); } private void checkOpen() throws IOException { if (seq == null) { throw new IOException("reader closed"); } } private boolean hasRemaining() { return remaining() > 0; } private int remaining() { requireNonNull(seq); // safe as long as we call this only after checkOpen return seq.length() - pos; } /* * To avoid the need to call requireNonNull so much, we could consider more clever approaches, * such as: * * - Make checkOpen return the non-null `seq`. Then callers can assign that to a local variable or * even back to `this.seq`. However, that may suggest that we're defending against concurrent * mutation, which is not an actual risk because we use `synchronized`. * - Make `remaining` require a non-null `seq` argument. But this is a bit weird because the * method, while it would avoid the instance field `seq` would still access the instance field * `pos`. */ @Override public synchronized int read(CharBuffer target) throws IOException { checkNotNull(target); checkOpen(); requireNonNull(seq); // safe because of checkOpen if (!hasRemaining()) { return -1; } int charsToRead = Math.min(target.remaining(), remaining()); for (int i = 0; i < charsToRead; i++) { target.put(seq.charAt(pos++)); } return charsToRead; } @Override public synchronized int read() throws IOException { checkOpen(); requireNonNull(seq); // safe because of checkOpen return hasRemaining() ? seq.charAt(pos++) : -1; } @Override public synchronized int read(char[] cbuf, int off, int len) throws IOException { checkPositionIndexes(off, off + len, cbuf.length); checkOpen(); requireNonNull(seq); // safe because of checkOpen if (!hasRemaining()) { return -1; } int charsToRead = Math.min(len, remaining()); for (int i = 0; i < charsToRead; i++) { cbuf[off + i] = seq.charAt(pos++); } return charsToRead; } @Override public synchronized long skip(long n) throws IOException { checkArgument(n >= 0, "n (%s) may not be negative", n); checkOpen(); int charsToSkip = (int) Math.min(remaining(), n); // safe because remaining is an int pos += charsToSkip; return charsToSkip; } @Override public synchronized boolean ready() throws IOException { checkOpen(); return true; } @Override public boolean markSupported() { return true; } @Override public synchronized void mark(int readAheadLimit) throws IOException { checkArgument(readAheadLimit >= 0, "readAheadLimit (%s) may not be negative", readAheadLimit); checkOpen(); mark = pos; } @Override public synchronized void reset() throws IOException { checkOpen(); pos = mark; } @Override public synchronized void close() throws IOException { seq = null; } }
3e038493af83634d77ce77aee1bc37206536ee35
0753867c790281239b8f213ac547d5b6a8451a33
/ex_lib/mini_rt/src/java/util/ArrayList.java
3a69b4ef42b902df20f6e62c5971913ccbced1ba
[ "LicenseRef-scancode-public-domain" ]
permissive
zhujiabin/miniJVM
386325e8554a6cbaa2442096a16b91767d75d4a7
4ae1cd1a40c5e23cb8f4bec0ebe1a3b94c611d8c
refs/heads/master
2020-04-28T05:57:09.444049
2019-03-07T08:17:27
2019-03-07T08:17:27
175,038,279
1
0
null
2019-03-11T16:14:52
2019-03-11T16:14:51
null
UTF-8
Java
false
false
21,851
java
package java.util; import java.lang.Cloneable; /* * @(#)ArrayList.java 1.49 05/03/03 * * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /** * Resizable-array implementation of the <tt>List</tt> interface. Implements * all optional list operations, and permits all elements, including * <tt>null</tt>. In addition to implementing the <tt>List</tt> interface, * this class provides methods to manipulate the size of the array that is * used internally to store the list. (This class is roughly equivalent to * <tt>Vector</tt>, except that it is unsynchronized.)<p> * * The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>, * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant * time. The <tt>add</tt> operation runs in <i>amortized constant time</i>, * that is, adding n elements requires O(n) time. All of the other operations * run in linear time (roughly speaking). The constant factor is low compared * to that for the <tt>LinkedList</tt> implementation.<p> * * Each <tt>ArrayList</tt> instance has a <i>capacity</i>. The capacity is * the size of the array used to store the elements in the list. It is always * at least as large as the list size. As elements are added to an ArrayList, * its capacity grows automatically. The details of the growth policy are not * specified beyond the fact that adding an element has constant amortized * time cost.<p> * * An application can increase the capacity of an <tt>ArrayList</tt> instance * before adding a large number of elements using the <tt>ensureCapacity</tt> * operation. This may reduce the amount of incremental reallocation.<p> * * <strong>Note that this implementation is not synchronized.</strong> If * multiple threads access an <tt>ArrayList</tt> instance concurrently, and at * least one of the threads modifies the list structurally, it <i>must</i> be * synchronized externally. (A structural modification is any operation that * adds or deletes one or more elements, or explicitly resizes the backing * array; merely setting the value of an element is not a structural * modification.) This is typically accomplished by synchronizing on some * object that naturally encapsulates the list. If no such object exists, the * list should be "wrapped" using the <tt>Collections.synchronizedList</tt> * method. This is best done at creation time, to prevent accidental * unsynchronized access to the list: * <pre> * List list = Collections.synchronizedList(new ArrayList(...)); * </pre><p> * * The iterators returned by this class's <tt>iterator</tt> and * <tt>listIterator</tt> methods are <i>fail-fast</i>: if list is structurally * modified at any time after the iterator is created, in any way except * through the iterator's own remove or add methods, the iterator will throw a * ConcurrentModificationException. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the * future.<p> * * Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i><p> * * This class is a member of the * <a href="{@docRoot}/../guide/collections/index.html"> * Java Collections Framework</a>. * * @author Josh Bloch * @author Neal Gafter * @version 1.49, 03/03/05 * @see Collection * @see List * @see LinkedList * @see Vector * @see Collections#synchronizedList(List) * @since 1.2 */ public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess { private static final long serialVersionUID = 8683452581122892189L; /** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. */ private transient E[] elementData; /** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size; /** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list. * @exception IllegalArgumentException if the specified initial capacity * is negative */ public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = (E[])new Object[initialCapacity]; } /** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this(10); } /** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. The <tt>ArrayList</tt> instance has an initial capacity of * 110% the size of the specified collection. * * @param c the collection whose elements are to be placed into this list. * @throws NullPointerException if the specified collection is null. */ public ArrayList(Collection<? extends E> c) { size = c.size(); // Allow 10% room for growth elementData = (E[])new Object[ (int)Math.min((size*110L)/100,Integer.MAX_VALUE)]; c.toArray(elementData); } /** * Trims the capacity of this <tt>ArrayList</tt> instance to be the * list's current size. An application can use this operation to minimize * the storage of an <tt>ArrayList</tt> instance. */ public void trimToSize() { modCount++; int oldCapacity = elementData.length; if (size < oldCapacity) { Object oldData[] = elementData; elementData = (E[])new Object[size]; System.arraycopy(oldData, 0, elementData, 0, size); } } /** * Increases the capacity of this <tt>ArrayList</tt> instance, if * necessary, to ensure that it can hold at least the number of elements * specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity. */ public void ensureCapacity(int minCapacity) { modCount++; int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData[] = elementData; int newCapacity = (oldCapacity * 3)/2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; elementData = (E[])new Object[newCapacity]; System.arraycopy(oldData, 0, elementData, 0, size); } } /** * Returns the number of elements in this list. * * @return the number of elements in this list. */ public int size() { return size; } /** * Tests if this list has no elements. * * @return <tt>true</tt> if this list has no elements; * <tt>false</tt> otherwise. */ public boolean isEmpty() { return size == 0; } /** * Returns <tt>true</tt> if this list contains the specified element. * * @param elem element whose presence in this List is to be tested. * @return <code>true</code> if the specified element is present; * <code>false</code> otherwise. */ public boolean contains(Object elem) { return indexOf(elem) >= 0; } /** * Searches for the first occurence of the given argument, testing * for equality using the <tt>equals</tt> method. * * @param elem an object. * @return the index of the first occurrence of the argument in this * list; returns <tt>-1</tt> if the object is not found. * @see Object#equals(Object) */ public int indexOf(Object elem) { if (elem == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (elem.equals(elementData[i])) return i; } return -1; } /** * Returns the index of the last occurrence of the specified object in * this list. * * @param elem the desired element. * @return the index of the last occurrence of the specified object in * this list; returns -1 if the object is not found. */ public int lastIndexOf(Object elem) { if (elem == null) { for (int i = size-1; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = size-1; i >= 0; i--) if (elem.equals(elementData[i])) return i; } return -1; } /** * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The * elements themselves are not copied.) * * @return a clone of this <tt>ArrayList</tt> instance. */ // public Object clone() { // try { // ArrayList<E> v = (ArrayList<E>) super.clone(); // v.elementData = (E[])new Object[size]; // System.arraycopy(elementData, 0, v.elementData, 0, size); // v.modCount = 0; // return v; // } catch (CloneNotSupportedException e) { // // this shouldn't happen, since we are Cloneable // throw new InternalError(); // } // } /** * Returns an array containing all of the elements in this list * in the correct order. * * @return an array containing all of the elements in this list * in the correct order. */ public Object[] toArray() { Object[] result = new Object[size]; System.arraycopy(elementData, 0, result, 0, size); return result; } /** * Returns an array containing all of the elements in this list in the * correct order; the runtime type of the returned array is that of the * specified array. If the list fits in the specified array, it is * returned therein. Otherwise, a new array is allocated with the runtime * type of the specified array and the size of this list.<p> * * If the list fits in the specified array with room to spare (i.e., the * array has more elements than the list), the element in the array * immediately following the end of the collection is set to * <tt>null</tt>. This is useful in determining the length of the list * <i>only</i> if the caller knows that the list does not contain any * <tt>null</tt> elements. * * @param a the array into which the elements of the list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the list. * @throws ArrayStoreException if the runtime type of a is not a supertype * of the runtime type of every element in this list. */ public <T> T[] toArray(T[] a) { if (a.length < size) // a = (Object[])java.lang.reflect.Array.newInstance( // a.getClass().getComponentType(), size); a=(T[])new Object[size]; System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } // Positional Access Operations /** * Returns the element at the specified position in this list. * * @param index index of element to return. * @return the element at the specified position in this list. * @throws IndexOutOfBoundsException if index is out of range <tt>(index * &lt; 0 || index &gt;= size())</tt>. */ public E get(int index) { RangeCheck(index); return elementData[index]; } /** * Replaces the element at the specified position in this list with * the specified element. * * @param index index of element to replace. * @param element element to be stored at the specified position. * @return the element previously at the specified position. * @throws IndexOutOfBoundsException if index out of range * <tt>(index &lt; 0 || index &gt;= size())</tt>. */ public E set(int index, E element) { RangeCheck(index); E oldValue = elementData[index]; elementData[index] = element; return oldValue; } /** * Appends the specified element to the end of this list. * * @param o element to be appended to this list. * @return <tt>true</tt> (as per the general contract of Collection.add). */ public boolean add(E o) { ensureCapacity(size + 1); // Increments modCount!! elementData[size++] = o; return true; } /** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted. * @param element element to be inserted. * @throws IndexOutOfBoundsException if index is out of range * <tt>(index &lt; 0 || index &gt; size())</tt>. */ public void add(int index, E element) { if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size); ensureCapacity(size+1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to removed. * @return the element that was removed from the list. * @throws IndexOutOfBoundsException if index out of range <tt>(index * &lt; 0 || index &gt;= size())</tt>. */ public E remove(int index) { RangeCheck(index); modCount++; E oldValue = elementData[index]; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work return oldValue; } /** * Removes a single instance of the specified element from this * list, if it is present (optional operation). More formally, * removes an element <tt>e</tt> such that <tt>(o==null ? e==null : * o.equals(e))</tt>, if the list contains one or more such * elements. Returns <tt>true</tt> if the list contained the * specified element (or equivalently, if the list changed as a * result of the call).<p> * * @param o element to be removed from this list, if present. * @return <tt>true</tt> if the list contained the specified element. */ public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } /* * Private remove method that skips bounds checking and does not * return the value removed. */ private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work } /** * Removes all of the elements from this list. The list will * be empty after this call returns. */ public void clear() { modCount++; // Let gc do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } /** * Appends all of the elements in the specified Collection to the end of * this list, in the order that they are returned by the * specified Collection's Iterator. The behavior of this operation is * undefined if the specified Collection is modified while the operation * is in progress. (This implies that the behavior of this call is * undefined if the specified Collection is this list, and this * list is nonempty.) * * @param c the elements to be inserted into this list. * @return <tt>true</tt> if this list changed as a result of the call. * @throws NullPointerException if the specified collection is null. */ public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacity(size + numNew); // Increments modCount System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; } /** * Inserts all of the elements in the specified Collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in the list in the order that they are returned by the * specified Collection's iterator. * * @param index index at which to insert first element * from the specified collection. * @param c elements to be inserted into this list. * @return <tt>true</tt> if this list changed as a result of the call. * @throws IndexOutOfBoundsException if index out of range <tt>(index * &lt; 0 || index &gt; size())</tt>. * @throws NullPointerException if the specified Collection is null. */ public boolean addAll(int index, Collection<? extends E> c) { if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: " + index + ", Size: " + size); Object[] a = c.toArray(); int numNew = a.length; ensureCapacity(size + numNew); // Increments modCount int numMoved = size - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; } /** * Removes from this List all of the elements whose index is between * fromIndex, inclusive and toIndex, exclusive. Shifts any succeeding * elements to the left (reduces their index). * This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements. * (If <tt>toIndex==fromIndex</tt>, this operation has no effect.) * * @param fromIndex index of first element to be removed. * @param toIndex index after last element to be removed. */ protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // Let gc do its work int newSize = size - (toIndex-fromIndex); while (size != newSize) elementData[--size] = null; } /** * Check if the given index is in range. If not, throw an appropriate * runtime exception. This method does *not* check if the index is * negative: It is always used immediately prior to an array access, * which throws an ArrayIndexOutOfBoundsException if index is negative. */ private void RangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size); } /** * Save the state of the <tt>ArrayList</tt> instance to a stream (that * is, serialize it). * * @serialData The length of the array backing the <tt>ArrayList</tt> * instance is emitted (int), followed by all of its elements * (each an <tt>Object</tt>) in the proper order. */ // private void writeObject(java.io.ObjectOutputStream s) // throws java.io.IOException{ // int expectedModCount = modCount; // // Write out element count, and any hidden stuff // s.defaultWriteObject(); // // // Write out array length // s.writeInt(elementData.length); // // // Write out all elements in the proper order. // for (int i=0; i<size; i++) // s.writeObject(elementData[i]); // // if (modCount != expectedModCount) { // throw new ConcurrentModificationException(); // } // } /** * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is, * deserialize it). */ // private void readObject(java.io.ObjectInputStream s) // throws java.io.IOException, ClassNotFoundException { // // Read in size, and any hidden stuff // s.defaultReadObject(); // // // Read in array length and allocate array // int arrayLength = s.readInt(); // Object[] a = elementData = (E[])new Object[arrayLength]; // // // Read in all elements in the proper order. // for (int i=0; i<size; i++) // a[i] = s.readObject(); // } }
037cd8f73d9ebcbe1234608ac7b37a5e66d1a8c5
36fa82ab4e0119db4fd9436911af91c924c29a08
/app/src/main/java/myapps/kz/betgames/fragments/AboutFragment.java
4bd56e479dc08bfdfa714ab7079c4ce04c536c58
[]
no_license
bekbossyn/betgames_android
31fa6587303e9f733c9cd02402df2ec06a065667
dc9e55fb0cbfbf648226cd0fe37b3447098fc1b3
refs/heads/master
2021-04-27T00:13:27.413977
2018-03-04T09:31:43
2018-03-04T09:31:43
123,774,415
0
0
null
null
null
null
UTF-8
Java
false
false
1,222
java
package myapps.kz.betgames.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import myapps.kz.betgames.MainActivity; import myapps.kz.betgames.R; /** * Created by rauan on 25.07.17. */ public class AboutFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_about, container, false); ((MainActivity) getActivity()).setToolbar("Соглашение", false); return view; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onPrepareOptionsMenu(Menu menu) { menu.findItem(R.id.action_refresh).setVisible(false); menu.findItem(R.id.action_silent).setVisible(false); menu.findItem(R.id.action_reset).setVisible(false); super.onPrepareOptionsMenu(menu); } }
5de8a6ba2fcf4b78cf63ab872f3c0d7f2b515972
5a40ec24879cc94f00dccd3f12b0a4a792a15a21
/app/src/main/java/com/carino/hackathon/speedscreen/fragments/adaptor/RecyclerItemDecoration.java
0094d438285042f8c3a505a9e1ec5a042c2987d5
[ "BSD-3-Clause" ]
permissive
alimertozdemir/CarIno
d0c9243630a369d35f8164c0c028d78ee601b1a9
4818687c7fa376372b12ad9ea1cede33c0177829
refs/heads/master
2021-07-22T14:48:25.303866
2017-11-06T07:03:26
2017-11-06T07:03:26
109,480,822
2
1
null
null
null
null
UTF-8
Java
false
false
1,087
java
package com.carino.hackathon.speedscreen.fragments.adaptor; import android.content.Context; import android.graphics.Rect; import android.support.v7.widget.RecyclerView; import android.view.View; import com.carino.hackathon.R; /** * Created by alimertozdemir on 4.11.2017. */ public class RecyclerItemDecoration extends RecyclerView.ItemDecoration { private final int decorationHeight; public RecyclerItemDecoration(Context context) { decorationHeight = context.getResources() .getDimensionPixelSize(R.dimen.recycler_item_decoration_height); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); if ((parent != null) && (view != null)) { int itemPosition = parent.getChildAdapterPosition(view); int totalCount = parent.getAdapter().getItemCount(); if (itemPosition >= 0 && itemPosition < totalCount - 1) outRect.bottom = decorationHeight; } } }
0f0928365ffc6650721c4c1dc2964483ca67e75b
9c18984be513e99a9ea0640e30f330e77eee128e
/SmartFarm/src/main/java/com/nuc/mapper/UserMapper.java
9a1b130e79b0e274f0d82cbaac4bf644a64ceefa
[ "Apache-2.0" ]
permissive
dengmin111/SmartFarmForIOT
9a36338e58d8cc3de059c31dbafa6b2b1f5daff1
3d2fcaaa52a7d5586af3117556b9c3eef99aa410
refs/heads/master
2020-03-27T23:45:43.760040
2019-03-30T13:18:19
2019-03-30T13:18:19
147,344,270
2
0
null
null
null
null
UTF-8
Java
false
false
482
java
package com.nuc.mapper; import java.util.List; import com.nuc.pojo.User; public interface UserMapper { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); User selectByUsernameandPassword(User user); User selectByUsername(String username); List<User> list(); }
aee43485eb7da9b40984bca530d8477a189e457d
50566ce5d2aab32465b974cfc64dc92b36708724
/src/com/williballenthin/RejistryView/RejTreeKeyNode.java
d0780432fdd2ca7c7e5927e8330fdb220d56a976
[ "Apache-2.0" ]
permissive
sidheshenator/RejView
ae1d93896bc927e03aa609dcc0ae025f8cbe4d7b
9903a6caaa5c93691db6bc63bf1c1bc8f25d4755
refs/heads/master
2020-12-03T05:32:41.066935
2013-08-21T03:31:07
2013-08-21T03:31:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,031
java
package com.williballenthin.RejistryView; import com.williballenthin.rejistry.RegistryKey; import com.williballenthin.rejistry.RegistryParseException; import com.williballenthin.rejistry.RegistryValue; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class RejTreeKeyNode implements RejTreeNode { private final RegistryKey _key; public RejTreeKeyNode(RegistryKey key) { this._key = key; } @Override public String toString() { try { return this._key.getName(); } catch (UnsupportedEncodingException e) { System.err.println("Failed to parse key name"); return "PARSE FAILED."; } } @Override public boolean hasChildren() { try { return this._key.getValueList().size() > 0 || this._key.getSubkeyList().size() > 0; } catch (RegistryParseException e) { System.err.println("Failed to parse key children."); return false; } } @Override public List<RejTreeNode> getChildren() { LinkedList<RejTreeNode> children = new LinkedList<RejTreeNode>(); try { Iterator<RegistryKey> keyit = this._key.getSubkeyList().iterator(); while (keyit.hasNext()) { children.add(new RejTreeKeyNode(keyit.next())); } Iterator<RegistryValue> valueit = this._key.getValueList().iterator(); while (valueit.hasNext()) { children.add(new RejTreeValueNode(valueit.next())); } } catch (RegistryParseException e) { System.err.println("Failed to parse key children."); } return children; } /** * @scope: package-protected */ RegistryKey getKey() { return this._key; } /** * TODO(wb): this isn't exactly MVC... */ public RejTreeNodeView getView() { return new RejTreeKeyView(this); } }
853b10c2990b647dead808a8f3a0588efa718c0d
413e8188b93e6b3b273cf83c2593ef4552843793
/app/src/main/java/com/example/dhruv/newsfeed/Models/CurrentWeather.java
7fe7b21cfdcb4e38c771a226ed368b78b3ca0b48
[]
no_license
anubhakushwaha/News-Ton
86dd779128aa749f78c8b189fe8845ba0223e96b
46f5a241816f28c9730573a9918b943c2882868f
refs/heads/master
2021-01-11T02:05:41.378967
2016-10-10T19:19:21
2016-10-10T19:19:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
733
java
package com.example.dhruv.newsfeed.Models; /** * Created by dhruv on 6/9/16. */ public class CurrentWeather extends WeatherForecast { private final float mTemperature; // Current temperature. public CurrentWeather(final String locationName, final long timestamp, final String description, final float temperature, final float minimumTemperature, final float maximumTemperature) { super(locationName, timestamp, description, minimumTemperature, maximumTemperature); mTemperature = temperature; } public float getTemperature() { return mTemperature; } }
8c6209aed53b8bf648df66054b446bcf23a4a7bb
5e21a8fc768b2a247189ecfcffd47da9a36fb13c
/src/Spath.java
09f01825709214ab53aaadf232243ddbae90f6cf
[]
no_license
Saragog/SPOJ_SHPATH
be1dbe291a7b8f861e8e169163c4d4208e9c5e9d
2a9d96061be4ae9aa91e5120785862ebb9d43115
refs/heads/master
2021-05-08T07:02:02.308755
2017-10-12T13:01:26
2017-10-12T13:01:26
106,693,405
0
0
null
null
null
null
UTF-8
Java
false
false
467
java
import java.util.List; import java.util.Scanner; public class Spath { private static Scanner input; List<City> cities; private class City { String cityName; int cityIndex; } private void performOneTest() { } public static void main(String[] args) { int testNumber; input = new Scanner(System.in); Spath program = new Spath(); testNumber = input.nextInt(); while (testNumber-- > 0) program.performOneTest(); return; } }
46eea211fae925b578fe1e769b2e25a6433b9102
ff1cf7f814ba5ceaf4cf9f0217578a56e53e9a28
/java-ssm-spring/java-ssm-springaop-aspectj/src/main/java/study/ssm/springaop/before/service/impl/SomeServiceImpl.java
219fda58b5fb5398bcb8acc528fff9662fe63137
[]
no_license
miniministrong/java-ssm-study
d12a8587d5f76fa28c8d03f81d3764b8abe1015b
943f6ff2b11eef3d272cd798c19dc924d500f386
refs/heads/master
2023-08-16T18:50:03.910674
2021-09-15T13:11:10
2021-09-15T13:11:10
406,769,301
0
0
null
null
null
null
UTF-8
Java
false
false
602
java
package study.ssm.springaop.before.service.impl; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Service; import study.ssm.springaop.before.service.SomeService; /** * @author dhl * @datetime 2021/7/20 16:14 */ @Service("someServiceImpl") public class SomeServiceImpl implements SomeService { @Override public void doSome(String name, Integer age) { // 需求,我们要在当前方法运行之前增加时间的输出 System.out.println("======SomeServiceImpl中的doSome方法执行了======"); } }
b08f84ab8fa80f9882bd749ca09bc1eb671c7b2c
ff92d22f751f410040f2bf1c3f5e1a9fc3f25899
/app/src/main/java/abhishek/custommenudrawer/Main.java
f4f09c3394a4104432b4cb90ba02edec58ad8702
[]
no_license
abhishek70/Custom-Menu-Drawer-Android-App
6f2b2c893dfecbbe85aadc1cf18a444a5ab6246b
d225c6583177919027884a91aae03d378dabb8bd
refs/heads/master
2020-05-18T19:21:39.942868
2014-09-13T22:36:34
2014-09-13T22:36:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,029
java
package abhishek.custommenudrawer; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.app.FragmentManager; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.support.v4.widget.DrawerLayout; import android.widget.ArrayAdapter; import android.widget.TextView; public class Main extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks { /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. */ private NavigationDrawerFragment mNavigationDrawerFragment; /** * Used to store the last screen title. For use in {@link #restoreActionBar()}. */ private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer); mTitle = getTitle(); // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); } @Override public void onNavigationDrawerItemSelected(int position) { // update the main content by replacing fragments FragmentManager fragmentManager = getFragmentManager(); switch (position) { case 0: fragmentManager.beginTransaction() .replace(R.id.container, HomeFragment.newInstance(position + 1)) .commit(); break; case 1: fragmentManager.beginTransaction() .replace(R.id.container, AboutFragment.newInstance(position + 1)) .commit(); break; case 2: fragmentManager.beginTransaction() .replace(R.id.container, ContactFragment.newInstance(position + 1)) .commit(); break; default: break; } } public void onSectionAttached(int number) { switch (number) { case 1: mTitle = getString(R.string.title_section1); break; case 2: mTitle = getString(R.string.title_section2); break; case 3: mTitle = getString(R.string.title_section3); break; } } public void restoreActionBar() { ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!mNavigationDrawerFragment.isDrawerOpen()) { // Only show items in the action bar relevant to this screen // if the drawer is not showing. Otherwise, let the drawer // decide what to show in the action bar. getMenuInflater().inflate(R.menu.main, menu); restoreActionBar(); return true; } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
c42d8800885b92f3f750e4a28c313dbdc2df20df
c7dcae5764580d0456be83c4db81ac7c8d901c3c
/Leet code week 2/Leet code Removes Duplicate from Sorted Arrays.java
d74389fe03c604c0f95715ce6ad56e70c2f89d19
[]
no_license
akkiitsme/Summer-Internship-program
eee7a8809510eb3034fc64849b638e0166a9e5f7
dfa170b74ae34b9941181689eb66d04b6a0b4a49
refs/heads/main
2023-06-21T11:26:59.620750
2021-07-18T17:33:31
2021-07-18T17:33:31
383,152,713
0
0
null
null
null
null
UTF-8
Java
false
false
2,199
java
/* Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass, then your solution will be accepted. Example 1: Input: nums = [1,1,2] Output: 2, nums = [1,2,_] Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0,0,1,1,1,2,2,3,3,4] Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). Constraints: 0 <= nums.length <= 3 * 104 -100 <= nums[i] <= 100 nums is sorted in non-decreasing order. */ class Solution { public int removeDuplicates(int[] nums) { if (nums.length < 2) return nums.length; int j = 0; int i = 1; while (i < nums.length) { if (nums[i] != nums[j]) { j++; nums[j] = nums[i]; } i++; } return j + 1; } }
8964476c437867fd27ed3100fb60bdebd19096fe
0398e3159f98e92c9f04cf6bcf3a961e0975a073
/src/dao/water/NoticeDao.java
fbbfe25c2b791d1cac611d6d66ee8a6ae52fc4ad
[]
no_license
kongemom1215/byerus
80d5a48159829a8237aa8bccf623ed5f906db7c4
d4c3422b62f66845dc9aa634b33a35736d310074
refs/heads/main
2023-04-01T22:44:07.218906
2021-03-30T04:43:32
2021-03-30T04:43:32
338,590,554
1
0
null
null
null
null
UTF-8
Java
false
false
6,314
java
package dao.water; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; public class NoticeDao { private static NoticeDao instance; private NoticeDao() { } public static NoticeDao getInstance() { if(instance==null) instance= new NoticeDao(); return instance; } private Connection getConnection() { Connection conn=null; try { Context ctx=new InitialContext(); DataSource ds=(DataSource) ctx.lookup("java:comp/env/jdbc/OracleDB"); conn=ds.getConnection(); } catch (Exception e) { System.out.println(e.getMessage()); } return conn; } public int getTotalCnt() throws SQLException { Connection conn = null; Statement stmt = null; ResultSet rs = null; String sql = "select count(*) from notice"; int tot = 0; try { conn = getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); if (rs.next()) { tot = rs.getInt(1); } System.out.println("tot->"+tot); } catch(Exception e) { System.out.println(e.getMessage()); } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); if (rs != null) rs.close(); } return tot; } public List<Notice> list(int startRow, int endRow) throws SQLException { List<Notice> list = new ArrayList<Notice>(); Connection conn = null; PreparedStatement pstmt= null; ResultSet rs = null; String sql = "select * from (select rownum rn ,a.* from (select n.* from notice n order by nid desc) a ) where rn between ? and ?"; try { conn = getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, startRow); pstmt.setInt(2, endRow); rs = pstmt.executeQuery(); while (rs.next()) { Notice notice = new Notice(); notice.setNid(rs.getInt("nid")); notice.setNtitle(rs.getNString("ntitle")); notice.setNcontent(rs.getString("ncontent")); notice.setNpublic(rs.getInt("npublic")); notice.setNdate(rs.getDate("ndate")); notice.setNfile(rs.getString("nfile")); notice.setNhit(rs.getInt("nhit")); list.add(notice); } } catch(Exception e) { System.out.println(e.getMessage()); } finally { if (rs !=null) rs.close(); if (pstmt != null) pstmt.close(); if (conn !=null) conn.close(); } return list; } public Review find(int rid) throws SQLException { String sql="select * from review where rid = ?"; Review review = new Review(); Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try { conn=getConnection(); pstmt=conn.prepareStatement(sql); pstmt.setInt(1, rid); rs=pstmt.executeQuery(); if(rs.next()) { review.setRid(rs.getInt("rid")); review.setSid(rs.getInt("sid")); review.setOid(rs.getInt("oid")); review.setPid(rs.getInt("pid")); review.setRwriter(rs.getString("rwriter")); review.setRtitle(rs.getString("rtitle")); review.setRcontent(rs.getString("rcontent")); review.setRimg(rs.getString("rimg")); review.setRdate(rs.getDate("rdate")); review.setRhit(rs.getInt("rhit")); review.setRcmt(rs.getString("rcmt")); review.setRcmtdate(rs.getDate("rcmtdate")); review.setOdate(rs.getDate("odate")); } } catch (Exception e) { System.out.println(e.getMessage()); } finally { if(rs!=null) rs.close(); if(pstmt!=null) pstmt.close(); if(conn!=null) conn.close(); } return review; } public Review select(int sid) throws SQLException { Review review = new Review(); Connection conn = null; String sql = "select * from review where sid="+sid; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = getConnection(); pstmt = conn.prepareStatement(sql); rs =pstmt.executeQuery(); if (rs.next()) { review.setRid(rs.getInt("rid")); review.setSid(rs.getInt("sid")); review.setOid(rs.getInt("oid")); review.setPid(rs.getInt("pid")); review.setRwriter(rs.getString("rwriter")); review.setRtitle(rs.getString("rtitle")); review.setRcontent(rs.getString("rcontent")); review.setRimg(rs.getString("rimg")); review.setRdate(rs.getDate("rdate")); review.setRhit(rs.getInt("rhit")); review.setRcmt(rs.getString("rcmt")); review.setRcmtdate(rs.getDate("rcmtdate")); review.setOdate(rs.getDate("odate")); } }catch(Exception e) { System.out.println(e.getMessage()); } finally { if(pstmt != null) pstmt.close(); if (conn != null) conn.close(); if (rs !=null) rs.close(); } return review; } public int update(Review review) throws SQLException { Connection conn = null; PreparedStatement pstmt = null; int result = 0; String sql="update review set rcontent=? ,rtitle=? where sid=?"; try { conn = getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, review.getRcontent()); pstmt.setString(2, review.getRtitle()); pstmt.setInt(3, review.getSid()); result = pstmt.executeUpdate(); System.out.println(result); } catch(Exception e) { System.out.println(e.getMessage()); } finally { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } return result; } public void readCount (int nid) throws SQLException { Connection conn = null; PreparedStatement pstmt= null; String sql = "update notice set nhit=nhit+1 where nid=?"; try { conn = getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, nid); pstmt.executeUpdate(); }catch (Exception e) { System.out.println(e.getMessage()); }finally { if(pstmt != null) pstmt.close(); if(conn!=null) conn.close(); } } }
38eb15efb2dffca07bf81ac70fb8b2c5382c3abd
781682c9629caff05942bbeb90c2b03f54e8a5a9
/Main.java
11cd88b28ce9b549ee4ecec5c9e141fdae9eeabb
[]
no_license
kamilahollerbach/hollerbach-cop3330-ex7
a2825b037b2dd49f3cb0a75402bf72b8355883f5
726e3957d65d2fde2615f4302dd7b5268b97a788
refs/heads/main
2023-08-03T08:56:07.908716
2021-09-13T22:00:02
2021-09-13T22:00:02
406,141,565
0
0
null
null
null
null
UTF-8
Java
false
false
889
java
/* * UCF COP3330 Fall 2021 Assignment 1 Solution * Copyright 2021 Kamila Hollerbach */ package com.company; import java.util.Scanner; import java.util.*; import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("What is the length of the room in feet?"); double length=sc.nextDouble(); System.out.println("What is the width of the room in feet?"); double width=sc.nextDouble(); System.out.println("You entered dimension of "+length+" by "+width+" feet"); double area=length*width; final double conversionFactor=area*0.09290304; System.out.println("The area is"); System.out.println(area+" square feet"); System.out.println(conversionFactor+" square meters"); } }
a7c4c7ec551602e33e478e43ad2fe54a3acdcee5
ac0cc9fc0d73a9435dae888bf89c627611b603b3
/src/main/java/minecrafttransportsimulator/blocks/instances/BlockBeacon.java
00e6e6edd9db0a4946d494dad69bd58a4ab0e8bc
[]
no_license
gyrohero/MinecraftTransportSimulator
560dced33074852bb153a806980a4428936841e8
484d754d9a8b901ff60aee38b6211917749291c2
refs/heads/master
2023-02-05T01:43:39.883760
2020-12-14T01:19:46
2020-12-14T01:19:46
257,940,767
0
0
null
2020-04-22T15:23:35
2020-04-22T15:23:35
null
UTF-8
Java
false
false
1,732
java
package minecrafttransportsimulator.blocks.instances; import java.util.List; import minecrafttransportsimulator.baseclasses.BeaconManager; import minecrafttransportsimulator.baseclasses.Point3i; import minecrafttransportsimulator.blocks.components.ABlockBaseDecor; import minecrafttransportsimulator.blocks.tileentities.instances.TileEntityBeacon; import minecrafttransportsimulator.blocks.tileentities.instances.TileEntityDecor; import minecrafttransportsimulator.guis.instances.GUITextEditor; import minecrafttransportsimulator.mcinterface.IWrapperNBT; import minecrafttransportsimulator.mcinterface.IWrapperPlayer; import minecrafttransportsimulator.mcinterface.IWrapperWorld; import minecrafttransportsimulator.mcinterface.MasterLoader; public class BlockBeacon extends ABlockBaseDecor<TileEntityBeacon>{ public BlockBeacon(){ super(); } @Override public boolean onClicked(IWrapperWorld world, Point3i point, Axis axis, IWrapperPlayer player){ if(world.isClient()){ MasterLoader.guiInterface.openGUI(new GUITextEditor((TileEntityDecor) world.getTileEntity(point))); } return true; } @Override public void onBroken(IWrapperWorld world, Point3i location){ TileEntityBeacon beacon = world.getTileEntity(location); if(beacon != null){ List<String> textLines = beacon.getTextLines(); BeaconManager.removeBeacon(world, textLines.get(TileEntityBeacon.BEACON_NAME_INDEX)); } } @Override public TileEntityBeacon createTileEntity(IWrapperWorld world, Point3i position, IWrapperNBT data){ return new TileEntityBeacon(world, position, data); } @Override public Class<TileEntityBeacon> getTileEntityClass(){ return TileEntityBeacon.class; } }
174295f4d8644f887eb84a0103888753afac4af1
7eecef9e67ac192503b049fced4ca2c59b5767f6
/src/main/java/com/ringcentral/definitions/NotificationRecipientInfo.java
9b6c8b424c906c1515048eecf259f1dfacffdab5
[]
no_license
PacoVu/ringcentral-java
985edecd37a92751a5f3206b7a045d9a99a63980
df6833104538fc75757a41a3542c3263cf421d28
refs/heads/master
2020-05-29T12:56:18.438431
2019-05-30T14:42:02
2019-05-30T14:42:02
140,632,299
0
0
null
2018-07-11T22:08:32
2018-07-11T22:08:31
null
UTF-8
Java
false
false
1,599
java
package com.ringcentral.definitions; import com.alibaba.fastjson.annotation.JSONField; public class NotificationRecipientInfo { // Phone number in E.164 (with '+' sign) format public String phoneNumber; public NotificationRecipientInfo phoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; return this; } // Extension number public String extensionNumber; public NotificationRecipientInfo extensionNumber(String extensionNumber) { this.extensionNumber = extensionNumber; return this; } // 'True' specifies that message is sent exactly to this recipient. Returned in to field for group MMS. Useful if one extension has several phone numbers public Boolean target; public NotificationRecipientInfo target(Boolean target) { this.target = target; return this; } // Contains party location (city, state) if one can be determined from phoneNumber. This property is filled only when phoneNumber is not empty and server can calculate location information from it (for example, this information is unavailable for US toll-free numbers) public String location; public NotificationRecipientInfo location(String location) { this.location = location; return this; } // Symbolic name associated with a caller/callee. If the phone does not belong to the known extension, only the location is returned, the name is not determined then public String name; public NotificationRecipientInfo name(String name) { this.name = name; return this; } }
64fa870902bf9ffbd24cd46552cd7c623e8b5b04
a9adc83d3a0f2ef0be6878fd5286d674c95363d0
/clients/kratos/java/src/test/java/sh/ory/kratos/api/CommonApiTest.java
0341ef29510b19c4d7843162ddcb4557661c8186
[ "Apache-2.0" ]
permissive
TuxCoder/sdk
e4625ca82da6e303e85a7d2f3e4220fd83fd1973
908f96e038142b99c3b6541f760f9dd158408791
refs/heads/master
2022-11-06T06:04:21.904547
2020-07-01T15:32:38
2020-07-01T16:00:10
273,890,630
0
0
null
2020-06-21T11:29:15
2020-06-21T11:29:15
null
UTF-8
Java
false
false
5,668
java
/* * Ory Kratos * Welcome to the ORY Kratos HTTP API documentation! * * The version of the OpenAPI document: latest * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package sh.ory.kratos.api; import sh.ory.kratos.ApiException; import sh.ory.kratos.model.ErrorContainer; import sh.ory.kratos.model.GenericError; import sh.ory.kratos.model.LoginRequest; import sh.ory.kratos.model.RegistrationRequest; import sh.ory.kratos.model.SettingsRequest; import sh.ory.kratos.model.VerificationRequest; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for CommonApi */ @Ignore public class CommonApiTest { private final CommonApi api = new CommonApi(); /** * * * Get a traits schema definition * * @throws ApiException * if the Api call fails */ @Test public void getSchemaTest() throws ApiException { String id = null; Object response = api.getSchema(id); // TODO: test validations } /** * Get the request context of browser-based login user flows * * This endpoint returns a login request&#39;s context with, for example, error details and other information. When accessing this endpoint through ORY Kratos&#39; Public API, ensure that cookies are set as they are required for CSRF to work. To prevent token scanning attacks, the public endpoint does not return 404 status codes to prevent scanning attacks. More information can be found at [ORY Kratos User Login and User Registration Documentation](https://www.ory.sh/docs/next/kratos/self-service/flows/user-login-user-registration). * * @throws ApiException * if the Api call fails */ @Test public void getSelfServiceBrowserLoginRequestTest() throws ApiException { String request = null; LoginRequest response = api.getSelfServiceBrowserLoginRequest(request); // TODO: test validations } /** * Get the request context of browser-based registration user flows * * This endpoint returns a registration request&#39;s context with, for example, error details and other information. When accessing this endpoint through ORY Kratos&#39; Public API, ensure that cookies are set as they are required for CSRF to work. To prevent token scanning attacks, the public endpoint does not return 404 status codes to prevent scanning attacks. More information can be found at [ORY Kratos User Login and User Registration Documentation](https://www.ory.sh/docs/next/kratos/self-service/flows/user-login-user-registration). * * @throws ApiException * if the Api call fails */ @Test public void getSelfServiceBrowserRegistrationRequestTest() throws ApiException { String request = null; RegistrationRequest response = api.getSelfServiceBrowserRegistrationRequest(request); // TODO: test validations } /** * Get the request context of browser-based settings flows * * When accessing this endpoint through ORY Kratos&#39; Public API, ensure that cookies are set as they are required for checking the auth session. To prevent scanning attacks, the public endpoint does not return 404 status codes but instead 403 or 500. More information can be found at [ORY Kratos User Settings &amp; Profile Management Documentation](../self-service/flows/user-settings). * * @throws ApiException * if the Api call fails */ @Test public void getSelfServiceBrowserSettingsRequestTest() throws ApiException { String request = null; SettingsRequest response = api.getSelfServiceBrowserSettingsRequest(request); // TODO: test validations } /** * Get user-facing self-service errors * * This endpoint returns the error associated with a user-facing self service errors. When accessing this endpoint through ORY Kratos&#39; Public API, ensure that cookies are set as they are required for CSRF to work. To prevent token scanning attacks, the public endpoint does not return 404 status codes to prevent scanning attacks. More information can be found at [ORY Kratos User User Facing Error Documentation](https://www.ory.sh/docs/kratos/self-service/flows/user-facing-errors). * * @throws ApiException * if the Api call fails */ @Test public void getSelfServiceErrorTest() throws ApiException { String error = null; ErrorContainer response = api.getSelfServiceError(error); // TODO: test validations } /** * Get the request context of browser-based verification flows * * When accessing this endpoint through ORY Kratos&#39; Public API, ensure that cookies are set as they are required for checking the auth session. To prevent scanning attacks, the public endpoint does not return 404 status codes but instead 403 or 500. More information can be found at [ORY Kratos Email and Phone Verification Documentation](https://www.ory.sh/docs/kratos/selfservice/flows/verify-email-account-activation). * * @throws ApiException * if the Api call fails */ @Test public void getSelfServiceVerificationRequestTest() throws ApiException { String request = null; VerificationRequest response = api.getSelfServiceVerificationRequest(request); // TODO: test validations } }
48dadfdaa9637f243f7f4551b5f4caf021f6166a
f0a5e9b32461d89c330eddb6c49d533335548d81
/src/main/java/pl/pjatk/movieService/CoreApplication.java
b816e1e6afa7014f90353fc328f959479b6b30cf
[]
no_license
s21357-pj/jaz_movieService
6b3d4ae859243f31ef1787f24469fe05816aadee
b8fd26d47583d3a543306640d7311e5084f5b57a
refs/heads/master
2023-05-27T16:25:17.807722
2021-06-03T12:34:45
2021-06-03T12:34:45
365,525,322
0
0
null
null
null
null
UTF-8
Java
false
false
311
java
package pl.pjatk.movieService; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CoreApplication { public static void main(String[] args) { SpringApplication.run(CoreApplication.class, args); } }
074d9f1b778e0a1c4854fd7efee278ab3853227f
8b74c61074fb3bce89e8942a16434a0c4c4f0d48
/app/src/main/java/com/example/currencyconverter/MainActivity.java
6a2e657ad0a8b411ddf4e2cb84bf250ea7ba3aed
[]
no_license
noor-fathima-khanum/CS407-currencyconverter
61f61e0de7c4184278fa6844148585f7d164b15a
c6a63b22be82378d30f821ee3e7d36d820d0e623
refs/heads/master
2020-12-30T02:37:04.776705
2020-02-07T03:09:52
2020-02-07T03:09:52
238,833,099
0
0
null
null
null
null
UTF-8
Java
false
false
1,066
java
package com.example.currencyconverter; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; public class MainActivity extends AppCompatActivity { public void clickFunction(View view) { EditText myTextField = (EditText) findViewById(R.id.editText); //Log.i("Info","Button Pressed"); String str = myTextField.getText().toString(); //Toast.makeText( MainActivity.this, myTextField.getText().toString(), Toast.LENGTH_LONG).show(); goToActivity2(str); } public void goToActivity2(String s) { Intent intent = new Intent(this,com.example.currencyconverter.Main2Activity.class); //int intValue = Integer.parseInt(s); intent.putExtra("message",s); startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
11afbd9a144924d39286d6c0734abf7978bb8e8f
74b2d906e427a9547ede09be65f6525066e12264
/src/main/java/com/peter/controller/MinutesController.java
630dbbfee61ac9fa17b4154d59517df56a2ccf5e
[]
no_license
patevn/fitness
4389ed249cb06c25e31e4f690c4cc289f5b826da
9470976c70a88ced0718bff99e03770493c0cc08
refs/heads/master
2021-08-20T05:53:17.158785
2017-11-28T10:12:01
2017-11-28T10:12:01
111,530,208
0
0
null
null
null
null
UTF-8
Java
false
false
585
java
package com.peter.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.peter.model.Exercise; /** * @author Peter */ @Controller public class MinutesController { @RequestMapping(value = "/addMinutes") public String addMinutes(@ModelAttribute ("exercise") Exercise exercise) { //the line above binds to <form:form commandName="exercise"> System.out.println("exercise: " + exercise.getMinutes()); return "addMinutes"; } }
672cc3f95d91c11575c58dd15f704d61cb056e15
77b3998da1db73cc2de0ebd9e0872e139428c405
/ejemploCompServiciosJSF192/src/java/servicios/service/AbstractFacade.java
2ed5d839e4ceab7b3322fb3131a89d68677e9b6b
[]
no_license
danielsinho007/primeraAplicacionServicio
70a29ac1d2915abadd914fce88c03abe7c049ffa
50850f4455918ad798b40b22776014d1e4645885
refs/heads/master
2020-09-16T18:37:06.075702
2019-11-25T03:43:46
2019-11-25T03:43:46
223,854,718
0
0
null
null
null
null
UTF-8
Java
false
false
1,978
java
/* * 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 servicios.service; import java.util.List; import javax.persistence.EntityManager; /** * * @author danimocr */ public abstract class AbstractFacade<T> { private Class<T> entityClass; public AbstractFacade(Class<T> entityClass) { this.entityClass = entityClass; } protected abstract EntityManager getEntityManager(); public void create(T entity) { getEntityManager().persist(entity); } public void edit(T entity) { getEntityManager().merge(entity); } public void remove(T entity) { getEntityManager().remove(getEntityManager().merge(entity)); } public T find(Object id) { return getEntityManager().find(entityClass, id); } public List<T> findAll() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); return getEntityManager().createQuery(cq).getResultList(); } public List<T> findRange(int[] range) { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); javax.persistence.Query q = getEntityManager().createQuery(cq); q.setMaxResults(range[1] - range[0] + 1); q.setFirstResult(range[0]); return q.getResultList(); } public int count() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); javax.persistence.criteria.Root<T> rt = cq.from(entityClass); cq.select(getEntityManager().getCriteriaBuilder().count(rt)); javax.persistence.Query q = getEntityManager().createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } }
ac61c6e45c5b3679abac778d618a59158fa348f0
77d564fdc48eacca65dee018e6e2fbb77ea7d73a
/src/main/java/com/ramsey/betterexamsrestapi/repo/UserRepo.java
28cdfc5c663aa8e1813196988246ceb2b35f3778
[]
no_license
ahmed-ramsey-shahin/BetterExams-RESTApi
73e813d03e426f62eb9aab74177cfd43ac14225f
d0eaf3dc15f560251d3bd3f636637fc6e6e86a55
refs/heads/master
2023-08-01T10:24:54.712413
2021-10-01T17:53:26
2021-10-01T17:53:26
410,865,916
1
0
null
null
null
null
UTF-8
Java
false
false
1,318
java
package com.ramsey.betterexamsrestapi.repo; import com.ramsey.betterexamsrestapi.entity.User; import com.ramsey.betterexamsrestapi.entity.UserType; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface UserRepo extends CrudRepository<User, String> { Boolean existsByUsernameOrEmail(String username, String email); Boolean existsByEmail(String email); Optional<User> findByUsernameAndType(String username, UserType userType); @Query("SELECT u FROM User u WHERE (u.username LIKE %:name% OR u.fullName LIKE %:name%) AND u.type = :type") List<User> findByName(String name, UserType type, Pageable pageable); @Query("SELECT s.user FROM Teacher t, IN(t.students) s WHERE (t.user.username = :username) and (s.user.username LIKE %:studentName% or s.user.fullName LIKE %:studentName%)") List<User> searchStudentForTeacher(String username, String studentName, Pageable pageable); @Query("SELECT s.user FROM Teacher t, IN(t.students) s WHERE t.user.username = :teacher and s.user.username = :student") Optional<User> findStudentForTeacher(String student, String teacher); }
727596d0b74f830411ad4534fdefed3aba574865
449fdb4375ac74fd49081203f1de837de4cff229
/app/src/main/java/co/com/planit/lavapp/client/ConsultaDescripcionPedido.java
0453681bb854bf47570cc5d7f6babf04a3f8abb9
[]
no_license
Scordevil/Lavapp
9b55d92fb3ef96bb3a128b9e2abf8d3747a03a5d
b6c8a4b4673c0ab6ca473274372ef18c62efe924
refs/heads/master
2021-01-12T12:23:32.841694
2016-11-02T22:29:19
2016-11-02T22:29:19
72,482,803
0
0
null
null
null
null
UTF-8
Java
false
false
11,044
java
package co.com.planit.lavapp.client; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import co.com.planit.lavapp.R; import co.com.planit.lavapp.common.EditarPerfil; import co.com.planit.lavapp.common.Login; import co.com.planit.lavapp.common.MainActivity; import co.com.planit.lavapp.common.Register; import co.com.planit.lavapp.config.UserLocalStore; import co.com.planit.lavapp.models.DescripcionPedido_TO; import co.com.planit.lavapp.models.Pedido_TO; import co.com.planit.lavapp.models.Usuario_TO; import co.com.planit.lavapp.service.ConsultarDescripcionPedidoSegunPedido; import co.com.planit.lavapp.service.ConsultarPedidos; import co.com.planit.lavapp.service.ConsultarPedidosCliente; import co.com.planit.lavapp.service.EliminarDescPedido; import co.com.planit.lavapp.service.ServerRequests; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; public class ConsultaDescripcionPedido extends AppCompatActivity { private AlertDialog.Builder dialogBuilder; UserLocalStore userLocalStore; ServerRequests serverRequests = new ServerRequests(); String ruta = serverRequests.BuscarRuta(); ListViewAdapter adapter1; TextView tvFecha, tvRango, tvDireccion, tvFechaR, tvDireccionR; List<String> IdPedido = new ArrayList<String>(); List<String> Fecha = new ArrayList<String>(); List<String> FechaInicio = new ArrayList<String>(); List<String> HoraInicio = new ArrayList<String>(); List<Integer> Imagenes = new ArrayList<Integer>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_consulta_descripcion_pedido); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); userLocalStore = new UserLocalStore(this); final ListView lista1 = (ListView) findViewById(R.id.listView1); tvFecha = (TextView) findViewById(R.id.tvFecha); tvRango = (TextView) findViewById(R.id.tvRango); tvDireccion = (TextView) findViewById(R.id.tvDireccion); tvFechaR = (TextView) findViewById(R.id.tvFechaR); tvDireccionR = (TextView) findViewById(R.id.tvDireccionR); int idPedido = getIntent().getExtras().getInt("idPed"); ConsultarPedidos(idPedido); Toast.makeText(getApplicationContext(), idPedido + "--", Toast.LENGTH_SHORT); Log.i("Prueba: ", idPedido + "--"); ConsultarDescripPedidos(idPedido); } public class ListViewAdapter extends BaseAdapter { // Declare Variables Context context; List<String> idPedido; List<String> fecha; List<String> fechaInicio; List<String> horaInicio; List<Integer> imagenes; LayoutInflater inflater; public ListViewAdapter(Context context, List<String> idPedido , List<String> fecha, List<String> fechaInicio, List<String> horaInicio, List<Integer> imagenes) { this.context = context; this.idPedido = idPedido; this.fecha = fecha; this.horaInicio = horaInicio; this.fechaInicio = fechaInicio; this.imagenes = imagenes; } public ListViewAdapter(Context context) { this.context = context; } @Override public int getCount() { return idPedido.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { // Declare Variables TextView txtIdPedido; TextView txtFecha; TextView txtFechaInicio; TextView txtHoraInicio; ImageView imgImg; //http://developer.android.com/intl/es/reference/android/view/LayoutInflater.html inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View itemView = inflater.inflate(R.layout.list_row, parent, false); // Locate the TextViews in listview_item.xml txtIdPedido = (TextView) itemView.findViewById(R.id.tv_titulo_single_post_circuito); txtFecha = (TextView) itemView.findViewById(R.id.tv_contenido_single_post_circuito); txtFechaInicio = (TextView) itemView.findViewById(R.id.tv_contenido_single_post_circuito2); txtHoraInicio = (TextView) itemView.findViewById(R.id.tv_contenido_single_post_circuito3); imgImg = (ImageView) itemView.findViewById(R.id.imagen_single_post_circuito); // Capture position and set to the TextViews txtIdPedido.setText(IdPedido.get(position)); txtFecha.setText(Fecha.get(position)); txtFechaInicio.setText(FechaInicio.get(position)); txtHoraInicio.setText(HoraInicio.get(position)); imgImg.setImageResource(Imagenes.get(position)); // txtSubtitle.setText(FechaInicio.get(position)); return itemView; } } private void ConsultarDescripPedidos(final int idPedido) { final ListView lista1 = (ListView) findViewById(R.id.listView1); final RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(ruta).build(); ConsultarDescripcionPedidoSegunPedido servicio = restAdapter.create(ConsultarDescripcionPedidoSegunPedido.class); servicio.consultarDescripcionPedidoSegunPedido(idPedido, new Callback<List<DescripcionPedido_TO>>() { @Override public void success(List<DescripcionPedido_TO> pedidos, Response response) { Collections.sort(pedidos); Log.i("pedidos: ", pedidos + ""); IdPedido.clear(); Fecha.clear(); FechaInicio.clear(); HoraInicio.clear(); Imagenes.clear(); for (int i = 0; i < pedidos.size(); i++) { IdPedido.add(pedidos.get(i).getIdDescripcionPedido() + ""); Fecha.add("Nombre: " + pedidos.get(i).getSubProducto().getNombre()); FechaInicio.add(" "); HoraInicio.add("Estado: " + pedidos.get(i).getEstado().getNombre()); Imagenes.add(R.drawable.jeans); } adapter1 = new ListViewAdapter(getApplicationContext(), IdPedido, Fecha, FechaInicio, HoraInicio, Imagenes); lista1.setAdapter(null); lista1.setAdapter(adapter1); lista1.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int posicion, long l) { // if (userLocalStore.getUserLoggedIn() == false) { final int idDesPed = Integer.parseInt(IdPedido.get(posicion)); Intent intent = new Intent(ConsultaDescripcionPedido.this, Historico.class); intent.putExtra("idProd", idDesPed); startActivity(intent); } }); // } @Override public void failure(RetrofitError retrofitError) { Log.i("Error", "mensaje" + retrofitError.getMessage()); } }); } private void ConsultarPedidos(int idPedido) { final RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(ruta).build(); ConsultarPedidos servicio = restAdapter.create(ConsultarPedidos.class); servicio.consultarPedido(idPedido, new Callback<Pedido_TO>() { @Override public void success(Pedido_TO pedido, Response response) { Log.i("pedidos: ",pedido.toString() ); tvFecha.setText("Fecha de Entrega: " + pedido.getFechaEntregaString().toString()); tvRango.setText("Rango de Horas: " + pedido.getHoraInicio().getHoraInicio().toString()); tvDireccion.setText("Dirección de Entrega: " + pedido.getDireccionEntrega().toString()); tvFechaR.setText("Fecha para Recibir: " + pedido.getFechaRecogidaString().toString()); tvDireccionR.setText("Dirección para Recibir: " + pedido.getDireccionRecogida().toString()); } @Override public void failure(RetrofitError retrofitError) { Log.i("Error: ", retrofitError.toString()); } }); } ; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. if (userLocalStore.getUserLoggedIn() == true) { getMenuInflater().inflate(R.menu.menu_main, menu); }else{ getMenuInflater().inflate(R.menu.menu_main2, menu); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.cerrar_Sesion) { userLocalStore.clearUserData(); userLocalStore.setUserLoggedIn(false); startActivity(new Intent(this, MainActivity.class)); } if (id == R.id.iniciar_sesion) { startActivity(new Intent(this, Login.class)); } if (id == R.id.inicio) { startActivity(new Intent(this, Inicio.class)); } if (id == R.id.editar_perfil) { startActivity(new Intent(this, EditarPerfil.class)); } if (id == R.id.consultar_pedidos) { startActivity(new Intent(this, ConsultarPedido.class)); } return super.onOptionsItemSelected(item); } }
206c15f3192536d634d41244c39cc94439bd31d4
aa1942498b50e96c66f908105f01313bf2d6764c
/SWO4/uebungMoodle5/Beispiel/test/at/lumetsnet/swe4/collections/test/TwoThreeFourSetTest.java
c28e3664c77d031fc7f7b17cdb58590d09c2ab69
[]
no_license
romanlum/StudyCode
b87a5e62bef3f95562653e56d9c60f3822a1c452
e8a5f5b90b38b4d8f957f5e14c555a204caaa350
refs/heads/master
2020-12-14T15:40:18.276993
2016-05-28T09:41:21
2016-05-28T09:41:21
33,830,960
0
0
null
null
null
null
UTF-8
Java
false
false
1,434
java
package at.lumetsnet.swe4.collections.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Comparator; import org.junit.Test; import at.lumetsnet.swe4.collections.SortedTreeSet; import at.lumetsnet.swe4.collections.TwoThreeFourTreeSet; public class TwoThreeFourSetTest extends SortedTreeSetTestBase { @Override protected <T> TwoThreeFourTreeSet<T> createSet(Comparator<T> comparator) { return new TwoThreeFourTreeSet<T>(comparator); } @Test public void testEmptyConstructor() { TwoThreeFourTreeSet<Integer> set = new TwoThreeFourTreeSet<>(); assertEquals(null, set.comparator()); } @Test public void testHeight() { final int NELEMS = 10000; SortedTreeSet<Integer> set = createSet(); for (int i = 1; i <= NELEMS; i++) { set.add(i); int h = set.height(); int n = set.size(); assertTrue("height(set) <= ld(size(set))+1", h <= Math.log((double) n) / Math.log(2.0) + 1); } } @Test public void testSingleNodeHeight() { SortedTreeSet<Integer> set = createSet(); set.add(1); assertEquals(0, set.height()); assertEquals(1, set.size()); } @Test public void testHeightAfterSplit() { SortedTreeSet<Integer> set = createSet(); set.add(1); set.add(2); set.add(3); set.add(4); // split assertEquals(1, set.height()); assertEquals(4, set.size()); } }
a1d6fdc829558530ff9aefef4d8863f22aa3eef4
a60d7543e9cf369db9a39d235b0ce07eb721aa12
/hippo-rest/src/main/java/com/yoterra/hippo/mob/controllers/ProductController.java
04415081cae4dfd7d6535ab8abbb6287d095ae9e
[]
no_license
nawelmohamed/hippo
7bd0da5b78f41178a314531d98d792ddfbc07aa8
8d4e81a4219e7e27a2a012aeaa3fc671a7d4221b
refs/heads/master
2023-09-04T18:31:43.908198
2021-08-26T11:54:52
2021-08-26T11:54:52
428,688,345
0
0
null
null
null
null
UTF-8
Java
false
false
5,186
java
package com.yoterra.hippo.mob.controllers; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.yoterra.data.records.ProductOffer; import com.yoterra.hippo.jpa.entities.comments.CommentProduct; import com.yoterra.hippo.jpa.entities.data.Product; import com.yoterra.hippo.jpa.entities.likes.LikeProduct; import com.yoterra.hippo.mob.model.AcMob; import com.yoterra.hippo.mob.model.CommentMob.ProductCommentMob; import com.yoterra.hippo.mob.model.LikeMob.ProductLikeMob; import com.yoterra.hippo.mob.model.OfferMob; import com.yoterra.hippo.mob.model.ProductFullMob; import com.yoterra.hippo.mob.model.ProductMob; import com.yoterra.hippo.mob.model.UserCtx; import com.yoterra.hippo.req.PageParams; import com.yoterra.hippo.res.RPage; import com.yoterra.hippo.res.Response; import com.yoterra.hippo.search.requests.ProductSearchRequest; import com.yoterra.hippo.services.ICommentService; import com.yoterra.hippo.services.ILikeService; import com.yoterra.hippo.services.ProductService; import com.yoterra.utils.CollectionUtils; import com.yoterra.utils.Opt; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @RestController @RequestMapping("/products") public class ProductController extends BaseController implements ICommentsController<String, Product, CommentProduct, ProductCommentMob>, ILikesController<String, Product, LikeProduct, ProductLikeMob>, IStringEntityController{ private static final Logger log = LoggerFactory.getLogger(ProductController.class); @Autowired private ProductService productService; @Operation(summary = "Search for (get a page of) products", description = "Search for (get a page of) products. Optionaly, apply filters (see the parameters). " + "Returns records with limited information (full info records should be only used for single product info screens). " + "It should be used on screens for displaying multiple products info.") @RequestMapping(method = RequestMethod.GET) public Response<RPage<ProductMob>> searchProducts(@ModelAttribute ProductSearchRequest req){ log.info("Products search page"); Page<Product> pPage = productService.searchProducts(req, true); RPage<ProductMob> page = RPage.of(pPage, ProductMob::new); return Response.success(null, page); } @Operation(summary = "Get a list of product names matching a specified query.", description = "Get a list of product IDs and names matching a specified query. " + "Mostly used to display a list of product names while typing it in a text box.") @RequestMapping(value="/autocomplete", params="q", method = RequestMethod.GET) public Response<RPage<AcMob>> autocompleteProducts(@RequestParam("q") @Parameter(description = "Query text") String q){ log.info("Products autocomplete page. Query: {}", q); ProductSearchRequest req = new ProductSearchRequest().initAutocompleteReq(q); Page<Product> pPage = productService.searchProducts(req, false); RPage<AcMob> page = RPage.of(pPage, AcMob::new); return Response.success(null, page); } @Operation(summary = "Get full info of one product.", description = "Get product record with full information.") @RequestMapping(value="/get", params="id", method = RequestMethod.GET) public Response<ProductFullMob> getProduct(@RequestParam("id") @Parameter(description = "Product id") String id){ log.info("Get product: {}", id); Product p = productService.getProduct(id, true); UserCtx userContext = productService.getUserContext(p); ProductFullMob pm = ProductFullMob.of(p, userContext); return Response.success(null, pm); } @RequestMapping(value="/get/offers", params="id", method = RequestMethod.GET) public Response<RPage<OfferMob>> getProductOffers(@RequestParam("id") String id, PageParams pageParams){ log.info("Get product offers: {}", id); Product p = productService.getProduct(id, true); List<ProductOffer> sortedOffers = p.getProductOffers(ProductOffer.Comparators.BY_LOWER_PRICE_ASC); Pageable pg = pageParams.getPageable(); List<OfferMob> offersPage = Opt.strm(sortedOffers).map(OfferMob::of) .skip(pg.getOffset()).limit(pg.getPageSize()).toList(); Page<OfferMob> page = new PageImpl<OfferMob>(offersPage, pg, CollectionUtils.size(sortedOffers)); return Response.success(null, RPage.of(page)); } @Override public Logger getLogger() { return log; } @Override public ILikeService<String, Product, LikeProduct> getLikeService() { return productService; } @Override public ICommentService<String, Product, CommentProduct> getCommentService() { return productService; } }
8be43d4ce530e2ee93dd80970fdcc996631775e5
ba7a08adbdd07dc8b45b4a3aea0e03cce73b4dc6
/hr-eureka-server/src/test/java/com/microservices/hreurekaserver/HrEurekaServerApplicationTests.java
a778f838aa6cd5ba45d5cf89c19e54e22b2fb8fe
[]
no_license
giuliana-bezerra/microservices-springboot
0f4a4144a030e094cd4270a69c24be0424c9d701
3e7f828c92dbee5d47cc5e43283d455668c53399
refs/heads/main
2023-04-15T02:38:20.279783
2021-02-23T14:04:34
2021-02-23T14:04:34
336,028,998
3
0
null
null
null
null
UTF-8
Java
false
false
232
java
package com.microservices.hreurekaserver; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class HrEurekaServerApplicationTests { @Test void contextLoads() { } }
09c0a95c9bfe3bd5240520cedab7fdf03b960556
898e786d8f299a478a88a8b2f8e91f063d712722
/src/main/java/pe/com/iquitos/app/security/DomainUserDetailsService.java
6caa0b29349a1d0a4d4b63246cf4545d3559a3eb
[]
no_license
luiighi2693/iquitos-app
b73818fa11a73d494c6d8445b60be57d2e10aafd
b5452ce047ebad07df80b5103974cf919f999b80
refs/heads/master
2021-06-30T21:04:04.328284
2019-02-06T01:54:36
2019-02-06T01:54:36
154,246,223
0
1
null
2020-09-18T09:45:00
2018-10-23T02:04:29
TypeScript
UTF-8
Java
false
false
2,670
java
package pe.com.iquitos.app.security; import pe.com.iquitos.app.domain.User; import pe.com.iquitos.app.repository.UserRepository; import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.*; import java.util.stream.Collectors; /** * Authenticate a user from the database. */ @Component("userDetailsService") public class DomainUserDetailsService implements UserDetailsService { private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class); private final UserRepository userRepository; public DomainUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Override @Transactional public UserDetails loadUserByUsername(final String login) { log.debug("Authenticating {}", login); if (new EmailValidator().isValid(login, null)) { return userRepository.findOneWithAuthoritiesByEmail(login) .map(user -> createSpringSecurityUser(login, user)) .orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database")); } String lowercaseLogin = login.toLowerCase(Locale.ENGLISH); return userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin) .map(user -> createSpringSecurityUser(lowercaseLogin, user)) .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")); } private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) { if (!user.getActivated()) { throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); } List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream() .map(authority -> new SimpleGrantedAuthority(authority.getName())) .collect(Collectors.toList()); return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities); } }
ae8eeac397f553d45121725f0d29f9bea540b90f
aafb4a4825eab483702d004760902a1c13a0a3d8
/JavaEx2/src/chapter11/DecimalFormatExample.java
b4ffcd54572d1d60d0efe8c293395c1a450e7754
[]
no_license
Jiwon0801/JAVA
120d6d187778920d57b49438a8b7c0c4fd4fa04e
7820eeff663a376ea1ee1db1b5a35a7042f89b0a
refs/heads/master
2020-04-22T03:36:55.584928
2019-02-11T10:39:14
2019-02-11T10:39:14
170,093,931
0
0
null
null
null
null
UTF-8
Java
false
false
1,314
java
package chapter11; import java.text.DecimalFormat; public class DecimalFormatExample { public static void main(String[] args) { double num = 1234567.89; DecimalFormat df = new DecimalFormat("0"); System.out.println(df.format(num)); df = new DecimalFormat("0.0"); System.out.println(df.format(num)); df = new DecimalFormat("0000000000.00000"); System.out.println(df.format(num)); df = new DecimalFormat("#"); System.out.println(df.format(num)); df = new DecimalFormat("#.#"); System.out.println(df.format(num)); df = new DecimalFormat("#########.#####"); System.out.println(df.format(num)); df = new DecimalFormat("#.0"); System.out.println(df.format(num)); df = new DecimalFormat("+#.0"); System.out.println(df.format(num)); df = new DecimalFormat("-#.0"); System.out.println(df.format(num)); df = new DecimalFormat("#,###.0"); System.out.println(df.format(num)); df = new DecimalFormat("0.0E0"); System.out.println(df.format(num)); df = new DecimalFormat("+#,### ; -#,###"); System.out.println(df.format(num)); df = new DecimalFormat("#.# %"); System.out.println(df.format(num)); df = new DecimalFormat("\u00A4 #,###"); System.out.println(df.format(num)); } }
e7ea2c7e0f4dd3b6585bed9c11f242df23f844ac
558394750002c6ca8429a349567f8e5ef95f474c
/app/src/main/java/example/beyondar/com/postexample/database/AppDatabase.java
666eab7c7c2b01585550c20fa51524d0d1e32cd6
[]
no_license
thilinawarnakula/Posts-Application-android
04c6f5a849b867c2f4e741259f383903a750d5ff
823f8e8e2868e216c2fedc56a7897fe3e4678fc5
refs/heads/master
2020-09-25T14:21:10.560338
2019-12-05T13:32:52
2019-12-05T13:32:52
226,022,586
1
0
null
null
null
null
UTF-8
Java
false
false
1,110
java
package example.beyondar.com.postexample.database; import androidx.room.Database; import androidx.room.RoomDatabase; import example.beyondar.com.postexample.model.entity.masterdata.Comments; import example.beyondar.com.postexample.model.entity.masterdata.MasterData; import example.beyondar.com.postexample.model.entity.masterdata.Posts; import example.beyondar.com.postexample.model.entity.masterdata.Users; import example.beyondar.com.postexample.repository.dto.masterdata.CommentDao; import example.beyondar.com.postexample.repository.dto.masterdata.MasterDataDao; import example.beyondar.com.postexample.repository.dto.masterdata.PostDao; import example.beyondar.com.postexample.repository.dto.masterdata.UserDao; @Database(entities = { MasterData.class, Posts.class, Comments.class, Users.class }, version = 1, exportSchema = false) public abstract class AppDatabase extends RoomDatabase { public abstract MasterDataDao masterDataDao(); public abstract PostDao postDao(); public abstract CommentDao commentDao(); public abstract UserDao userDao(); }
e89667c80a49f84746d09960b7ea5fd73b6a9119
1e11d0bcf4c3f9c3dc937e5fc25687bf9d65de2a
/src/main/java/com/home/project/services/TopicService.java
aff7a20c562ac456b4b08c0eda05bdb8cede1c5d
[]
no_license
cvofravi/genieral
7e56f6227577709f3a3c77cc6b34dae56f61759a
7d05048b3e0239c262ef8245ef2da34a12fd4ad7
refs/heads/master
2020-04-13T06:22:17.288614
2018-12-24T19:38:42
2018-12-24T19:38:42
163,018,533
0
0
null
null
null
null
UTF-8
Java
false
false
1,130
java
package com.home.project.services; import com.home.project.domain.Topic; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Service public class TopicService { private List<Topic> topics = new ArrayList<>(Arrays.asList( new Topic("1","C Language","High Level Language"), new Topic("2","COBOL","High Level Language"), new Topic("3","Java","Object Oriented Language") )); public List<Topic> getAllTopics(){ return topics; } public Topic getTopic(String id){ return topics.stream() .filter(t -> t.getId().equals(id)) .findFirst() .get(); } public void addTopic(Topic topic) { topics.add(topic); } public void updateTopic(String id, Topic topic) { for(int i=0;i<topics.size();i++){ Topic t = topics.get(i); if(t.getId().equals(id)){ topics.set(i,topic); return; } } } public void deleteTopic(String id) { topics.removeIf(t -> t.getId().equals(id)); } }
bbacc84f7c1106ae9ffd9b1398c9421631c42af1
4d74ecbd6187a8917195c6c2061e0e6b501c62a4
/src/controller/DespesaControllerPT1.java
7dd7402a1a0ab69a914ec9e2911f9c7111ab4841
[ "MIT" ]
permissive
luis-sousa/GC-v1.1b
fbc88f7a23bb1789095b280adad3952626b789a8
b8e9087898439a33d5272a9402364454b7ad2743
refs/heads/master
2021-05-16T05:52:05.984677
2017-09-12T14:41:53
2017-09-12T14:41:53
103,272,609
0
0
null
null
null
null
UTF-8
Java
false
false
4,970
java
package controller; /* * ESTGF - Escola Superior de Tecnologia e Gestão de Felgueiras */ /* IPP - Instituto Politécnico do Porto */ /* LEI - Licenciatura em Engenharia Informática*/ /* Projeto Final 2013/2014 /* */ import application.DespesaPT1; import application.DespesaPT2; import dao.OrcamentoDAO; import java.net.URL; import java.sql.SQLException; import java.util.List; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.Stage; import model.Orcamento; /** * Classe DespesaControllerPT1 está responsável pelo controlo dos eventos * relativos á Stage que permite gerir despesas, permitindo escolher um * orçamento para depois se fazer o CRUD de despesas do mesmo * * @author Luís Sousa - 8090228 */ public class DespesaControllerPT1 implements Initializable { @FXML private TableColumn clVersao; @FXML private TableColumn clData; @FXML private TableColumn clAno; @FXML private Button btProximo; @FXML private TableView tbOrcamento; @FXML private ObservableList<Orcamento> orcamento; private int idOrcamentoSel; private int positionOrcamentoTable; private OrcamentoDAO dao; /** * Método que permite avançar para a Stage seguinte onde se começa a fazer o * CRUD das desepesas do Orçamento escolhido aqui * * @param event * @throws Exception */ @FXML private void btNextFired(ActionEvent event) throws ClassNotFoundException, SQLException, Exception { new DespesaControllerPT2().setIdOrc(getIdOrcamentoSel()); DespesaPT1.getStage().close(); new DespesaPT2().start(new Stage()); } /** * Devolve orçamento seleccionado * * @return orçamento */ private Orcamento getTableOrcamentoSeleccionado() { if (tbOrcamento != null) { List<Orcamento> tabela = tbOrcamento.getSelectionModel().getSelectedItems(); if (tabela.size() == 1) { final Orcamento orcamentoSeleccionado = tabela.get(0); return orcamentoSeleccionado; } } return null; } /** * Listener tableview que entra em ação quando muda o orcamento selecionado * na tabela */ private final ListChangeListener<Orcamento> selectorTableOrcamento = new ListChangeListener<Orcamento>() { @Override public void onChanged(ListChangeListener.Change<? extends Orcamento> c) { try { getIdOrcamentoSel(); btProximo.setDisable(false); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(OrcamentoControllerPT0.class.getName()).log(Level.SEVERE, null, ex); } } }; /** * Iniciar a tabela */ private void iniciarTableView() { clVersao.setCellValueFactory(new PropertyValueFactory<Orcamento, String>("versao")); clAno.setCellValueFactory(new PropertyValueFactory<Orcamento, Integer>("ano")); clData.setCellValueFactory(new PropertyValueFactory<Orcamento, String>("data")); orcamento = FXCollections.observableArrayList(); tbOrcamento.setItems(orcamento); } /** * Inicia a classe DespesaControllerPT1. * * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { this.iniciarTableView(); btProximo.setDisable(true); final ObservableList<Orcamento> tabelaOrcamentoSel = tbOrcamento.getSelectionModel().getSelectedItems(); tabelaOrcamentoSel.addListener(selectorTableOrcamento); dao = new OrcamentoDAO(); for (Orcamento orc : dao.getAllOrcamentos()) { if (orc.getEstado().equals("Definitivo")) { orcamento.add(orc); } } } /** * Método que retorna o id do Orçamento Seleccionado * * @return id do Orçamento */ private int getIdOrcamentoSel() throws ClassNotFoundException, SQLException { dao = new OrcamentoDAO(); int id; try { id = dao.getOrcamentoId(getTableOrcamentoSeleccionado().getVersao(), getTableOrcamentoSeleccionado().getAno()); } catch (Exception ex) { id = -1; } this.idOrcamentoSel = id; //System.out.println("ID SEL" + idOrcamentoSel); dao.close(); return id; } }
8400dbfe97e939319339011910ade61a649016a4
1a9c29b6f81d1d628200d61325a65b395a3bfb8d
/src/com/java/v2/activity/Test215Activity.java
5c7bdcfc89370a110452f17b97148663ad87378b
[]
no_license
sakiskaliakoudas/effective-octo-train
3407706bfa549b6105b1e4d0f13def438fbbe4ac
c3a7c06f4b7b22891dc7253be2c5131c54005d15
refs/heads/master
2023-05-30T18:45:42.004426
2021-06-28T07:01:27
2021-06-28T07:01:27
343,089,882
0
0
null
2021-06-28T07:01:28
2021-02-28T11:36:50
Shell
UTF-8
Java
false
false
43
java
This is a Test Activity 15 in v2 directory
1224ae5f6781cfe6178235ed99a82ea833139eef
9f37eb11dd30cfca66b9ec4e8c5bd09d2a015f67
/src/main/java/Project/DAO/ResultatDAO.java
36febfb8283daa1cdb741c41214a0b1546ba4225
[]
no_license
Pierre72250/SpringPong
aa06274c30d032ffbac9ece6b0b8dd06c77c32cb
360d1aeac890ad74e246cf57fc6b0cb066ddf155
refs/heads/master
2020-12-31T01:01:43.112274
2017-04-20T11:59:03
2017-04-20T11:59:03
80,601,520
0
0
null
null
null
null
UTF-8
Java
false
false
292
java
package Project.DAO; import Project.Model.Resultat; import Project.Model.User; public interface ResultatDAO { public Long add(Resultat resultat); public Long getTotalMatchs(User user); public Long getTotalVictories(User user); public Long getTotalLooses(User user); }
d18eae0f94d0adfe4fe2578d9610e94b57966bef
66c6ceb5bf304d1a6cc6c1bdadd9975a8f49d7b8
/core/src/test/java/com/expediagroup/rhapsody/core/work/WorkBuffererTest.java
58f233be067910e9c0fbd7718865b5339e3ca82a
[ "Apache-2.0" ]
permissive
nikos912000/rhapsody
552d18e6bac830a1d11de20207f64326b09d603f
348dfb13969f40436bb008565c65ea7bd0920ae5
refs/heads/master
2020-11-24T10:31:17.648431
2019-12-14T22:35:17
2019-12-14T22:35:17
228,109,169
0
0
NOASSERTION
2019-12-15T00:38:33
2019-12-15T00:38:32
null
UTF-8
Java
false
false
5,600
java
/** * Copyright 2019 Expedia, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.expediagroup.rhapsody.core.work; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.LongStream; import org.junit.Test; import org.reactivestreams.Publisher; import com.expediagroup.rhapsody.api.WorkType; import com.expediagroup.rhapsody.test.TestWork; import com.expediagroup.rhapsody.util.Defaults; import reactor.core.publisher.FluxProcessor; import reactor.core.publisher.UnicastProcessor; import reactor.test.StepVerifier; public class WorkBuffererTest { private static final Duration STEP_DURATION = Duration.ofMillis(200); private static final WorkBufferConfig BUFFER_CONFIG = new WorkBufferConfig(STEP_DURATION.multipliedBy(4), 8, Defaults.CONCURRENCY); private final FluxProcessor<TestWork, TestWork> eventQueue = UnicastProcessor.create(); private final Consumer<TestWork> eventConsumer = eventQueue.sink()::next; private final Publisher<List<TestWork>> buffer = eventQueue.transform(WorkBufferer.identity(BUFFER_CONFIG)); @Test public void bufferedCommitsAreImmediatelyEmitted() { TestWork commit1 = TestWork.create(WorkType.COMMIT, "SOME/URL/1"); TestWork commit2 = TestWork.create(WorkType.COMMIT, "SOME/URL/2"); StepVerifier.create(buffer) .then(() -> { eventConsumer.accept(commit1); eventConsumer.accept(commit2); }) .expectNext(Collections.singletonList(commit1)) .expectNext(Collections.singletonList(commit2)) .thenCancel() .verify(); } @Test public void bufferedNonCommitsAreEmittedAfterBufferDuration() { TestWork intent = TestWork.create(WorkType.INTENT, "SOME/URL"); TestWork retry = TestWork.create(WorkType.RETRY, "SOME/URL", intent.workHeader().inceptionEpochMilli() + 1L); TestWork cancel = TestWork.create(WorkType.CANCEL, "SOME/URL", retry.workHeader().inceptionEpochMilli() + 1L); StepVerifier.create(buffer) .then(() -> { eventConsumer.accept(intent); eventConsumer.accept(retry); eventConsumer.accept(cancel); }) .expectNoEvent(BUFFER_CONFIG.getBufferDuration().minus(STEP_DURATION)) .expectNext(Arrays.asList(intent, retry, cancel)) .thenCancel() .verify(); } @Test public void bufferedNonCommitsAreEmittedWithCommit() { TestWork intent = TestWork.create(WorkType.INTENT, "SOME/URL"); TestWork retry = TestWork.create(WorkType.RETRY, "SOME/URL", intent.workHeader().inceptionEpochMilli() + 1L); TestWork cancel = TestWork.create(WorkType.CANCEL, "SOME/URL", retry.workHeader().inceptionEpochMilli() + 1L); TestWork commit = TestWork.create(WorkType.COMMIT, "SOME/URL", cancel.workHeader().inceptionEpochMilli() + 1L); StepVerifier.create(buffer) .then(() -> { eventConsumer.accept(intent); eventConsumer.accept(retry); eventConsumer.accept(cancel); }) .expectNoEvent(STEP_DURATION) .then(() -> eventConsumer.accept(commit)) .expectNext(Arrays.asList(intent, retry, cancel, commit)) .thenCancel() .verify(); } @Test public void interleavedWorkAreBufferedCorrectly() { TestWork intent1 = TestWork.create(WorkType.INTENT, "SOME/URL/1"); TestWork commit1 = TestWork.create(WorkType.COMMIT, "SOME/URL/1", intent1.workHeader().inceptionEpochMilli() + 1L); TestWork intent2 = TestWork.create(WorkType.INTENT, "SOME/URL/2"); TestWork commit2 = TestWork.create(WorkType.COMMIT, "SOME/URL/2", intent2.workHeader().inceptionEpochMilli() + 1L); StepVerifier.create(buffer) .then(() -> { eventConsumer.accept(intent1); eventConsumer.accept(intent2); }) .expectNoEvent(STEP_DURATION) .then(() -> eventConsumer.accept(commit2)) .expectNext(Arrays.asList(intent2, commit2)) .expectNoEvent(STEP_DURATION) .then(() -> eventConsumer.accept(commit1)) .expectNext(Arrays.asList(intent1, commit1)) .thenCancel() .verify(); } @Test public void workIsBufferedUpToMaxSize() { TestWork intent = TestWork.create(WorkType.INTENT, "SOME/URL"); StepVerifier.create(buffer) .then(() -> LongStream.range(0, BUFFER_CONFIG.getMaxBufferSize() - 1).forEach(i -> eventConsumer.accept(intent))) .expectNoEvent(STEP_DURATION) .then(() -> eventConsumer.accept(intent)) .expectNext(LongStream.range(0, BUFFER_CONFIG.getMaxBufferSize()).mapToObj(i -> intent).collect(Collectors.toList())) .thenCancel() .verify(); } }
620b336309c75e6485584a88755f2ac9e0258d85
45797c09bef5a041ea975154060c4258ab8673f9
/Lecture23_24_25_BinaryTree/BinaryTreeUse.java
c95552e14de97e7a67438a13842505d3c9cfd3b5
[]
no_license
chaitanya9807/DsWithJava
5363a5664e8a8cead409e2decfb5402cfb43a83f
f50dc1cdbd2a39208a1d46301cf18a205d248a59
refs/heads/master
2020-04-16T14:22:42.595326
2019-08-18T13:11:22
2019-08-18T13:11:22
165,664,515
0
0
null
null
null
null
UTF-8
Java
false
false
13,084
java
package Lecture23_24_25_BinaryTree; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; class BalancedPair { int height; boolean isBalanced; } class DiameterPair { int height; int diameter; } class LinkedListNode<T> { T data; LinkedListNode<T> next; LinkedListNode(T data) { this.data = data; } } public class BinaryTreeUse { public static Scanner s = new Scanner(System.in); public static BinaryTreeNode<Integer> takeInput() { Queue<BinaryTreeNode<Integer>> queue = new LinkedList<>(); System.out.println("Enter root's data: "); int first = s.nextInt(); BinaryTreeNode<Integer> root = new BinaryTreeNode<>(first); queue.add(root); while (!queue.isEmpty()) { BinaryTreeNode<Integer> node = queue.remove(); System.out.println("Enter left child of " + node.data + ": "); int leftChild = s.nextInt(); if (leftChild != -1) { BinaryTreeNode<Integer> leftNode = new BinaryTreeNode<>(leftChild); node.left = leftNode; queue.add(leftNode); } System.out.println("Enter right child of " + node.data + ": "); int rightChild = s.nextInt(); if (rightChild != -1) { BinaryTreeNode<Integer> rightNode = new BinaryTreeNode<>(rightChild); node.right = rightNode; queue.add(rightNode); } } return root; } public static void PreOrderTraversal(BinaryTreeNode<Integer> root) { if (root == null) { return; } System.out.print(root.data + " "); PreOrderTraversal(root.left); PreOrderTraversal(root.right); } public static void InorderTraversal(BinaryTreeNode<Integer> root) { if (root == null) { return; } InorderTraversal(root.left); System.out.print(root.data + " "); InorderTraversal(root.right); } public static void PostOrderTraversal(BinaryTreeNode<Integer> root) { if (root == null) { return; } PostOrderTraversal(root.left); PostOrderTraversal(root.right); System.out.print(root.data + " "); } public static int sumOfAllNodes(BinaryTreeNode<Integer> root) { if (root == null) { return 0; } int sum = root.data; sum += sumOfAllNodes(root.left); sum += sumOfAllNodes(root.right); return sum; } public static int countNoOfNodes(BinaryTreeNode<Integer> root) { if (root == null) { return 0; } int count = 1; count += countNoOfNodes(root.left); count += countNoOfNodes(root.right); return count; } public static boolean FindNode(BinaryTreeNode<Integer> root, int n) { if (root == null) { return false; } if (root.data == n) { return true; } if (FindNode(root.left, n)) { return true; } else if (FindNode(root.right, n)) { return true; } return false; } public static int countLeafNodes(BinaryTreeNode<Integer> root) { if (root == null) { return 0; } if (root.left == null && root.right == null) { return 1; } else { int count = 0; count += countLeafNodes(root.left); count += countLeafNodes(root.right); return count; } } public static void Mirror(BinaryTreeNode<Integer> root) { if (root == null) { return; } Mirror(root.left); Mirror(root.right); BinaryTreeNode<Integer> temp = root.left; root.left = root.right; root.right = temp; } public static BinaryTreeNode<Integer> findMaxDataNode(BinaryTreeNode<Integer> root) { if (root == null) { BinaryTreeNode<Integer> base = new BinaryTreeNode<>(Integer.MIN_VALUE); return base; } BinaryTreeNode<Integer> leftMax = findMaxDataNode(root.left); BinaryTreeNode<Integer> rightMax = findMaxDataNode(root.right); BinaryTreeNode<Integer> maxNode = root; if (maxNode.data > leftMax.data && maxNode.data > rightMax.data) { return maxNode; } else if (leftMax.data > maxNode.data && leftMax.data > rightMax.data) { return leftMax; } else { return rightMax; } } public static void PrintLevelWise(BinaryTreeNode<Integer> root) { Queue<BinaryTreeNode<Integer>> queue = new LinkedList<>(); queue.add(root); queue.add(null); while (!queue.isEmpty()) { BinaryTreeNode<Integer> node = queue.remove(); if (node == null) { if (!queue.isEmpty()) { queue.add(null); System.out.println(); } } else { System.out.print(node.data + " "); } } } public static int NodesGreaterThanX(BinaryTreeNode<Integer> root, int x) { if (root == null) { return 0; } int count = 0; if (root.data > x) { count++; } count += NodesGreaterThanX(root.left, x); count += NodesGreaterThanX(root.right, x); return count; } public static void printLevelWiseColonPattern(BinaryTreeNode<Integer> root) { Queue<BinaryTreeNode<Integer>> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { BinaryTreeNode<Integer> node = queue.remove(); String str = node.data + ":L:"; if (node.left != null) { str += node.left.data + ",R:"; queue.add(node.left); } else { str += "-1,R:"; } if (node.right != null) { str += node.right.data; queue.add(node.right); } else { str += "-1"; } System.out.println(str); } } public static int height(BinaryTreeNode<Integer> root) { if (root == null) { return 0; } int leftHeight = height(root.left); int rightHeight = height(root.right); return Math.max(leftHeight, rightHeight) + 1; } /* visiting each node twice to get two different values instead make a class with the required properties and return the object of that class making the code efficient and hence making the approach bad. */ public static boolean isBalanced(BinaryTreeNode<Integer> root) { if (root == null) { return true; } int leftHeight = height(root.left); int rightHeight = height(root.right); if (Math.abs(leftHeight - rightHeight) <= 1) { return isBalanced(root.left) && isBalanced(root.right); } else { return false; } } public static BalancedPair isBalanceBetterApproach(BinaryTreeNode<Integer> root) { if (root == null) { BalancedPair BaseCase = new BalancedPair(); BaseCase.height = 0; BaseCase.isBalanced = true; return BaseCase; } BalancedPair left = isBalanceBetterApproach(root.left); BalancedPair right = isBalanceBetterApproach(root.right); BalancedPair retVal = new BalancedPair(); retVal.height = Math.max(left.height, right.height) + 1; /*if (Math.abs(left.height - right.height) <= 1) { retVal.isBalanced = left.isBalanced && right.isBalanced; } else { retVal.isBalanced = false; }*/ retVal.isBalanced = Math.abs(left.height - right.height) <= 1 && (left.isBalanced && right.isBalanced); return retVal; } /* visiting each node twice to get two different values instead make a class with the required properties and return the object of that class making the code efficient and hence making the approach bad. */ public static int diameter(BinaryTreeNode<Integer> root) { if (root == null) { return 0; } int height = height(root.left) + height(root.right); int leftDiam = diameter(root.left); int rightDiam = diameter(root.right); return Math.max(height, Math.max(leftDiam, rightDiam)); } public static DiameterPair diameterBetter(BinaryTreeNode<Integer> root) { if (root == null) { DiameterPair BaseCase = new DiameterPair(); return BaseCase; } DiameterPair left = diameterBetter(root.left); DiameterPair right = diameterBetter(root.right); DiameterPair retVal = new DiameterPair(); retVal.height = Math.max(left.height, right.height) + 1; retVal.diameter = Math.max((left.height + right.height + 1), Math.max(left.diameter, right.diameter)); return retVal; } public static BinaryTreeNode<Integer> ConstructWithInorderAndPreorder(int[] pre, int sPre, int ePre, int[] In, int sIn, int eIn) { if ((sPre > ePre) || (sIn > eIn)) { return null; } int rootelement = pre[sPre]; BinaryTreeNode<Integer> root = new BinaryTreeNode<>(rootelement); int pos = -1; for (int i = sIn; i <= eIn; i++) { if (In[i] == rootelement) { pos = i; break; } } int count = pos - sIn; root.left = ConstructWithInorderAndPreorder(pre, sPre + 1, sPre + count, In, sIn, pos - 1); root.right = ConstructWithInorderAndPreorder(pre, sPre + count + 1, ePre, In, pos + 1, eIn); return root; } public static BinaryTreeNode<Integer> SearchInBST(BinaryTreeNode<Integer> root, int element) { if (root == null) { return null; } if (root.data == element) { return root; } else { if (root.data < element) { return SearchInBST(root.right, element); } else { return SearchInBST(root.left, element); } } } public static ArrayList findPath(BinaryTreeNode<Integer> root, int element) { if (root == null) { return null; } if (root.data == element) { ArrayList<Integer> path = new ArrayList<>(); path.add(root.data); return path; } else if (root.data > element) { ArrayList<Integer> path = findPath(root.left, element); if (path != null) { path.add(root.data); } return path; } else { ArrayList<Integer> path = findPath(root.right, element); if (path != null) { path.add(root.data); } return path; } } public static BinaryTreeNode<Integer> generateBST(int[] arr, int sI, int eI) { if (sI > eI) { return null; } int mid = (sI + eI) / 2; BinaryTreeNode<Integer> root = new BinaryTreeNode<>(arr[mid]); root.left = generateBST(arr, sI, mid - 1); root.right = generateBST(arr, mid + 1, eI); return root; } public static LinkedListNode<Integer> BSTtoSortedLL(BinaryTreeNode<Integer> root) { if (root == null) { return null; } LinkedListNode<Integer> rootNode = new LinkedListNode<>(root.data); LinkedListNode<Integer> head = rootNode; LinkedListNode<Integer> leftHead = BSTtoSortedLL(root.left); LinkedListNode<Integer> rightHead = BSTtoSortedLL(root.right); if (leftHead != null) { head = leftHead; LinkedListNode<Integer> temp = leftHead; while (temp.next != null) { temp = temp.next; } temp.next = rootNode; } rootNode.next = rightHead; return head; } public static boolean isBST_(BinaryTreeNode<Integer> root, int min, int max) { if (root == null) { return true; } if (root.data >= min && root.data <= max) { return isBST_(root.left, min, root.data - 1) && isBST_(root.right, root.data, max); } else { return false; } } public static void main(String[] args) { BinaryTreeNode<Integer> root = takeInput(); PrintLevelWise(root); } }
7e2ac0b8844402ad9cac6b4436a0beee691f036a
2a27f061cb7cbedce3a87eba996364d194a9ce40
/src/main/java/com/example/demo/_config/MongoConfig.java
747c75f3999d763e3637bc9543ae2e22b27a660b
[]
no_license
tlacuache987/spring-data-mongodb-listeners
15c27577f877c56d16311dab082735f23b1b4d7b
44275d643c3a14c4071053705f2928ecf24c4350
refs/heads/master
2020-03-23T14:54:51.527077
2018-07-20T12:19:42
2018-07-20T12:19:42
141,707,805
0
0
null
null
null
null
UTF-8
Java
false
false
731
java
package com.example.demo._config; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.config.AbstractMongoConfiguration; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import com.mongodb.Mongo; import com.mongodb.MongoClient; @Configuration @EnableMongoRepositories(basePackages = "com.example.demo.repository") public class MongoConfig extends AbstractMongoConfiguration { @Override public String getDatabaseName() { return "local"; } @Override public Mongo mongo() throws Exception { return new MongoClient("127.0.0.1", 27017); } @Override protected String getMappingBasePackage() { return "com.example.demo.documents"; } }
17d8fce53b36b309bd5fd0814a5c928452b36358
4d3c211bc491072ba9b815fd87f5b6fbcb08fb70
/JavaStudy/src/ch06/Exam6_3_2.java
bf540ed2c7fbf6076e40cf8bae63cf0632e83723
[]
no_license
ShinDaeCheol/JavaStudy
00ee2a18941f8ab6b598870887c9b8f9b184eab5
0305e36bc250277345ec898511d79ed869a4d76f
refs/heads/master
2020-04-28T19:40:57.612687
2019-03-20T08:36:46
2019-03-20T08:36:46
175,518,961
0
0
null
null
null
null
UTF-8
Java
false
false
52
java
package ch06; public class Exam6_3_2 { }
[ "Student@DESKTOP-EF9PEQ2" ]
Student@DESKTOP-EF9PEQ2
5e8faa9af06510f8d5851dd46c5e6089f6cf046a
4e16a6780f479bf703e240a1549d090b0bafc53b
/work/decompile-c69e3af0/net/minecraft/world/level/block/piston/BlockPistonMoving.java
523f0aa95b602930313de5ab135bee4ea4dc8392
[]
no_license
0-Yama/ServLT
559b683832d1f284b94ef4a9dbd4d8adb543e649
b2153c73bea55fdd4f540ed2fba3a1e46ec37dc5
refs/heads/master
2023-03-16T01:37:14.727842
2023-03-05T14:55:51
2023-03-05T14:55:51
302,899,503
0
2
null
2020-10-15T10:51:21
2020-10-10T12:42:47
JavaScript
UTF-8
Java
false
false
6,968
java
package net.minecraft.world.level.block.piston; import java.util.Collections; import java.util.List; import javax.annotation.Nullable; import net.minecraft.core.BlockPosition; import net.minecraft.core.EnumDirection; import net.minecraft.world.EnumHand; import net.minecraft.world.EnumInteractionResult; import net.minecraft.world.entity.player.EntityHuman; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.GeneratorAccess; import net.minecraft.world.level.IBlockAccess; import net.minecraft.world.level.World; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.BlockTileEntity; import net.minecraft.world.level.block.EnumBlockMirror; import net.minecraft.world.level.block.EnumBlockRotation; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.TileEntity; import net.minecraft.world.level.block.entity.TileEntityTypes; import net.minecraft.world.level.block.state.BlockBase; import net.minecraft.world.level.block.state.BlockStateList; import net.minecraft.world.level.block.state.IBlockData; import net.minecraft.world.level.block.state.properties.BlockPropertyPistonType; import net.minecraft.world.level.block.state.properties.BlockStateDirection; import net.minecraft.world.level.block.state.properties.BlockStateEnum; import net.minecraft.world.level.pathfinder.PathMode; import net.minecraft.world.level.storage.loot.LootTableInfo; import net.minecraft.world.level.storage.loot.parameters.LootContextParameters; import net.minecraft.world.phys.MovingObjectPositionBlock; import net.minecraft.world.phys.Vec3D; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShapeCollision; import net.minecraft.world.phys.shapes.VoxelShapes; public class BlockPistonMoving extends BlockTileEntity { public static final BlockStateDirection FACING = BlockPistonExtension.FACING; public static final BlockStateEnum<BlockPropertyPistonType> TYPE = BlockPistonExtension.TYPE; public BlockPistonMoving(BlockBase.Info blockbase_info) { super(blockbase_info); this.registerDefaultState((IBlockData) ((IBlockData) ((IBlockData) this.stateDefinition.any()).setValue(BlockPistonMoving.FACING, EnumDirection.NORTH)).setValue(BlockPistonMoving.TYPE, BlockPropertyPistonType.DEFAULT)); } @Nullable @Override public TileEntity newBlockEntity(BlockPosition blockposition, IBlockData iblockdata) { return null; } public static TileEntity newMovingBlockEntity(BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1, EnumDirection enumdirection, boolean flag, boolean flag1) { return new TileEntityPiston(blockposition, iblockdata, iblockdata1, enumdirection, flag, flag1); } @Nullable @Override public <T extends TileEntity> BlockEntityTicker<T> getTicker(World world, IBlockData iblockdata, TileEntityTypes<T> tileentitytypes) { return createTickerHelper(tileentitytypes, TileEntityTypes.PISTON, TileEntityPiston::tick); } @Override public void onRemove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { if (!iblockdata.is(iblockdata1.getBlock())) { TileEntity tileentity = world.getBlockEntity(blockposition); if (tileentity instanceof TileEntityPiston) { ((TileEntityPiston) tileentity).finalTick(); } } } @Override public void destroy(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata) { BlockPosition blockposition1 = blockposition.relative(((EnumDirection) iblockdata.getValue(BlockPistonMoving.FACING)).getOpposite()); IBlockData iblockdata1 = generatoraccess.getBlockState(blockposition1); if (iblockdata1.getBlock() instanceof BlockPiston && (Boolean) iblockdata1.getValue(BlockPiston.EXTENDED)) { generatoraccess.removeBlock(blockposition1, false); } } @Override public EnumInteractionResult use(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { if (!world.isClientSide && world.getBlockEntity(blockposition) == null) { world.removeBlock(blockposition, false); return EnumInteractionResult.CONSUME; } else { return EnumInteractionResult.PASS; } } @Override public List<ItemStack> getDrops(IBlockData iblockdata, LootTableInfo.Builder loottableinfo_builder) { TileEntityPiston tileentitypiston = this.getBlockEntity(loottableinfo_builder.getLevel(), new BlockPosition((Vec3D) loottableinfo_builder.getParameter(LootContextParameters.ORIGIN))); return tileentitypiston == null ? Collections.emptyList() : tileentitypiston.getMovedState().getDrops(loottableinfo_builder); } @Override public VoxelShape getShape(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { return VoxelShapes.empty(); } @Override public VoxelShape getCollisionShape(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { TileEntityPiston tileentitypiston = this.getBlockEntity(iblockaccess, blockposition); return tileentitypiston != null ? tileentitypiston.getCollisionShape(iblockaccess, blockposition) : VoxelShapes.empty(); } @Nullable private TileEntityPiston getBlockEntity(IBlockAccess iblockaccess, BlockPosition blockposition) { TileEntity tileentity = iblockaccess.getBlockEntity(blockposition); return tileentity instanceof TileEntityPiston ? (TileEntityPiston) tileentity : null; } @Override public ItemStack getCloneItemStack(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata) { return ItemStack.EMPTY; } @Override public IBlockData rotate(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { return (IBlockData) iblockdata.setValue(BlockPistonMoving.FACING, enumblockrotation.rotate((EnumDirection) iblockdata.getValue(BlockPistonMoving.FACING))); } @Override public IBlockData mirror(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { return iblockdata.rotate(enumblockmirror.getRotation((EnumDirection) iblockdata.getValue(BlockPistonMoving.FACING))); } @Override protected void createBlockStateDefinition(BlockStateList.a<Block, IBlockData> blockstatelist_a) { blockstatelist_a.add(BlockPistonMoving.FACING, BlockPistonMoving.TYPE); } @Override public boolean isPathfindable(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { return false; } }
3d5ad08f1e69c00d52907c56bbaef4164ffcc440
99b05f5d84f6abac8f786d95d39993d4d058dea0
/src/main/java/mcf/UFST_test/NumberToStringConverter.java
7d1d1edb3bf3fba88483b9b8d23e143dd391bafa
[]
no_license
mf226/UFST_test
6ae18ff551fff45adec995b57c5cd36911d1f1c7
54f5a1b742737817c506f4693f0f04159ca3e92a
refs/heads/master
2023-02-11T05:03:11.027486
2021-01-05T16:54:03
2021-01-05T16:54:03
326,678,642
0
0
null
null
null
null
UTF-8
Java
false
false
3,969
java
package mcf.UFST_test; import javax.inject.Singleton; @Singleton public class NumberToStringConverter { public NumberToStringConverter(){ } public String NumberToString(double value) { if(value < 0) { throw new IllegalArgumentException("Negative number not allowed"); } if(value >= 1000000) { throw new IllegalArgumentException("Number in millions not allowed"); } String[] numbers = String.valueOf(String.format("%.2f", value)).split("\\,"); int decimals = numbers.length > 1 ? Integer.parseInt(numbers[1]) : 0; String text1 = doubleToText(Integer.parseInt(numbers[0]), "DOLLAR"); String text2 = doubleToText(decimals, "CENT"); return formatString(text1.concat(" AND ").concat(text2)); } private String doubleToText(int number, String appendingText) { // making the appending text plural char[] numberArray = number != 0 ? String.valueOf(number).toCharArray() : new char[]{}; appendingText = number != 1 ? appendingText.concat("S") : appendingText; return convert(numberArray, numberArray.length, appendingText, ""); } private String convert(char[] number, int index, String appendingText, String resultText) { resultText += " "; if (index == 0 && number.length == 0 && resultText.trim().isEmpty()) { return String.format("ZERO %s", appendingText); } else if (index == 0) { return String.format("%1$s %2$s", resultText, appendingText); } int currentIndex = number.length - index; switch (index % 3) { case 0: // hundreds resultText += getNumber(Integer.parseInt(String.valueOf(number[currentIndex])), false, "HUNDRED"); break; case 1: // single resultText += getNumber(Character.getNumericValue(number[currentIndex]), false, ""); break; case 2: // tens int tmpNumber = Integer.parseInt(number[currentIndex] + String.valueOf(number[currentIndex + 1])); if (tmpNumber > 10 && tmpNumber < 20) { resultText += getTeenNumbers(tmpNumber); index -= 1; break; } resultText += getNumber(Character.getNumericValue(number[currentIndex]), true, ""); } index -= 1; if (index == 3) { resultText += " THOUSAND"; } return convert(number, index, appendingText, resultText); } String formatString(String txt) { return txt.trim().replaceAll("\\s{2,}", " ").toUpperCase(); //return txt.substring(0, 1).toUpperCase() + txt.substring(1); } String getTeenNumbers(int number) { switch (number) { case 11: return "ELEVEN"; case 12: return "TWELVE"; case 13: return "THIRTEEN"; case 14: return "FOURTEEN"; case 15: return "FIFTEEN"; case 16: return "SIXTEEN"; case 17: return "SEVENTEEN"; case 18: return "EIGHTEEN"; case 19: return "NINETEEN"; default: return ""; } } String getNumber(int number, boolean tens, String appendingText) { String[][] numbers = new String[][]{ {"", ""}, {"ONE", "TEN"}, {"TWO", "TWENTY"}, {"THREE", "THIRTY"}, {"FOUR", "FORTY"}, {"FIVE", "FIFTY"}, {"SIX", "SIXTY"}, {"SEVEN", "SEVENTY"}, {"EIGHT", "EIGHTY"}, {"NINE", "NINETY"}, }; return numbers[number][tens ? 1 : 0] + (number > 0 ? " " + appendingText : ""); } }
d18d511a74913ddb419ef3e3a41d7edb3b5d4d45
256439126c147b046145b8bedcae26d8d7753806
/src/main/java/com/github/chunkmerge/util/AbstractIterator.java
63f2a1b73cfb8e7f7da6d5451f1575f48d12e836
[ "Apache-2.0" ]
permissive
stefanmahler/chunkmerge
e5253c2667242dd1fc3a2b3fafbe1ed087b7cfb9
6818e3cfe1f90f2fc9d4d0a27ea331c21f0b61aa
refs/heads/master
2021-01-01T18:27:57.584466
2020-11-11T16:57:46
2020-11-11T16:57:46
17,843,369
0
0
null
null
null
null
UTF-8
Java
false
false
426
java
package com.github.chunkmerge.util; import java.util.Iterator; import java.util.NoSuchElementException; public abstract class AbstractIterator<T> implements Iterator<T> { @Override public final void remove() { throw new UnsupportedOperationException("remove() is not supported."); } protected final void validateHasNext() { if (!hasNext()) { throw new NoSuchElementException(toString()); } } }
6b73e960a877365c1d80b166e7d139ce7c987c7f
ce303c0e1f610f17eaa260c22db14caebaf62e4f
/src/main/java/com/newswebsite/dao/ArticleDao.java
f8787816e0feedc79e20f483bfcb790a17b08251
[]
no_license
VedgeKonn/NewsWebsite
f7759f565630ebcc28cd97cd4e07982c4081a27e
60a73e35e623ae0505245081a7787242a51c00b2
refs/heads/master
2021-01-20T16:10:06.389044
2017-05-23T06:51:45
2017-05-23T06:51:45
81,537,905
0
0
null
null
null
null
UTF-8
Java
false
false
550
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.newswebsite.dao; /** * * @author ivan */ import java.util.List; import com.newswebsite.model.Article; public interface ArticleDao { Article findById(int id); void saveArticle(Article article); void deleteArticleById(int id); List<Article> findAllArticles(); Article findArticleById(int id); }
b076c96c5cbed7d25ddf2a64196ef759a2ac771a
9907c42e682abe96d43c58ed1d669aa80869d512
/src/test/java/com/zendesk/maxwell/AbstractIntegrationTest.java
a4526380984bc3cffad6a8cff6b2f328f3aacd1b
[ "Apache-2.0" ]
permissive
vishnuagarwal21/maxwell
b84f23f41da67e3e682532fb482ef19d6d354caa
405b6e18087ad0c832b8e96d8860d4afe992b5bf
refs/heads/master
2021-01-18T00:16:33.028895
2016-03-01T03:20:03
2016-03-01T03:20:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,715
java
package com.zendesk.maxwell; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang.StringUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class AbstractIntegrationTest extends AbstractMaxwellTest { public static final TypeReference<Map<String, Object>> MAP_STRING_OBJECT_REF = new TypeReference<Map<String, Object>>() {}; ObjectMapper mapper = new ObjectMapper(); protected Map<String, Object> parseJSON(String json) throws Exception { mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); return mapper.readValue(json, MaxwellIntegrationTest.MAP_STRING_OBJECT_REF); } private void runJSONTest(List<String> sql, List<Map<String, Object>> expectedJSON) throws Exception { List<Map<String, Object>> eventJSON = new ArrayList<>(); List<Map<String, Object>> matched = new ArrayList<>(); List<RowMap> rows = getRowsForSQL(null, sql.toArray(new String[sql.size()])); for ( RowMap r : rows ) { String s = r.toJSON(); Map<String, Object> outputMap = parseJSON(s); outputMap.remove("ts"); outputMap.remove("xid"); outputMap.remove("commit"); eventJSON.add(outputMap); for ( Map<String, Object> b : expectedJSON ) { if ( outputMap.equals(b) ) matched.add(b); } } for ( Map j : matched ) { expectedJSON.remove(j); } if ( expectedJSON.size() > 0 ) { String msg = "Did not find: \n" + StringUtils.join(expectedJSON.iterator(), "\n") + "\n\n in : " + StringUtils.join(eventJSON.iterator(), "\n"); assertThat(msg, false, is(true)); } } protected void runJSONTestFile(String fname) throws Exception { File file = new File(fname); ArrayList<Map<String, Object>> jsonAsserts = new ArrayList<>(); ArrayList<String> inputSQL = new ArrayList<>(); BufferedReader reader = new BufferedReader(new FileReader(file)); ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); while ( reader.ready() ) { String line = reader.readLine(); if ( line.matches("^\\s*$")) { continue; } if ( line.matches("^\\s*\\->\\s*\\{.*") ) { line = line.replaceAll("^\\s*\\->\\s*", ""); jsonAsserts.add(mapper.<Map<String, Object>>readValue(line, MaxwellIntegrationTest.MAP_STRING_OBJECT_REF)); } else { inputSQL.add(line); } } reader.close(); runJSONTest(inputSQL, jsonAsserts); } }
b9b4924b8a1b6d68b9dc74ca0da3f1a917ebc8ea
a7e9ff833c38c32d41317af95ef3dcc911bb40b3
/src/enumerators/EnumTipoServico.java
a599fbc8d0b826438a8a306983b4ccb0cfa6e2a0
[]
no_license
ttuca123/selenium
31c1eea4e9b2de727915cd27a097ba01ee6f3498
e2360ab43db3b9f8882f0d808900c2d4c4acb4c7
refs/heads/master
2021-05-02T08:50:19.757076
2018-02-08T20:38:32
2018-02-08T20:38:32
120,813,658
0
0
null
null
null
null
UTF-8
Java
false
false
329
java
package enumerators; public enum EnumTipoServico { SIMPLES("SIMPLES"), CASADO("CASADO"), INTEGRADO("INTEGRADO"); private String valor; private EnumTipoServico(String valor) { this.valor = valor; } public String getValor() { return valor; } public void setValor(String valor) { this.valor = valor; } }
d51bdb3951ef4c3eb09952554c7d3d9853397f53
4c30a2811698a209bad3801b76f0fcd212352cb4
/src/com/anterp/modules/custom/CustomController.java
3743750333a3193fefb296e915fb76ced77c586b
[]
no_license
dineshkummarc/AntERP
c898763b0b3827abf18e1ad39ca16fb8f62afafc
b9c2abe6014f783df1f7bd7fb6ff829e0f1e7537
refs/heads/master
2021-01-17T21:30:26.903558
2012-05-13T07:59:08
2012-05-13T07:59:08
4,403,184
0
0
null
null
null
null
UTF-8
Java
false
false
3,814
java
package com.anterp.modules.custom; import java.util.List; import org.apache.ibatis.session.RowBounds; import org.apache.log4j.Logger; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.anterp.modules.Controllers; import com.anterp.modules.Pagers; import com.anterp.mybatis.domain.Custom; import com.anterp.mybatis.domain.CustomExample; import com.anterp.mybatis.mapper.CustomMapper; import com.anterp.tool.JsonUtil; @Controller @RequestMapping("/modules/custom") public class CustomController { private Logger logger = Logger.getLogger(CustomController.class); @Autowired private CustomMapper customMapper; @Autowired private CustomService customService; @Autowired @Qualifier("anterpSqlSessionTemplate") private SqlSessionTemplate sqlSessionTemplate; @RequestMapping("/getAll") public String getAllCustom( @RequestParam("page") int page, @RequestParam("rows") int rows, @RequestParam(value = "searchName", required = false) String searchName, @RequestParam(value = "searchPhone", required = false) String searchPhone, Model model) { System.out.println(searchName + "," + searchPhone); // 查询条件 CustomExample example = new CustomExample(); if (searchName != null) { example.createCriteria().andCustnameLikeInsensitive( "%" + searchName + "%"); } if (searchPhone != null) { example.createCriteria().andPhonenoLikeInsensitive( "%" + searchPhone + "%"); } customMapper.selectByExample(example); // 分页参数 RowBounds rowBounds = new RowBounds(Pagers.getOffset(page, rows), rows); int totalNumber = customMapper.countByExample(example); example.setOrderByClause("lastmodifytime DESC"); @SuppressWarnings("unchecked") List<Custom> customs = (List<Custom>) sqlSessionTemplate.selectList( "com.anterp.mybatis.mapper.CustomMapper.selectByExample", example, rowBounds); model.addAttribute("rows", customs); model.addAttribute("page", page); model.addAttribute("total", Pagers.getTotalPage(totalNumber, rows)); model.addAttribute("records", totalNumber); // System.out.println("page:" + page + ",rows:" + rows); // System.out.println(customs.size()); return Controllers.JsonViewName; } @RequestMapping("/create") public String createCustom(@RequestParam("custom") String customStr, Model model) { try { Custom custom = JsonUtil.getObject(Custom.class, customStr); this.customService.createCustom(custom); Controllers.setSuccess(model); } catch (Throwable e) { logger.error("Create custom error", e); Controllers.setError(model, "custom.001", "Create custom error."); } return Controllers.JsonViewName; } @RequestMapping("/update") public String updateCustom(@RequestParam("custom") String customStr, Model model) { try { Custom custom = JsonUtil.getObject(Custom.class, customStr); this.customService.updateCustom(custom); Controllers.setSuccess(model); } catch (Throwable e) { logger.error("Update custom error", e); Controllers.setError(model, "custom.002", "Update custom error."); } return Controllers.JsonViewName; } @RequestMapping("/delete") public String deleteCustom(@RequestParam("custId") int custId, Model model) { try { this.customMapper.deleteByPrimaryKey(custId); Controllers.setSuccess(model); } catch (Throwable t) { logger.error("Delete custom error", t); Controllers.setError(model, "custom.003", "Delete custom error."); } return Controllers.JsonViewName; } }
2bd15b51b811b483b943bdf17faf5e4eb773a94a
77edae6393a73e14231e838554075ba29195ec3f
/app/src/main/java/com/gordon/olver/weidumovie/model/md5/Base64.java
a6701de72a06e231cbcefccac7e1ec81412bcd36
[]
no_license
zhaoguangjin/WeiDuMovies-master
2745d0328ae1626fcf34df3b6edc63310ef83f0a
326ee17b5962f81fb48be02f5c10631df95fd58e
refs/heads/master
2020-05-07T21:52:17.824305
2019-04-12T02:28:36
2019-04-12T02:28:36
180,914,903
0
0
null
null
null
null
UTF-8
Java
false
false
10,991
java
/* * Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * Copyright 1999-2002,2004 The Apache Software Foundation. * * 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.gordon.olver.weidumovie.model.md5; /** * This class provides encode/decode for RFC 2045 Base64 as * defined by RFC 2045, N. Freed and N. Borenstein. * RFC 2045: Multipurpose Internet Mail Extensions (MIME) * Part One: Format of Internet Message Bodies. Reference * 1996 Available at: http://www.ietf.org/rfc/rfc2045.txt * This class is used by XML Schema binary format validation * * This implementation does not encode/decode streaming * data. You need the data that you will encode/decode * already on a byte arrray. * * @xerces.internal * * @author Jeffrey Rodriguez * @author Sandy Gao */ public final class Base64 { static private final int BASELENGTH = 128; static private final int LOOKUPLENGTH = 64; static private final int TWENTYFOURBITGROUP = 24; static private final int EIGHTBIT = 8; static private final int SIXTEENBIT = 16; static private final int SIXBIT = 6; static private final int FOURBYTE = 4; static private final int SIGN = -128; static private final char PAD = '='; static private final boolean fDebug = false; static final private byte [] base64Alphabet = new byte[BASELENGTH]; static final private char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; static { for (int i = 0; i < BASELENGTH; ++i) { base64Alphabet[i] = -1; } for (int i = 'Z'; i >= 'A'; i--) { base64Alphabet[i] = (byte) (i-'A'); } for (int i = 'z'; i>= 'a'; i--) { base64Alphabet[i] = (byte) ( i-'a' + 26); } for (int i = '9'; i >= '0'; i--) { base64Alphabet[i] = (byte) (i-'0' + 52); } base64Alphabet['+'] = 62; base64Alphabet['/'] = 63; for (int i = 0; i<=25; i++) lookUpBase64Alphabet[i] = (char)('A'+i); for (int i = 26, j = 0; i<=51; i++, j++) lookUpBase64Alphabet[i] = (char)('a'+ j); for (int i = 52, j = 0; i<=61; i++, j++) lookUpBase64Alphabet[i] = (char)('0' + j); lookUpBase64Alphabet[62] = (char)'+'; lookUpBase64Alphabet[63] = (char)'/'; } protected static boolean isWhiteSpace(char octect) { return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); } protected static boolean isPad(char octect) { return (octect == PAD); } protected static boolean isData(char octect) { return (octect < BASELENGTH && base64Alphabet[octect] != -1); } protected static boolean isBase64(char octect) { return (isWhiteSpace(octect) || isPad(octect) || isData(octect)); } /** * Encodes hex octects into Base64 * * @param binaryData Array containing binaryData * @return Encoded Base64 array */ public static String encode(byte[] binaryData) { if (binaryData == null) return null; int lengthDataBits = binaryData.length*EIGHTBIT; if (lengthDataBits == 0) { return ""; } int fewerThan24bits = lengthDataBits%TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits/TWENTYFOURBITGROUP; int numberQuartet = fewerThan24bits != 0 ? numberTriplets+1 : numberTriplets; char encodedData[] = null; encodedData = new char[numberQuartet*4]; byte k=0, l=0, b1=0,b2=0,b3=0; int encodedIndex = 0; int dataIndex = 0; if (fDebug) { System.out.println("number of triplets = " + numberTriplets ); } for (int i=0; i<numberTriplets; i++) { b1 = binaryData[dataIndex++]; b2 = binaryData[dataIndex++]; b3 = binaryData[dataIndex++]; if (fDebug) { System.out.println( "b1= " + b1 +", b2= " + b2 + ", b3= " + b3 ); } l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc); if (fDebug) { System.out.println( "val2 = " + val2 ); System.out.println( "k4 = " + (k<<4)); System.out.println( "vak = " + (val2 | (k<<4))); } encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ]; encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ]; } // form integral number of 6-bit groups if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte) ( b1 &0x03 ); if (fDebug) { System.out.println("b1=" + b1); System.out.println("b1<<2 = " + (b1>>2) ); } byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; encodedData[encodedIndex++] = lookUpBase64Alphabet[ k<<4 ]; encodedData[encodedIndex++] = PAD; encodedData[encodedIndex++] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex +1 ]; l = ( byte ) ( b2 &0x0f ); k = ( byte ) ( b1 &0x03 ); byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; encodedData[encodedIndex++] = lookUpBase64Alphabet[ l<<2 ]; encodedData[encodedIndex++] = PAD; } return new String(encodedData); } /** * Decodes Base64 data into octects * * @param encoded string containing Base64 data * @return Array containind decoded data. */ public static byte[] decode(String encoded) { if (encoded == null) return null; char[] base64Data = encoded.toCharArray(); // remove white spaces int len = removeWhiteSpace(base64Data); if (len%FOURBYTE != 0) { return null;//should be divisible by four } int numberQuadruple = (len/FOURBYTE ); if (numberQuadruple == 0) return new byte[0]; byte decodedData[] = null; byte b1=0,b2=0,b3=0,b4=0; char d1=0,d2=0,d3=0,d4=0; int i = 0; int encodedIndex = 0; int dataIndex = 0; decodedData = new byte[ (numberQuadruple)*3]; for (; i<numberQuadruple-1; i++) { if (!isData( (d1 = base64Data[dataIndex++]) )|| !isData( (d2 = base64Data[dataIndex++]) )|| !isData( (d3 = base64Data[dataIndex++]) )|| !isData( (d4 = base64Data[dataIndex++]) )) return null;//if found "no data" just return null b1 = base64Alphabet[d1]; b2 = base64Alphabet[d2]; b3 = base64Alphabet[d3]; b4 = base64Alphabet[d4]; decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); } if (!isData( (d1 = base64Data[dataIndex++]) ) || !isData( (d2 = base64Data[dataIndex++]) )) { return null;//if found "no data" just return null } b1 = base64Alphabet[d1]; b2 = base64Alphabet[d2]; d3 = base64Data[dataIndex++]; d4 = base64Data[dataIndex++]; if (!isData( (d3 ) ) || !isData( (d4 ) )) {//Check if they are PAD characters if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] if ((b2 & 0xf) != 0)//last 4 bits should be zero return null; byte[] tmp = new byte[ i*3 + 1 ]; System.arraycopy( decodedData, 0, tmp, 0, i*3 ); tmp[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ; return tmp; } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] b3 = base64Alphabet[ d3 ]; if ((b3 & 0x3 ) != 0)//last 2 bits should be zero return null; byte[] tmp = new byte[ i*3 + 2 ]; System.arraycopy( decodedData, 0, tmp, 0, i*3 ); tmp[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ); tmp[encodedIndex] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); return tmp; } else { return null;//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data } } else { //No PAD e.g 3cQl b3 = base64Alphabet[ d3 ]; b4 = base64Alphabet[ d4 ]; decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); } return decodedData; } /** * remove WhiteSpace from MIME containing encoded Base64 data. * * @param data the byte array of base64 data (with WS) * @return the new length */ protected static int removeWhiteSpace(char[] data) { if (data == null) return 0; // count characters that's not whitespace int newSize = 0; int len = data.length; for (int i = 0; i < len; i++) { if (!isWhiteSpace(data[i])) data[newSize++] = data[i]; } return newSize; } }
fcb363a0d020eabd198a1ec3599fff179021e794
5ca3901b424539c2cf0d3dda52d8d7ba2ed91773
/src_procyon/y/a/E_1.java
4726c7c1f9bf3ed3de9aa0a70e3301c13af9caf0
[]
no_license
fjh658/bindiff
c98c9c24b0d904be852182ecbf4f81926ce67fb4
2a31859b4638404cdc915d7ed6be19937d762743
refs/heads/master
2021-01-20T06:43:12.134977
2016-06-29T17:09:03
2016-06-29T17:09:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
932
java
package y.a; import y.c.*; class E { private final q a; private double b; private double c; private int d; private final f e; E(final q a) { this.a = a; this.b = 0.0; this.c = 0.0; this.d = Integer.MIN_VALUE; this.e = new f(); } q a() { return this.a; } static double a(final E e, final double c) { return e.c = c; } static int a(final E e, final int d) { return e.d = d; } static int a(final E e) { return e.d; } static double b(final E e, final double n) { return e.c += n; } static double b(final E e) { return e.c; } static f c(final E e) { return e.e; } static double d(final E e) { return e.b; } static double c(final E e, final double n) { return e.b += n; } }
f758a0465fd6c4058e9147843156012d9fcc2fcb
12b14b30fcaf3da3f6e9dc3cb3e717346a35870a
/examples/commons-math3/mutations/mutants-AbstractIntegerDistribution/6/org/apache/commons/math3/distribution/AbstractIntegerDistribution.java
6a67fd2252af5513d8fbfd2528c2e47707f25346
[ "BSD-3-Clause", "Minpack", "Apache-2.0" ]
permissive
SmartTests/smartTest
b1de326998857e715dcd5075ee322482e4b34fb6
b30e8ec7d571e83e9f38cd003476a6842c06ef39
refs/heads/main
2023-01-03T01:27:05.262904
2020-10-27T20:24:48
2020-10-27T20:24:48
305,502,060
0
0
null
null
null
null
UTF-8
Java
false
false
8,460
java
/* * 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.commons.math3.distribution; import java.io.Serializable; import org.apache.commons.math3.exception.MathInternalError; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.random.RandomGenerator; import org.apache.commons.math3.random.RandomDataImpl; import org.apache.commons.math3.util.FastMath; /** * Base class for integer-valued discrete distributions. Default * implementations are provided for some of the methods that do not vary * from distribution to distribution. * * @version $Id$ */ public abstract class AbstractIntegerDistribution implements IntegerDistribution, Serializable { /** Serializable version identifier */ private static final long serialVersionUID = -1146319659338487221L; /** * RandomData instance used to generate samples from the distribution. * @deprecated As of 3.1, to be removed in 4.0. Please use the * {@link #random} instance variable instead. */ @Deprecated protected final RandomDataImpl randomData = new RandomDataImpl(); /** * RNG instance used to generate samples from the distribution. * @since 3.1 */ protected final RandomGenerator random; /** * @deprecated As of 3.1, to be removed in 4.0. Please use * {@link #AbstractIntegerDistribution(RandomGenerator)} instead. */ @Deprecated protected AbstractIntegerDistribution() { // Legacy users are only allowed to access the deprecated "randomData". // New users are forbidden to use this constructor. random = null; } /** * @param rng Random number generator. * @since 3.1 */ protected AbstractIntegerDistribution(RandomGenerator rng) { random = rng; } /** * {@inheritDoc} * * The default implementation uses the identity * <p>{@code P(x0 < X <= x1) = P(X <= x1) - P(X <= x0)}</p> */ public double cumulativeProbability(int x0, int x1) throws NumberIsTooLargeException { if (x1 < x0) { throw new NumberIsTooLargeException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT, x0, x1, false); } return cumulativeProbability(x1) - cumulativeProbability(x0); } /** * {@inheritDoc} * * The default implementation returns * <ul> * <li>{@link #getSupportLowerBound()} for {@code p = 0},</li> * <li>{@link #getSupportUpperBound()} for {@code p = 1}, and</li> * <li>{@link #solveInverseCumulativeProbability(double, int, int)} for * {@code 0 < p < 1}.</li> * </ul> */ public int inverseCumulativeProbability(final double p) throws OutOfRangeException { if (p < 0.0 || p > 1.0) { throw new OutOfRangeException(p, 0, 1); } int lower = getSupportLowerBound(); if (p == 0.0) { return lower; } if (lower == Integer.MIN_VALUE) { if (checkedCumulativeProbability(lower) >= p) { return lower; } } else { lower -= 1; // this ensures cumulativeProbability(lower) < p, which // is important for the solving step } int upper = getSupportUpperBound(); if (p == 1.0) { return upper; } // use the one-sided Chebyshev inequality to narrow the bracket // cf. AbstractRealDistribution.inverseCumulativeProbability(double) final double mu = getNumericalMean(); final double sigma = FastMath.sqrt(getNumericalVariance()); final boolean chebyshevApplies = !(Double.isInfinite(mu) || Double.isNaN(mu) || Double.isInfinite(sigma) || Double.isNaN(sigma) || sigma == 0.0); if (chebyshevApplies) { double k = FastMath.sqrt((1.0 - p) / p); double tmp = mu - k * sigma; if (tmp > lower) { lower = ((int) Math.ceil(tmp)) - 1; } k = 1.0 / k; tmp = mu + k * sigma; if (tmp < upper) { upper = ((int) Math.ceil(tmp)) - 1; } } return solveInverseCumulativeProbability(p, lower, upper); } /** * This is a utility function used by {@link * #inverseCumulativeProbability(double)}. It assumes {@code 0 < p < 1} and * that the inverse cumulative probability lies in the bracket {@code * (lower, upper]}. The implementation does simple bisection to find the * smallest {@code p}-quantile <code>inf{x in Z | P(X<=x) >= p}</code>. * * @param p the cumulative probability * @param lower a value satisfying {@code cumulativeProbability(lower) < p} * @param upper a value satisfying {@code p <= cumulativeProbability(upper)} * @return the smallest {@code p}-quantile of this distribution */ protected int solveInverseCumulativeProbability(final double p, int lower, int upper) { while (lower + 1 < upper) { int xm = (lower + upper) / 2; if (xm < lower || xm > upper) { /* * Overflow. * There will never be an overflow in both calculation methods * for xm at the same time */ xm = lower + (upper - lower) / 2; } double pm = checkedCumulativeProbability(xm); if (pm >= p) { upper = xm; } else { lower = xm; } } return upper; } /** {@inheritDoc} */ public void reseedRandomGenerator(long seed) { random.setSeed(seed); randomData.reSeed(seed); } /** * {@inheritDoc} * * The default implementation uses the * <a href="http://en.wikipedia.org/wiki/Inverse_transform_sampling"> * inversion method</a>. */ public int sample() { return inverseCumulativeProbability(random.nextDouble()); } /** * {@inheritDoc} * * The default implementation generates the sample by calling * {@link #sample()} in a loop. */ public int[] sample(int sampleSize) { if (sampleSize <= 0) { throw new NotStrictlyPositiveException( LocalizedFormats.NUMBER_OF_SAMPLES, sampleSize); } int[] out = new int[sampleSize]; for (int i = 0; i < sampleSize; i++) { out[i] = sample(); } return out; } /** * Computes the cumulative probability function and checks for {@code NaN} * values returned. Throws {@code MathInternalError} if the value is * {@code NaN}. Rethrows any exception encountered evaluating the cumulative * probability function. Throws {@code MathInternalError} if the cumulative * probability function returns {@code NaN}. * * @param argument input value * @return the cumulative probability * @throws MathInternalError if the cumulative probability is {@code NaN} */ private double checkedCumulativeProbability(int argument) throws MathInternalError { double result = Double.NaN; result = cumulativeProbability(argument); if (Double.isNaN(result)) { throw new MathInternalError(LocalizedFormats .DISCRETE_CUMULATIVE_PROBABILITY_RETURNED_NAN, argument); } return result; } }
aba90caa42cef0c61528f899d8565d269ba6ea7d
4509c031ee4c5d1e8ae9906625082bd9c365b47a
/src/first/RevPyramid.java
df089c92f8f0066dd2ebf655e6bef902edb6889d
[]
no_license
chavanyogesh1397/Java-Practice
809daec5d909a4bba76b2cb5a01ce742dbde476d
220220e41d4d599d27eaf0f4bb366a3ded867c67
refs/heads/master
2023-04-27T05:56:31.628343
2021-05-06T06:37:09
2021-05-06T06:37:09
364,814,332
0
0
null
null
null
null
UTF-8
Java
false
false
320
java
package first; public class RevPyramid { public static void main(String[] args) { //***** //**** //*** //** //* for(int i=1;i<=5;i++)//5 { for(int j=5;j>=i;j--)//1 { System.out.print(" *"); //* * * * * // } System.out.println(); } } }
[ "yogesh@DESKTOP-5HBRUB1" ]
yogesh@DESKTOP-5HBRUB1
53b9b6f7eb02381636a3a1f83d0a1b0a94c71cc3
cd3ccc969d6e31dce1a0cdc21de71899ab670a46
/agp-7.1.0-alpha01/tools/base/layoutlib-api/src/test/java/com/android/resources/ResourceNamespaceTest.java
aadf947d89b8702f538e3a7e994a6366ef1ac6e9
[ "Apache-2.0" ]
permissive
jomof/CppBuildCacheWorkInProgress
75e76e1bd1d8451e3ee31631e74f22e5bb15dd3c
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
refs/heads/main
2023-05-28T19:03:16.798422
2021-06-10T20:59:25
2021-06-10T20:59:25
374,736,765
0
1
Apache-2.0
2021-06-07T21:06:53
2021-06-07T16:44:55
Java
UTF-8
Java
false
false
4,772
java
// Copyright (C) 2017 The Android Open Source Project // // 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.android.resources; import static com.android.ide.common.rendering.api.ResourceNamespace.ANDROID; import static com.android.ide.common.rendering.api.ResourceNamespace.RES_AUTO; import static com.android.ide.common.rendering.api.ResourceNamespace.Resolver.EMPTY_RESOLVER; import static com.android.ide.common.rendering.api.ResourceNamespace.TOOLS; import static com.android.ide.common.rendering.api.ResourceNamespace.fromNamespacePrefix; import static com.android.ide.common.rendering.api.ResourceNamespace.fromNamespaceUri; import static com.android.ide.common.rendering.api.ResourceNamespace.fromPackageName; import static org.junit.Assert.*; import com.android.ide.common.rendering.api.AndroidConstants; import com.android.ide.common.rendering.api.ResourceNamespace; import com.google.common.collect.ImmutableMap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.junit.Test; public class ResourceNamespaceTest { @Test public void packageName() { assertEquals("android", ANDROID.getPackageName()); assertNull(RES_AUTO.getPackageName()); } @Test @SuppressWarnings("ConstantConditions") // suppress null warnings, that's what we're testing. public void fromPrefix() { assertEquals( "com.example", fromNamespacePrefix("com.example", RES_AUTO, EMPTY_RESOLVER).getPackageName()); assertEquals( AndroidConstants.ANDROID_NS_NAME, fromNamespacePrefix("android", RES_AUTO, EMPTY_RESOLVER).getPackageName()); assertNull(fromNamespacePrefix(null, RES_AUTO, EMPTY_RESOLVER).getPackageName()); assertEquals( "android", fromNamespacePrefix(null, ANDROID, EMPTY_RESOLVER).getPackageName()); ImmutableMap<String, String> namespaces = ImmutableMap.of( "aaa", "http://schemas.android.com/apk/res/madeup", "ex", "http://schemas.android.com/apk/res/com.example"); assertEquals( "com.example", fromNamespacePrefix("ex", RES_AUTO, namespaces::get).getPackageName()); } @Test public void androidSingleton() throws Exception { assertSame(ANDROID, fromPackageName("android")); assertSame( ANDROID, fromNamespacePrefix("android", RES_AUTO, prefix -> AndroidConstants.ANDROID_URI)); assertSame(ANDROID, fromNamespaceUri(AndroidConstants.ANDROID_URI)); assertSame(ANDROID, serializeAndDeserialize(ANDROID)); } @Test public void testEquals() { ResourceNamespace aaa = fromPackageName("aaa"); ResourceNamespace bbb1 = fromPackageName("bbb"); ResourceNamespace bbb2 = fromPackageName("bbb"); assertEquals(aaa, aaa); assertEquals(bbb1, bbb2); assertNotEquals(aaa, bbb1); assertNotEquals(bbb1, aaa); assertNotEquals(ANDROID, aaa); assertNotEquals(TOOLS, aaa); assertNotEquals(RES_AUTO, aaa); assertNotEquals(ANDROID, bbb2); assertNotEquals(TOOLS, bbb2); assertNotEquals(RES_AUTO, bbb2); } @Test public void xmlNamespaceUri() { assertEquals(AndroidConstants.ANDROID_URI, ANDROID.getXmlNamespaceUri()); } private static ResourceNamespace serializeAndDeserialize(ResourceNamespace namespace) throws IOException, ClassNotFoundException { //noinspection resource: ByteArrayOutputStream doesn't leak resources. ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(bytes)) { objectOutputStream.writeObject(namespace); } ResourceNamespace deserialized; try (ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { deserialized = (ResourceNamespace) objectInputStream.readObject(); } return deserialized; } }
4ab0962b84f69aabf4164e0992bb1148b764f1be
2d4506dfaae690bda5634b0ac6a5b9b953da3fba
/src/tests/SimpleScriptsHome.java
d9dbb39e94973389c9105a7450ec5accc677a7a4
[ "Apache-2.0" ]
permissive
eglu2016/JavaAppiumMobAppNotMaven
b1af0a8f54b65f5b9c622d53258c14c52141f852
842a0bf3ec45f04e183d2103b49dce8fafaa0092
refs/heads/main
2022-12-25T10:36:18.202095
2020-10-09T09:06:15
2020-10-09T09:06:15
302,579,251
0
0
null
null
null
null
UTF-8
Java
false
false
1,277
java
package tests; import libs.CoreTestCase; import org.junit.Test; import ui.SearchPageObject; public class SimpleScriptsHome extends CoreTestCase { @Test public void testMethodCreation() { SearchPageObject SearchPageObject = new SearchPageObject(driver); SearchPageObject.initSearchInput(); SearchPageObject.assertSearchInputHasLabelText(); } @Test public void testCancelSearch() { SearchPageObject SearchPageObject = new SearchPageObject(driver); SearchPageObject.initSearchInput(); SearchPageObject.typeSearchLine("IATA"); SearchPageObject.waitForSearchResult("Redirected from IATA"); SearchPageObject.waitForSearchResult("Three-letter code designating many airports around the world"); SearchPageObject.waitForCancelButtonToAppear(); SearchPageObject.clickCancelSearch(); SearchPageObject.clickCancelSearch(); SearchPageObject.waitForCancelButtonToDisAppear(); } @Test public void testCheckWorldsInSearch() { SearchPageObject SearchPageObject = new SearchPageObject(driver); SearchPageObject.initSearchInput(); SearchPageObject.typeSearchLine("Java"); SearchPageObject.assertResultsContainsText("Java"); } }
8169d6918237378da6ad610717bf663dd2737798
3970cbf79779a6d4ff9df7e7c0d3bceb06731d12
/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkInterfaceTest.java
c36d52d8bd0f131874175de5a4947015017b8aa2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
UNIVERSAL-IT-SYSTEMS/google-cloud-java
f437a22ee066cdde793d35a210ac850afcb7d831
007c15368003e289dd7f52dafbfa7c5fdcd39d7e
refs/heads/master
2020-05-29T08:46:30.359441
2016-09-28T10:18:50
2016-09-28T10:18:50
69,464,462
0
1
null
2016-09-28T13:10:48
2016-09-28T13:10:47
null
UTF-8
Java
false
false
7,435
java
/* * Copyright 2016 Google Inc. All Rights Reserved. * * 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.google.cloud.compute; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import com.google.common.collect.ImmutableList; import org.junit.Assert; import org.junit.Test; import java.util.List; public class NetworkInterfaceTest { private static final String NAME = "networkInterface"; private static final NetworkId NETWORK = NetworkId.of("project", "network"); private static final String NETWORK_IP = "192.168.1.1"; private static final SubnetworkId SUBNETWORK = SubnetworkId.of("project", "region", "subnetwork"); private static final NetworkInterface.AccessConfig ACCESS_CONFIG = NetworkInterface.AccessConfig.builder() .name("accessConfig") .natIp("192.168.1.1") .type(NetworkInterface.AccessConfig.Type.ONE_TO_ONE_NAT) .build(); private static final List<NetworkInterface.AccessConfig> ACCESS_CONFIGURATIONS = ImmutableList.of(ACCESS_CONFIG); private static final NetworkInterface NETWORK_INTERFACE = NetworkInterface.builder(NETWORK) .name(NAME) .networkIp(NETWORK_IP) .subnetwork(SUBNETWORK) .accessConfigurations(ACCESS_CONFIGURATIONS) .build(); @Test public void testAccessConfigToBuilder() { NetworkInterface.AccessConfig accessConfig = ACCESS_CONFIG.toBuilder().name("newName").build(); assertEquals("newName", accessConfig.name()); compareAccessConfig(ACCESS_CONFIG, accessConfig.toBuilder().name("accessConfig").build()); } @Test public void testAccessConfigToBuilderIncomplete() { NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.of(); compareAccessConfig(accessConfig, accessConfig.toBuilder().build()); } @Test public void testToBuilder() { compareNetworkInterface(NETWORK_INTERFACE, NETWORK_INTERFACE.toBuilder().build()); NetworkInterface networkInterface = NETWORK_INTERFACE.toBuilder().name("newInterface").build(); assertEquals("newInterface", networkInterface.name()); networkInterface = networkInterface.toBuilder().name(NAME).build(); compareNetworkInterface(NETWORK_INTERFACE, networkInterface); } @Test public void testToBuilderIncomplete() { NetworkInterface networkInterface = NetworkInterface.of(NETWORK); assertEquals(networkInterface, networkInterface.toBuilder().build()); networkInterface = NetworkInterface.of(NETWORK.network()); assertEquals(networkInterface, networkInterface.toBuilder().build()); } @Test public void testAccessConfigBuilder() { assertEquals("accessConfig", ACCESS_CONFIG.name()); assertEquals("192.168.1.1", ACCESS_CONFIG.natIp()); Assert.assertEquals(NetworkInterface.AccessConfig.Type.ONE_TO_ONE_NAT, ACCESS_CONFIG.type()); } @Test public void testBuilder() { assertEquals(NAME, NETWORK_INTERFACE.name()); assertEquals(NETWORK, NETWORK_INTERFACE.network()); assertEquals(NETWORK_IP, NETWORK_INTERFACE.networkIp()); assertEquals(SUBNETWORK, NETWORK_INTERFACE.subnetwork()); assertEquals(ACCESS_CONFIGURATIONS, NETWORK_INTERFACE.accessConfigurations()); NetworkInterface networkInterface = NetworkInterface.builder("network") .name(NAME) .networkIp(NETWORK_IP) .subnetwork(SUBNETWORK) .accessConfigurations(ACCESS_CONFIG) .build(); assertEquals(NAME, networkInterface.name()); assertEquals(NetworkId.of("network"), networkInterface.network()); assertEquals(NETWORK_IP, networkInterface.networkIp()); assertEquals(SUBNETWORK, networkInterface.subnetwork()); assertEquals(ACCESS_CONFIGURATIONS, networkInterface.accessConfigurations()); } @Test public void testAccessConfigOf() { NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.of("192.168.1.1"); assertNull(accessConfig.name()); assertEquals("192.168.1.1", accessConfig.natIp()); assertNull(accessConfig.type()); accessConfig = NetworkInterface.AccessConfig.of(); assertNull(accessConfig.name()); assertNull(accessConfig.natIp()); assertNull(accessConfig.type()); } @Test public void testOf() { NetworkInterface networkInterface = NetworkInterface.of(NETWORK); assertNull(networkInterface.name()); assertEquals(NETWORK, networkInterface.network()); assertNull(networkInterface.networkIp()); assertNull(networkInterface.subnetwork()); networkInterface = NetworkInterface.of(NETWORK.network()); assertNull(networkInterface.name()); assertNull(networkInterface.network().project()); assertEquals(NETWORK.network(), networkInterface.network().network()); assertNull(networkInterface.networkIp()); assertNull(networkInterface.subnetwork()); } @Test public void testAccessConfigToAndFromPb() { NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.fromPb(ACCESS_CONFIG.toPb()); compareAccessConfig(ACCESS_CONFIG, accessConfig); accessConfig = NetworkInterface.AccessConfig.of(); compareAccessConfig(accessConfig, NetworkInterface.AccessConfig.fromPb(accessConfig.toPb())); } @Test public void testToAndFromPb() { NetworkInterface networkInterface = NetworkInterface.fromPb(NETWORK_INTERFACE.toPb()); compareNetworkInterface(NETWORK_INTERFACE, networkInterface); networkInterface = NetworkInterface.of(NETWORK); compareNetworkInterface(networkInterface, NetworkInterface.fromPb(networkInterface.toPb())); } @Test public void testSetProjectId() { NetworkInterface networkInterface = NetworkInterface.of(NETWORK); compareNetworkInterface(networkInterface, NetworkInterface.of(NetworkId.of("network")).setProjectId("project")); networkInterface = NETWORK_INTERFACE.toBuilder() .network(NetworkId.of("network")) .subnetwork(SubnetworkId.of("region", "subnetwork")) .build(); compareNetworkInterface(NETWORK_INTERFACE, networkInterface.setProjectId("project")); } public void compareAccessConfig(NetworkInterface.AccessConfig expected, NetworkInterface.AccessConfig value) { assertEquals(expected, value); assertEquals(expected.name(), value.name()); assertEquals(expected.natIp(), value.natIp()); assertEquals(expected.type(), value.type()); assertEquals(expected.hashCode(), value.hashCode()); } public void compareNetworkInterface(NetworkInterface expected, NetworkInterface value) { assertEquals(expected, value); assertEquals(expected.name(), value.name()); assertEquals(expected.network(), value.network()); assertEquals(expected.networkIp(), value.networkIp()); assertEquals(expected.subnetwork(), value.subnetwork()); assertEquals(expected.accessConfigurations(), value.accessConfigurations()); assertEquals(expected.hashCode(), value.hashCode()); } }
421fba5b944fc3c72c036a8a04bd73b0d24259f6
b5fd6e762ba76e1eaba1468adf2e1320560f0fdb
/src/main/java/com/challenge/weather/search/view/CityWeather.java
3247bd717729bb618f32c41864fd0001c4051f45
[]
no_license
erickgr2/challengeCode
859141e3c718a562c7bba9664ebf0eafaaedf6e6
c554c4befe909d829ac55d004f56e9a68965b74d
refs/heads/master
2020-05-30T09:25:33.087591
2019-05-31T19:02:34
2019-05-31T19:02:34
188,714,733
0
1
null
2019-05-30T19:55:47
2019-05-26T17:53:01
Java
UTF-8
Java
false
false
414
java
package com.challenge.weather.search.view; import lombok.Getter; import lombok.Setter; import java.time.LocalDate; /** * POJO class used to show information in the static content. * * @author Erick Garcia * */ @Getter @Setter public class CityWeather { LocalDate date; String city; String description; String temperatureC; String temperatureF; String sunriseTime; String sunsetTime; }
f0dcd147c7c904658ca5a2a81f3bb22222a3a760
de5599ae57a5a16831ab11693b65f58fc5edfcc2
/CCTechPhotoApp/src/UtilityJson/UtilityjsonInfo.java
98373c48b63d625c84448df55e4e173f11550fde
[]
no_license
Renu-creator/YouFrame
3054b88f19e6f805e12dca8abefc7e44c0509aa2
472929e01a330981fafd398fa0b17040eecb2cd3
refs/heads/master
2022-12-18T13:56:34.128497
2020-09-14T07:41:36
2020-09-14T07:41:36
295,336,727
0
0
null
null
null
null
UTF-8
Java
false
false
828
java
package UtilityJson; import com.fasterxml.jackson.databind.ObjectMapper; public class UtilityjsonInfo { private static final ObjectMapper mapper = new ObjectMapper(); public static Object getObjectFromJSON(String jsonString, Class<?> className) { Object readValue = null; try { readValue = mapper.readValue(jsonString, className); } catch (Exception e) { e.printStackTrace(); } System.out.println(jsonString); System.out.println(readValue); return readValue; } public static String getJSONFromObject(Object object) { String jsonData = null; try { jsonData = mapper.writeValueAsString(object); } catch (Exception e) { System.out.println("Error in getJSONFromObject "+ e); } return jsonData; } }
be43e5d899dad45c140c0bde1788915ca5ede7c3
54cc35f6becb117464ec479ea3a1f39ef44f4e58
/src/main/java/com/rentalsystem/swp/security/CustomUserDetailsService.java
28644ad61e1c3b08ee1b683c1748eda2db58ed5a
[]
no_license
lackadacka/SWPProject
ef4933d46ca9b40a5ec215b10986397ce8530881
2e7efc3b9d85148c067bd7b84e84df8ed18cabde
refs/heads/master
2022-11-30T23:44:10.321626
2019-04-27T17:21:35
2019-04-27T17:21:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,484
java
package com.rentalsystem.swp.security; import com.rentalsystem.swp.Repositories.UserRepository; import com.rentalsystem.swp.models.UserProfile; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class CustomUserDetailsService implements UserDetailsService { @Autowired UserRepository userRepository; @Override @Transactional public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // Let people login with either username or email UserProfile user = userRepository.findByEmail(username) .orElseThrow(() -> new UsernameNotFoundException("User not found with username or email : " + username) ); return UserPrincipal.create(user); } // This method is used by JWTAuthenticationFilter @Transactional public UserDetails loadUserById(Long id) { UserProfile user = userRepository.findById(id).orElseThrow( () -> new UsernameNotFoundException("User not found with id : " + id) ); return UserPrincipal.create(user); } }
184fc7bd8269814f4f7cb39d6602b77f35f2dbef
87e17f3f22c9e36d8d8c04d0d77f3ae2aefa4dfc
/app/src/main/java/net/shenru/qqgroup/task/TroopWorker.java
03514edda5c849223c390ae4842d5863103319d2
[]
no_license
xtdhwl/qqgroup
3d0c658d31c2659ab8c5773fbe816ed77d0fd2f4
6fb056c702d0573d7d513436244965107c0e504e
refs/heads/master
2021-05-10T17:21:31.901727
2018-02-03T17:20:22
2018-02-03T17:20:22
118,607,650
3
0
null
null
null
null
UTF-8
Java
false
false
3,291
java
package net.shenru.qqgroup.task; import android.util.Log; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityWindowInfo; import com.orhanobut.logger.Logger; import com.tencent.mobileqq.activity.SplashActivity; import com.tencent.mobileqq.activity.contact.troop.TroopActivity; import net.shenru.qqgroup.util.NodeInfoUtil; import java.util.List; import java.util.concurrent.TimeUnit; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import static android.content.ContentValues.TAG; import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_CLICKED; /** * Created by xtdhwl on 29/01/2018. */ public class TroopWorker extends BaseWorker { private AccessibilityEvent mEvent; private boolean isRuning = false; @Override public void exec() { Logger.i("exec()"); } @Override public void onEvent(AccessibilityEvent event) { mEvent = event; if (isRuning) { return; } isRuning = true; CharSequence className = event.getClassName(); int eventType = event.getEventType(); if (eventType == AccessibilityEvent.TYPE_WINDOWS_CHANGED || eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { if (TroopActivity.class.getName().equals(className)) { getCallback().onResult(true, null); setFinish(true); return; } else if (SplashActivity.class.getName().equals(className)) { //在主页 } else { //TODO main task // Logger.e("去首页"); //TODO 去主页 return; } } if (event.getEventType() == TYPE_VIEW_CLICKED) { List<CharSequence> texts = event.getText(); if (!texts.isEmpty()) { CharSequence text = texts.get(0); if ("群组".equals(text)) { Logger.i("ignore TYPE_VIEW_CLICKED"); isRuning = false; return; } } } boolean b = goTroop(event); isRuning = false; } private boolean goTroop(AccessibilityEvent event) { AccessibilityNodeInfo root; if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { root = event.getSource(); } else { root = NodeInfoUtil.getRootParent(event.getSource()); } if (root == null) { Logger.w("AccessibilityNodeInfo root null"); return false; } // List<AccessibilityNodeInfo> conNodeInfoList = root.findAccessibilityNodeInfosByText("联系人"); List<AccessibilityNodeInfo> conNodeInfoList = root.findAccessibilityNodeInfosByText("群组"); if (!conNodeInfoList.isEmpty()) { AccessibilityNodeInfo cNodeInfo = conNodeInfoList.get(0); cNodeInfo.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK); return true; } return false; } }
75c3f7c63a1b0bf72fc6dba6220fd5abc970d041
b998b375e53c0d8141db7f8e07cb01b494ed3d0a
/Decompiled-APK/com/samsung/android/visasdk/facade/data/ProvisionAckRequest.java
4bb346a37eed065cc3d15adb1a11005011251dbf
[]
no_license
atthisaccount/SPay-inner-workings
c3b6256c8ed10c2492d19eca8e63f656cd855be2
6dd83a6ea0916c272423ea0dc1fa3757baa632e7
refs/heads/master
2022-03-22T04:12:05.100198
2019-10-06T13:25:49
2019-10-06T13:25:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
671
java
package com.samsung.android.visasdk.facade.data; public class ProvisionAckRequest { private String api; private String failureReason; private String provisioningStatus; public String getApi() { return this.api; } public void setApi(String str) { this.api = str; } public String getFailureReason() { return this.failureReason; } public void setFailureReason(String str) { this.failureReason = str; } public String getProvisioningStatus() { return this.provisioningStatus; } public void setProvisioningStatus(String str) { this.provisioningStatus = str; } }
c8d113487742e4bfcde178d4d1497fb4094a9dc1
b7d17be4b7ed48b22d86d5db61403eb7015448b5
/kodilla-good-patterns/src/main/java/com/kodilla/good/patterns/challenges/MovieStore.java
8ab49b9157add15426ed7a21984f7655a8d7dbf3
[]
no_license
komnen83/Jakub-Bauman-Kodilla-Java
1fe1c91a8d1659712a7747b1e8b86a56b8b3b306
3c1874b4ad2fedc5800fb15c53050c049f19beee
refs/heads/master
2020-03-07T15:34:58.030785
2018-08-23T13:42:59
2018-08-23T13:42:59
127,558,833
0
0
null
null
null
null
UTF-8
Java
false
false
1,285
java
import java.util.*; import java.util.stream.Collectors; class MovieStore { public Map<String, List<String>> getMovies() { List<String> ironManTranslations = new ArrayList<>(); ironManTranslations.add("Żelazny Człowiek"); ironManTranslations.add("Iron Man"); List<String> avengersTranslations = new ArrayList<>(); avengersTranslations.add("Mściciele"); avengersTranslations.add("Avengers"); List<String> flashTranslations = new ArrayList<>(); flashTranslations.add("Błyskawica"); flashTranslations.add("Flash"); Map<String, List<String>> booksTitlesWithTranslations = new HashMap<>(); booksTitlesWithTranslations.put("IM", ironManTranslations); booksTitlesWithTranslations.put("AV", avengersTranslations); booksTitlesWithTranslations.put("FL", flashTranslations); return booksTitlesWithTranslations; } } class MovieStoreMain { public static void main(String[] args) { MovieStore movieStore = new MovieStore(); String movies = movieStore.getMovies().entrySet().stream() .flatMap(s -> s.getValue().stream()) .collect(Collectors.joining(" ! ",""," ! ")); System.out.println(movies); } }
d14aa183bcb1e177098f6a20a3ce438668627f51
935929a24e854704aa0a782aeb5e27942678dbb3
/src/main/java/com/example/demo/student/StudentService.java
2a2fcbcb632fc95d9070c8fabad30b42c5b1854e
[]
no_license
vgshettigar/demo
63e41cc20189dc87cb1c7260d7a07130110b54ef
b2b45a424d9718c4d955aa0b8343775fc20e8c66
refs/heads/master
2023-05-28T16:12:53.259066
2021-01-24T18:01:10
2021-01-24T18:01:10
330,751,411
0
0
null
null
null
null
UTF-8
Java
false
false
537
java
package com.example.demo.student; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; import java.util.Collection; import java.util.List; @Service public class StudentService { public Student getStudents() { return new Student( 1L, "Mariam", "[email protected]", LocalDate.of(2000, Month.JANUARY, 5), 21); } }
09705e9cf1317cbd614e9756783f1d7725d1c79f
e9886898f83a441cfb6d6e7bbbb2813847c4574c
/MDS/src/com/report/agentReportDao.java
3870d4928f79ff69a2800746c2e6c96e546d3886
[]
no_license
msmartpay/proxima
3f792d1d49dd9ae5526c0567e7439c2f96220ba1
a4d2969c5eac96b6b2bb0cab439723220183bb6c
refs/heads/main
2023-04-19T18:40:22.362280
2021-05-04T12:23:44
2021-05-04T12:27:40
302,057,747
0
1
null
null
null
null
UTF-8
Java
false
false
9,380
java
package com.report; import java.io.File; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import com.db.DBConnection; public class agentReportDao { public final String downloadLRTReport(Connection con,String mdId,String filePath){ ResultSet rs=null; String Status="DownloadNotAllowed"; int i=0; int j=1; try { con=DBConnection.getConnection(); String sql="select a.agent_initial+convert(varchar(10),l.user_id) as AgentID," + "d.distributor_initial+convert(varchar(10),a.distributor_id) as DSID," + "m.md_initial+convert(varchar(10),d.md_id) as MDID,l.Agent_tran_id ,l.mobile_number,l.mobile_operator," + "l.date_of_recharge,convert(varchar(10),l.date_time,108) as time,l.amount,l.service,l.mob_commission," + "l.status from live_recharge l,agent_details a ,distributor_details d,md_details m " + "where a.agent_id=l.user_id and a.distributor_id=d.distributor_id and d.md_id=m.md_id and " + "l.user_id in (select agent_id from agent_details where distributor_id in " + "(select distributor_id from distributor_details where md_id='"+mdId+"')) and " + "date_of_recharge=convert(varchar(10),getdate()-1,120) order by date_of_recharge desc"; System.out.println(sql); Statement stmt = con.createStatement(); rs=stmt.executeQuery(sql); // rs=cstmt.executeQuery(); WritableWorkbook workbook; workbook=Workbook.createWorkbook(new File(filePath)); WritableSheet sheet=workbook.createSheet("Excel Sheet", 0); sheet.addCell(new Label(0,i,"S.No.")); sheet.addCell(new Label(1,i,"LA Id")); sheet.addCell(new Label(2,i,"AFC Id")); sheet.addCell(new Label(3,i,"MFC ID")); sheet.addCell(new Label(4,i,"User Type")); sheet.addCell(new Label(5,i,"LA Txn ID")); sheet.addCell(new Label(6,i,"Connection Number")); sheet.addCell(new Label(7,i,"Connection Operator")); sheet.addCell(new Label(8,i,"Date of Recharge")); sheet.addCell(new Label(9,i,"Time of Recharge")); sheet.addCell(new Label(10,i,"Transaction Amount")); sheet.addCell(new Label(11,i,"Service")); sheet.addCell(new Label(12,i,"Commission")); sheet.addCell(new Label(13,i,"Status")); int index = 1; /* writer.append("SNo"); writer.append(';'); writer.append("Agent ID"); writer.append(';'); writer.append("Distributor ID"); writer.append(';'); writer.append("Master distributor ID"); writer.append(';'); writer.append("Connection Number"); writer.append(';'); writer.append("Connection Operator"); writer.append(';'); writer.append("Date of Recharge"); writer.append(';'); writer.append("Time of Recharge"); writer.append(';'); writer.append("Gross Amount"); writer.append(';'); writer.append("Commission"); writer.append(';'); writer.append("Status"); writer.append('\n'); */ while(rs.next()){ String indexvalue=""+index; sheet.addCell(new Label(0,j,indexvalue)); sheet.addCell(new Label(1,j,rs.getString(1))); sheet.addCell(new Label(2,j,rs.getString(2))); sheet.addCell(new Label(3,j,rs.getString(3))); sheet.addCell(new Label(4,j,"Lead Associate")); sheet.addCell(new Label(5,j,","+rs.getString(4))); sheet.addCell(new Label(6,j,","+rs.getString(5))); sheet.addCell(new Label(7,j,rs.getString(6))); sheet.addCell(new Label(8,j,rs.getString(7))); sheet.addCell(new Label(9,j,rs.getString(8))); sheet.addCell(new Label(10,j,rs.getString(9))); sheet.addCell(new Label(11,j,rs.getString(10))); sheet.addCell(new Label(12,j,rs.getString(11))); sheet.addCell(new Label(13,j,rs.getString(12))); index++; j++; } System.out.println("Data is saved in excel file at path and j is "+j); if(j>1){ Status="DownloadAllowed"; } workbook.write(); workbook.close(); System.out.println("Data is saved in excel file at path and status is "+Status); }catch(Exception e) { System.out.println("Exception in getAccountStatement"+e.toString()); } finally { try { if(rs!=null) rs.close(); if(con!=null) con.close(); } catch(Exception e) { System.out.println("Exception in getAccountStatement while closing connection"+e.toString()); } } return Status; } public final String downloadATTReport(Connection con,String mdId,String filePath){ ResultSet rs=null; String Status="DownloadNotAllowed"; int i=0; int j=1; try { con=DBConnection.getConnection(); String sql="select b.aid as AGID,a.Transaction_Id,a.UserType,a.Date_of_Transaction,a.Time_of_Transaction,a.Service,a.Agent_balAmt_b_Ded, a.ReqAmount,a.Commession,a.Service_charge1,a.Service_charge2,a.Other_charge,a.extra_commission,a.DeductedAmt,a.Action_on_bal_amt,a.Agent_balAmt_A_Ded,a.Tran_status,a.Updated_date,a.updated_time,a.Remark from dbo.agent_transaction_details a,agent_details b where a.agent_id in (select agent_id from agent_details where distributor_id in(select distributor_id from distributor_details where md_id ='"+mdId+"'))and a.agent_id=b.agent_id and a.Date_of_Transaction between convert(varchar(10),getdate()-7,120) and convert(varchar(10),getdate(),120) order by a.Date_of_Transaction desc"; System.out.println(sql); Statement stmt = con.createStatement(); rs=stmt.executeQuery(sql); // rs=cstmt.executeQuery(); WritableWorkbook workbook; workbook=Workbook.createWorkbook(new File(filePath)); WritableSheet sheet=workbook.createSheet("Excel Sheet", 0); sheet.addCell(new Label(0,i,"S.No.")); sheet.addCell(new Label(1,i,"LA Id")); sheet.addCell(new Label(2,i,"Txn Id")); sheet.addCell(new Label(3,i,"User Type")); sheet.addCell(new Label(4,i,"Date of Recharge")); sheet.addCell(new Label(5,i,"Time of Recharge")); sheet.addCell(new Label(6,i,"Service")); sheet.addCell(new Label(7,i,"Agent Bal. before Deduction")); sheet.addCell(new Label(8,i,"Requested Amount")); sheet.addCell(new Label(9,i,"Commission")); // sheet.addCell(new Label(10,i,"DeductedAmt")); sheet.addCell(new Label(10,i,"Service Charge1")); sheet.addCell(new Label(11,i,"Service Charge2")); sheet.addCell(new Label(12,i,"Other Charges")); sheet.addCell(new Label(13,i,"Extra commission")); sheet.addCell(new Label(14,i,"Deducted Amount")); sheet.addCell(new Label(15,i,"Action_on_bal_amt")); sheet.addCell(new Label(16,i,"Agent Bal. After Deduction")); sheet.addCell(new Label(17,i,"Tran_status")); sheet.addCell(new Label(18,i,"Updated_date")); sheet.addCell(new Label(19,i,"updated_time")); sheet.addCell(new Label(20,i,"Remark")); int index = 1; while(rs.next()){ String indexvalue=""+index; sheet.addCell(new Label(0,j,indexvalue)); sheet.addCell(new Label(1,j,rs.getString(1))); sheet.addCell(new Label(2,j,","+rs.getString(2))); sheet.addCell(new Label(3,j,rs.getString(3))); sheet.addCell(new Label(4,j,rs.getString(4))); sheet.addCell(new Label(5,j,","+rs.getString(5))); sheet.addCell(new Label(6,j,rs.getString(6))); sheet.addCell(new Label(7,j,rs.getString(7))); sheet.addCell(new Label(8,j,rs.getString(8))); sheet.addCell(new Label(9,j,rs.getString(9))); sheet.addCell(new Label(10,j,rs.getString(10))); sheet.addCell(new Label(11,j,rs.getString(11))); sheet.addCell(new Label(12,j,rs.getString(12))); sheet.addCell(new Label(13,j,rs.getString(13))); sheet.addCell(new Label(14,j,rs.getString(14))); sheet.addCell(new Label(15,j,rs.getString(15))); sheet.addCell(new Label(16,j,rs.getString(16))); sheet.addCell(new Label(17,j,rs.getString(17))); sheet.addCell(new Label(18,j,rs.getString(18))); sheet.addCell(new Label(19,j,rs.getString(19))); sheet.addCell(new Label(20,j,rs.getString(20))); index++; j++; } System.out.println("Data is saved in excel file at path and j is "+j); if(j>1){ Status="DownloadAllowed"; } workbook.write(); workbook.close(); System.out.println("Data is saved in excel file at path and status is "+Status); }catch(Exception e) { System.out.println("Exception in getAccountStatement"+e.toString()); } finally { try { if(rs!=null) rs.close(); if(con!=null) con.close(); } catch(Exception e) { System.out.println("Exception in getAccountStatement while closing connection"+e.toString()); } } return Status; } }
a15804d098c2f3be8ae16286eccc1d2cc33837aa
b2f70cc58291b750a60234180de772ff2df0c6ea
/app/src/main/java/cn/com/reformer/brake/vh/ScanVH.java
68a91ed3a6699c5b60b3e1f8294593f96e2306aa
[ "Apache-2.0" ]
permissive
yunmengjiuzhang/TestBrake
7601b42f70eeb1daaba17b10319016ea3bb45f62
1b501724a382f1ad7e4da17d50f13daf9339a8a2
refs/heads/master
2021-09-06T20:20:10.078326
2018-02-11T03:14:19
2018-02-11T03:14:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,594
java
package cn.com.reformer.brake.vh; import android.databinding.BindingAdapter; import android.databinding.DataBindingUtil; import android.databinding.ObservableArrayList; import android.databinding.ObservableField; import android.databinding.ViewDataBinding; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import cn.com.reformer.brake.BR; import cn.com.reformer.brake.BaseActivity; import cn.com.reformer.brake.R; import cn.com.reformer.brake.utils.BleUtils; import cn.com.reformer.ble.BleBean; import mutils.ThreadUtils; public class ScanVH extends BaseVH { public final ObservableField<Boolean> isRefresh = new ObservableField<>(true); public final ObservableArrayList<BleBean> itmesVHs = new ObservableArrayList<>(); public ScanVH(BaseActivity ctx) { super(ctx); } public void onRefreshClick(View view) { refresh(); } public void refresh() { itmesVHs.clear(); isRefresh.set(true); BleUtils.scan(); ThreadUtils.runOnUiThreadDelayed(new Runnable() { @Override public void run() { isRefresh.set(false); } }, 5000); } public void OnNewBleBean(final BleBean bean) { itmesVHs.add(bean); } @BindingAdapter({"app:scanRecyclerView", "app:arraylist"}) public static void scanAdapter(final RecyclerView recyclerView, final ScanVH scanVH, final ArrayList<BleBean> arrayList) { if (scanVH != null) { recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext())); recyclerView.setItemAnimator(new DefaultItemAnimator());// TODO: 2017/8/3 0003 recyclerView.setAdapter(new RecyclerView.Adapter() { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewDataBinding binding = null; RecyclerView.ViewHolder viewHolder = null; switch (viewType) { case 0: binding = DataBindingUtil.inflate(scanVH.mCtx.getLayoutInflater(), R.layout.item_scan, parent, false); viewHolder = new ScanItemVH(binding); binding.setVariable(BR.scanitem, viewHolder); break; case 1: binding = DataBindingUtil.inflate(scanVH.mCtx.getLayoutInflater(), R.layout.item_scan2, parent, false); viewHolder = new ScanItemVH2(binding); binding.setVariable(BR.scanitem2, viewHolder); break; } return viewHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { if (getItemViewType(position) == 0) { ScanItemVH viewHolder = (ScanItemVH) holder; // BleBean bleBean = scanVH.ScanItemVHs.get(position); BleBean bleBean = arrayList.get(position); viewHolder.mBean = bleBean; viewHolder.mMac.set(bleBean.name + " " + bleBean.getMacStr() + " " + bleBean.rssi); viewHolder.getBinding().executePendingBindings(); } else { ScanItemVH2 viewHolder = (ScanItemVH2) holder; BleBean bleBean = arrayList.get(position); // BleBean bleBean = scanVH.ScanItemVHs.get(position); viewHolder.mBean = bleBean; viewHolder.mMac.set(bleBean.name + " " + bleBean.getMacStr() + " " + bleBean.rssi); viewHolder.getBinding().executePendingBindings(); } } @Override public int getItemCount() { return arrayList.size(); } @Override public int getItemViewType(int position) { String name = arrayList.get(position).name; if (name != null && name.contains("RF")) { return 1; } else { return 0; } } @Override public long getItemId(int position) { return super.getItemId(position); } }); } } @BindingAdapter({"app:swipeRefreshLayout"}) public static void refreshScan(final SwipeRefreshLayout swipeRefreshLayout, final ScanVH scanVH) { if (scanVH != null) { swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { scanVH.refresh(); ThreadUtils.runOnUiThreadDelayed(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(false); scanVH.isRefresh.set(false); } }, 1000); } }); } } }
cbe00b62266ee32188f8a64c294166e2029343fe
f3a9738c972396677d0b5aa3436cd335e39ddc56
/AA_PDL/src/main/java/pack/ACH_Clear_Admin.java
1ee6d18c0db5aa5d8e51b05d68b1acf5c6431897
[]
no_license
venkat3030/AA_venkat
22f9ce24f21d4254124b8eab9fdf5d51629246e5
cd9e5aaeceb96fe7bc7cd525851ecaa0cff24308
refs/heads/master
2022-07-19T01:02:33.556518
2020-01-22T06:56:03
2020-01-22T06:56:03
235,505,889
0
0
null
2022-06-29T17:55:23
2020-01-22T05:34:43
HTML
UTF-8
Java
false
false
10,841
java
package pack; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.ITestResult; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Random; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; /*import Test.CO_ILP.Need; import Test.CO_ILP.scenario;*/ import pack.*; import bsh.*; //import scala.collection.Iterator; //import scala.collection.Set; //import Pages.HomePage; //import Pages.LoginPage; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.FileReader; public class ACH_Clear_Admin extends AA_PDL{ public static void ACH_Clear_Admin(String SSN,String FileName) throws Exception { //Excel TestData = new Excel("E:/QC_Workspace/AA_Automation/TestData/PDL/"+FileName); //Excel TestData = new Excel(System.getProperty("user.dir")+"/TestData/PDL_Regression_Prod/"+FileName); int lastrow=TestData.getLastRow("NewLoan"); System.out.println("NewLoan "+lastrow); String sheetName="NewLoan"; for(int row=2;row<=lastrow;row++) { String RegSSN = TestData.getCellData(sheetName,"SSN",row); if(SSN.equals(RegSSN)) { String TxnType=TestData.getCellData(sheetName,"TxnType",row); String TenderType = TestData.getCellData(sheetName,"TenderType",row); String ProductID=TestData.getCellData(sheetName,"ProductID",row); //String UserName = TestData.getCellData(sheetName,"UserName",row); //String Password = TestData.getCellData(sheetName,"Password",row); ////String StoreId = TestData.getCellData(sheetName,"StoreId",row); //String AdminURL=TestData.getCellData(sheetName,"AdminURL",row); //System.out.println(AdminURL); test.log(LogStatus.INFO, "Scheduler-Store Aging"); //System.out.println(ProductID); //String AppURL = TestData.getCellData(sheetName,"AppURL",row); //appUrl = AppURL; Login.Login(UserName, Password, StoreId); String SSN1 = SSN.substring(0, 3); String SSN2 = SSN.substring(3,5); String SSN3 = SSN.substring(5,9); Thread.sleep(2000); //Thread.sleep(1000); driver.switchTo().frame("topFrame"); driver.findElement(By.xpath("//*[contains(text(),'Loan Transactions')]")).click(); test.log(LogStatus.PASS, "Clicked on Loan Transactions"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.switchTo().defaultContent(); driver.switchTo().frame("mainFrame"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.findElement(By.cssSelector("li[id='911101']")).click(); test.log(LogStatus.PASS, "Clicked on Transactions"); driver.switchTo().frame("main"); driver.findElement(By.name("ssn1")).sendKeys(SSN1); test.log(LogStatus.PASS, "SSN1 is entered: "+SSN1); driver.findElement(By.name("ssn2")).sendKeys(SSN2); test.log(LogStatus.PASS, "SSN2 is entered: "+SSN2); driver.findElement(By.name("ssn3")).sendKeys(SSN3); test.log(LogStatus.PASS, "SSN3 is entered: "+SSN3); driver.findElement(By.name("submit1")).click(); test.log(LogStatus.PASS, "Click on submit Button"); for(String winHandle : driver.getWindowHandles()){ driver.switchTo().window(winHandle); } driver.switchTo().defaultContent(); driver.switchTo().frame("mainFrame"); driver.switchTo().frame("main"); driver.findElement(By.name("button")).click(); test.log(LogStatus.PASS, "Click on GO Button"); for(String winHandle : driver.getWindowHandles()){ driver.switchTo().window(winHandle); } driver.switchTo().defaultContent(); driver.switchTo().frame("mainFrame"); driver.switchTo().frame("main"); if(ProductID.equals("PDL")) { driver.findElement(By.xpath("//input[@value='Go' and @type='button']")).click(); //html/body/form[1]/table/tbody/tr/td/table/tbody/tr/td/table[2]/tbody/tr[7]/td[2]/table/tbody/tr/td/table/tbody/tr[5]/td[11]/input[1] } test.log(LogStatus.PASS, "Click on GO Button"); for( String winHandle1 : driver.getWindowHandles()) { driver.switchTo().window(winHandle1); } driver.switchTo().defaultContent(); driver.switchTo().frame("mainFrame"); driver.switchTo().frame("main"); driver.findElement(By.name("transactionList")).sendKeys("History"); if(ProductID.equals("PDL")) { driver.findElement(By.id("go_Button")).click(); } for( String winHandle1 : driver.getWindowHandles()) { driver.switchTo().window(winHandle1); } driver.switchTo().defaultContent(); driver.switchTo().frame("mainFrame"); driver.switchTo().frame("main"); String loanNumber=null; loanNumber = driver.findElement(By.xpath("//*[@id='transactionHistoryTable']/tbody/tr/td[4]/table/tbody/tr[4]/td/span[2]")).getText(); //*[@id="transactionHistoryTable"]/tbody/tr/td[4]/table/tbody/tr[4]/td/span[2] test.log(LogStatus.PASS, "Capture LoanNumber"+loanNumber); //driver = new InternetExplorerDriver(); // pradeep driver.get(AdminURL); driver.findElement(By.name("loginRequestBean.userId")).sendKeys("admin"); test.log(LogStatus.PASS, "Username is entered: admin"); driver.findElement(By.name("loginRequestBean.password")).sendKeys(Password); test.log(LogStatus.PASS, "Password is entered: "+Password); driver.findElement(By.name("login")).click(); test.log(LogStatus.PASS, "Clicked on Submit button"); Thread.sleep(2000); driver.switchTo().defaultContent(); driver.switchTo().frame("topFrame"); driver.findElement(By.xpath("//*[contains(text(),'Transactions')]")).click(); test.log(LogStatus.PASS, "Clicked on Transactions"); driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS); driver.switchTo().defaultContent(); driver.switchTo().frame("mainFrame"); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); driver.findElement(By.linkText("ACH")).click(); test.log(LogStatus.PASS, "Clicked on ACH"); Thread.sleep(5000); driver.findElement(By.linkText("Payday Loan")).click(); test.log(LogStatus.PASS, "Clicked on PayDayLoan"); driver.findElement(By.linkText("ACH Clear")).click(); test.log(LogStatus.PASS, "Clicked on ACH Clear"); /*driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);*/ driver.switchTo().defaultContent(); driver.switchTo().frame("mainFrame"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.findElement(By.linkText("QA Jobs")).click(); test.log(LogStatus.PASS, "Clicked on QA Jobs"); Thread.sleep(2000); driver.switchTo().defaultContent(); driver.switchTo().frame("mainFrame"); driver.switchTo().frame("main"); driver.findElement(By.name("requestBean.locationNbr")).sendKeys(StoreId); test.log(LogStatus.PASS, "StoreId is entered: "+StoreId); driver.findElement(By.name("submit")).click(); test.log(LogStatus.PASS, "Clicked on Submit button"); for( String winHandle1 : driver.getWindowHandles()) { driver.switchTo().window(winHandle1); } driver.switchTo().defaultContent(); driver.switchTo().frame("mainFrame"); driver.switchTo().frame("main"); // int rowsize = driver.findElements(By.name("/html/body/table/tbody/tr/td/table[2]/tbody/tr")).size(); List<WebElement> options = driver.findElements(By.xpath("/html/body/table/tbody/tr/td/table[2]/tbody/tr")); int rowsize = options.size(); for (int i=4; i<=rowsize;i++) { String value = driver.findElement(By.xpath("/html/body/table/tbody/tr/td/table[2]/tbody/tr["+i+"]/td[1]/input")).getAttribute("value"); // /html/body/table/tbody/tr/td/table[2]/tbody/tr[4]/td[1]/input if(value.contains(loanNumber)) { driver.findElement(By.xpath("/html/body/table/tbody/tr/td/table[2]/tbody/tr["+i+"]/td[1]/input")).click(); driver.findElement(By.xpath("//*[@id='CmdReturnPosting']")).click(); ////*[@id="CmdReturnPosting"] break; } } /*driver.findElement(By.name("requestBean.chkName")).click();; test.log(LogStatus.PASS, "Customer Record CheckBox Selected"); driver.findElement(By.name("rtnReasonId")).sendKeys("R01-Insufficient Funds"); test.log(LogStatus.PASS, "Return Reason Selected as :: R01-Insufficient Funds"); driver.findElement(By.name("CmdReturnPosting")).click(); test.log(LogStatus.PASS, "Clicked on ACH Return Posting button");*/ for( String winHandle1 : driver.getWindowHandles()) { driver.switchTo().window(winHandle1); } driver.switchTo().defaultContent(); driver.switchTo().frame("mainFrame"); driver.switchTo().frame("main"); /*if(driver.findElement(By.name("Ok")).isDisplayed()) { test.log(LogStatus.PASS, "ACH Clear Done Successfull"); driver.findElement(By.name("Ok")).click(); }*/ } } } }
406952a3690325727d3fdcdda4f779d75e7e5883
b52fa223f54b51cc271e1cbfc4c28aa76e734718
/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/StreamOperatorStateContext.java
2eb777a8db6e38b6b444187532bcac2fdfe1885c
[ "ISC", "Apache-2.0", "BSD-3-Clause", "OFL-1.1" ]
permissive
itharavi/flink
1d0b7e711df93d3a13eae42da71a08dc45aaf71f
f0f9343a35ff21017e2406614b34a9b1f2712330
refs/heads/master
2023-08-03T02:53:12.278756
2020-01-08T05:58:54
2020-01-10T15:51:31
233,090,272
3
1
Apache-2.0
2023-07-23T02:28:35
2020-01-10T16:47:58
null
UTF-8
Java
false
false
2,532
java
/* * 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.flink.streaming.api.operators; import org.apache.flink.runtime.state.AbstractKeyedStateBackend; import org.apache.flink.runtime.state.KeyGroupStatePartitionStreamProvider; import org.apache.flink.runtime.state.OperatorStateBackend; import org.apache.flink.runtime.state.StatePartitionStreamProvider; import org.apache.flink.util.CloseableIterable; /** * This interface represents a context from which a stream operator can initialize everything connected to state such * as e.g. backends, raw state, and timer service manager. */ public interface StreamOperatorStateContext { /** * Returns true, the states provided by this context are restored from a checkpoint/savepoint. */ boolean isRestored(); /** * Returns the operator state backend for the stream operator. */ OperatorStateBackend operatorStateBackend(); /** * Returns the keyed state backend for the stream operator. This method returns null for non-keyed operators. */ AbstractKeyedStateBackend<?> keyedStateBackend(); /** * Returns the internal timer service manager for the stream operator. This method returns null for non-keyed * operators. */ InternalTimeServiceManager<?> internalTimerServiceManager(); /** * Returns an iterable to obtain input streams for previously stored operator state partitions that are assigned to * this stream operator. */ CloseableIterable<StatePartitionStreamProvider> rawOperatorStateInputs(); /** * Returns an iterable to obtain input streams for previously stored keyed state partitions that are assigned to * this operator. This method returns null for non-keyed operators. */ CloseableIterable<KeyGroupStatePartitionStreamProvider> rawKeyedStateInputs(); }
1ea2c7a981379bc8a632b93d89bf0010b8a8731f
6f43913522f73d5f0e54829585caeb6583be4784
/JavaApplication2/src/javaapplication2/JavaApplication2.java
9813aa56051ce2e872d2c9fcad7940b5862d5d7e
[]
no_license
PaulloWeverton/poow20171
ee8eadaba0c1972cc44a9cc9182df2e6fd56a388
e8847326d49d578f07ecae968b839c639e35eb78
refs/heads/master
2021-01-23T17:38:13.486359
2017-03-10T02:18:18
2017-03-10T02:18:18
82,986,178
0
0
null
null
null
null
UTF-8
Java
false
false
443
java
/* * 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 javaapplication2; /** * * @author Laboratorio */ public class JavaApplication2 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } }
66cbe03ad334680c87b55257b448682a46412fee
6cbfe46c57a7adbe7900a4968a49d0ceca4fc970
/android/src/main/java/com/poowf/argon2/RNArgon2Package.java
638e1c6af8f8e6e55de1e90da72a1d22e98d86ba
[ "MIT" ]
permissive
PinkDiamond1/react-native-argon2
005851290e0bf9fb0fce7696659005207357feee
9add47e2cb5eb2f5883db37db8fe6b58f8fb33d6
refs/heads/master
2023-03-16T11:30:21.570599
2020-10-14T22:14:37
2020-10-14T22:14:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,015
java
package com.poowf.argon2; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class RNArgon2Package implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new RNArgon2Module(reactContext)); return modules; } // Deprecated since React Native 0.47 public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactApplicationContext) { return Collections.emptyList(); } }
5b348ff153ac83c3c16d41a29258689f6594dd7a
6d5ed6a245babb5b574a5d1895e7ec6243a19db9
/spring-demo-one/src/com/luv2code/springdemo/SetterDemoApp.java
c85717e398ddc12c510b91763d0c9cc952bb261e
[]
no_license
WebAppEngineers/Emerging-App
b898bb7346076aa7fc4d80532416eca9c2e4d7d9
964c13a4ebbf886529d063e1b4acd940d4278296
refs/heads/master
2020-03-27T16:24:14.497625
2018-12-19T07:38:09
2018-12-19T07:38:09
146,780,277
0
0
null
2018-12-19T07:38:10
2018-08-30T17:01:21
Java
UTF-8
Java
false
false
863
java
package com.luv2code.springdemo; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SetterDemoApp { public static void main(String[] args) { //load the spring configuration file ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //retrieve bean from spring container CricketCoach theCoach = context.getBean("myCricketCoach", CricketCoach.class); //call method on the bean System.out.println(theCoach.getDailyWorkout()); System.out.println(theCoach.getDailyFortune()); //call our new methods to get the literal values System.out.println(theCoach.getEmailAddress()); System.out.println(theCoach.getTeam()); //close the application context context.close(); } }
3b140fa9579263769aa1fe48c3f8639df7f7edeb
071a9fa7cfee0d1bf784f6591cd8d07c6b2a2495
/corpus/norm-class/eclipse.jdt.core/2530.java
29b9c9e1d8ff029ddbf85256a0567f5b7cb489ed
[ "MIT" ]
permissive
masud-technope/ACER-Replication-Package-ASE2017
41a7603117f01382e7e16f2f6ae899e6ff3ad6bb
cb7318a729eb1403004d451a164c851af2d81f7a
refs/heads/master
2021-06-21T02:19:43.602864
2021-02-13T20:44:09
2021-02-13T20:44:09
187,748,164
0
0
null
null
null
null
UTF-8
Java
false
false
143
java
test foo string tokenizer stringtokenizer token ise r tokeniser string tokenizer stringtokenizer token ise r tokeniser count tokens counttokens
08e46f5e15793db69ce34480b8990a07eca49d0c
d03553db3cb3b8f28467d5ea23f9c1bef027e52b
/umg-api/src/main/java/com/weshare/umg/util/IpUtils.java
fc507a83678aa1a965f1b7cff7d6dd78af37a1ef
[]
no_license
AudreyKe/umg
f94f499b107b32dc3c7b6c271e7d970fcf92620a
a194698b81327fe230eabe852f632dcc738bfbf2
refs/heads/master
2022-12-24T04:22:38.008702
2019-05-27T08:11:47
2019-05-27T08:11:48
188,758,382
0
0
null
null
null
null
UTF-8
Java
false
false
6,964
java
package com.weshare.umg.util; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.net.util.IPAddressUtil; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; import java.util.regex.Matcher; import java.util.regex.Pattern; public class IpUtils { /**增加日志*/ private final static Logger logger = LoggerFactory.getLogger(IpUtils.class); private static final String LOCAL_IPV4 = "127.0.0.1"; private static final String LOCAL_IPV6 = "0:0:0:0:0:0:0:1"; private static final String IP_UNKNOWN = "unknown"; public static final String IPV4 = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b"; private static String ip = null; /**获取本地IP*/ public static String getLocalIp() { if (ip == null) { synchronized (IpUtils.class) { if (ip == null) { ip = localIp(); } } } return ip; } /** * @Description 判断IP是否是内网 * @return true:内网 false:公网 **/ public static boolean internalIp(String ip) { byte[] addr = IPAddressUtil.textToNumericFormatV4(ip); return internalIp(addr); } public static boolean internalIp(byte[] addr) { final byte b0 = addr[0]; final byte b1 = addr[1]; final byte b2 = addr[2]; final byte b3 = addr[3]; //10.x.x.x/8 final byte SECTION_1 = 0x0A; //172.16.x.x/12 final byte SECTION_2 = (byte) 0xAC; final byte SECTION_3 = (byte) 0x10; final byte SECTION_4 = (byte) 0x1F; //192.168.x.x/16 final byte SECTION_5 = (byte) 0xC0; final byte SECTION_6 = (byte) 0xA8; //127.0.0.1 final byte SECTION_7 = (byte) 0x7F; final byte SECTION_8 = (byte) 0x00; final byte SECTION_9 = (byte) 0x01; switch (b0) { case SECTION_1: return true; case SECTION_2: if (b1 >= SECTION_3 && b1 <= SECTION_4) { return true; } case SECTION_5: switch (b1) { case SECTION_6: return true; } case SECTION_7: if( b1 == b2 && b2 == SECTION_8 && b3 == SECTION_9){ return true; } default: return false; } } /** * 获取本地ip字符串 * @return 本地的ip字符 */ private static String localIp() { try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface .getNetworkInterfaces(); NetworkInterface network; Enumeration<InetAddress> inetAddresses; while (networkInterfaces.hasMoreElements()) { network = networkInterfaces.nextElement(); if (network.getName().startsWith("eth") && !network.isLoopback() && !network.isVirtual()) { inetAddresses = network.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress inetAddress = inetAddresses.nextElement(); String hostAddress = inetAddress.getHostAddress(); if (!hostAddress.contains(":")){ return hostAddress; } } } } } catch (Exception ex) { logger.error("localIp error!",ex); } return LOCAL_IPV4; } /*** * 获取客户端IP地址;if通过了Nginx获取;X-Real-IP, * @param request 客户端请求的对象 * @return 返回客户端ip字符串 */ public static String getClientIP(HttpServletRequest request) { String ip = request.getHeader("X-Real-IP"); // 先获取代理机传过来的客户端IP by trentluo if (StringUtils.isBlank(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) { String forwardIp = request.getHeader("X-Forwarded-For"); if (StringUtils.isNoneBlank(forwardIp)) { String[] ipLists = forwardIp.split(","); ip = ipLists[0]; } } if (StringUtils.isBlank(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (StringUtils.isBlank(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isBlank(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if (LOCAL_IPV4.equals(ip) || LOCAL_IPV6.equals(ip)) { //获取本机真实IP ip = getLocalIp(); } return ip; } /** * 根据ip地址计算出long型的数据 * @param strIP IP V4 地址 * @return long值 */ public static long ipv4ToLong(String strIP) { if(isIpv4(strIP)){ long[] ip = new long[4]; // 先找到IP地址字符串中.的位置 int position1 = strIP.indexOf("."); int position2 = strIP.indexOf(".", position1 + 1); int position3 = strIP.indexOf(".", position2 + 1); // 将每个.之间的字符串转换成整型 ip[0] = Long.parseLong(strIP.substring(0, position1)); ip[1] = Long.parseLong(strIP.substring(position1 + 1, position2)); ip[2] = Long.parseLong(strIP.substring(position2 + 1, position3)); ip[3] = Long.parseLong(strIP.substring(position3 + 1)); return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3]; } return 0; } public static boolean isIpv4(String ip) { if(StringUtils.isBlank(ip)){ return false; } Pattern p = Pattern.compile(IPV4); Matcher m = p.matcher(ip); return m.matches(); } /** * 根据long值获取ip v4地址 * * @param longIP IP的long表示形式 * @return IP V4 地址 */ public static String longToIpv4(long longIP) { StringBuffer sb = new StringBuffer(); // 直接右移24位 sb.append(String.valueOf(longIP >>> 24)); sb.append("."); // 将高8位置0,然后右移16位 sb.append(String.valueOf((longIP & 0x00FFFFFF) >>> 16)); sb.append("."); sb.append(String.valueOf((longIP & 0x0000FFFF) >>> 8)); sb.append("."); sb.append(String.valueOf(longIP & 0x000000FF)); return sb.toString(); } }
cde164999bf1abd995ea32ab2dd51ef92c9d5483
06d479913406787b97bcbe828cf9384c77872e93
/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2RefreshTokenAuthenticationConverter.java
20882163ba931574e9efccb0401b25741f30603d
[ "Apache-2.0" ]
permissive
hanhongyuan/spring-authorization-server
d831b71bc63b56a1319ab857b40d055e9ff16cc2
725c300db227d63f53e921556308da0a1735b78a
refs/heads/main
2023-07-20T08:34:16.624959
2021-08-19T00:14:55
2021-08-19T00:14:55
397,773,110
1
0
Apache-2.0
2021-08-19T00:47:36
2021-08-19T00:47:36
null
UTF-8
Java
false
false
4,018
java
/* * Copyright 2020-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.authorization.web.authentication; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.springframework.lang.Nullable; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.server.authorization.authentication.OAuth2RefreshTokenAuthenticationToken; import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter; import org.springframework.security.web.authentication.AuthenticationConverter; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; /** * Attempts to extract an Access Token Request from {@link HttpServletRequest} for the OAuth 2.0 Refresh Token Grant * and then converts it to an {@link OAuth2RefreshTokenAuthenticationToken} used for authenticating the authorization grant. * * @author Joe Grandja * @since 0.1.2 * @see AuthenticationConverter * @see OAuth2RefreshTokenAuthenticationToken * @see OAuth2TokenEndpointFilter */ public final class OAuth2RefreshTokenAuthenticationConverter implements AuthenticationConverter { @Nullable @Override public Authentication convert(HttpServletRequest request) { // grant_type (REQUIRED) String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE); if (!AuthorizationGrantType.REFRESH_TOKEN.getValue().equals(grantType)) { return null; } Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication(); MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getParameters(request); // refresh_token (REQUIRED) String refreshToken = parameters.getFirst(OAuth2ParameterNames.REFRESH_TOKEN); if (!StringUtils.hasText(refreshToken) || parameters.get(OAuth2ParameterNames.REFRESH_TOKEN).size() != 1) { OAuth2EndpointUtils.throwError( OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REFRESH_TOKEN, OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI); } // scope (OPTIONAL) String scope = parameters.getFirst(OAuth2ParameterNames.SCOPE); if (StringUtils.hasText(scope) && parameters.get(OAuth2ParameterNames.SCOPE).size() != 1) { OAuth2EndpointUtils.throwError( OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.SCOPE, OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI); } Set<String> requestedScopes = null; if (StringUtils.hasText(scope)) { requestedScopes = new HashSet<>( Arrays.asList(StringUtils.delimitedListToStringArray(scope, " "))); } Map<String, Object> additionalParameters = new HashMap<>(); parameters.forEach((key, value) -> { if (!key.equals(OAuth2ParameterNames.GRANT_TYPE) && !key.equals(OAuth2ParameterNames.REFRESH_TOKEN) && !key.equals(OAuth2ParameterNames.SCOPE)) { additionalParameters.put(key, value.get(0)); } }); return new OAuth2RefreshTokenAuthenticationToken( refreshToken, clientPrincipal, requestedScopes, additionalParameters); } }
d85317798f91f606cb4c2e2f7c4ea19eecedcc13
fd966e1679d20b0639ef4146aed5482ac88338ac
/1941720192/ArrayObjects/src/arrayobjects/ArrayObjects.java
bde4f34b9ceb70ed683892f192c3cf2934ff4b74
[]
no_license
zulfikarrahman30/AlgoritmaStrukturData
7eff638515b3008959ca7b1b88aaf946f5830d85
5022127a11c42802290dcd256209500e38816ac8
refs/heads/master
2021-01-03T16:20:37.523392
2020-04-30T05:39:50
2020-04-30T05:39:50
240,148,502
0
0
null
2020-02-13T01:03:18
2020-02-13T01:03:17
null
UTF-8
Java
false
false
428
java
/* * 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 arrayobjects; /** * * @author USER */ public class ArrayObjects { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } }
ff8502e9f6c1cb01fef0a674d4979d0e588ffc64
3493491468732d4272c503ccec9e02a555123317
/Java/_PizzaService_WEB/src/main/java/com/java/myrotiuk/exception/StatusOrderException.java
d0be28536daac29961bc18838c7bb860353c5aeb
[]
no_license
IvanMyrotiuk/MyWorks
0e9f90105d7a65e1d75789a4d48bfc315014f6f2
6c48849f16ef1729474f360f920a3c21644f98f0
refs/heads/master
2021-01-21T04:32:20.620768
2016-06-24T04:02:03
2016-06-24T04:02:03
55,106,657
0
0
null
null
null
null
UTF-8
Java
false
false
163
java
package com.java.myrotiuk.exception; public class StatusOrderException extends RuntimeException { public StatusOrderException(String name) { super(name); } }
d0c5be4d0df171c80854c5a1a08dcbab72da6a42
9f30fbae8035c2fc1cb681855db1bc32964ffbd4
/Java/HuangDongJiang/Task6/task6-noCache/main/java/com/baidu/controller/StudentController.java
8223685ee183d978a7c9ec41c5fc03599beffd9c
[]
no_license
IT-xzy/Task
f2d309cbea962bec628df7be967ac335fd358b15
4f72d55b8c9247064b7c15db172fd68415492c48
refs/heads/master
2022-12-23T04:53:59.410971
2019-06-20T21:14:15
2019-06-20T21:14:15
126,955,174
18
395
null
2022-12-16T12:17:21
2018-03-27T08:34:32
null
UTF-8
Java
false
false
2,976
java
package com.baidu.controller; import com.baidu.pojo.Student; import com.baidu.service.StudentService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.Resource; import java.util.List; import java.util.logging.Logger; @Controller public class StudentController { private static final Log log = LogFactory.getLog(StudentController.class); @Autowired private StudentService studentService; @Resource private Student student; static Logger logger = Logger.getLogger("StudentController.class"); //主界面 @RequestMapping("/index") public String indexController(){ return "curd"; } // 添加学生信息 @RequestMapping(value = "/student",method = RequestMethod.POST) public String addStudent(int id, String name, String school){ student.setId(id); student.setName(name); student.setSchool(school); studentService.saveStudent(student); return "success"; } // 删除学生信息 @RequestMapping(value = "/student",method =RequestMethod.DELETE) public String deleteStudent(@RequestParam("id") int id) throws Exception { studentService.deleteStudentById(id); return "success"; } // 更新学生信息 @RequestMapping(value = "/student/infomation",method =RequestMethod.PUT) public String addStudent(@RequestParam("id") int id,@RequestParam("name") String name) throws Exception { student.setId(id); student.setName(name); studentService.updateStudent(student); return "success"; } // 根据ID查找单个学生信息(测试json) @RequestMapping(value = "/student/id",method =RequestMethod.GET) public String findStudentToJson( int id,Model model) throws Exception { Student student1 = studentService.findStudentById(id); model.addAttribute("student",student1); model.addAttribute("code",111); model.addAttribute("message","正确返回"); return "studentItem"; } // 根据ID查找单个学生信息(测试jsp) @RequestMapping(value = "jsp/student/id",method =RequestMethod.GET) public String findStudentToJsp( int id,Model model) throws Exception { Student student1 = studentService.findStudentById(id); model.addAttribute("student",student1); model.addAttribute("code",111); model.addAttribute("message","正确返回"); return "studentItemJsp"; } // 查找所有学生信息 @RequestMapping(value = "/allStudent",method =RequestMethod.GET) public String findAllStudent(Model model) { List<Student> studentList = studentService.findAllStudent(); model.addAttribute("studentList",studentList); return "studentList"; } }
29d49ab9f69e5fc6603cceaf21710f7ea25e89d7
5d69d80b9f723eaacf5bebd7e7745c6b842d68e8
/src/com/g/multithreading/practise/SleepYieldStop.java
53b188f32b11ffc2d21f87c3a4b2b5e337389ede
[]
no_license
Bishnu-KC/ChapterWise
0c06423393316fed91fa7ac6bb17b4c2dfea834c
079e39091a91878ecde97d6364b71e1a7240e35d
refs/heads/master
2020-03-28T16:28:16.819773
2018-09-13T21:11:00
2018-09-13T21:11:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,093
java
package com.g.multithreading.practise; class A1 extends Thread { public void run() { for (int i=1;i<=5;i++) { if(i==3) yield(); System.out.println("\t From Thread A: i= "+i); } System.out.println("Exit from A."); } } class B1 extends Thread { public void run() { for (int j=1;j<=5;j++) { System.out.println("\t From Thread B: j = "+j); if(j==3) stop(); } System.out.println("Exit From B"); } } class C1 extends Thread { public void run() { for(int k=1; k<=5;k++) { System.out.println("\t From Thread C: k = "+k); if(k==3) { try { sleep(1000); } catch(Exception e) { e.printStackTrace(); System.out.print("Exception Occured:"); } } } System.out.println("Exit from C."); } } public class SleepYieldStop { public static void main(String[] args) { System.out.println("Start Tread A:"); new A1().start(); System.out.println("Start Tread A:"); new B1().start(); System.out.println("Start Tread A:"); new C1().start(); System.out.println("End of main Thread:"); } }
c7915b353c1fe382b16d2913adc5cd7e16f9859c
38fc24b295c0f2bd416b6065da06ea56df6a1fce
/evaluator/src/main/java/org/semanticweb/fbench/evaluation/Evaluation.java
0dbaf933da8f133af1a9987ad456930508456579
[ "Apache-2.0", "AGPL-3.0-only" ]
permissive
semagrow/kobe
189730f8fafe178b2207812c18d37b4e653f58e5
847bf4a93ccec7d44a5f2946ac75b1b9c3af43c0
refs/heads/devel
2022-08-31T12:19:17.970589
2021-12-03T18:59:30
2021-12-03T18:59:30
47,556,626
8
5
Apache-2.0
2022-03-29T21:05:28
2015-12-07T14:21:39
Java
UTF-8
Java
false
false
10,568
java
package org.semanticweb.fbench.evaluation; import org.semanticweb.fbench.Config; import org.semanticweb.fbench.LogUtils; import org.semanticweb.fbench.query.Query; import org.semanticweb.fbench.query.QueryManager; import org.semanticweb.fbench.report.EarlyResultsMonitor; import org.semanticweb.fbench.report.ReportStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class for the actual evaluation runtime. <p> * * Can be configured dynamically using "evaluationClass" property. * * @see SesameEvaluation * @author as * */ public abstract class Evaluation { public static Logger log = LoggerFactory.getLogger(Evaluation.class); protected ReportStream report; protected EarlyResultsMonitor earlyResults; public Evaluation() { } public final void run() throws Exception { // initialize the early results monitor try { earlyResults = (EarlyResultsMonitor)Class.forName(Config.getConfig().getEarlyResultsMonitorClass()).newInstance(); earlyResults.init(); } catch (Exception e) { log.error("Error while configuring early results monitor. Check your earlyResultsMonitorClass setting. [" + Config.getConfig().getReportStream() + "]: " + e.getMessage()); log.debug("Exception details:", e); System.exit(1); } // intialize the report stream, default is SimpleReportStream try { report = (ReportStream)Class.forName(Config.getConfig().getReportStream()).newInstance(); report.open(); } catch (Exception e) { log.error("Error while configuring the report output stream [" + Config.getConfig().getReportStream() + "]: " + e.getMessage()); log.debug("Exception details:", e); report.close(); System.exit(1); } // perform any initialization, e.g. in Sesame load repositories try { report.initializationBegin(); long initializationStart = System.currentTimeMillis(); initialize(); long initializationDuration = System.currentTimeMillis() - initializationStart; report.initializationEnd(initializationDuration); } catch (Exception e) { log.error("Error during initialization in " + this.getClass().getCanonicalName() + " (" + e.getClass().getSimpleName() + "): " + e.getMessage()); log.debug("Exception details:", e); report.close(); System.exit(1); } if (Config.getConfig().isFill()) { log.info("Fill mode activated. No query evalutation. Done."); report.endEvaluation(0); report.close(); System.exit(0); } // depending on config run the evaluation with different settings // debugMode -> run evaluation once // timeout -> use extra thread and stop query execution after timeout // otherwise -> n runs if (Config.getConfig().isDebugMode()) { runEval(); } else if (Config.getConfig().getTimeout()>0) { runMultiEvalTimeout(); } else { runMultiEval(); } earlyResults.close(); report.close(); // perform any clean up, e.g. in Sesame close repositories try { log.info("Peform any cleanup operation."); finish(); } catch (Exception e) { log.error("Error during clean up in " + this.getClass().getCanonicalName() + " (" + e.getClass().getSimpleName() + "): " + e.getMessage()); log.debug("Exception details:", e); } } protected void runEval() { log.info("Evaluation of queries in debug mode (one run per query)..."); boolean showResult = Config.getConfig().isShowResults(); report.beginEvaluation(Config.getConfig().getDataConfig(), Config.getConfig().getQuerySet(), QueryManager.getQueryManager().getQueries().size(), 1); long evalStart = System.currentTimeMillis(); for (Query q : QueryManager.getQueryManager().getQueries()) { try { LogUtils.setMDC(); log.debug("Experiment: " + Config.getConfig().getExperimentName() + " - Query: " + q.getIdentifier() + " - Run: 1"); report.beginQueryEvaluation(q, 1); long start = System.currentTimeMillis(); earlyResults.nextQuery(q, start); int numberOfResults = runQueryDebug(q, 1, showResult); long duration = System.currentTimeMillis() - start; earlyResults.queryDone(); report.endQueryEvaluation(q, 1, duration, numberOfResults); queryRunEnd(q, false); log.info(q.getIdentifier() + " (#1, duration: " + duration + "ms, results " + numberOfResults + ")"); } catch (Exception e) { report.endQueryEvaluation(q, 1, -2, -1); log.error("Error executing query " + q.getIdentifier()+ " (" + e.getClass().getSimpleName() + "): " + e.getMessage()); log.debug("Exception details:", e); queryRunEnd(q, true); } } long overallDuration = System.currentTimeMillis() - evalStart; report.endEvaluation(overallDuration); log.info("Evaluation of queries done. Overall duration: " + overallDuration + "ms"); } protected void runMultiEval() { log.info("Evaluation of queries in multiple runs..."); int evalRuns = Config.getConfig().getEvalRuns(); report.beginEvaluation(Config.getConfig().getDataConfig(), Config.getConfig().getQuerySet(), QueryManager.getQueryManager().getQueries().size(), evalRuns); long evalStart = System.currentTimeMillis(); for (int run = 1; run <= evalRuns; run++){ report.beginRun(run, evalRuns); long runStart = System.currentTimeMillis(); for (Query q : QueryManager.getQueryManager().getQueries()){ try { LogUtils.setMDC(); log.debug("Experiment: " + Config.getConfig().getExperimentName() + " - Query: " + q.getIdentifier() + " - Run: " + run); report.beginQueryEvaluation(q, run); long start = System.currentTimeMillis(); earlyResults.nextQuery(q, start); int numberOfResults = runQuery(q, run); long duration = System.currentTimeMillis() - start; earlyResults.queryDone(); report.endQueryEvaluation(q, run, duration, numberOfResults); queryRunEnd(q, false); } catch (Exception e) { report.endQueryEvaluation(q, run, -2, -1); log.error("Error executing query " + q.getIdentifier()+ " (" + e.getClass().getSimpleName() + "): " + e.getMessage()); log.debug("Exception details:", e); queryRunEnd(q, true); } } long runDuration = System.currentTimeMillis() - runStart; report.endRun(run, evalRuns, runDuration); } long overallDuration = System.currentTimeMillis() - evalStart; report.endEvaluation(overallDuration); log.info("Evaluation of queries done."); } protected synchronized void runMultiEvalTimeout() { int evalRuns = Config.getConfig().getEvalRuns(); long timeout = Config.getConfig().getTimeout(); log.info("Evaluation of queries in multiple runs (using timeout of " + timeout + "ms) ..."); report.beginEvaluation(Config.getConfig().getDataConfig(), Config.getConfig().getQuerySet(), QueryManager.getQueryManager().getQueries().size(), evalRuns); long evalStart = System.currentTimeMillis(); boolean reInit = false; for (int run = 1; run <= evalRuns; run++){ report.beginRun(run, evalRuns); long runStart = System.currentTimeMillis(); for (Query q : QueryManager.getQueryManager().getQueries()) { try { LogUtils.setMDC(); log.debug("Experiment: " + Config.getConfig().getExperimentName() + " - Query: " + q.getIdentifier() + " - Run: " + run); if (log.isTraceEnabled()) log.trace("Query: " + q.getQuery()); EvaluationThread eval = new EvaluationThread(this, q, report, earlyResults, run); if (reInit) { this.reInitialize(); // re establish connections reInit = false; } eval.start(); synchronized (Evaluation.class) { Evaluation.class.wait(timeout); } eval.interrupt(); // XXX eval.stop(); // TODO check if this is really safe in this scenario, we have shared objects if (!eval.isFinished()) { log.info("Execution of query " + q.getIdentifier() + " resulted in timeout."); report.endQueryEvaluation(q, run, -1, -1); reInit = true; } if (eval.isError()) reInit = true; } catch (InterruptedException e) { log.info("Execution of query " + q.getIdentifier() + " resulted in timeout."); report.endQueryEvaluation(q, run, -1, -1); reInit = true; } catch (Exception e) { report.endQueryEvaluation(q, run, -2, -1); log.error("Error executing query " + q.getIdentifier()+ " (" + e.getClass().getSimpleName() + "): " + e.getMessage()); log.debug("Exception details:", e); reInit = true; } earlyResults.queryDone(); queryRunEnd(q, reInit); } long runDuration = System.currentTimeMillis() - runStart; report.endRun(run, evalRuns, runDuration); } long overallDuration = System.currentTimeMillis() - evalStart; report.endEvaluation(overallDuration); log.info("Evaluation of queries done."); } /** * Perform any initializations here, i.e. load repositories, open streams, etc. * * @throws Exception */ public abstract void initialize() throws Exception; /** * Perform any initializations here, i.e. load repositories, open streams, etc. * * @throws Exception */ public abstract void reInitialize() throws Exception; /** * Clean up after all queries are run, i.e. close streams etc * @throws Exception */ public abstract void finish() throws Exception; /** * Run the specified query. Avoid printing debug information. * * Note: you can use the class internal reportStream to print messages * * @param query * the query to be executed * @return * the number of results * @throws Exception */ public abstract int runQuery(Query query, int run) throws Exception; /** * run the query in debug mode, i.e. printing debug information is ok and not * relevant for any timings * * @param query * @param showResult * @return * @throws Exception */ public abstract int runQueryDebug(Query query, int run, boolean showResult) throws Exception; /** * This method is invoked when a query is run through. Can be used to introduce * a timeout after a query, e.g. for SPARQL this might be convenient to reduce * load * * @param query * @param error */ protected void queryRunEnd(Query query, boolean error) { ; // behaviour can be implemented by sub classes } }
7dde3d2a1515fa95d991c581103d7b6e523e15be
6a2014b118ad2653cafa11487dd4de831f58f3e0
/ProjetoVeiculo/src/Veiculo.java
6de448d1cef6bb4b1eb9b3f5c4d7383611278282
[]
no_license
EsterHolanda/workspace_java20
f314f521189f9aba12954cbc3a43a4e2d519df42
ccda18d5753d1dbb7b98735a670bab1a6ef6771a
refs/heads/master
2023-07-09T14:43:36.786130
2021-08-10T21:01:10
2021-08-10T21:01:10
393,168,263
0
0
null
null
null
null
ISO-8859-1
Java
false
false
560
java
// já que temos uma classe abtrata não posso dar new em objetos dela // podem pode utilizar como template-modelo-molde-padrão a aser seguido // com os requisitos essenciais com o tipo de dados que precisam ter // alem disso podemos exigir q quem herdar dessa classe, compromete-se a escrever a logica dos // métodos definidos, aqui na classe abstrata defini-se o "oq" e nos demais o "como" public abstract class Veiculo { String marca; String modelo; // aqui definimos o "oq" public abstract void acelerar(); public abstract void frear(); }
6abee1144090206fa72d7f65787f002df0816249
4e75a27310d8eaabee5bf460d8fe8184db4af8f8
/Recursion/[Leetcode] 364. Nested List Weight Sum II/test364/src/main/java/lzhou/programmingtest/leetcode/test364/NestedInteger.java
2115285303f1126ecff769819dfbf8270475965b
[]
no_license
lingyanzhou/Programming-Tests
01e32b7d7930020b68b3e160ec704de30557a574
cb732360095e476728c20b2f1314de92c7bac057
refs/heads/master
2021-01-11T19:44:44.459171
2017-07-10T00:06:22
2017-07-10T00:06:22
79,385,967
0
1
null
null
null
null
UTF-8
Java
false
false
614
java
package lzhou.programmingtest.leetcode.test364; import java.util.*; public interface NestedInteger { // @return true if this NestedInteger holds a single integer, rather than a nested list. public boolean isInteger(); // @return the single integer that this NestedInteger holds, if it holds a single integer // Return null if this NestedInteger holds a nested list public Integer getInteger(); // @return the nested list that this NestedInteger holds, if it holds a nested list // Return null if this NestedInteger holds a single integer public List<NestedInteger> getList(); }
5c60bbebc3a0f704f56835144ee321d7a30db124
69e6f6822221088dbb6e27f731fc4d117c20aef3
/yiQu_Api/src/main/java/com/quanmai/yiqu/api/vo/BarCodeInfo.java
ae72a18dccdb5f12ebc910364814cfb5baa2c89c
[]
no_license
zengweitao/YiQuLife
f7dd201be283dfd64f7348b4525d328e7b7b94a9
30dd021e56c8e0914e2e2c23705baf49ffa319ce
refs/heads/master
2021-01-01T18:10:57.454138
2017-07-25T06:38:40
2017-07-25T06:38:40
98,272,858
0
0
null
null
null
null
UTF-8
Java
false
false
747
java
package com.quanmai.yiqu.api.vo; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; public class BarCodeInfo implements Serializable{ /** * */ private static final long serialVersionUID = 8196885321120664480L; public BarCodeInfo() { // TODO Auto-generated constructor stub } public BarCodeInfo(JSONObject jsonObject) throws JSONException { code=new String(); address=jsonObject.getString("address"); time=jsonObject.getString("get_time"); terminalno=jsonObject.getString("terminalno"); phone=jsonObject.getString("phone"); // TODO Auto-generated constructor stub } public String code; public String address; public String time; public String phone; public String terminalno; }
3730438b67218dd0c8a4ca39edfeb9e372dd7cf0
c3e7170bebddcd4024f7dcfeeb2be9b68170382c
/app/src/main/java/sjsu/illuminate/illuminate/Fragments/LearnHungerFragment.java
03818cc0b32475ae6a739f95935c2d16d1a20e95
[]
no_license
mattmontero/Illuminate
c94384888b39a7c87112db370cc27bfa2ce94e0e
48d926f3d89e41470dc2db9b96d52051933ccb94
refs/heads/master
2021-01-21T06:30:06.004164
2017-07-28T02:57:43
2017-07-28T02:57:43
83,236,697
0
0
null
null
null
null
UTF-8
Java
false
false
3,784
java
package sjsu.illuminate.illuminate.Fragments; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import sjsu.illuminate.illuminate.R; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link LearnHungerFragmentInteractionListener} interface * to handle interaction events. * Use the {@link LearnHungerFragment#newInstance} factory method to * create an instance of this fragment. */ public class LearnHungerFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private LearnHungerFragmentInteractionListener mListener; public LearnHungerFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment LearnHungerFragment. */ // TODO: Rename and change types and number of parameters public static LearnHungerFragment newInstance(String param1, String param2) { LearnHungerFragment fragment = new LearnHungerFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_learn_hunger, container, false); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onLearnHungerFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof LearnHungerFragmentInteractionListener) { mListener = (LearnHungerFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement LearnDreamFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface LearnHungerFragmentInteractionListener { // TODO: Update argument type and name void onLearnHungerFragmentInteraction(Uri uri); } }
ac5e882af92f98d0e961bbf8638e15b78dadd1d4
85327010e90693c41fc759eca0483163cfd2b2fc
/eclipse_code/Quanlikhobai/src/database/connect/Connector.java
ce49e5ebbc032a02e863d452997dfb3aed8e04f6
[]
no_license
cvhoangpt/20191_OOP
331bf1e3804bb56ce1e553c0275d82683d63071f
091b0d81c588e9d6d9f1eee99a28be79d4a4b30b
refs/heads/master
2022-03-27T04:46:56.511820
2019-12-19T15:06:17
2019-12-19T15:06:17
219,410,641
0
0
null
null
null
null
UTF-8
Java
false
false
2,000
java
package database.connect; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import gui.form.Dialog; /** * Phương thức liên kết cơ sở dữ liệu thông qua Java Database Connectivity API. * Sử dụng cách khởi tạo Lazy initialization (đơn luồng) của mẫu thiết kế Singleton pattern. * @author hoangcv */ public class Connector { /** * Liên kết đến localhost qua JDBC */ private static String DB_URL = "jdbc:mysql://localhost:3306/oop20191?useLegacyDatetimeCode=false&serverTimezone=UTC"; /** * Tên người dùng (mặc định là root) */ private static String USERNAME = "root"; /** * Mật khẩu (bỏ trống) */ private static String PASSWORD = ""; /** * Đối tượng thuộc lớp Connection */ protected Connection conn; /** * Đối tượng thuộc lớp Connector */ private static Connector instance; /** * Hàm khởi tạo */ protected Connector() { try { Class.forName("com.mysql.cj.jdbc.Driver"); this.conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); //System.out.println("Connector notice: Connection successfully ..."); } catch (ClassNotFoundException e) { System.out.println(e); } catch (SQLException e) { System.err.print("Connector notice: Connection failed."); Dialog d = new Dialog(); d.databaseError(); e.printStackTrace(); System.exit(0); } } private Connection getConnection() { return conn; } /** * Phương thức "khởi tạo lười biếng" * @return instance * @throws SQLException */ public static Connector getInstance() throws SQLException { if (instance == null) { instance = new Connector(); } else if (instance.getConnection().isClosed()) { instance = new Connector(); } return instance; } }
8bed4954de4bcd8fff12e112363011f7847154d8
340a8c6c7a29311b49d0bef395513c38fb8dedbd
/library/src/main/java/com/qr/core/adapter/base/animation/SlideInBottomAnimation.java
138b3f8a3ffecee58174497f23e4839f1b60ca76
[]
no_license
qr973440230/QRTools
1b1ebcaaa9d8c7128d89cd3904f184c552aaf217
a68b07c1cc3137224077b4fd53cb47832068e0b3
refs/heads/master
2020-05-15T21:37:27.867214
2019-06-08T12:42:08
2019-06-08T12:42:08
182,502,735
2
0
null
null
null
null
UTF-8
Java
false
false
482
java
package com.qr.core.adapter.base.animation; import android.animation.Animator; import android.animation.ObjectAnimator; import android.view.View; /** * https://github.com/CymChad/BaseRecyclerViewAdapterHelper */ public class SlideInBottomAnimation implements BaseAnimation { @Override public Animator[] getAnimators(View view) { return new Animator[]{ ObjectAnimator.ofFloat(view, "translationY", view.getMeasuredHeight(), 0) }; } }
139071589f8a3b3b8aafe4a42df0ea65854a5b2b
8f0d508be866a9a5c515c1bbbc5bf85693ef3ffd
/java338/src/main/java/soupply/java338/type/ListAddPlayer.java
94cb6522ec87afb9bcdaa99d380d10eb97981c1b
[ "MIT" ]
permissive
hanbule/java
83e7e1e2725b48370b0151a2ac1ec222b5e99264
40fecf30625bdbdc71cce4c6e3222022c0387c6e
refs/heads/master
2021-09-21T22:43:25.890116
2018-09-02T09:28:23
2018-09-02T09:28:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,554
java
package soupply.java338.type; import java.util.*; import soupply.util.*; public class ListAddPlayer extends Type { // gamemode public static final int SURVIVAL = (int)0; public static final int CREATIVE = (int)1; public static final int ADVENTURE = (int)2; public static final int SPECTATOR = (int)3; public UUID uuid; public String name; public soupply.java338.type.Property[] properties; public int gamemode; public int latency; public boolean hasDisplayName; public String displayName; public ListAddPlayer() { this.uuid = new UUID(0, 0); } public ListAddPlayer(UUID uuid, String name, soupply.java338.type.Property[] properties, int gamemode, int latency, boolean hasDisplayName, String displayName) { this.uuid = uuid; this.name = name; this.properties = properties; this.gamemode = gamemode; this.latency = latency; this.hasDisplayName = hasDisplayName; this.displayName = displayName; } @Override public void encodeBody(Buffer _buffer) { _buffer.writeUUID(uuid); byte[] bfz = _buffer.convertString(name); _buffer.writeVaruint((int)bfz.length); _buffer.writeBytes(bfz); _buffer.writeVaruint((int)properties.length); for(soupply.java338.type.Property cjcvdlc:properties) { cjcvdlc.encodeBody(_buffer); } _buffer.writeVaruint(gamemode); _buffer.writeVaruint(latency); _buffer.writeBool(hasDisplayName); if(hasDisplayName==true) { byte[] zlcxe5bu = _buffer.convertString(displayName); _buffer.writeVaruint((int)zlcxe5bu.length); _buffer.writeBytes(zlcxe5bu); } } @Override public void decodeBody(Buffer _buffer) throws DecodeException { uuid = _buffer.readUUID(); final int bvbfz = _buffer.readVaruint(); name = _buffer.readString(bvbfz); final int bbbbcrzm = _buffer.readVaruint(); properties = new soupply.java338.type.Property[bbbbcrzm]; for(int cjcvdlc=0;cjcvdlc<properties.length;cjcvdlc++) { properties[cjcvdlc].decodeBody(_buffer); } gamemode = _buffer.readVaruint(); latency = _buffer.readVaruint(); hasDisplayName = _buffer.readBool(); if(hasDisplayName==true) { final int bvzlcxe5 = _buffer.readVaruint(); displayName = _buffer.readString(bvzlcxe5); } } }
6c90e72248f5bc31107ee106b31ae31ad06613e2
fe8cbad9d86f535095066eecd5ed52168c396712
/git 2kolok ps/9cas/9.ned/ServerObradaPartnera/src/poslovnaLogika/KontrolerPL.java
dc60623ed86eaa987f6e973f8235ce4e69aef490
[]
no_license
icarus94/ps_kolok2
2a85e9a69f1fdaf8cc9711456ba7f060f732e406
76c562940cf9b67b97e009bf7fa2c4887d6034b2
refs/heads/master
2021-01-25T06:25:37.913565
2017-06-07T00:15:13
2017-06-07T00:15:13
93,573,899
0
0
null
null
null
null
UTF-8
Java
false
false
3,231
java
/* * 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 poslovnaLogika; import dbbr.DBBroker; import domen.Mesto; import domen.PoslovniPartner; import domen.Proizvod; import domen.Racun; import domen.StavkaRacuna; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * * @author student */ public class KontrolerPL { List<Mesto> listaMesta; List<PoslovniPartner> listaPartnera; DBBroker dbbr; private static KontrolerPL instanca; public static KontrolerPL vratiInstancu() { if (instanca == null) { instanca = new KontrolerPL(); } return instanca; } private KontrolerPL() { listaMesta = new ArrayList<>(); listaPartnera = new ArrayList<>(); inicijalizujMesta(); dbbr = new DBBroker(); } private void inicijalizujMesta() { listaMesta.add(new Mesto(11000, "Beograd")); listaMesta.add(new Mesto(11070, "Novi Beograd")); listaMesta.add(new Mesto(11010, "Vozdovac")); listaMesta.add(new Mesto(35230, "Cuprija")); listaMesta.add(new Mesto(11250, "Zeleznik")); } public List<Mesto> vratiSvaMesta() throws Exception { //return listaMesta; dbbr.uspostaviKonekciju(); return dbbr.vratiSvaMesta(); } public List<PoslovniPartner> vratiSvePartnere() throws Exception { //return listaMesta; dbbr.uspostaviKonekciju(); return dbbr.vratiSvePartnere(); } public List<Proizvod> vratiSveProizvode() throws Exception { //return listaMesta; dbbr.uspostaviKonekciju(); return dbbr.vratiSveProizvode(); } public void sacuvajRacun(Racun r) throws Exception{ try { dbbr.uspostaviKonekciju(); dbbr.sacuvajRacun(r); for(StavkaRacuna stavka:r.getStavke()){ dbbr.sacuvajStavku(stavka); } dbbr.potvrdiTransakciju(); } catch (SQLException sqle) { dbbr.ponistiTransakciju(); } } public void sacuvajPartnera(PoslovniPartner partner) throws Exception { //listaPartnera.add(partner); try { dbbr.uspostaviKonekciju(); dbbr.sacuvajPartnera(partner); dbbr.potvrdiTransakciju(); } catch (SQLException sqle) { dbbr.ponistiTransakciju(); } } public void sacuvajListuPartnera(List<PoslovniPartner> partneri) throws Exception { //listaPartnera.add(partner); try { dbbr.uspostaviKonekciju(); for (PoslovniPartner partner : partneri) { dbbr.sacuvajPartnera(partner); } dbbr.potvrdiTransakciju(); } catch (SQLException sqle) { sqle.printStackTrace(); dbbr.ponistiTransakciju(); throw sqle; } } // public List<PoslovniPartner> vratiSvePartnere() { // return listaPartnera; // } }
1c6793ccbc1a32249792b5a08e5a6e0730ec352e
bbc28a7faeb1d5fa91e7c37783a68fb9ae991840
/todo-jpa/src/test/java/com/sha/todojpa/TodoJpaApplicationTests.java
dcc85507020f83aca609d621b6d594bfdfd83d67
[]
no_license
shajahanp0005/springboot
30fd366ea1c136c57a1ad4cdeb4633948b29b152
02d757870796e2bfec9c69be6af37b6231d182cb
refs/heads/master
2022-11-17T16:52:22.722628
2020-07-18T16:56:09
2020-07-18T16:56:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
217
java
package com.sha.todojpa; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class TodoJpaApplicationTests { @Test void contextLoads() { } }
208cffc335169a3065c12b6c2d182c3f85f03846
57bc8fd390dbbe42f85d7ae3f30600887064ef29
/src/main/java/com/therealdanvega/config/LoggingConfiguration.java
b89257f797323c060e9d728cc97c2794181d2f24
[]
no_license
susimsek/jhipster-jblog
e58f0a53f0eb4a91488cc9c706a7a45d9974289d
54bcf073c57faa3363dc5f96eaadae1f85b34971
refs/heads/master
2022-12-21T15:39:13.863022
2019-06-02T14:57:18
2019-06-02T14:57:18
189,844,255
1
0
null
2022-12-16T04:52:37
2019-06-02T12:34:23
Java
UTF-8
Java
false
false
12,505
java
package com.therealdanvega.config; import java.net.InetSocketAddress; import java.util.Iterator; import io.github.jhipster.config.JHipsterProperties; import ch.qos.logback.classic.AsyncAppender; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.boolex.OnMarkerEvaluator; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.LoggerContextListener; import ch.qos.logback.core.Appender; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.filter.EvaluatorFilter; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.spi.FilterReply; import net.logstash.logback.appender.LogstashTcpSocketAppender; import net.logstash.logback.composite.ContextJsonProvider; import net.logstash.logback.composite.GlobalCustomFieldsJsonProvider; import net.logstash.logback.composite.loggingevent.ArgumentsJsonProvider; import net.logstash.logback.composite.loggingevent.LogLevelJsonProvider; import net.logstash.logback.composite.loggingevent.LoggerNameJsonProvider; import net.logstash.logback.composite.loggingevent.LoggingEventFormattedTimestampJsonProvider; import net.logstash.logback.composite.loggingevent.LoggingEventJsonProviders; import net.logstash.logback.composite.loggingevent.LoggingEventPatternJsonProvider; import net.logstash.logback.composite.loggingevent.MdcJsonProvider; import net.logstash.logback.composite.loggingevent.MessageJsonProvider; import net.logstash.logback.composite.loggingevent.StackTraceJsonProvider; import net.logstash.logback.composite.loggingevent.ThreadNameJsonProvider; import net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder; import net.logstash.logback.encoder.LogstashEncoder; import net.logstash.logback.stacktrace.ShortenedThrowableConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; @Configuration public class LoggingConfiguration { private static final String CONSOLE_APPENDER_NAME = "CONSOLE"; private static final String LOGSTASH_APPENDER_NAME = "LOGSTASH"; private static final String ASYNC_LOGSTASH_APPENDER_NAME = "ASYNC_LOGSTASH"; private final Logger log = LoggerFactory.getLogger(LoggingConfiguration.class); private LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); private final String appName; private final String serverPort; private final JHipsterProperties jHipsterProperties; public LoggingConfiguration(@Value("${spring.application.name}") String appName, @Value("${server.port}") String serverPort, JHipsterProperties jHipsterProperties) { this.appName = appName; this.serverPort = serverPort; this.jHipsterProperties = jHipsterProperties; if (this.jHipsterProperties.getLogging().isUseJsonFormat()) { addJsonConsoleAppender(context); } if (this.jHipsterProperties.getLogging().getLogstash().isEnabled()) { addLogstashTcpSocketAppender(context); } if (this.jHipsterProperties.getLogging().isUseJsonFormat() || this.jHipsterProperties.getLogging().getLogstash().isEnabled()) { addContextListener(context); } if (this.jHipsterProperties.getMetrics().getLogs().isEnabled()) { setMetricsMarkerLogbackFilter(context); } } private void addJsonConsoleAppender(LoggerContext context) { log.info("Initializing Console logging"); // More documentation is available at: https://github.com/logstash/logstash-logback-encoder ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>(); consoleAppender.setContext(context); consoleAppender.setEncoder(compositeJsonEncoder(context)); consoleAppender.setName(CONSOLE_APPENDER_NAME); consoleAppender.start(); context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).detachAppender(CONSOLE_APPENDER_NAME); context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).addAppender(consoleAppender); } private void addLogstashTcpSocketAppender(LoggerContext context) { log.info("Initializing Logstash logging"); // More documentation is available at: https://github.com/logstash/logstash-logback-encoder LogstashTcpSocketAppender logstashAppender = new LogstashTcpSocketAppender(); logstashAppender.addDestinations(new InetSocketAddress(this.jHipsterProperties.getLogging().getLogstash().getHost(), this.jHipsterProperties.getLogging().getLogstash().getPort())); logstashAppender.setContext(context); logstashAppender.setEncoder(logstashEncoder()); logstashAppender.setName(LOGSTASH_APPENDER_NAME); logstashAppender.start(); // Wrap the appender in an Async appender for performance AsyncAppender asyncLogstashAppender = new AsyncAppender(); asyncLogstashAppender.setContext(context); asyncLogstashAppender.setName(ASYNC_LOGSTASH_APPENDER_NAME); asyncLogstashAppender.setQueueSize(this.jHipsterProperties.getLogging().getLogstash().getQueueSize()); asyncLogstashAppender.addAppender(logstashAppender); asyncLogstashAppender.start(); context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).addAppender(asyncLogstashAppender); } private LoggingEventCompositeJsonEncoder compositeJsonEncoder(LoggerContext context) { final LoggingEventCompositeJsonEncoder compositeJsonEncoder = new LoggingEventCompositeJsonEncoder(); compositeJsonEncoder.setContext(context); compositeJsonEncoder.setProviders(jsonProviders(context)); compositeJsonEncoder.start(); return compositeJsonEncoder; } private LogstashEncoder logstashEncoder() { final LogstashEncoder logstashEncoder = new LogstashEncoder(); logstashEncoder.setThrowableConverter(throwableConverter()); logstashEncoder.setCustomFields(customFields()); return logstashEncoder; } private LoggingEventJsonProviders jsonProviders(LoggerContext context) { final LoggingEventJsonProviders jsonProviders = new LoggingEventJsonProviders(); jsonProviders.addArguments(new ArgumentsJsonProvider()); jsonProviders.addContext(new ContextJsonProvider<>()); jsonProviders.addGlobalCustomFields(customFieldsJsonProvider()); jsonProviders.addLogLevel(new LogLevelJsonProvider()); jsonProviders.addLoggerName(loggerNameJsonProvider()); jsonProviders.addMdc(new MdcJsonProvider()); jsonProviders.addMessage(new MessageJsonProvider()); jsonProviders.addPattern(new LoggingEventPatternJsonProvider()); jsonProviders.addStackTrace(stackTraceJsonProvider()); jsonProviders.addThreadName(new ThreadNameJsonProvider()); jsonProviders.addTimestamp(timestampJsonProvider()); jsonProviders.setContext(context); return jsonProviders; } private GlobalCustomFieldsJsonProvider<ILoggingEvent> customFieldsJsonProvider() { final GlobalCustomFieldsJsonProvider<ILoggingEvent> customFieldsJsonProvider = new GlobalCustomFieldsJsonProvider<>(); customFieldsJsonProvider.setCustomFields(customFields()); return customFieldsJsonProvider; } private String customFields () { StringBuilder customFields = new StringBuilder(); customFields.append("{"); customFields.append("\"app_name\":\"").append(this.appName).append("\""); customFields.append(",").append("\"app_port\":\"").append(this.serverPort).append("\""); customFields.append("}"); return customFields.toString(); } private LoggerNameJsonProvider loggerNameJsonProvider() { final LoggerNameJsonProvider loggerNameJsonProvider = new LoggerNameJsonProvider(); loggerNameJsonProvider.setShortenedLoggerNameLength(20); return loggerNameJsonProvider; } private StackTraceJsonProvider stackTraceJsonProvider() { StackTraceJsonProvider stackTraceJsonProvider = new StackTraceJsonProvider(); stackTraceJsonProvider.setThrowableConverter(throwableConverter()); return stackTraceJsonProvider; } private ShortenedThrowableConverter throwableConverter() { final ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter(); throwableConverter.setRootCauseFirst(true); return throwableConverter; } private LoggingEventFormattedTimestampJsonProvider timestampJsonProvider() { final LoggingEventFormattedTimestampJsonProvider timestampJsonProvider = new LoggingEventFormattedTimestampJsonProvider(); timestampJsonProvider.setTimeZone("UTC"); timestampJsonProvider.setFieldName("timestamp"); return timestampJsonProvider; } private void addContextListener(LoggerContext context) { LogbackLoggerContextListener loggerContextListener = new LogbackLoggerContextListener(this.jHipsterProperties); loggerContextListener.setContext(context); context.addListener(loggerContextListener); } // Configure a log filter to remove "metrics" logs from all appenders except the "LOGSTASH" appender private void setMetricsMarkerLogbackFilter(LoggerContext context) { log.info("Filtering metrics logs from all appenders except the {} appender", LOGSTASH_APPENDER_NAME); OnMarkerEvaluator onMarkerMetricsEvaluator = new OnMarkerEvaluator(); onMarkerMetricsEvaluator.setContext(context); onMarkerMetricsEvaluator.addMarker("metrics"); onMarkerMetricsEvaluator.start(); EvaluatorFilter<ILoggingEvent> metricsFilter = new EvaluatorFilter<>(); metricsFilter.setContext(context); metricsFilter.setEvaluator(onMarkerMetricsEvaluator); metricsFilter.setOnMatch(FilterReply.DENY); metricsFilter.start(); context.getLoggerList().forEach((logger) -> { for (Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); it.hasNext();) { Appender<ILoggingEvent> appender = it.next(); if (!appender.getName().equals(ASYNC_LOGSTASH_APPENDER_NAME) && !(appender.getName().equals(CONSOLE_APPENDER_NAME) && this.jHipsterProperties.getLogging().isUseJsonFormat())) { log.debug("Filter metrics logs from the {} appender", appender.getName()); appender.setContext(context); appender.addFilter(metricsFilter); appender.start(); } } }); } /** * Logback configuration is achieved by configuration file and API. * When configuration file change is detected, the configuration is reset. * This listener ensures that the programmatic configuration is also re-applied after reset. */ class LogbackLoggerContextListener extends ContextAwareBase implements LoggerContextListener { private final JHipsterProperties jHipsterProperties; private LogbackLoggerContextListener(JHipsterProperties jHipsterProperties) { this.jHipsterProperties = jHipsterProperties; } @Override public boolean isResetResistant() { return true; } @Override public void onStart(LoggerContext context) { if (this.jHipsterProperties.getLogging().isUseJsonFormat()) { addJsonConsoleAppender(context); } if (this.jHipsterProperties.getLogging().getLogstash().isEnabled()) { addLogstashTcpSocketAppender(context); } } @Override public void onReset(LoggerContext context) { if (this.jHipsterProperties.getLogging().isUseJsonFormat()) { addJsonConsoleAppender(context); } if (this.jHipsterProperties.getLogging().getLogstash().isEnabled()) { addLogstashTcpSocketAppender(context); } } @Override public void onStop(LoggerContext context) { // Nothing to do. } @Override public void onLevelChange(ch.qos.logback.classic.Logger logger, Level level) { // Nothing to do. } } }
61ba719d99d1eef067fb5055704e7949624d5137
ae5eb1a38b4d22c82dfd67c86db73592094edc4b
/project346/src/main/java/org/gradle/test/performance/largejavamultiproject/project346/p1732/Production34654.java
81daf64fb75221fc47b7fd694a8b121fc2317836
[]
no_license
big-guy/largeJavaMultiProject
405cc7f55301e1fd87cee5878a165ec5d4a071aa
1cd6a3f9c59e9b13dffa35ad27d911114f253c33
refs/heads/main
2023-03-17T10:59:53.226128
2021-03-04T01:01:39
2021-03-04T01:01:39
344,307,977
0
0
null
null
null
null
UTF-8
Java
false
false
1,890
java
package org.gradle.test.performance.largejavamultiproject.project346.p1732; public class Production34654 { private String property0; public String getProperty0() { return property0; } public void setProperty0(String value) { property0 = value; } private String property1; public String getProperty1() { return property1; } public void setProperty1(String value) { property1 = value; } private String property2; public String getProperty2() { return property2; } public void setProperty2(String value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
647d1bed2ba32e79869630cca8c42a5e6b21e6be
4ece14d7262535e9fd502189342f0d9f5e8bc2c1
/src/main/java/com/liferon/polls/security/JwtAuthenticationFilter.java
ff0be7e9a5c795a96b14565644392903cef22dce
[]
no_license
olantobi/polling_app
30668be8f28ed1a8401db82c710fb2d3073b8d2f
11ed9b2b1935168babc54c6ccab56e094e11444b
refs/heads/master
2020-04-14T15:43:55.626981
2019-01-03T07:26:12
2019-01-03T07:26:12
163,935,932
0
0
null
null
null
null
UTF-8
Java
false
false
2,299
java
package com.liferon.polls.security; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Slf4j public class JwtAuthenticationFilter extends OncePerRequestFilter { @Autowired private JwtTokenProvider tokenProvider; @Autowired private CustomUserDetailsService customUserDetailsService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String jwt = getJwtFromRequest(request); if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) { Long userId = tokenProvider.getUserIdFromJwt(jwt); UserDetails userDetails = customUserDetailsService.loaduserById(userId); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception ex) { log.error("Could not set authentication in security context", ex); } filterChain.doFilter(request, response); } private String getJwtFromRequest(HttpServletRequest request) { String bearerToken = request.getHeader("Authorization"); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { return bearerToken.split(" ")[1]; } return null; } }
793798d2b49af0a4d1d8620049f7899af62ad33a
b9ec265cabe1f7a869b96471cfe0e1b75818d467
/src/main/java/org/docksidestage/hangar/dbflute/exentity/WhiteOnParadeRef.java
3aefbc3826d25848256462170a3d83efb408f881
[ "Apache-2.0" ]
permissive
shin-kinoshita/dbflute-test-active-hangar
0135e84c5f2055008c95e0c3d1523b08526f6d71
130c8cb76f4023de691c423f8d576c497e8fccd3
refs/heads/master
2020-04-17T01:13:59.120804
2019-01-31T14:54:14
2019-01-31T14:54:14
166,082,680
0
0
Apache-2.0
2019-01-23T15:35:25
2019-01-16T17:34:38
Java
UTF-8
Java
false
false
493
java
package org.docksidestage.hangar.dbflute.exentity; import org.docksidestage.hangar.dbflute.bsentity.BsWhiteOnParadeRef; /** * The entity of WHITE_ON_PARADE_REF. * <p> * You can implement your original methods here. * This class remains when re-generating. * </p> * @author DBFlute(AutoGenerator) */ public class WhiteOnParadeRef extends BsWhiteOnParadeRef { /** The serial version UID for object serialization. (Default) */ private static final long serialVersionUID = 1L; }
64ae88383afccb89c525ea294afa2a80c51a4fa9
2c773c73d445d6732b7948aef8909c8028c94767
/Triangle.java
ec87e31b0f6a2ddf0a4ead799dd4604b6a558daf
[]
no_license
smsali97/Stuffies
c5eaa8421a42904bd20f2e626de9a3376d4246de
d286b602028331539abfe4576a3a59c358ef3fd9
refs/heads/master
2021-01-21T20:42:32.341602
2017-05-24T09:11:35
2017-05-24T09:11:35
92,269,482
0
0
null
null
null
null
UTF-8
Java
false
false
977
java
public class Triangle { private Point v1; private Point v2; private Point v3; // param. constructor public Triangle(Point p1, Point p2, Point p3) { v1 = p1; v2 = p2; v3 = p3; } @Override public String toString() { // "MyTriangle[v1=(x1,y1),v2=(x2,y2),v3=(x3,y3)]" String str = String.format("MyTriangle[v1=(%d,%d),v2=(%d,%d),v3=(%d,%d)]",v1.getX(),v1.getY(),v2.getX(),v2.getX(),v3.getX(),v3.getY()); return str; } // perimeter = sum of 3 sides public double getPerimeter() { return v1.distance(v2) + v2.distance(v3) + v3.distance(v1); } // equilateral all three sides equal, isoceles two sides, scalene one side public String getType(){ double side1 = v1.distance(v2); double side2 = v2.distance(v3); double side3 = v3.distance(v1); if ( side1 == side2 && side2 == side3) { return "Equilateral"; } else if ( side1 == side2 || side2 == side3 || side3 == side1) { return "Isosceles"; } else return "Scalene"; } }
[ "Muhammad Sualeh Ali" ]
Muhammad Sualeh Ali
6310bacb6897f9b6fcaaaeac37d6de17d27d27e4
7127f7ea1d1507ac2b1cda5f6d9c1a89cca655e3
/plugin/idea/src/com/perl5/lang/perl/idea/configuration/module/PerlModuleBuilderBase.java
356688c5b254a989a10155c4bc1c97446344f201
[ "Apache-2.0" ]
permissive
jonas-lindmark/Perl5-IDEA
9818c4aad93b63d4fba65a8179ef7a0a0a373024
13d36e01e768ba06e9988b0fade7cad054ad6d56
refs/heads/master
2021-07-04T22:06:24.284136
2021-02-05T13:55:56
2021-02-05T13:55:56
238,300,397
0
0
NOASSERTION
2020-02-04T20:33:26
2020-02-04T20:33:26
null
UTF-8
Java
false
false
3,598
java
/* * Copyright 2015-2020 Alexandr Evstigneev * * 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.perl5.lang.perl.idea.configuration.module; import com.intellij.ide.util.projectWizard.ModuleBuilder; import com.intellij.ide.util.projectWizard.ModuleWizardStep; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.projectRoots.SdkTypeId; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import com.intellij.openapi.util.AtomicNotNullLazyValue; import com.perl5.lang.perl.idea.modules.PerlModuleType; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import javax.swing.*; public abstract class PerlModuleBuilderBase<Settings extends PerlProjectGenerationSettings> extends ModuleBuilder { private final @NotNull AtomicNotNullLazyValue<PerlProjectGeneratorPeerBase<Settings>> myPeerProvider = AtomicNotNullLazyValue.createValue(() -> getGenerator().createPeer()); public final @NotNull PerlProjectGeneratorPeerBase<Settings> getPeer() { return myPeerProvider.getValue(); } public final @NotNull Settings getSettings() { return getPeer().getSettings(); } @Override public final Icon getNodeIcon() { return getGenerator().getLogo(); } @Override public final @Nls(capitalization = Nls.Capitalization.Title) String getPresentableName() { return getGenerator().getName(); } /** * @return generator paired with this builder. All work is delegated to the generator and it's peer. This builder is just a wrapper * fixme this should just seek for existing generator, but seem they gonna be disabled for now */ protected abstract @NotNull PerlProjectGeneratorBase<Settings> getGenerator(); @Override public ModuleType<?> getModuleType() { return PerlModuleType.getInstance(); } @Override public final boolean isSuitableSdkType(SdkTypeId sdkType) { return false; } @SuppressWarnings("RedundantThrows") @Override public final void setupRootModel(@NotNull ModifiableRootModel modifiableRootModel) throws ConfigurationException { doAddContentEntry(modifiableRootModel); } @Override protected final void setProjectType(Module module) { getGenerator().configureModule(module, getSettings()); } @Override public final ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext, @NotNull ModulesProvider modulesProvider) { if (!isStepAvailable(wizardContext, modulesProvider)) { return ModuleWizardStep.EMPTY_ARRAY; } getSettings().setProject(wizardContext.getProject()); return new ModuleWizardStep[]{new PerlDelegatingModuleWizardStep(getPeer())}; } /** * @return true iff we should add a peer-based step */ protected boolean isStepAvailable(@NotNull WizardContext wizardContext, @NotNull ModulesProvider modulesProvider) { return true; } }
0ffb8a3de5be02ecd6c1d4f622bc80812bd444de
51474b5580a50dd680b3485ebe7142b933bc2bce
/app/src/main/java/com/amindset/ve/amindset/TextChat/Data.java
88636c4326b74168581522e6769e7462a444f142
[]
no_license
LangMike/Android
2ffccbef0f8466cf9eab07b97d1a435f884e98f8
6bc8da4b7e3e3b4116553fa0980c669aacc686c4
refs/heads/master
2020-09-23T01:07:14.853043
2019-12-02T12:51:42
2019-12-02T12:51:42
225,362,118
0
0
null
null
null
null
UTF-8
Java
false
false
367
java
package com.amindset.ve.amindset.TextChat; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Data { @SerializedName("token") @Expose private String token; public String getToken() { return token; } public void setToken(String token) { this.token = token; } }