blob_id stringlengths 40 40 | __id__ int64 225 39,780B | directory_id stringlengths 40 40 | path stringlengths 6 313 | content_id stringlengths 40 40 | detected_licenses list | license_type stringclasses 2
values | repo_name stringlengths 6 132 | repo_url stringlengths 25 151 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 70 | visit_date timestamp[ns] | revision_date timestamp[ns] | committer_date timestamp[ns] | github_id int64 7.28k 689M ⌀ | star_events_count int64 0 131k | fork_events_count int64 0 48k | gha_license_id stringclasses 23
values | gha_fork bool 2
classes | gha_event_created_at timestamp[ns] | gha_created_at timestamp[ns] | gha_updated_at timestamp[ns] | gha_pushed_at timestamp[ns] | gha_size int64 0 40.4M ⌀ | gha_stargazers_count int32 0 112k ⌀ | gha_forks_count int32 0 39.4k ⌀ | gha_open_issues_count int32 0 11k ⌀ | gha_language stringlengths 1 21 ⌀ | gha_archived bool 2
classes | gha_disabled bool 1
class | content stringlengths 7 4.37M | src_encoding stringlengths 3 16 | language stringclasses 1
value | length_bytes int64 7 4.37M | extension stringclasses 24
values | filename stringlengths 4 174 | language_id stringclasses 1
value | entities list | contaminating_dataset stringclasses 0
values | malware_signatures list | redacted_content stringlengths 7 4.37M | redacted_length_bytes int64 7 4.37M | alphanum_fraction float32 0.25 0.94 | alpha_fraction float32 0.25 0.94 | num_lines int32 1 84k | avg_line_length float32 0.76 99.9 | std_line_length float32 0 220 | max_line_length int32 5 998 | is_vendor bool 2
classes | is_generated bool 1
class | max_hex_length int32 0 319 | hex_fraction float32 0 0.38 | max_unicode_length int32 0 408 | unicode_fraction float32 0 0.36 | max_base64_length int32 0 506 | base64_fraction float32 0 0.5 | avg_csv_sep_count float32 0 4 | is_autogen_header bool 1
class | is_empty_html bool 1
class | shard stringclasses 16
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
82e4d0eb9039da8a844f542f4899c27220a48aee | 6,322,191,922,817 | 8a6ee57a638d05de15517d95b0fd946b1dbaa0f9 | /src/main/java/com/esoft/jdp2p/invest/service/impl/InvestCalculatorImpl.java | bf9ef50100cb4898dd4441a937e3559d060f9bd1 | [] | no_license | shi0288/guoshang | https://github.com/shi0288/guoshang | 46607a74fa8a7cb1547114deb755d98b7cfd9bca | af97e3d05e623049dfa9c3155a492e3655684264 | refs/heads/master | 2020-02-29T20:09:42.831000 | 2016-04-07T09:03:28 | 2016-04-07T09:03:28 | 48,344,864 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.esoft.jdp2p.invest.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.esoft.jdp2p.invest.service.InvestCalculator;
import com.esoft.jdp2p.repay.service.RepayCalculator;
@Service("investCalculator")
public class InvestCalculatorImpl implements InvestCalculator {
@Resource
RepayCalculator repayCalculator;
@Override
public Double calculateAnticipatedInterest(double investMoney, String loanId) {
return repayCalculator
.calculateAnticipatedInterest(investMoney, loanId);
}
}
| UTF-8 | Java | 559 | java | InvestCalculatorImpl.java | Java | [] | null | [] | package com.esoft.jdp2p.invest.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.esoft.jdp2p.invest.service.InvestCalculator;
import com.esoft.jdp2p.repay.service.RepayCalculator;
@Service("investCalculator")
public class InvestCalculatorImpl implements InvestCalculator {
@Resource
RepayCalculator repayCalculator;
@Override
public Double calculateAnticipatedInterest(double investMoney, String loanId) {
return repayCalculator
.calculateAnticipatedInterest(investMoney, loanId);
}
}
| 559 | 0.826476 | 0.821109 | 22 | 24.40909 | 25.149839 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.909091 | false | false | 10 |
00d6be34206e4fa0c13c798359da994cfcc5ba92 | 26,980,984,615,455 | 5fca869392dce659ca7545c81f303771b0a80499 | /src/main/java/com/springrest/springrest/services/EmployeeServiceImpl.java | f1b106e339873b52cb5335261bafb250e3bedfc3 | [] | no_license | akshat31/spring-boot-rest-api | https://github.com/akshat31/spring-boot-rest-api | d24a9134c2cbd99d4f488e9b5530458c3daf7edb | 0b84fffbd21f2fc62286a4b5436d2551c6b02adf | refs/heads/master | 2022-11-21T23:43:32.450000 | 2020-07-29T07:08:39 | 2020-07-29T07:08:39 | 283,424,894 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.springrest.springrest.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.springrest.springrest.entities.Employee;
@Service("employee")
public class EmployeeServiceImpl implements EmployeeService {
List<Employee> empl;
public EmployeeServiceImpl() {
empl = new ArrayList<>();
empl.add(new Employee(001, "akshat soni", "FrontEnd"));
empl.add(new Employee(002, "swagtika mohapatra", "BackEnd"));
empl.add(new Employee(003, "pritam kumar", "DevOps"));
empl.add(new Employee(004, "athif alam", "DataBase"));
}
@Override
public List<Employee> getEmployee() {
// TODO Auto-generated method stub
return empl;
}
@Override
public Employee getEmploye(long employeeId) {
Employee e = null;
for (Employee oneEmpl: empl) {
if (oneEmpl.getId() == employeeId) {
e = oneEmpl;
break;
}
}
return e;
}
@Override
public Employee addEmployee(Employee addempl) {
empl.add(addempl);
return addempl;
}
}
| UTF-8 | Java | 1,028 | java | EmployeeServiceImpl.java | Java | [
{
"context": " new ArrayList<>();\n\t\templ.add(new Employee(001, \"akshat soni\", \"FrontEnd\"));\n\t\templ.add(new Employee(002, \"swa",
"end": 407,
"score": 0.9998539686203003,
"start": 396,
"tag": "NAME",
"value": "akshat soni"
},
{
"context": "oni\", \"FrontEnd\"));\n\t\templ.ad... | null | [] | package com.springrest.springrest.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.springrest.springrest.entities.Employee;
@Service("employee")
public class EmployeeServiceImpl implements EmployeeService {
List<Employee> empl;
public EmployeeServiceImpl() {
empl = new ArrayList<>();
empl.add(new Employee(001, "<NAME>", "FrontEnd"));
empl.add(new Employee(002, "<NAME>", "BackEnd"));
empl.add(new Employee(003, "<NAME>", "DevOps"));
empl.add(new Employee(004, "<NAME>", "DataBase"));
}
@Override
public List<Employee> getEmployee() {
// TODO Auto-generated method stub
return empl;
}
@Override
public Employee getEmploye(long employeeId) {
Employee e = null;
for (Employee oneEmpl: empl) {
if (oneEmpl.getId() == employeeId) {
e = oneEmpl;
break;
}
}
return e;
}
@Override
public Employee addEmployee(Employee addempl) {
empl.add(addempl);
return addempl;
}
}
| 1,001 | 0.706226 | 0.694553 | 49 | 19.979591 | 20.091108 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.693878 | false | false | 10 |
3cc84811243658437f856c483a535ad17603e934 | 28,406,913,702,249 | fada4f8c65328edcf8ce34b3c3edbd1a4fe83812 | /core/src/main/java/com/imaibo/portfolio/repository/rdb/StockRepository.java | 18abe03de053c311bac7148b04a56bd16b647f5f | [] | no_license | AngusZhu/invest-portfolio | https://github.com/AngusZhu/invest-portfolio | 60758754e229f055321eb33f4dd7a793829c5d3a | c4f56f9c71c89164e3a0c2a91c9859427b2f62ac | refs/heads/master | 2016-09-01T11:45:47.508000 | 2015-10-17T06:03:43 | 2015-10-17T06:03:43 | 44,425,955 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.imaibo.portfolio.repository.rdb;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import com.imaibo.portfolio.domain.rdb.Stock;
import com.imaibo.portfolio.domain.rdb.User;
import com.imaibo.portfolio.domain.rdb.projection.StockIndustryProjection;
@RepositoryRestResource(excerptProjection = StockIndustryProjection.class)
public interface StockRepository extends JpaRepository<Stock, Long>{
//@Query("select s from Stock s where s.stockIndustry.id = :id")
//List<Stock> findTop10ByStockIndustry(@Param("id") Long id, Pageable pageable);
@Query("select s from Stock s where s.stockCode = :stockCode")
List<Stock> findByStockCode(@Param("stockCode") String stockCode);
@Query("select s from Stock s where s.stockName = :stockName")
List<Stock> findByStockName(@Param("stockName") String stockName);
List<Stock> findTop10ByOrderByBetaDesc();
// @Query("select s from Stock s order by beta Desc")
// List<Stock> findAllByOrderByBetaDesc();
List<Stock> findTop10ByOrderBySentimentDesc();
Page<Stock> findByStockCodeContaining(@Param("stockCode") String stockCode, Pageable pageable);
Page<Stock> findByStockNameContaining(@Param("stockName") String stockName, Pageable pageable);
@Query("select s from Stock s where s.stockCode like %:stockValue% or s.stockName like %:stockValue% or s.chinesePhonetic like %:stockValue%")
List<Stock> findTop10ByStockCodeOrStockNameOrChinesePhonetic(@Param("stockValue") String stockValue);
Page<Stock> findByUsers(@Param("user") User user, Pageable pageable);
List<Stock> findByStockCodeLikeOrStockNameLikeOrChinesePhoneticLike(@Param("stockCode") String stockCode,@Param("stockName") String stockName,@Param("chinesePhonetic") String chinesePhonetic);
List<Stock> findTop10ByStockCodeContainsOrStockNameContainsOrChinesePhoneticContains(@Param("stockCode") String stockCode,@Param("stockName") String stockName,@Param("chinesePhonetic") String chinesePhonetic);
//Page<Lot> findByLotNoLike(@Param("lotNo") String lotNo, Pageable pageable);
}
| UTF-8 | Java | 2,353 | java | StockRepository.java | Java | [] | null | [] | package com.imaibo.portfolio.repository.rdb;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import com.imaibo.portfolio.domain.rdb.Stock;
import com.imaibo.portfolio.domain.rdb.User;
import com.imaibo.portfolio.domain.rdb.projection.StockIndustryProjection;
@RepositoryRestResource(excerptProjection = StockIndustryProjection.class)
public interface StockRepository extends JpaRepository<Stock, Long>{
//@Query("select s from Stock s where s.stockIndustry.id = :id")
//List<Stock> findTop10ByStockIndustry(@Param("id") Long id, Pageable pageable);
@Query("select s from Stock s where s.stockCode = :stockCode")
List<Stock> findByStockCode(@Param("stockCode") String stockCode);
@Query("select s from Stock s where s.stockName = :stockName")
List<Stock> findByStockName(@Param("stockName") String stockName);
List<Stock> findTop10ByOrderByBetaDesc();
// @Query("select s from Stock s order by beta Desc")
// List<Stock> findAllByOrderByBetaDesc();
List<Stock> findTop10ByOrderBySentimentDesc();
Page<Stock> findByStockCodeContaining(@Param("stockCode") String stockCode, Pageable pageable);
Page<Stock> findByStockNameContaining(@Param("stockName") String stockName, Pageable pageable);
@Query("select s from Stock s where s.stockCode like %:stockValue% or s.stockName like %:stockValue% or s.chinesePhonetic like %:stockValue%")
List<Stock> findTop10ByStockCodeOrStockNameOrChinesePhonetic(@Param("stockValue") String stockValue);
Page<Stock> findByUsers(@Param("user") User user, Pageable pageable);
List<Stock> findByStockCodeLikeOrStockNameLikeOrChinesePhoneticLike(@Param("stockCode") String stockCode,@Param("stockName") String stockName,@Param("chinesePhonetic") String chinesePhonetic);
List<Stock> findTop10ByStockCodeContainsOrStockNameContainsOrChinesePhoneticContains(@Param("stockCode") String stockCode,@Param("stockName") String stockName,@Param("chinesePhonetic") String chinesePhonetic);
//Page<Lot> findByLotNoLike(@Param("lotNo") String lotNo, Pageable pageable);
}
| 2,353 | 0.798555 | 0.794305 | 50 | 46.060001 | 47.946808 | 211 | false | false | 0 | 0 | 0 | 0 | 72 | 0.030599 | 1.28 | false | false | 10 |
79c0ed2d7d66703396098469e29552d004c9c0c0 | 25,211,458,040,286 | aec7ddc4cf6fb01fc508fc7496588f232adac4ef | /app/src/main/java/redleon/net/comanda/dialogs/TableNumberDialogForDiner.java | c52b15a4c22788aa753e99626e866ffe8065c55e | [] | no_license | leonlipe/Comanda | https://github.com/leonlipe/Comanda | 46fa51272b767d0b2ae8527d77ff30a87a22adf1 | 399314fa48eb4b1087c97610df3d6919866c3635 | refs/heads/master | 2021-01-18T21:44:07.155000 | 2017-05-29T05:54:36 | 2017-05-29T05:54:36 | 34,548,611 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package redleon.net.comanda.dialogs;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.ListAdapter;
import android.widget.Toast;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.*;
import cz.msebera.android.httpclient.Header;
import org.json.JSONObject;
import java.util.ArrayList;
import redleon.net.comanda.R;
import redleon.net.comanda.activities.ServicesActivity;
import redleon.net.comanda.adapters.TableArrayAdapter;
import redleon.net.comanda.fragments.ComandasFragment;
import redleon.net.comanda.model.Table;
import redleon.net.comanda.network.HttpClient;
import redleon.net.comanda.utils.Network;
/**
* Created by leon on 05/01/16.
*/
public class TableNumberDialogForDiner extends DialogFragment implements DialogInterface.OnClickListener {
private Integer origin;
private ArrayList<Table> items;
private ComandasFragment comandasFragment;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//setmSelectedItems(new ArrayList<Extra>()); // Where we track the selected items
final Context ctx = getActivity().getBaseContext();
ListAdapter adapter = new TableArrayAdapter(getActivity().getApplicationContext(),getItems());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
builder.setTitle(R.string.dialog_set_table)
.setAdapter(adapter,new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int item) {
Table checkedItem = getItems().get(item);
RequestParams params = Network.makeAuthParams(ctx);
params.put("table_id", checkedItem.getId());
HttpClient.post("/reassigndiner/" + origin, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// Pull out the first event on the public timeline
try {
String sResponse = response.getString("status");
if (sResponse.equals("ok")) {
} else {
Toast.makeText(ctx, response.getString("reason"), Toast.LENGTH_SHORT).show();
return;
}
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(ctx, "La persona se reasigno correctamente.", Toast.LENGTH_SHORT).show();
//refresh activity
ServicesActivity servicesActivity = (ServicesActivity) comandasFragment.getActivity();
servicesActivity.updateForPersonChange();
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject jsonObject) {
Toast.makeText(ctx, "Ocurrio un error inesperado:" + throwable.getMessage(), Toast.LENGTH_LONG).show();
}
}, ctx);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
@Override
public void onClick(DialogInterface dialog, int which) {
}
public ArrayList<Table> getItems() {
return items;
}
public void setItems(ArrayList<Table> items) {
this.items = items;
}
public Integer getOrigin() {
return origin;
}
public void setOrigin(Integer origin) {
this.origin = origin;
}
public ComandasFragment getComandasFragment() {
return comandasFragment;
}
public void setComandasFragment(ComandasFragment comandasFragment) {
this.comandasFragment = comandasFragment;
}
} | UTF-8 | Java | 4,681 | java | TableNumberDialogForDiner.java | Java | [
{
"context": "leon.net.comanda.utils.Network;\n\n/**\n * Created by leon on 05/01/16.\n */\npublic class TableNumberDialog",
"end": 888,
"score": 0.5130086541175842,
"start": 886,
"tag": "NAME",
"value": "le"
},
{
"context": "n.net.comanda.utils.Network;\n\n/**\n * Created by leon on... | null | [] | package redleon.net.comanda.dialogs;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.ListAdapter;
import android.widget.Toast;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.*;
import cz.msebera.android.httpclient.Header;
import org.json.JSONObject;
import java.util.ArrayList;
import redleon.net.comanda.R;
import redleon.net.comanda.activities.ServicesActivity;
import redleon.net.comanda.adapters.TableArrayAdapter;
import redleon.net.comanda.fragments.ComandasFragment;
import redleon.net.comanda.model.Table;
import redleon.net.comanda.network.HttpClient;
import redleon.net.comanda.utils.Network;
/**
* Created by leon on 05/01/16.
*/
public class TableNumberDialogForDiner extends DialogFragment implements DialogInterface.OnClickListener {
private Integer origin;
private ArrayList<Table> items;
private ComandasFragment comandasFragment;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//setmSelectedItems(new ArrayList<Extra>()); // Where we track the selected items
final Context ctx = getActivity().getBaseContext();
ListAdapter adapter = new TableArrayAdapter(getActivity().getApplicationContext(),getItems());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
builder.setTitle(R.string.dialog_set_table)
.setAdapter(adapter,new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int item) {
Table checkedItem = getItems().get(item);
RequestParams params = Network.makeAuthParams(ctx);
params.put("table_id", checkedItem.getId());
HttpClient.post("/reassigndiner/" + origin, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// Pull out the first event on the public timeline
try {
String sResponse = response.getString("status");
if (sResponse.equals("ok")) {
} else {
Toast.makeText(ctx, response.getString("reason"), Toast.LENGTH_SHORT).show();
return;
}
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(ctx, "La persona se reasigno correctamente.", Toast.LENGTH_SHORT).show();
//refresh activity
ServicesActivity servicesActivity = (ServicesActivity) comandasFragment.getActivity();
servicesActivity.updateForPersonChange();
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject jsonObject) {
Toast.makeText(ctx, "Ocurrio un error inesperado:" + throwable.getMessage(), Toast.LENGTH_LONG).show();
}
}, ctx);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
@Override
public void onClick(DialogInterface dialog, int which) {
}
public ArrayList<Table> getItems() {
return items;
}
public void setItems(ArrayList<Table> items) {
this.items = items;
}
public Integer getOrigin() {
return origin;
}
public void setOrigin(Integer origin) {
this.origin = origin;
}
public ComandasFragment getComandasFragment() {
return comandasFragment;
}
public void setComandasFragment(ComandasFragment comandasFragment) {
this.comandasFragment = comandasFragment;
}
} | 4,681 | 0.578722 | 0.577227 | 131 | 34.740459 | 33.025223 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.534351 | false | false | 10 |
ac7b8fcd56b9951521758aa14d9788f046f32ce4 | 31,971,736,597,210 | f924a9a81abef5b368f599f1da56bb67d3207316 | /q1w1/src/q1_2w1/Q1_1w1.java | 0f6de3ca5cacd92d7548e385a264ac6ee9f07e61 | [] | no_license | kasperpagh/q1-w1 | https://github.com/kasperpagh/q1-w1 | 79979e1b495666b332fc0cc8aa585fa0b594a03e | e531533bd70285b148c7ba4643b3394bf41e1f3e | refs/heads/master | 2020-03-29T13:47:39.826000 | 2015-08-26T07:24:00 | 2015-08-26T07:24:00 | 41,360,923 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package q1_2w1;
/**
*
* @author pagh
*/
public class Q1_1w1
{
public static void main(String[] args)
{
boolean abekat = true;
Even even = new Even();
T1 t1 = new T1(even);
T1 t2 = new T1(even);
t1.start();
t2.start();
while (true)
{
if ((t1.gogo(even) % 2) != 0)
{
System.out.println("ulige tal!!!");
break;
}
if ((t2.gogo(even) % 2) != 0)
{
System.out.println("ulige tal!!!");
break;
}
}
}
}
| UTF-8 | Java | 815 | java | Q1_1w1.java | Java | [
{
"context": "the editor.\n */\npackage q1_2w1;\n\n/**\n *\n * @author pagh\n */\npublic class Q1_1w1\n{\n public static void ",
"end": 224,
"score": 0.9836069345474243,
"start": 220,
"tag": "USERNAME",
"value": "pagh"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package q1_2w1;
/**
*
* @author pagh
*/
public class Q1_1w1
{
public static void main(String[] args)
{
boolean abekat = true;
Even even = new Even();
T1 t1 = new T1(even);
T1 t2 = new T1(even);
t1.start();
t2.start();
while (true)
{
if ((t1.gogo(even) % 2) != 0)
{
System.out.println("ulige tal!!!");
break;
}
if ((t2.gogo(even) % 2) != 0)
{
System.out.println("ulige tal!!!");
break;
}
}
}
}
| 815 | 0.456442 | 0.431902 | 41 | 18.878048 | 18.584278 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.341463 | false | false | 10 |
afab57d4020cc4c643929f99ac2a9d245de667c9 | 31,971,736,597,278 | 6f672fb72caedccb841ee23f53e32aceeaf1895e | /Shopping/offerup_source/src/com/paypal/android/sdk/payments/av.java | 9eb0c7cda292bdb3377cdb1554955a28f377488f | [] | no_license | cha63506/CompSecurity | https://github.com/cha63506/CompSecurity | 5c69743f660b9899146ed3cf21eceabe3d5f4280 | eee7e74f4088b9c02dd711c061fc04fb1e4e2654 | refs/heads/master | 2018-03-23T04:15:18.480000 | 2015-12-19T01:29:58 | 2015-12-19T01:29:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.paypal.android.sdk.payments;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
// Referenced classes of package com.paypal.android.sdk.payments:
// bf, PayPalProfileSharingActivity, aw, br,
// bh
final class av
implements bf
{
final PayPalProfileSharingActivity a;
av(PayPalProfileSharingActivity paypalprofilesharingactivity)
{
a = paypalprofilesharingactivity;
super();
}
public final void a()
{
Date date = Calendar.getInstance().getTime();
if (PayPalProfileSharingActivity.d(a).compareTo(date) > 0)
{
long l = PayPalProfileSharingActivity.d(a).getTime() - date.getTime();
PayPalProfileSharingActivity.a();
(new StringBuilder("Delaying ")).append(l).append(" miliseconds so user doesn't see flicker.");
PayPalProfileSharingActivity.a(a, new Timer());
PayPalProfileSharingActivity.e(a).schedule(new aw(this), l);
return;
} else
{
PayPalProfileSharingActivity.c(a);
return;
}
}
public final void a(bh bh)
{
br.a(a, bh);
}
}
| UTF-8 | Java | 1,378 | java | av.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus",
"end": 61,
"score": 0.9995941519737244,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
] | null | [] | // Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.paypal.android.sdk.payments;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
// Referenced classes of package com.paypal.android.sdk.payments:
// bf, PayPalProfileSharingActivity, aw, br,
// bh
final class av
implements bf
{
final PayPalProfileSharingActivity a;
av(PayPalProfileSharingActivity paypalprofilesharingactivity)
{
a = paypalprofilesharingactivity;
super();
}
public final void a()
{
Date date = Calendar.getInstance().getTime();
if (PayPalProfileSharingActivity.d(a).compareTo(date) > 0)
{
long l = PayPalProfileSharingActivity.d(a).getTime() - date.getTime();
PayPalProfileSharingActivity.a();
(new StringBuilder("Delaying ")).append(l).append(" miliseconds so user doesn't see flicker.");
PayPalProfileSharingActivity.a(a, new Timer());
PayPalProfileSharingActivity.e(a).schedule(new aw(this), l);
return;
} else
{
PayPalProfileSharingActivity.c(a);
return;
}
}
public final void a(bh bh)
{
br.a(a, bh);
}
}
| 1,368 | 0.63135 | 0.625544 | 49 | 27.12245 | 26.483442 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.489796 | false | false | 10 |
440cd3729ecb675835472cb43bd6f8fb2ec634a8 | 9,371,618,667,014 | 6656e047eb247a25b42b204842a2e8b5c339c1d2 | /app/src/main/java/com/bbeaggoo/myapplication/adapter/AdapterContract.java | ec3fba815b9d2d101796d89041a01a4622859f94 | [] | no_license | iamjunyoung/MyApplication | https://github.com/iamjunyoung/MyApplication | 0e60b323e05dbd5298fe00c7bf0c00e4b63b7457 | a707bda687bbac6a67f5ac550adbdb1dfd8a8046 | refs/heads/master | 2020-03-14T10:37:50.196000 | 2018-06-24T13:44:35 | 2018-06-24T13:44:35 | 131,571,590 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bbeaggoo.myapplication.adapter;
import com.bbeaggoo.myapplication.datas.ItemObjects;
import com.bbeaggoo.myapplication.listener.OnItemClickListener;
import java.util.List;
/**
* Created by junyoung on 2018. 3. 13..
*/
public interface AdapterContract{
interface Model {
void add(ItemObjects itemObjects);
ItemObjects remove(int position);
ItemObjects get(int position);
void addItems(List<ItemObjects> list);
int getSize();
void clearItem();
}
interface View {
void refreshItemList();
void refreshItemAdded(int position);
void refreshItemRemoved(int postion);
void refreshItemChanged(int position);
void setOnClickListener(OnItemClickListener onClickListener);
}
}
| UTF-8 | Java | 790 | java | AdapterContract.java | Java | [
{
"context": "istener;\n\nimport java.util.List;\n/**\n * Created by junyoung on 2018. 3. 13..\n */\n\npublic interface AdapterCon",
"end": 213,
"score": 0.9994761943817139,
"start": 205,
"tag": "USERNAME",
"value": "junyoung"
}
] | null | [] | package com.bbeaggoo.myapplication.adapter;
import com.bbeaggoo.myapplication.datas.ItemObjects;
import com.bbeaggoo.myapplication.listener.OnItemClickListener;
import java.util.List;
/**
* Created by junyoung on 2018. 3. 13..
*/
public interface AdapterContract{
interface Model {
void add(ItemObjects itemObjects);
ItemObjects remove(int position);
ItemObjects get(int position);
void addItems(List<ItemObjects> list);
int getSize();
void clearItem();
}
interface View {
void refreshItemList();
void refreshItemAdded(int position);
void refreshItemRemoved(int postion);
void refreshItemChanged(int position);
void setOnClickListener(OnItemClickListener onClickListener);
}
}
| 790 | 0.694937 | 0.686076 | 31 | 24.483871 | 21.141415 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483871 | false | false | 10 |
b5001397631525f1a5ca717bf50be61ece0fe47a | 20,143,396,654,611 | a7b448a9168e75a35cda944ab1bdd553957c890c | /app/src/main/java/kh/com/psnd/network/model/UserProfile.java | 221f93e8a71062ca9e6fd3392147bb38018594ce | [] | no_license | nicarayz/psnd-app | https://github.com/nicarayz/psnd-app | 35ec6c7e3d6deab3866d14ef7630448c50fcc376 | 272c502ccc881e6585d970394d5293e7a4122482 | refs/heads/master | 2022-12-26T16:29:25.225000 | 2020-10-14T08:27:53 | 2020-10-14T08:27:53 | 272,333,959 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kh.com.psnd.network.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import core.lib.network.model.BaseGson;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
public class UserProfile extends BaseGson {
public static final String EXTRA = "UserProfile";
@SerializedName("id")
private String id;
@SerializedName("username")
private String username;
@SerializedName("password")
private String password;
@SerializedName("role")
private UserRole role;
@SerializedName("privileges")
private List<UserPrivilege> privileges;
@SerializedName("created_at")
private String createdAt;
@SerializedName("created_by")
private String createBy;
@SerializedName("modified_at")
private String modifiedAt;
@SerializedName("modified_by")
private String modifiedBy;
@SerializedName("active")
private boolean active;
@SerializedName("active_color")
private String activeColor;
@SerializedName("staff")
private SearchStaff staff;
}
| UTF-8 | Java | 1,113 | java | UserProfile.java | Java | [
{
"context": "id\")\n private String id;\n\n @SerializedName(\"username\")\n private String username;\n\n @SerializedNa",
"end": 429,
"score": 0.5528069138526917,
"start": 421,
"tag": "USERNAME",
"value": "username"
}
] | null | [] | package kh.com.psnd.network.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import core.lib.network.model.BaseGson;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
public class UserProfile extends BaseGson {
public static final String EXTRA = "UserProfile";
@SerializedName("id")
private String id;
@SerializedName("username")
private String username;
@SerializedName("password")
private String password;
@SerializedName("role")
private UserRole role;
@SerializedName("privileges")
private List<UserPrivilege> privileges;
@SerializedName("created_at")
private String createdAt;
@SerializedName("created_by")
private String createBy;
@SerializedName("modified_at")
private String modifiedAt;
@SerializedName("modified_by")
private String modifiedBy;
@SerializedName("active")
private boolean active;
@SerializedName("active_color")
private String activeColor;
@SerializedName("staff")
private SearchStaff staff;
}
| 1,113 | 0.72327 | 0.72327 | 53 | 20 | 16.366095 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.358491 | false | false | 10 |
206eee188f742fff352c63631e828a4f478191a8 | 12,077,448,061,210 | a126673181d3c7b6838acf7182042073549f3eb7 | /src/jCiv/map/DisasterZone.java | 00235e642a3a9a1e49114f0eb0743c0ae70285f9 | [] | no_license | neviyn/jCiv | https://github.com/neviyn/jCiv | 2b5204b3f3dd448243c49b622529a49f5196084b | e26f99ddf05a7fcf5a0f03d34e6cbe5a0a01666f | refs/heads/master | 2021-01-18T11:40:43.595000 | 2012-05-29T10:56:50 | 2012-05-29T10:56:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jCiv.map;
import java.util.ArrayList;
/**
* User: nathan
* Date: 24/05/12
* Time: 13:42
*/
public abstract class DisasterZone {
private final ArrayList<MapNode> zones;
/**
*
* @param zones
*/
public DisasterZone(ArrayList<MapNode> zones)
{
this.zones = zones;
}
/**
* @return List of zones within this disaster area.
*/
public ArrayList<MapNode> getZones()
{
return zones;
}
/**
* @param playerNum The number representing the player we are checking for tokens of.
* @return Does this area contain units belonging to the parameter player.
*/
public boolean containsPlayer(int playerNum)
{
boolean found = false;
for(MapNode node:zones)
{
// TODO: Add code for checking if a map node contains tokens of a certain player.
}
return found;
}
public boolean cityIsAffected(int nodeID)
{
return containsNode(nodeID);
}
/**
* Check whether this zone contains a given mapNode
* @param nodeID the id of the mapnode to be checked
* @return true if the zone contains the node
*/
public boolean containsNode(int nodeID)
{
boolean found = false;
for (MapNode n : zones) {
if (n.nodeNum == nodeID) {
found = true;
}
}
return found;
}
@Override
public String toString()
{
String result = "\tAffected nodes:";
for (MapNode n : zones) {
result += "\n\t\tID:" + n.nodeNum;
}
return result;
}
}
| UTF-8 | Java | 1,602 | java | DisasterZone.java | Java | [
{
"context": "iv.map;\n\nimport java.util.ArrayList;\n\n/**\n * User: nathan\n * Date: 24/05/12\n * Time: 13:42\n */\npublic abstr",
"end": 67,
"score": 0.9985840320587158,
"start": 61,
"tag": "USERNAME",
"value": "nathan"
}
] | null | [] | package jCiv.map;
import java.util.ArrayList;
/**
* User: nathan
* Date: 24/05/12
* Time: 13:42
*/
public abstract class DisasterZone {
private final ArrayList<MapNode> zones;
/**
*
* @param zones
*/
public DisasterZone(ArrayList<MapNode> zones)
{
this.zones = zones;
}
/**
* @return List of zones within this disaster area.
*/
public ArrayList<MapNode> getZones()
{
return zones;
}
/**
* @param playerNum The number representing the player we are checking for tokens of.
* @return Does this area contain units belonging to the parameter player.
*/
public boolean containsPlayer(int playerNum)
{
boolean found = false;
for(MapNode node:zones)
{
// TODO: Add code for checking if a map node contains tokens of a certain player.
}
return found;
}
public boolean cityIsAffected(int nodeID)
{
return containsNode(nodeID);
}
/**
* Check whether this zone contains a given mapNode
* @param nodeID the id of the mapnode to be checked
* @return true if the zone contains the node
*/
public boolean containsNode(int nodeID)
{
boolean found = false;
for (MapNode n : zones) {
if (n.nodeNum == nodeID) {
found = true;
}
}
return found;
}
@Override
public String toString()
{
String result = "\tAffected nodes:";
for (MapNode n : zones) {
result += "\n\t\tID:" + n.nodeNum;
}
return result;
}
}
| 1,602 | 0.577403 | 0.571161 | 74 | 20.648649 | 21.061962 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.432432 | false | false | 10 |
053010f2493728fafa41b6caa5b3661fc7fe3902 | 31,971,736,598,825 | 1ee29fce36a8deab98d74548457fad35a4324dfb | /Final/FinalProject/src/main/java/by/training/finalproject/dal/UserDAO.java | 6725fe6ced9d2bb6cd3c4735357cec606ad7a79c | [] | no_license | ArtemKolganow/trainingRep | https://github.com/ArtemKolganow/trainingRep | ca907dc2374d10dfdf888ad40131855e20fbd2a2 | e728c979e885680cde8b4d685d2d7f03eefa7e5b | refs/heads/master | 2022-06-30T17:28:24.307000 | 2020-05-09T20:39:23 | 2020-05-09T20:39:23 | 227,861,196 | 0 | 0 | null | false | 2022-01-04T16:39:59 | 2019-12-13T14:48:37 | 2020-05-10T17:47:51 | 2022-01-04T16:39:58 | 7,471 | 0 | 0 | 9 | Java | false | false | package by.training.finalproject.dal;
import by.training.finalproject.entity.User;
import java.util.List;
public interface UserDAO extends AbstractDAO<Integer, User> {
User findEntityByLoginAndPass(String login, String pass) throws DataObjectException;
User findEntityById(Integer id) throws DataObjectException;
}
| UTF-8 | Java | 326 | java | UserDAO.java | Java | [] | null | [] | package by.training.finalproject.dal;
import by.training.finalproject.entity.User;
import java.util.List;
public interface UserDAO extends AbstractDAO<Integer, User> {
User findEntityByLoginAndPass(String login, String pass) throws DataObjectException;
User findEntityById(Integer id) throws DataObjectException;
}
| 326 | 0.812883 | 0.812883 | 10 | 31.6 | 30.394737 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 10 |
91a0728c8ad672a279624e30b0f63c92f4084850 | 18,219,251,312,049 | 04d12be16f944590f4f7e0ba53c4cef6c8af879c | /practise-learning/src/main/java/nowcode/top101/_43_包含MIN函数的栈.java | 6a8fcb8985b2c2d52f581aad1a28643f62744484 | [
"MIT"
] | permissive | n1ck3dcydoom/learning-note | https://github.com/n1ck3dcydoom/learning-note | 3388016b0ca2648c5a6c3de0b420f2b472f1a424 | fcbf6ad37c4f8c0a44d8998b7283405f31736ab0 | refs/heads/master | 2023-04-29T23:49:21.100000 | 2022-12-12T01:51:57 | 2022-12-12T01:51:57 | 251,662,928 | 1 | 0 | MIT | false | 2023-04-17T17:43:02 | 2020-03-31T16:25:38 | 2022-01-10T15:36:46 | 2023-04-17T17:42:58 | 11,190 | 0 | 0 | 1 | Java | false | false | package nowcode.top101;
import java.util.Stack;
/**
* Created by n!Ck
* Date: 2022/11/18
* Time: 11:21
* Description:
*/
public class _43_包含MIN函数的栈 {
public static void main(String[] args) {
MyStack s = new MyStack();
s.push(-1);
s.push(2);
System.out.println(s.min());
System.out.println(s.top());
s.pop();
s.push(1);
System.out.println(s.top());
System.out.println(s.min());
}
static class MyStack {
Stack<Integer> s = new Stack<>();
// 最小栈保存最小值
Stack<Integer> mins = new Stack<>();
public void push(int node) {
s.add(node);
if (mins.isEmpty()) {
mins.add(node);
} else {
if (node >= mins.peek()) {
mins.add(mins.peek());
} else {
mins.add(node);
}
}
}
public void pop() {
s.pop();
mins.pop();
}
public int top() {
return s.peek();
}
public int min() {
return mins.peek();
}
}
}
| UTF-8 | Java | 1,199 | java | _43_包含MIN函数的栈.java | Java | [
{
"context": "op101;\n\nimport java.util.Stack;\n\n/**\n * Created by n!Ck\n * Date: 2022/11/18\n * Time: 11:21\n * Description",
"end": 72,
"score": 0.9982032775878906,
"start": 68,
"tag": "USERNAME",
"value": "n!Ck"
}
] | null | [] | package nowcode.top101;
import java.util.Stack;
/**
* Created by n!Ck
* Date: 2022/11/18
* Time: 11:21
* Description:
*/
public class _43_包含MIN函数的栈 {
public static void main(String[] args) {
MyStack s = new MyStack();
s.push(-1);
s.push(2);
System.out.println(s.min());
System.out.println(s.top());
s.pop();
s.push(1);
System.out.println(s.top());
System.out.println(s.min());
}
static class MyStack {
Stack<Integer> s = new Stack<>();
// 最小栈保存最小值
Stack<Integer> mins = new Stack<>();
public void push(int node) {
s.add(node);
if (mins.isEmpty()) {
mins.add(node);
} else {
if (node >= mins.peek()) {
mins.add(mins.peek());
} else {
mins.add(node);
}
}
}
public void pop() {
s.pop();
mins.pop();
}
public int top() {
return s.peek();
}
public int min() {
return mins.peek();
}
}
}
| 1,199 | 0.426132 | 0.409052 | 57 | 19.543859 | 13.654984 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 10 |
64202acbd3a7b7d08ed7290326082ea7873b99e0 | 5,068,061,432,391 | 9ca52103def57c4b51499608d9e46d2f87543e2a | /binarySearchTree/src/main/java/BinaryTree.java | dade9ccd36aa05a797b972b8b619b7cbed264c7f | [] | no_license | lengocnu8497/DataStructures | https://github.com/lengocnu8497/DataStructures | b181d52ca68529b76381b492191c38df7ca046a1 | 3db35f01776d39e0025c29daeac3d008279f1ad3 | refs/heads/master | 2020-09-10T03:16:04.701000 | 2020-07-09T04:02:27 | 2020-07-09T04:02:27 | 221,635,534 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | ///
//Name: Le, Nu
//Homework: 1
//Due: 11/14/2019
//Course: cs-2400-01-f19
//Description: A program that reads in user's input and build a binary search tree
//based upon these input. Then it displays the tree in pre-,post-,in- order format.
public class BinaryTree<T> implements BinaryTreeInterface<T>{
private BinaryNode<T> root;
public BinaryTree()
{
root = null;
}
public BinaryTree(T rootData)
{
root = new BinaryNode<>(rootData);
}
public BinaryTree(T rootData, BinaryTree<T> leftTree, BinaryTree<T> rightTree)
{
initializeTree(rootData,leftTree,rightTree);
}
public void initializeTree(T rootData, BinaryTree<T> leftTree, BinaryTree<T> rightTree)
{
root = new BinaryNode<>(rootData);
if((leftTree != null) && !leftTree.isEmpty())
root.setLeftChild(leftTree.root.copy());
if((rightTree != null) && !rightTree.isEmpty())
root.setRightChild(rightTree.root.copy());
}
public boolean isEmpty()
{
return root == null;
}
public void setRootData( T rootData)
{
root.setData(rootData);
}
public void setRootNode(BinaryNode<T> rootNode)
{
root = rootNode;
}
public void setTree(T rootData, BinaryTreeInterface<T> leftTree,
BinaryTreeInterface<T> rightTree)
{
initializeTree(rootData,(BinaryTree<T>) leftTree, (BinaryTree<T>) rightTree);
}
protected BinaryNode<T> getRootNode()
{
return root;
}
}
| UTF-8 | Java | 1,661 | java | BinaryTree.java | Java | [
{
"context": "///\r\n//Name: Le, Nu\r\n//Homework: 1\r\n//Due: 11/14/2019\r\n//Cours",
"end": 24,
"score": 0.9997801780700684,
"start": 18,
"tag": "NAME",
"value": "Le, Nu"
}
] | null | [] | ///
//Name: <NAME>
//Homework: 1
//Due: 11/14/2019
//Course: cs-2400-01-f19
//Description: A program that reads in user's input and build a binary search tree
//based upon these input. Then it displays the tree in pre-,post-,in- order format.
public class BinaryTree<T> implements BinaryTreeInterface<T>{
private BinaryNode<T> root;
public BinaryTree()
{
root = null;
}
public BinaryTree(T rootData)
{
root = new BinaryNode<>(rootData);
}
public BinaryTree(T rootData, BinaryTree<T> leftTree, BinaryTree<T> rightTree)
{
initializeTree(rootData,leftTree,rightTree);
}
public void initializeTree(T rootData, BinaryTree<T> leftTree, BinaryTree<T> rightTree)
{
root = new BinaryNode<>(rootData);
if((leftTree != null) && !leftTree.isEmpty())
root.setLeftChild(leftTree.root.copy());
if((rightTree != null) && !rightTree.isEmpty())
root.setRightChild(rightTree.root.copy());
}
public boolean isEmpty()
{
return root == null;
}
public void setRootData( T rootData)
{
root.setData(rootData);
}
public void setRootNode(BinaryNode<T> rootNode)
{
root = rootNode;
}
public void setTree(T rootData, BinaryTreeInterface<T> leftTree,
BinaryTreeInterface<T> rightTree)
{
initializeTree(rootData,(BinaryTree<T>) leftTree, (BinaryTree<T>) rightTree);
}
protected BinaryNode<T> getRootNode()
{
return root;
}
}
| 1,661 | 0.581577 | 0.571343 | 62 | 24.790323 | 25.729446 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.403226 | false | false | 10 |
9852c18d6c7616b3cee82af5680b848032b57d98 | 33,389,075,818,291 | ca994f6d4da2703b3fe7b483fb3166201fad78fd | /portal-service-api/src/main/java/com/bestpay/portal/service/cum/request/PortalMerchantCodeQueryRequest.java | c29421a10f9a4fca712fde951c25873418affef8 | [] | no_license | daixiaohei/bpep-portal-service | https://github.com/daixiaohei/bpep-portal-service | eedbc470ed91a3cb4610a37c6d510a1b2b6622a7 | e58e4a68aa623999bc244b0d961ff0d27270948d | refs/heads/master | 2016-08-26T07:26:56.516000 | 2016-06-03T07:02:18 | 2016-06-03T07:02:18 | 61,784,189 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bestpay.portal.service.cum.request;
import com.bestpay.portal.service.account.request.base.PortalRequest;
import lombok.*;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* User: xiezequn
* Date: 2015/12/09
* Depiction: 根据客户账户号查询 客户号,客户账户号,登录号,账户号对应关系
*/
@Data
@ToString(callSuper = true)
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
public class PortalMerchantCodeQueryRequest extends PortalRequest implements Serializable{
/**
* 账户号
*/
@Length(max = 128,message = "客户账户号最大长度为64")
@NotBlank(message ="客户账户号不允许为空")
private String merchantCode;
}
| UTF-8 | Java | 826 | java | PortalMerchantCodeQueryRequest.java | Java | [
{
"context": "able;\n\n/**\n * Created with IntelliJ IDEA.\n * User: xiezequn\n * Date: 2015/12/09\n * Depiction: 根据客户账户号查询 客户号,客",
"end": 323,
"score": 0.9995983242988586,
"start": 315,
"tag": "USERNAME",
"value": "xiezequn"
}
] | null | [] | package com.bestpay.portal.service.cum.request;
import com.bestpay.portal.service.account.request.base.PortalRequest;
import lombok.*;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* User: xiezequn
* Date: 2015/12/09
* Depiction: 根据客户账户号查询 客户号,客户账户号,登录号,账户号对应关系
*/
@Data
@ToString(callSuper = true)
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
public class PortalMerchantCodeQueryRequest extends PortalRequest implements Serializable{
/**
* 账户号
*/
@Length(max = 128,message = "客户账户号最大长度为64")
@NotBlank(message ="客户账户号不允许为空")
private String merchantCode;
}
| 826 | 0.754167 | 0.736111 | 29 | 23.827587 | 22.982855 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.275862 | false | false | 10 |
079c3927502a450c28538ea9e070989ae2fd9c76 | 10,247,791,972,964 | 037637a2c0d177362285e0608d4f4f00dc4cfce9 | /components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/composite/MapOfMapsConverter.java | 633b9c8ae7513bdcfcf838248e653c83f0555232 | [
"Apache-2.0",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | dmgerman/camel | https://github.com/dmgerman/camel | 07379b6a1d191078b085b62bbb0a6732141994aa | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | refs/heads/master | 2023-01-03T23:00:15.190000 | 2019-12-20T08:30:29 | 2019-12-20T08:30:29 | 230,528,998 | 0 | 0 | Apache-2.0 | false | 2023-01-02T22:14:35 | 2019-12-27T22:50:51 | 2019-12-28T01:30:10 | 2023-01-02T22:14:34 | 129,843 | 0 | 0 | 3 | Java | false | false | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.camel.component.salesforce.api.dto.composite
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|salesforce
operator|.
name|api
operator|.
name|dto
operator|.
name|composite
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashMap
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Iterator
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|com
operator|.
name|thoughtworks
operator|.
name|xstream
operator|.
name|converters
operator|.
name|Converter
import|;
end_import
begin_import
import|import
name|com
operator|.
name|thoughtworks
operator|.
name|xstream
operator|.
name|converters
operator|.
name|MarshallingContext
import|;
end_import
begin_import
import|import
name|com
operator|.
name|thoughtworks
operator|.
name|xstream
operator|.
name|converters
operator|.
name|UnmarshallingContext
import|;
end_import
begin_import
import|import
name|com
operator|.
name|thoughtworks
operator|.
name|xstream
operator|.
name|io
operator|.
name|HierarchicalStreamReader
import|;
end_import
begin_import
import|import
name|com
operator|.
name|thoughtworks
operator|.
name|xstream
operator|.
name|io
operator|.
name|HierarchicalStreamWriter
import|;
end_import
begin_class
DECL|class|MapOfMapsConverter
specifier|public
class|class
name|MapOfMapsConverter
implements|implements
name|Converter
block|{
DECL|field|ATTRIBUTES_PROPERTY
specifier|private
specifier|static
specifier|final
name|String
name|ATTRIBUTES_PROPERTY
init|=
literal|"attributes"
decl_stmt|;
annotation|@
name|Override
DECL|method|canConvert (final Class type)
specifier|public
name|boolean
name|canConvert
parameter_list|(
specifier|final
name|Class
name|type
parameter_list|)
block|{
return|return
literal|true
return|;
block|}
annotation|@
name|Override
DECL|method|marshal (final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context)
specifier|public
name|void
name|marshal
parameter_list|(
specifier|final
name|Object
name|source
parameter_list|,
specifier|final
name|HierarchicalStreamWriter
name|writer
parameter_list|,
specifier|final
name|MarshallingContext
name|context
parameter_list|)
block|{
name|context
operator|.
name|convertAnother
argument_list|(
name|source
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|unmarshal (final HierarchicalStreamReader reader, final UnmarshallingContext context)
specifier|public
name|Object
name|unmarshal
parameter_list|(
specifier|final
name|HierarchicalStreamReader
name|reader
parameter_list|,
specifier|final
name|UnmarshallingContext
name|context
parameter_list|)
block|{
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|Object
argument_list|>
name|ret
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
while|while
condition|(
name|reader
operator|.
name|hasMoreChildren
argument_list|()
condition|)
block|{
name|readMap
argument_list|(
name|reader
argument_list|,
name|ret
argument_list|)
expr_stmt|;
block|}
return|return
name|ret
return|;
block|}
DECL|method|readMap (final HierarchicalStreamReader reader, final Map<String, Object> map)
name|Object
name|readMap
parameter_list|(
specifier|final
name|HierarchicalStreamReader
name|reader
parameter_list|,
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|Object
argument_list|>
name|map
parameter_list|)
block|{
if|if
condition|(
name|reader
operator|.
name|hasMoreChildren
argument_list|()
condition|)
block|{
name|reader
operator|.
name|moveDown
argument_list|()
expr_stmt|;
specifier|final
name|String
name|key
init|=
name|reader
operator|.
name|getNodeName
argument_list|()
decl_stmt|;
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|attributes
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
specifier|final
name|Iterator
name|attributeNames
init|=
name|reader
operator|.
name|getAttributeNames
argument_list|()
decl_stmt|;
while|while
condition|(
name|attributeNames
operator|.
name|hasNext
argument_list|()
condition|)
block|{
specifier|final
name|String
name|attributeName
init|=
operator|(
name|String
operator|)
name|attributeNames
operator|.
name|next
argument_list|()
decl_stmt|;
name|attributes
operator|.
name|put
argument_list|(
name|attributeName
argument_list|,
name|reader
operator|.
name|getAttribute
argument_list|(
name|attributeName
argument_list|)
argument_list|)
expr_stmt|;
block|}
name|Object
name|nested
init|=
name|readMap
argument_list|(
name|reader
argument_list|,
operator|new
name|HashMap
argument_list|<>
argument_list|()
argument_list|)
decl_stmt|;
if|if
condition|(
operator|!
name|attributes
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
if|if
condition|(
name|nested
operator|instanceof
name|String
condition|)
block|{
specifier|final
name|Map
argument_list|<
name|Object
argument_list|,
name|Object
argument_list|>
name|newNested
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
name|newNested
operator|.
name|put
argument_list|(
name|key
argument_list|,
name|nested
argument_list|)
expr_stmt|;
name|newNested
operator|.
name|put
argument_list|(
name|ATTRIBUTES_PROPERTY
argument_list|,
name|attributes
argument_list|)
expr_stmt|;
name|nested
operator|=
name|newNested
expr_stmt|;
block|}
else|else
block|{
annotation|@
name|SuppressWarnings
argument_list|(
literal|"unchecked"
argument_list|)
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|Object
argument_list|>
name|nestedMap
init|=
operator|(
name|Map
argument_list|<
name|String
argument_list|,
name|Object
argument_list|>
operator|)
name|nested
decl_stmt|;
name|nestedMap
operator|.
name|put
argument_list|(
name|ATTRIBUTES_PROPERTY
argument_list|,
name|attributes
argument_list|)
expr_stmt|;
block|}
block|}
name|map
operator|.
name|put
argument_list|(
name|key
argument_list|,
name|nested
argument_list|)
expr_stmt|;
name|reader
operator|.
name|moveUp
argument_list|()
expr_stmt|;
name|readMap
argument_list|(
name|reader
argument_list|,
name|map
argument_list|)
expr_stmt|;
block|}
else|else
block|{
return|return
name|reader
operator|.
name|getValue
argument_list|()
return|;
block|}
return|return
name|map
return|;
block|}
block|}
end_class
end_unit
| UTF-8 | Java | 7,411 | java | MapOfMapsConverter.java | Java | [] | null | [] | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.camel.component.salesforce.api.dto.composite
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|salesforce
operator|.
name|api
operator|.
name|dto
operator|.
name|composite
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashMap
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Iterator
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|com
operator|.
name|thoughtworks
operator|.
name|xstream
operator|.
name|converters
operator|.
name|Converter
import|;
end_import
begin_import
import|import
name|com
operator|.
name|thoughtworks
operator|.
name|xstream
operator|.
name|converters
operator|.
name|MarshallingContext
import|;
end_import
begin_import
import|import
name|com
operator|.
name|thoughtworks
operator|.
name|xstream
operator|.
name|converters
operator|.
name|UnmarshallingContext
import|;
end_import
begin_import
import|import
name|com
operator|.
name|thoughtworks
operator|.
name|xstream
operator|.
name|io
operator|.
name|HierarchicalStreamReader
import|;
end_import
begin_import
import|import
name|com
operator|.
name|thoughtworks
operator|.
name|xstream
operator|.
name|io
operator|.
name|HierarchicalStreamWriter
import|;
end_import
begin_class
DECL|class|MapOfMapsConverter
specifier|public
class|class
name|MapOfMapsConverter
implements|implements
name|Converter
block|{
DECL|field|ATTRIBUTES_PROPERTY
specifier|private
specifier|static
specifier|final
name|String
name|ATTRIBUTES_PROPERTY
init|=
literal|"attributes"
decl_stmt|;
annotation|@
name|Override
DECL|method|canConvert (final Class type)
specifier|public
name|boolean
name|canConvert
parameter_list|(
specifier|final
name|Class
name|type
parameter_list|)
block|{
return|return
literal|true
return|;
block|}
annotation|@
name|Override
DECL|method|marshal (final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context)
specifier|public
name|void
name|marshal
parameter_list|(
specifier|final
name|Object
name|source
parameter_list|,
specifier|final
name|HierarchicalStreamWriter
name|writer
parameter_list|,
specifier|final
name|MarshallingContext
name|context
parameter_list|)
block|{
name|context
operator|.
name|convertAnother
argument_list|(
name|source
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|unmarshal (final HierarchicalStreamReader reader, final UnmarshallingContext context)
specifier|public
name|Object
name|unmarshal
parameter_list|(
specifier|final
name|HierarchicalStreamReader
name|reader
parameter_list|,
specifier|final
name|UnmarshallingContext
name|context
parameter_list|)
block|{
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|Object
argument_list|>
name|ret
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
while|while
condition|(
name|reader
operator|.
name|hasMoreChildren
argument_list|()
condition|)
block|{
name|readMap
argument_list|(
name|reader
argument_list|,
name|ret
argument_list|)
expr_stmt|;
block|}
return|return
name|ret
return|;
block|}
DECL|method|readMap (final HierarchicalStreamReader reader, final Map<String, Object> map)
name|Object
name|readMap
parameter_list|(
specifier|final
name|HierarchicalStreamReader
name|reader
parameter_list|,
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|Object
argument_list|>
name|map
parameter_list|)
block|{
if|if
condition|(
name|reader
operator|.
name|hasMoreChildren
argument_list|()
condition|)
block|{
name|reader
operator|.
name|moveDown
argument_list|()
expr_stmt|;
specifier|final
name|String
name|key
init|=
name|reader
operator|.
name|getNodeName
argument_list|()
decl_stmt|;
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|attributes
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
specifier|final
name|Iterator
name|attributeNames
init|=
name|reader
operator|.
name|getAttributeNames
argument_list|()
decl_stmt|;
while|while
condition|(
name|attributeNames
operator|.
name|hasNext
argument_list|()
condition|)
block|{
specifier|final
name|String
name|attributeName
init|=
operator|(
name|String
operator|)
name|attributeNames
operator|.
name|next
argument_list|()
decl_stmt|;
name|attributes
operator|.
name|put
argument_list|(
name|attributeName
argument_list|,
name|reader
operator|.
name|getAttribute
argument_list|(
name|attributeName
argument_list|)
argument_list|)
expr_stmt|;
block|}
name|Object
name|nested
init|=
name|readMap
argument_list|(
name|reader
argument_list|,
operator|new
name|HashMap
argument_list|<>
argument_list|()
argument_list|)
decl_stmt|;
if|if
condition|(
operator|!
name|attributes
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
if|if
condition|(
name|nested
operator|instanceof
name|String
condition|)
block|{
specifier|final
name|Map
argument_list|<
name|Object
argument_list|,
name|Object
argument_list|>
name|newNested
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
name|newNested
operator|.
name|put
argument_list|(
name|key
argument_list|,
name|nested
argument_list|)
expr_stmt|;
name|newNested
operator|.
name|put
argument_list|(
name|ATTRIBUTES_PROPERTY
argument_list|,
name|attributes
argument_list|)
expr_stmt|;
name|nested
operator|=
name|newNested
expr_stmt|;
block|}
else|else
block|{
annotation|@
name|SuppressWarnings
argument_list|(
literal|"unchecked"
argument_list|)
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|Object
argument_list|>
name|nestedMap
init|=
operator|(
name|Map
argument_list|<
name|String
argument_list|,
name|Object
argument_list|>
operator|)
name|nested
decl_stmt|;
name|nestedMap
operator|.
name|put
argument_list|(
name|ATTRIBUTES_PROPERTY
argument_list|,
name|attributes
argument_list|)
expr_stmt|;
block|}
block|}
name|map
operator|.
name|put
argument_list|(
name|key
argument_list|,
name|nested
argument_list|)
expr_stmt|;
name|reader
operator|.
name|moveUp
argument_list|()
expr_stmt|;
name|readMap
argument_list|(
name|reader
argument_list|,
name|map
argument_list|)
expr_stmt|;
block|}
else|else
block|{
return|return
name|reader
operator|.
name|getValue
argument_list|()
return|;
block|}
return|return
name|map
return|;
block|}
block|}
end_class
end_unit
| 7,411 | 0.791931 | 0.790582 | 477 | 14.534591 | 37.565502 | 810 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.075472 | false | false | 10 |
16d4cd89e326b22ee57d1d774b8d918441f93dc6 | 8,675,833,986,000 | 98078bb3202a2532e31446c8436b1cc19ee2deb7 | /app/src/main/java/com/xiaozhiguang/impl/CallerImplement.java | ec7816507d0a77a4c75456878fbe65ebb95fece2 | [] | no_license | xiaozhiguang/DataResolve | https://github.com/xiaozhiguang/DataResolve | a15e276a64891f0681a3bcc6005fcffc619c7871 | a5b01d04a6475d3e64a09e682e5478b312e0dae5 | refs/heads/master | 2017-10-05T21:48:28.217000 | 2017-06-22T06:01:57 | 2017-06-22T06:01:57 | 94,876,406 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xiaozhiguang.impl;
import android.util.Base64;
import com.xiaozhiguang.bean.UserBean;
import com.xiaozhiguang.dataresolve.HttpCaller;
import com.xiaozhiguang.main.AppConfig;
import com.xiaozhiguang.dataresolve.RequestDataCallback;
import okhttp3.FormBody;
/**
* Created by xiaozhiguang on 2017/6/19.
*
* 作用:作为网络请求的中间层 进行具体的网络请求操作
*
*/
public class CallerImplement {
private static CallerImplement _instance = null;
public static CallerImplement getInstance(){
if (_instance == null){
_instance = new CallerImplement();
}
return _instance;
}
// 获取新闻信息
public void getNews(String keyword,RequestDataCallback<UserBean> callback){
String url = base64Decode(AppConfig.NEWS_IP);
FormBody params = new FormBody.Builder()
.add("key",AppConfig.NEWS_APP_KEY)
.add("keyword",keyword)
.build();
HttpCaller.getInstance().<UserBean>post(UserBean.class,url,params,callback);
}
// URL通过base64解密
public String base64Decode(String url){
String str = new String(Base64.decode(url.getBytes(),Base64.DEFAULT));
return str;
}
}
| UTF-8 | Java | 1,264 | java | CallerImplement.java | Java | [
{
"context": "back;\n\nimport okhttp3.FormBody;\n\n/**\n * Created by xiaozhiguang on 2017/6/19.\n *\n * 作用:作为网络请求的中间层 进行具体的网络请求操作\n *\n",
"end": 302,
"score": 0.9996627569198608,
"start": 290,
"tag": "USERNAME",
"value": "xiaozhiguang"
}
] | null | [] | package com.xiaozhiguang.impl;
import android.util.Base64;
import com.xiaozhiguang.bean.UserBean;
import com.xiaozhiguang.dataresolve.HttpCaller;
import com.xiaozhiguang.main.AppConfig;
import com.xiaozhiguang.dataresolve.RequestDataCallback;
import okhttp3.FormBody;
/**
* Created by xiaozhiguang on 2017/6/19.
*
* 作用:作为网络请求的中间层 进行具体的网络请求操作
*
*/
public class CallerImplement {
private static CallerImplement _instance = null;
public static CallerImplement getInstance(){
if (_instance == null){
_instance = new CallerImplement();
}
return _instance;
}
// 获取新闻信息
public void getNews(String keyword,RequestDataCallback<UserBean> callback){
String url = base64Decode(AppConfig.NEWS_IP);
FormBody params = new FormBody.Builder()
.add("key",AppConfig.NEWS_APP_KEY)
.add("keyword",keyword)
.build();
HttpCaller.getInstance().<UserBean>post(UserBean.class,url,params,callback);
}
// URL通过base64解密
public String base64Decode(String url){
String str = new String(Base64.decode(url.getBytes(),Base64.DEFAULT));
return str;
}
}
| 1,264 | 0.66806 | 0.651338 | 47 | 24.446808 | 23.785217 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.468085 | false | false | 10 |
0670207d2d439a78dfe1d8f8685fda97a37f3b14 | 8,675,833,985,705 | ee83e7183dd94f82876553cddcaa76689231775e | /books-jpa/src/main/java/ru/otus/books/repositories/impl/BookRepositoryJpaImpl.java | d3f1ec36fc0783ae37b41df30af5f0ddd2f78534 | [] | no_license | ant-liza/2021-02-otus-spring-prokhorova | https://github.com/ant-liza/2021-02-otus-spring-prokhorova | 0897b07eac227f025917f65b853479fd08f063c6 | 48f6006568f6fff56211e416c76ac3f7f0dde7bd | refs/heads/main | 2023-06-15T09:52:21.520000 | 2021-06-30T14:29:28 | 2021-06-30T14:29:28 | 342,294,769 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.otus.books.repositories.impl;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import ru.otus.books.models.Book;
import ru.otus.books.models.Note;
import ru.otus.books.repositories.jpa.BookRepositoryJpa;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.List;
import java.util.Optional;
@Repository
public class BookRepositoryJpaImpl implements BookRepositoryJpa {
@PersistenceContext
EntityManager em;
@Transactional(readOnly = true)
@Override
public long count() {
return em.createQuery("select count(*) from Book b", Long.class).getSingleResult();
}
@Transactional
@Override
public Book save(Book book) {
if (book.getBookId() == 0) {
em.persist(book);
em.flush();
return book;
} else {
return em.merge(book);
}
}
@Transactional(readOnly = true)
@Override
public List<Book> findAll() {
TypedQuery<Book> query = em.createQuery("select b from Book b", Book.class);
return query.getResultList();
}
@Transactional(readOnly = true)
@Override
public Optional<Book> findById(long id) {
return Optional.ofNullable(em.find(Book.class, id));
}
@Transactional(readOnly = true)
@Override
public List<Book> findBookByAuthorId(long authorId) {
Query query = em.createQuery("select b from Author a join a.books b where a.authorId=:authorId", Book.class);
query.setParameter("authorId",authorId);
return query.getResultList();
}
@Transactional
@Override
public void delete(Book book) {
em.remove(book);
}
}
| UTF-8 | Java | 1,841 | java | BookRepositoryJpaImpl.java | Java | [] | null | [] | package ru.otus.books.repositories.impl;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import ru.otus.books.models.Book;
import ru.otus.books.models.Note;
import ru.otus.books.repositories.jpa.BookRepositoryJpa;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.List;
import java.util.Optional;
@Repository
public class BookRepositoryJpaImpl implements BookRepositoryJpa {
@PersistenceContext
EntityManager em;
@Transactional(readOnly = true)
@Override
public long count() {
return em.createQuery("select count(*) from Book b", Long.class).getSingleResult();
}
@Transactional
@Override
public Book save(Book book) {
if (book.getBookId() == 0) {
em.persist(book);
em.flush();
return book;
} else {
return em.merge(book);
}
}
@Transactional(readOnly = true)
@Override
public List<Book> findAll() {
TypedQuery<Book> query = em.createQuery("select b from Book b", Book.class);
return query.getResultList();
}
@Transactional(readOnly = true)
@Override
public Optional<Book> findById(long id) {
return Optional.ofNullable(em.find(Book.class, id));
}
@Transactional(readOnly = true)
@Override
public List<Book> findBookByAuthorId(long authorId) {
Query query = em.createQuery("select b from Author a join a.books b where a.authorId=:authorId", Book.class);
query.setParameter("authorId",authorId);
return query.getResultList();
}
@Transactional
@Override
public void delete(Book book) {
em.remove(book);
}
}
| 1,841 | 0.679522 | 0.678979 | 65 | 27.323076 | 23.633163 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 10 |
6b415faa653396f94fb8e77e98e482fe549ad6b4 | 27,462,020,958,697 | e68f6c877c3fcbc4e72a72c68831205b6c9f63fc | /core/src/com/mana_wars/model/entity/user/UserDungeonsAPI.java | 4510c35442ea7dd930d5ddda08a85ff6bf48a5d5 | [
"MIT"
] | permissive | dembanakh/mana-wars | https://github.com/dembanakh/mana-wars | 6945522c01452f5fe50112ef1137327229995da2 | d1aec1f3ab603238cec376e37cd1ee17c8b1bbd8 | refs/heads/master | 2023-07-23T22:01:55.561000 | 2021-08-29T20:19:38 | 2021-08-29T20:19:38 | 396,413,113 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mana_wars.model.entity.user;
public interface UserDungeonsAPI extends UserBaseAPI{
int getLevel();
int getManaAmount();
}
| UTF-8 | Java | 143 | java | UserDungeonsAPI.java | Java | [] | null | [] | package com.mana_wars.model.entity.user;
public interface UserDungeonsAPI extends UserBaseAPI{
int getLevel();
int getManaAmount();
}
| 143 | 0.755245 | 0.755245 | 6 | 22.833334 | 19.23033 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 10 |
5ee5e493185b7f7027885b5f0906ae82b482000d | 11,046,655,948,713 | 69185b9e08d7aef088470b7d4ffae67c9a85678d | /src/main/java/hw_12/task_4/LambdaUserMain.java | f7bf890c0f9965749f3f5761962aae60a196b483 | [] | no_license | AmberInsane/TMS_HomeworkProject | https://github.com/AmberInsane/TMS_HomeworkProject | 2676614b3b8a00299a6c84bfb7dc698e7c4bf1cc | b8cf9c43d2a5986b2da4eb84751456a35e83b42f | refs/heads/master | 2022-05-28T01:02:53.277000 | 2020-01-16T11:40:45 | 2020-01-16T11:40:45 | 212,679,352 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hw_12.task_4;
import java.util.Scanner;
import java.util.function.Supplier;
import java.util.regex.Pattern;
public class LambdaUserMain {
public static void main(String[] args) {
try {
Supplier<User> newUser = () -> {
Scanner scanner = new Scanner(System.in);
System.out.println("Put in student's name");
String name = scanner.nextLine();
if (name.matches("[a-zA-Z]+")) {
return new User(name);
} else {
//return null; // лучше эксепшн
throw new IllegalArgumentException("Incorrect input name");
}
};
User user = newUser.get();
System.out.println(user);
} catch (IllegalArgumentException e) {
System.err.println(e.getMessage());
}
}
}
| UTF-8 | Java | 906 | java | LambdaUserMain.java | Java | [] | null | [] | package hw_12.task_4;
import java.util.Scanner;
import java.util.function.Supplier;
import java.util.regex.Pattern;
public class LambdaUserMain {
public static void main(String[] args) {
try {
Supplier<User> newUser = () -> {
Scanner scanner = new Scanner(System.in);
System.out.println("Put in student's name");
String name = scanner.nextLine();
if (name.matches("[a-zA-Z]+")) {
return new User(name);
} else {
//return null; // лучше эксепшн
throw new IllegalArgumentException("Incorrect input name");
}
};
User user = newUser.get();
System.out.println(user);
} catch (IllegalArgumentException e) {
System.err.println(e.getMessage());
}
}
}
| 906 | 0.520134 | 0.516779 | 28 | 30.928572 | 20.542515 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 10 |
bef3e2da705503e01d48757d527896d5dd773dfb | 7,464,653,216,134 | 7fa1347865c232c6f4676be228e57dc368a9710f | /app/src/main/java/edu/wgu/gavin/c196/models/CourseMentor.java | 81bbf21dd21038608135f8ffeba9abc5567ef37f | [] | no_license | gavinwade12/C196 | https://github.com/gavinwade12/C196 | 3ded765380367103d6b5285378be9043af904dd4 | 373a10c15e321d15872c8f8aa543c15cb5de5d17 | refs/heads/master | 2020-03-28T19:43:40.553000 | 2018-09-30T04:40:26 | 2018-09-30T04:40:26 | 149,003,684 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.wgu.gavin.c196.models;
import android.database.Cursor;
import edu.wgu.gavin.c196.data.WGUContract;
public class CourseMentor {
public long id;
public long courseId;
public String name;
public String phoneNumber;
public String emailAddress;
public static CourseMentor fromCursor(Cursor cursor) {
CourseMentor mentor = new CourseMentor();
mentor.id = cursor.getLong(cursor.getColumnIndex(WGUContract.CourseMentors._ID));
mentor.courseId = cursor.getLong(cursor.getColumnIndex(WGUContract.CourseMentors.COURSE_ID));
mentor.name = cursor.getString(cursor.getColumnIndex(WGUContract.CourseMentors.NAME));
mentor.phoneNumber = cursor.getString(cursor.getColumnIndex(WGUContract.CourseMentors.PHONE_NUMBER));
mentor.emailAddress = cursor.getString(cursor.getColumnIndex(WGUContract.CourseMentors.EMAIL_ADDRESS));
return mentor;
}
}
| UTF-8 | Java | 927 | java | CourseMentor.java | Java | [] | null | [] | package edu.wgu.gavin.c196.models;
import android.database.Cursor;
import edu.wgu.gavin.c196.data.WGUContract;
public class CourseMentor {
public long id;
public long courseId;
public String name;
public String phoneNumber;
public String emailAddress;
public static CourseMentor fromCursor(Cursor cursor) {
CourseMentor mentor = new CourseMentor();
mentor.id = cursor.getLong(cursor.getColumnIndex(WGUContract.CourseMentors._ID));
mentor.courseId = cursor.getLong(cursor.getColumnIndex(WGUContract.CourseMentors.COURSE_ID));
mentor.name = cursor.getString(cursor.getColumnIndex(WGUContract.CourseMentors.NAME));
mentor.phoneNumber = cursor.getString(cursor.getColumnIndex(WGUContract.CourseMentors.PHONE_NUMBER));
mentor.emailAddress = cursor.getString(cursor.getColumnIndex(WGUContract.CourseMentors.EMAIL_ADDRESS));
return mentor;
}
}
| 927 | 0.747573 | 0.7411 | 25 | 36.080002 | 36.310791 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 10 |
d87cb372887f7e1bef550aba8ae548b955b6a8cd | 7,464,653,216,627 | 002bb305c109bf89957195cbb5dc2705f6abec5f | /src/main/java/cn/luoweifei/controller/UserController.java | ed6ba09b59fab042a3cc8a195ba19ae6fbe7bd69 | [] | no_license | lwfqw/ssm | https://github.com/lwfqw/ssm | 3eb21f512656537b27c0e2353216412b7066128f | 2535a62ac47e18fe272eec47f042cb89a794185c | refs/heads/master | 2021-05-16T20:43:29.589000 | 2020-03-29T07:45:29 | 2020-03-29T07:45:29 | 250,462,445 | 0 | 0 | null | false | 2020-10-13T20:43:55 | 2020-03-27T06:55:05 | 2020-03-29T07:45:32 | 2020-10-13T20:43:54 | 20,192 | 0 | 0 | 1 | Java | false | false | package cn.luoweifei.controller;
import cn.luoweifei.entity.User;
import cn.luoweifei.service.UserServer;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/qinMing/user")
public class UserController {
@Autowired
UserServer userServer;
public static final Logger loger=Logger.getLogger(UserController.class);
@RequestMapping("/go")
public String go(){return "index";}
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String login(String tel, String password, Model model, HttpServletRequest request){
loger.info("login");
User user=userServer.selectByTel(tel.trim());
loger.info("当前用户:"+user.toString());
model.addAttribute("currUser",user);
if(user.getPassword().equals(password)){
request.getSession().setAttribute("user",user);
return "index";
}
model.addAttribute("msg","账号或密码错误");
return "forword:/qinMing/welcome.jsp";
}
@RequestMapping("/heihei")
public String heiHei(){return "heihei";}
@RequestMapping("/change")
public String change(HttpServletRequest request,Model model){
model.addAttribute("user",request.getSession().getAttribute("user"));
loger.info("change: "+request.getSession().getAttribute("user").toString());
return "change";
}
@RequestMapping("/modify")
public String changed(User user){
loger.info("change user:"+user.toString()+" had"+userServer.update(user));
return "redirect:/qinMing/user/change";
}
}
| UTF-8 | Java | 1,957 | java | UserController.java | Java | [] | null | [] | package cn.luoweifei.controller;
import cn.luoweifei.entity.User;
import cn.luoweifei.service.UserServer;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/qinMing/user")
public class UserController {
@Autowired
UserServer userServer;
public static final Logger loger=Logger.getLogger(UserController.class);
@RequestMapping("/go")
public String go(){return "index";}
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String login(String tel, String password, Model model, HttpServletRequest request){
loger.info("login");
User user=userServer.selectByTel(tel.trim());
loger.info("当前用户:"+user.toString());
model.addAttribute("currUser",user);
if(user.getPassword().equals(password)){
request.getSession().setAttribute("user",user);
return "index";
}
model.addAttribute("msg","账号或密码错误");
return "forword:/qinMing/welcome.jsp";
}
@RequestMapping("/heihei")
public String heiHei(){return "heihei";}
@RequestMapping("/change")
public String change(HttpServletRequest request,Model model){
model.addAttribute("user",request.getSession().getAttribute("user"));
loger.info("change: "+request.getSession().getAttribute("user").toString());
return "change";
}
@RequestMapping("/modify")
public String changed(User user){
loger.info("change user:"+user.toString()+" had"+userServer.update(user));
return "redirect:/qinMing/user/change";
}
}
| 1,957 | 0.711628 | 0.711111 | 49 | 38.489796 | 23.71353 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.755102 | false | false | 10 |
5531e71cc0a414bf3d09f92953976bb7361bbbe5 | 27,900,107,613,320 | cce32174c8d10682bb96cad60e46269cb4cd4ddc | /src/com/syntax/class07/workDay.java | 26eeee0618b1f9bd66a104007d0891b1779b1b6d | [] | no_license | Emanyasin/JavaCava | https://github.com/Emanyasin/JavaCava | 7af2f5369c3aa9985e0178ecfb3a0e693b505496 | 7b6cc06fe5062af9ccb594adc80a017c655ab097 | refs/heads/master | 2021-04-03T14:42:51.085000 | 2020-03-22T15:32:40 | 2020-03-22T15:32:40 | 248,367,868 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.syntax.class07;
public class workDay {
// Create a boolean variable workDay and assign true create int variable day and
// assign it to 1
// As long as it is workDay print “I need a day off” and increase day.
// Once day is 6 print “I do not need a day off any more”
public static void main(String[] args) {
boolean workDay;
int day = 8;
while (day < 6) {
if (day >= 6) {
System.out.println("I do not need a day off any more");
}
System.out.println("I need a day off");
day++;
}
//2nd way
boolean workDay1=true;
int day1=1;
while(workDay1) {
if (day1<6) {
System.out.println("I need a day off");
}else {
System.out.println("I do not need a day off");
workDay1=false;
}
day1++;
}
//USING LOOP
//hello five times
int num1=1;
do {
System.out.println("Hello");
num1++;
}while(num1<=5);
}
}
| WINDOWS-1250 | Java | 952 | java | workDay.java | Java | [] | null | [] | package com.syntax.class07;
public class workDay {
// Create a boolean variable workDay and assign true create int variable day and
// assign it to 1
// As long as it is workDay print “I need a day off” and increase day.
// Once day is 6 print “I do not need a day off any more”
public static void main(String[] args) {
boolean workDay;
int day = 8;
while (day < 6) {
if (day >= 6) {
System.out.println("I do not need a day off any more");
}
System.out.println("I need a day off");
day++;
}
//2nd way
boolean workDay1=true;
int day1=1;
while(workDay1) {
if (day1<6) {
System.out.println("I need a day off");
}else {
System.out.println("I do not need a day off");
workDay1=false;
}
day1++;
}
//USING LOOP
//hello five times
int num1=1;
do {
System.out.println("Hello");
num1++;
}while(num1<=5);
}
}
| 952 | 0.57839 | 0.556144 | 48 | 17.666666 | 19.549438 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.145833 | false | false | 10 |
b75e657298f96dd1bafcb4b3d72d4afea3851781 | 27,900,107,615,086 | e76205b76576ab1944b4f196cab424357121b1de | /jsp-jdbc/src/main/java/idiom/jsp/complex/jdbc/entity/Bookshelf.java | bfdf9f48933bd083952736c96e6d5d543aa5f2f7 | [] | no_license | aerben/idiomatic | https://github.com/aerben/idiomatic | 848f22e4eaa28dfc955d45a806718f91cce6adf9 | 14d2c6eb91af8112f8cf61158c050b01a1fcad89 | refs/heads/master | 2016-09-07T15:19:49.395000 | 2014-02-14T16:30:04 | 2014-02-14T16:30:04 | 16,008,364 | 0 | 1 | null | false | 2014-02-08T11:45:27 | 2014-01-17T18:43:41 | 2014-02-08T11:45:26 | 2014-02-08T11:45:27 | 1,940 | 0 | 0 | 0 | Java | null | null | package idiom.jsp.complex.jdbc.entity;
/**
* Bookshelf entity
*
* @author erben
*/
public class Bookshelf implements Entity {
private long id;
private String name;
private final String location;
public Bookshelf(String location) {
this.location = location;
}
public Bookshelf(long id, String name, String location) {
this.id = id;
this.name = name;
this.location = location;
}
@Override
public long getId() {
return id;
}
@Override
public void setId(long id) {
if (id > -1)
this.id = id;
else throw new IllegalArgumentException("Negative ids are not allowed");
}
public String getName() {
return name;
}
public String getLocation() {
return location;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bookshelf bookshelf = (Bookshelf) o;
if (id != bookshelf.id) return false;
if (location != null ? !location.equals(bookshelf.location) : bookshelf.location != null) return false;
return !(name != null ? !name.equals(bookshelf.name) : bookshelf.name != null);
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
return result;
}
@Override
public String toString() {
return String.format("Bookshelf{id=%d, location='%s'}", id, location);
}
}
| UTF-8 | Java | 1,673 | java | Bookshelf.java | Java | [
{
"context": "dbc.entity;\n\n/**\n * Bookshelf entity\n *\n * @author erben\n */\npublic class Bookshelf implements Entity {\n\n ",
"end": 83,
"score": 0.9609208703041077,
"start": 78,
"tag": "USERNAME",
"value": "erben"
}
] | null | [] | package idiom.jsp.complex.jdbc.entity;
/**
* Bookshelf entity
*
* @author erben
*/
public class Bookshelf implements Entity {
private long id;
private String name;
private final String location;
public Bookshelf(String location) {
this.location = location;
}
public Bookshelf(long id, String name, String location) {
this.id = id;
this.name = name;
this.location = location;
}
@Override
public long getId() {
return id;
}
@Override
public void setId(long id) {
if (id > -1)
this.id = id;
else throw new IllegalArgumentException("Negative ids are not allowed");
}
public String getName() {
return name;
}
public String getLocation() {
return location;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bookshelf bookshelf = (Bookshelf) o;
if (id != bookshelf.id) return false;
if (location != null ? !location.equals(bookshelf.location) : bookshelf.location != null) return false;
return !(name != null ? !name.equals(bookshelf.name) : bookshelf.name != null);
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
return result;
}
@Override
public String toString() {
return String.format("Bookshelf{id=%d, location='%s'}", id, location);
}
}
| 1,673 | 0.57621 | 0.570831 | 71 | 22.563381 | 24.668924 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.43662 | false | false | 10 |
4c8a00123272972d16f5b887b1069c0e1aebc6b9 | 21,019,569,952,163 | ca030864a3a1c24be6b9d1802c2353da4ca0d441 | /classes2.dex_source_from_JADX/com/facebook/katana/urimap/Fb4aComponentHelperFactory.java | 978e8c639a12ea3b239eb0a1bc67552ee5803ea8 | [] | no_license | pxson001/facebook-app | https://github.com/pxson001/facebook-app | 87aa51e29195eeaae69adeb30219547f83a5b7b1 | 640630f078980f9818049625ebc42569c67c69f7 | refs/heads/master | 2020-04-07T20:36:45.758000 | 2018-03-07T09:04:57 | 2018-03-07T09:04:57 | 124,208,458 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook.katana.urimap;
import com.facebook.common.errorreporting.AbstractFbErrorReporter;
import com.facebook.common.errorreporting.FbErrorReporterImpl;
import com.facebook.common.fragmentconstants.FragmentConstants;
import com.facebook.common.fragmentconstants.FragmentConstants$ContentFragmentType;
import com.facebook.common.stringformat.StringFormatUtil;
import com.facebook.crudolib.urimap.runtime.ComponentHelper;
import com.facebook.inject.IdBasedProvider;
import com.facebook.inject.InjectorLike;
import com.facebook.proxygen.HTTPTransportCallback;
import com.facebook.timeline.TimelineUriMapHelper;
import com.facebook.video.livemap.LiveMapUriMapHelper;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
/* compiled from: shutdown */
public class Fb4aComponentHelperFactory {
private static volatile Fb4aComponentHelperFactory f4849e;
private final LiveMapUriMapHelper f4850a;
private final AbstractFbErrorReporter f4851b;
public final PaymentSettingsPickerScreenActivityComponentHelper f4852c;
public final TimelineUriMapHelper f4853d;
public static com.facebook.katana.urimap.Fb4aComponentHelperFactory m8684a(@javax.annotation.Nullable com.facebook.inject.InjectorLike r5) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.JadxRuntimeException: Can't find immediate dominator for block B:24:0x003b in {17, 19, 21, 23, 26, 28} preds:[]
at jadx.core.dex.visitors.blocksmaker.BlockProcessor.computeDominators(BlockProcessor.java:129)
at jadx.core.dex.visitors.blocksmaker.BlockProcessor.processBlocksTree(BlockProcessor.java:48)
at jadx.core.dex.visitors.blocksmaker.BlockProcessor.rerun(BlockProcessor.java:44)
at jadx.core.dex.visitors.blocksmaker.BlockFinallyExtract.visit(BlockFinallyExtract.java:57)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:31)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:17)
at jadx.core.ProcessClass.process(ProcessClass.java:37)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:306)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:199)
*/
/*
r0 = f4849e;
if (r0 != 0) goto L_0x0032;
L_0x0004:
r1 = com.facebook.katana.urimap.Fb4aComponentHelperFactory.class;
monitor-enter(r1);
r0 = f4849e; Catch:{ all -> 0x003a }
if (r0 != 0) goto L_0x0031; Catch:{ all -> 0x003a }
L_0x000b:
if (r5 == 0) goto L_0x0031; Catch:{ all -> 0x003a }
L_0x000d:
r2 = com.facebook.inject.ScopeSet.m1499a(); Catch:{ all -> 0x003a }
r3 = r2.m1503b(); Catch:{ all -> 0x003a }
r0 = com.facebook.inject.SingletonScope.class; Catch:{ all -> 0x003a }
r0 = r5.getInstance(r0); Catch:{ all -> 0x003a }
r0 = (com.facebook.inject.SingletonScope) r0; Catch:{ all -> 0x003a }
r4 = r0.enterScope(); Catch:{ all -> 0x003a }
r0 = r5.getApplicationInjector(); Catch:{ all -> 0x0035 }
r0 = m8685b(r0); Catch:{ all -> 0x0035 }
f4849e = r0; Catch:{ all -> 0x0035 }
com.facebook.inject.SingletonScope.m1338a(r4);
r2.m1505c(r3);
L_0x0031:
monitor-exit(r1); Catch:{ }
L_0x0032:
r0 = f4849e;
return r0;
L_0x0035:
r0 = move-exception;
com.facebook.inject.SingletonScope.m1338a(r4); Catch:{ all -> 0x0035 }
throw r0; Catch:{ all -> 0x0035 }
L_0x003a:
r0 = move-exception;
r2.m1505c(r3); Catch:{ all -> 0x003a }
throw r0; Catch:{ all -> 0x003a }
L_0x003f:
r0 = move-exception;
monitor-exit(r1); Catch:{ all -> 0x003a }
throw r0;
*/
throw new UnsupportedOperationException("Method not decompiled: com.facebook.katana.urimap.Fb4aComponentHelperFactory.a(com.facebook.inject.InjectorLike):com.facebook.katana.urimap.Fb4aComponentHelperFactory");
}
private static Fb4aComponentHelperFactory m8685b(InjectorLike injectorLike) {
return new Fb4aComponentHelperFactory(FbErrorReporterImpl.m2317a(injectorLike), new LiveMapUriMapHelper(), PaymentSettingsPickerScreenActivityComponentHelper.m8690a(injectorLike), new TimelineUriMapHelper(IdBasedProvider.m1811a(injectorLike, 4245), IdBasedProvider.m1811a(injectorLike, 4442)));
}
@Inject
public Fb4aComponentHelperFactory(AbstractFbErrorReporter abstractFbErrorReporter, LiveMapUriMapHelper liveMapUriMapHelper, PaymentSettingsPickerScreenActivityComponentHelper paymentSettingsPickerScreenActivityComponentHelper, TimelineUriMapHelper timelineUriMapHelper) {
this.f4851b = abstractFbErrorReporter;
this.f4850a = liveMapUriMapHelper;
this.f4852c = paymentSettingsPickerScreenActivityComponentHelper;
this.f4853d = timelineUriMapHelper;
}
@Nullable
public final ComponentHelper m8686a(int i) {
FragmentConstants$ContentFragmentType a = FragmentConstants.a(i);
if (a == null) {
this.f4851b.m2350b("Fb4aComponentHelperFactory", StringFormatUtil.formatStrLocaleSafe("No fragment type for fragmentId = %d", Integer.valueOf(i)));
return null;
}
switch (1.a[a.ordinal()]) {
case HTTPTransportCallback.FIRST_HEADER_BYTE_FLUSHED /*1*/:
case HTTPTransportCallback.FIRST_BODY_BYTE_FLUSHED /*2*/:
case 3:
return this.f4853d;
case HTTPTransportCallback.LAST_BODY_BYTE_FLUSHED /*4*/:
return this.f4850a;
default:
return null;
}
}
}
| UTF-8 | Java | 5,786 | java | Fb4aComponentHelperFactory.java | Java | [] | null | [] | package com.facebook.katana.urimap;
import com.facebook.common.errorreporting.AbstractFbErrorReporter;
import com.facebook.common.errorreporting.FbErrorReporterImpl;
import com.facebook.common.fragmentconstants.FragmentConstants;
import com.facebook.common.fragmentconstants.FragmentConstants$ContentFragmentType;
import com.facebook.common.stringformat.StringFormatUtil;
import com.facebook.crudolib.urimap.runtime.ComponentHelper;
import com.facebook.inject.IdBasedProvider;
import com.facebook.inject.InjectorLike;
import com.facebook.proxygen.HTTPTransportCallback;
import com.facebook.timeline.TimelineUriMapHelper;
import com.facebook.video.livemap.LiveMapUriMapHelper;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
/* compiled from: shutdown */
public class Fb4aComponentHelperFactory {
private static volatile Fb4aComponentHelperFactory f4849e;
private final LiveMapUriMapHelper f4850a;
private final AbstractFbErrorReporter f4851b;
public final PaymentSettingsPickerScreenActivityComponentHelper f4852c;
public final TimelineUriMapHelper f4853d;
public static com.facebook.katana.urimap.Fb4aComponentHelperFactory m8684a(@javax.annotation.Nullable com.facebook.inject.InjectorLike r5) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.JadxRuntimeException: Can't find immediate dominator for block B:24:0x003b in {17, 19, 21, 23, 26, 28} preds:[]
at jadx.core.dex.visitors.blocksmaker.BlockProcessor.computeDominators(BlockProcessor.java:129)
at jadx.core.dex.visitors.blocksmaker.BlockProcessor.processBlocksTree(BlockProcessor.java:48)
at jadx.core.dex.visitors.blocksmaker.BlockProcessor.rerun(BlockProcessor.java:44)
at jadx.core.dex.visitors.blocksmaker.BlockFinallyExtract.visit(BlockFinallyExtract.java:57)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:31)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:17)
at jadx.core.ProcessClass.process(ProcessClass.java:37)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:306)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:199)
*/
/*
r0 = f4849e;
if (r0 != 0) goto L_0x0032;
L_0x0004:
r1 = com.facebook.katana.urimap.Fb4aComponentHelperFactory.class;
monitor-enter(r1);
r0 = f4849e; Catch:{ all -> 0x003a }
if (r0 != 0) goto L_0x0031; Catch:{ all -> 0x003a }
L_0x000b:
if (r5 == 0) goto L_0x0031; Catch:{ all -> 0x003a }
L_0x000d:
r2 = com.facebook.inject.ScopeSet.m1499a(); Catch:{ all -> 0x003a }
r3 = r2.m1503b(); Catch:{ all -> 0x003a }
r0 = com.facebook.inject.SingletonScope.class; Catch:{ all -> 0x003a }
r0 = r5.getInstance(r0); Catch:{ all -> 0x003a }
r0 = (com.facebook.inject.SingletonScope) r0; Catch:{ all -> 0x003a }
r4 = r0.enterScope(); Catch:{ all -> 0x003a }
r0 = r5.getApplicationInjector(); Catch:{ all -> 0x0035 }
r0 = m8685b(r0); Catch:{ all -> 0x0035 }
f4849e = r0; Catch:{ all -> 0x0035 }
com.facebook.inject.SingletonScope.m1338a(r4);
r2.m1505c(r3);
L_0x0031:
monitor-exit(r1); Catch:{ }
L_0x0032:
r0 = f4849e;
return r0;
L_0x0035:
r0 = move-exception;
com.facebook.inject.SingletonScope.m1338a(r4); Catch:{ all -> 0x0035 }
throw r0; Catch:{ all -> 0x0035 }
L_0x003a:
r0 = move-exception;
r2.m1505c(r3); Catch:{ all -> 0x003a }
throw r0; Catch:{ all -> 0x003a }
L_0x003f:
r0 = move-exception;
monitor-exit(r1); Catch:{ all -> 0x003a }
throw r0;
*/
throw new UnsupportedOperationException("Method not decompiled: com.facebook.katana.urimap.Fb4aComponentHelperFactory.a(com.facebook.inject.InjectorLike):com.facebook.katana.urimap.Fb4aComponentHelperFactory");
}
private static Fb4aComponentHelperFactory m8685b(InjectorLike injectorLike) {
return new Fb4aComponentHelperFactory(FbErrorReporterImpl.m2317a(injectorLike), new LiveMapUriMapHelper(), PaymentSettingsPickerScreenActivityComponentHelper.m8690a(injectorLike), new TimelineUriMapHelper(IdBasedProvider.m1811a(injectorLike, 4245), IdBasedProvider.m1811a(injectorLike, 4442)));
}
@Inject
public Fb4aComponentHelperFactory(AbstractFbErrorReporter abstractFbErrorReporter, LiveMapUriMapHelper liveMapUriMapHelper, PaymentSettingsPickerScreenActivityComponentHelper paymentSettingsPickerScreenActivityComponentHelper, TimelineUriMapHelper timelineUriMapHelper) {
this.f4851b = abstractFbErrorReporter;
this.f4850a = liveMapUriMapHelper;
this.f4852c = paymentSettingsPickerScreenActivityComponentHelper;
this.f4853d = timelineUriMapHelper;
}
@Nullable
public final ComponentHelper m8686a(int i) {
FragmentConstants$ContentFragmentType a = FragmentConstants.a(i);
if (a == null) {
this.f4851b.m2350b("Fb4aComponentHelperFactory", StringFormatUtil.formatStrLocaleSafe("No fragment type for fragmentId = %d", Integer.valueOf(i)));
return null;
}
switch (1.a[a.ordinal()]) {
case HTTPTransportCallback.FIRST_HEADER_BYTE_FLUSHED /*1*/:
case HTTPTransportCallback.FIRST_BODY_BYTE_FLUSHED /*2*/:
case 3:
return this.f4853d;
case HTTPTransportCallback.LAST_BODY_BYTE_FLUSHED /*4*/:
return this.f4850a;
default:
return null;
}
}
}
| 5,786 | 0.720705 | 0.658486 | 117 | 48.452991 | 46.826374 | 302 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.923077 | false | false | 10 |
a0a06cdf23fde18a6d9e192403bc48542c982d81 | 31,911,607,016,224 | f1212cc702a31059df1f4b9f026ab92f1effcd73 | /src/main/java/com/scut/indoorLocation/mapper/AccessPointMapper.java | f043244604f444d8467bb0b508d0869ca6f89986 | [] | no_license | MMMMMMMingor/indoor_location_backend | https://github.com/MMMMMMMingor/indoor_location_backend | 449014006ba4fdd7c23c4d7cffabe7ca43c83932 | b5e0bb378c4f8c48d5c707bf3f866fdc5cbdfa85 | refs/heads/master | 2022-06-29T13:10:49.427000 | 2020-04-21T11:19:08 | 2020-04-21T11:19:08 | 249,469,775 | 6 | 0 | null | false | 2022-06-17T03:03:20 | 2020-03-23T15:31:17 | 2022-05-09T01:59:31 | 2022-06-17T03:03:20 | 246 | 6 | 0 | 1 | Java | false | false | package com.scut.indoorLocation.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.scut.indoorLocation.entity.AccessPoint;
/**
* Created by Mingor on 2020/2/18 20:26
*/
public interface AccessPointMapper extends BaseMapper<AccessPoint> {
}
| UTF-8 | Java | 268 | java | AccessPointMapper.java | Java | [
{
"context": "oorLocation.entity.AccessPoint;\n\n/**\n * Created by Mingor on 2020/2/18 20:26\n */\npublic interface AccessPoi",
"end": 173,
"score": 0.9983797669410706,
"start": 167,
"tag": "USERNAME",
"value": "Mingor"
}
] | null | [] | package com.scut.indoorLocation.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.scut.indoorLocation.entity.AccessPoint;
/**
* Created by Mingor on 2020/2/18 20:26
*/
public interface AccessPointMapper extends BaseMapper<AccessPoint> {
}
| 268 | 0.798507 | 0.757463 | 10 | 25.799999 | 25.6 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 10 |
3988e16ffd2e5741e55d9c44ffe9ab501913344a | 21,079,699,523,216 | 225011bbc304c541f0170ef5b7ba09b967885e95 | /com/vungle/publisher/kp.java | b9f65312fa096d4deb983ccb84f2e4192363ac2c | [] | no_license | sebaudracco/bubble | https://github.com/sebaudracco/bubble | 66536da5367f945ca3318fecc4a5f2e68c1df7ee | e282cda009dfc9422594b05c63e15f443ef093dc | refs/heads/master | 2023-08-25T09:32:04.599000 | 2018-08-14T15:27:23 | 2018-08-14T15:27:23 | 140,444,001 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vungle.publisher;
import com.vungle.publisher.ki.a;
import dagger.MembersInjector;
import dagger.internal.Factory;
import dagger.internal.MembersInjectors;
/* compiled from: vungle */
public final class kp implements Factory<a> {
static final /* synthetic */ boolean f10635a = (!kp.class.desiredAssertionStatus());
private final MembersInjector<a> f10636b;
public /* synthetic */ Object get() {
return m13583a();
}
public kp(MembersInjector<a> membersInjector) {
if (f10635a || membersInjector != null) {
this.f10636b = membersInjector;
return;
}
throw new AssertionError();
}
public a m13583a() {
return (a) MembersInjectors.injectMembers(this.f10636b, new a());
}
public static Factory<a> m13582a(MembersInjector<a> membersInjector) {
return new kp(membersInjector);
}
}
| UTF-8 | Java | 903 | java | kp.java | Java | [] | null | [] | package com.vungle.publisher;
import com.vungle.publisher.ki.a;
import dagger.MembersInjector;
import dagger.internal.Factory;
import dagger.internal.MembersInjectors;
/* compiled from: vungle */
public final class kp implements Factory<a> {
static final /* synthetic */ boolean f10635a = (!kp.class.desiredAssertionStatus());
private final MembersInjector<a> f10636b;
public /* synthetic */ Object get() {
return m13583a();
}
public kp(MembersInjector<a> membersInjector) {
if (f10635a || membersInjector != null) {
this.f10636b = membersInjector;
return;
}
throw new AssertionError();
}
public a m13583a() {
return (a) MembersInjectors.injectMembers(this.f10636b, new a());
}
public static Factory<a> m13582a(MembersInjector<a> membersInjector) {
return new kp(membersInjector);
}
}
| 903 | 0.665559 | 0.621262 | 32 | 27.21875 | 23.739122 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 10 |
a25190b94d4cb332685a655f8f30badb0ba30343 | 21,174,188,809,899 | 884d214faecc7378c8c803fd2327fca5d7733e58 | /src/sortingalgorithmsimulator/Client.java | 5742616aed0345749161044b2339c0dde57dc428 | [] | no_license | pranto47/Sorting-Algorithm-Simulator | https://github.com/pranto47/Sorting-Algorithm-Simulator | 16554bf4c3be88b7295f3d408324c4373175e583 | 4b4687900222f71e86dbc7d10d9d399382c90dd6 | refs/heads/main | 2023-02-21T18:05:17.712000 | 2021-01-26T17:03:50 | 2021-01-26T17:03:50 | 333,152,667 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sortingalgorithmsimulator;
import java.awt.HeadlessException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javax.swing.JOptionPane;
class ReadThread1 extends ClassLoader implements Runnable {
private Thread thread1;
private DataInputStream in;
boolean receive=true;
String sortName;
public ReadThread1(DataInputStream in,String sortName) {
this.sortName=sortName;
this.in=in;
this.thread1 = new Thread(this);
thread1.start();
}
public void findClass(byte [][] classData,String []classNames) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
new JFXPanel();
Platform.runLater(new Runnable() {
@Override
public void run() {
Class res=null;
Class resinner=null;
Class resinner1=null;
Class resinner2=null;
int length=classNames.length;
switch (length) {
case 1:
res = defineClass(classData[0], 0, classData[0].length);
break;
case 2:
res = defineClass( classData[0], 0, classData[0].length);
resinner = defineClass(classData[1], 0, classData[1].length);
break;
case 3:
res = defineClass( classData[0], 0, classData[0].length);
resinner = defineClass( classData[1], 0, classData[1].length);
resinner1 = defineClass(classData[2], 0, classData[2].length);
break;
case 4:
res = defineClass( classData[0], 0, classData[0].length);
resinner = defineClass(classData[1], 0, classData[1].length);
resinner1 = defineClass(classData[2], 0, classData[2].length);
resinner2 = defineClass(classData[3], 0, classData[3].length);
break;
default:
break;
}
try {
res.getMethod("start").invoke(res.newInstance());
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
}
}
});
}
public void createfile(byte[][] classdata, String[] classNames) throws FileNotFoundException, IOException {
for (int i = 0; i < classNames.length; i++) {
String filename = classNames[i]+"_Data"+".txt";///
File file=new File(filename);
FileOutputStream fi = new FileOutputStream(file);
fi.write(classdata[i], 0, classdata[i].length);
fi.close();
}
}
@Override
public void run() {
try {
while (receive) {
int len=in.readInt();
byte [] data_name = new byte[len];
in.read(data_name, 0, len);
String names=new String(data_name,"UTF-8");
String [] className=names.split(" ");
int classnumbers = className.length;
byte[][] totalldata =new byte[classnumbers][];
for (int i = 0; i < className.length; i++) {
int length = in.readInt();
totalldata [i] = new byte[length];
in.readFully(totalldata[i], 0, length);
}
if(len==0){
JOptionPane.showMessageDialog(null, "Data is Unavailable.Try Later");
} else {
String trim = sortName.trim();
String newtrim = trim + "_Information";
String filename = newtrim + ".txt";////
File f = new File(filename);
if (f.createNewFile()) {
FileWriter filereader = new FileWriter(f);
BufferedWriter buffer = new BufferedWriter(filereader);
buffer.write(names);
buffer.close();
createfile(totalldata, className);
}
findClass(totalldata, className);
}
receive = false;
}
} catch (IOException e) {
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
Logger.getLogger(ReadThread1.class.getName()).log(Level.SEVERE, null, ex);
}
try {
in.close();
} catch (IOException ex) {
System.out.println("Interrupted");
}
}
}
class SimpleClassLoader1 extends ClassLoader{
private Hashtable classes = new Hashtable();
public SimpleClassLoader1() {
}
byte getClassImplFromDataBase(String className)[] {
System.out.println(" >>>>>> Fetching the implementation of "+className);
byte result[];
try {
String filename=className+"_Data.txt";
FileInputStream fi = new FileInputStream(filename);
result = new byte[fi.available()];
fi.read(result);
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void findClass(byte[] [] classData,int length){
new JFXPanel();
Platform.runLater(new Runnable() {
@Override
public void run() {
Class res=null;
Class resinner=null;
Class resinner1=null;
Class resinner2=null;
switch (length) {
case 1:
res = defineClass(classData[0], 0, classData[0].length);
break;
case 2:
res = defineClass( classData[0], 0, classData[0].length);
resinner = defineClass(classData[1], 0, classData[1].length);
break;
case 3:
res = defineClass( classData[0], 0, classData[0].length);
resinner = defineClass( classData[1], 0, classData[1].length);
resinner1 = defineClass(classData[2], 0, classData[2].length);
break;
case 4:
res = defineClass( classData[0], 0, classData[0].length);
resinner = defineClass(classData[1], 0, classData[1].length);
resinner1 = defineClass(classData[2], 0, classData[2].length);
resinner2 = defineClass(classData[3], 0, classData[3].length);
break;
default:
break;
}
try {
res.getMethod("start").invoke(res.newInstance());
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
Logger.getLogger(SimpleClassLoader.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
class WriteThread1 implements Runnable {
private Thread thr;
DataOutputStream out;
private boolean sendMessage=true;
String sortName;
public WriteThread1(DataOutputStream out,String sortName) {
this.sortName=sortName;
this.out=out;
this.thr = new Thread(this);
thr.start();
}
@Override
public void run() {
try {
while (true) {
if(sendMessage){
out.write(sortName.getBytes());
sendMessage=false;
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
try {
out.close();
} catch (IOException ex) {
System.out.println("Interrupted");
}
}
}
public class Client {
String sortName;
String serveraddress;
Client(String sortName,String serveraddress){
this.sortName=sortName;
this.serveraddress=serveraddress;
}
public void start() {
try {
String trim = sortName.trim();
String newtrim=trim+"_Information";
String filename = newtrim+".txt";///
File f = new File(filename);
if((f.exists())){
FileReader filereader = new FileReader(f);
BufferedReader buffer = new BufferedReader(filereader);
String names=buffer.readLine();
String [] classnames=names.split(" ");
int length=classnames.length;
byte[][] totalldata = new byte[length][];
SimpleClassLoader1 ob=new SimpleClassLoader1 ();
for (int i = 0; i <length; i++) {
totalldata[i] =ob.getClassImplFromDataBase(classnames[i]);
}
buffer.close();
ob.findClass(totalldata, length);
System.out.println("Data Exist");
}
else {
System.out.println("Data doesn't exist");
JOptionPane.showMessageDialog(null, "File does not exist.Load it from server.");
int serverPort = 33333;
Socket clientSock = new Socket(serveraddress, serverPort);
DataInputStream in = new DataInputStream(clientSock.getInputStream());
DataOutputStream out = new DataOutputStream(clientSock.getOutputStream());
ReadThread1 readThread = new ReadThread1(in, sortName);
WriteThread1 writeThread = new WriteThread1(out, sortName);
}
} catch (IOException | HeadlessException e) {
System.out.println(e);
}
}
}
| UTF-8 | Java | 11,284 | java | Client.java | Java | [] | null | [] | package sortingalgorithmsimulator;
import java.awt.HeadlessException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javax.swing.JOptionPane;
class ReadThread1 extends ClassLoader implements Runnable {
private Thread thread1;
private DataInputStream in;
boolean receive=true;
String sortName;
public ReadThread1(DataInputStream in,String sortName) {
this.sortName=sortName;
this.in=in;
this.thread1 = new Thread(this);
thread1.start();
}
public void findClass(byte [][] classData,String []classNames) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
new JFXPanel();
Platform.runLater(new Runnable() {
@Override
public void run() {
Class res=null;
Class resinner=null;
Class resinner1=null;
Class resinner2=null;
int length=classNames.length;
switch (length) {
case 1:
res = defineClass(classData[0], 0, classData[0].length);
break;
case 2:
res = defineClass( classData[0], 0, classData[0].length);
resinner = defineClass(classData[1], 0, classData[1].length);
break;
case 3:
res = defineClass( classData[0], 0, classData[0].length);
resinner = defineClass( classData[1], 0, classData[1].length);
resinner1 = defineClass(classData[2], 0, classData[2].length);
break;
case 4:
res = defineClass( classData[0], 0, classData[0].length);
resinner = defineClass(classData[1], 0, classData[1].length);
resinner1 = defineClass(classData[2], 0, classData[2].length);
resinner2 = defineClass(classData[3], 0, classData[3].length);
break;
default:
break;
}
try {
res.getMethod("start").invoke(res.newInstance());
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
}
}
});
}
public void createfile(byte[][] classdata, String[] classNames) throws FileNotFoundException, IOException {
for (int i = 0; i < classNames.length; i++) {
String filename = classNames[i]+"_Data"+".txt";///
File file=new File(filename);
FileOutputStream fi = new FileOutputStream(file);
fi.write(classdata[i], 0, classdata[i].length);
fi.close();
}
}
@Override
public void run() {
try {
while (receive) {
int len=in.readInt();
byte [] data_name = new byte[len];
in.read(data_name, 0, len);
String names=new String(data_name,"UTF-8");
String [] className=names.split(" ");
int classnumbers = className.length;
byte[][] totalldata =new byte[classnumbers][];
for (int i = 0; i < className.length; i++) {
int length = in.readInt();
totalldata [i] = new byte[length];
in.readFully(totalldata[i], 0, length);
}
if(len==0){
JOptionPane.showMessageDialog(null, "Data is Unavailable.Try Later");
} else {
String trim = sortName.trim();
String newtrim = trim + "_Information";
String filename = newtrim + ".txt";////
File f = new File(filename);
if (f.createNewFile()) {
FileWriter filereader = new FileWriter(f);
BufferedWriter buffer = new BufferedWriter(filereader);
buffer.write(names);
buffer.close();
createfile(totalldata, className);
}
findClass(totalldata, className);
}
receive = false;
}
} catch (IOException e) {
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
Logger.getLogger(ReadThread1.class.getName()).log(Level.SEVERE, null, ex);
}
try {
in.close();
} catch (IOException ex) {
System.out.println("Interrupted");
}
}
}
class SimpleClassLoader1 extends ClassLoader{
private Hashtable classes = new Hashtable();
public SimpleClassLoader1() {
}
byte getClassImplFromDataBase(String className)[] {
System.out.println(" >>>>>> Fetching the implementation of "+className);
byte result[];
try {
String filename=className+"_Data.txt";
FileInputStream fi = new FileInputStream(filename);
result = new byte[fi.available()];
fi.read(result);
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void findClass(byte[] [] classData,int length){
new JFXPanel();
Platform.runLater(new Runnable() {
@Override
public void run() {
Class res=null;
Class resinner=null;
Class resinner1=null;
Class resinner2=null;
switch (length) {
case 1:
res = defineClass(classData[0], 0, classData[0].length);
break;
case 2:
res = defineClass( classData[0], 0, classData[0].length);
resinner = defineClass(classData[1], 0, classData[1].length);
break;
case 3:
res = defineClass( classData[0], 0, classData[0].length);
resinner = defineClass( classData[1], 0, classData[1].length);
resinner1 = defineClass(classData[2], 0, classData[2].length);
break;
case 4:
res = defineClass( classData[0], 0, classData[0].length);
resinner = defineClass(classData[1], 0, classData[1].length);
resinner1 = defineClass(classData[2], 0, classData[2].length);
resinner2 = defineClass(classData[3], 0, classData[3].length);
break;
default:
break;
}
try {
res.getMethod("start").invoke(res.newInstance());
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
Logger.getLogger(SimpleClassLoader.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
class WriteThread1 implements Runnable {
private Thread thr;
DataOutputStream out;
private boolean sendMessage=true;
String sortName;
public WriteThread1(DataOutputStream out,String sortName) {
this.sortName=sortName;
this.out=out;
this.thr = new Thread(this);
thr.start();
}
@Override
public void run() {
try {
while (true) {
if(sendMessage){
out.write(sortName.getBytes());
sendMessage=false;
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
try {
out.close();
} catch (IOException ex) {
System.out.println("Interrupted");
}
}
}
public class Client {
String sortName;
String serveraddress;
Client(String sortName,String serveraddress){
this.sortName=sortName;
this.serveraddress=serveraddress;
}
public void start() {
try {
String trim = sortName.trim();
String newtrim=trim+"_Information";
String filename = newtrim+".txt";///
File f = new File(filename);
if((f.exists())){
FileReader filereader = new FileReader(f);
BufferedReader buffer = new BufferedReader(filereader);
String names=buffer.readLine();
String [] classnames=names.split(" ");
int length=classnames.length;
byte[][] totalldata = new byte[length][];
SimpleClassLoader1 ob=new SimpleClassLoader1 ();
for (int i = 0; i <length; i++) {
totalldata[i] =ob.getClassImplFromDataBase(classnames[i]);
}
buffer.close();
ob.findClass(totalldata, length);
System.out.println("Data Exist");
}
else {
System.out.println("Data doesn't exist");
JOptionPane.showMessageDialog(null, "File does not exist.Load it from server.");
int serverPort = 33333;
Socket clientSock = new Socket(serveraddress, serverPort);
DataInputStream in = new DataInputStream(clientSock.getInputStream());
DataOutputStream out = new DataOutputStream(clientSock.getOutputStream());
ReadThread1 readThread = new ReadThread1(in, sortName);
WriteThread1 writeThread = new WriteThread1(out, sortName);
}
} catch (IOException | HeadlessException e) {
System.out.println(e);
}
}
}
| 11,284 | 0.509926 | 0.500443 | 286 | 37.454544 | 29.718075 | 198 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.909091 | false | false | 10 |
c76b79a83fa941fec783791a70d5b6ef66ef6d8c | 22,247,930,599,871 | c69b09fe89c06e1d83ae8c1d87a46678288d0eda | /solon/src/main/java/org/noear/solon/core/Props.java | add4fb0891787543227b4a1f88b01c8d46d78936 | [
"Apache-2.0"
] | permissive | dongatsh/solon | https://github.com/dongatsh/solon | fb9d3da2ce67746dd8cfe1fef288e2de1bc3d1a2 | 4c3a074e8e4db7f367f75603ea8347d2c501c69d | refs/heads/master | 2023-08-28T18:16:44.023000 | 2021-10-31T16:21:03 | 2021-10-31T16:21:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.noear.solon.core;
import org.noear.solon.SolonProps;
import org.noear.solon.Utils;
import org.noear.solon.core.wrap.ClassWrap;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.function.BiConsumer;
import java.util.function.Function;
/**
* 通用属性集合(为 SolonProperties 的基类)
*
* 在 Properties 基础上,添加了些方法
*
* @see SolonProps
* @author noear
* @since 1.0
* */
public class Props extends Properties {
public Props() {
super();
}
public Props(Properties defaults) {
super(defaults);
}
/**
* 获取某项配置
*/
public String get(String key) {
return getProperty(key);
}
/**
* @param expr 兼容 ${key} or key
*/
public String getByExpr(String expr) {
String name = expr;
if (name.startsWith("${") && name.endsWith("}")) {
name = expr.substring(2, name.length() - 1);
}
return get(name);
}
public String getByParse(String expr) {
if (Utils.isEmpty(expr)) {
return expr;
}
int start = expr.indexOf("${");
if (start < 0) {
return expr;
} else {
int end = expr.indexOf("}");
String name = expr.substring(start + 2, end);
String value = get(name);
return expr.substring(0, start) + value + expr.substring(end + 1);
}
}
/**
* 获取某项配置(如果没有,输出默认值)
*
* @param def 默认值
*/
public String get(String key, String def) {
return getProperty(key, def);
}
/**
* 获取某项配置,并转为布尔型(如果没有,输出默认值)
*
* @param def 默认值
*/
public boolean getBool(String key, boolean def) {
return getOrDef(key, def, Boolean::parseBoolean);
}
/**
* 获取某项配置,并转为整型(如果没有,输出默认值)
*
* @param def 默认值
*/
public int getInt(String key, int def) {
return getOrDef(key, def, Integer::parseInt);
}
/**
* 获取某项配置,并转为长整型(如果没有,输出默认值)
*
* @param def 默认值
*/
public long getLong(String key, long def) {
return getOrDef(key, def, Long::parseLong);
}
/**
* 获取某项配置,并转为又精度型(如果没有,输出默认值)
*
* @param def 默认值
*/
public Double getDouble(String key, double def) {
return getOrDef(key, def, Double::parseDouble);
}
private <T> T getOrDef(String key, T def, Function<String, T> convert) {
String temp = get(key);
if (Utils.isEmpty(temp)) {
return def;
} else {
return convert.apply(temp);
}
}
/**
* 查找 keyStarts 开头的所有配置;并生成一个新的 Bean
*
* @param keyStarts key 的开始字符
*/
public <T> T getBean(String keyStarts, Class<T> type) {
return ClassWrap.get(type).newBy(getProp(keyStarts));
}
/**
* 查找 keyStarts 开头的所有配置;并生成一个新的 配置集
*
* @param keyStarts key 的开始字符
*/
public Props getProp(String keyStarts) {
Props prop = new Props();
doFind(keyStarts + ".", prop::put);
return prop;
}
/**
* @param expr 兼容 ${key} or key
*/
public Props getPropByExpr(String expr) {
String name = expr;
if (name.startsWith("${") && name.endsWith("}")) {
name = expr.substring(2, name.length() - 1);
}
return getProp(name);
}
/**
* 查找 keyStarts 开头的所有配置;并生成一个新的 Map
*
* @param keyStarts key 的开始字符
*/
public NvMap getXmap(String keyStarts) {
NvMap map = new NvMap();
doFind(keyStarts + ".", map::put);
return map;
}
public List<String> getList(String keyStarts) {
List<String> ary = new ArrayList<>();
doFind(keyStarts + "[", (k, v) -> {
ary.add(v);
});
return ary;
}
private void doFind(String keyStarts, BiConsumer<String, String> setFun) {
String key2 = keyStarts;
int idx2 = key2.length();
forEach((k, v) -> {
if (k instanceof String && v instanceof String) {
String keyStr = (String) k;
if (keyStr.startsWith(key2)) {
String key = keyStr.substring(idx2);
setFun.accept(key, (String) v);
if (key.contains("-")) {
String[] ss = key.split("-");
StringBuilder sb = new StringBuilder(key.length());
sb.append(ss[0]);
for (int i = 1; i < ss.length; i++) {
if (ss[i].length() > 1) {
sb.append(ss[i].substring(0, 1).toUpperCase()).append(ss[i].substring(1));
} else {
sb.append(ss[i].toUpperCase());
}
}
setFun.accept(sb.toString(), (String) v);
}
}
}
});
}
/**
* 重写 forEach,增加 defaults 的遍历
*/
@Override
public synchronized void forEach(BiConsumer<? super Object, ? super Object> action) {
if (defaults == null) {
super.forEach(action);
} else {
defaults.forEach(action);
super.forEach((k, v) -> {
if (defaults.containsKey(k) == false) {
action.accept(k, v);
}
});
}
}
}
| UTF-8 | Java | 5,931 | java | Props.java | Java | [
{
"context": "erties 基础上,添加了些方法\n *\n * @see SolonProps\n * @author noear\n * @since 1.0\n * */\npublic class Props extends Pr",
"end": 401,
"score": 0.9996472597122192,
"start": 396,
"tag": "USERNAME",
"value": "noear"
}
] | null | [] | package org.noear.solon.core;
import org.noear.solon.SolonProps;
import org.noear.solon.Utils;
import org.noear.solon.core.wrap.ClassWrap;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.function.BiConsumer;
import java.util.function.Function;
/**
* 通用属性集合(为 SolonProperties 的基类)
*
* 在 Properties 基础上,添加了些方法
*
* @see SolonProps
* @author noear
* @since 1.0
* */
public class Props extends Properties {
public Props() {
super();
}
public Props(Properties defaults) {
super(defaults);
}
/**
* 获取某项配置
*/
public String get(String key) {
return getProperty(key);
}
/**
* @param expr 兼容 ${key} or key
*/
public String getByExpr(String expr) {
String name = expr;
if (name.startsWith("${") && name.endsWith("}")) {
name = expr.substring(2, name.length() - 1);
}
return get(name);
}
public String getByParse(String expr) {
if (Utils.isEmpty(expr)) {
return expr;
}
int start = expr.indexOf("${");
if (start < 0) {
return expr;
} else {
int end = expr.indexOf("}");
String name = expr.substring(start + 2, end);
String value = get(name);
return expr.substring(0, start) + value + expr.substring(end + 1);
}
}
/**
* 获取某项配置(如果没有,输出默认值)
*
* @param def 默认值
*/
public String get(String key, String def) {
return getProperty(key, def);
}
/**
* 获取某项配置,并转为布尔型(如果没有,输出默认值)
*
* @param def 默认值
*/
public boolean getBool(String key, boolean def) {
return getOrDef(key, def, Boolean::parseBoolean);
}
/**
* 获取某项配置,并转为整型(如果没有,输出默认值)
*
* @param def 默认值
*/
public int getInt(String key, int def) {
return getOrDef(key, def, Integer::parseInt);
}
/**
* 获取某项配置,并转为长整型(如果没有,输出默认值)
*
* @param def 默认值
*/
public long getLong(String key, long def) {
return getOrDef(key, def, Long::parseLong);
}
/**
* 获取某项配置,并转为又精度型(如果没有,输出默认值)
*
* @param def 默认值
*/
public Double getDouble(String key, double def) {
return getOrDef(key, def, Double::parseDouble);
}
private <T> T getOrDef(String key, T def, Function<String, T> convert) {
String temp = get(key);
if (Utils.isEmpty(temp)) {
return def;
} else {
return convert.apply(temp);
}
}
/**
* 查找 keyStarts 开头的所有配置;并生成一个新的 Bean
*
* @param keyStarts key 的开始字符
*/
public <T> T getBean(String keyStarts, Class<T> type) {
return ClassWrap.get(type).newBy(getProp(keyStarts));
}
/**
* 查找 keyStarts 开头的所有配置;并生成一个新的 配置集
*
* @param keyStarts key 的开始字符
*/
public Props getProp(String keyStarts) {
Props prop = new Props();
doFind(keyStarts + ".", prop::put);
return prop;
}
/**
* @param expr 兼容 ${key} or key
*/
public Props getPropByExpr(String expr) {
String name = expr;
if (name.startsWith("${") && name.endsWith("}")) {
name = expr.substring(2, name.length() - 1);
}
return getProp(name);
}
/**
* 查找 keyStarts 开头的所有配置;并生成一个新的 Map
*
* @param keyStarts key 的开始字符
*/
public NvMap getXmap(String keyStarts) {
NvMap map = new NvMap();
doFind(keyStarts + ".", map::put);
return map;
}
public List<String> getList(String keyStarts) {
List<String> ary = new ArrayList<>();
doFind(keyStarts + "[", (k, v) -> {
ary.add(v);
});
return ary;
}
private void doFind(String keyStarts, BiConsumer<String, String> setFun) {
String key2 = keyStarts;
int idx2 = key2.length();
forEach((k, v) -> {
if (k instanceof String && v instanceof String) {
String keyStr = (String) k;
if (keyStr.startsWith(key2)) {
String key = keyStr.substring(idx2);
setFun.accept(key, (String) v);
if (key.contains("-")) {
String[] ss = key.split("-");
StringBuilder sb = new StringBuilder(key.length());
sb.append(ss[0]);
for (int i = 1; i < ss.length; i++) {
if (ss[i].length() > 1) {
sb.append(ss[i].substring(0, 1).toUpperCase()).append(ss[i].substring(1));
} else {
sb.append(ss[i].toUpperCase());
}
}
setFun.accept(sb.toString(), (String) v);
}
}
}
});
}
/**
* 重写 forEach,增加 defaults 的遍历
*/
@Override
public synchronized void forEach(BiConsumer<? super Object, ? super Object> action) {
if (defaults == null) {
super.forEach(action);
} else {
defaults.forEach(action);
super.forEach((k, v) -> {
if (defaults.containsKey(k) == false) {
action.accept(k, v);
}
});
}
}
}
| 5,931 | 0.498072 | 0.494215 | 219 | 23.863014 | 20.915998 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.442922 | false | false | 10 |
7d01613d6c497bf6e5edc9dec4fd588b1338e69f | 1,108,101,576,474 | 2bbec7d980f35bc6768c1c535b4100c2fdde8201 | /app/src/main/java/com/vpos/amedora/vposmerchant/TransactionListingActivity.java | 7e15cb71111ca1e80917d1c1aaa478457ab320b9 | [] | no_license | runningjack/vposmerchant | https://github.com/runningjack/vposmerchant | 7aeaac86be1bc6e04b84e7e3f5863e9730426603 | 4b0986a2e452755a0d6856caabcb6125062cf8ac | refs/heads/master | 2021-01-10T04:28:48.677000 | 2016-01-03T21:17:53 | 2016-01-03T21:18:28 | 48,961,001 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vpos.amedora.vposmerchant;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.vpos.amedora.vposmerchant.helper.DatabaseHelper;
import com.vpos.amedora.vposmerchant.model.Transaction;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
/**
* Created by Amedora on 8/5/2015.
*/
public class TransactionListingActivity extends AppCompatActivity {
public static String TRANS_ID = "trans_id";
public static String TRANS_ACCOUNT_NO = "account_no";
public static String TRANS_AMOUNT = "amount";
public static String TRANS_DATE = "transdate";
ListView lv ;
DatabaseHelper db = new DatabaseHelper(this);
ArrayList<HashMap<String, String>> transList;
LvAdapter adapter;
protected void onCreate(Bundle savedInstanceBundle){
super.onCreate(savedInstanceBundle);
setContentView(R.layout.activity_transactions);
lv = (ListView)findViewById(R.id.lvtransactions);
transList = new ArrayList<HashMap<String, String>>();
// List<WebSite> siteList = rssDb.getAllSites();
List<Transaction> transactions = db.getAllTransactions();
//sqliteIds = new String[transactions.size()];
// loop through each website
for (int i = 0; i < transactions.size(); i++) {
Transaction s = transactions.get(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
Double amount = new Double(s.getTrans_amount());
NumberFormat numberFormatter;
String amountOut;
numberFormatter = NumberFormat.getNumberInstance(Locale.US);
amountOut = numberFormatter.format(amount);
map.put(TRANS_DATE, String.valueOf(s.getCreated_at()));
map.put(TRANS_ID, String.valueOf(s.getTransId()));
map.put(TRANS_AMOUNT, String.valueOf("₦"+amountOut));
// adding HashList to ArrayList
transList.add(map);
// add sqlite id to array
// used when deleting a website from sqlite
//sqliteIds[i] = String.valueOf(s.getId());
}
/**
* Updating list view with websites
* */
adapter=new LvAdapter(this, transList);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
}
| UTF-8 | Java | 2,849 | java | TransactionListingActivity.java | Java | [
{
"context": ".List;\nimport java.util.Locale;\n\n/**\n * Created by Amedora on 8/5/2015.\n */\npublic class TransactionListingA",
"end": 557,
"score": 0.9825008511543274,
"start": 550,
"tag": "USERNAME",
"value": "Amedora"
}
] | null | [] | package com.vpos.amedora.vposmerchant;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.vpos.amedora.vposmerchant.helper.DatabaseHelper;
import com.vpos.amedora.vposmerchant.model.Transaction;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
/**
* Created by Amedora on 8/5/2015.
*/
public class TransactionListingActivity extends AppCompatActivity {
public static String TRANS_ID = "trans_id";
public static String TRANS_ACCOUNT_NO = "account_no";
public static String TRANS_AMOUNT = "amount";
public static String TRANS_DATE = "transdate";
ListView lv ;
DatabaseHelper db = new DatabaseHelper(this);
ArrayList<HashMap<String, String>> transList;
LvAdapter adapter;
protected void onCreate(Bundle savedInstanceBundle){
super.onCreate(savedInstanceBundle);
setContentView(R.layout.activity_transactions);
lv = (ListView)findViewById(R.id.lvtransactions);
transList = new ArrayList<HashMap<String, String>>();
// List<WebSite> siteList = rssDb.getAllSites();
List<Transaction> transactions = db.getAllTransactions();
//sqliteIds = new String[transactions.size()];
// loop through each website
for (int i = 0; i < transactions.size(); i++) {
Transaction s = transactions.get(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
Double amount = new Double(s.getTrans_amount());
NumberFormat numberFormatter;
String amountOut;
numberFormatter = NumberFormat.getNumberInstance(Locale.US);
amountOut = numberFormatter.format(amount);
map.put(TRANS_DATE, String.valueOf(s.getCreated_at()));
map.put(TRANS_ID, String.valueOf(s.getTransId()));
map.put(TRANS_AMOUNT, String.valueOf("₦"+amountOut));
// adding HashList to ArrayList
transList.add(map);
// add sqlite id to array
// used when deleting a website from sqlite
//sqliteIds[i] = String.valueOf(s.getId());
}
/**
* Updating list view with websites
* */
adapter=new LvAdapter(this, transList);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
}
| 2,849 | 0.657534 | 0.654724 | 88 | 31.352272 | 24.774456 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.659091 | false | false | 10 |
006af75238229c5ad06bf94d11bc73e9cca5d038 | 1,108,101,574,110 | c602a04471f58504908224a6a138ec836a5d77f8 | /KolamRenang.java | 9d67ca192a2de72cda7ea2f409c93f94587a570c | [] | no_license | KevinStefano/Marketplace_System | https://github.com/KevinStefano/Marketplace_System | a8b460a7e26198fa91f89dec6bf2f6290db40222 | c96f821b2fd865c62eb17b45dfc240ca7141bc8b | refs/heads/master | 2022-06-20T10:43:18.782000 | 2020-05-07T15:42:18 | 2020-05-07T15:42:18 | 262,039,997 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class KolamRenang implements Fasilitas {
Properti prop;
public KolamRenang () {
}
@Override
public String getDeskripsi() {
return "Kolam Renang";
}
@Override
public int kalkulasiHarga() {
return 0;
}
} | UTF-8 | Java | 248 | java | KolamRenang.java | Java | [
{
"context": " public String getDeskripsi() {\n return \"Kolam Renang\";\n }\n\n\t@Override\n\tpublic int kalkulasiHarga() ",
"end": 179,
"score": 0.8277977108955383,
"start": 167,
"tag": "NAME",
"value": "Kolam Renang"
}
] | null | [] | public class KolamRenang implements Fasilitas {
Properti prop;
public KolamRenang () {
}
@Override
public String getDeskripsi() {
return "<NAME>";
}
@Override
public int kalkulasiHarga() {
return 0;
}
} | 242 | 0.633065 | 0.629032 | 16 | 14.5625 | 14.216929 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 10 |
cb8823ed1c2d911530d8feda5109f4ee66c0859c | 6,442,451,009,678 | 12803fe7254a09b75d0c0f2d5d3ca69a4596be85 | /DP/src/com/hs/dp/twoD/Triangle.java | c1a19a7ebf764b596f019691236d77f6d687aa02 | [] | no_license | hareramcse/Datastructure | https://github.com/hareramcse/Datastructure | 7b84f4f74cb8a5fde7b0614044251f9d184ef452 | 5a1f425d470184e6f03e5cba3d8d5a8fb8635e47 | refs/heads/master | 2023-04-29T20:47:40.085000 | 2023-04-22T10:08:03 | 2023-04-22T10:08:03 | 155,093,125 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hs.dp.twoD;
import java.util.Arrays;
public class Triangle {
public int minimumTotal(int[][] grid) {
int m = grid.length;
int n = grid.length;
int[][] dp = new int[m][n];
for (int[] row : dp) {
Arrays.fill(row, -1);
}
return solveMemo(0, 0, grid, dp);
}
private int solveMemo(int m, int n, int[][] grid, int[][] dp) {
if (m == grid.length - 1)
return grid[m][n];
if (dp[m][n] != -1)
return dp[m][n];
int down = grid[m][n] + solveMemo(m + 1, n, grid, dp);
int diagonal = grid[m][n] + solveMemo(m + 1, n + 1, grid, dp);
return dp[m][n] = Math.min(down, diagonal);
}
public static void main(String[] args) {
Triangle obj = new Triangle();
int[][] grid = { { 2 }, { 3, 4 }, { 6, 5, 7 }, { 4, 1, 8, 3 } };
int result = obj.minimumTotal(grid);
System.out.println(result);
}
} | UTF-8 | Java | 835 | java | Triangle.java | Java | [] | null | [] | package com.hs.dp.twoD;
import java.util.Arrays;
public class Triangle {
public int minimumTotal(int[][] grid) {
int m = grid.length;
int n = grid.length;
int[][] dp = new int[m][n];
for (int[] row : dp) {
Arrays.fill(row, -1);
}
return solveMemo(0, 0, grid, dp);
}
private int solveMemo(int m, int n, int[][] grid, int[][] dp) {
if (m == grid.length - 1)
return grid[m][n];
if (dp[m][n] != -1)
return dp[m][n];
int down = grid[m][n] + solveMemo(m + 1, n, grid, dp);
int diagonal = grid[m][n] + solveMemo(m + 1, n + 1, grid, dp);
return dp[m][n] = Math.min(down, diagonal);
}
public static void main(String[] args) {
Triangle obj = new Triangle();
int[][] grid = { { 2 }, { 3, 4 }, { 6, 5, 7 }, { 4, 1, 8, 3 } };
int result = obj.minimumTotal(grid);
System.out.println(result);
}
} | 835 | 0.564072 | 0.542515 | 37 | 21.594595 | 20.03977 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.27027 | false | false | 10 |
86855065061556df1fd5ed8389edc060ae4c9d37 | 14,671,608,309,713 | d8d1113b6b3657fa0b686c4c5d83b9cf95e228be | /comevokafka/src/main/java/com/evo/kafka/utils/ConsumerGroupLag.java | a6d0cdc781d80b13e744e591f4fd881e6d1ad304 | [] | no_license | arumugam-ramasamy/algorithms | https://github.com/arumugam-ramasamy/algorithms | a38a818e86f4236574d1929e733acc7464b318bd | 6a9f5c3598e650358d7224acfb8256d8cde95ea0 | refs/heads/master | 2023-08-09T22:10:23.103000 | 2023-01-30T22:33:48 | 2023-01-30T22:33:48 | 155,135,667 | 0 | 0 | null | false | 2023-09-05T22:00:41 | 2018-10-29T01:45:12 | 2022-05-01T16:02:52 | 2023-09-05T22:00:40 | 115,572 | 0 | 0 | 23 | Java | false | false | package com.evo.kafka.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import kafka.admin.AdminClient;
import kafka.admin.AdminClient.ConsumerGroupSummary;
import kafka.admin.AdminClient.ConsumerSummary;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.requests.OffsetFetchResponse.PartitionData;
import java.util.*;
public class ConsumerGroupLag {
private String bootstrapServer;
private String group;
private boolean outputAsJson = false;
private boolean includeStartOffset = false;
private Long groupStabilizationTimeoutMs = 5000L;
private Long waitForResponseTime = 1000L;
public String getBootstrapServer() {
return bootstrapServer;
}
public void setBootstrapServer(String bootstrapServer) {
this.bootstrapServer = bootstrapServer;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public boolean isOutputAsJson() {
return outputAsJson;
}
public void setOutputAsJson(boolean outputAsJson) {
this.outputAsJson = outputAsJson;
}
public boolean isIncludeStartOffset() {
return includeStartOffset;
}
public void setIncludeStartOffset(boolean includeStartOffset) {
this.includeStartOffset = includeStartOffset;
}
public Long getGroupStabilizationTimeoutMs() {
return groupStabilizationTimeoutMs;
}
public void setGroupStabilizationTimeoutMs(Long groupStabilizationTimeoutMs) {
this.groupStabilizationTimeoutMs = groupStabilizationTimeoutMs;
}
public Long getWaitForResponseTime() {
return waitForResponseTime;
}
public void setWaitForResponseTime(Long waitForResponseTime) {
this.waitForResponseTime = waitForResponseTime;
}
public class PartitionState {
public long logStartOffset;
public long logEndOffset;
public int partition;
public Object currentOffset;
public Object lag;
public String consumerId;
public String host;
public String clientId;
}
public List<Long> getOffset () throws JsonProcessingException, OffsetFetchException {
/* String bootstrapServer;
String group;
boolean outputAsJson = false;
boolean includeStartOffset = false;
Long groupStabilizationTimeoutMs = 5000L;
Long waitForResponseTime = 1000L;*/
/* // parse command-line arguments to get bootstrap.servers and group.id
Options options = new Options();
try {
options.addOption(Option.builder("b").longOpt("bootstrap-server").hasArg().argName("bootstrap-server")
.desc("Server to connect to <host:9092>").required().build());
options.addOption(Option.builder("g").longOpt("group").hasArg().argName("group").desc(
"The consumer group we wish to act on").required().build());
options.addOption(Option.builder("J").longOpt("json").argName("outputAsJson").desc(
"Output the data as json").build());
options.addOption(Option.builder("s").longOpt("include-start-offset").argName("includeStartOffset").desc(
"Include log-start-offset (the offset of the first record in a partition)").build());
options.addOption(Option.builder("t").longOpt("group-stabilization-timeout")
.argName("groupStabilizationTimeoutMs")
.desc("time (ms) to wait for the consumer group description to be avaialble (e.g. wait for a consumer group rebalance to complete)")
.build());
options.addOption(Option.builder("w").longOpt("response-wait-time")
.argName("waitForResponseTime")
.desc("time (ms) to wait for asking request response.")
.build());
CommandLine line = new DefaultParser().parse(options, args);
bootstrapServer = line.getOptionValue("bootstrap-server");
group = line.getOptionValue("group");
outputAsJson = line.hasOption("json");
includeStartOffset = line.hasOption("s");
} catch (ParseException ex) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("ConsumerGroupLag", "Consumer Group Lag", options, ex.toString(), true);
throw new RuntimeException("Invalid command line options.");
}
*/
Properties props = new Properties();
props.put("bootstrap.servers", this.getBootstrapServer());
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("group.id", this.getGroup());
Properties props2 = new Properties();
props2.put("bootstrap.servers", this.getBootstrapServer());
AdminClient ac = AdminClient.create(props) ;
/*
* {
* "topic-name" : {
* "partition-number" : {
* "logStartOffset" : ...
* "logEndOffset" : ...
* "partition" : ...
* "currentOffset" : ...
* "lag" : ...
* "consumerId" : ...
* "host" : ...
* "clientId" : ...
* },
* ...
* }
* }
*/
Collection<TopicPartition> c = new ArrayList<TopicPartition>();
ConsumerGroupSummary summary = ac.describeConsumerGroup(this.getGroup(), this.getGroupStabilizationTimeoutMs());
if (summary.state().equals("Dead")) {
System.out.format("Consumer group %s does not exist.", this.getGroup());
System.out.println();
System.exit(1);
}
if (!summary.state().equals("Stable")) {
// PreparingRebalance, AwaitingSync
System.err.format("Warning: Consumer group %s has state %s.", this.getGroup(), summary.state());
System.err.println();
}
scala.collection.immutable.List<ConsumerSummary> scalaList = summary.consumers().get();
List<ConsumerSummary> csList = scala.collection.JavaConversions.seqAsJavaList(scalaList);
if (csList.isEmpty()) {
System.out.format("Consumer group %s is rebalancing.", this.getGroup());
System.out.println();
System.exit(1);
}
Map<TopicPartition, ConsumerSummary> whoOwnsPartition = new HashMap<TopicPartition, ConsumerSummary>();
List<String> topicNamesList = new ArrayList<String>();
for (ConsumerSummary cs : csList) {
scala.collection.immutable.List<TopicPartition> scalaAssignment = cs.assignment();
List<TopicPartition> assignment = scala.collection.JavaConversions.seqAsJavaList(scalaAssignment);
for (TopicPartition tp : assignment) {
whoOwnsPartition.put(tp, cs);
topicNamesList.add(tp.topic());
}
c.addAll(assignment);
}
//Get Per broker topic info based on topic list
TopicPartitionsOffsetInfo topicPartitionsOffsetInfo = new TopicPartitionsOffsetInfo(ac);
topicPartitionsOffsetInfo.storeTopicPartitionPerNodeInfo(props, topicNamesList);
//Get endoffset and BeginningOffsets info for all topics
Map<TopicPartition, Long> endOffsets = topicPartitionsOffsetInfo.getEndOffsets();
Map<TopicPartition, Long> beginningOffsets = topicPartitionsOffsetInfo.getBeginningOffsets();
//Get commited offset info
topicPartitionsOffsetInfo.findCoordinatorNodeForGroup(this.getGroup(), this.getWaitForResponseTime());
Map<TopicPartition, PartitionData> commitedOffsets = topicPartitionsOffsetInfo.getCommitedOffsets(this.getGroup(), (
List<TopicPartition>) c, this.getWaitForResponseTime());
Map<String, Map<Integer, PartitionState>> results = new HashMap<String, Map<Integer, PartitionState>>();
for (TopicPartition tp : c) {
if (!results.containsKey(tp.topic())) {
results.put(tp.topic(), new HashMap<Integer, PartitionState>());
}
Map<Integer, PartitionState> topicMap = results.get(tp.topic());
if (!topicMap.containsKey(tp.partition())) {
topicMap.put(tp.partition(), new PartitionState());
}
PartitionState partitionMap = topicMap.get(tp.partition());
PartitionData topicPartitionCommitedOffset = commitedOffsets.get(tp);
//-1: No Info available
if(topicPartitionCommitedOffset.offset == -1){
topicPartitionCommitedOffset = null;
}
long end = endOffsets.get(tp);
long begin = beginningOffsets.get(tp);
partitionMap.logStartOffset = begin;
partitionMap.logEndOffset = end;
partitionMap.partition = tp.partition();
if (topicPartitionCommitedOffset == null) {
// no committed offsets
partitionMap.currentOffset = "unknown";
} else {
partitionMap.currentOffset = topicPartitionCommitedOffset.offset;
}
if (topicPartitionCommitedOffset == null || end == -1) {
// no committed offsets
partitionMap.lag = "unknown";
} else {
partitionMap.lag = end - topicPartitionCommitedOffset.offset;
}
ConsumerSummary cs = whoOwnsPartition.get(tp);
partitionMap.consumerId = cs.consumerId();
partitionMap.host = cs.host();
partitionMap.clientId = cs.clientId();
}
List<Long> offsets = new ArrayList<>() ;
if (this.isOutputAsJson()) {
ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(results);
System.out.println(jsonInString);
} else {
System.out.format("%-30s %-30s %-10s %-15s %-15s %-15s %-30s", "GROUP", "TOPIC", "PARTITION", "CURRENT-OFFSET", "LOG-END-OFFSET", "LAG", "OWNER");
if (this.isIncludeStartOffset()) {
System.out.format(" %-15s", "LOG-START-OFFSET");
}
System.out.println();
for (String topic : results.keySet()) {
Map<Integer, PartitionState> partitionToAssignmentInfo = results.get(topic);
for (int partition : partitionToAssignmentInfo.keySet()) {
PartitionState partitionState = partitionToAssignmentInfo.get(partition);
//Object currentOffset = partitionState.currentOffset;
offsets.add ((Long) partitionState.currentOffset) ;
long logEndOffset = partitionState.logEndOffset;
Object lag = partitionState.lag;
String host = partitionState.host;
String clientId = partitionState.clientId;
if (this.isIncludeStartOffset()) {
System.out.format(" %-15s", partitionState.logStartOffset);
}
System.out.println();
}
}
}
return offsets ;
}
}
| UTF-8 | Java | 11,518 | java | ConsumerGroupLag.java | Java | [] | null | [] | package com.evo.kafka.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import kafka.admin.AdminClient;
import kafka.admin.AdminClient.ConsumerGroupSummary;
import kafka.admin.AdminClient.ConsumerSummary;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.requests.OffsetFetchResponse.PartitionData;
import java.util.*;
public class ConsumerGroupLag {
private String bootstrapServer;
private String group;
private boolean outputAsJson = false;
private boolean includeStartOffset = false;
private Long groupStabilizationTimeoutMs = 5000L;
private Long waitForResponseTime = 1000L;
public String getBootstrapServer() {
return bootstrapServer;
}
public void setBootstrapServer(String bootstrapServer) {
this.bootstrapServer = bootstrapServer;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public boolean isOutputAsJson() {
return outputAsJson;
}
public void setOutputAsJson(boolean outputAsJson) {
this.outputAsJson = outputAsJson;
}
public boolean isIncludeStartOffset() {
return includeStartOffset;
}
public void setIncludeStartOffset(boolean includeStartOffset) {
this.includeStartOffset = includeStartOffset;
}
public Long getGroupStabilizationTimeoutMs() {
return groupStabilizationTimeoutMs;
}
public void setGroupStabilizationTimeoutMs(Long groupStabilizationTimeoutMs) {
this.groupStabilizationTimeoutMs = groupStabilizationTimeoutMs;
}
public Long getWaitForResponseTime() {
return waitForResponseTime;
}
public void setWaitForResponseTime(Long waitForResponseTime) {
this.waitForResponseTime = waitForResponseTime;
}
public class PartitionState {
public long logStartOffset;
public long logEndOffset;
public int partition;
public Object currentOffset;
public Object lag;
public String consumerId;
public String host;
public String clientId;
}
public List<Long> getOffset () throws JsonProcessingException, OffsetFetchException {
/* String bootstrapServer;
String group;
boolean outputAsJson = false;
boolean includeStartOffset = false;
Long groupStabilizationTimeoutMs = 5000L;
Long waitForResponseTime = 1000L;*/
/* // parse command-line arguments to get bootstrap.servers and group.id
Options options = new Options();
try {
options.addOption(Option.builder("b").longOpt("bootstrap-server").hasArg().argName("bootstrap-server")
.desc("Server to connect to <host:9092>").required().build());
options.addOption(Option.builder("g").longOpt("group").hasArg().argName("group").desc(
"The consumer group we wish to act on").required().build());
options.addOption(Option.builder("J").longOpt("json").argName("outputAsJson").desc(
"Output the data as json").build());
options.addOption(Option.builder("s").longOpt("include-start-offset").argName("includeStartOffset").desc(
"Include log-start-offset (the offset of the first record in a partition)").build());
options.addOption(Option.builder("t").longOpt("group-stabilization-timeout")
.argName("groupStabilizationTimeoutMs")
.desc("time (ms) to wait for the consumer group description to be avaialble (e.g. wait for a consumer group rebalance to complete)")
.build());
options.addOption(Option.builder("w").longOpt("response-wait-time")
.argName("waitForResponseTime")
.desc("time (ms) to wait for asking request response.")
.build());
CommandLine line = new DefaultParser().parse(options, args);
bootstrapServer = line.getOptionValue("bootstrap-server");
group = line.getOptionValue("group");
outputAsJson = line.hasOption("json");
includeStartOffset = line.hasOption("s");
} catch (ParseException ex) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("ConsumerGroupLag", "Consumer Group Lag", options, ex.toString(), true);
throw new RuntimeException("Invalid command line options.");
}
*/
Properties props = new Properties();
props.put("bootstrap.servers", this.getBootstrapServer());
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("group.id", this.getGroup());
Properties props2 = new Properties();
props2.put("bootstrap.servers", this.getBootstrapServer());
AdminClient ac = AdminClient.create(props) ;
/*
* {
* "topic-name" : {
* "partition-number" : {
* "logStartOffset" : ...
* "logEndOffset" : ...
* "partition" : ...
* "currentOffset" : ...
* "lag" : ...
* "consumerId" : ...
* "host" : ...
* "clientId" : ...
* },
* ...
* }
* }
*/
Collection<TopicPartition> c = new ArrayList<TopicPartition>();
ConsumerGroupSummary summary = ac.describeConsumerGroup(this.getGroup(), this.getGroupStabilizationTimeoutMs());
if (summary.state().equals("Dead")) {
System.out.format("Consumer group %s does not exist.", this.getGroup());
System.out.println();
System.exit(1);
}
if (!summary.state().equals("Stable")) {
// PreparingRebalance, AwaitingSync
System.err.format("Warning: Consumer group %s has state %s.", this.getGroup(), summary.state());
System.err.println();
}
scala.collection.immutable.List<ConsumerSummary> scalaList = summary.consumers().get();
List<ConsumerSummary> csList = scala.collection.JavaConversions.seqAsJavaList(scalaList);
if (csList.isEmpty()) {
System.out.format("Consumer group %s is rebalancing.", this.getGroup());
System.out.println();
System.exit(1);
}
Map<TopicPartition, ConsumerSummary> whoOwnsPartition = new HashMap<TopicPartition, ConsumerSummary>();
List<String> topicNamesList = new ArrayList<String>();
for (ConsumerSummary cs : csList) {
scala.collection.immutable.List<TopicPartition> scalaAssignment = cs.assignment();
List<TopicPartition> assignment = scala.collection.JavaConversions.seqAsJavaList(scalaAssignment);
for (TopicPartition tp : assignment) {
whoOwnsPartition.put(tp, cs);
topicNamesList.add(tp.topic());
}
c.addAll(assignment);
}
//Get Per broker topic info based on topic list
TopicPartitionsOffsetInfo topicPartitionsOffsetInfo = new TopicPartitionsOffsetInfo(ac);
topicPartitionsOffsetInfo.storeTopicPartitionPerNodeInfo(props, topicNamesList);
//Get endoffset and BeginningOffsets info for all topics
Map<TopicPartition, Long> endOffsets = topicPartitionsOffsetInfo.getEndOffsets();
Map<TopicPartition, Long> beginningOffsets = topicPartitionsOffsetInfo.getBeginningOffsets();
//Get commited offset info
topicPartitionsOffsetInfo.findCoordinatorNodeForGroup(this.getGroup(), this.getWaitForResponseTime());
Map<TopicPartition, PartitionData> commitedOffsets = topicPartitionsOffsetInfo.getCommitedOffsets(this.getGroup(), (
List<TopicPartition>) c, this.getWaitForResponseTime());
Map<String, Map<Integer, PartitionState>> results = new HashMap<String, Map<Integer, PartitionState>>();
for (TopicPartition tp : c) {
if (!results.containsKey(tp.topic())) {
results.put(tp.topic(), new HashMap<Integer, PartitionState>());
}
Map<Integer, PartitionState> topicMap = results.get(tp.topic());
if (!topicMap.containsKey(tp.partition())) {
topicMap.put(tp.partition(), new PartitionState());
}
PartitionState partitionMap = topicMap.get(tp.partition());
PartitionData topicPartitionCommitedOffset = commitedOffsets.get(tp);
//-1: No Info available
if(topicPartitionCommitedOffset.offset == -1){
topicPartitionCommitedOffset = null;
}
long end = endOffsets.get(tp);
long begin = beginningOffsets.get(tp);
partitionMap.logStartOffset = begin;
partitionMap.logEndOffset = end;
partitionMap.partition = tp.partition();
if (topicPartitionCommitedOffset == null) {
// no committed offsets
partitionMap.currentOffset = "unknown";
} else {
partitionMap.currentOffset = topicPartitionCommitedOffset.offset;
}
if (topicPartitionCommitedOffset == null || end == -1) {
// no committed offsets
partitionMap.lag = "unknown";
} else {
partitionMap.lag = end - topicPartitionCommitedOffset.offset;
}
ConsumerSummary cs = whoOwnsPartition.get(tp);
partitionMap.consumerId = cs.consumerId();
partitionMap.host = cs.host();
partitionMap.clientId = cs.clientId();
}
List<Long> offsets = new ArrayList<>() ;
if (this.isOutputAsJson()) {
ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(results);
System.out.println(jsonInString);
} else {
System.out.format("%-30s %-30s %-10s %-15s %-15s %-15s %-30s", "GROUP", "TOPIC", "PARTITION", "CURRENT-OFFSET", "LOG-END-OFFSET", "LAG", "OWNER");
if (this.isIncludeStartOffset()) {
System.out.format(" %-15s", "LOG-START-OFFSET");
}
System.out.println();
for (String topic : results.keySet()) {
Map<Integer, PartitionState> partitionToAssignmentInfo = results.get(topic);
for (int partition : partitionToAssignmentInfo.keySet()) {
PartitionState partitionState = partitionToAssignmentInfo.get(partition);
//Object currentOffset = partitionState.currentOffset;
offsets.add ((Long) partitionState.currentOffset) ;
long logEndOffset = partitionState.logEndOffset;
Object lag = partitionState.lag;
String host = partitionState.host;
String clientId = partitionState.clientId;
if (this.isIncludeStartOffset()) {
System.out.format(" %-15s", partitionState.logStartOffset);
}
System.out.println();
}
}
}
return offsets ;
}
}
| 11,518 | 0.616947 | 0.61304 | 281 | 39.989323 | 32.958672 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622776 | false | false | 10 |
fa03d7b34313c57dc82a86f989e0076f12fe50be | 10,007,273,809,934 | b6be5f0283dcbda6f8f37c777804a9a0b4cb416e | /app/src/main/java/com/facebook_sync/Facebook_Sync.java | 6a205d17d508caca7d946fdf957d3152d0f8478b | [] | no_license | shanzin/Facebook_Sync | https://github.com/shanzin/Facebook_Sync | 8fbcf977c5f0d02a84ce96d3ad9dd92ad0f25dfa | c87b349845c4a21a386758e6ab9a45479ef7cd75 | refs/heads/master | 2021-01-25T10:44:20.049000 | 2015-08-13T02:40:27 | 2015-08-13T02:40:27 | 40,635,208 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook_sync;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.HttpMethod;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class Facebook_Sync extends Activity {
CallbackManager callbackManager;
private AccessToken accessToken;
private Button button_get_user_list;
LocalBroadcastManager mLocalBroadcastManager;
BroadcastReceiver mReceiver;
public static final String pic_url_broadcast = "com.facebook_sync_broadcast_pic_url";
ProgressDialog pDialog;
Bitmap bitmap;
ImageView myImageView;
private Handler timer_handler = new Handler( );
private Runnable timer_runnable;
private int uid = 0;
@Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
@Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
//初始化FacebookSdk,記得要放第一行,不然setContentView會出錯
FacebookSdk.sdkInitialize(getApplicationContext());
Log.d("FB", "sdkInitialize complete");
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
//宣告callback Manager
callbackManager = CallbackManager.Factory.create();
//找到login button
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends");
//幫loginButton增加callback function
//這邊為了方便 直接寫成inner class
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
//accessToken之後或許還會用到 先存起來
accessToken = loginResult.getAccessToken();
Log.d("FB", "access token got.");
//send request and call graph api
GraphRequest request = new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/{friend-list-id}",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
//當RESPONSE回來的時候
@Override
public void onCompleted(GraphResponse response) {
/* handle the result */
Log.d("FB", "friend list id");
}
}
);
//包入你想要得到的資料 送出request
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
request.executeAsync();
}
//登入取消
@Override
public void onCancel() {
// App code
Log.d("FB", "CANCEL");
}
//登入失敗
@Override
public void onError(FacebookException exception) {
// App code
Log.d("FB", exception.toString());
}
}/*loginButton.registerCallback*/
);
/*Broadcast register*/
IntentFilter pic_url_filter = new IntentFilter();
pic_url_filter.addAction(pic_url_broadcast);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(pic_url_broadcast)) {
if(intent.getStringExtra("pic_url") == null) {
Log.d("FB", "UID out of range");
timer_handler.removeCallbacks(timer_runnable); //停止Timer
}
else {
Log.d("FB", intent.getStringExtra("pic_url"));
}
}
new LoadImage().execute(intent.getStringExtra("pic_url"));
}
};
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
mLocalBroadcastManager.registerReceiver(mReceiver, pic_url_filter);
}/*protected void onCreate*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_facebook__sync, menu);
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void dispFacebookUserPic(String pic_url) {
try{
URL url = new URL(pic_url);
URLConnection urlConnection = url.openConnection();
InputStream is = (InputStream) urlConnection.getInputStream();
Drawable draw = Drawable.createFromStream(is, "src");
myImageView.setImageDrawable(draw);
}catch (Exception e) {
//TODO handle error
Log.d("FB", "disp pic error");
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
myImageView.setImageBitmap(image);
}else{
Toast.makeText(Facebook_Sync.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
private void pic_update_timer(){
timer_runnable = new Runnable( ) {
public void run ( ) {
Facebook_Util fb_util = new Facebook_Util();
fb_util.getTagFriendPic(uid);
uid++;
timer_handler.postDelayed(this,2000);
}
};
timer_handler.postDelayed(timer_runnable, 2000); // 开始Timer
}
}
| UTF-8 | Java | 8,499 | java | Facebook_Sync.java | Java | [] | null | [] | package com.facebook_sync;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.HttpMethod;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class Facebook_Sync extends Activity {
CallbackManager callbackManager;
private AccessToken accessToken;
private Button button_get_user_list;
LocalBroadcastManager mLocalBroadcastManager;
BroadcastReceiver mReceiver;
public static final String pic_url_broadcast = "com.facebook_sync_broadcast_pic_url";
ProgressDialog pDialog;
Bitmap bitmap;
ImageView myImageView;
private Handler timer_handler = new Handler( );
private Runnable timer_runnable;
private int uid = 0;
@Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
@Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
//初始化FacebookSdk,記得要放第一行,不然setContentView會出錯
FacebookSdk.sdkInitialize(getApplicationContext());
Log.d("FB", "sdkInitialize complete");
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
//宣告callback Manager
callbackManager = CallbackManager.Factory.create();
//找到login button
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends");
//幫loginButton增加callback function
//這邊為了方便 直接寫成inner class
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
//accessToken之後或許還會用到 先存起來
accessToken = loginResult.getAccessToken();
Log.d("FB", "access token got.");
//send request and call graph api
GraphRequest request = new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/{friend-list-id}",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
//當RESPONSE回來的時候
@Override
public void onCompleted(GraphResponse response) {
/* handle the result */
Log.d("FB", "friend list id");
}
}
);
//包入你想要得到的資料 送出request
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
request.executeAsync();
}
//登入取消
@Override
public void onCancel() {
// App code
Log.d("FB", "CANCEL");
}
//登入失敗
@Override
public void onError(FacebookException exception) {
// App code
Log.d("FB", exception.toString());
}
}/*loginButton.registerCallback*/
);
/*Broadcast register*/
IntentFilter pic_url_filter = new IntentFilter();
pic_url_filter.addAction(pic_url_broadcast);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(pic_url_broadcast)) {
if(intent.getStringExtra("pic_url") == null) {
Log.d("FB", "UID out of range");
timer_handler.removeCallbacks(timer_runnable); //停止Timer
}
else {
Log.d("FB", intent.getStringExtra("pic_url"));
}
}
new LoadImage().execute(intent.getStringExtra("pic_url"));
}
};
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
mLocalBroadcastManager.registerReceiver(mReceiver, pic_url_filter);
}/*protected void onCreate*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_facebook__sync, menu);
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void dispFacebookUserPic(String pic_url) {
try{
URL url = new URL(pic_url);
URLConnection urlConnection = url.openConnection();
InputStream is = (InputStream) urlConnection.getInputStream();
Drawable draw = Drawable.createFromStream(is, "src");
myImageView.setImageDrawable(draw);
}catch (Exception e) {
//TODO handle error
Log.d("FB", "disp pic error");
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
myImageView.setImageBitmap(image);
}else{
Toast.makeText(Facebook_Sync.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
private void pic_update_timer(){
timer_runnable = new Runnable( ) {
public void run ( ) {
Facebook_Util fb_util = new Facebook_Util();
fb_util.getTagFriendPic(uid);
uid++;
timer_handler.postDelayed(this,2000);
}
};
timer_handler.postDelayed(timer_runnable, 2000); // 开始Timer
}
}
| 8,499 | 0.579969 | 0.578651 | 243 | 33.349792 | 24.548035 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.559671 | false | false | 10 |
280ff92408d310e14af8d719bedfef14688b69b5 | 16,312,285,857,097 | 9b31469fd341891c93cf81ea950f97c1a6df8a4e | /工具代码/基础算法-数据结构/src/math/MathTest.java | 50535bd9ed731f0acaf3df741f2c09f56a446f60 | [] | no_license | luozhaoemail/java-demo | https://github.com/luozhaoemail/java-demo | 3a4ea606aba911c2b6a56c5153de4b36d2f3cb4d | ca9a0be928db4d92b067ff491249482f271ff71d | refs/heads/master | 2022-12-24T12:07:26.095000 | 2020-06-09T03:53:38 | 2020-06-09T03:53:38 | 187,343,711 | 1 | 1 | null | false | 2022-12-16T05:55:03 | 2019-05-18T10:20:34 | 2020-06-09T03:53:41 | 2022-12-16T05:55:00 | 55,729 | 1 | 1 | 15 | Java | false | false | package math;
import java.math.BigDecimal;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.stat.descriptive.moment.Kurtosis;
import org.apache.commons.math3.stat.descriptive.moment.Mean;
import org.apache.commons.math3.stat.descriptive.moment.Skewness;
import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation;
import org.apache.commons.math3.stat.descriptive.rank.Percentile;
public class MathTest {
public static void main(String[] args) {
double[] values = new double[] {0,54,56,67,67,76,78,88,90,99,100,90,89,87,78,67,66,56,55,34};
//71.6000 23.104977818643324 0.6000 2 0 1 2
Mean mean = new Mean(); // 算术平均值
System.out.println("mean:"+mean.evaluate(values));
StandardDeviation StandardDeviation =new StandardDeviation();//标准差
System.out.println("StandardDeviation: " +StandardDeviation.evaluate(values));
Percentile percentile = new Percentile(); // 百分位数:一组n个观测值按数值大小排列,处于p%位置的值称第p百分位数
System.out.println("percentile: " + percentile.evaluate(values,60));
Skewness skewness = new Skewness(); //偏度
System.out.println("skewness:"+skewness.evaluate(values));
Kurtosis kurtosis = new Kurtosis(); //峰度
System.out.println("kurtosis:"+kurtosis.evaluate(values));
// NormalDistribution normaldis = new NormalDistribution(0,1);//新建一个标准正态分布对象
double avg = new Mean().evaluate(values);
double std = new StandardDeviation().evaluate(values);
NormalDistribution normaldis = new NormalDistribution(avg,std); //正态分布
System.out.println("normaldis: ");
for(int i=0;i<values.length;i++){
double s1 = normaldis.cumulativeProbability(values[i]); //计算正态分布概率
double f1 = new BigDecimal(s1).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.print(f1+",");
}
}
}
| UTF-8 | Java | 2,046 | java | MathTest.java | Java | [] | null | [] | package math;
import java.math.BigDecimal;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.stat.descriptive.moment.Kurtosis;
import org.apache.commons.math3.stat.descriptive.moment.Mean;
import org.apache.commons.math3.stat.descriptive.moment.Skewness;
import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation;
import org.apache.commons.math3.stat.descriptive.rank.Percentile;
public class MathTest {
public static void main(String[] args) {
double[] values = new double[] {0,54,56,67,67,76,78,88,90,99,100,90,89,87,78,67,66,56,55,34};
//71.6000 23.104977818643324 0.6000 2 0 1 2
Mean mean = new Mean(); // 算术平均值
System.out.println("mean:"+mean.evaluate(values));
StandardDeviation StandardDeviation =new StandardDeviation();//标准差
System.out.println("StandardDeviation: " +StandardDeviation.evaluate(values));
Percentile percentile = new Percentile(); // 百分位数:一组n个观测值按数值大小排列,处于p%位置的值称第p百分位数
System.out.println("percentile: " + percentile.evaluate(values,60));
Skewness skewness = new Skewness(); //偏度
System.out.println("skewness:"+skewness.evaluate(values));
Kurtosis kurtosis = new Kurtosis(); //峰度
System.out.println("kurtosis:"+kurtosis.evaluate(values));
// NormalDistribution normaldis = new NormalDistribution(0,1);//新建一个标准正态分布对象
double avg = new Mean().evaluate(values);
double std = new StandardDeviation().evaluate(values);
NormalDistribution normaldis = new NormalDistribution(avg,std); //正态分布
System.out.println("normaldis: ");
for(int i=0;i<values.length;i++){
double s1 = normaldis.cumulativeProbability(values[i]); //计算正态分布概率
double f1 = new BigDecimal(s1).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.print(f1+",");
}
}
}
| 2,046 | 0.700524 | 0.65445 | 52 | 35.73077 | 31.666601 | 97 | false | false | 27 | 0.027749 | 0 | 0 | 0 | 0 | 2.096154 | false | false | 10 |
e807b151163bb5f273590fd70c29b710a49da4ab | 10,926,396,848,091 | 27171e5939eea40761257cfbd0fcf78435033433 | /src/StacksAndQueues/MaximumAreaHistogram.java | 3d2b8a76aa5220df857767e4369adc954961a5c7 | [
"Apache-2.0"
] | permissive | Shivamsharma009/Interview | https://github.com/Shivamsharma009/Interview | c8512a97fa71981bb2ebf82e3831dc8dc8a9a3df | 4c0d223cb2dca7e7a4ae279a03d5578ed5bd9e12 | refs/heads/master | 2020-12-13T05:59:37.001000 | 2020-05-19T21:20:50 | 2020-05-19T21:20:50 | 234,330,034 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package StacksAndQueues;
import java.util.Stack;
public class MaximumAreaHistogram {
static void MaxAreaHistogram(int[] arr, int n) {
int[] rb = new int[arr.length];//nse index on the right side
Stack<Integer> st = new Stack<>();
st.push(arr.length - 1);
rb[arr.length - 1] = arr.length;
for (int i = arr.length - 2; i >= 0; i--) {
while (st.size() > 0 && arr[i] <= arr[st.peek()]) {
st.pop();
}
if (st.size() == 0) {
rb[i] = arr.length;
} else {
rb[i] = st.peek();
}
st.push(i);
}
int[] lb = new int[arr.length];//nse index on the left side
st = new Stack<>();
st.push(0);
lb[0] = -1;
for (int i = 1; i < arr.length; i++) {
while (st.size() > 0 && arr[i] <= arr[st.peek()]) {
st.pop();
}
if (st.size() == 0) {
lb[i] = -1;
} else {
lb[i] = st.peek();
}
st.push(i);
}
//area
int max_area = 0;
for(int i = 0 ;i < arr.length;i++)
{
int width = rb[i] - lb[i] - 1;
int area = arr[i] * width;
if(area > max_area){
max_area = area;
}
}
System.out.println("Maximum Area Histogram is "+max_area);
}
//Driver Program
public static void main(String[] args)
{
int []arr = new int[]{6,2,5,4,5,1,6};
int n = arr.length;
MaxAreaHistogram(arr,n);
}
}
| UTF-8 | Java | 1,643 | java | MaximumAreaHistogram.java | Java | [] | null | [] | package StacksAndQueues;
import java.util.Stack;
public class MaximumAreaHistogram {
static void MaxAreaHistogram(int[] arr, int n) {
int[] rb = new int[arr.length];//nse index on the right side
Stack<Integer> st = new Stack<>();
st.push(arr.length - 1);
rb[arr.length - 1] = arr.length;
for (int i = arr.length - 2; i >= 0; i--) {
while (st.size() > 0 && arr[i] <= arr[st.peek()]) {
st.pop();
}
if (st.size() == 0) {
rb[i] = arr.length;
} else {
rb[i] = st.peek();
}
st.push(i);
}
int[] lb = new int[arr.length];//nse index on the left side
st = new Stack<>();
st.push(0);
lb[0] = -1;
for (int i = 1; i < arr.length; i++) {
while (st.size() > 0 && arr[i] <= arr[st.peek()]) {
st.pop();
}
if (st.size() == 0) {
lb[i] = -1;
} else {
lb[i] = st.peek();
}
st.push(i);
}
//area
int max_area = 0;
for(int i = 0 ;i < arr.length;i++)
{
int width = rb[i] - lb[i] - 1;
int area = arr[i] * width;
if(area > max_area){
max_area = area;
}
}
System.out.println("Maximum Area Histogram is "+max_area);
}
//Driver Program
public static void main(String[] args)
{
int []arr = new int[]{6,2,5,4,5,1,6};
int n = arr.length;
MaxAreaHistogram(arr,n);
}
}
| 1,643 | 0.409617 | 0.395618 | 66 | 23.89394 | 19.027992 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.606061 | false | false | 10 |
12082940ebc16f28e4315bd56e9e7fc163390d23 | 1,855,425,906,245 | eabae988f94765fe58595d09faca1a0c4d404da9 | /exercicio3/Pessoa.java | e23c540d4dc9a777efb71a633b2176a3ef608d15 | [] | no_license | nicolasjosino/poo-uni7 | https://github.com/nicolasjosino/poo-uni7 | 13250c1b156d1f75a8d0f6860dc46bd9e27fabbf | e8166df9c2f80179ff4094b0b9edd1719e3d6190 | refs/heads/main | 2023-05-30T05:07:22.601000 | 2021-06-17T01:39:44 | 2021-06-17T01:39:44 | 335,805,400 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Pessoa {
private int alturaEmCm;
public void setAltura(int alturaEmCm) {
this.alturaEmCm = alturaEmCm;
}
public int setAltura(double alturaEmMetros) {
this.alturaEmCm = (int) alturaEmMetros * 100;
return this.alturaEmCm;
}
public int getAlturaEmCm() {
return alturaEmCm;
}
public double getAlturaEmMetros() {
return alturaEmCm / 100d;
}
}
| UTF-8 | Java | 401 | java | Pessoa.java | Java | [] | null | [] | public class Pessoa {
private int alturaEmCm;
public void setAltura(int alturaEmCm) {
this.alturaEmCm = alturaEmCm;
}
public int setAltura(double alturaEmMetros) {
this.alturaEmCm = (int) alturaEmMetros * 100;
return this.alturaEmCm;
}
public int getAlturaEmCm() {
return alturaEmCm;
}
public double getAlturaEmMetros() {
return alturaEmCm / 100d;
}
}
| 401 | 0.678304 | 0.663342 | 22 | 17.227272 | 16.908663 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 10 |
34835f89031574b7786834e25f463f65fccf4747 | 9,311,489,129,118 | 3e08872841f5fdb32e1334e0f9bf72dc0e827930 | /dopaas-uci/dopaas-uci-service-starter-facade/src/main/java/com/wl4g/dopaas/uci/service/impl/ProjectServiceImpl.java | 71d93046f0a0a53f6f255f6976b17de116fbadbb | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | wl4g/xcloud-devops | https://github.com/wl4g/xcloud-devops | 8fc8f9cd26d80b6083d7596441ebe3c631ac4150 | 1d094d15b35ab6e8ea9710ffaa8aa2df2addafe9 | refs/heads/master | 2023-03-14T01:02:02.794000 | 2022-02-21T06:58:04 | 2022-02-21T06:58:04 | 160,456,912 | 2 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2017 ~ 2050 the original author or authors <Wanglsir@gmail.com, 983708408@qq.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wl4g.dopaas.uci.service.impl;
import com.wl4g.component.common.serialize.JacksonUtils;
import com.wl4g.component.core.bean.BaseBean;
import com.wl4g.component.core.framework.operator.GenericOperatorAdapter;
import com.wl4g.component.core.page.PageHolder;
import com.wl4g.dopaas.cmdb.service.AppClusterService;
import com.wl4g.dopaas.common.bean.cmdb.AppCluster;
import com.wl4g.dopaas.common.bean.uci.Dependency;
import com.wl4g.dopaas.common.bean.uci.Project;
import com.wl4g.dopaas.common.bean.urm.SourceRepo;
import com.wl4g.dopaas.common.bean.urm.model.CompositeBasicVcsProjectModel;
import com.wl4g.dopaas.uci.data.DependencyDao;
import com.wl4g.dopaas.uci.data.ProjectDao;
import com.wl4g.dopaas.uci.service.ProjectService;
import com.wl4g.dopaas.urm.operator.VcsOperator;
import com.wl4g.dopaas.urm.operator.VcsOperator.VcsProviderKind;
import com.wl4g.dopaas.urm.operator.model.VcsBranchModel;
import com.wl4g.dopaas.urm.operator.model.VcsTagModel;
import com.wl4g.dopaas.urm.service.RepoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.List;
import static com.wl4g.component.core.bean.BaseBean.DEL_FLAG_NORMAL;
import static com.wl4g.component.core.bean.BaseBean.ENABLED;
import static com.wl4g.dopaas.common.constant.UciConstants.TASK_LOCK_STATUS_UNLOCK;
import static com.wl4g.iam.common.utils.IamOrganizationUtils.getRequestOrganizationCode;
import static com.wl4g.iam.common.utils.IamOrganizationUtils.getRequestOrganizationCodes;
/**
* @author vjay
* @date 2019-05-17 10:24:00
*/
@Service
public class ProjectServiceImpl implements ProjectService {
final protected Logger log = LoggerFactory.getLogger(getClass());
private @Autowired GenericOperatorAdapter<VcsProviderKind, VcsOperator> vcsOperator;
private @Autowired ProjectDao projectDao;
private @Autowired DependencyDao dependencyDao;
private @Autowired RepoService repoService;
private @Autowired AppClusterService appClusterService;
@Override
public void save(Project project) {
if (null != project.getId() && project.getId() > 0) {
project.preUpdate();
update(project);
} else {
project.preInsert(getRequestOrganizationCode());
project.setDelFlag(DEL_FLAG_NORMAL);
project.setEnable(ENABLED);
project.setLockStatus(TASK_LOCK_STATUS_UNLOCK);
insert(project);
}
}
@Transactional
public int insert(Project project) {
Project hasProject = getByAppClusterId(project.getAppClusterId());
// check repeated
Assert.state(hasProject == null, "Config Repeated");
int result = projectDao.insertSelective(project);
if (project.getDependencies() != null) {
for (Dependency dependency : project.getDependencies()) {
if (dependency.getDependentId() != null) {
dependency.setProjectId(project.getId());
dependency.preInsert();
dependencyDao.insertSelective(dependency);
}
}
}
return result;
}
@Transactional
public int update(Project project) {
Project hasProject = getByAppClusterId(project.getAppClusterId());
// check repeated
Assert.state(hasProject == null || hasProject.getId().longValue() == project.getId().longValue(), "Config Repeated");
project.preUpdate();
int result = projectDao.updateByPrimaryKeySelective(project);
dependencyDao.deleteByProjectId(project.getId());
if (project.getDependencies() != null) {
for (Dependency dependency : project.getDependencies()) {
if (dependency.getDependentId() != null) {
dependency.setProjectId(project.getId());
dependency.preInsert();
dependencyDao.insertSelective(dependency);
}
}
}
return result;
}
@Override
public int deleteById(Long id) {
Project project = new Project();
project.preUpdate();
project.setId(id);
project.setDelFlag(BaseBean.DEL_FLAG_DELETE);
return projectDao.updateByPrimaryKeySelective(project);
}
@Override
public int removeById(Long id) {
return projectDao.deleteByPrimaryKey(id);
}
@Override
public PageHolder<Project> list(PageHolder<Project> pm, String groupName, String projectName) {
List<Long> clusterIds = appClusterService.getIdsByLikeName(groupName);
pm.useCount().bind();
List<Project> list = projectDao.list(getRequestOrganizationCodes(), clusterIds, projectName, null);
for (Project project : list) {
AppCluster appCluster = appClusterService.getById(project.getAppClusterId());
if (appCluster != null) {
project.setGroupName(appCluster.getName());
}
}
pm.setRecords(list);
return pm;
}
@Override
public List<Project> getBySelect(Integer isBoot) {
List<Project> list = projectDao.list(getRequestOrganizationCodes(), null, null, isBoot);
for (Project project : list) {
AppCluster appCluster = appClusterService.getById(project.getAppClusterId());
if (appCluster != null) {
project.setGroupName(appCluster.getName());
}
}
return list;
}
@Override
public Project selectByPrimaryKey(Long id) {
Project project = getProjectById(id);
List<Dependency> dependencies = dependencyDao.getParentsByProjectId(project.getId());
project.setDependencies(dependencies);
return project;
}
@Override
public Project getProjectById(Long id) { // fix Cross db
Project project = projectDao.selectByPrimaryKey(id);
SourceRepo sourceRepo = repoService.detail(project.getVcsId());
project.setVcs(sourceRepo);
return project;
}
@Override
public Project getByAppClusterId(Long appClusteId) {
Project project = projectDao.getByAppClusterId(appClusteId);
project.setVcs(repoService.detail(project.getVcsId()));
return project;
}
@Override
public int updateLockStatus(Long id, Integer lockStatus) {
Project project = new Project();
project.setId(id);
project.setLockStatus(lockStatus);
return projectDao.updateByPrimaryKeySelective(project);
}
@Override
public List<String> getBranchs(Long appClusterId, Integer tagOrBranch) throws Exception {
Assert.notNull(appClusterId, "id can not be null");
Project project = getByAppClusterId(appClusterId);
buildVcsProject(project);
Assert.notNull(project, "not found project ,please check you project config");
return getBranchByProject(project, tagOrBranch);
}
@Override
public List<String> getBranchsByProjectId(Long projectId, Integer tagOrBranch) throws Exception {
Assert.notNull(projectId, "id can not be null");
Project project = getProjectById(projectId);
buildVcsProject(project);
Assert.notNull(project, "not found project ,please check you project config");
return getBranchByProject(project, tagOrBranch);
}
private List<String> getBranchByProject(Project project, Integer tagOrBranch) throws Exception {
List<String> result = new ArrayList<>();
if (tagOrBranch != null && tagOrBranch == 2) { // tag
List<VcsTagModel> remoteTags = vcsOperator.forOperator(project.getVcs().getProviderKind())
.getRemoteTags(project.getVcs(), project.getVcsProject());
for (VcsTagModel vcsTagModel : remoteTags) {
result.add(vcsTagModel.getName());
}
}
// Branch
else {
List<VcsBranchModel> remoteBranchs = vcsOperator.forOperator(project.getVcs().getProviderKind())
.getRemoteBranchs(project.getVcs(), project.getVcsProject());
for (VcsBranchModel vcsBranchModel : remoteBranchs) {
result.add(vcsBranchModel.getName());
}
}
return result;
}
private void buildVcsProject(Project project) {
String gitInfo = project.getGitInfo();
if (StringUtils.isNotBlank(gitInfo)) {
CompositeBasicVcsProjectModel compositeBasicVcsProjectModel = JacksonUtils.parseJSON(gitInfo,
CompositeBasicVcsProjectModel.class);
project.setVcsProject(compositeBasicVcsProjectModel);
}
}
} | UTF-8 | Java | 8,577 | java | ProjectServiceImpl.java | Java | [
{
"context": "right 2017 ~ 2050 the original author or authors <Wanglsir@gmail.com, 983708408@qq.com>.\n *\n * Licensed under the Apac",
"end": 78,
"score": 0.9999189376831055,
"start": 60,
"tag": "EMAIL",
"value": "Wanglsir@gmail.com"
},
{
"context": "e original author or authors <W... | null | [] | /*
* Copyright 2017 ~ 2050 the original author or authors <<EMAIL>, <EMAIL>>.
*
* 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.wl4g.dopaas.uci.service.impl;
import com.wl4g.component.common.serialize.JacksonUtils;
import com.wl4g.component.core.bean.BaseBean;
import com.wl4g.component.core.framework.operator.GenericOperatorAdapter;
import com.wl4g.component.core.page.PageHolder;
import com.wl4g.dopaas.cmdb.service.AppClusterService;
import com.wl4g.dopaas.common.bean.cmdb.AppCluster;
import com.wl4g.dopaas.common.bean.uci.Dependency;
import com.wl4g.dopaas.common.bean.uci.Project;
import com.wl4g.dopaas.common.bean.urm.SourceRepo;
import com.wl4g.dopaas.common.bean.urm.model.CompositeBasicVcsProjectModel;
import com.wl4g.dopaas.uci.data.DependencyDao;
import com.wl4g.dopaas.uci.data.ProjectDao;
import com.wl4g.dopaas.uci.service.ProjectService;
import com.wl4g.dopaas.urm.operator.VcsOperator;
import com.wl4g.dopaas.urm.operator.VcsOperator.VcsProviderKind;
import com.wl4g.dopaas.urm.operator.model.VcsBranchModel;
import com.wl4g.dopaas.urm.operator.model.VcsTagModel;
import com.wl4g.dopaas.urm.service.RepoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.List;
import static com.wl4g.component.core.bean.BaseBean.DEL_FLAG_NORMAL;
import static com.wl4g.component.core.bean.BaseBean.ENABLED;
import static com.wl4g.dopaas.common.constant.UciConstants.TASK_LOCK_STATUS_UNLOCK;
import static com.wl4g.iam.common.utils.IamOrganizationUtils.getRequestOrganizationCode;
import static com.wl4g.iam.common.utils.IamOrganizationUtils.getRequestOrganizationCodes;
/**
* @author vjay
* @date 2019-05-17 10:24:00
*/
@Service
public class ProjectServiceImpl implements ProjectService {
final protected Logger log = LoggerFactory.getLogger(getClass());
private @Autowired GenericOperatorAdapter<VcsProviderKind, VcsOperator> vcsOperator;
private @Autowired ProjectDao projectDao;
private @Autowired DependencyDao dependencyDao;
private @Autowired RepoService repoService;
private @Autowired AppClusterService appClusterService;
@Override
public void save(Project project) {
if (null != project.getId() && project.getId() > 0) {
project.preUpdate();
update(project);
} else {
project.preInsert(getRequestOrganizationCode());
project.setDelFlag(DEL_FLAG_NORMAL);
project.setEnable(ENABLED);
project.setLockStatus(TASK_LOCK_STATUS_UNLOCK);
insert(project);
}
}
@Transactional
public int insert(Project project) {
Project hasProject = getByAppClusterId(project.getAppClusterId());
// check repeated
Assert.state(hasProject == null, "Config Repeated");
int result = projectDao.insertSelective(project);
if (project.getDependencies() != null) {
for (Dependency dependency : project.getDependencies()) {
if (dependency.getDependentId() != null) {
dependency.setProjectId(project.getId());
dependency.preInsert();
dependencyDao.insertSelective(dependency);
}
}
}
return result;
}
@Transactional
public int update(Project project) {
Project hasProject = getByAppClusterId(project.getAppClusterId());
// check repeated
Assert.state(hasProject == null || hasProject.getId().longValue() == project.getId().longValue(), "Config Repeated");
project.preUpdate();
int result = projectDao.updateByPrimaryKeySelective(project);
dependencyDao.deleteByProjectId(project.getId());
if (project.getDependencies() != null) {
for (Dependency dependency : project.getDependencies()) {
if (dependency.getDependentId() != null) {
dependency.setProjectId(project.getId());
dependency.preInsert();
dependencyDao.insertSelective(dependency);
}
}
}
return result;
}
@Override
public int deleteById(Long id) {
Project project = new Project();
project.preUpdate();
project.setId(id);
project.setDelFlag(BaseBean.DEL_FLAG_DELETE);
return projectDao.updateByPrimaryKeySelective(project);
}
@Override
public int removeById(Long id) {
return projectDao.deleteByPrimaryKey(id);
}
@Override
public PageHolder<Project> list(PageHolder<Project> pm, String groupName, String projectName) {
List<Long> clusterIds = appClusterService.getIdsByLikeName(groupName);
pm.useCount().bind();
List<Project> list = projectDao.list(getRequestOrganizationCodes(), clusterIds, projectName, null);
for (Project project : list) {
AppCluster appCluster = appClusterService.getById(project.getAppClusterId());
if (appCluster != null) {
project.setGroupName(appCluster.getName());
}
}
pm.setRecords(list);
return pm;
}
@Override
public List<Project> getBySelect(Integer isBoot) {
List<Project> list = projectDao.list(getRequestOrganizationCodes(), null, null, isBoot);
for (Project project : list) {
AppCluster appCluster = appClusterService.getById(project.getAppClusterId());
if (appCluster != null) {
project.setGroupName(appCluster.getName());
}
}
return list;
}
@Override
public Project selectByPrimaryKey(Long id) {
Project project = getProjectById(id);
List<Dependency> dependencies = dependencyDao.getParentsByProjectId(project.getId());
project.setDependencies(dependencies);
return project;
}
@Override
public Project getProjectById(Long id) { // fix Cross db
Project project = projectDao.selectByPrimaryKey(id);
SourceRepo sourceRepo = repoService.detail(project.getVcsId());
project.setVcs(sourceRepo);
return project;
}
@Override
public Project getByAppClusterId(Long appClusteId) {
Project project = projectDao.getByAppClusterId(appClusteId);
project.setVcs(repoService.detail(project.getVcsId()));
return project;
}
@Override
public int updateLockStatus(Long id, Integer lockStatus) {
Project project = new Project();
project.setId(id);
project.setLockStatus(lockStatus);
return projectDao.updateByPrimaryKeySelective(project);
}
@Override
public List<String> getBranchs(Long appClusterId, Integer tagOrBranch) throws Exception {
Assert.notNull(appClusterId, "id can not be null");
Project project = getByAppClusterId(appClusterId);
buildVcsProject(project);
Assert.notNull(project, "not found project ,please check you project config");
return getBranchByProject(project, tagOrBranch);
}
@Override
public List<String> getBranchsByProjectId(Long projectId, Integer tagOrBranch) throws Exception {
Assert.notNull(projectId, "id can not be null");
Project project = getProjectById(projectId);
buildVcsProject(project);
Assert.notNull(project, "not found project ,please check you project config");
return getBranchByProject(project, tagOrBranch);
}
private List<String> getBranchByProject(Project project, Integer tagOrBranch) throws Exception {
List<String> result = new ArrayList<>();
if (tagOrBranch != null && tagOrBranch == 2) { // tag
List<VcsTagModel> remoteTags = vcsOperator.forOperator(project.getVcs().getProviderKind())
.getRemoteTags(project.getVcs(), project.getVcsProject());
for (VcsTagModel vcsTagModel : remoteTags) {
result.add(vcsTagModel.getName());
}
}
// Branch
else {
List<VcsBranchModel> remoteBranchs = vcsOperator.forOperator(project.getVcs().getProviderKind())
.getRemoteBranchs(project.getVcs(), project.getVcsProject());
for (VcsBranchModel vcsBranchModel : remoteBranchs) {
result.add(vcsBranchModel.getName());
}
}
return result;
}
private void buildVcsProject(Project project) {
String gitInfo = project.getGitInfo();
if (StringUtils.isNotBlank(gitInfo)) {
CompositeBasicVcsProjectModel compositeBasicVcsProjectModel = JacksonUtils.parseJSON(gitInfo,
CompositeBasicVcsProjectModel.class);
project.setVcsProject(compositeBasicVcsProjectModel);
}
}
} | 8,557 | 0.765536 | 0.758074 | 244 | 34.155739 | 28.270218 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.008197 | false | false | 10 |
3da4bd80c8ea75d2873723dc0f80a0aa5a92e5e3 | 3,393,024,207,549 | 90f17cd659cc96c8fff1d5cfd893cbbe18b1240f | /src/main/java/io/grpc/util/RoundRobinLoadBalancerFactory.java | 51063feeb031a74f73b299e7af69c5c6f7c56809 | [] | no_license | redpicasso/fluffy-octo-robot | https://github.com/redpicasso/fluffy-octo-robot | c9b98d2e8745805edc8ddb92e8afc1788ceadd08 | b2b62d7344da65af7e35068f40d6aae0cd0835a6 | refs/heads/master | 2022-11-15T14:43:37.515000 | 2020-07-01T22:19:16 | 2020-07-01T22:19:16 | 276,492,708 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.grpc.util;
import androidx.core.app.NotificationCompat;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.firebase.analytics.FirebaseAnalytics.Param;
import io.grpc.Attributes;
import io.grpc.Attributes.Builder;
import io.grpc.Attributes.Key;
import io.grpc.ConnectivityState;
import io.grpc.ConnectivityStateInfo;
import io.grpc.EquivalentAddressGroup;
import io.grpc.ExperimentalApi;
import io.grpc.LoadBalancer;
import io.grpc.LoadBalancer.Factory;
import io.grpc.LoadBalancer.Helper;
import io.grpc.LoadBalancer.PickResult;
import io.grpc.LoadBalancer.PickSubchannelArgs;
import io.grpc.LoadBalancer.Subchannel;
import io.grpc.LoadBalancer.SubchannelPicker;
import io.grpc.Metadata;
import io.grpc.Status;
import io.grpc.internal.GrpcAttributes;
import io.grpc.internal.ServiceConfigUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
public final class RoundRobinLoadBalancerFactory extends Factory {
private static final RoundRobinLoadBalancerFactory INSTANCE = new RoundRobinLoadBalancerFactory();
@VisibleForTesting
static final class Ref<T> {
T value;
Ref(T t) {
this.value = t;
}
}
@VisibleForTesting
static final class RoundRobinLoadBalancer extends LoadBalancer {
private static final Status EMPTY_OK = Status.OK.withDescription("no subchannels ready");
@VisibleForTesting
static final Key<Ref<ConnectivityStateInfo>> STATE_INFO = Key.create("state-info");
static final Key<Ref<Subchannel>> STICKY_REF = Key.create("sticky-ref");
private static final Logger logger = Logger.getLogger(RoundRobinLoadBalancer.class.getName());
private RoundRobinPicker currentPicker = new EmptyPicker(EMPTY_OK);
private ConnectivityState currentState;
private final Helper helper;
private final Random random;
@Nullable
private StickinessState stickinessState;
private final Map<EquivalentAddressGroup, Subchannel> subchannels = new HashMap();
@VisibleForTesting
static final class StickinessState {
static final int MAX_ENTRIES = 1000;
final Queue<String> evictionQueue = new ConcurrentLinkedQueue();
final Metadata.Key<String> key;
final ConcurrentMap<String, Ref<Subchannel>> stickinessMap = new ConcurrentHashMap();
StickinessState(@Nonnull String str) {
this.key = Metadata.Key.of(str, Metadata.ASCII_STRING_MARSHALLER);
}
@Nonnull
Subchannel maybeRegister(String str, @Nonnull Subchannel subchannel) {
Ref ref = (Ref) subchannel.getAttributes().get(RoundRobinLoadBalancer.STICKY_REF);
Ref ref2;
do {
ref2 = (Ref) this.stickinessMap.putIfAbsent(str, ref);
if (ref2 == null) {
addToEvictionQueue(str);
return subchannel;
}
Subchannel subchannel2 = (Subchannel) ref2.value;
if (subchannel2 != null && RoundRobinLoadBalancer.isReady(subchannel2)) {
return subchannel2;
}
} while (!this.stickinessMap.replace(str, ref2, ref));
return subchannel;
}
private void addToEvictionQueue(String str) {
while (this.stickinessMap.size() >= 1000) {
String str2 = (String) this.evictionQueue.poll();
if (str2 == null) {
break;
}
this.stickinessMap.remove(str2);
}
this.evictionQueue.add(str);
}
void remove(Subchannel subchannel) {
((Ref) subchannel.getAttributes().get(RoundRobinLoadBalancer.STICKY_REF)).value = null;
}
@Nullable
Subchannel getSubchannel(String str) {
Ref ref = (Ref) this.stickinessMap.get(str);
return ref != null ? (Subchannel) ref.value : null;
}
}
RoundRobinLoadBalancer(Helper helper) {
this.helper = (Helper) Preconditions.checkNotNull(helper, "helper");
this.random = new Random();
}
public void handleResolvedAddressGroups(List<EquivalentAddressGroup> list, Attributes attributes) {
Set keySet = this.subchannels.keySet();
Set stripAttrs = stripAttrs(list);
Set<EquivalentAddressGroup> set = setsDifference(stripAttrs, keySet);
Set<EquivalentAddressGroup> set2 = setsDifference(keySet, stripAttrs);
Map map = (Map) attributes.get(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG);
if (map != null) {
String stickinessMetadataKeyFromServiceConfig = ServiceConfigUtil.getStickinessMetadataKeyFromServiceConfig(map);
if (stickinessMetadataKeyFromServiceConfig != null) {
if (stickinessMetadataKeyFromServiceConfig.endsWith(Metadata.BINARY_HEADER_SUFFIX)) {
logger.log(Level.FINE, "Binary stickiness header is not supported. The header '{0}' will be ignored", stickinessMetadataKeyFromServiceConfig);
} else {
StickinessState stickinessState = this.stickinessState;
if (stickinessState == null || !stickinessState.key.name().equals(stickinessMetadataKeyFromServiceConfig)) {
this.stickinessState = new StickinessState(stickinessMetadataKeyFromServiceConfig);
}
}
}
}
for (EquivalentAddressGroup equivalentAddressGroup : set) {
Builder builder = Attributes.newBuilder().set(STATE_INFO, new Ref(ConnectivityStateInfo.forNonError(ConnectivityState.IDLE)));
Ref ref = null;
if (this.stickinessState != null) {
Key key = STICKY_REF;
Ref ref2 = new Ref(null);
builder.set(key, ref2);
ref = ref2;
}
Subchannel subchannel = (Subchannel) Preconditions.checkNotNull(this.helper.createSubchannel(equivalentAddressGroup, builder.build()), "subchannel");
if (ref != null) {
ref.value = subchannel;
}
this.subchannels.put(equivalentAddressGroup, subchannel);
subchannel.requestConnection();
}
for (EquivalentAddressGroup remove : set2) {
shutdownSubchannel((Subchannel) this.subchannels.remove(remove));
}
updateBalancingState();
}
public void handleNameResolutionError(Status status) {
ConnectivityState connectivityState = ConnectivityState.TRANSIENT_FAILURE;
RoundRobinPicker roundRobinPicker = this.currentPicker;
if (!(roundRobinPicker instanceof ReadyPicker)) {
roundRobinPicker = new EmptyPicker(status);
}
updateBalancingState(connectivityState, roundRobinPicker);
}
public void handleSubchannelState(Subchannel subchannel, ConnectivityStateInfo connectivityStateInfo) {
if (this.subchannels.get(subchannel.getAddresses()) == subchannel) {
if (connectivityStateInfo.getState() == ConnectivityState.SHUTDOWN) {
StickinessState stickinessState = this.stickinessState;
if (stickinessState != null) {
stickinessState.remove(subchannel);
}
}
if (connectivityStateInfo.getState() == ConnectivityState.IDLE) {
subchannel.requestConnection();
}
getSubchannelStateInfoRef(subchannel).value = connectivityStateInfo;
updateBalancingState();
}
}
private void shutdownSubchannel(Subchannel subchannel) {
subchannel.shutdown();
getSubchannelStateInfoRef(subchannel).value = ConnectivityStateInfo.forNonError(ConnectivityState.SHUTDOWN);
StickinessState stickinessState = this.stickinessState;
if (stickinessState != null) {
stickinessState.remove(subchannel);
}
}
public void shutdown() {
for (Subchannel shutdownSubchannel : getSubchannels()) {
shutdownSubchannel(shutdownSubchannel);
}
}
private void updateBalancingState() {
List filterNonFailingSubchannels = filterNonFailingSubchannels(getSubchannels());
if (filterNonFailingSubchannels.isEmpty()) {
Object obj = null;
Status status = EMPTY_OK;
for (Subchannel subchannelStateInfoRef : getSubchannels()) {
ConnectivityStateInfo connectivityStateInfo = (ConnectivityStateInfo) getSubchannelStateInfoRef(subchannelStateInfoRef).value;
if (connectivityStateInfo.getState() == ConnectivityState.CONNECTING || connectivityStateInfo.getState() == ConnectivityState.IDLE) {
obj = 1;
}
if (status == EMPTY_OK || !status.isOk()) {
status = connectivityStateInfo.getStatus();
}
}
updateBalancingState(obj != null ? ConnectivityState.CONNECTING : ConnectivityState.TRANSIENT_FAILURE, new EmptyPicker(status));
return;
}
updateBalancingState(ConnectivityState.READY, new ReadyPicker(filterNonFailingSubchannels, this.random.nextInt(filterNonFailingSubchannels.size()), this.stickinessState));
}
private void updateBalancingState(ConnectivityState connectivityState, RoundRobinPicker roundRobinPicker) {
if (connectivityState != this.currentState || !roundRobinPicker.isEquivalentTo(this.currentPicker)) {
this.helper.updateBalancingState(connectivityState, roundRobinPicker);
this.currentState = connectivityState;
this.currentPicker = roundRobinPicker;
}
}
private static List<Subchannel> filterNonFailingSubchannels(Collection<Subchannel> collection) {
List<Subchannel> arrayList = new ArrayList(collection.size());
for (Subchannel subchannel : collection) {
if (isReady(subchannel)) {
arrayList.add(subchannel);
}
}
return arrayList;
}
private static Set<EquivalentAddressGroup> stripAttrs(List<EquivalentAddressGroup> list) {
Set<EquivalentAddressGroup> hashSet = new HashSet(list.size());
for (EquivalentAddressGroup addresses : list) {
hashSet.add(new EquivalentAddressGroup(addresses.getAddresses()));
}
return hashSet;
}
@VisibleForTesting
Collection<Subchannel> getSubchannels() {
return this.subchannels.values();
}
private static Ref<ConnectivityStateInfo> getSubchannelStateInfoRef(Subchannel subchannel) {
return (Ref) Preconditions.checkNotNull(subchannel.getAttributes().get(STATE_INFO), "STATE_INFO");
}
static boolean isReady(Subchannel subchannel) {
return ((ConnectivityStateInfo) getSubchannelStateInfoRef(subchannel).value).getState() == ConnectivityState.READY;
}
private static <T> Set<T> setsDifference(Set<T> set, Set<T> set2) {
Set<T> hashSet = new HashSet(set);
hashSet.removeAll(set2);
return hashSet;
}
Map<String, Ref<Subchannel>> getStickinessMapForTest() {
StickinessState stickinessState = this.stickinessState;
if (stickinessState == null) {
return null;
}
return stickinessState.stickinessMap;
}
}
private static abstract class RoundRobinPicker extends SubchannelPicker {
abstract boolean isEquivalentTo(RoundRobinPicker roundRobinPicker);
private RoundRobinPicker() {
}
}
@VisibleForTesting
static final class EmptyPicker extends RoundRobinPicker {
private final Status status;
EmptyPicker(@Nonnull Status status) {
super();
this.status = (Status) Preconditions.checkNotNull(status, NotificationCompat.CATEGORY_STATUS);
}
public PickResult pickSubchannel(PickSubchannelArgs pickSubchannelArgs) {
return this.status.isOk() ? PickResult.withNoResult() : PickResult.withError(this.status);
}
boolean isEquivalentTo(RoundRobinPicker roundRobinPicker) {
if (roundRobinPicker instanceof EmptyPicker) {
EmptyPicker emptyPicker = (EmptyPicker) roundRobinPicker;
if (Objects.equal(this.status, emptyPicker.status) || (this.status.isOk() && emptyPicker.status.isOk())) {
return true;
}
}
return false;
}
}
@VisibleForTesting
static final class ReadyPicker extends RoundRobinPicker {
private static final AtomicIntegerFieldUpdater<ReadyPicker> indexUpdater = AtomicIntegerFieldUpdater.newUpdater(ReadyPicker.class, Param.INDEX);
private volatile int index;
private final List<Subchannel> list;
@Nullable
private final StickinessState stickinessState;
ReadyPicker(List<Subchannel> list, int i, @Nullable StickinessState stickinessState) {
super();
Preconditions.checkArgument(list.isEmpty() ^ 1, "empty list");
this.list = list;
this.stickinessState = stickinessState;
this.index = i - 1;
}
/* JADX WARNING: Removed duplicated region for block: B:11:0x0031 */
public io.grpc.LoadBalancer.PickResult pickSubchannel(io.grpc.LoadBalancer.PickSubchannelArgs r3) {
/*
r2 = this;
r0 = r2.stickinessState;
if (r0 == 0) goto L_0x002d;
L_0x0004:
r3 = r3.getHeaders();
r0 = r2.stickinessState;
r0 = r0.key;
r3 = r3.get(r0);
r3 = (java.lang.String) r3;
if (r3 == 0) goto L_0x002d;
L_0x0014:
r0 = r2.stickinessState;
r0 = r0.getSubchannel(r3);
if (r0 == 0) goto L_0x0022;
L_0x001c:
r1 = io.grpc.util.RoundRobinLoadBalancerFactory.RoundRobinLoadBalancer.isReady(r0);
if (r1 != 0) goto L_0x002e;
L_0x0022:
r0 = r2.stickinessState;
r1 = r2.nextSubchannel();
r0 = r0.maybeRegister(r3, r1);
goto L_0x002e;
L_0x002d:
r0 = 0;
L_0x002e:
if (r0 == 0) goto L_0x0031;
L_0x0030:
goto L_0x0035;
L_0x0031:
r0 = r2.nextSubchannel();
L_0x0035:
r3 = io.grpc.LoadBalancer.PickResult.withSubchannel(r0);
return r3;
*/
throw new UnsupportedOperationException("Method not decompiled: io.grpc.util.RoundRobinLoadBalancerFactory.ReadyPicker.pickSubchannel(io.grpc.LoadBalancer$PickSubchannelArgs):io.grpc.LoadBalancer$PickResult");
}
private Subchannel nextSubchannel() {
int size = this.list.size();
int incrementAndGet = indexUpdater.incrementAndGet(this);
if (incrementAndGet >= size) {
size = incrementAndGet % size;
indexUpdater.compareAndSet(this, incrementAndGet, size);
} else {
size = incrementAndGet;
}
return (Subchannel) this.list.get(size);
}
@VisibleForTesting
List<Subchannel> getList() {
return this.list;
}
boolean isEquivalentTo(RoundRobinPicker roundRobinPicker) {
boolean z = false;
if (!(roundRobinPicker instanceof ReadyPicker)) {
return false;
}
ReadyPicker readyPicker = (ReadyPicker) roundRobinPicker;
if (readyPicker == this || (this.stickinessState == readyPicker.stickinessState && this.list.size() == readyPicker.list.size() && new HashSet(this.list).containsAll(readyPicker.list))) {
z = true;
}
return z;
}
}
private RoundRobinLoadBalancerFactory() {
}
public static RoundRobinLoadBalancerFactory getInstance() {
return INSTANCE;
}
public LoadBalancer newLoadBalancer(Helper helper) {
return new RoundRobinLoadBalancer(helper);
}
}
| UTF-8 | Java | 18,011 | java | RoundRobinLoadBalancerFactory.java | Java | [
{
"context": "Nullable;\r\n\r\n@ExperimentalApi(\"https://github.com/grpc/grpc-java/issues/1771\")\r\npublic final class Round",
"end": 1558,
"score": 0.9993504881858826,
"start": 1554,
"tag": "USERNAME",
"value": "grpc"
},
{
"context": "essState != null) {\r\n Key... | null | [] | package io.grpc.util;
import androidx.core.app.NotificationCompat;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.firebase.analytics.FirebaseAnalytics.Param;
import io.grpc.Attributes;
import io.grpc.Attributes.Builder;
import io.grpc.Attributes.Key;
import io.grpc.ConnectivityState;
import io.grpc.ConnectivityStateInfo;
import io.grpc.EquivalentAddressGroup;
import io.grpc.ExperimentalApi;
import io.grpc.LoadBalancer;
import io.grpc.LoadBalancer.Factory;
import io.grpc.LoadBalancer.Helper;
import io.grpc.LoadBalancer.PickResult;
import io.grpc.LoadBalancer.PickSubchannelArgs;
import io.grpc.LoadBalancer.Subchannel;
import io.grpc.LoadBalancer.SubchannelPicker;
import io.grpc.Metadata;
import io.grpc.Status;
import io.grpc.internal.GrpcAttributes;
import io.grpc.internal.ServiceConfigUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771")
public final class RoundRobinLoadBalancerFactory extends Factory {
private static final RoundRobinLoadBalancerFactory INSTANCE = new RoundRobinLoadBalancerFactory();
@VisibleForTesting
static final class Ref<T> {
T value;
Ref(T t) {
this.value = t;
}
}
@VisibleForTesting
static final class RoundRobinLoadBalancer extends LoadBalancer {
private static final Status EMPTY_OK = Status.OK.withDescription("no subchannels ready");
@VisibleForTesting
static final Key<Ref<ConnectivityStateInfo>> STATE_INFO = Key.create("state-info");
static final Key<Ref<Subchannel>> STICKY_REF = Key.create("sticky-ref");
private static final Logger logger = Logger.getLogger(RoundRobinLoadBalancer.class.getName());
private RoundRobinPicker currentPicker = new EmptyPicker(EMPTY_OK);
private ConnectivityState currentState;
private final Helper helper;
private final Random random;
@Nullable
private StickinessState stickinessState;
private final Map<EquivalentAddressGroup, Subchannel> subchannels = new HashMap();
@VisibleForTesting
static final class StickinessState {
static final int MAX_ENTRIES = 1000;
final Queue<String> evictionQueue = new ConcurrentLinkedQueue();
final Metadata.Key<String> key;
final ConcurrentMap<String, Ref<Subchannel>> stickinessMap = new ConcurrentHashMap();
StickinessState(@Nonnull String str) {
this.key = Metadata.Key.of(str, Metadata.ASCII_STRING_MARSHALLER);
}
@Nonnull
Subchannel maybeRegister(String str, @Nonnull Subchannel subchannel) {
Ref ref = (Ref) subchannel.getAttributes().get(RoundRobinLoadBalancer.STICKY_REF);
Ref ref2;
do {
ref2 = (Ref) this.stickinessMap.putIfAbsent(str, ref);
if (ref2 == null) {
addToEvictionQueue(str);
return subchannel;
}
Subchannel subchannel2 = (Subchannel) ref2.value;
if (subchannel2 != null && RoundRobinLoadBalancer.isReady(subchannel2)) {
return subchannel2;
}
} while (!this.stickinessMap.replace(str, ref2, ref));
return subchannel;
}
private void addToEvictionQueue(String str) {
while (this.stickinessMap.size() >= 1000) {
String str2 = (String) this.evictionQueue.poll();
if (str2 == null) {
break;
}
this.stickinessMap.remove(str2);
}
this.evictionQueue.add(str);
}
void remove(Subchannel subchannel) {
((Ref) subchannel.getAttributes().get(RoundRobinLoadBalancer.STICKY_REF)).value = null;
}
@Nullable
Subchannel getSubchannel(String str) {
Ref ref = (Ref) this.stickinessMap.get(str);
return ref != null ? (Subchannel) ref.value : null;
}
}
RoundRobinLoadBalancer(Helper helper) {
this.helper = (Helper) Preconditions.checkNotNull(helper, "helper");
this.random = new Random();
}
public void handleResolvedAddressGroups(List<EquivalentAddressGroup> list, Attributes attributes) {
Set keySet = this.subchannels.keySet();
Set stripAttrs = stripAttrs(list);
Set<EquivalentAddressGroup> set = setsDifference(stripAttrs, keySet);
Set<EquivalentAddressGroup> set2 = setsDifference(keySet, stripAttrs);
Map map = (Map) attributes.get(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG);
if (map != null) {
String stickinessMetadataKeyFromServiceConfig = ServiceConfigUtil.getStickinessMetadataKeyFromServiceConfig(map);
if (stickinessMetadataKeyFromServiceConfig != null) {
if (stickinessMetadataKeyFromServiceConfig.endsWith(Metadata.BINARY_HEADER_SUFFIX)) {
logger.log(Level.FINE, "Binary stickiness header is not supported. The header '{0}' will be ignored", stickinessMetadataKeyFromServiceConfig);
} else {
StickinessState stickinessState = this.stickinessState;
if (stickinessState == null || !stickinessState.key.name().equals(stickinessMetadataKeyFromServiceConfig)) {
this.stickinessState = new StickinessState(stickinessMetadataKeyFromServiceConfig);
}
}
}
}
for (EquivalentAddressGroup equivalentAddressGroup : set) {
Builder builder = Attributes.newBuilder().set(STATE_INFO, new Ref(ConnectivityStateInfo.forNonError(ConnectivityState.IDLE)));
Ref ref = null;
if (this.stickinessState != null) {
Key key = STICKY_REF;
Ref ref2 = new Ref(null);
builder.set(key, ref2);
ref = ref2;
}
Subchannel subchannel = (Subchannel) Preconditions.checkNotNull(this.helper.createSubchannel(equivalentAddressGroup, builder.build()), "subchannel");
if (ref != null) {
ref.value = subchannel;
}
this.subchannels.put(equivalentAddressGroup, subchannel);
subchannel.requestConnection();
}
for (EquivalentAddressGroup remove : set2) {
shutdownSubchannel((Subchannel) this.subchannels.remove(remove));
}
updateBalancingState();
}
public void handleNameResolutionError(Status status) {
ConnectivityState connectivityState = ConnectivityState.TRANSIENT_FAILURE;
RoundRobinPicker roundRobinPicker = this.currentPicker;
if (!(roundRobinPicker instanceof ReadyPicker)) {
roundRobinPicker = new EmptyPicker(status);
}
updateBalancingState(connectivityState, roundRobinPicker);
}
public void handleSubchannelState(Subchannel subchannel, ConnectivityStateInfo connectivityStateInfo) {
if (this.subchannels.get(subchannel.getAddresses()) == subchannel) {
if (connectivityStateInfo.getState() == ConnectivityState.SHUTDOWN) {
StickinessState stickinessState = this.stickinessState;
if (stickinessState != null) {
stickinessState.remove(subchannel);
}
}
if (connectivityStateInfo.getState() == ConnectivityState.IDLE) {
subchannel.requestConnection();
}
getSubchannelStateInfoRef(subchannel).value = connectivityStateInfo;
updateBalancingState();
}
}
private void shutdownSubchannel(Subchannel subchannel) {
subchannel.shutdown();
getSubchannelStateInfoRef(subchannel).value = ConnectivityStateInfo.forNonError(ConnectivityState.SHUTDOWN);
StickinessState stickinessState = this.stickinessState;
if (stickinessState != null) {
stickinessState.remove(subchannel);
}
}
public void shutdown() {
for (Subchannel shutdownSubchannel : getSubchannels()) {
shutdownSubchannel(shutdownSubchannel);
}
}
private void updateBalancingState() {
List filterNonFailingSubchannels = filterNonFailingSubchannels(getSubchannels());
if (filterNonFailingSubchannels.isEmpty()) {
Object obj = null;
Status status = EMPTY_OK;
for (Subchannel subchannelStateInfoRef : getSubchannels()) {
ConnectivityStateInfo connectivityStateInfo = (ConnectivityStateInfo) getSubchannelStateInfoRef(subchannelStateInfoRef).value;
if (connectivityStateInfo.getState() == ConnectivityState.CONNECTING || connectivityStateInfo.getState() == ConnectivityState.IDLE) {
obj = 1;
}
if (status == EMPTY_OK || !status.isOk()) {
status = connectivityStateInfo.getStatus();
}
}
updateBalancingState(obj != null ? ConnectivityState.CONNECTING : ConnectivityState.TRANSIENT_FAILURE, new EmptyPicker(status));
return;
}
updateBalancingState(ConnectivityState.READY, new ReadyPicker(filterNonFailingSubchannels, this.random.nextInt(filterNonFailingSubchannels.size()), this.stickinessState));
}
private void updateBalancingState(ConnectivityState connectivityState, RoundRobinPicker roundRobinPicker) {
if (connectivityState != this.currentState || !roundRobinPicker.isEquivalentTo(this.currentPicker)) {
this.helper.updateBalancingState(connectivityState, roundRobinPicker);
this.currentState = connectivityState;
this.currentPicker = roundRobinPicker;
}
}
private static List<Subchannel> filterNonFailingSubchannels(Collection<Subchannel> collection) {
List<Subchannel> arrayList = new ArrayList(collection.size());
for (Subchannel subchannel : collection) {
if (isReady(subchannel)) {
arrayList.add(subchannel);
}
}
return arrayList;
}
private static Set<EquivalentAddressGroup> stripAttrs(List<EquivalentAddressGroup> list) {
Set<EquivalentAddressGroup> hashSet = new HashSet(list.size());
for (EquivalentAddressGroup addresses : list) {
hashSet.add(new EquivalentAddressGroup(addresses.getAddresses()));
}
return hashSet;
}
@VisibleForTesting
Collection<Subchannel> getSubchannels() {
return this.subchannels.values();
}
private static Ref<ConnectivityStateInfo> getSubchannelStateInfoRef(Subchannel subchannel) {
return (Ref) Preconditions.checkNotNull(subchannel.getAttributes().get(STATE_INFO), "STATE_INFO");
}
static boolean isReady(Subchannel subchannel) {
return ((ConnectivityStateInfo) getSubchannelStateInfoRef(subchannel).value).getState() == ConnectivityState.READY;
}
private static <T> Set<T> setsDifference(Set<T> set, Set<T> set2) {
Set<T> hashSet = new HashSet(set);
hashSet.removeAll(set2);
return hashSet;
}
Map<String, Ref<Subchannel>> getStickinessMapForTest() {
StickinessState stickinessState = this.stickinessState;
if (stickinessState == null) {
return null;
}
return stickinessState.stickinessMap;
}
}
private static abstract class RoundRobinPicker extends SubchannelPicker {
abstract boolean isEquivalentTo(RoundRobinPicker roundRobinPicker);
private RoundRobinPicker() {
}
}
@VisibleForTesting
static final class EmptyPicker extends RoundRobinPicker {
private final Status status;
EmptyPicker(@Nonnull Status status) {
super();
this.status = (Status) Preconditions.checkNotNull(status, NotificationCompat.CATEGORY_STATUS);
}
public PickResult pickSubchannel(PickSubchannelArgs pickSubchannelArgs) {
return this.status.isOk() ? PickResult.withNoResult() : PickResult.withError(this.status);
}
boolean isEquivalentTo(RoundRobinPicker roundRobinPicker) {
if (roundRobinPicker instanceof EmptyPicker) {
EmptyPicker emptyPicker = (EmptyPicker) roundRobinPicker;
if (Objects.equal(this.status, emptyPicker.status) || (this.status.isOk() && emptyPicker.status.isOk())) {
return true;
}
}
return false;
}
}
@VisibleForTesting
static final class ReadyPicker extends RoundRobinPicker {
private static final AtomicIntegerFieldUpdater<ReadyPicker> indexUpdater = AtomicIntegerFieldUpdater.newUpdater(ReadyPicker.class, Param.INDEX);
private volatile int index;
private final List<Subchannel> list;
@Nullable
private final StickinessState stickinessState;
ReadyPicker(List<Subchannel> list, int i, @Nullable StickinessState stickinessState) {
super();
Preconditions.checkArgument(list.isEmpty() ^ 1, "empty list");
this.list = list;
this.stickinessState = stickinessState;
this.index = i - 1;
}
/* JADX WARNING: Removed duplicated region for block: B:11:0x0031 */
public io.grpc.LoadBalancer.PickResult pickSubchannel(io.grpc.LoadBalancer.PickSubchannelArgs r3) {
/*
r2 = this;
r0 = r2.stickinessState;
if (r0 == 0) goto L_0x002d;
L_0x0004:
r3 = r3.getHeaders();
r0 = r2.stickinessState;
r0 = r0.key;
r3 = r3.get(r0);
r3 = (java.lang.String) r3;
if (r3 == 0) goto L_0x002d;
L_0x0014:
r0 = r2.stickinessState;
r0 = r0.getSubchannel(r3);
if (r0 == 0) goto L_0x0022;
L_0x001c:
r1 = io.grpc.util.RoundRobinLoadBalancerFactory.RoundRobinLoadBalancer.isReady(r0);
if (r1 != 0) goto L_0x002e;
L_0x0022:
r0 = r2.stickinessState;
r1 = r2.nextSubchannel();
r0 = r0.maybeRegister(r3, r1);
goto L_0x002e;
L_0x002d:
r0 = 0;
L_0x002e:
if (r0 == 0) goto L_0x0031;
L_0x0030:
goto L_0x0035;
L_0x0031:
r0 = r2.nextSubchannel();
L_0x0035:
r3 = io.grpc.LoadBalancer.PickResult.withSubchannel(r0);
return r3;
*/
throw new UnsupportedOperationException("Method not decompiled: io.grpc.util.RoundRobinLoadBalancerFactory.ReadyPicker.pickSubchannel(io.grpc.LoadBalancer$PickSubchannelArgs):io.grpc.LoadBalancer$PickResult");
}
private Subchannel nextSubchannel() {
int size = this.list.size();
int incrementAndGet = indexUpdater.incrementAndGet(this);
if (incrementAndGet >= size) {
size = incrementAndGet % size;
indexUpdater.compareAndSet(this, incrementAndGet, size);
} else {
size = incrementAndGet;
}
return (Subchannel) this.list.get(size);
}
@VisibleForTesting
List<Subchannel> getList() {
return this.list;
}
boolean isEquivalentTo(RoundRobinPicker roundRobinPicker) {
boolean z = false;
if (!(roundRobinPicker instanceof ReadyPicker)) {
return false;
}
ReadyPicker readyPicker = (ReadyPicker) roundRobinPicker;
if (readyPicker == this || (this.stickinessState == readyPicker.stickinessState && this.list.size() == readyPicker.list.size() && new HashSet(this.list).containsAll(readyPicker.list))) {
z = true;
}
return z;
}
}
private RoundRobinLoadBalancerFactory() {
}
public static RoundRobinLoadBalancerFactory getInstance() {
return INSTANCE;
}
public LoadBalancer newLoadBalancer(Helper helper) {
return new RoundRobinLoadBalancer(helper);
}
}
| 18,011 | 0.60402 | 0.595025 | 410 | 41.929268 | 35.755569 | 221 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.597561 | false | false | 10 |
61c6d7e71e15171ec1c4d22f9adac2820974ce57 | 21,689,584,880,354 | d5c9c369f3909678c17e347d964c6935c86b0c9c | /src/main/java/model/Suscripcion.java | a2d08f2934abb9e586baa3e0fe8f4c9921b262f9 | [] | no_license | jmbustos010/PII_2021_1_p3_frontend | https://github.com/jmbustos010/PII_2021_1_p3_frontend | bf5a13fbc8bc83b3486a1fcf0d7d6ed28c99f011 | 26116864e9196bbd11f4592e6d0dc2afc55efbef | refs/heads/master | 2023-04-14T16:58:57.540000 | 2021-04-23T02:14:42 | 2021-04-23T02:14:42 | 360,737,385 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model;
public class Suscripcion { private long id;
private String tiposuscripcion;
private String fechainicio;
private String fechacierre;
private String nombrealumno;
private long precio;
public Suscripcion(){
}
public Suscripcion(long id, String tiposuscripcion, String fechainicio, String fechacierre, String nombrealumno, long precio){
this.id = id;
this.tiposuscripcion = tiposuscripcion;
this.fechainicio = fechainicio;
this.fechacierre = fechacierre;
this.nombrealumno = nombrealumno;
this.precio = precio;
}
/////setters/////
public void setId(long id) {
this.id = id;
}
public void setPrecio(long precio) {
this.precio = precio;
}
public void setTiposuscripcion(String tiposuscripcion) {
this.tiposuscripcion = tiposuscripcion;
}
public void setFechainicio(String fechainicio) {
this.fechainicio = fechainicio;
}
public void setFechacierre(String fechacierre) {
this.fechacierre = fechacierre;
}
public void setNombrealumno(String nombrealumno) {
this.nombrealumno = nombrealumno;
}
//////getters/////
public long getId() {
return id;
}
public long getPrecio() {
return precio;
}
public String getFechacierre() {
return fechacierre;
}
public String getFechainicio() {
return fechainicio;
}
public String getnombrealumno() {
return nombrealumno;
}
public String gettiposuscripcion() {
return tiposuscripcion;
}
}
| UTF-8 | Java | 1,664 | java | Suscripcion.java | Java | [] | null | [] | package model;
public class Suscripcion { private long id;
private String tiposuscripcion;
private String fechainicio;
private String fechacierre;
private String nombrealumno;
private long precio;
public Suscripcion(){
}
public Suscripcion(long id, String tiposuscripcion, String fechainicio, String fechacierre, String nombrealumno, long precio){
this.id = id;
this.tiposuscripcion = tiposuscripcion;
this.fechainicio = fechainicio;
this.fechacierre = fechacierre;
this.nombrealumno = nombrealumno;
this.precio = precio;
}
/////setters/////
public void setId(long id) {
this.id = id;
}
public void setPrecio(long precio) {
this.precio = precio;
}
public void setTiposuscripcion(String tiposuscripcion) {
this.tiposuscripcion = tiposuscripcion;
}
public void setFechainicio(String fechainicio) {
this.fechainicio = fechainicio;
}
public void setFechacierre(String fechacierre) {
this.fechacierre = fechacierre;
}
public void setNombrealumno(String nombrealumno) {
this.nombrealumno = nombrealumno;
}
//////getters/////
public long getId() {
return id;
}
public long getPrecio() {
return precio;
}
public String getFechacierre() {
return fechacierre;
}
public String getFechainicio() {
return fechainicio;
}
public String getnombrealumno() {
return nombrealumno;
}
public String gettiposuscripcion() {
return tiposuscripcion;
}
}
| 1,664 | 0.623798 | 0.623798 | 72 | 22.111111 | 21.964336 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 10 |
87cf48d19f2321e2e1139a29fef6b80e8cd47535 | 6,167,573,091,559 | 65cdbf762a9488aa5d10018a27752797482b999d | /jscience/mathematics/src/main/java/org/jscience/mathematics/linear/ComplexVector.java | 3a68e4bc25056530d8f7a13f570d52048a0c9e32 | [
"BSD-2-Clause"
] | permissive | krichter722/jscience | https://github.com/krichter722/jscience | 3386559f99e54b21be13741f8c22ccfbf0c8dbdb | 968a07f2c7838778feb19b6d04807a8d66b03fe0 | refs/heads/master | 2021-01-10T08:34:20.420000 | 2014-01-09T21:37:33 | 2014-01-09T21:37:33 | 47,670,017 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
* Copyright (C) 2014 - JScience (http://jscience.org/)
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software is
* freely granted, provided that this notice is preserved.
*/
package org.jscience.mathematics.linear;
import java.util.List;
import javolution.util.Index;
import javolution.context.ComputeContext;
import org.jscience.mathematics.number.Complex;
import org.jscience.mathematics.number.Float64;
import org.jscience.mathematics.structure.NormedVectorSpace;
/**
* <p> A {@link DenseVector dense vector} of 64 bits floating points
* complex numbers.
* [code]
* // Creates a complex vector of dimension 3.
* FloatVector V = Vectors.floatVector(new double[]{0.1, 0.2, 0.3},
* new double[]{0.7, 0.7, 0.7});
* double x1 = V.getRealValue(0);
* double x2 = V.getImaginaryValue(0);
* double norm = V.normValue();
* [/code]</p>
*
* @author <a href="mailto:jean-marie@dautelle.com">Jean-Marie Dautelle</a>
* @version 5.0, December 12, 2009
* @see SparseVector
*/
public interface ComplexVector extends DenseVector<Complex<Float64>>,
NormedVectorSpace<Vector<Complex<Float64>>, Complex<Float64>>,
ComputeContext.Local {
/**
* Returns the {@code double} real value of a single complex number
* element of this vector.
*
* @param i the element index (range [0..dimension[).
* @return <code>get(i).getReal().doubleValue()</code>.
* @throws IndexOutOfBoundsException <code>(i < 0) || (i >= getDimension())</code>
*/
double getRealValue(int i);
/**
* Returns the {@code double} imaginary value of a single complex number
* element of this vector.
*
* @param i the element index (range [0..dimension[).
* @return <code>get(i).getImaginary().doubleValue()</code>.
* @throws IndexOutOfBoundsException <code>(i < 0) || (i >= getDimension())</code>
*/
double getImaginaryValue(int i);
/**
* Returns the {@code double} value of the {@link NormedVectorSpace#norm()
* norm} of this vector.
*
* @return <code>norm().magnitude()</code>.
*/
double normValue();
@Override
ComplexMatrix asColumn();
@Override
ComplexMatrix asRow();
@Override
ComplexVector cross(Vector<Complex<Float64>> that);
@Override
ComplexVector getSubVector(List<Index> indices);
@Override
ComplexVector minus(Vector<Complex<Float64>> that);
@Override
ComplexVector opposite();
@Override
ComplexVector plus(Vector<Complex<Float64>> that);
@Override
ComplexMatrix tensor(Vector<Complex<Float64>> that);
@Override
ComplexVector times(Complex<Float64> k);
}
| UTF-8 | Java | 2,670 | java | ComplexVector.java | Java | [
{
"context": "de]</p> \n * \n * @author <a href=\"mailto:jean-marie@dautelle.com\">Jean-Marie Dautelle</a>\n * @version 5.0, Decembe",
"end": 1037,
"score": 0.9999276995658875,
"start": 1014,
"tag": "EMAIL",
"value": "jean-marie@dautelle.com"
},
{
"context": " @author <a hr... | null | [] | /*
* JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
* Copyright (C) 2014 - JScience (http://jscience.org/)
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software is
* freely granted, provided that this notice is preserved.
*/
package org.jscience.mathematics.linear;
import java.util.List;
import javolution.util.Index;
import javolution.context.ComputeContext;
import org.jscience.mathematics.number.Complex;
import org.jscience.mathematics.number.Float64;
import org.jscience.mathematics.structure.NormedVectorSpace;
/**
* <p> A {@link DenseVector dense vector} of 64 bits floating points
* complex numbers.
* [code]
* // Creates a complex vector of dimension 3.
* FloatVector V = Vectors.floatVector(new double[]{0.1, 0.2, 0.3},
* new double[]{0.7, 0.7, 0.7});
* double x1 = V.getRealValue(0);
* double x2 = V.getImaginaryValue(0);
* double norm = V.normValue();
* [/code]</p>
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version 5.0, December 12, 2009
* @see SparseVector
*/
public interface ComplexVector extends DenseVector<Complex<Float64>>,
NormedVectorSpace<Vector<Complex<Float64>>, Complex<Float64>>,
ComputeContext.Local {
/**
* Returns the {@code double} real value of a single complex number
* element of this vector.
*
* @param i the element index (range [0..dimension[).
* @return <code>get(i).getReal().doubleValue()</code>.
* @throws IndexOutOfBoundsException <code>(i < 0) || (i >= getDimension())</code>
*/
double getRealValue(int i);
/**
* Returns the {@code double} imaginary value of a single complex number
* element of this vector.
*
* @param i the element index (range [0..dimension[).
* @return <code>get(i).getImaginary().doubleValue()</code>.
* @throws IndexOutOfBoundsException <code>(i < 0) || (i >= getDimension())</code>
*/
double getImaginaryValue(int i);
/**
* Returns the {@code double} value of the {@link NormedVectorSpace#norm()
* norm} of this vector.
*
* @return <code>norm().magnitude()</code>.
*/
double normValue();
@Override
ComplexMatrix asColumn();
@Override
ComplexMatrix asRow();
@Override
ComplexVector cross(Vector<Complex<Float64>> that);
@Override
ComplexVector getSubVector(List<Index> indices);
@Override
ComplexVector minus(Vector<Complex<Float64>> that);
@Override
ComplexVector opposite();
@Override
ComplexVector plus(Vector<Complex<Float64>> that);
@Override
ComplexMatrix tensor(Vector<Complex<Float64>> that);
@Override
ComplexVector times(Complex<Float64> k);
}
| 2,641 | 0.698502 | 0.678652 | 95 | 27.105263 | 25.662783 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.989474 | false | false | 10 |
18532bebc3a3d660204d1652087040848d24baf6 | 20,031,727,518,271 | bc9e2d905e9605371f3235159a28adf1375c068c | /indhio-crypt/src/main/java/com/indhio/crypt/services/ContaService.java | e79e9eabba31f6165ce6e7d8ff3593d3b88922dc | [] | no_license | indhio/portfolio | https://github.com/indhio/portfolio | 644da48ebdc9590c71674fb50354f2f2b83f687d | 2a36c4a3edd76f5e8dfc9f76cd6523cc70f7f6cd | refs/heads/master | 2016-07-26T19:42:50.242000 | 2013-12-26T13:36:49 | 2013-12-26T13:36:49 | 2,617,684 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.indhio.crypt.services;
import java.util.List;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import com.indhio.crypt.dao.ContaDAO;
import com.indhio.crypt.entity.Conta;
@Name("contaService")
public class ContaService {
@In(create = true, required = false)
private ContaDAO contaDAO;
public List<Conta> getContasPorNome(String nome, Long idUsuario) {
return contaDAO.getContasPorNome(nome, idUsuario);
}
public Conta get(Long id) {
return contaDAO.find(id);
}
public void update(Conta conta) {
if (conta != null) {
if (conta.getId() == null || conta.getId().intValue() == 0) {
contaDAO.save(conta);
} else {
contaDAO.merge(conta);
}
}
}
public void delete(Long id) {
contaDAO.delete(id);
}
}
| UTF-8 | Java | 820 | java | ContaService.java | Java | [] | null | [] | package com.indhio.crypt.services;
import java.util.List;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import com.indhio.crypt.dao.ContaDAO;
import com.indhio.crypt.entity.Conta;
@Name("contaService")
public class ContaService {
@In(create = true, required = false)
private ContaDAO contaDAO;
public List<Conta> getContasPorNome(String nome, Long idUsuario) {
return contaDAO.getContasPorNome(nome, idUsuario);
}
public Conta get(Long id) {
return contaDAO.find(id);
}
public void update(Conta conta) {
if (conta != null) {
if (conta.getId() == null || conta.getId().intValue() == 0) {
contaDAO.save(conta);
} else {
contaDAO.merge(conta);
}
}
}
public void delete(Long id) {
contaDAO.delete(id);
}
}
| 820 | 0.665854 | 0.664634 | 39 | 19.02564 | 18.748657 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.384615 | false | false | 14 |
870b4f794ece50c7fae0c1d9eace84c2409f7a91 | 21,010,980,076,230 | b684071a6a928b0bc93031cb13024cee03896508 | /src/test/java/ipacs/pages/ICMCompanyProfilePage.java | b4d0de20175fcc155279c8715c5106576ed41167 | [] | no_license | ashwini-codoid/IPACS-e2e | https://github.com/ashwini-codoid/IPACS-e2e | 74f26fdb9a88413e123651a58a9e9a673e69dd70 | 8cb56fa7782841b8a7e75c1f9374f77b1e551b1d | refs/heads/master | 2023-03-29T06:07:01.518000 | 2021-04-07T08:10:04 | 2021-04-07T08:10:04 | 350,616,280 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ipacs.pages;
import cap.common.BasePage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class ICMCompanyProfilePage extends BasePage {
public ICMCompanyProfilePage(WebDriver driver) {
super(driver);
}
@FindBy(how = How.XPATH, using = "((//div[@id='firmProfile'])//following::dt[1])[1]")
protected WebElement eleCompanyName;
@FindBy(how = How.XPATH, using = "(//label[.='Search:'])[1]")
protected WebElement btnSearchInDocumentation;
protected String strSubTabLocator = new StringBuilder()
.append("//a[text()='")
.append("<<SUBTAB>>").append("']").toString();
@FindBy(how = How.XPATH, using = "//div[.='Upload New Document']")
protected WebElement btnUploadNewDocumentInLicenses;
@FindBy(how = How.XPATH, using = "//div[.='Apply New License']")
protected WebElement btnApplyNewLicenseInLicensesInfo;
@FindBy(how = How.XPATH, using = "//a[text()='Documentation']")
protected WebElement btnDocumentationInCompanyProfile;
@FindBy(how = How.XPATH, using = "//a[text()='Licenses']")
protected WebElement btnLicensesInCompanyProfile;
@FindBy(how = How.XPATH, using = "//a[text()='Licenses Info']")
protected WebElement btnLicensesInfoInCompanyProfile;
@FindBy(how = How.XPATH, using = "//a[text()='Company Profile']")
protected WebElement btnCompanyInCompanyProfile;
public boolean verifyCompanyProfilePage() {
waitForElement(btnCompanyInCompanyProfile);
verifyElement(btnCompanyInCompanyProfile);
return verifyElement(eleCompanyName);
}
public boolean verifyDocumentationPage(){
click(btnDocumentationInCompanyProfile);
waitForElement(btnSearchInDocumentation);
return verifyElement(btnSearchInDocumentation);
}
public boolean verifyLicensesPage(){
click(btnLicensesInCompanyProfile);
waitForElement(btnUploadNewDocumentInLicenses);
return verifyElement(btnUploadNewDocumentInLicenses);
}
public boolean verifyLicensesInfoPage(){
click(btnLicensesInfoInCompanyProfile);
waitForElement(btnApplyNewLicenseInLicensesInfo);
return verifyElement(btnApplyNewLicenseInLicensesInfo);
}
} | UTF-8 | Java | 2,357 | java | ICMCompanyProfilePage.java | Java | [] | null | [] | package ipacs.pages;
import cap.common.BasePage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class ICMCompanyProfilePage extends BasePage {
public ICMCompanyProfilePage(WebDriver driver) {
super(driver);
}
@FindBy(how = How.XPATH, using = "((//div[@id='firmProfile'])//following::dt[1])[1]")
protected WebElement eleCompanyName;
@FindBy(how = How.XPATH, using = "(//label[.='Search:'])[1]")
protected WebElement btnSearchInDocumentation;
protected String strSubTabLocator = new StringBuilder()
.append("//a[text()='")
.append("<<SUBTAB>>").append("']").toString();
@FindBy(how = How.XPATH, using = "//div[.='Upload New Document']")
protected WebElement btnUploadNewDocumentInLicenses;
@FindBy(how = How.XPATH, using = "//div[.='Apply New License']")
protected WebElement btnApplyNewLicenseInLicensesInfo;
@FindBy(how = How.XPATH, using = "//a[text()='Documentation']")
protected WebElement btnDocumentationInCompanyProfile;
@FindBy(how = How.XPATH, using = "//a[text()='Licenses']")
protected WebElement btnLicensesInCompanyProfile;
@FindBy(how = How.XPATH, using = "//a[text()='Licenses Info']")
protected WebElement btnLicensesInfoInCompanyProfile;
@FindBy(how = How.XPATH, using = "//a[text()='Company Profile']")
protected WebElement btnCompanyInCompanyProfile;
public boolean verifyCompanyProfilePage() {
waitForElement(btnCompanyInCompanyProfile);
verifyElement(btnCompanyInCompanyProfile);
return verifyElement(eleCompanyName);
}
public boolean verifyDocumentationPage(){
click(btnDocumentationInCompanyProfile);
waitForElement(btnSearchInDocumentation);
return verifyElement(btnSearchInDocumentation);
}
public boolean verifyLicensesPage(){
click(btnLicensesInCompanyProfile);
waitForElement(btnUploadNewDocumentInLicenses);
return verifyElement(btnUploadNewDocumentInLicenses);
}
public boolean verifyLicensesInfoPage(){
click(btnLicensesInfoInCompanyProfile);
waitForElement(btnApplyNewLicenseInLicensesInfo);
return verifyElement(btnApplyNewLicenseInLicensesInfo);
}
} | 2,357 | 0.710649 | 0.709376 | 69 | 33.173912 | 26.405949 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false | 14 |
ecb8017e354280ab3218286e179e8875f8ba7e5d | 14,568,529,129,961 | 26e888bf1d25bcdc42b6c82c601560e7d650ddc2 | /202108271515/springmvc/src/main/java/com/zichen/factory/DynamicFactory.java | a3f9038738f5716233b56e748f79608d670b2f70 | [] | no_license | zichenlbl/LearnSpringMVC | https://github.com/zichenlbl/LearnSpringMVC | 8ae59148cf6e02bf49d698aeac1e4eee82f2c943 | d0bc71e5b13e15a512cf28df0d90a93581d2e84d | refs/heads/main | 2023-07-25T09:25:55.478000 | 2021-08-29T11:55:51 | 2021-08-29T11:55:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zichen.factory;
import com.zichen.dao.UserDao;
import com.zichen.dao.impl.UserDaoImpl;
/**
* 工厂模式实例方法创建对象
* @author zc
* @date 2021-08-27 16:23
*/
public class DynamicFactory {
public UserDao getUserDao() {
return new UserDaoImpl();
}
}
| UTF-8 | Java | 297 | java | DynamicFactory.java | Java | [
{
"context": ".impl.UserDaoImpl;\n\n/**\n * 工厂模式实例方法创建对象\n * @author zc\n * @date 2021-08-27 16:23\n */\npublic class Dynami",
"end": 134,
"score": 0.9996448755264282,
"start": 132,
"tag": "USERNAME",
"value": "zc"
}
] | null | [] | package com.zichen.factory;
import com.zichen.dao.UserDao;
import com.zichen.dao.impl.UserDaoImpl;
/**
* 工厂模式实例方法创建对象
* @author zc
* @date 2021-08-27 16:23
*/
public class DynamicFactory {
public UserDao getUserDao() {
return new UserDaoImpl();
}
}
| 297 | 0.677656 | 0.6337 | 17 | 15.058824 | 14.094098 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.235294 | false | false | 14 |
fb2c7122b37a7faa65f3abf2738aceff46d02357 | 9,070,970,995,720 | 3a3458b4f25ced3bf7024b56138cf29111c55270 | /src/main/java/com/example/shoppingmall/dao/UserRepository.java | bbaea36c7b2e40bfb4c8761c5819f3f88804131a | [] | no_license | kinlll/shopping-mall | https://github.com/kinlll/shopping-mall | 8fb718eeff77a49def00377bceb77b3bd8a09908 | ec40fbad0e36950b662be8cf6bb9214660d9971f | refs/heads/master | 2020-11-29T17:29:51.434000 | 2020-01-03T08:23:26 | 2020-01-03T08:23:26 | 230,178,588 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.shoppingmall.dao;
import com.example.shoppingmall.po.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,Integer> {
User findByLoginacctAndUserpswd(String loginacct, String userpswd);
}
| UTF-8 | Java | 287 | java | UserRepository.java | Java | [] | null | [] | package com.example.shoppingmall.dao;
import com.example.shoppingmall.po.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,Integer> {
User findByLoginacctAndUserpswd(String loginacct, String userpswd);
}
| 287 | 0.832753 | 0.832753 | 8 | 34.875 | 29.075064 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 14 |
e8cf9c180e8413e4cb904cc784056f117f8a9c8e | 14,508,399,574,369 | c7daf6639f424024f28a55822a6cfa2f1e6974c4 | /SocialLoginServlets/src/com/casey/gae/sociallogin/SocialLoginServlet.java | 572056dc3adfd80cb96dd5f3ae5e880abcf8289e | [] | no_license | KCastillo/WebServices | https://github.com/KCastillo/WebServices | 4b804fd3755ad0f5b5e04a93806a48203fa3f62f | 42c76de3b76594423dde723d649e4ec20afde34c | refs/heads/master | 2016-09-05T17:42:01.763000 | 2013-05-14T15:36:47 | 2013-05-14T15:36:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.casey.gae.sociallogin;
import java.io.IOException;
import javax.servlet.http.*;
@SuppressWarnings("serial")
public class SocialLoginServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp){
try {
processRequest(req,resp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void processRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Facebook facebook = new Facebook();
resp.sendRedirect(facebook.getLoginRedirectURL());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp){
try {
processRequest(req, resp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| UTF-8 | Java | 842 | java | SocialLoginServlet.java | Java | [] | null | [] | package com.casey.gae.sociallogin;
import java.io.IOException;
import javax.servlet.http.*;
@SuppressWarnings("serial")
public class SocialLoginServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp){
try {
processRequest(req,resp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void processRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Facebook facebook = new Facebook();
resp.sendRedirect(facebook.getLoginRedirectURL());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp){
try {
processRequest(req, resp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 842 | 0.709026 | 0.709026 | 33 | 23.515152 | 24.17878 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.939394 | false | false | 14 |
a7db0f50cf06f70bfe447d7773f39ac75b232b8b | 13,632,226,234,169 | c498cefc16ba5d75b54d65297b88357d669c8f48 | /gameserver/src/ru/catssoftware/gameserver/handler/itemhandlers/SoulCrystals.java | 77e78f072dc018a858c2eb210840c90e2ac79911 | [] | no_license | ManWithShotgun/l2i-JesusXD-3 | https://github.com/ManWithShotgun/l2i-JesusXD-3 | e17f7307d9c5762b60a2039655d51ab36ec76fad | 8e13b4dda28905792621088714ebb6a31f223c90 | refs/heads/master | 2021-01-17T16:10:42.561000 | 2016-07-22T18:41:22 | 2016-07-22T18:41:22 | 63,967,514 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.catssoftware.gameserver.handler.itemhandlers;
import ru.catssoftware.gameserver.ThreadPoolManager;
import ru.catssoftware.gameserver.datatables.SkillTable;
import ru.catssoftware.gameserver.handler.IItemHandler;
import ru.catssoftware.gameserver.model.L2Attackable;
import ru.catssoftware.gameserver.model.L2ItemInstance;
import ru.catssoftware.gameserver.model.L2Object;
import ru.catssoftware.gameserver.model.L2Skill;
import ru.catssoftware.gameserver.model.actor.instance.L2MonsterInstance;
import ru.catssoftware.gameserver.model.actor.instance.L2PcInstance;
import ru.catssoftware.gameserver.model.actor.instance.L2PlayableInstance;
import ru.catssoftware.gameserver.network.SystemMessageId;
import ru.catssoftware.gameserver.network.serverpackets.ActionFailed;
public class SoulCrystals implements IItemHandler
{
private static final int[] ITEM_IDS =
{
4629,
4630,
4631,
4632,
4633,
4634,
4635,
4636,
4637,
4638,
4639,
5577,
5580,
5908,
9570,
4640,
4641,
4642,
4643,
4644,
4645,
4646,
4647,
4648,
4649,
4650,
5578,
5581,
5911,
9572,
4651,
4652,
4653,
4654,
4655,
4656,
4657,
4658,
4659,
4660,
4661,
5579,
5582,
5914
};
public void useItem(L2PlayableInstance playable, L2ItemInstance item, boolean par)
{
}
public void useItem(L2PlayableInstance playable, L2ItemInstance item)
{
if (!(playable instanceof L2PcInstance))
return;
L2PcInstance activeChar = (L2PcInstance) playable;
L2Object target = activeChar.getTarget();
if (!(target instanceof L2MonsterInstance))
{
// Send a System Message to the caster
activeChar.sendPacket(SystemMessageId.INCORRECT_TARGET);
activeChar.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
// u can use soul crystal only when target hp goes below <50%
if (((L2MonsterInstance) target).getStatus().getCurrentHp() > ((L2MonsterInstance) target).getMaxHp() / 2.0)
{
activeChar.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
int crystalId = item.getItemId();
// Soul Crystal Casting section
L2Skill skill = SkillTable.getInstance().getInfo(2096, 1);
activeChar.useMagic(skill, false, true);
CrystalFinalizer cf = new CrystalFinalizer(activeChar, target, crystalId);
ThreadPoolManager.getInstance().scheduleEffect(cf, skill.getHitTime());
}
static class CrystalFinalizer implements Runnable
{
private L2PcInstance _activeChar;
private L2Attackable _target;
private int _crystalId;
CrystalFinalizer(L2PcInstance activeChar, L2Object target, int crystalId)
{
_activeChar = activeChar;
_target = (L2Attackable) target;
_crystalId = crystalId;
}
public void run()
{
if (_activeChar.isDead() || _target.isDead())
return;
_activeChar.enableAllSkills();
try
{
_target.addAbsorber(_activeChar, _crystalId);
_activeChar.setTarget(_target);
}
catch (Exception e)
{
_log.error(e.getMessage(), e);
}
}
}
public int[] getItemIds()
{
return ITEM_IDS;
}
} | UTF-8 | Java | 3,075 | java | SoulCrystals.java | Java | [] | null | [] | package ru.catssoftware.gameserver.handler.itemhandlers;
import ru.catssoftware.gameserver.ThreadPoolManager;
import ru.catssoftware.gameserver.datatables.SkillTable;
import ru.catssoftware.gameserver.handler.IItemHandler;
import ru.catssoftware.gameserver.model.L2Attackable;
import ru.catssoftware.gameserver.model.L2ItemInstance;
import ru.catssoftware.gameserver.model.L2Object;
import ru.catssoftware.gameserver.model.L2Skill;
import ru.catssoftware.gameserver.model.actor.instance.L2MonsterInstance;
import ru.catssoftware.gameserver.model.actor.instance.L2PcInstance;
import ru.catssoftware.gameserver.model.actor.instance.L2PlayableInstance;
import ru.catssoftware.gameserver.network.SystemMessageId;
import ru.catssoftware.gameserver.network.serverpackets.ActionFailed;
public class SoulCrystals implements IItemHandler
{
private static final int[] ITEM_IDS =
{
4629,
4630,
4631,
4632,
4633,
4634,
4635,
4636,
4637,
4638,
4639,
5577,
5580,
5908,
9570,
4640,
4641,
4642,
4643,
4644,
4645,
4646,
4647,
4648,
4649,
4650,
5578,
5581,
5911,
9572,
4651,
4652,
4653,
4654,
4655,
4656,
4657,
4658,
4659,
4660,
4661,
5579,
5582,
5914
};
public void useItem(L2PlayableInstance playable, L2ItemInstance item, boolean par)
{
}
public void useItem(L2PlayableInstance playable, L2ItemInstance item)
{
if (!(playable instanceof L2PcInstance))
return;
L2PcInstance activeChar = (L2PcInstance) playable;
L2Object target = activeChar.getTarget();
if (!(target instanceof L2MonsterInstance))
{
// Send a System Message to the caster
activeChar.sendPacket(SystemMessageId.INCORRECT_TARGET);
activeChar.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
// u can use soul crystal only when target hp goes below <50%
if (((L2MonsterInstance) target).getStatus().getCurrentHp() > ((L2MonsterInstance) target).getMaxHp() / 2.0)
{
activeChar.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
int crystalId = item.getItemId();
// Soul Crystal Casting section
L2Skill skill = SkillTable.getInstance().getInfo(2096, 1);
activeChar.useMagic(skill, false, true);
CrystalFinalizer cf = new CrystalFinalizer(activeChar, target, crystalId);
ThreadPoolManager.getInstance().scheduleEffect(cf, skill.getHitTime());
}
static class CrystalFinalizer implements Runnable
{
private L2PcInstance _activeChar;
private L2Attackable _target;
private int _crystalId;
CrystalFinalizer(L2PcInstance activeChar, L2Object target, int crystalId)
{
_activeChar = activeChar;
_target = (L2Attackable) target;
_crystalId = crystalId;
}
public void run()
{
if (_activeChar.isDead() || _target.isDead())
return;
_activeChar.enableAllSkills();
try
{
_target.addAbsorber(_activeChar, _crystalId);
_activeChar.setTarget(_target);
}
catch (Exception e)
{
_log.error(e.getMessage(), e);
}
}
}
public int[] getItemIds()
{
return ITEM_IDS;
}
} | 3,075 | 0.719024 | 0.651057 | 137 | 21.452555 | 24.148861 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.729927 | false | false | 14 |
ae2fd30593a00ec3113d7567c47a0f7311e9430a | 2,448,131,384,943 | 0a46859cce8da115814bf043fe0e965eafb1b08b | /maximum_subarray_sum/kadane.java | 6acc42b50089aeb16414662fd4b54fb64e51f129 | [
"MIT"
] | permissive | Sahil-Gupta582/CP-Dictionary | https://github.com/Sahil-Gupta582/CP-Dictionary | 8f1deed3a0a67d716ac45e5d741fc6d9bb0cfa5e | 7755d347b4e7fe0c03b063cb58cb0a6dbb67f08f | refs/heads/master | 2023-06-02T05:06:39.536000 | 2020-10-02T07:54:19 | 2020-10-02T07:54:19 | 298,664,384 | 2 | 1 | MIT | true | 2022-04-01T14:11:43 | 2020-09-25T19:38:48 | 2021-06-15T09:44:52 | 2021-06-15T10:15:16 | 184 | 2 | 1 | 0 | C++ | false | false | import java.io.*;
import java.util.StringTokenizer;
public class kadane {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solution.solve(in, out);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] readArray(int n)
{
int[] arr=new int[n];
for(int i=0;i<n;i++) arr[i]=nextInt();
return arr;
}
}
}
class Solution
{
public static void solve(kadane.InputReader in,PrintWriter out)
{
System.out.println("Enter size of array");
int n=in.nextInt();
System.out.println("Enter elements of array");
int[] arr=in.readArray(n);
out.println("Maximum Subarray sum ="+sum(arr));
}
public static int sum(int[] arr)
{
int len=arr.length;
int max=Integer.MIN_VALUE;
int sum=0;
for(int i=0;i<len;i++)
{
sum+=arr[i];
max=Math.max(max,sum);
if(sum<0)
sum=0;
}
return max;
}
} | UTF-8 | Java | 2,116 | java | kadane.java | Java | [] | null | [] | import java.io.*;
import java.util.StringTokenizer;
public class kadane {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solution.solve(in, out);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] readArray(int n)
{
int[] arr=new int[n];
for(int i=0;i<n;i++) arr[i]=nextInt();
return arr;
}
}
}
class Solution
{
public static void solve(kadane.InputReader in,PrintWriter out)
{
System.out.println("Enter size of array");
int n=in.nextInt();
System.out.println("Enter elements of array");
int[] arr=in.readArray(n);
out.println("Maximum Subarray sum ="+sum(arr));
}
public static int sum(int[] arr)
{
int len=arr.length;
int max=Integer.MIN_VALUE;
int sum=0;
for(int i=0;i<len;i++)
{
sum+=arr[i];
max=Math.max(max,sum);
if(sum<0)
sum=0;
}
return max;
}
} | 2,116 | 0.528828 | 0.524102 | 76 | 26.855263 | 19.640656 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565789 | false | false | 14 |
0c83c48978069a786ace838274bf3eeb38fe8438 | 2,448,131,381,979 | 914775a0f641d3487f996e04baf1effde53432ba | /connectToDb/src/main/java/com/javaeeeee/api/group_table.java | 86a9c0fd496f5159a0abfcb4ed7dac628677ddb1 | [] | no_license | VartikaBhatia/Splitwise-Java | https://github.com/VartikaBhatia/Splitwise-Java | 9b250cd1fa856712525d6f93d03845f9f0f2e8c8 | 005c962c59a281ee7251c9b993da793c69229cc5 | refs/heads/master | 2020-05-23T12:31:42.515000 | 2019-05-15T06:02:23 | 2019-05-15T06:02:23 | 186,758,718 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.javaeeeee.api;
import java.util.List;
public class group_table {
private String group_name;
private String group_id;
public group_table(){}
public group_table( String group_name,String group_id)
{
this.group_id=group_id;
this.group_name=group_name;
}
public String getGroup_name() {
return group_name;
}
public void setGroup_name(String group_name) {
this.group_name = group_name;
}
public String getGroup_id() {
return group_id;
}
public void setGroup_id(String group_id) {
this.group_id = group_id;
}
}
| UTF-8 | Java | 634 | java | group_table.java | Java | [] | null | [] | package com.javaeeeee.api;
import java.util.List;
public class group_table {
private String group_name;
private String group_id;
public group_table(){}
public group_table( String group_name,String group_id)
{
this.group_id=group_id;
this.group_name=group_name;
}
public String getGroup_name() {
return group_name;
}
public void setGroup_name(String group_name) {
this.group_name = group_name;
}
public String getGroup_id() {
return group_id;
}
public void setGroup_id(String group_id) {
this.group_id = group_id;
}
}
| 634 | 0.61041 | 0.61041 | 37 | 16.135136 | 17.167162 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.297297 | false | false | 14 |
e7aff0d7b74a83428669d771692f104a9ac5fdfc | 7,842,610,334,496 | 1fd0e659afd5e39b69faa8ded5a0eb654ec60d9a | /src/Editor/DrawTools/TilePencil.java | ecb4d8f3c84c228100e08928d6ff19f39b075104 | [] | no_license | HazilTheNut/WonderText | https://github.com/HazilTheNut/WonderText | 8cbfd5ce66ac104c9b95bdb1bb61b2fa3db13cbe | 721b89ac98802ff9724cf1e7fcc68050a55bf8fc | refs/heads/master | 2021-04-28T15:20:02.493000 | 2019-10-03T03:08:08 | 2019-10-03T03:08:08 | 121,986,065 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Editor.DrawTools;
import Data.LevelData;
import Engine.Layer;
import Engine.SpecialText;
import Data.TileStruct;
import javax.swing.*;
/**
* Created by Jared on 2/25/2018.
*/
public class TilePencil extends DrawTool {
/**
* TilePencil:
*
* Ever wanted to make a tiny change without bothering to use the 'Scan" button?
* Have no fear, TilePencil is here!
*/
private Layer tilesLayer; //We're not editing the backdrop anymore, so a workaround must be done.
private TileStruct tileData;
private LevelData ldata;
public TilePencil(Layer dataLayer, LevelData levelData){
tilesLayer = dataLayer;
ldata = levelData; //Done!
}
@Override
public void onActivate(JPanel panel) {
TOOL_TYPE = TYPE_TILE;
}
public void setTileData(TileStruct struct) {tileData = struct; }
@Override
public void onDraw(Layer layer, Layer highlight, int col, int row, SpecialText text) {
tilesLayer.editLayer(col, row, tileData.getDisplayChar());
ldata.setTileData(col, row, tileData.getTileId());
}
@Override
public void onDrawStart(Layer layer, Layer highlight, int col, int row, SpecialText text) {
tilesLayer.editLayer(col, row, tileData.getDisplayChar());
ldata.setTileData(col, row, tileData.getTileId());
System.out.printf("[TilePencil] drawStart: col = %1$d row = %2$d\n", col, row);
}
}
| UTF-8 | Java | 1,436 | java | TilePencil.java | Java | [
{
"context": "eStruct;\n\nimport javax.swing.*;\n\n/**\n * Created by Jared on 2/25/2018.\n */\npublic class TilePencil extends",
"end": 169,
"score": 0.9990101456642151,
"start": 164,
"tag": "NAME",
"value": "Jared"
}
] | null | [] | package Editor.DrawTools;
import Data.LevelData;
import Engine.Layer;
import Engine.SpecialText;
import Data.TileStruct;
import javax.swing.*;
/**
* Created by Jared on 2/25/2018.
*/
public class TilePencil extends DrawTool {
/**
* TilePencil:
*
* Ever wanted to make a tiny change without bothering to use the 'Scan" button?
* Have no fear, TilePencil is here!
*/
private Layer tilesLayer; //We're not editing the backdrop anymore, so a workaround must be done.
private TileStruct tileData;
private LevelData ldata;
public TilePencil(Layer dataLayer, LevelData levelData){
tilesLayer = dataLayer;
ldata = levelData; //Done!
}
@Override
public void onActivate(JPanel panel) {
TOOL_TYPE = TYPE_TILE;
}
public void setTileData(TileStruct struct) {tileData = struct; }
@Override
public void onDraw(Layer layer, Layer highlight, int col, int row, SpecialText text) {
tilesLayer.editLayer(col, row, tileData.getDisplayChar());
ldata.setTileData(col, row, tileData.getTileId());
}
@Override
public void onDrawStart(Layer layer, Layer highlight, int col, int row, SpecialText text) {
tilesLayer.editLayer(col, row, tileData.getDisplayChar());
ldata.setTileData(col, row, tileData.getTileId());
System.out.printf("[TilePencil] drawStart: col = %1$d row = %2$d\n", col, row);
}
}
| 1,436 | 0.672006 | 0.665738 | 50 | 27.719999 | 29.146553 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.78 | false | false | 14 |
07e53b3541d085c5aea9583131a4b19a25c313bc | 8,014,408,993,241 | 7aff2921589fc5e1c58c54c0ca92f5e65ecd2414 | /dms-portal/src/main/java/com/emxcel/dms/portal/controller/ClientController.java | bceb039f16ce83bff56c761b60684df8d9c6994a | [] | no_license | khatriarpit/Arpit_Booking | https://github.com/khatriarpit/Arpit_Booking | cd71dd4fbbc007087fd198f034be75b146b7b280 | 8b2ed6624eaad2b21f922a3bde9f8dcac501f330 | refs/heads/master | 2021-01-23T05:19:17.908000 | 2017-03-27T06:11:55 | 2017-03-27T06:11:55 | 86,297,455 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.emxcel.dms.portal.controller;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.emxcel.dms.core.business.constants.Constants;
import com.emxcel.dms.core.business.exception.ServiceException;
import com.emxcel.dms.core.business.services.car.CarNameService;
import com.emxcel.dms.core.business.services.car.CarService;
import com.emxcel.dms.core.business.services.car.CarTypeService;
import com.emxcel.dms.core.business.services.city.CityService;
import com.emxcel.dms.core.business.services.client.ClientModelService;
import com.emxcel.dms.core.business.services.client.PreBookingService;
import com.emxcel.dms.core.business.services.client.TripCancelHistoryService;
import com.emxcel.dms.core.business.services.companymaster.CompanyMasterService;
import com.emxcel.dms.core.business.services.driver.DriverService;
import com.emxcel.dms.core.business.services.guest.GuestService;
import com.emxcel.dms.core.business.services.mapping.CarDriverMappingService;
import com.emxcel.dms.core.business.services.notification.AlertSchedulerService;
import com.emxcel.dms.core.business.services.notification.NotificationService;
import com.emxcel.dms.core.business.services.superadmin.DestinationMasterService;
import com.emxcel.dms.core.business.services.superadmin.InvoicePackageService;
import com.emxcel.dms.core.business.services.superadmin.RateOfContractService;
import com.emxcel.dms.core.business.services.tax.TaxSlabService;
import com.emxcel.dms.core.business.services.user.UserService;
import com.emxcel.dms.core.business.utils.CommonUtil;
import com.emxcel.dms.core.business.utils.OTPData;
import com.emxcel.dms.core.business.utils.SMSSend;
import com.emxcel.dms.core.model.car.Car;
import com.emxcel.dms.core.model.car.CarDriverMapping;
import com.emxcel.dms.core.model.car.CarName;
import com.emxcel.dms.core.model.car.CarType;
import com.emxcel.dms.core.model.client.ClientModel;
import com.emxcel.dms.core.model.client.PreBooking;
import com.emxcel.dms.core.model.client.TripCancelHistory;
import com.emxcel.dms.core.model.common.AlertScheduler;
import com.emxcel.dms.core.model.common.Notification;
import com.emxcel.dms.core.model.companymaster.CompanyMaster;
import com.emxcel.dms.core.model.driver.Driver;
import com.emxcel.dms.core.model.guest.Guest;
import com.emxcel.dms.core.model.superadmin.DestinationMaster;
import com.emxcel.dms.core.model.tax.TaxSlab;
import com.emxcel.dms.core.model.user.User;
import com.emxcel.dms.portal.constants.UrlConstants;
import com.emxcel.dms.portal.constants.ViewConstants;
import com.emxcel.dms.portal.model.BookCarBean;
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Call;
import com.twilio.type.PhoneNumber;
/**
* @author Jimit Patel.
*/
@Controller
public class ClientController {
private static final Logger logger = Logger.getLogger(ClientController.class);
/**
* **We autowired it to use services of DriverService **.
*/
@Inject
private DriverService driverService;
/**
* **We autowired it to use services of GuestService **.
*/
@Inject
private GuestService guestService;
/**
* **We autowired it to use services of ClientModelService **.
*/
@Inject
private ClientModelService clientModelService;
/**
* **We autowired it to use services of RateOfContractService **.
*/
@Inject
private RateOfContractService rateOfContractService;
/**
* **We autowired it to use services of InvoicePackageService **.
*/
@Inject
private InvoicePackageService invoicePackageService;
/**
* **We autowired it to use services of CityService **.
*/
@Inject
private CityService cityService;
/**
* **We autowired it to use services of CarService **.
*/
@Inject
private CarService carService;
/**
* **We autowired it to use services of DestinationMasterService **.
*/
@Inject
private DestinationMasterService destinationMasterService;
/**
* **We autowired it to use services of CompanyMasterService **.
*/
@Inject
private CompanyMasterService companyMasterService;
/**
* **We autowired it to use services of TaxSlabService **.
*/
@Inject
private TaxSlabService taxSlabService;
/**
* **We autowired it to use services of CarTypeService **.
*/
@Inject
private CarTypeService carTypeService;
/**
* **We autowired it to use services of CarNameService **.
*/
@Inject
private CarNameService carNameService;
/**
* **We autowired it to use services of CarDriverMappingService **.
*/
@Inject
private PreBookingService preBookingService;
@Inject
private TripCancelHistoryService tripCancelHistoryService;
@Inject
private UserService userService;
@Inject
private CarDriverMappingService carDriverMappingService;
@PersistenceContext
private EntityManager manager;
/**
* SimpMessagingTemplate.
*/
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
/**
* NotificationService.
*/
@Inject
private NotificationService notificationService;
/**
* AlertSchedulerService.
*/
@Inject
private AlertSchedulerService alertSchedulerService;
/**
* Created By : Jimit Patel , Date: 20-01-2017 Use : To get the list of
* Companies from Company Master for automatic suggestions.
*
* @param query
* **Requested From Client Booking Jsp**
* @return comapnyList
*/
@ResponseBody
@RequestMapping(value = UrlConstants.GETCOMPANY_LIST, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<CompanyMaster> getCompanyList(@RequestParam(value = "term", required = false) final String query) {
return companyMasterService.getCompanyNameList(query);
}
/**
* Created By : Jimit Patel , Date: 06-03-2017 Use : To get the list of
* Contact from Guest for automatic suggestions.
*
* @param query
* **Requested From Client Booking Jsp**
* @return comapnyList
*/
@ResponseBody
@RequestMapping(value = UrlConstants.GET_CONTACT_LIST, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Guest> getContactList(@RequestParam(value = "term", required = false) final String query) {
return guestService.getContactNumberList(query);
}
/**
* Created By : Jimit Patel , Date: 06-03-2017 Use : To get the Detail Of
* Customer on the basis of Mobile No.
*
* @param query
* **Requested From Client Booking Jsp**
* @return comapnyList
*/
@ResponseBody
@RequestMapping(value = UrlConstants.GET_GUEST_DETAIL, method = RequestMethod.POST)
public Guest getGuestDetail(
@RequestParam(value = "contactNo", required = false) final String contactNo) {
return guestService.getGuestDetailByContactNo(contactNo);
}
/**
* Created By : Jimit Patel , Date: 20-01-2017 Use : To get the list of
* Source Place from Source Destination Master for automatic suggestions.
*
* @param query
* **Requested From Client Booking Jsp**
* @return sourcePlaceList
*/
@ResponseBody
@RequestMapping(value = UrlConstants.SOURCEPLACE_LIST, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<DestinationMaster> getSourceList(@RequestParam("term") final String query,
final RedirectAttributes redirect) {
List<DestinationMaster> sourcePlaceList = null;
try {
sourcePlaceList = destinationMasterService.getsourcePlaceList(query);
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
redirect.addFlashAttribute(Constants.MESSAGE, " Something Went Wrong !!!");
return Collections.emptyList();
}
return sourcePlaceList;
}
/**
* Created By : Jimit Patel , Date: 20-01-2017 Use : To get the list of
* Destination Place from Source Destination Master for automatic
* suggestions.
*
* @param query
* **Requested From Client Booking Jsp**
* @return destinationPlaceList
*/
@ResponseBody
@RequestMapping(value = UrlConstants.DESTINATIONPLACE_LIST, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<DestinationMaster> getDestinationList(@RequestParam("term") final String query,
final RedirectAttributes redirect) {
List<DestinationMaster> destinationPlaceList = null;
try {
destinationPlaceList = destinationMasterService.getdestinationPlaceList(query);
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
redirect.addFlashAttribute(Constants.MESSAGE, " Something Went Wrong !!!");
return Collections.emptyList();
}
return destinationPlaceList;
}
/**
* Created By : Jimit Patel , Date: 23-01-2017. Use : To get the list of tax
* Slab on the basis of selected invoice category.
*
* @param id
* **Get Invoice category id From Client Booking Jsp**
* @return listoftax
*/
@RequestMapping(value = UrlConstants.INVOICE_TAX_LIST, method = RequestMethod.POST)
@ResponseBody
public List<TaxSlab> getAllTaxes(
@RequestParam(value = "invoiceCategories", required = false) final String categoryId) {
try {
if (categoryId != null && !("").equals(categoryId)) {
return taxSlabService.getTaxSlabById(Long.valueOf(categoryId));
} else {
return Collections.emptyList();
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
return Collections.emptyList();
}
}
/**
* Created By : Jimit Patel , Date: 23-01-2017. Use : To get the list of Booked Cars
* @param session`
* @param clientModel
* @param result
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.LIST_BOOKEDCARS, method = RequestMethod.GET)
private ModelAndView bookedCarList(final HttpSession session,
@ModelAttribute("command") final ClientModel clientModel, final BindingResult result) {
User user = (User) session.getAttribute("user");
Map<String, Object> map = new HashMap<>();
List<ClientModel> listOfClient = clientModelService.getClientAndGuestModel(user.getTanentID());
List<ClientModel> clientArry = new ArrayList<>();
for (ClientModel clientModel1 : listOfClient) {
if (clientModel1.getPickUpLocation() != null && !("").equals(clientModel1.getPickUpLocation())) {
byte[] pickUpLocation = Base64.getDecoder().decode(clientModel1.getPickUpLocation());
clientModel1.setPickUpLocation(new String(pickUpLocation));
} else {
clientModel1.setPickUpLocation("");
}
if (clientModel1.getDrop_location() != null && !("").equals(clientModel1.getDrop_location())) {
byte[] dropLocation = Base64.getDecoder().decode(clientModel1.getDrop_location());
clientModel1.setDrop_location(new String(dropLocation));
} else {
clientModel1.setDrop_location("");
}
clientArry.add(clientModel1);
}
map.put("clientModelList", clientArry);
return new ModelAndView(ViewConstants.LIST_BOOKEDCARS, map);
}
/**
* Created By : Jimit Patel , Date: 20-01-2017. Use: To open Client Booking
* Page through Search Car Page
*
* @param carId
* **carId**
* @param clientId
* **clientId**
* @param clientModel
* **clientModel**
* @param pickUpDateTime
* **picUpDateTime**
* @param dropDateTime
* **dropDateTime**
* @param result
* **result**
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.CLIENT_PAGE, method = RequestMethod.POST)
private ModelAndView addClient(@RequestParam(value = "carId", required = false) final String carId,
@RequestParam(value = "clientId", required = false) final String clientId,
@ModelAttribute("command") final ClientModel clientModel,
@RequestParam(value = "pickUpDateTime1", required = false) final String pickUpDateTime,
@RequestParam(value = "dropDateTime1", required = false) final String dropDateTime,
@RequestParam(value = "driverId", required = false) final String driverId,
@RequestParam(value = "preBooking", required = false) final String prebBookingId,
final BindingResult result, final RedirectAttributes ra) {
Map<String, Object> map = new HashMap<>();
try {
Car car = this.carService.getById(Long.valueOf(carId));
if (car != null && !("").equals(car)) {
map.put("carDtls", car);
CarType carType = this.carTypeService.getById(car.getCarTypeId());
if (carType != null) {
map.put("carTypeDtls", carType);
}
CarName carName = this.carNameService.getById(car.getCarNameId());
if (carName != null) {
map.put("carNameDtls", carName);
}
Driver driverDtlS = null;
if (driverId != null) {
driverDtlS = this.driverService.getById(Long.valueOf(driverId));
} else {
ClientModel clientModelForDriver = clientModelService.getById(Long.valueOf(clientId));
driverDtlS = this.driverService.getById(clientModelForDriver.getDriver().getId());
}
map.put("driverDtlS", driverDtlS);
}
map.put("InvoiceDTL", invoicePackageService.list());
map.put("RateContract", rateOfContractService.list());
map.put("CityDTL", cityService.list());
map.put("CompanyMasterDTL", companyMasterService.list());
map.put("pickUpDateTime", pickUpDateTime);
map.put("dropDateTime", dropDateTime);
if (clientId != null && !("a").equals(clientId)) {
ClientModel clientModel1 = clientModelService.getById(Long.valueOf(clientId));
if (clientModel1.getPickUpLocation() != null && !("").equals(clientModel1.getPickUpLocation())) {
byte[] pickUpLocation = Base64.getDecoder().decode(clientModel1.getPickUpLocation());
clientModel1.setPickUpLocation(new String(pickUpLocation));
} else {
clientModel1.setPickUpLocation("");
}
if (clientModel1.getDrop_location() != null && !("").equals(clientModel1.getDrop_location())) {
byte[] dropLocation = Base64.getDecoder().decode(clientModel1.getDrop_location());
clientModel1.setDrop_location(new String(dropLocation));
} else {
clientModel1.setDrop_location("");
}
map.put("clientModel", clientModel1);
}
if (prebBookingId != null && !prebBookingId.equals("")) {
PreBooking preBooking = preBookingService.getById(Long.valueOf(prebBookingId));
map.put("preBookingId", prebBookingId);
ClientModel clientModel1 = new ClientModel();
clientModel1.setId(Long.valueOf("0"));
clientModel1.setInvoiceMode(preBooking.getInvoiceMode());
clientModel1.setGuest(guestService.getById(preBooking.getGuest().getId()));
byte[] pickUpLocation = Base64.getDecoder().decode(preBooking.getPickUpLocation());
clientModel1.setPickUpLocation(new String(pickUpLocation));
byte[] dropLocation = Base64.getDecoder().decode(preBooking.getDrop_location());
clientModel1.setDrop_location(new String(dropLocation));
clientModel1.setInvoiceMode(preBooking.getInvoiceMode());
clientModel1.setCity(cityService.getById(preBooking.getCity().getId()));
clientModel1.setLandmark(preBooking.getLandmark());
clientModel1.setPincode(preBooking.getPincode());
clientModel1.setRemarks(preBooking.getRemarks());
clientModel1.setInvoicePackage(invoicePackageService.getById(preBooking.getInvoicePackage().getId()));
clientModel1.setRateOfContract(rateOfContractService.getById(preBooking.getRateOfContract().getId()));
clientModel1.setMinkms(preBooking.getMinkms());
clientModel1.setMinrate(preBooking.getMinrate());
clientModel1.setDriverAllownce(preBooking.getDriverAllownce());
clientModel1.setGraceHours(preBooking.getGraceHours());
clientModel1.setPaymentMode(preBooking.getPaymentMode());
clientModel1.setHnkKms(preBooking.getHnkKms());
clientModel1.setHnkHours(preBooking.getHnkHours());
clientModel1.setHnkAmount(preBooking.getHnkAmount());
clientModel1.setAdditionalHours(preBooking.getAdditionalHours());
clientModel1.setAdditionalKms(preBooking.getAdditionalKms());
clientModel1.setSourcePlace(preBooking.getSourcePlace());
clientModel1.setDestinationPlace(preBooking.getDestinationPlace());
clientModel1.setSndPrice(preBooking.getSndPrice());
if (preBooking.getCompanyMaster() != null) {
clientModel1.setCompanyMaster(companyMasterService.getById(preBooking.getCompanyMaster().getId()));
}
map.put("clientModel", clientModel1);
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
ra.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.SEARCH_CAR);
}
return new ModelAndView(ViewConstants.CLIENT_PAGE, map);
}
/**
* Created By : Jimit Patel , Date: 20-01-2017 Use: To Save the Booking
* Details Of Client.
*
* @param pickUpDateTime
* **picUpDateTime**
* @param dropDate
* **dropDate**
* @param clientModel
* **clientModel**
* @param result
* **result**
* @param session
* **session**
* @exception ServiceException
* @return ModelAndView
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = UrlConstants.SAVE_CLIENT, method = RequestMethod.POST)
private ModelAndView saveClientDetails(
@ModelAttribute("command") @RequestParam("pickUpDateTime") String pickUpDateTime,
@RequestParam("dropDateTime") String dropDate,
@RequestParam("preBookingId") String preBookingId,
final ClientModel clientModel,
final BindingResult result, HttpSession session, final RedirectAttributes redirect) {
try {
clientModelService.saveClientDetails(clientModel, session, pickUpDateTime, dropDate, preBookingId);
SimpleDateFormat diff = new SimpleDateFormat(Constants.PORTAL_DATE_FORMAT);
Calendar cal = Calendar.getInstance();
cal.setTime(diff.parse(CommonUtil.convertTimestampToDateInString(clientModel.getPickUpDateTime())));
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.add(Calendar.MINUTE, -60);
Date date1 = cal.getTime();
Timer timer1 = new Timer(true);
AlertScheduler alertScheduler1 = alertSchedulerService.saveAlertSchedulerReturnEntity(date1,
clientModel.getTripId(), false, 1);
timer1.schedule(new TimerTask() {
@Override
public void run() {
try {
ClientModel clientModelNew = null;
// 1 hour left then Notification Alert to Admin & DE
int hour = 1;
String msg = "Your Trip Has Left " + hour + " Hour to start !!!";
if (clientModel.getDriver() != null && clientModel.getDriver().getTokenID() != null) {
CommonUtil.getTokenByContactNo(clientModel.getDriver().getTokenID(), msg + " ,tripID="
+ clientModel.getTripId() + "," + "latlong=" + clientModel.getPickUpLatLong() + "", "driverApp");
}
// Sleep for 10 sec
Thread.sleep(10000);
clientModelNew = clientModelService.getTripByTripId(clientModel.getTripId());
msg = getMessageForTripAlert(clientModelNew);
getAlerts(clientModelNew, hour, msg);
alertSchedulerService.updateAlertSchedulerReturnEntity(true, alertScheduler1);
timer1.cancel();
timer1.purge();
} catch (Exception e) {
e.printStackTrace();
}
};
}, date1);
cal = Calendar.getInstance();
cal.setTime(diff.parse(CommonUtil.convertTimestampToDateInString(clientModel.getPickUpDateTime())));
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.add(Calendar.MINUTE, -58);
Date date2 = cal.getTime();
AlertScheduler alertScheduler2 = alertSchedulerService.saveAlertSchedulerReturnEntity(date2,
clientModel.getTripId(), false, 2);
Timer timer2 = new Timer(true);
timer2.schedule(new TimerTask() {
@Override
public void run() {
try {
ClientModel clientModelNew = null;
// 45 min left then Notification Alert to Admin & DE
int fortyFiveMinutes = 45;
String msg = "Your Trip Has Left " + fortyFiveMinutes + " minutes to start !!!";
if (clientModel.getDriver() != null && clientModel.getDriver().getTokenID() != null) {
CommonUtil.getTokenByContactNo(clientModel.getDriver().getTokenID(), msg + " ,tripID="
+ clientModel.getTripId() + "," + "latlong=" + clientModel.getPickUpLatLong() + "", "driverApp");
}
// Sleep for 10 sec
Thread.sleep(10000);
clientModelNew = clientModelService.getTripByTripId(clientModel.getTripId());
msg = getMessageForTripAlert(clientModelNew);
getAlerts(clientModelNew, fortyFiveMinutes, "minutes");
alertSchedulerService.updateAlertSchedulerReturnEntity(true, alertScheduler2);
timer2.cancel();
timer2.purge();
} catch (Exception e) {
e.printStackTrace();
}
};
}, date2);
cal = Calendar.getInstance();
cal.setTime(diff.parse(CommonUtil.convertTimestampToDateInString(clientModel.getPickUpDateTime())));
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.add(Calendar.MINUTE, -56);
Date date3 = cal.getTime();
AlertScheduler alertScheduler3 = alertSchedulerService.saveAlertSchedulerReturnEntity(date3,
clientModel.getTripId(), false, 3);
Timer timer3 = new Timer(true);
timer3.schedule(new TimerTask() {
@Override
public void run() {
try {
ClientModel clientModelNew = null;
// 30 min left then Notification Alert to Admin & DE
int thrityMinutes = 30;
String msg = "Your Trip Has Left " + thrityMinutes + " minutes to start !!!";
if (clientModel.getDriver() != null && clientModel.getDriver().getTokenID() != null) {
CommonUtil.getTokenByContactNo(clientModel.getDriver().getTokenID(), msg + " ,tripID="
+ clientModel.getTripId() + "," + "latlong=" + clientModel.getPickUpLatLong() + "", "driverApp");
}
// Sleep for 10 sec
Thread.sleep(10000);
clientModelNew = clientModelService.getTripByTripId(clientModel.getTripId());
msg = getMessageForTripAlert(clientModel);
if (clientModelNew != null && clientModelNew.getDriverDistanceMin() != null
&& thrityMinutes < clientModelNew.getDriverDistanceMin()) {
getAlerts(clientModelNew, thrityMinutes, msg);
final String ACCOUNT_SID = "AC4e1f4bb93ef57dc18d1ad9cbb4acea65";
final String AUTH_TOKEN = "c893e27cd8f65850a3e384e59de4f1d6";
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
Call call = null;
try {
call = Call
.creator(new PhoneNumber("+917405799970"), new PhoneNumber("+18583465930"),
new URI("https://handler.twilio.com/twiml/EHa8565f08cfa0860cd2f067271a9682ce"))
.create();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
alertSchedulerService.updateAlertSchedulerReturnEntity(true, alertScheduler3);
timer3.cancel();
timer3.purge();
} catch (Exception e) {
e.printStackTrace();
}
};
}, date3);
if (clientModel.getDriver() != null && clientModel.getDriver().getTokenID() != null) {
// if (clientModel.getGuest() != null && token != null) {
String message = "One Trip has been Booked !! ./n";
CommonUtil.getTokenByContactNo(clientModel.getDriver().getTokenID(), message, "driverApp");
}
if (clientModel.getGuest() != null && clientModel.getGuest().getTokenID() != null) {
// if (clientModel.getGuest() != null && token != null) {
String message = "Your Trip has been Booked !! ./n";
CommonUtil.getTokenByContactNo(clientModel.getGuest().getTokenID(), message, "feedApp");
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
redirect.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
/**
* Created By : Jimit Patel , Date: 20-01-2017 Use: To Update Booking Detail
* @param pickUpDateTime
* @param dropDate
* @param clientModel
* @param result
* @param ra
* @return
*/
@RequestMapping(value = UrlConstants.UPDATE_CLIENT, method = RequestMethod.POST)
private ModelAndView updateClient(@ModelAttribute("command") @RequestParam("pickUpDateTime") String pickUpDateTime,
@RequestParam("dropDateTime") String dropDate, final ClientModel clientModel, final BindingResult result,
final RedirectAttributes redirect) {
try {
clientModelService.updateClientDetsils(clientModel, pickUpDateTime, dropDate);
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
redirect.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
/**
* @param tripId
* @param result
* @return
*/
@RequestMapping(value = UrlConstants.CANCELED_TRIP, method = RequestMethod.GET)
private ModelAndView cancelBookedCarTrip(@RequestParam(value = "tripId", required = false) final String tripId,
final ClientModel clientModel, final BindingResult result, final RedirectAttributes ra) {
try {
clientModelService.setSatusCancel(tripId);
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
ra.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
/**
* @param cartype
* @param clientId
* @param changeRequestBy
* @return
*/
@RequestMapping(value = UrlConstants.CHANGE_REQUEST, method = RequestMethod.POST)
public ModelAndView changeRequestPage(@ModelAttribute("command") final CarType cartype,
@RequestParam(value = "clientId", required = false) final String clientId,
@RequestParam(value = "flag", required = false) final String changeRequestBy) {
ModelAndView model = new ModelAndView();
model.addObject("changeRequestBy",changeRequestBy);
if (clientId != null && !("").equals(clientId)) {
ClientModel clientModel=clientModelService.getById(Long.valueOf(clientId));
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
List<Driver> driverList=manager.createNamedQuery("getAvailableDrivers", Driver.class)
.setParameter("picUpDateTime", dateFormat.format(clientModel.getPickUpDateTime()))
.setParameter("dropDate", dateFormat.format(clientModel.getDropDateTime()))
.setParameter("tanentID", clientModel.getTanentID()).getResultList();
List<Car> carList = manager.createNamedQuery("getCarAvailableListForAllCarType", Car.class)
.setParameter("picUpDateTime", dateFormat.format(clientModel.getPickUpDateTime()))
.setParameter("dropDate",dateFormat.format(clientModel.getDropDateTime()))
.setParameter("tanentID", clientModel.getTanentID()).getResultList();
List<BookCarBean> listOfBookCar=new ArrayList<>();
Car carModel=carService.getById(clientModel.getCar().getId());
carList.add(carModel);
for (Car car : carList) {
BookCarBean bookCarBean = new BookCarBean();
bookCarBean.setCarId(car.getId());
bookCarBean.setCarNumber(car.getCarNo());
CarType carType = carTypeService.getById(car.getCarTypeId());
bookCarBean.setCarType(carType.getCarType());
CarName carName = carNameService.getById(car.getCarNameId());
bookCarBean.setCarName(carName.getCarName());
listOfBookCar.add(bookCarBean);
}
model.addObject("driverList", driverList);
if (changeRequestBy != null) {
if (changeRequestBy.equals("driver")) {
model.addObject("changeRequestBy", changeRequestBy);
}
} else {
model.addObject("listOfBookCar", listOfBookCar);
model.addObject("changeRequestBy", null);
}
model.addObject("clientId", clientId);
model.addObject("carNo", carModel.getId());
}
model.setViewName(ViewConstants.CHANGE_REQUEST);
return model;
}
/**
* @param cartype
* @param clientId
* @param carId
* @param driverId
* @param changeRequestBy
* @param ra
* @return
* @throws ServiceException
*/
@RequestMapping(value = UrlConstants.CHANGE_REQUEST_ACCEPT, method = RequestMethod.POST)
public ModelAndView changeRequestAccepted(@ModelAttribute("command") final CarType cartype,
@RequestParam(value = "clientId", required = false) final String clientId,
@RequestParam(value = "carId", required = false) final String carId,
@RequestParam(value = "driverId", required = false) final String driverId ,
@RequestParam(value = "changeRequestBy", required = false) final String changeRequestBy,
final RedirectAttributes ra) throws ServiceException {
ClientModel clientModel = clientModelService.getById(Long.valueOf(clientId));
if(driverId!=null && !("0").equals(driverId)) {
Driver driver = driverService.getById(Long.valueOf(driverId));
clientModel.setDriver(driver);
}
if (carId != null && !("0").equals(carId) && !carId.equals("")) {
Car car = carService.getById(Long.valueOf(carId));
clientModel.setCar(car);
}
TripCancelHistory tripCancelHistory = copyClientObjectToTrip(clientModel);
tripCancelHistoryService.save(tripCancelHistory);
clientModel.setStatusID(CommonUtil.getStatusIDByStatus(Constants.TRIP_STATUS_PENDING));
clientModelService.update(clientModel);
ra.addFlashAttribute(Constants.MESSAGE, "Change(s) Request Accepted & Updated Successfully !!!");
if (changeRequestBy == null) {
return new ModelAndView(Constants.REDIRECT + UrlConstants.CANCEL_REQUEST_LIST);
} else {
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
}
/**
* @param cartype
* @param clientId
* @param carId
* @param driverId
* @param ra
* @return
* @throws ServiceException
*/
@RequestMapping(value = UrlConstants.CHANGE_REQUEST_REJECT, method = RequestMethod.POST)
public ModelAndView changeRequestRejected(@ModelAttribute("command") final CarType cartype,
@RequestParam(value = "clientId", required = false) final String clientId,
@RequestParam(value = "carId", required = false) final String carId,
@RequestParam(value = "driverId", required = false) final String driverId, final RedirectAttributes ra)
throws ServiceException {
ClientModel clientModel = clientModelService.getById(Long.valueOf(clientId));
clientModel.setStatusID(CommonUtil.getStatusIDByStatus("Pending"));
clientModelService.update(clientModel);
ra.addFlashAttribute(Constants.MESSAGE, "Sorry , Change Request Rejected ... !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.CANCEL_REQUEST_LIST);
}
/**
* Created By: Jimit Patel Date:22/02/2017 Use: To fetch the list of Driver
* Cancel Request List
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.CANCEL_REQUEST_LIST, method = RequestMethod.GET)
public ModelAndView cancelrequestList(@ModelAttribute("command") final ClientModel clientModel,
final RedirectAttributes ra) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.getUserByUsername(auth.getName());
List<ClientModel> cancelRequestList = clientModelService.getDriverCancelList(user.getTanentID());
Map<String, Object> map = new HashMap<String, Object>();
try {
if (cancelRequestList != null) {
List<ClientModel> clientArry = new ArrayList<>();
for (ClientModel clientModel1 : cancelRequestList) {
if (clientModel1.getPickUpLocation() != null && !("").equals(clientModel1.getPickUpLocation())) {
byte[] pickUpLocation = Base64.getDecoder().decode(clientModel1.getPickUpLocation());
clientModel1.setPickUpLocation(new String(pickUpLocation));
} else {
clientModel1.setPickUpLocation("");
}
if (clientModel1.getDrop_location() != null && !("").equals(clientModel1.getDrop_location())) {
byte[] dropLocation = Base64.getDecoder().decode(clientModel1.getDrop_location());
clientModel1.setDrop_location(new String(dropLocation));
} else {
clientModel1.setDrop_location("");
}
clientArry.add(clientModel1);
}
map.put("CancelList", clientArry);
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
ra.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.BOOK_CAR_LIST);
}
return new ModelAndView(ViewConstants.LIST_CANCEL_REQUEST, map);
}
/**
* Created By: Jimit Patel Date:23/02/2017 Use: Driver Cancel Request
* Approve Or reject
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.DRIVER_REQUEST_OPERATION, method = RequestMethod.GET)
public ModelAndView cancelOperation(@ModelAttribute("command") final ClientModel clientModel,
@RequestParam(value = "clientId", required = false) final String clientId, final RedirectAttributes ra) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("clientId", Long.valueOf(clientId));
return new ModelAndView(ViewConstants.DRIVER_REQUEST_OPERATION, map);
}
/**
* Created By: Jimit Patel Date:23/02/2017 Use: Driver Cancel Request reject
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@ResponseBody
@RequestMapping(value = UrlConstants.REJECT_DRIVER_CANCEL_REQUEST, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ClientModel rejectdriverrequest(@RequestParam(value = "clientId", required = false) final String clientId)
throws ServiceException {
ClientModel clientModel = clientModelService.getById(Long.valueOf(clientId));
clientModel.setStatusID(CommonUtil.getStatusIDByStatus("Pending"));
clientModelService.update(clientModel);
return clientModel;
}
/**
* Created By: Jimit Patel Date:23/02/2017 Use: Driver Cancel Request
* approve
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@ResponseBody
@RequestMapping(value = UrlConstants.APPROVE_CHANGE_LATER, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ClientModel approveChangeLater(@RequestParam(value = "clientId", required = false) final String clientId)
throws ServiceException {
ClientModel clientModel = clientModelService.getById(Long.valueOf(clientId));
TripCancelHistory tripCancelHistory = copyClientObjectToTrip(clientModel);
tripCancelHistoryService.save(tripCancelHistory);
clientModel.setStatusID(CommonUtil.getStatusIDByStatus("Unassign"));
clientModel.setDriver(null);
clientModelService.update(clientModel);
return clientModel;
}
/**
* Created By: Jimit Patel Date:23/02/2017 Use: to maintain trip history
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
public TripCancelHistory copyClientObjectToTrip(ClientModel clientModel)
{
TripCancelHistory tripHistory = new TripCancelHistory();
if (clientModel != null) {
tripHistory.setInvoiceMode(clientModel.getInvoiceMode());
tripHistory.setPickUpLocation(clientModel.getPickUpLocation());
tripHistory.setPickUpLatLong(clientModel.getPickUpLatLong());
tripHistory.setLandmark(clientModel.getLandmark());
tripHistory.setPincode(clientModel.getPincode());
tripHistory.setPickUpDateTime(clientModel.getPickUpDateTime());
tripHistory.setDrop_location(clientModel.getDrop_location());
tripHistory.setDropDateTime(clientModel.getDropDateTime());
tripHistory.setDropLatLong(clientModel.getDropLatLong());
tripHistory.setRemarks(clientModel.getRemarks());
tripHistory.setHnkKms(clientModel.getHnkKms());
tripHistory.setHnkHours(clientModel.getHnkHours());
tripHistory.setHnkAmount(clientModel.getHnkAmount());
tripHistory.setAdditionalHours(clientModel.getAdditionalHours());
tripHistory.setAdditionalKms(clientModel.getAdditionalKms());
tripHistory.setMinkms(clientModel.getMinkms());
tripHistory.setMinrate(clientModel.getMinrate());
tripHistory.setGraceHours(clientModel.getGraceHours());
tripHistory.setAddcharges(clientModel.getAddcharges());
tripHistory.setStatusID(clientModel.getStatusID());
tripHistory.setSourcePlace(clientModel.getSourcePlace());
tripHistory.setDestinationPlace(clientModel.getDestinationPlace());
tripHistory.setSndPrice(clientModel.getSndPrice());
tripHistory.setTripId(clientModel.getTripId());
tripHistory.setGuest(clientModel.getGuest());
tripHistory.setInvoicePackage(clientModel.getInvoicePackage());
tripHistory.setRateOfContract(clientModel.getRateOfContract());
tripHistory.setCar(clientModel.getCar());
tripHistory.setDriver(clientModel.getDriver());
tripHistory.setCity(clientModel.getCity());
tripHistory.setCompanyMaster(clientModel.getCompanyMaster());
tripHistory.setCanceledId(clientModel.getCanceledId());
tripHistory.setOtp(clientModel.getOtp());
tripHistory.setBillableAmount(clientModel.getBillableAmount());
tripHistory.setDriverDistanceMin(clientModel.getDriverDistanceMin());
return tripHistory;
}
return tripHistory;
}
/**
* Created By: Jimit Patel Date:28/02/2017 Use: To fetch the list of
* Customer Cancel Request List
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.CUSTOMER_CANCEL_REQUEST, method = RequestMethod.GET)
public ModelAndView customerCancelrequestList(@ModelAttribute("command") final ClientModel clientModel,
final RedirectAttributes ra) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.getUserByUsername(auth.getName());
List<ClientModel> cancelRequestList = clientModelService.getCustomerCancelList(user.getTanentID());
Map<String, Object> map = new HashMap<String, Object>();
try {
if (cancelRequestList != null) {
List<ClientModel> clientArry = new ArrayList<>();
for (ClientModel clientModel1 : cancelRequestList) {
if (clientModel1.getPickUpLocation() != null && !("").equals(clientModel1.getPickUpLocation())) {
byte[] pickUpLocation = Base64.getDecoder().decode(clientModel1.getPickUpLocation());
clientModel1.setPickUpLocation(new String(pickUpLocation));
} else {
clientModel1.setPickUpLocation("");
}
if (clientModel1.getDrop_location() != null && !("").equals(clientModel1.getDrop_location())) {
byte[] dropLocation = Base64.getDecoder().decode(clientModel1.getDrop_location());
clientModel1.setDrop_location(new String(dropLocation));
} else {
clientModel1.setDrop_location("");
}
clientArry.add(clientModel1);
}
map.put("CustomerCancelList", clientArry);
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
ra.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.BOOK_CAR_LIST);
}
return new ModelAndView(ViewConstants.LIST_CUSTOMER_CANCEL_REQUEST, map);
}
/**
* Created By: Jimit Patel Date:28/02/2017 Use: To approve Customer Cancel
* Request
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.CUSTOMER_CANCEL_APPROVE, method = RequestMethod.GET)
public ModelAndView customerCancelrequestApprove(final RedirectAttributes ra,
@RequestParam(value = "tripId", required = false) final String tripId) throws ServiceException {
try {
if (tripId != null) {
ClientModel clientModel = clientModelService.getTripByTripId(tripId);
Guest guest = guestService.getById(clientModel.getGuest().getId());
int otp = OTPData.generateOtp();
if (guest != null) {
SMSSend.sendSms(guest, otp);
}
clientModel.setOtp(otp);
clientModelService.update(clientModel);
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
ra.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
}
return new ModelAndView(Constants.REDIRECT + UrlConstants.CUSTOMER_CANCEL_REQUEST);
}
/**
* Created By: Jimit Patel Date:28/02/2017 Use: To approve Customer Cancel
* Request
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.CUSTOMER_CANCEL_REJECT, method = RequestMethod.GET)
public ModelAndView customerCancelrequestReject(@ModelAttribute("command") ClientModel clientModel,
final RedirectAttributes ra, @RequestParam(value = "tripId", required = false) final String tripId,
@RequestParam(value = "pickupdate", required = false) final String pickupdate) throws ServiceException {
try {
if (tripId != null) {
clientModel = clientModelService.getTripByTripId(tripId);
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
DateFormat formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = formatter.parse(pickupdate);
if (new Timestamp(date.getTime()).after(timestamp)) {
clientModel.setStatusID(CommonUtil.getStatusIDByStatus(Constants.TRIP_STATUS_PENDING));
clientModelService.update(clientModel);
} else {
ra.addFlashAttribute(Constants.MESSAGE, "You can Not Reject This trip");
}
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
ra.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
}
return new ModelAndView(Constants.REDIRECT + UrlConstants.CUSTOMER_CANCEL_REQUEST);
}
/**
* @param carId
* @return
*/
@ResponseBody
@RequestMapping(value = UrlConstants.GET_DRIVER_BY_CAR, method = RequestMethod.POST)
private Driver getDriverByCar(@RequestParam("carId") final String carId) {
CarDriverMapping carDriver = null;
Driver driver = null;
if (carId != null && !"".equals(carId)) {
carDriver = carDriverMappingService.getCarDriverByCarId(Long.valueOf(carId));
if (carDriver.getDriId() != null) {
driver = driverService.getById(carDriver.getDriId());
}
}
return driver;
}
/**
* @param clientModel
* @param distance
* @param msg
*/
public void getAlerts(ClientModel clientModel, int distance, String msg) {
try {
if (clientModel != null && clientModel.getDriverDistanceMin() != null
&& distance < clientModel.getDriverDistanceMin()) {
if (clientModel.getCreatedBy() != null) {
Notification notification = notificationService.saveAlertSchedulerNotification(msg,
clientModel.getTanentID());
User user = userService.getUserByUsername(clientModel.getUpdatedBy());
List<User> userList = userService.listOfUserByIdAndTanentID(true, clientModel.getTanentID());
if (user != null) {
if (distance == 45) {
if (user.getContactNo() != null) {
SMSSend.sendSms(Long.valueOf("" + user.getContactNo()), msg);
}
if (clientModel.getDriver() != null && clientModel.getDriver().getContactNo() != null) {
SMSSend.sendSms(Long.valueOf(clientModel.getDriver().getContactNo()), msg);
}
}
}
if (userList != null && userList.size() > 0) {
if (distance == 45) {
if (userList.get(0).getContactNo() != null) {
SMSSend.sendSms(Long.valueOf("" + userList.get(0).getContactNo()), msg);
}
}
if (userList.get(0).getUsername() != null && !userList.get(0).getUsername().equals("")) {
simpMessagingTemplate.convertAndSendToUser(userList.get(0).getUsername(), "/queue/notify",
notification);
}
}
if (user != null && user.getUsername() != null) {
simpMessagingTemplate.convertAndSendToUser(user.getUsername(), "/queue/notify", notification);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param clientModel
* @return
*/
public String getMessageForTripAlert(ClientModel clientModel) {
String msg = "";
msg = "Driver is beyond the reach of upcoming trip.";
msg += "<br>Trip : " + clientModel.getTripId() + ".";
msg += "<br>Car No : " + clientModel.getCar().getCarNo() + ".";
msg += "<br>Driver Name : " + clientModel.getDriver().getFullName() + ".";
msg += "<br>Driver Contact Number : " + clientModel.getDriver().getContactNo() + ".";
msg += "<br>Pick Up Location : " + clientModel.getPickUpLocation() + ".";
msg += "<br>Please Contact to Driver or change the driver.";
msg += "<br><a style='color:red;' href='" + UrlConstants.CHANGE_REQUEST
+ "'>Click On Link to Change Request Page</a>";
return msg;
}
/**
* @param date1
* @param date2
* @param timeUnit
* @return
*/
public long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
return timeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS);
}
} | UTF-8 | Java | 46,295 | java | ClientController.java | Java | [
{
"context": "mport com.twilio.type.PhoneNumber;\n\n/**\n * @author Jimit Patel.\n */\n\n@Controller\npublic class ClientController {",
"end": 4188,
"score": 0.9997879266738892,
"start": 4177,
"tag": "NAME",
"value": "Jimit Patel"
},
{
"context": "vice alertSchedulerService;\n\n\t/**... | null | [] | package com.emxcel.dms.portal.controller;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.emxcel.dms.core.business.constants.Constants;
import com.emxcel.dms.core.business.exception.ServiceException;
import com.emxcel.dms.core.business.services.car.CarNameService;
import com.emxcel.dms.core.business.services.car.CarService;
import com.emxcel.dms.core.business.services.car.CarTypeService;
import com.emxcel.dms.core.business.services.city.CityService;
import com.emxcel.dms.core.business.services.client.ClientModelService;
import com.emxcel.dms.core.business.services.client.PreBookingService;
import com.emxcel.dms.core.business.services.client.TripCancelHistoryService;
import com.emxcel.dms.core.business.services.companymaster.CompanyMasterService;
import com.emxcel.dms.core.business.services.driver.DriverService;
import com.emxcel.dms.core.business.services.guest.GuestService;
import com.emxcel.dms.core.business.services.mapping.CarDriverMappingService;
import com.emxcel.dms.core.business.services.notification.AlertSchedulerService;
import com.emxcel.dms.core.business.services.notification.NotificationService;
import com.emxcel.dms.core.business.services.superadmin.DestinationMasterService;
import com.emxcel.dms.core.business.services.superadmin.InvoicePackageService;
import com.emxcel.dms.core.business.services.superadmin.RateOfContractService;
import com.emxcel.dms.core.business.services.tax.TaxSlabService;
import com.emxcel.dms.core.business.services.user.UserService;
import com.emxcel.dms.core.business.utils.CommonUtil;
import com.emxcel.dms.core.business.utils.OTPData;
import com.emxcel.dms.core.business.utils.SMSSend;
import com.emxcel.dms.core.model.car.Car;
import com.emxcel.dms.core.model.car.CarDriverMapping;
import com.emxcel.dms.core.model.car.CarName;
import com.emxcel.dms.core.model.car.CarType;
import com.emxcel.dms.core.model.client.ClientModel;
import com.emxcel.dms.core.model.client.PreBooking;
import com.emxcel.dms.core.model.client.TripCancelHistory;
import com.emxcel.dms.core.model.common.AlertScheduler;
import com.emxcel.dms.core.model.common.Notification;
import com.emxcel.dms.core.model.companymaster.CompanyMaster;
import com.emxcel.dms.core.model.driver.Driver;
import com.emxcel.dms.core.model.guest.Guest;
import com.emxcel.dms.core.model.superadmin.DestinationMaster;
import com.emxcel.dms.core.model.tax.TaxSlab;
import com.emxcel.dms.core.model.user.User;
import com.emxcel.dms.portal.constants.UrlConstants;
import com.emxcel.dms.portal.constants.ViewConstants;
import com.emxcel.dms.portal.model.BookCarBean;
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Call;
import com.twilio.type.PhoneNumber;
/**
* @author <NAME>.
*/
@Controller
public class ClientController {
private static final Logger logger = Logger.getLogger(ClientController.class);
/**
* **We autowired it to use services of DriverService **.
*/
@Inject
private DriverService driverService;
/**
* **We autowired it to use services of GuestService **.
*/
@Inject
private GuestService guestService;
/**
* **We autowired it to use services of ClientModelService **.
*/
@Inject
private ClientModelService clientModelService;
/**
* **We autowired it to use services of RateOfContractService **.
*/
@Inject
private RateOfContractService rateOfContractService;
/**
* **We autowired it to use services of InvoicePackageService **.
*/
@Inject
private InvoicePackageService invoicePackageService;
/**
* **We autowired it to use services of CityService **.
*/
@Inject
private CityService cityService;
/**
* **We autowired it to use services of CarService **.
*/
@Inject
private CarService carService;
/**
* **We autowired it to use services of DestinationMasterService **.
*/
@Inject
private DestinationMasterService destinationMasterService;
/**
* **We autowired it to use services of CompanyMasterService **.
*/
@Inject
private CompanyMasterService companyMasterService;
/**
* **We autowired it to use services of TaxSlabService **.
*/
@Inject
private TaxSlabService taxSlabService;
/**
* **We autowired it to use services of CarTypeService **.
*/
@Inject
private CarTypeService carTypeService;
/**
* **We autowired it to use services of CarNameService **.
*/
@Inject
private CarNameService carNameService;
/**
* **We autowired it to use services of CarDriverMappingService **.
*/
@Inject
private PreBookingService preBookingService;
@Inject
private TripCancelHistoryService tripCancelHistoryService;
@Inject
private UserService userService;
@Inject
private CarDriverMappingService carDriverMappingService;
@PersistenceContext
private EntityManager manager;
/**
* SimpMessagingTemplate.
*/
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
/**
* NotificationService.
*/
@Inject
private NotificationService notificationService;
/**
* AlertSchedulerService.
*/
@Inject
private AlertSchedulerService alertSchedulerService;
/**
* Created By : <NAME> , Date: 20-01-2017 Use : To get the list of
* Companies from Company Master for automatic suggestions.
*
* @param query
* **Requested From Client Booking Jsp**
* @return comapnyList
*/
@ResponseBody
@RequestMapping(value = UrlConstants.GETCOMPANY_LIST, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<CompanyMaster> getCompanyList(@RequestParam(value = "term", required = false) final String query) {
return companyMasterService.getCompanyNameList(query);
}
/**
* Created By : <NAME> , Date: 06-03-2017 Use : To get the list of
* Contact from Guest for automatic suggestions.
*
* @param query
* **Requested From Client Booking Jsp**
* @return comapnyList
*/
@ResponseBody
@RequestMapping(value = UrlConstants.GET_CONTACT_LIST, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Guest> getContactList(@RequestParam(value = "term", required = false) final String query) {
return guestService.getContactNumberList(query);
}
/**
* Created By : <NAME> , Date: 06-03-2017 Use : To get the Detail Of
* Customer on the basis of Mobile No.
*
* @param query
* **Requested From Client Booking Jsp**
* @return comapnyList
*/
@ResponseBody
@RequestMapping(value = UrlConstants.GET_GUEST_DETAIL, method = RequestMethod.POST)
public Guest getGuestDetail(
@RequestParam(value = "contactNo", required = false) final String contactNo) {
return guestService.getGuestDetailByContactNo(contactNo);
}
/**
* Created By : <NAME> , Date: 20-01-2017 Use : To get the list of
* Source Place from Source Destination Master for automatic suggestions.
*
* @param query
* **Requested From Client Booking Jsp**
* @return sourcePlaceList
*/
@ResponseBody
@RequestMapping(value = UrlConstants.SOURCEPLACE_LIST, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<DestinationMaster> getSourceList(@RequestParam("term") final String query,
final RedirectAttributes redirect) {
List<DestinationMaster> sourcePlaceList = null;
try {
sourcePlaceList = destinationMasterService.getsourcePlaceList(query);
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
redirect.addFlashAttribute(Constants.MESSAGE, " Something Went Wrong !!!");
return Collections.emptyList();
}
return sourcePlaceList;
}
/**
* Created By : <NAME> , Date: 20-01-2017 Use : To get the list of
* Destination Place from Source Destination Master for automatic
* suggestions.
*
* @param query
* **Requested From Client Booking Jsp**
* @return destinationPlaceList
*/
@ResponseBody
@RequestMapping(value = UrlConstants.DESTINATIONPLACE_LIST, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<DestinationMaster> getDestinationList(@RequestParam("term") final String query,
final RedirectAttributes redirect) {
List<DestinationMaster> destinationPlaceList = null;
try {
destinationPlaceList = destinationMasterService.getdestinationPlaceList(query);
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
redirect.addFlashAttribute(Constants.MESSAGE, " Something Went Wrong !!!");
return Collections.emptyList();
}
return destinationPlaceList;
}
/**
* Created By : <NAME> , Date: 23-01-2017. Use : To get the list of tax
* Slab on the basis of selected invoice category.
*
* @param id
* **Get Invoice category id From Client Booking Jsp**
* @return listoftax
*/
@RequestMapping(value = UrlConstants.INVOICE_TAX_LIST, method = RequestMethod.POST)
@ResponseBody
public List<TaxSlab> getAllTaxes(
@RequestParam(value = "invoiceCategories", required = false) final String categoryId) {
try {
if (categoryId != null && !("").equals(categoryId)) {
return taxSlabService.getTaxSlabById(Long.valueOf(categoryId));
} else {
return Collections.emptyList();
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
return Collections.emptyList();
}
}
/**
* Created By : <NAME> , Date: 23-01-2017. Use : To get the list of Booked Cars
* @param session`
* @param clientModel
* @param result
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.LIST_BOOKEDCARS, method = RequestMethod.GET)
private ModelAndView bookedCarList(final HttpSession session,
@ModelAttribute("command") final ClientModel clientModel, final BindingResult result) {
User user = (User) session.getAttribute("user");
Map<String, Object> map = new HashMap<>();
List<ClientModel> listOfClient = clientModelService.getClientAndGuestModel(user.getTanentID());
List<ClientModel> clientArry = new ArrayList<>();
for (ClientModel clientModel1 : listOfClient) {
if (clientModel1.getPickUpLocation() != null && !("").equals(clientModel1.getPickUpLocation())) {
byte[] pickUpLocation = Base64.getDecoder().decode(clientModel1.getPickUpLocation());
clientModel1.setPickUpLocation(new String(pickUpLocation));
} else {
clientModel1.setPickUpLocation("");
}
if (clientModel1.getDrop_location() != null && !("").equals(clientModel1.getDrop_location())) {
byte[] dropLocation = Base64.getDecoder().decode(clientModel1.getDrop_location());
clientModel1.setDrop_location(new String(dropLocation));
} else {
clientModel1.setDrop_location("");
}
clientArry.add(clientModel1);
}
map.put("clientModelList", clientArry);
return new ModelAndView(ViewConstants.LIST_BOOKEDCARS, map);
}
/**
* Created By : <NAME> , Date: 20-01-2017. Use: To open Client Booking
* Page through Search Car Page
*
* @param carId
* **carId**
* @param clientId
* **clientId**
* @param clientModel
* **clientModel**
* @param pickUpDateTime
* **picUpDateTime**
* @param dropDateTime
* **dropDateTime**
* @param result
* **result**
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.CLIENT_PAGE, method = RequestMethod.POST)
private ModelAndView addClient(@RequestParam(value = "carId", required = false) final String carId,
@RequestParam(value = "clientId", required = false) final String clientId,
@ModelAttribute("command") final ClientModel clientModel,
@RequestParam(value = "pickUpDateTime1", required = false) final String pickUpDateTime,
@RequestParam(value = "dropDateTime1", required = false) final String dropDateTime,
@RequestParam(value = "driverId", required = false) final String driverId,
@RequestParam(value = "preBooking", required = false) final String prebBookingId,
final BindingResult result, final RedirectAttributes ra) {
Map<String, Object> map = new HashMap<>();
try {
Car car = this.carService.getById(Long.valueOf(carId));
if (car != null && !("").equals(car)) {
map.put("carDtls", car);
CarType carType = this.carTypeService.getById(car.getCarTypeId());
if (carType != null) {
map.put("carTypeDtls", carType);
}
CarName carName = this.carNameService.getById(car.getCarNameId());
if (carName != null) {
map.put("carNameDtls", carName);
}
Driver driverDtlS = null;
if (driverId != null) {
driverDtlS = this.driverService.getById(Long.valueOf(driverId));
} else {
ClientModel clientModelForDriver = clientModelService.getById(Long.valueOf(clientId));
driverDtlS = this.driverService.getById(clientModelForDriver.getDriver().getId());
}
map.put("driverDtlS", driverDtlS);
}
map.put("InvoiceDTL", invoicePackageService.list());
map.put("RateContract", rateOfContractService.list());
map.put("CityDTL", cityService.list());
map.put("CompanyMasterDTL", companyMasterService.list());
map.put("pickUpDateTime", pickUpDateTime);
map.put("dropDateTime", dropDateTime);
if (clientId != null && !("a").equals(clientId)) {
ClientModel clientModel1 = clientModelService.getById(Long.valueOf(clientId));
if (clientModel1.getPickUpLocation() != null && !("").equals(clientModel1.getPickUpLocation())) {
byte[] pickUpLocation = Base64.getDecoder().decode(clientModel1.getPickUpLocation());
clientModel1.setPickUpLocation(new String(pickUpLocation));
} else {
clientModel1.setPickUpLocation("");
}
if (clientModel1.getDrop_location() != null && !("").equals(clientModel1.getDrop_location())) {
byte[] dropLocation = Base64.getDecoder().decode(clientModel1.getDrop_location());
clientModel1.setDrop_location(new String(dropLocation));
} else {
clientModel1.setDrop_location("");
}
map.put("clientModel", clientModel1);
}
if (prebBookingId != null && !prebBookingId.equals("")) {
PreBooking preBooking = preBookingService.getById(Long.valueOf(prebBookingId));
map.put("preBookingId", prebBookingId);
ClientModel clientModel1 = new ClientModel();
clientModel1.setId(Long.valueOf("0"));
clientModel1.setInvoiceMode(preBooking.getInvoiceMode());
clientModel1.setGuest(guestService.getById(preBooking.getGuest().getId()));
byte[] pickUpLocation = Base64.getDecoder().decode(preBooking.getPickUpLocation());
clientModel1.setPickUpLocation(new String(pickUpLocation));
byte[] dropLocation = Base64.getDecoder().decode(preBooking.getDrop_location());
clientModel1.setDrop_location(new String(dropLocation));
clientModel1.setInvoiceMode(preBooking.getInvoiceMode());
clientModel1.setCity(cityService.getById(preBooking.getCity().getId()));
clientModel1.setLandmark(preBooking.getLandmark());
clientModel1.setPincode(preBooking.getPincode());
clientModel1.setRemarks(preBooking.getRemarks());
clientModel1.setInvoicePackage(invoicePackageService.getById(preBooking.getInvoicePackage().getId()));
clientModel1.setRateOfContract(rateOfContractService.getById(preBooking.getRateOfContract().getId()));
clientModel1.setMinkms(preBooking.getMinkms());
clientModel1.setMinrate(preBooking.getMinrate());
clientModel1.setDriverAllownce(preBooking.getDriverAllownce());
clientModel1.setGraceHours(preBooking.getGraceHours());
clientModel1.setPaymentMode(preBooking.getPaymentMode());
clientModel1.setHnkKms(preBooking.getHnkKms());
clientModel1.setHnkHours(preBooking.getHnkHours());
clientModel1.setHnkAmount(preBooking.getHnkAmount());
clientModel1.setAdditionalHours(preBooking.getAdditionalHours());
clientModel1.setAdditionalKms(preBooking.getAdditionalKms());
clientModel1.setSourcePlace(preBooking.getSourcePlace());
clientModel1.setDestinationPlace(preBooking.getDestinationPlace());
clientModel1.setSndPrice(preBooking.getSndPrice());
if (preBooking.getCompanyMaster() != null) {
clientModel1.setCompanyMaster(companyMasterService.getById(preBooking.getCompanyMaster().getId()));
}
map.put("clientModel", clientModel1);
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
ra.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.SEARCH_CAR);
}
return new ModelAndView(ViewConstants.CLIENT_PAGE, map);
}
/**
* Created By : <NAME> , Date: 20-01-2017 Use: To Save the Booking
* Details Of Client.
*
* @param pickUpDateTime
* **picUpDateTime**
* @param dropDate
* **dropDate**
* @param clientModel
* **clientModel**
* @param result
* **result**
* @param session
* **session**
* @exception ServiceException
* @return ModelAndView
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = UrlConstants.SAVE_CLIENT, method = RequestMethod.POST)
private ModelAndView saveClientDetails(
@ModelAttribute("command") @RequestParam("pickUpDateTime") String pickUpDateTime,
@RequestParam("dropDateTime") String dropDate,
@RequestParam("preBookingId") String preBookingId,
final ClientModel clientModel,
final BindingResult result, HttpSession session, final RedirectAttributes redirect) {
try {
clientModelService.saveClientDetails(clientModel, session, pickUpDateTime, dropDate, preBookingId);
SimpleDateFormat diff = new SimpleDateFormat(Constants.PORTAL_DATE_FORMAT);
Calendar cal = Calendar.getInstance();
cal.setTime(diff.parse(CommonUtil.convertTimestampToDateInString(clientModel.getPickUpDateTime())));
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.add(Calendar.MINUTE, -60);
Date date1 = cal.getTime();
Timer timer1 = new Timer(true);
AlertScheduler alertScheduler1 = alertSchedulerService.saveAlertSchedulerReturnEntity(date1,
clientModel.getTripId(), false, 1);
timer1.schedule(new TimerTask() {
@Override
public void run() {
try {
ClientModel clientModelNew = null;
// 1 hour left then Notification Alert to Admin & DE
int hour = 1;
String msg = "Your Trip Has Left " + hour + " Hour to start !!!";
if (clientModel.getDriver() != null && clientModel.getDriver().getTokenID() != null) {
CommonUtil.getTokenByContactNo(clientModel.getDriver().getTokenID(), msg + " ,tripID="
+ clientModel.getTripId() + "," + "latlong=" + clientModel.getPickUpLatLong() + "", "driverApp");
}
// Sleep for 10 sec
Thread.sleep(10000);
clientModelNew = clientModelService.getTripByTripId(clientModel.getTripId());
msg = getMessageForTripAlert(clientModelNew);
getAlerts(clientModelNew, hour, msg);
alertSchedulerService.updateAlertSchedulerReturnEntity(true, alertScheduler1);
timer1.cancel();
timer1.purge();
} catch (Exception e) {
e.printStackTrace();
}
};
}, date1);
cal = Calendar.getInstance();
cal.setTime(diff.parse(CommonUtil.convertTimestampToDateInString(clientModel.getPickUpDateTime())));
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.add(Calendar.MINUTE, -58);
Date date2 = cal.getTime();
AlertScheduler alertScheduler2 = alertSchedulerService.saveAlertSchedulerReturnEntity(date2,
clientModel.getTripId(), false, 2);
Timer timer2 = new Timer(true);
timer2.schedule(new TimerTask() {
@Override
public void run() {
try {
ClientModel clientModelNew = null;
// 45 min left then Notification Alert to Admin & DE
int fortyFiveMinutes = 45;
String msg = "Your Trip Has Left " + fortyFiveMinutes + " minutes to start !!!";
if (clientModel.getDriver() != null && clientModel.getDriver().getTokenID() != null) {
CommonUtil.getTokenByContactNo(clientModel.getDriver().getTokenID(), msg + " ,tripID="
+ clientModel.getTripId() + "," + "latlong=" + clientModel.getPickUpLatLong() + "", "driverApp");
}
// Sleep for 10 sec
Thread.sleep(10000);
clientModelNew = clientModelService.getTripByTripId(clientModel.getTripId());
msg = getMessageForTripAlert(clientModelNew);
getAlerts(clientModelNew, fortyFiveMinutes, "minutes");
alertSchedulerService.updateAlertSchedulerReturnEntity(true, alertScheduler2);
timer2.cancel();
timer2.purge();
} catch (Exception e) {
e.printStackTrace();
}
};
}, date2);
cal = Calendar.getInstance();
cal.setTime(diff.parse(CommonUtil.convertTimestampToDateInString(clientModel.getPickUpDateTime())));
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.add(Calendar.MINUTE, -56);
Date date3 = cal.getTime();
AlertScheduler alertScheduler3 = alertSchedulerService.saveAlertSchedulerReturnEntity(date3,
clientModel.getTripId(), false, 3);
Timer timer3 = new Timer(true);
timer3.schedule(new TimerTask() {
@Override
public void run() {
try {
ClientModel clientModelNew = null;
// 30 min left then Notification Alert to Admin & DE
int thrityMinutes = 30;
String msg = "Your Trip Has Left " + thrityMinutes + " minutes to start !!!";
if (clientModel.getDriver() != null && clientModel.getDriver().getTokenID() != null) {
CommonUtil.getTokenByContactNo(clientModel.getDriver().getTokenID(), msg + " ,tripID="
+ clientModel.getTripId() + "," + "latlong=" + clientModel.getPickUpLatLong() + "", "driverApp");
}
// Sleep for 10 sec
Thread.sleep(10000);
clientModelNew = clientModelService.getTripByTripId(clientModel.getTripId());
msg = getMessageForTripAlert(clientModel);
if (clientModelNew != null && clientModelNew.getDriverDistanceMin() != null
&& thrityMinutes < clientModelNew.getDriverDistanceMin()) {
getAlerts(clientModelNew, thrityMinutes, msg);
final String ACCOUNT_SID = "AC4e1f4bb93ef57dc18d1ad9cbb4acea65";
final String AUTH_TOKEN = "<PASSWORD>";
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
Call call = null;
try {
call = Call
.creator(new PhoneNumber("+917405799970"), new PhoneNumber("+18583465930"),
new URI("https://handler.twilio.com/twiml/EHa8565f08cfa0860cd2f067271a9682ce"))
.create();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
alertSchedulerService.updateAlertSchedulerReturnEntity(true, alertScheduler3);
timer3.cancel();
timer3.purge();
} catch (Exception e) {
e.printStackTrace();
}
};
}, date3);
if (clientModel.getDriver() != null && clientModel.getDriver().getTokenID() != null) {
// if (clientModel.getGuest() != null && token != null) {
String message = "One Trip has been Booked !! ./n";
CommonUtil.getTokenByContactNo(clientModel.getDriver().getTokenID(), message, "driverApp");
}
if (clientModel.getGuest() != null && clientModel.getGuest().getTokenID() != null) {
// if (clientModel.getGuest() != null && token != null) {
String message = "Your Trip has been Booked !! ./n";
CommonUtil.getTokenByContactNo(clientModel.getGuest().getTokenID(), message, "feedApp");
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
redirect.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
/**
* Created By : <NAME> , Date: 20-01-2017 Use: To Update Booking Detail
* @param pickUpDateTime
* @param dropDate
* @param clientModel
* @param result
* @param ra
* @return
*/
@RequestMapping(value = UrlConstants.UPDATE_CLIENT, method = RequestMethod.POST)
private ModelAndView updateClient(@ModelAttribute("command") @RequestParam("pickUpDateTime") String pickUpDateTime,
@RequestParam("dropDateTime") String dropDate, final ClientModel clientModel, final BindingResult result,
final RedirectAttributes redirect) {
try {
clientModelService.updateClientDetsils(clientModel, pickUpDateTime, dropDate);
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
redirect.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
/**
* @param tripId
* @param result
* @return
*/
@RequestMapping(value = UrlConstants.CANCELED_TRIP, method = RequestMethod.GET)
private ModelAndView cancelBookedCarTrip(@RequestParam(value = "tripId", required = false) final String tripId,
final ClientModel clientModel, final BindingResult result, final RedirectAttributes ra) {
try {
clientModelService.setSatusCancel(tripId);
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
ra.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
/**
* @param cartype
* @param clientId
* @param changeRequestBy
* @return
*/
@RequestMapping(value = UrlConstants.CHANGE_REQUEST, method = RequestMethod.POST)
public ModelAndView changeRequestPage(@ModelAttribute("command") final CarType cartype,
@RequestParam(value = "clientId", required = false) final String clientId,
@RequestParam(value = "flag", required = false) final String changeRequestBy) {
ModelAndView model = new ModelAndView();
model.addObject("changeRequestBy",changeRequestBy);
if (clientId != null && !("").equals(clientId)) {
ClientModel clientModel=clientModelService.getById(Long.valueOf(clientId));
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
List<Driver> driverList=manager.createNamedQuery("getAvailableDrivers", Driver.class)
.setParameter("picUpDateTime", dateFormat.format(clientModel.getPickUpDateTime()))
.setParameter("dropDate", dateFormat.format(clientModel.getDropDateTime()))
.setParameter("tanentID", clientModel.getTanentID()).getResultList();
List<Car> carList = manager.createNamedQuery("getCarAvailableListForAllCarType", Car.class)
.setParameter("picUpDateTime", dateFormat.format(clientModel.getPickUpDateTime()))
.setParameter("dropDate",dateFormat.format(clientModel.getDropDateTime()))
.setParameter("tanentID", clientModel.getTanentID()).getResultList();
List<BookCarBean> listOfBookCar=new ArrayList<>();
Car carModel=carService.getById(clientModel.getCar().getId());
carList.add(carModel);
for (Car car : carList) {
BookCarBean bookCarBean = new BookCarBean();
bookCarBean.setCarId(car.getId());
bookCarBean.setCarNumber(car.getCarNo());
CarType carType = carTypeService.getById(car.getCarTypeId());
bookCarBean.setCarType(carType.getCarType());
CarName carName = carNameService.getById(car.getCarNameId());
bookCarBean.setCarName(carName.getCarName());
listOfBookCar.add(bookCarBean);
}
model.addObject("driverList", driverList);
if (changeRequestBy != null) {
if (changeRequestBy.equals("driver")) {
model.addObject("changeRequestBy", changeRequestBy);
}
} else {
model.addObject("listOfBookCar", listOfBookCar);
model.addObject("changeRequestBy", null);
}
model.addObject("clientId", clientId);
model.addObject("carNo", carModel.getId());
}
model.setViewName(ViewConstants.CHANGE_REQUEST);
return model;
}
/**
* @param cartype
* @param clientId
* @param carId
* @param driverId
* @param changeRequestBy
* @param ra
* @return
* @throws ServiceException
*/
@RequestMapping(value = UrlConstants.CHANGE_REQUEST_ACCEPT, method = RequestMethod.POST)
public ModelAndView changeRequestAccepted(@ModelAttribute("command") final CarType cartype,
@RequestParam(value = "clientId", required = false) final String clientId,
@RequestParam(value = "carId", required = false) final String carId,
@RequestParam(value = "driverId", required = false) final String driverId ,
@RequestParam(value = "changeRequestBy", required = false) final String changeRequestBy,
final RedirectAttributes ra) throws ServiceException {
ClientModel clientModel = clientModelService.getById(Long.valueOf(clientId));
if(driverId!=null && !("0").equals(driverId)) {
Driver driver = driverService.getById(Long.valueOf(driverId));
clientModel.setDriver(driver);
}
if (carId != null && !("0").equals(carId) && !carId.equals("")) {
Car car = carService.getById(Long.valueOf(carId));
clientModel.setCar(car);
}
TripCancelHistory tripCancelHistory = copyClientObjectToTrip(clientModel);
tripCancelHistoryService.save(tripCancelHistory);
clientModel.setStatusID(CommonUtil.getStatusIDByStatus(Constants.TRIP_STATUS_PENDING));
clientModelService.update(clientModel);
ra.addFlashAttribute(Constants.MESSAGE, "Change(s) Request Accepted & Updated Successfully !!!");
if (changeRequestBy == null) {
return new ModelAndView(Constants.REDIRECT + UrlConstants.CANCEL_REQUEST_LIST);
} else {
return new ModelAndView(Constants.REDIRECT + UrlConstants.LIST_BOOKEDCARS);
}
}
/**
* @param cartype
* @param clientId
* @param carId
* @param driverId
* @param ra
* @return
* @throws ServiceException
*/
@RequestMapping(value = UrlConstants.CHANGE_REQUEST_REJECT, method = RequestMethod.POST)
public ModelAndView changeRequestRejected(@ModelAttribute("command") final CarType cartype,
@RequestParam(value = "clientId", required = false) final String clientId,
@RequestParam(value = "carId", required = false) final String carId,
@RequestParam(value = "driverId", required = false) final String driverId, final RedirectAttributes ra)
throws ServiceException {
ClientModel clientModel = clientModelService.getById(Long.valueOf(clientId));
clientModel.setStatusID(CommonUtil.getStatusIDByStatus("Pending"));
clientModelService.update(clientModel);
ra.addFlashAttribute(Constants.MESSAGE, "Sorry , Change Request Rejected ... !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.CANCEL_REQUEST_LIST);
}
/**
* Created By: <NAME> Date:22/02/2017 Use: To fetch the list of Driver
* Cancel Request List
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.CANCEL_REQUEST_LIST, method = RequestMethod.GET)
public ModelAndView cancelrequestList(@ModelAttribute("command") final ClientModel clientModel,
final RedirectAttributes ra) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.getUserByUsername(auth.getName());
List<ClientModel> cancelRequestList = clientModelService.getDriverCancelList(user.getTanentID());
Map<String, Object> map = new HashMap<String, Object>();
try {
if (cancelRequestList != null) {
List<ClientModel> clientArry = new ArrayList<>();
for (ClientModel clientModel1 : cancelRequestList) {
if (clientModel1.getPickUpLocation() != null && !("").equals(clientModel1.getPickUpLocation())) {
byte[] pickUpLocation = Base64.getDecoder().decode(clientModel1.getPickUpLocation());
clientModel1.setPickUpLocation(new String(pickUpLocation));
} else {
clientModel1.setPickUpLocation("");
}
if (clientModel1.getDrop_location() != null && !("").equals(clientModel1.getDrop_location())) {
byte[] dropLocation = Base64.getDecoder().decode(clientModel1.getDrop_location());
clientModel1.setDrop_location(new String(dropLocation));
} else {
clientModel1.setDrop_location("");
}
clientArry.add(clientModel1);
}
map.put("CancelList", clientArry);
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
ra.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.BOOK_CAR_LIST);
}
return new ModelAndView(ViewConstants.LIST_CANCEL_REQUEST, map);
}
/**
* Created By: <NAME> Date:23/02/2017 Use: Driver Cancel Request
* Approve Or reject
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.DRIVER_REQUEST_OPERATION, method = RequestMethod.GET)
public ModelAndView cancelOperation(@ModelAttribute("command") final ClientModel clientModel,
@RequestParam(value = "clientId", required = false) final String clientId, final RedirectAttributes ra) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("clientId", Long.valueOf(clientId));
return new ModelAndView(ViewConstants.DRIVER_REQUEST_OPERATION, map);
}
/**
* Created By: <NAME> Date:23/02/2017 Use: Driver Cancel Request reject
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@ResponseBody
@RequestMapping(value = UrlConstants.REJECT_DRIVER_CANCEL_REQUEST, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ClientModel rejectdriverrequest(@RequestParam(value = "clientId", required = false) final String clientId)
throws ServiceException {
ClientModel clientModel = clientModelService.getById(Long.valueOf(clientId));
clientModel.setStatusID(CommonUtil.getStatusIDByStatus("Pending"));
clientModelService.update(clientModel);
return clientModel;
}
/**
* Created By: <NAME> Date:23/02/2017 Use: Driver Cancel Request
* approve
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@ResponseBody
@RequestMapping(value = UrlConstants.APPROVE_CHANGE_LATER, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ClientModel approveChangeLater(@RequestParam(value = "clientId", required = false) final String clientId)
throws ServiceException {
ClientModel clientModel = clientModelService.getById(Long.valueOf(clientId));
TripCancelHistory tripCancelHistory = copyClientObjectToTrip(clientModel);
tripCancelHistoryService.save(tripCancelHistory);
clientModel.setStatusID(CommonUtil.getStatusIDByStatus("Unassign"));
clientModel.setDriver(null);
clientModelService.update(clientModel);
return clientModel;
}
/**
* Created By: <NAME> Date:23/02/2017 Use: to maintain trip history
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
public TripCancelHistory copyClientObjectToTrip(ClientModel clientModel)
{
TripCancelHistory tripHistory = new TripCancelHistory();
if (clientModel != null) {
tripHistory.setInvoiceMode(clientModel.getInvoiceMode());
tripHistory.setPickUpLocation(clientModel.getPickUpLocation());
tripHistory.setPickUpLatLong(clientModel.getPickUpLatLong());
tripHistory.setLandmark(clientModel.getLandmark());
tripHistory.setPincode(clientModel.getPincode());
tripHistory.setPickUpDateTime(clientModel.getPickUpDateTime());
tripHistory.setDrop_location(clientModel.getDrop_location());
tripHistory.setDropDateTime(clientModel.getDropDateTime());
tripHistory.setDropLatLong(clientModel.getDropLatLong());
tripHistory.setRemarks(clientModel.getRemarks());
tripHistory.setHnkKms(clientModel.getHnkKms());
tripHistory.setHnkHours(clientModel.getHnkHours());
tripHistory.setHnkAmount(clientModel.getHnkAmount());
tripHistory.setAdditionalHours(clientModel.getAdditionalHours());
tripHistory.setAdditionalKms(clientModel.getAdditionalKms());
tripHistory.setMinkms(clientModel.getMinkms());
tripHistory.setMinrate(clientModel.getMinrate());
tripHistory.setGraceHours(clientModel.getGraceHours());
tripHistory.setAddcharges(clientModel.getAddcharges());
tripHistory.setStatusID(clientModel.getStatusID());
tripHistory.setSourcePlace(clientModel.getSourcePlace());
tripHistory.setDestinationPlace(clientModel.getDestinationPlace());
tripHistory.setSndPrice(clientModel.getSndPrice());
tripHistory.setTripId(clientModel.getTripId());
tripHistory.setGuest(clientModel.getGuest());
tripHistory.setInvoicePackage(clientModel.getInvoicePackage());
tripHistory.setRateOfContract(clientModel.getRateOfContract());
tripHistory.setCar(clientModel.getCar());
tripHistory.setDriver(clientModel.getDriver());
tripHistory.setCity(clientModel.getCity());
tripHistory.setCompanyMaster(clientModel.getCompanyMaster());
tripHistory.setCanceledId(clientModel.getCanceledId());
tripHistory.setOtp(clientModel.getOtp());
tripHistory.setBillableAmount(clientModel.getBillableAmount());
tripHistory.setDriverDistanceMin(clientModel.getDriverDistanceMin());
return tripHistory;
}
return tripHistory;
}
/**
* Created By: <NAME> Date:28/02/2017 Use: To fetch the list of
* Customer Cancel Request List
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.CUSTOMER_CANCEL_REQUEST, method = RequestMethod.GET)
public ModelAndView customerCancelrequestList(@ModelAttribute("command") final ClientModel clientModel,
final RedirectAttributes ra) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.getUserByUsername(auth.getName());
List<ClientModel> cancelRequestList = clientModelService.getCustomerCancelList(user.getTanentID());
Map<String, Object> map = new HashMap<String, Object>();
try {
if (cancelRequestList != null) {
List<ClientModel> clientArry = new ArrayList<>();
for (ClientModel clientModel1 : cancelRequestList) {
if (clientModel1.getPickUpLocation() != null && !("").equals(clientModel1.getPickUpLocation())) {
byte[] pickUpLocation = Base64.getDecoder().decode(clientModel1.getPickUpLocation());
clientModel1.setPickUpLocation(new String(pickUpLocation));
} else {
clientModel1.setPickUpLocation("");
}
if (clientModel1.getDrop_location() != null && !("").equals(clientModel1.getDrop_location())) {
byte[] dropLocation = Base64.getDecoder().decode(clientModel1.getDrop_location());
clientModel1.setDrop_location(new String(dropLocation));
} else {
clientModel1.setDrop_location("");
}
clientArry.add(clientModel1);
}
map.put("CustomerCancelList", clientArry);
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
ra.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
return new ModelAndView(Constants.REDIRECT + UrlConstants.BOOK_CAR_LIST);
}
return new ModelAndView(ViewConstants.LIST_CUSTOMER_CANCEL_REQUEST, map);
}
/**
* Created By: <NAME> Date:28/02/2017 Use: To approve Customer Cancel
* Request
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.CUSTOMER_CANCEL_APPROVE, method = RequestMethod.GET)
public ModelAndView customerCancelrequestApprove(final RedirectAttributes ra,
@RequestParam(value = "tripId", required = false) final String tripId) throws ServiceException {
try {
if (tripId != null) {
ClientModel clientModel = clientModelService.getTripByTripId(tripId);
Guest guest = guestService.getById(clientModel.getGuest().getId());
int otp = OTPData.generateOtp();
if (guest != null) {
SMSSend.sendSms(guest, otp);
}
clientModel.setOtp(otp);
clientModelService.update(clientModel);
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
ra.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
}
return new ModelAndView(Constants.REDIRECT + UrlConstants.CUSTOMER_CANCEL_REQUEST);
}
/**
* Created By: <NAME> Date:28/02/2017 Use: To approve Customer Cancel
* Request
*
* @param clientModel
* @param ra
* @return ModelAndView
*/
@RequestMapping(value = UrlConstants.CUSTOMER_CANCEL_REJECT, method = RequestMethod.GET)
public ModelAndView customerCancelrequestReject(@ModelAttribute("command") ClientModel clientModel,
final RedirectAttributes ra, @RequestParam(value = "tripId", required = false) final String tripId,
@RequestParam(value = "pickupdate", required = false) final String pickupdate) throws ServiceException {
try {
if (tripId != null) {
clientModel = clientModelService.getTripByTripId(tripId);
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
DateFormat formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = formatter.parse(pickupdate);
if (new Timestamp(date.getTime()).after(timestamp)) {
clientModel.setStatusID(CommonUtil.getStatusIDByStatus(Constants.TRIP_STATUS_PENDING));
clientModelService.update(clientModel);
} else {
ra.addFlashAttribute(Constants.MESSAGE, "You can Not Reject This trip");
}
}
} catch (Exception e) {
logger.error(Constants.EXCEPTION_THROW, e);
ra.addFlashAttribute(Constants.MESSAGE, "Something Went Wrong !!!");
}
return new ModelAndView(Constants.REDIRECT + UrlConstants.CUSTOMER_CANCEL_REQUEST);
}
/**
* @param carId
* @return
*/
@ResponseBody
@RequestMapping(value = UrlConstants.GET_DRIVER_BY_CAR, method = RequestMethod.POST)
private Driver getDriverByCar(@RequestParam("carId") final String carId) {
CarDriverMapping carDriver = null;
Driver driver = null;
if (carId != null && !"".equals(carId)) {
carDriver = carDriverMappingService.getCarDriverByCarId(Long.valueOf(carId));
if (carDriver.getDriId() != null) {
driver = driverService.getById(carDriver.getDriId());
}
}
return driver;
}
/**
* @param clientModel
* @param distance
* @param msg
*/
public void getAlerts(ClientModel clientModel, int distance, String msg) {
try {
if (clientModel != null && clientModel.getDriverDistanceMin() != null
&& distance < clientModel.getDriverDistanceMin()) {
if (clientModel.getCreatedBy() != null) {
Notification notification = notificationService.saveAlertSchedulerNotification(msg,
clientModel.getTanentID());
User user = userService.getUserByUsername(clientModel.getUpdatedBy());
List<User> userList = userService.listOfUserByIdAndTanentID(true, clientModel.getTanentID());
if (user != null) {
if (distance == 45) {
if (user.getContactNo() != null) {
SMSSend.sendSms(Long.valueOf("" + user.getContactNo()), msg);
}
if (clientModel.getDriver() != null && clientModel.getDriver().getContactNo() != null) {
SMSSend.sendSms(Long.valueOf(clientModel.getDriver().getContactNo()), msg);
}
}
}
if (userList != null && userList.size() > 0) {
if (distance == 45) {
if (userList.get(0).getContactNo() != null) {
SMSSend.sendSms(Long.valueOf("" + userList.get(0).getContactNo()), msg);
}
}
if (userList.get(0).getUsername() != null && !userList.get(0).getUsername().equals("")) {
simpMessagingTemplate.convertAndSendToUser(userList.get(0).getUsername(), "/queue/notify",
notification);
}
}
if (user != null && user.getUsername() != null) {
simpMessagingTemplate.convertAndSendToUser(user.getUsername(), "/queue/notify", notification);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param clientModel
* @return
*/
public String getMessageForTripAlert(ClientModel clientModel) {
String msg = "";
msg = "Driver is beyond the reach of upcoming trip.";
msg += "<br>Trip : " + clientModel.getTripId() + ".";
msg += "<br>Car No : " + clientModel.getCar().getCarNo() + ".";
msg += "<br>Driver Name : " + clientModel.getDriver().getFullName() + ".";
msg += "<br>Driver Contact Number : " + clientModel.getDriver().getContactNo() + ".";
msg += "<br>Pick Up Location : " + clientModel.getPickUpLocation() + ".";
msg += "<br>Please Contact to Driver or change the driver.";
msg += "<br><a style='color:red;' href='" + UrlConstants.CHANGE_REQUEST
+ "'>Click On Link to Change Request Page</a>";
return msg;
}
/**
* @param date1
* @param date2
* @param timeUnit
* @return
*/
public long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
return timeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS);
}
} | 46,178 | 0.722195 | 0.713144 | 1,144 | 39.468533 | 31.864426 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.874126 | false | false | 14 |
64d60232fb16f4ce4f375aab4a5032e1e510e852 | 8,014,408,995,015 | 52184d4dd2f072b6c680d67d496e0fb02f58f9b8 | /src/org/usfirst/frc/team1747/robot/CyborgController.java | 9f32cd5cb4048ce2af74c91b5c7620f03b64eeb0 | [] | no_license | frc1747/Robot2015 | https://github.com/frc1747/Robot2015 | 911d926c768284849dae68938ba434a762e75583 | 35899369fefee02ed35f1e946e23a17a3ed48b06 | refs/heads/master | 2021-01-15T13:43:13.225000 | 2016-01-14T00:27:15 | 2016-01-14T00:27:15 | 29,637,073 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.usfirst.frc.team1747.robot;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class CyborgController extends Cyborg{
private static final int LEFT_JOY_HORIZ_AXIS = 0;
private static final int LEFT_JOY_VERT_AXIS = 1;
private static final int TRIGGER_AXIS = 2;
private static final int RIGHT_JOY_HORIZ_AXIS = 3;
private static final int RIGHT_JOY_VERT_AXIS = 4;
private static final int JOY_X_BUTTON = 1;
private static final int JOY_A_BUTTON = 2;
private static final int JOY_B_BUTTON = 3;
private static final int JOY_Y_BUTTON = 4;
JoystickButton buttonA, buttonB, buttonX, buttonY;
public CyborgController(int portNum) {
super(portNum);
buttonX = new JoystickButton(controller, JOY_X_BUTTON);
buttonY = new JoystickButton(controller, JOY_Y_BUTTON);
buttonA = new JoystickButton(controller, JOY_A_BUTTON);
buttonB = new JoystickButton(controller, JOY_B_BUTTON);
}
public JoystickButton getButtonOne() {
return buttonX;
}
public JoystickButton getButtonTwo() {
return buttonA;
}
public JoystickButton getButtonThree() {
return buttonB;
}
public JoystickButton getButtonFour() {
return buttonY;
}
public double getLeftVert() {
return -controller.getRawAxis(LEFT_JOY_VERT_AXIS);
}
public double getLeftHoriz() {
return controller.getRawAxis(LEFT_JOY_HORIZ_AXIS);
}
public double getRightVert() {
return -controller.getRawAxis(RIGHT_JOY_VERT_AXIS);
}
public double getRightHoriz() {
return controller.getRawAxis(RIGHT_JOY_HORIZ_AXIS);
}
public double getTriggerAxis(){
return -controller.getRawAxis(TRIGGER_AXIS);
}
public void logToSmartDashboard(){
super.logToSmartDashboard();
SmartDashboard.putBoolean("Button One",buttonX.get());
SmartDashboard.putBoolean("Button Two",buttonA.get());
SmartDashboard.putBoolean("Button Three",buttonB.get());
SmartDashboard.putBoolean("Button Four",buttonY.get());
SmartDashboard.putNumber("Left Joystick X", getLeftHoriz());
SmartDashboard.putNumber("Left Joystick Y", getLeftVert());
SmartDashboard.putNumber("Right Joystick X", getRightHoriz());
SmartDashboard.putNumber("Right Joystick Y", getRightVert());
SmartDashboard.putNumber("Trigger Axis", getTriggerAxis());
}
} | UTF-8 | Java | 2,289 | java | CyborgController.java | Java | [] | null | [] | package org.usfirst.frc.team1747.robot;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class CyborgController extends Cyborg{
private static final int LEFT_JOY_HORIZ_AXIS = 0;
private static final int LEFT_JOY_VERT_AXIS = 1;
private static final int TRIGGER_AXIS = 2;
private static final int RIGHT_JOY_HORIZ_AXIS = 3;
private static final int RIGHT_JOY_VERT_AXIS = 4;
private static final int JOY_X_BUTTON = 1;
private static final int JOY_A_BUTTON = 2;
private static final int JOY_B_BUTTON = 3;
private static final int JOY_Y_BUTTON = 4;
JoystickButton buttonA, buttonB, buttonX, buttonY;
public CyborgController(int portNum) {
super(portNum);
buttonX = new JoystickButton(controller, JOY_X_BUTTON);
buttonY = new JoystickButton(controller, JOY_Y_BUTTON);
buttonA = new JoystickButton(controller, JOY_A_BUTTON);
buttonB = new JoystickButton(controller, JOY_B_BUTTON);
}
public JoystickButton getButtonOne() {
return buttonX;
}
public JoystickButton getButtonTwo() {
return buttonA;
}
public JoystickButton getButtonThree() {
return buttonB;
}
public JoystickButton getButtonFour() {
return buttonY;
}
public double getLeftVert() {
return -controller.getRawAxis(LEFT_JOY_VERT_AXIS);
}
public double getLeftHoriz() {
return controller.getRawAxis(LEFT_JOY_HORIZ_AXIS);
}
public double getRightVert() {
return -controller.getRawAxis(RIGHT_JOY_VERT_AXIS);
}
public double getRightHoriz() {
return controller.getRawAxis(RIGHT_JOY_HORIZ_AXIS);
}
public double getTriggerAxis(){
return -controller.getRawAxis(TRIGGER_AXIS);
}
public void logToSmartDashboard(){
super.logToSmartDashboard();
SmartDashboard.putBoolean("Button One",buttonX.get());
SmartDashboard.putBoolean("Button Two",buttonA.get());
SmartDashboard.putBoolean("Button Three",buttonB.get());
SmartDashboard.putBoolean("Button Four",buttonY.get());
SmartDashboard.putNumber("Left Joystick X", getLeftHoriz());
SmartDashboard.putNumber("Left Joystick Y", getLeftVert());
SmartDashboard.putNumber("Right Joystick X", getRightHoriz());
SmartDashboard.putNumber("Right Joystick Y", getRightVert());
SmartDashboard.putNumber("Trigger Axis", getTriggerAxis());
}
} | 2,289 | 0.753604 | 0.747925 | 79 | 27.987341 | 23.70787 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.696203 | false | false | 14 |
2c1ea71b2c119adcb2c4816c82bd9f24a5853c00 | 32,409,823,217,468 | 226a1c2f4e40489ec8a154e4104c77fc20b48d2c | /dali/src/com/credit/CreditPublicity/dao/SGSEntityDao.java | dc4a7793abffd737c6e8d88c2b7ae0bf9e32a28a | [] | no_license | ysy183beauty/zx_mh | https://github.com/ysy183beauty/zx_mh | 582dd768df84bb9d5f5e9c916613764fb1918e71 | c4c84b41c40d8df787ea50a33b32022eb00f59d6 | refs/heads/master | 2023-02-12T02:47:25.547000 | 2020-12-22T13:23:04 | 2020-12-22T13:23:04 | 323,548,615 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.credit.CreditPublicity.dao;
import com.credit.CreditPublicity.entity.QzqdEntity;
import com.credit.CreditPublicity.entity.SGSEntity;
import com.npt.bridge.base.NptBaseDao;
import java.util.List;
/**
* 项目: 〔大理〕征信
* 作者: jiaoss
* 日期: 2018年3月20日16:08:45
* 备注:
*/
public interface SGSEntityDao extends NptBaseDao<SGSEntity, Long> {
List getCountGroupByDataType(String type);
List getCountGroupBySection();
}
| UTF-8 | Java | 465 | java | SGSEntityDao.java | Java | [
{
"context": "\n\nimport java.util.List;\n\n/**\n * 项目: 〔大理〕征信\n * 作者: jiaoss\n * 日期: 2018年3月20日16:08:45\n * 备注:\n */\npublic inter",
"end": 241,
"score": 0.9996369481086731,
"start": 235,
"tag": "USERNAME",
"value": "jiaoss"
}
] | null | [] | package com.credit.CreditPublicity.dao;
import com.credit.CreditPublicity.entity.QzqdEntity;
import com.credit.CreditPublicity.entity.SGSEntity;
import com.npt.bridge.base.NptBaseDao;
import java.util.List;
/**
* 项目: 〔大理〕征信
* 作者: jiaoss
* 日期: 2018年3月20日16:08:45
* 备注:
*/
public interface SGSEntityDao extends NptBaseDao<SGSEntity, Long> {
List getCountGroupByDataType(String type);
List getCountGroupBySection();
}
| 465 | 0.763341 | 0.733179 | 18 | 22.944445 | 21.15675 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 14 |
8be9e5fc4eb859b49b1c8dac638f3f04db151b6b | 2,310,692,445,650 | c056fcb7427fc06eb2168412f48187405f10e34b | /aisinoprotocolutils/src/main/java/com/aisino/protocol/bean/REQUEST_KBFPMB.java | 959772cf3f51c1eb9dc2366d54f153906dc6960e | [] | no_license | wwx441476/aisino | https://github.com/wwx441476/aisino | b1fd3c6d56a047faed8f5ba7c0473a0416e138c5 | 69a3c10ef104e9550d3b8811dfe16ca14f230621 | refs/heads/master | 2020-08-01T17:42:03.768000 | 2019-09-26T10:34:35 | 2019-09-26T10:34:35 | 211,063,889 | 0 | 1 | null | false | 2021-01-21T00:26:05 | 2019-09-26T10:34:06 | 2019-09-26T10:34:58 | 2021-01-21T00:26:03 | 3,028 | 0 | 1 | 48 | Java | false | false | package com.aisino.protocol.bean;
public class REQUEST_KBFPMB implements REQUEST_BEAN {
private String DSPTBM;
public String getDSPTBM() {
return DSPTBM;
}
public void setDSPTBM(String dSPTBM) {
DSPTBM = dSPTBM;
}
}
| UTF-8 | Java | 228 | java | REQUEST_KBFPMB.java | Java | [] | null | [] | package com.aisino.protocol.bean;
public class REQUEST_KBFPMB implements REQUEST_BEAN {
private String DSPTBM;
public String getDSPTBM() {
return DSPTBM;
}
public void setDSPTBM(String dSPTBM) {
DSPTBM = dSPTBM;
}
}
| 228 | 0.736842 | 0.736842 | 13 | 16.538462 | 17.018612 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 14 |
e77385f423be8802e79a740b0213662d59d89295 | 13,125,420,115,978 | 328970ce1df915b3021359267f2fbe653359fc37 | /Leetcode/problems/Array/888_FairCandySwap_1.java | 9624325e3335db24b1b8284a0c19025ba54b850b | [] | no_license | baiyue12138/leetcode | https://github.com/baiyue12138/leetcode | 997f060115874eb37035c470b7c375948af4ce67 | 8e0f96eeb07f20d94eb5000baaad67228b6a5a36 | refs/heads/master | 2020-06-21T00:30:37.275000 | 2019-07-17T02:46:31 | 2019-07-17T02:46:31 | 190,007,358 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Solution {
public int[] fairCandySwap(int[] A, int[] B) {
int[]C=new int[2];
int sumA=0;
int sumB=0;
int sizeA=A.length;
int sizeB=B.length;
for(int i=0;i<sizeA;i++){
sumA+=A[i];
}
for(int i=0;i<sizeB;i++){
sumB+=B[i];
}
int d=(sumA-sumB)/2;
for(int i=0;i<sizeA;i++){
for(int j=0;j<sizeB;j++){
if((A[i]-B[j])==d)
{
C[0]=A[i];
C[1]=B[j];
return C;
}
}
}
return null;
}
} | UTF-8 | Java | 674 | java | 888_FairCandySwap_1.java | Java | [] | null | [] | class Solution {
public int[] fairCandySwap(int[] A, int[] B) {
int[]C=new int[2];
int sumA=0;
int sumB=0;
int sizeA=A.length;
int sizeB=B.length;
for(int i=0;i<sizeA;i++){
sumA+=A[i];
}
for(int i=0;i<sizeB;i++){
sumB+=B[i];
}
int d=(sumA-sumB)/2;
for(int i=0;i<sizeA;i++){
for(int j=0;j<sizeB;j++){
if((A[i]-B[j])==d)
{
C[0]=A[i];
C[1]=B[j];
return C;
}
}
}
return null;
}
} | 674 | 0.321958 | 0.307122 | 27 | 23.037037 | 10.884857 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 14 |
b85de112a6c6e211293d7325e7d07dd9ca6677ef | 4,492,535,827,593 | 2e58ec96755618d1a8605191bc866d58d5e479df | /locationweb1/src/main/java/com/psa/locationweb1/repositories/LocationRepository.java | 486b6f4c8ec87a6e27cab501f3500f133b15d06d | [] | no_license | Pradeep1003/SpringBoot-Project | https://github.com/Pradeep1003/SpringBoot-Project | 5316ec55184145293b7988ad36342db294c8b364 | 6b25ac07f89df213a869136b413eb6e65b67e8f5 | refs/heads/master | 2022-11-24T19:54:14.107000 | 2020-07-23T09:58:21 | 2020-07-23T09:58:21 | 281,914,703 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.psa.locationweb1.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import com.psa.locationweb1.entities.Location;
public interface LocationRepository extends JpaRepository<Location, Integer> {
}
| UTF-8 | Java | 296 | java | LocationRepository.java | Java | [] | null | [] | package com.psa.locationweb1.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import com.psa.locationweb1.entities.Location;
public interface LocationRepository extends JpaRepository<Location, Integer> {
}
| 296 | 0.847973 | 0.841216 | 10 | 28.6 | 29.783216 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 14 |
e465ec2ba6e6b6c36a45e3b6756db13b43292243 | 16,312,285,818,136 | 9fa378791170e904a10d1a70b4484b5dd6fa4813 | /app/src/main/java/com/qgfun/go/entity/Category.java | c5290271fef61f022680c276fa9edecc9d5d23ba | [] | no_license | colaly/Go | https://github.com/colaly/Go | 213f6863a2f4fdb00d59c219eac9187d8c6e1dc3 | f5d288f3b105dc50bdf96deb99d881d08419a4ef | refs/heads/master | 2023-02-15T16:08:20.336000 | 2021-01-11T08:02:12 | 2021-01-11T08:02:12 | 327,781,555 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.qgfun.go.entity;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @author LLY
* date: 2020/4/18 10:39
* package name: com.qgfun.go.entity
*/
public class Category implements Parcelable {
private String category;
private String remark;
private String id;
public Category(String category, String id) {
this.category = category;
this.id = id;
}
public Category(String category, String id,String remark) {
this.category = category;
this.id = id;
this.remark = remark;
}
public String getCategory() {
return category;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public void setCategory(String category) {
this.category = category;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.category);
dest.writeString(this.remark);
dest.writeString(this.id);
}
protected Category(Parcel in) {
this.category = in.readString();
this.remark = in.readString();
this.id = in.readString();
}
public static final Creator<Category> CREATOR = new Creator<Category>() {
@Override
public Category createFromParcel(Parcel source) {
return new Category(source);
}
@Override
public Category[] newArray(int size) {
return new Category[size];
}
};
}
| UTF-8 | Java | 1,738 | java | Category.java | Java | [
{
"context": "cel;\nimport android.os.Parcelable;\n\n/**\n * @author LLY\n * date: 2020/4/18 10:39\n * package name: com.qgf",
"end": 105,
"score": 0.9992027282714844,
"start": 102,
"tag": "USERNAME",
"value": "LLY"
}
] | null | [] | package com.qgfun.go.entity;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @author LLY
* date: 2020/4/18 10:39
* package name: com.qgfun.go.entity
*/
public class Category implements Parcelable {
private String category;
private String remark;
private String id;
public Category(String category, String id) {
this.category = category;
this.id = id;
}
public Category(String category, String id,String remark) {
this.category = category;
this.id = id;
this.remark = remark;
}
public String getCategory() {
return category;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public void setCategory(String category) {
this.category = category;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.category);
dest.writeString(this.remark);
dest.writeString(this.id);
}
protected Category(Parcel in) {
this.category = in.readString();
this.remark = in.readString();
this.id = in.readString();
}
public static final Creator<Category> CREATOR = new Creator<Category>() {
@Override
public Category createFromParcel(Parcel source) {
return new Category(source);
}
@Override
public Category[] newArray(int size) {
return new Category[size];
}
};
}
| 1,738 | 0.596663 | 0.589758 | 81 | 20.456791 | 17.995918 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.382716 | false | false | 14 |
8544995aacecb4cd37c8775fdfe129e2a6cebcf7 | 15,573,551,464,314 | 73ea1876a54d5abe90af65d948c4d79641330c9d | /src/test/java/net/bndy/wf/test/UtilsTest.java | 9f2e3d4c0f4a43ed0129261fd04c4d5e7086c21f | [
"MIT"
] | permissive | limingxu/web-framework-for-java | https://github.com/limingxu/web-framework-for-java | 55f9f54e9abf7ca4c7278bce8bf997064cb1581c | 7af055b8fd35d65d4e0992c009241ff0e66a75bf | refs/heads/master | 2021-08-26T09:44:46.519000 | 2017-11-23T02:54:31 | 2017-11-23T02:54:31 | 111,752,945 | 0 | 1 | null | true | 2017-11-23T02:17:02 | 2017-11-23T02:17:01 | 2017-11-21T01:17:05 | 2017-11-21T13:12:05 | 11,447 | 0 | 0 | 0 | null | false | null | package net.bndy.wf.test;
import org.junit.Assert;
import org.junit.Test;
import net.bndy.wf.lib.StringHelper;
import net.bndy.wf.lib.HttpHelper;
public class UtilsTest extends _Test {
@Test
public void generateRandomString() {
System.out.println(StringHelper.generateRandomString(11));
System.out.println(StringHelper.generateUUID());
Assert.assertEquals(StringHelper.generateRandomString(10).length(), 10);
}
@Test
public void httpGet() throws Exception {
String s = HttpHelper.requestGet("http://www.hashcollision.org/hkn/python/idle_intro/index.html");
System.out.println(s);
Assert.assertTrue(s.indexOf("<!DOCTYPE") == 0);
}
@Test
public void httpPost() throws Exception {
// TODO
}
}
| UTF-8 | Java | 722 | java | UtilsTest.java | Java | [] | null | [] | package net.bndy.wf.test;
import org.junit.Assert;
import org.junit.Test;
import net.bndy.wf.lib.StringHelper;
import net.bndy.wf.lib.HttpHelper;
public class UtilsTest extends _Test {
@Test
public void generateRandomString() {
System.out.println(StringHelper.generateRandomString(11));
System.out.println(StringHelper.generateUUID());
Assert.assertEquals(StringHelper.generateRandomString(10).length(), 10);
}
@Test
public void httpGet() throws Exception {
String s = HttpHelper.requestGet("http://www.hashcollision.org/hkn/python/idle_intro/index.html");
System.out.println(s);
Assert.assertTrue(s.indexOf("<!DOCTYPE") == 0);
}
@Test
public void httpPost() throws Exception {
// TODO
}
}
| 722 | 0.739612 | 0.729917 | 29 | 23.896551 | 25.32049 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.310345 | false | false | 14 |
85d693072618b12c57aaa3de8ce87f828ee3b17e | 16,363,825,453,058 | f87a15b7b357236e311e37bf571b94c0f38f1f9a | /src/main/java/com/openclinica/ui/repository/AuthorizationRepository.java | 40d75ae038be9d8946aa5c4d87c03715614ab2d5 | [] | no_license | kkrumlian/jhipster-app | https://github.com/kkrumlian/jhipster-app | 332f7d4bdc8b31ab9601a2c316bb1ded2c5a8260 | c9293a7ad47a0b30885fe28fd4808d9f76025938 | refs/heads/master | 2021-01-21T22:34:30.849000 | 2014-10-21T02:23:46 | 2014-10-21T02:23:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.openclinica.ui.repository;
import com.openclinica.ui.domain.Authorization;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* Spring Data JPA repository for the Authorization entity.
*/
public interface AuthorizationRepository extends JpaRepository<Authorization, Long> {
List<Authorization> findByStudyStudyOidAndStudyInstanceUrlIgnoreCase(String studyOid,String instanceUrl);
}
| UTF-8 | Java | 451 | java | AuthorizationRepository.java | Java | [] | null | [] | package com.openclinica.ui.repository;
import com.openclinica.ui.domain.Authorization;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* Spring Data JPA repository for the Authorization entity.
*/
public interface AuthorizationRepository extends JpaRepository<Authorization, Long> {
List<Authorization> findByStudyStudyOidAndStudyInstanceUrlIgnoreCase(String studyOid,String instanceUrl);
}
| 451 | 0.809313 | 0.809313 | 15 | 29.066668 | 35.431561 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 14 |
23359a7582126b52b1aa9f8bfcc80d7fb7c37226 | 27,711,129,032,625 | b1f7606b96bb3becb12e693eb8ab8eeb6da6a2ad | /ExemploRectangulo1/src/exemplorectangulo1/ExemploRectangulo1.java | 30fa341dafbe65a1364a5472e62075ce7fb324a8 | [] | no_license | agarridogarcia123/ExemploObxetos | https://github.com/agarridogarcia123/ExemploObxetos | e4a29a77d33dddf12fa9f2322d0a3e298f06d24c | ea505ce8d1638bb4fd10903e58f27ea9ff11f0d4 | refs/heads/master | 2021-01-10T23:48:29.420000 | 2016-10-13T10:12:07 | 2016-10-13T10:12:07 | 70,794,396 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package exemplorectangulo1;
import javax.swing.JOptionPane;
public class ExemploRectangulo1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Rectangulo rec1= new Rectangulo(5f,10f);
rec1.amosar();
rec1.setAltura(7f);
rec1.amosar();
Rectangulo rec2= new Rectangulo();
rec2.setBase(14.2f);
rec2.setAltura(6.9f);
rec2.amosar();
rec1.calcularArea();
/*float res =rec1.calculaPerimetro();
System.out.println("perimetro = " +res);*/
System.out.println("perimetro = " + rec1.calculaPerimetro());
Rectangulo rec3= new Rectangulo ();
rec3.setBase(20f);
rec3.setAltura(10f);
rec3.amosar();
rec3.calcularArea();
System.out.println( "perimetro = " + rec3.calculaPerimetro());
Rectangulo rec4= new Rectangulo();
rec4.introducirValores();
rec4.calcularArea();
System.out.println("perimetro = " + rec4.calculaPerimetro());
}
}
| UTF-8 | Java | 1,151 | java | ExemploRectangulo1.java | Java | [] | null | [] |
package exemplorectangulo1;
import javax.swing.JOptionPane;
public class ExemploRectangulo1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Rectangulo rec1= new Rectangulo(5f,10f);
rec1.amosar();
rec1.setAltura(7f);
rec1.amosar();
Rectangulo rec2= new Rectangulo();
rec2.setBase(14.2f);
rec2.setAltura(6.9f);
rec2.amosar();
rec1.calcularArea();
/*float res =rec1.calculaPerimetro();
System.out.println("perimetro = " +res);*/
System.out.println("perimetro = " + rec1.calculaPerimetro());
Rectangulo rec3= new Rectangulo ();
rec3.setBase(20f);
rec3.setAltura(10f);
rec3.amosar();
rec3.calcularArea();
System.out.println( "perimetro = " + rec3.calculaPerimetro());
Rectangulo rec4= new Rectangulo();
rec4.introducirValores();
rec4.calcularArea();
System.out.println("perimetro = " + rec4.calculaPerimetro());
}
}
| 1,151 | 0.549088 | 0.517811 | 45 | 24.555555 | 19.051456 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 14 |
7884b923c7110f0c2f65ac8cabd8cc074f7e2686 | 1,408,749,318,914 | 4e912dfcace17225686c916667fb7cbb993e9196 | /app/src/main/java/com/example/hitman1337x/journalapp/database/DiaryEntry.java | a72fe2d9b09859cafcca6e4558b3571df3775f47 | [] | no_license | NicholasTurner23/Journal-App | https://github.com/NicholasTurner23/Journal-App | 0a2e18e43ff93dcc09c5e48e586636b634f03a25 | c0a52a9a0ba5d1f402d28911210b30859b487873 | refs/heads/master | 2021-09-17T11:38:51.886000 | 2018-07-01T20:57:35 | 2018-07-01T20:57:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.hitman1337x.journalapp.database;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Date;
import java.util.function.ToDoubleBiFunction;
@Entity(tableName = "diary")
public class DiaryEntry {
@PrimaryKey(autoGenerate = true)
private int id;
private String title, description;
private Date createdOn;
@Ignore
public DiaryEntry (String title, String description, Date createdOn)
{
this.title = title;
this.description = description;
this.createdOn = createdOn;
}
public DiaryEntry (int id, String title, String description, Date createdOn)
{
this.title = title;
this.description = description;
this.createdOn = createdOn;
}
public void setId(int id) { this.id = id;}
public int getId(){return id;}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
} | UTF-8 | Java | 1,529 | java | DiaryEntry.java | Java | [
{
"context": "package com.example.hitman1337x.journalapp.database;\n\nimport android.arch.persist",
"end": 31,
"score": 0.9976083636283875,
"start": 20,
"tag": "USERNAME",
"value": "hitman1337x"
}
] | null | [] | package com.example.hitman1337x.journalapp.database;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Date;
import java.util.function.ToDoubleBiFunction;
@Entity(tableName = "diary")
public class DiaryEntry {
@PrimaryKey(autoGenerate = true)
private int id;
private String title, description;
private Date createdOn;
@Ignore
public DiaryEntry (String title, String description, Date createdOn)
{
this.title = title;
this.description = description;
this.createdOn = createdOn;
}
public DiaryEntry (int id, String title, String description, Date createdOn)
{
this.title = title;
this.description = description;
this.createdOn = createdOn;
}
public void setId(int id) { this.id = id;}
public int getId(){return id;}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
} | 1,529 | 0.678875 | 0.675605 | 67 | 21.835821 | 19.806976 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.492537 | false | false | 14 |
2809d9eeec2ff15d74a5effd42542a6f31954f31 | 5,463,198,440,946 | b27fda3c6a74adf5eab2ac043f641991a2a3668f | /DBProjSecurityClient/src/com/jeeihyun/client/handle/KeyGenerator.java | 0294e0e4887cdb79bd886865c9496aabd339a447 | [] | no_license | elis0m/DBSecurityProj | https://github.com/elis0m/DBSecurityProj | 7dac3373af21eaef9b5de79b946164093c61ce0d | 7ec1677de4a9d4d30efefc630f2277e2740762d2 | refs/heads/master | 2022-12-18T13:26:30.864000 | 2020-09-25T15:14:15 | 2020-09-25T15:14:15 | 298,605,138 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jeeihyun.client.handle;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;
import com.jeeihyun.client.security.AES;
import com.jeeihyun.client.security.SHA256;
import com.jeeihyun.client.utils.kMap;
public class KeyGenerator {
public static ArrayList make(){
Random ran = new Random();
AES aes = new AES();
SHA256 sha256 = new SHA256();
FileHandler fl = new FileHandler();
ArrayList<ArrayList<String>> containvector;
kMap[][] keyMap = new kMap[128][128];
for(int i = 0; i < 128; i++){
for(int j = 0; j < 128; j++) {
keyMap[i][j] = new kMap();
}
}
// key generate
String Keys = makeRandomHex(20);
String Keyt = makeRandomHex(20);
System.out.println("Key generation result : Random HEXcode KeyS and KeyT are created successfully !");
containvector = fl.getList();
ArrayList<Integer> al;
ArrayList<ArrayList> x = new ArrayList<>();
for(int i = 0; i < 128; i++){
x.add(new ArrayList<Integer>());
}
for(int i = 0; i < 128; i++){
al = x.get(i);
for(int j = 0; j < 128; j++) {
al.add(j + 1);
}
}
for(int i = 0; i < containvector.size(); i++){
ArrayList<String> contain = containvector.get(i);
String Keye = aes.Function(contain.get(0),Keys);
String stag = aes.Function(contain.get(0),Keyt);
for(int j = 0; j < contain.size() - 1; j++){
String msg = contain.get(j+1);
contain.set(j+1,aes.encryptAES(msg,Keye));
BigInteger blk = new BigInteger(sha256.SHA256Encryption(aes.Functionbar(stag,Integer.toString(j+1))),16);
String blkbin = blk.toString(2);
String b = blkbin.substring(0,7);
String l = blkbin.substring(7,87);
String k = blkbin.substring(87,216);
int bint = Integer.parseInt(b,2);
ArrayList<Integer> y = x.get(bint);
int random;
int num;
while(true) {
random = ran.nextInt(128);
num = y.get(random);
if (!(num==1000)) break;
}
y.set(random,1000);
keyMap[bint][num-1].setLabel(l);
BigInteger one = new BigInteger(contain.get(j+1),16);
BigInteger bik = new BigInteger(k,2);
if(j==contain.size()-2){
one = one.xor(bik);
keyMap[bint][num-1].setValue(one.toString(2));
}else{
String tmp = one.toString(2);
while(tmp.length()<128){
tmp="0"+tmp;
}
BigInteger two = new BigInteger("1"+tmp,2);
two = two.xor(bik);
keyMap[bint][num-1].setValue(two.toString(2));
}
}
}
fl.saveKey(Keyt,1);
fl.saveKey(Keys,0);
ArrayList<String> list = new ArrayList<>();
for(int i = 0; i < 128; i++){
for(int j = 0; j < 128; j++) {
if (!keyMap[i][j].getLabel().equals("")){
String b = Integer.toHexString(i);
if(i<16) b="0"+b;
String c = Integer.toHexString(j);
if(j<16) c="0"+c;
String a = "%"+b+"%"+c+"%"+keyMap[i][j].getLabel()+"%"+keyMap[i][j].getValue();
list.add(a);
}
}
}
return list;
}
private static String makeRandomHex(int numchars){
Random r = new Random();
StringBuffer sb = new StringBuffer();
while(sb.length() < numchars){
sb.append(Integer.toHexString(r.nextInt()));
}
return sb.toString().substring(0, numchars);
}
}
| UTF-8 | Java | 4,170 | java | KeyGenerator.java | Java | [] | null | [] | package com.jeeihyun.client.handle;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;
import com.jeeihyun.client.security.AES;
import com.jeeihyun.client.security.SHA256;
import com.jeeihyun.client.utils.kMap;
public class KeyGenerator {
public static ArrayList make(){
Random ran = new Random();
AES aes = new AES();
SHA256 sha256 = new SHA256();
FileHandler fl = new FileHandler();
ArrayList<ArrayList<String>> containvector;
kMap[][] keyMap = new kMap[128][128];
for(int i = 0; i < 128; i++){
for(int j = 0; j < 128; j++) {
keyMap[i][j] = new kMap();
}
}
// key generate
String Keys = makeRandomHex(20);
String Keyt = makeRandomHex(20);
System.out.println("Key generation result : Random HEXcode KeyS and KeyT are created successfully !");
containvector = fl.getList();
ArrayList<Integer> al;
ArrayList<ArrayList> x = new ArrayList<>();
for(int i = 0; i < 128; i++){
x.add(new ArrayList<Integer>());
}
for(int i = 0; i < 128; i++){
al = x.get(i);
for(int j = 0; j < 128; j++) {
al.add(j + 1);
}
}
for(int i = 0; i < containvector.size(); i++){
ArrayList<String> contain = containvector.get(i);
String Keye = aes.Function(contain.get(0),Keys);
String stag = aes.Function(contain.get(0),Keyt);
for(int j = 0; j < contain.size() - 1; j++){
String msg = contain.get(j+1);
contain.set(j+1,aes.encryptAES(msg,Keye));
BigInteger blk = new BigInteger(sha256.SHA256Encryption(aes.Functionbar(stag,Integer.toString(j+1))),16);
String blkbin = blk.toString(2);
String b = blkbin.substring(0,7);
String l = blkbin.substring(7,87);
String k = blkbin.substring(87,216);
int bint = Integer.parseInt(b,2);
ArrayList<Integer> y = x.get(bint);
int random;
int num;
while(true) {
random = ran.nextInt(128);
num = y.get(random);
if (!(num==1000)) break;
}
y.set(random,1000);
keyMap[bint][num-1].setLabel(l);
BigInteger one = new BigInteger(contain.get(j+1),16);
BigInteger bik = new BigInteger(k,2);
if(j==contain.size()-2){
one = one.xor(bik);
keyMap[bint][num-1].setValue(one.toString(2));
}else{
String tmp = one.toString(2);
while(tmp.length()<128){
tmp="0"+tmp;
}
BigInteger two = new BigInteger("1"+tmp,2);
two = two.xor(bik);
keyMap[bint][num-1].setValue(two.toString(2));
}
}
}
fl.saveKey(Keyt,1);
fl.saveKey(Keys,0);
ArrayList<String> list = new ArrayList<>();
for(int i = 0; i < 128; i++){
for(int j = 0; j < 128; j++) {
if (!keyMap[i][j].getLabel().equals("")){
String b = Integer.toHexString(i);
if(i<16) b="0"+b;
String c = Integer.toHexString(j);
if(j<16) c="0"+c;
String a = "%"+b+"%"+c+"%"+keyMap[i][j].getLabel()+"%"+keyMap[i][j].getValue();
list.add(a);
}
}
}
return list;
}
private static String makeRandomHex(int numchars){
Random r = new Random();
StringBuffer sb = new StringBuffer();
while(sb.length() < numchars){
sb.append(Integer.toHexString(r.nextInt()));
}
return sb.toString().substring(0, numchars);
}
}
| 4,170 | 0.469544 | 0.441727 | 128 | 31.578125 | 22.865643 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8125 | false | false | 14 |
3e985069ad847e62188cd5067049fe8c0077410d | 12,884,901,940,628 | 1fcb375ec7fd5f6a721cc19faa43f55fa5dcb1a6 | /src/com/github/nikbenson/roleplaybot/modules/player/PlayerModule.java | ddc0c1af67ee51bfe274024a1e59ea672728d83b | [] | no_license | NikBenson/RoleplayBot-modules-Player | https://github.com/NikBenson/RoleplayBot-modules-Player | ba06a7309b273c867506255c131c19abceb06065 | 1d018cfca0717dc89e9add5e95a2c6503d5e285c | refs/heads/main | 2023-02-21T17:08:30.046000 | 2021-01-23T10:51:25 | 2021-01-23T10:51:25 | 330,474,507 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.nikbenson.roleplaybot.modules.player;
import com.github.nikbenson.roleplaybot.configurations.ConfigurationManager;
import com.github.nikbenson.roleplaybot.modules.RoleplayBotModule;
import net.dv8tion.jda.api.entities.Guild;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class PlayerModule implements RoleplayBotModule {
public static void main(String[] args) {
System.out.println("Please place in RoleplayBot's modules folder!!!");
System.exit(0);
}
private Map<Guild, PlayerManager> managers = new HashMap<>();
public PlayerManager getPlayerManager(Guild guild) {
return managers.get(guild);
}
@Override
public boolean isActive(Guild guild) {
return managers.containsKey(guild);
}
@Override
public void load(Guild guild) {
if(!managers.containsKey(guild)) {
PlayerManager playerManager = new PlayerManager(guild);
ConfigurationManager configurationManager = ConfigurationManager.getInstance();
configurationManager.registerConfiguration(playerManager);
try {
configurationManager.load(playerManager);
} catch (Exception ignored) {}
managers.put(guild, playerManager);
}
}
@Override
public void unload(Guild guild) {
if(managers.containsKey(guild)) {
try {
ConfigurationManager.getInstance().save(managers.get(guild));
} catch (IOException e) {
System.out.printf("Could not save Players for %s%n", guild.getId());
}
managers.remove(guild);
}
}
@Override
public Guild[] getLoaded() {
return managers.keySet().toArray(new Guild[0]);
}
}
| UTF-8 | Java | 1,582 | java | PlayerModule.java | Java | [
{
"context": "package com.github.nikbenson.roleplaybot.modules.player;\n\nimport com.github.ni",
"end": 28,
"score": 0.9996457695960999,
"start": 19,
"tag": "USERNAME",
"value": "nikbenson"
},
{
"context": "on.roleplaybot.modules.player;\n\nimport com.github.nikbenson.roleplaybot.con... | null | [] | package com.github.nikbenson.roleplaybot.modules.player;
import com.github.nikbenson.roleplaybot.configurations.ConfigurationManager;
import com.github.nikbenson.roleplaybot.modules.RoleplayBotModule;
import net.dv8tion.jda.api.entities.Guild;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class PlayerModule implements RoleplayBotModule {
public static void main(String[] args) {
System.out.println("Please place in RoleplayBot's modules folder!!!");
System.exit(0);
}
private Map<Guild, PlayerManager> managers = new HashMap<>();
public PlayerManager getPlayerManager(Guild guild) {
return managers.get(guild);
}
@Override
public boolean isActive(Guild guild) {
return managers.containsKey(guild);
}
@Override
public void load(Guild guild) {
if(!managers.containsKey(guild)) {
PlayerManager playerManager = new PlayerManager(guild);
ConfigurationManager configurationManager = ConfigurationManager.getInstance();
configurationManager.registerConfiguration(playerManager);
try {
configurationManager.load(playerManager);
} catch (Exception ignored) {}
managers.put(guild, playerManager);
}
}
@Override
public void unload(Guild guild) {
if(managers.containsKey(guild)) {
try {
ConfigurationManager.getInstance().save(managers.get(guild));
} catch (IOException e) {
System.out.printf("Could not save Players for %s%n", guild.getId());
}
managers.remove(guild);
}
}
@Override
public Guild[] getLoaded() {
return managers.keySet().toArray(new Guild[0]);
}
}
| 1,582 | 0.747788 | 0.745891 | 61 | 24.934425 | 24.741859 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.655738 | false | false | 14 |
8c4f11d768967185aa9bbc2aeff6eebf55ac28ae | 5,746,666,307,324 | 4edce2a17e0c0800cdfeaa4b111e0c2fbea4563b | /net/minecraft/src/MainShutdownHook.java | 95251f415b2bd6ccf3aa8d9bc1ed85eed7369fea | [] | no_license | zaices/minecraft | https://github.com/zaices/minecraft | da9b99abd99ac56e787eef1b6fecbd06b2d4cd51 | 4a99d8295e7ce939663e90ba8f1899c491545cde | refs/heads/master | 2021-01-10T20:20:38.388000 | 2013-10-06T00:16:11 | 2013-10-06T00:18:48 | 13,142,359 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.minecraft.src;
public final class MainShutdownHook extends Thread
{
public void run()
{
Minecraft.stopIntegratedServer();
}
}
| UTF-8 | Java | 159 | java | MainShutdownHook.java | Java | [] | null | [] | package net.minecraft.src;
public final class MainShutdownHook extends Thread
{
public void run()
{
Minecraft.stopIntegratedServer();
}
}
| 159 | 0.685535 | 0.685535 | 9 | 16.666666 | 17.79513 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 14 |
f63cc319163ba212dd29c20c8974adc745e09d35 | 20,521,353,753,157 | 2bd62a0a91451d454d5b130ff91465d35d210646 | /src/main/java/com/kobe/nucleus/web/rest/RetourFournisseurResource.java | 8a697ec128a30fcae428dd4f8bda1ecb7718625a | [] | no_license | kkobena/nucleus | https://github.com/kkobena/nucleus | ce54c036a489da5618e0f3b035761e01387494cb | 62ff795f09cd015b844db53d3e3025cbf3ca39eb | refs/heads/master | 2023-08-14T20:52:52.631000 | 2021-09-29T11:30:42 | 2021-09-29T11:30:42 | 256,178,120 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kobe.nucleus.web.rest;
import com.kobe.nucleus.service.RetourFournisseurService;
import com.kobe.nucleus.web.rest.errors.BadRequestAlertException;
import com.kobe.nucleus.service.dto.RetourFournisseurDTO;
import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing {@link com.kobe.nucleus.domain.RetourFournisseur}.
*/
@RestController
@RequestMapping("/api")
public class RetourFournisseurResource {
private final Logger log = LoggerFactory.getLogger(RetourFournisseurResource.class);
private static final String ENTITY_NAME = "retourFournisseur";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final RetourFournisseurService retourFournisseurService;
public RetourFournisseurResource(RetourFournisseurService retourFournisseurService) {
this.retourFournisseurService = retourFournisseurService;
}
/**
* {@code POST /retour-fournisseurs} : Create a new retourFournisseur.
*
* @param retourFournisseurDTO the retourFournisseurDTO to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new retourFournisseurDTO, or with status {@code 400 (Bad Request)} if the retourFournisseur has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/retour-fournisseurs")
public ResponseEntity<RetourFournisseurDTO> createRetourFournisseur(@Valid @RequestBody RetourFournisseurDTO retourFournisseurDTO) throws URISyntaxException {
log.debug("REST request to save RetourFournisseur : {}", retourFournisseurDTO);
if (retourFournisseurDTO.getId() != null) {
throw new BadRequestAlertException("A new retourFournisseur cannot already have an ID", ENTITY_NAME, "idexists");
}
RetourFournisseurDTO result = retourFournisseurService.save(retourFournisseurDTO);
return ResponseEntity.created(new URI("/api/retour-fournisseurs/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* {@code PUT /retour-fournisseurs} : Updates an existing retourFournisseur.
*
* @param retourFournisseurDTO the retourFournisseurDTO to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated retourFournisseurDTO,
* or with status {@code 400 (Bad Request)} if the retourFournisseurDTO is not valid,
* or with status {@code 500 (Internal Server Error)} if the retourFournisseurDTO couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/retour-fournisseurs")
public ResponseEntity<RetourFournisseurDTO> updateRetourFournisseur(@Valid @RequestBody RetourFournisseurDTO retourFournisseurDTO) throws URISyntaxException {
log.debug("REST request to update RetourFournisseur : {}", retourFournisseurDTO);
if (retourFournisseurDTO.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
RetourFournisseurDTO result = retourFournisseurService.save(retourFournisseurDTO);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, retourFournisseurDTO.getId().toString()))
.body(result);
}
/**
* {@code GET /retour-fournisseurs} : get all the retourFournisseurs.
*
* @param pageable the pagination information.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of retourFournisseurs in body.
*/
@GetMapping("/retour-fournisseurs")
public ResponseEntity<List<RetourFournisseurDTO>> getAllRetourFournisseurs(Pageable pageable) {
log.debug("REST request to get a page of RetourFournisseurs");
Page<RetourFournisseurDTO> page = retourFournisseurService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
* {@code GET /retour-fournisseurs/:id} : get the "id" retourFournisseur.
*
* @param id the id of the retourFournisseurDTO to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the retourFournisseurDTO, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/retour-fournisseurs/{id}")
public ResponseEntity<RetourFournisseurDTO> getRetourFournisseur(@PathVariable Long id) {
log.debug("REST request to get RetourFournisseur : {}", id);
Optional<RetourFournisseurDTO> retourFournisseurDTO = retourFournisseurService.findOne(id);
return ResponseUtil.wrapOrNotFound(retourFournisseurDTO);
}
/**
* {@code DELETE /retour-fournisseurs/:id} : delete the "id" retourFournisseur.
*
* @param id the id of the retourFournisseurDTO to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/retour-fournisseurs/{id}")
public ResponseEntity<Void> deleteRetourFournisseur(@PathVariable Long id) {
log.debug("REST request to delete RetourFournisseur : {}", id);
retourFournisseurService.delete(id);
return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();
}
}
| UTF-8 | Java | 6,322 | java | RetourFournisseurResource.java | Java | [] | null | [] | package com.kobe.nucleus.web.rest;
import com.kobe.nucleus.service.RetourFournisseurService;
import com.kobe.nucleus.web.rest.errors.BadRequestAlertException;
import com.kobe.nucleus.service.dto.RetourFournisseurDTO;
import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing {@link com.kobe.nucleus.domain.RetourFournisseur}.
*/
@RestController
@RequestMapping("/api")
public class RetourFournisseurResource {
private final Logger log = LoggerFactory.getLogger(RetourFournisseurResource.class);
private static final String ENTITY_NAME = "retourFournisseur";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final RetourFournisseurService retourFournisseurService;
public RetourFournisseurResource(RetourFournisseurService retourFournisseurService) {
this.retourFournisseurService = retourFournisseurService;
}
/**
* {@code POST /retour-fournisseurs} : Create a new retourFournisseur.
*
* @param retourFournisseurDTO the retourFournisseurDTO to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new retourFournisseurDTO, or with status {@code 400 (Bad Request)} if the retourFournisseur has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/retour-fournisseurs")
public ResponseEntity<RetourFournisseurDTO> createRetourFournisseur(@Valid @RequestBody RetourFournisseurDTO retourFournisseurDTO) throws URISyntaxException {
log.debug("REST request to save RetourFournisseur : {}", retourFournisseurDTO);
if (retourFournisseurDTO.getId() != null) {
throw new BadRequestAlertException("A new retourFournisseur cannot already have an ID", ENTITY_NAME, "idexists");
}
RetourFournisseurDTO result = retourFournisseurService.save(retourFournisseurDTO);
return ResponseEntity.created(new URI("/api/retour-fournisseurs/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* {@code PUT /retour-fournisseurs} : Updates an existing retourFournisseur.
*
* @param retourFournisseurDTO the retourFournisseurDTO to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated retourFournisseurDTO,
* or with status {@code 400 (Bad Request)} if the retourFournisseurDTO is not valid,
* or with status {@code 500 (Internal Server Error)} if the retourFournisseurDTO couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/retour-fournisseurs")
public ResponseEntity<RetourFournisseurDTO> updateRetourFournisseur(@Valid @RequestBody RetourFournisseurDTO retourFournisseurDTO) throws URISyntaxException {
log.debug("REST request to update RetourFournisseur : {}", retourFournisseurDTO);
if (retourFournisseurDTO.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
RetourFournisseurDTO result = retourFournisseurService.save(retourFournisseurDTO);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, retourFournisseurDTO.getId().toString()))
.body(result);
}
/**
* {@code GET /retour-fournisseurs} : get all the retourFournisseurs.
*
* @param pageable the pagination information.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of retourFournisseurs in body.
*/
@GetMapping("/retour-fournisseurs")
public ResponseEntity<List<RetourFournisseurDTO>> getAllRetourFournisseurs(Pageable pageable) {
log.debug("REST request to get a page of RetourFournisseurs");
Page<RetourFournisseurDTO> page = retourFournisseurService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
* {@code GET /retour-fournisseurs/:id} : get the "id" retourFournisseur.
*
* @param id the id of the retourFournisseurDTO to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the retourFournisseurDTO, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/retour-fournisseurs/{id}")
public ResponseEntity<RetourFournisseurDTO> getRetourFournisseur(@PathVariable Long id) {
log.debug("REST request to get RetourFournisseur : {}", id);
Optional<RetourFournisseurDTO> retourFournisseurDTO = retourFournisseurService.findOne(id);
return ResponseUtil.wrapOrNotFound(retourFournisseurDTO);
}
/**
* {@code DELETE /retour-fournisseurs/:id} : delete the "id" retourFournisseur.
*
* @param id the id of the retourFournisseurDTO to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/retour-fournisseurs/{id}")
public ResponseEntity<Void> deleteRetourFournisseur(@PathVariable Long id) {
log.debug("REST request to delete RetourFournisseur : {}", id);
retourFournisseurService.delete(id);
return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();
}
}
| 6,322 | 0.739956 | 0.735369 | 127 | 48.779526 | 43.012161 | 204 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.527559 | false | false | 14 |
0036b4e7cdc7b68c8345508eb9f1b71ca3941c72 | 25,056,839,237,879 | 5ed6e7df2f65c1bb4c1f031662f99eebbfafcbdf | /Team6/src/kr/co/koo/izone/user/stu_List.java | 6551e7bdb69228f22f204b1064c89e45cff81dfd | [] | no_license | garamv20/azaz | https://github.com/garamv20/azaz | d48d657ed479865597bfd1d590f7e8fdc1e7b168 | 2caaec41a4ed602d357b3d30bdf75b38113870a0 | refs/heads/master | 2023-05-08T23:46:03.729000 | 2021-05-27T09:00:58 | 2021-05-27T09:00:58 | 358,091,942 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kr.co.koo.izone.user;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class stu_List implements stu_Service {
public void execute(HttpServletRequest request, HttpServletResponse response) {
StudentDBBean dao = StudentDBBean.getInstance();
List<StudentBean> infos = dao.getStuInfo();
request.setAttribute("infos", infos);
}
}
| UTF-8 | Java | 429 | java | stu_List.java | Java | [] | null | [] | package kr.co.koo.izone.user;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class stu_List implements stu_Service {
public void execute(HttpServletRequest request, HttpServletResponse response) {
StudentDBBean dao = StudentDBBean.getInstance();
List<StudentBean> infos = dao.getStuInfo();
request.setAttribute("infos", infos);
}
}
| 429 | 0.771562 | 0.771562 | 20 | 20.35 | 24.24103 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.95 | false | false | 14 |
bb8b7a677d15ab32f151bbb1cd43e9d4d3ec5865 | 20,237,885,963,907 | 2951b0a34ed6370183da6af66e291cdb2ceb9dc5 | /jstl-lib/src/lib/LeftMenu.java | cdf868380f8c2726e3b0db9cf953e43a310dc5ce | [] | no_license | DmitryKuzin/Java_Informatics | https://github.com/DmitryKuzin/Java_Informatics | 49a36cc50de3a9a31703a1f648be3307f0608125 | 0e4c7b6138510f3a5b82c863b912fdeef76cc4d1 | refs/heads/master | 2021-01-10T18:06:20.909000 | 2015-12-08T11:56:02 | 2015-12-08T11:56:02 | 44,623,725 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lib;
import lib.Header;
import java.util.List;
import java.util.Map;
/**
* Created by kuzin on 30.10.2015.
*/
public class LeftMenu extends Header {
// public LeftMenu(){}
// public LeftMenu(Map<String,List<String>> src) {
// super(src);
// }
// @Override
// public String toString(){
// String template="leftMenu:";
// for(String s: li.keySet()) {
// template+=s+"\n";
// for (String u : li.get(s)) {
// template += u + "\n";
// }
// template+="\n";
// }
// return template;
// }
}
| UTF-8 | Java | 608 | java | LeftMenu.java | Java | [
{
"context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by kuzin on 30.10.2015.\n */\npublic class LeftMenu extends ",
"end": 103,
"score": 0.9995986819267273,
"start": 98,
"tag": "USERNAME",
"value": "kuzin"
}
] | null | [] | package lib;
import lib.Header;
import java.util.List;
import java.util.Map;
/**
* Created by kuzin on 30.10.2015.
*/
public class LeftMenu extends Header {
// public LeftMenu(){}
// public LeftMenu(Map<String,List<String>> src) {
// super(src);
// }
// @Override
// public String toString(){
// String template="leftMenu:";
// for(String s: li.keySet()) {
// template+=s+"\n";
// for (String u : li.get(s)) {
// template += u + "\n";
// }
// template+="\n";
// }
// return template;
// }
}
| 608 | 0.495066 | 0.481908 | 28 | 20.714285 | 14.824827 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.392857 | false | false | 14 |
7468a0753e9f9a68356dbc40b22e4bf5e57c8253 | 2,388,001,884,350 | c3318c5aa49b3e848cf8a4a7460117e09599c0a7 | /app/src/main/java/com/yuahp/falling/TestSurface.java | 6e31a4110f5c257263c14012f38a51f3a1cc3dc0 | [] | no_license | YuahP/Falling | https://github.com/YuahP/Falling | a24b9acd01c299b98e7a5212072d7b9218f4a34b | bfa3228548157440148201c85bc8abd396bd4811 | refs/heads/master | 2020-04-16T15:45:22.700000 | 2016-08-17T02:38:25 | 2016-08-17T02:38:25 | 41,727,799 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yuahp.falling;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class TestSurface extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private SurfaceHolder holder;
private Bitmap img;
private Bitmap img2;
private Thread thread;
int width,height;
private Context context_;
boolean retry = true;
boolean running = false;
private Display display;
private int dvch,dvcw;
private Random random = new Random();
private Paint paint;
private int ranx = 0;
private int ro = 0;
private int x,y = 0;
private int sx,sy;
Matrix matrix = new Matrix();
List<SurfaceInit> list = new ArrayList<SurfaceInit>();
int weather = 0;
public TestSurface(Context context) {
super(context);
context_ = context;
display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
img2 = BitmapFactory.decodeResource(getResources(), R.drawable.shine_1);
list = new ArrayList<SurfaceInit>();
paint = new Paint();
holder = getHolder();
holder.setFormat(PixelFormat.TRANSLUCENT);
holder.addCallback(this);
paint.setAlpha(130);
}
public void setRunning(boolean run){
running = run;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
setRunning(true);
thread = new Thread(this);
thread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
retry = true;
setRunning(false);
while(retry) {
try{
List<SurfaceInit> list = null;
retry = false;
thread.join();
} catch (Exception e) {
e.getStackTrace();
}
}
}
@Override
public void run() {
Canvas canvas;
while (running) {
canvas = null;
try {
canvas = holder.lockCanvas(null);
synchronized (holder) {
if(canvas != null) {
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
if (display.getOrientation() == Configuration.ORIENTATION_PORTRAIT) {
dvch = display.getHeight();
dvcw = display.getWidth();
Log.i("Falling-Surface1", String.valueOf(dvch) + ',' + String.valueOf(dvcw));
} else {
dvch = display.getHeight();
dvcw = display.getWidth();
Log.i("Falling-Surface2", String.valueOf(dvch) + ',' + String.valueOf(dvcw));
}
for (int i = 0; i < list.size(); i++) {
SurfaceInit Init = list.get(i);
if (Init.weather == 1) { // rain
canvas.drawBitmap(Init.imgbit, Init.x, Init.y, null);
}
if (Init.weather == 2) { // snow
matrix.reset();
matrix.postRotate(ro);
matrix.postTranslate(Init.x, Init.y);
canvas.drawBitmap(Init.imgbit, matrix, null);
}
}
if (weather == 0 && Controller.cloudy <= 30) {
canvas.drawBitmap(img2, 0, 0, paint);
}
make();
move();
ro++;
if (ro >= 360) {
ro = 0;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}
}
public void make() {
int x = random.nextInt(dvcw);
int y = -30;
int speedX = 0;
int speedY = 0;
Bitmap imgbit = null;
int cloudy = Controller.cloudy;
int snow = Controller.snow;
int rain = Controller.rain;
int temp = Controller.temp;
if (list.size() <= temp *2 && snow == 0) {
if(rain >= 1) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.rain_1_32);
speedY = random.nextInt(30) + 1;
weather = 1;
SurfaceInit Init = new SurfaceInit(x, y, speedX, speedY, imgbit, weather);
list.add(Init);
}
} else if (temp *4 - list.size() > 0 && snow >= 1) {
if(snow >= 1) {
int imgran = random.nextInt(6) + 1;
if (imgran == 1) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.snow_1_16);
}
if (imgran == 2) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.snow_1_8);
}
if (imgran == 3) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.snow_2_16);
}
if (imgran == 4) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.snow_2_8);
}
if (imgran == 5) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.snow_3_16);
}
if (imgran == 6) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.snow_3_8);
}
speedY = random.nextInt(20) + 1;
weather = 2;
SurfaceInit Init = new SurfaceInit(x, y, speedX, speedY, imgbit, weather);
list.add(Init);
}
}
}
public void move() {
for(int i=0; i<list.size(); i++) {
SurfaceInit Init = list.get(i);
if (Init.speedX != 0) {
Init.x += Init.speedX;
}
Init.y += Init.speedY;
if(Init.y >= dvch +20 ) {
list.remove(Init);
}
if(Init.x >= dvcw +20 ) {
list.remove(Init);
}
if(Init.x <= -20 ) {
list.remove(Init);
}
}
}
} | UTF-8 | Java | 7,213 | java | TestSurface.java | Java | [] | null | [] | package com.yuahp.falling;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class TestSurface extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private SurfaceHolder holder;
private Bitmap img;
private Bitmap img2;
private Thread thread;
int width,height;
private Context context_;
boolean retry = true;
boolean running = false;
private Display display;
private int dvch,dvcw;
private Random random = new Random();
private Paint paint;
private int ranx = 0;
private int ro = 0;
private int x,y = 0;
private int sx,sy;
Matrix matrix = new Matrix();
List<SurfaceInit> list = new ArrayList<SurfaceInit>();
int weather = 0;
public TestSurface(Context context) {
super(context);
context_ = context;
display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
img2 = BitmapFactory.decodeResource(getResources(), R.drawable.shine_1);
list = new ArrayList<SurfaceInit>();
paint = new Paint();
holder = getHolder();
holder.setFormat(PixelFormat.TRANSLUCENT);
holder.addCallback(this);
paint.setAlpha(130);
}
public void setRunning(boolean run){
running = run;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
setRunning(true);
thread = new Thread(this);
thread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
retry = true;
setRunning(false);
while(retry) {
try{
List<SurfaceInit> list = null;
retry = false;
thread.join();
} catch (Exception e) {
e.getStackTrace();
}
}
}
@Override
public void run() {
Canvas canvas;
while (running) {
canvas = null;
try {
canvas = holder.lockCanvas(null);
synchronized (holder) {
if(canvas != null) {
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
if (display.getOrientation() == Configuration.ORIENTATION_PORTRAIT) {
dvch = display.getHeight();
dvcw = display.getWidth();
Log.i("Falling-Surface1", String.valueOf(dvch) + ',' + String.valueOf(dvcw));
} else {
dvch = display.getHeight();
dvcw = display.getWidth();
Log.i("Falling-Surface2", String.valueOf(dvch) + ',' + String.valueOf(dvcw));
}
for (int i = 0; i < list.size(); i++) {
SurfaceInit Init = list.get(i);
if (Init.weather == 1) { // rain
canvas.drawBitmap(Init.imgbit, Init.x, Init.y, null);
}
if (Init.weather == 2) { // snow
matrix.reset();
matrix.postRotate(ro);
matrix.postTranslate(Init.x, Init.y);
canvas.drawBitmap(Init.imgbit, matrix, null);
}
}
if (weather == 0 && Controller.cloudy <= 30) {
canvas.drawBitmap(img2, 0, 0, paint);
}
make();
move();
ro++;
if (ro >= 360) {
ro = 0;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}
}
public void make() {
int x = random.nextInt(dvcw);
int y = -30;
int speedX = 0;
int speedY = 0;
Bitmap imgbit = null;
int cloudy = Controller.cloudy;
int snow = Controller.snow;
int rain = Controller.rain;
int temp = Controller.temp;
if (list.size() <= temp *2 && snow == 0) {
if(rain >= 1) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.rain_1_32);
speedY = random.nextInt(30) + 1;
weather = 1;
SurfaceInit Init = new SurfaceInit(x, y, speedX, speedY, imgbit, weather);
list.add(Init);
}
} else if (temp *4 - list.size() > 0 && snow >= 1) {
if(snow >= 1) {
int imgran = random.nextInt(6) + 1;
if (imgran == 1) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.snow_1_16);
}
if (imgran == 2) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.snow_1_8);
}
if (imgran == 3) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.snow_2_16);
}
if (imgran == 4) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.snow_2_8);
}
if (imgran == 5) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.snow_3_16);
}
if (imgran == 6) {
imgbit = BitmapFactory.decodeResource(getResources(), R.drawable.snow_3_8);
}
speedY = random.nextInt(20) + 1;
weather = 2;
SurfaceInit Init = new SurfaceInit(x, y, speedX, speedY, imgbit, weather);
list.add(Init);
}
}
}
public void move() {
for(int i=0; i<list.size(); i++) {
SurfaceInit Init = list.get(i);
if (Init.speedX != 0) {
Init.x += Init.speedX;
}
Init.y += Init.speedY;
if(Init.y >= dvch +20 ) {
list.remove(Init);
}
if(Init.x >= dvcw +20 ) {
list.remove(Init);
}
if(Init.x <= -20 ) {
list.remove(Init);
}
}
}
} | 7,213 | 0.487315 | 0.476501 | 227 | 30.779736 | 24.823162 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.687225 | false | false | 14 |
65c3bdf68f83271b4983ea0d780b0ae8cc5c85ad | 2,362,232,054,578 | 2cd444d31fff771d9a18acf77f72de09b1758aed | /AAU/P4/SPO/Lectures/SPO 01 - 2014_02_04/src/spo/opg2_simple/Program.java | f20692911d4ac7b540f0867a6904d7d6f7985c97 | [] | no_license | Stg3orge/TheVault | https://github.com/Stg3orge/TheVault | cf691afcd56e46d2e65415a656b7dedf50b386fb | 12a75c4b7bb44c49899694f028216c646a30c56d | refs/heads/master | 2021-04-03T10:25:38.403000 | 2019-05-08T06:11:54 | 2019-05-08T06:11:54 | 124,516,647 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* A _simple_ solution to assignment 2 from "before Lecture 1" on 4/2 - 2014
*
* @author Thomas Bøgholm - boegholm@cs.aau.dk
*/
package spo.opg2_simple;
public class Program {
public static void main(String[] args) {
Node root =
new Node("Times", // root
new Node("Plus", // left of Times
new Node("Var", // left of Plus
new Node("a", null, null), // left of Var
null), // right of Var
new Node("Var", // right of Plus
new Node("n", null, null), // left of Var
null) // right of Var
),
new Node("Int", // right of Times
new Node("1", null, null), // left of Int
null // right of Int
)
);
System.out.println("preorder");
preorder_DFS(root);
System.out.println();
System.out.println("inorder");
inorder_DFS(root);
System.out.println();
System.out.println("postorder");
postorder_DFS(root);
System.out.println();
}
// http://en.wikipedia.org/wiki/Tree_traversal#Depth-first
public static void preorder_DFS(Node root){
if(root == null) return;
System.out.print(root + " ");
preorder_DFS(root.left);
preorder_DFS(root.right);
}
public static void inorder_DFS(Node root){
if(root == null) return;
inorder_DFS(root.left);
System.out.print(root+" ");
inorder_DFS(root.right);
}
public static void postorder_DFS(Node root){
if(root == null) return;
postorder_DFS(root.left);
postorder_DFS(root.right);
System.out.print(root+" ");
}
} | UTF-8 | Java | 1,572 | java | Program.java | Java | [
{
"context": " \"before Lecture 1\" on 4/2 - 2014\r\n * \r\n * @author Thomas Bøgholm - boegholm@cs.aau.dk\r\n */\r\n\r\npackage spo.opg2_sim",
"end": 113,
"score": 0.9998953342437744,
"start": 99,
"tag": "NAME",
"value": "Thomas Bøgholm"
},
{
"context": "1\" on 4/2 - 2014\r\n * \r\n... | null | [] | /**
* A _simple_ solution to assignment 2 from "before Lecture 1" on 4/2 - 2014
*
* @author <NAME> - <EMAIL>
*/
package spo.opg2_simple;
public class Program {
public static void main(String[] args) {
Node root =
new Node("Times", // root
new Node("Plus", // left of Times
new Node("Var", // left of Plus
new Node("a", null, null), // left of Var
null), // right of Var
new Node("Var", // right of Plus
new Node("n", null, null), // left of Var
null) // right of Var
),
new Node("Int", // right of Times
new Node("1", null, null), // left of Int
null // right of Int
)
);
System.out.println("preorder");
preorder_DFS(root);
System.out.println();
System.out.println("inorder");
inorder_DFS(root);
System.out.println();
System.out.println("postorder");
postorder_DFS(root);
System.out.println();
}
// http://en.wikipedia.org/wiki/Tree_traversal#Depth-first
public static void preorder_DFS(Node root){
if(root == null) return;
System.out.print(root + " ");
preorder_DFS(root.left);
preorder_DFS(root.right);
}
public static void inorder_DFS(Node root){
if(root == null) return;
inorder_DFS(root.left);
System.out.print(root+" ");
inorder_DFS(root.right);
}
public static void postorder_DFS(Node root){
if(root == null) return;
postorder_DFS(root.left);
postorder_DFS(root.right);
System.out.print(root+" ");
}
} | 1,552 | 0.583068 | 0.576703 | 60 | 24.216667 | 17.492943 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.516667 | false | false | 14 |
62de53a1e2cfd76ba1ed176ca1c9368e4a45cf10 | 2,362,232,054,541 | 54e18e5e7d6ae2ec10a0a8767fc8a73e5a7bc9d0 | /src/main/java/org/perscholas/security/AppSecurityConfiguration.java | e9c577eccc05a244b138349bb8252c0fb4b282a4 | [] | no_license | loitrem/WarehouseInventoryManagementCaseStudy | https://github.com/loitrem/WarehouseInventoryManagementCaseStudy | 12609902c7362bdcb0ab62fb4a6b331e6fb9aee0 | b5fe4ed2dc10ede6473cb10a4c2518b64fa748d2 | refs/heads/main | 2023-06-11T19:57:16.302000 | 2021-07-05T03:00:43 | 2021-07-05T03:00:43 | 374,270,760 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.perscholas.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.*;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/users/**", "/employees/**", "/inventory/**", "/inventorygroups/**")
.hasAnyAuthority("ROLE_USER", "ROLE_AUTH_USER", "ROLE_ADMIN")
.antMatchers("/", "/register")
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/login/authenticate")
.defaultSuccessUrl("/users/home")
.failureUrl("/login?error=true")
.permitAll()
.and()
.rememberMe()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/403");
}
//allows anyone to access these urls
@Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/assets/**");
}
@Autowired
private AppUserDetailService appUserDetailService;
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(appUserDetailService);
provider.setPasswordEncoder(getPasswordEncoder());
return provider;
}
@Bean
public static PasswordEncoder getPasswordEncoder() {
PasswordEncoder defaultEncoder = new BCryptPasswordEncoder(4);
String idForEncode = "bcrypt";
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put(idForEncode, new BCryptPasswordEncoder());
encoders.put("noop", NoOpPasswordEncoder.getInstance());
encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
encoders.put("scrypt", new SCryptPasswordEncoder());
encoders.put("sha256", new StandardPasswordEncoder());
DelegatingPasswordEncoder passwordEncoder = new DelegatingPasswordEncoder(idForEncode, encoders);
passwordEncoder.setDefaultPasswordEncoderForMatches(defaultEncoder);
return passwordEncoder;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
}
| UTF-8 | Java | 4,173 | java | AppSecurityConfiguration.java | Java | [
{
"context": "age(\"/login\")\n .usernameParameter(\"username\")\n .passwordParameter(\"password\")\n",
"end": 1945,
"score": 0.9995073080062866,
"start": 1937,
"tag": "USERNAME",
"value": "username"
},
{
"context": "r(\"username\")\n .pas... | null | [] | package org.perscholas.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.*;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/users/**", "/employees/**", "/inventory/**", "/inventorygroups/**")
.hasAnyAuthority("ROLE_USER", "ROLE_AUTH_USER", "ROLE_ADMIN")
.antMatchers("/", "/register")
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("<PASSWORD>")
.loginProcessingUrl("/login/authenticate")
.defaultSuccessUrl("/users/home")
.failureUrl("/login?error=true")
.permitAll()
.and()
.rememberMe()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/403");
}
//allows anyone to access these urls
@Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/assets/**");
}
@Autowired
private AppUserDetailService appUserDetailService;
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(appUserDetailService);
provider.setPasswordEncoder(getPasswordEncoder());
return provider;
}
@Bean
public static PasswordEncoder getPasswordEncoder() {
PasswordEncoder defaultEncoder = new BCryptPasswordEncoder(4);
String idForEncode = "bcrypt";
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put(idForEncode, new BCryptPasswordEncoder());
encoders.put("noop", NoOpPasswordEncoder.getInstance());
encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
encoders.put("scrypt", new SCryptPasswordEncoder());
encoders.put("sha256", new StandardPasswordEncoder());
DelegatingPasswordEncoder passwordEncoder = new DelegatingPasswordEncoder(idForEncode, encoders);
passwordEncoder.setDefaultPasswordEncoderForMatches(defaultEncoder);
return passwordEncoder;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
}
| 4,175 | 0.688474 | 0.686317 | 98 | 41.581635 | 30.129625 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540816 | false | false | 14 |
37bc139bcb86f38c8acc2d4eeff4e39e7492d164 | 5,918,464,951,160 | 3a487a8f87e7336d802c360688810df93652d4be | /src/main/java/dbService/DBService.java | b949f2d3279d1837aa15c556a993feebd9dae699 | [] | no_license | Sguhaaa/ServletWithJSPHibernate-master_ | https://github.com/Sguhaaa/ServletWithJSPHibernate-master_ | aa0e66da05eeb5a46cbc072ca6e517d2bafee240 | d75cf737dfe9807479a9c893d9db8c11d0fadf67 | refs/heads/master | 2023-05-03T06:26:49.219000 | 2021-05-26T19:54:15 | 2021-05-26T19:54:15 | 371,153,421 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dbService;
import dbService.dao.UserDAO;
import dbService.data.UserProfile;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class DBService {
private static final String hibernate_show_sql = "true";
private static final String hibernate_hbm2ddl_auto = "update";
private static SessionFactory sessionFactory = null;
public DBService() {
Configuration configuration = getConfiguration();
sessionFactory = createSessionFactory(configuration);
}
public UserProfile getUser(String login){
Session session = sessionFactory.openSession();
UserProfile dataSet = new UserDAO(session).get(login);
session.close();
return dataSet;
}
public void addUser(UserProfile userProfile) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
UserDAO dao = new UserDAO(session);
dao.insertUser(userProfile.getLogin(), userProfile.getPassword(), userProfile.getEmail());
transaction.commit();
session.close();
}
private static SessionFactory createSessionFactory(Configuration configuration) {
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
builder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = builder.build();
return configuration.buildSessionFactory(serviceRegistry);
}
private Configuration getConfiguration() {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(UserProfile.class);
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/servletwithjsp?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Europe/Moscow");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "root");
configuration.setProperty("hibernate.show_sql", hibernate_show_sql);
configuration.setProperty("hibernate.hbm2ddl.auto", hibernate_hbm2ddl_auto);
return configuration;
}
}
| UTF-8 | Java | 2,598 | java | DBService.java | Java | [
{
"context": "ion.setProperty(\"hibernate.connection.password\", \"root\");\n configuration.setProperty(\"hibernate.s",
"end": 2394,
"score": 0.9363630414009094,
"start": 2390,
"tag": "PASSWORD",
"value": "root"
}
] | null | [] | package dbService;
import dbService.dao.UserDAO;
import dbService.data.UserProfile;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class DBService {
private static final String hibernate_show_sql = "true";
private static final String hibernate_hbm2ddl_auto = "update";
private static SessionFactory sessionFactory = null;
public DBService() {
Configuration configuration = getConfiguration();
sessionFactory = createSessionFactory(configuration);
}
public UserProfile getUser(String login){
Session session = sessionFactory.openSession();
UserProfile dataSet = new UserDAO(session).get(login);
session.close();
return dataSet;
}
public void addUser(UserProfile userProfile) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
UserDAO dao = new UserDAO(session);
dao.insertUser(userProfile.getLogin(), userProfile.getPassword(), userProfile.getEmail());
transaction.commit();
session.close();
}
private static SessionFactory createSessionFactory(Configuration configuration) {
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
builder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = builder.build();
return configuration.buildSessionFactory(serviceRegistry);
}
private Configuration getConfiguration() {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(UserProfile.class);
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/servletwithjsp?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Europe/Moscow");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "<PASSWORD>");
configuration.setProperty("hibernate.show_sql", hibernate_show_sql);
configuration.setProperty("hibernate.hbm2ddl.auto", hibernate_hbm2ddl_auto);
return configuration;
}
}
| 2,604 | 0.743264 | 0.74057 | 60 | 42.299999 | 37.103146 | 216 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.783333 | false | false | 14 |
524cb0f74a833daf9f5245eab1ace66dd412f4e1 | 6,631,429,526,004 | b0767133c0873b9848a4b3cae36846f1fe3e98bf | /OnedayClass/src/com/javaproject/home/empty.java | 19d9cd89cce88f255ecf95f323c87bc76c663be5 | [] | no_license | Hyoeun-Kwon/JavaProject_OnedayClass_team2 | https://github.com/Hyoeun-Kwon/JavaProject_OnedayClass_team2 | 5bd9e415cf8e59853e903410e96d236707ce9bfe | df0cb5d57f207da4109ce160f572c082f6091779 | refs/heads/main | 2023-04-16T09:14:46.222000 | 2021-04-26T07:15:08 | 2021-04-26T07:15:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.javaproject.home;
public class empty {
}
| UTF-8 | Java | 55 | java | empty.java | Java | [] | null | [] | package com.javaproject.home;
public class empty {
}
| 55 | 0.745455 | 0.745455 | 5 | 10 | 12.181953 | 29 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 14 |
fcbd6b19a1fd40bbbdce3333df04149ad35e4fe7 | 6,631,429,529,065 | 3400055bae00fdeab9c39f7b4dff8f7d74f7fc22 | /gotopXmzh/src/com/eos/web/taglib/html/PrivateRadioTag.java | 60cd85f0f9ff2f0b9302f7a5546ef502f4d3d436 | [] | no_license | junzero/XMXM | https://github.com/junzero/XMXM | ce250507601bcdc78dd1781971c89e01ac25049e | f53b17749c119522f84e4f615bfe985e9a16ebe2 | refs/heads/master | 2016-08-10T13:54:46.754000 | 2015-09-28T06:28:04 | 2015-09-28T06:28:04 | 43,273,873 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi
// Source File Name: PrivateRadioTag.java
package com.eos.web.taglib.html;
import com.eos.web.taglib.util.XpathUtil;
import com.primeton.web.core.control.ComponentFactory;
import com.primeton.web.core.control.WebComponent;
import javax.servlet.jsp.JspException;
// Referenced classes of package com.eos.web.taglib.html:
// BaseInputTag
public class PrivateRadioTag extends BaseInputTag
{
private String checked;
private String checkedValue;
public PrivateRadioTag()
{
checked = null;
checkedValue = null;
}
public String getChecked()
{
return checked;
}
public void setChecked(String checked)
{
this.checked = checked;
}
public void setChecked(boolean checked)
{
this.checked = String.valueOf(checked);
}
public void initAttributes()
throws JspException
{
super.initAttributes();
checked = XpathUtil.getStringByXpathSupport(getRootObj(), checked);
checkedValue = XpathUtil.getStringByXpathSupport(getRootObj(), checkedValue);
}
protected void prepareValue()
{
if(checked != null && checked.equalsIgnoreCase("true"))
component.setAttribute("checked", "true");
String tmpValue = getValue();
if(getPropertyValue() != null)
tmpValue = String.valueOf(getPropertyValue());
if(tmpValue != null)
{
if(tmpValue.equals(getCheckedValue()))
component.setAttribute("checked", "true");
component.setValue(tmpValue);
}
}
public int doStartTag()
throws JspException
{
initAttributes();
try
{
component = ComponentFactory.createWebComponent("radio", getModelField());
prepareAttributes();
}
catch(Exception e)
{
throw new JspException(e);
}
return 1;
}
public void release()
{
super.release();
checked = null;
checkedValue = null;
}
public String getCheckedValue()
{
return checkedValue;
}
public void setCheckedValue(String checkedValue)
{
this.checkedValue = checkedValue;
}
}
| UTF-8 | Java | 2,417 | java | PrivateRadioTag.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.kpdus.com/jad.html\n",
"end": 61,
"score": 0.9996551275253296,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
] | null | [] | // Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi
// Source File Name: PrivateRadioTag.java
package com.eos.web.taglib.html;
import com.eos.web.taglib.util.XpathUtil;
import com.primeton.web.core.control.ComponentFactory;
import com.primeton.web.core.control.WebComponent;
import javax.servlet.jsp.JspException;
// Referenced classes of package com.eos.web.taglib.html:
// BaseInputTag
public class PrivateRadioTag extends BaseInputTag
{
private String checked;
private String checkedValue;
public PrivateRadioTag()
{
checked = null;
checkedValue = null;
}
public String getChecked()
{
return checked;
}
public void setChecked(String checked)
{
this.checked = checked;
}
public void setChecked(boolean checked)
{
this.checked = String.valueOf(checked);
}
public void initAttributes()
throws JspException
{
super.initAttributes();
checked = XpathUtil.getStringByXpathSupport(getRootObj(), checked);
checkedValue = XpathUtil.getStringByXpathSupport(getRootObj(), checkedValue);
}
protected void prepareValue()
{
if(checked != null && checked.equalsIgnoreCase("true"))
component.setAttribute("checked", "true");
String tmpValue = getValue();
if(getPropertyValue() != null)
tmpValue = String.valueOf(getPropertyValue());
if(tmpValue != null)
{
if(tmpValue.equals(getCheckedValue()))
component.setAttribute("checked", "true");
component.setValue(tmpValue);
}
}
public int doStartTag()
throws JspException
{
initAttributes();
try
{
component = ComponentFactory.createWebComponent("radio", getModelField());
prepareAttributes();
}
catch(Exception e)
{
throw new JspException(e);
}
return 1;
}
public void release()
{
super.release();
checked = null;
checkedValue = null;
}
public String getCheckedValue()
{
return checkedValue;
}
public void setCheckedValue(String checkedValue)
{
this.checkedValue = checkedValue;
}
}
| 2,407 | 0.619363 | 0.615639 | 98 | 23.663265 | 21.423306 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 14 |
261c2aa3df1831577f3f4bbace70e23da9d7b9f3 | 30,270,929,545,752 | df7f5043e2437caf7f3532346de2a6f0e1b81fa9 | /FlightBookingApp/src/main/java/com/example/demo/repository/FlightRepository.java | a3a50789e691705ef9918a0d575d88eb5cfaf14d | [] | no_license | privaratsabari33/Boot | https://github.com/privaratsabari33/Boot | 9bbed50f111b314915387e99012003467d49e087 | 669d28a7ca6df1a792d5cecb8fbca499e7568fcd | refs/heads/master | 2021-03-15T08:51:24.663000 | 2020-03-13T12:10:23 | 2020-03-13T12:10:23 | 246,838,656 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.FlightBook;
@Repository
public interface FlightRepository extends JpaRepository<FlightBook, Long>{
List<FlightBook> getBySource(String source, String destination);
}
| UTF-8 | Java | 397 | java | FlightRepository.java | Java | [] | null | [] | package com.example.demo.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.FlightBook;
@Repository
public interface FlightRepository extends JpaRepository<FlightBook, Long>{
List<FlightBook> getBySource(String source, String destination);
}
| 397 | 0.783375 | 0.783375 | 17 | 21.235294 | 26.280231 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 14 |
ab48b6ad4139dd57faf92ba8f2718c76efee46be | 30,270,929,548,199 | c27743f5cf02fbefaf644c432b87e09da54e0664 | /src/test/java/weibo4j/AccountTest.java | ef20344d00e4b9c5864e20a3bb9ee9945de6c307 | [] | no_license | georgecao/weibo-java-sdk-v2 | https://github.com/georgecao/weibo-java-sdk-v2 | c6e5287bda12bc5f18721476b20420f91392bb79 | c55d6094a7bce8ebd94dc95aad566b4f86e2d89e | refs/heads/master | 2021-07-18T22:26:09.748000 | 2020-06-16T04:18:50 | 2020-06-16T04:18:50 | 4,256,289 | 0 | 0 | null | false | 2021-06-04T01:02:02 | 2012-05-08T02:14:42 | 2020-06-16T04:18:54 | 2021-06-04T01:02:01 | 236 | 2 | 0 | 2 | Java | false | false | package weibo4j;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weibo4j.model.*;
import weibo4j.util.ParamUtils;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertNotNull;
/**
* Say something?
* <pre>
* User: zhangzhi.cao
* Date: 12-7-2
* Time: 下午3:36
* </pre>
*/
public class AccountTest {
private static final Logger LOG = LoggerFactory.getLogger(AccountTest.class);
private static final boolean debug = LOG.isDebugEnabled();
Weibo weibo = WeiboService.getOne();
@Test
public void testCreateAccount() throws Exception {
AccountUser accountUser = AccountUser.AccountUserBuilder.newBuilder()
.city(10)
.screenName("George")
.realName("George")
.realNameVisible(VisibleScope.SELF)
.province(100)
.birthday(new Date())
.birthdayVisible(BirthdayVisibleScope.CONSTELLATION)
.credentialsType(CredentialType.HK_MO_TW_ID)
.credentialsNum("323232323")
.email("email@qq.com")
.emailVisible(VisibleScope.ALL)
.url("http://abc.com")
.urlVisible(VisibleScope.FOLLOWING)
.qq("1111111111")
.qqVisible(VisibleScope.SELF)
.msn("aaa@bbb.com")
.msnVisible(VisibleScope.FOLLOWING)
.lang(Lang.ZH_CN)
.gender(Gender.MALE)
.description("desc")
.build();
List<HttpParameter> list = ParamUtils.get(accountUser);
for (HttpParameter pp : list) {
LOG.info("{}={},", pp.getName(), pp.getValue());
}
LOG.info("{}", list.size());
Account account = new Account("2.00tBx13B0WKLFi98a3201060TbLJLB");
Long userId = account.createAccount(accountUser);
LOG.info("User id is: {}", userId);
}
@Test
public void testGetAccountEducation() throws Exception {
List<Education> value = weibo.getAccountService().getAccountEducation("2099907877");
assertNotNull(value);
LOG.info("{}", value);
}
@Test
public void testGetAccountCareer() throws Exception {
List<Career> value = weibo.getAccountService().getAccountCareer("1246205697");
assertNotNull(value);
LOG.info("{}", value);
}
}
| UTF-8 | Java | 2,441 | java | AccountTest.java | Java | [
{
"context": "tNotNull;\n\n/**\n * Say something?\n * <pre>\n * User: zhangzhi.cao\n * Date: 12-7-2\n * Time: 下午3:36\n * </p",
"end": 290,
"score": 0.6840328574180603,
"start": 289,
"tag": "NAME",
"value": "z"
},
{
"context": "otNull;\n\n/**\n * Say something?\n * <pre>\n * User: zha... | null | [] | package weibo4j;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weibo4j.model.*;
import weibo4j.util.ParamUtils;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertNotNull;
/**
* Say something?
* <pre>
* User: zhangzhi.cao
* Date: 12-7-2
* Time: 下午3:36
* </pre>
*/
public class AccountTest {
private static final Logger LOG = LoggerFactory.getLogger(AccountTest.class);
private static final boolean debug = LOG.isDebugEnabled();
Weibo weibo = WeiboService.getOne();
@Test
public void testCreateAccount() throws Exception {
AccountUser accountUser = AccountUser.AccountUserBuilder.newBuilder()
.city(10)
.screenName("George")
.realName("George")
.realNameVisible(VisibleScope.SELF)
.province(100)
.birthday(new Date())
.birthdayVisible(BirthdayVisibleScope.CONSTELLATION)
.credentialsType(CredentialType.HK_MO_TW_ID)
.credentialsNum("323232323")
.email("<EMAIL>")
.emailVisible(VisibleScope.ALL)
.url("http://abc.com")
.urlVisible(VisibleScope.FOLLOWING)
.qq("1111111111")
.qqVisible(VisibleScope.SELF)
.msn("<EMAIL>")
.msnVisible(VisibleScope.FOLLOWING)
.lang(Lang.ZH_CN)
.gender(Gender.MALE)
.description("desc")
.build();
List<HttpParameter> list = ParamUtils.get(accountUser);
for (HttpParameter pp : list) {
LOG.info("{}={},", pp.getName(), pp.getValue());
}
LOG.info("{}", list.size());
Account account = new Account("2.00tBx13B0WKLFi98a3201060TbLJLB");
Long userId = account.createAccount(accountUser);
LOG.info("User id is: {}", userId);
}
@Test
public void testGetAccountEducation() throws Exception {
List<Education> value = weibo.getAccountService().getAccountEducation("2099907877");
assertNotNull(value);
LOG.info("{}", value);
}
@Test
public void testGetAccountCareer() throws Exception {
List<Career> value = weibo.getAccountService().getAccountCareer("1246205697");
assertNotNull(value);
LOG.info("{}", value);
}
}
| 2,432 | 0.595404 | 0.56627 | 78 | 30.243589 | 23.487141 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.410256 | false | false | 14 |
ced11b480887f721b4d9a7dd39d890d196141694 | 21,019,569,949,776 | 7d24ba67181f203d097aa35edddff65521b3fa4a | /app/src/main/java/com/example/fitnessapp/BackHomeActivity.java | 4b7eba2bbb888c96407fdca3903d2507a828806f | [] | no_license | YueyangLiulyy/CISC325 | https://github.com/YueyangLiulyy/CISC325 | 1106f81fc3c2abfdf11257b4148471dc1abc7fd6 | 039c09cda84fef08ba0b485b43dd61c54886bd60 | refs/heads/master | 2022-04-13T18:22:16.166000 | 2020-04-04T00:13:21 | 2020-04-04T00:13:21 | 234,967,948 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.fitnessapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
public class BackHomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_back_home);
getSetBackDefault();
userChoice();
}
private void getSetBackDefault(){
SharedPreferences sharedPreferences = getSharedPreferences("back", MODE_PRIVATE);
boolean pullup = sharedPreferences.getBoolean(getString(R.string.pullup),true);
boolean latpulldown = sharedPreferences.getBoolean(getString(R.string.latPulldown), true);
boolean dumbbellsinglearmrow = sharedPreferences.getBoolean(getString(R.string.dumbBellSingleArmRow), true);
boolean bentoverbarbellrow = sharedPreferences.getBoolean(getString(R.string.bentOverBarbellRow),false);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(getString(R.string.pullup),true);
editor.putBoolean(getString(R.string.latPulldown),true);
editor.putBoolean(getString(R.string.dumbBellSingleArmRow),true);
editor.putBoolean(getString(R.string.bentOverBarbellRow),false);
editor.apply();
setChestDefault(pullup, latpulldown, dumbbellsinglearmrow, bentoverbarbellrow);
}
private void setChestDefault(boolean pullup, boolean latpulldown, boolean dumbbellsinglearmrow,
boolean bentoverbarbellrow){
CheckBox checkBox1 = findViewById(R.id.pullupCheckBox);
CheckBox checkBox2 = findViewById(R.id.latPulldownCheckBox);
CheckBox checkBox3 = findViewById(R.id.dumbbellSingleArmRowCheckBox);
CheckBox checkBox4 = findViewById(R.id.bentoverBarbellRowCheckBox);
if(pullup) checkBox1.setChecked(true);
if(latpulldown) checkBox2.setChecked(true);
if(dumbbellsinglearmrow) checkBox3.setChecked(true);
if(bentoverbarbellrow) checkBox4.setChecked(true);
}
private void userChoice(){
final CheckBox checkBox1 = findViewById(R.id.pullupCheckBox);
final CheckBox checkBox2 = findViewById(R.id.latPulldownCheckBox);
final CheckBox checkBox3 = findViewById(R.id.dumbbellSingleArmRowCheckBox);
final CheckBox checkBox4 = findViewById(R.id.bentoverBarbellRowCheckBox);
SharedPreferences sharedPreferences = getSharedPreferences("back", MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
checkBox1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// when click it makes it checked
if(checkBox1.isChecked()){
editor.putBoolean(getString(R.string.pullup), true);
editor.apply();
}
else {
editor.putBoolean(getString(R.string.pullup), false);
editor.apply();
}
}
});
checkBox2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkBox2.isChecked()){
editor.putBoolean(getString(R.string.latPulldown), true);
editor.apply();
}
else{
editor.putBoolean(getString(R.string.latPulldown), false);
editor.apply();
}
}
});
checkBox3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkBox3.isChecked()){
editor.putBoolean(getString(R.string.dumbBellSingleArmRow), true);
editor.apply();
}
else{
editor.putBoolean(getString(R.string.dumbBellSingleArmRow), false);
editor.apply();
}
}
});
checkBox4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkBox4.isChecked()){
editor.putBoolean(getString(R.string.bentOverBarbellRow), true);
editor.apply();
}
else{
editor.putBoolean(getString(R.string.bentOverBarbellRow), false);
editor.apply();
}
}
});
}
}
| UTF-8 | Java | 4,745 | java | BackHomeActivity.java | Java | [] | null | [] | package com.example.fitnessapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
public class BackHomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_back_home);
getSetBackDefault();
userChoice();
}
private void getSetBackDefault(){
SharedPreferences sharedPreferences = getSharedPreferences("back", MODE_PRIVATE);
boolean pullup = sharedPreferences.getBoolean(getString(R.string.pullup),true);
boolean latpulldown = sharedPreferences.getBoolean(getString(R.string.latPulldown), true);
boolean dumbbellsinglearmrow = sharedPreferences.getBoolean(getString(R.string.dumbBellSingleArmRow), true);
boolean bentoverbarbellrow = sharedPreferences.getBoolean(getString(R.string.bentOverBarbellRow),false);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(getString(R.string.pullup),true);
editor.putBoolean(getString(R.string.latPulldown),true);
editor.putBoolean(getString(R.string.dumbBellSingleArmRow),true);
editor.putBoolean(getString(R.string.bentOverBarbellRow),false);
editor.apply();
setChestDefault(pullup, latpulldown, dumbbellsinglearmrow, bentoverbarbellrow);
}
private void setChestDefault(boolean pullup, boolean latpulldown, boolean dumbbellsinglearmrow,
boolean bentoverbarbellrow){
CheckBox checkBox1 = findViewById(R.id.pullupCheckBox);
CheckBox checkBox2 = findViewById(R.id.latPulldownCheckBox);
CheckBox checkBox3 = findViewById(R.id.dumbbellSingleArmRowCheckBox);
CheckBox checkBox4 = findViewById(R.id.bentoverBarbellRowCheckBox);
if(pullup) checkBox1.setChecked(true);
if(latpulldown) checkBox2.setChecked(true);
if(dumbbellsinglearmrow) checkBox3.setChecked(true);
if(bentoverbarbellrow) checkBox4.setChecked(true);
}
private void userChoice(){
final CheckBox checkBox1 = findViewById(R.id.pullupCheckBox);
final CheckBox checkBox2 = findViewById(R.id.latPulldownCheckBox);
final CheckBox checkBox3 = findViewById(R.id.dumbbellSingleArmRowCheckBox);
final CheckBox checkBox4 = findViewById(R.id.bentoverBarbellRowCheckBox);
SharedPreferences sharedPreferences = getSharedPreferences("back", MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
checkBox1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// when click it makes it checked
if(checkBox1.isChecked()){
editor.putBoolean(getString(R.string.pullup), true);
editor.apply();
}
else {
editor.putBoolean(getString(R.string.pullup), false);
editor.apply();
}
}
});
checkBox2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkBox2.isChecked()){
editor.putBoolean(getString(R.string.latPulldown), true);
editor.apply();
}
else{
editor.putBoolean(getString(R.string.latPulldown), false);
editor.apply();
}
}
});
checkBox3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkBox3.isChecked()){
editor.putBoolean(getString(R.string.dumbBellSingleArmRow), true);
editor.apply();
}
else{
editor.putBoolean(getString(R.string.dumbBellSingleArmRow), false);
editor.apply();
}
}
});
checkBox4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkBox4.isChecked()){
editor.putBoolean(getString(R.string.bentOverBarbellRow), true);
editor.apply();
}
else{
editor.putBoolean(getString(R.string.bentOverBarbellRow), false);
editor.apply();
}
}
});
}
}
| 4,745 | 0.620232 | 0.616017 | 117 | 39.555557 | 30.030025 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 14 |
d44419305f4d4e20da520b33d6beba3589336c53 | 9,363,028,765,000 | eac3415f1847c83152d585853b5cacea1d47ebd1 | /src/com/instancia2/ejemploinicializacion/ClaseEstatica.java | 66e7231b6d587188490f737286455de4b52c64e6 | [] | no_license | jorgiom4/002-Clases | https://github.com/jorgiom4/002-Clases | d2154c4c443d8db7f6603f5d1169e36cf270f168 | 3fa43ebda44c00ea08bd9c261d033ddb06f04a6e | refs/heads/master | 2020-03-19T10:22:28.133000 | 2018-06-18T19:18:30 | 2018-06-18T19:18:30 | 136,364,553 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.instancia2.ejemploinicializacion;
/**
* Ejemplo de tipo static
*
*/
public class ClaseEstatica {
public static int numeroEstatico;
public static String nombreCompuesto (String nombre, String apellidos){
return nombre + " " + apellidos;
}
}
| UTF-8 | Java | 281 | java | ClaseEstatica.java | Java | [] | null | [] | package com.instancia2.ejemploinicializacion;
/**
* Ejemplo de tipo static
*
*/
public class ClaseEstatica {
public static int numeroEstatico;
public static String nombreCompuesto (String nombre, String apellidos){
return nombre + " " + apellidos;
}
}
| 281 | 0.690391 | 0.686833 | 16 | 16.5625 | 22.033976 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 14 |
ed93796dc45df75351241276b4ff537927558129 | 21,174,188,806,571 | f2b349ccbf3b6bfee7ebc3047dfd7b8d5bf8b487 | /Fre.java | 74ceb632b2328c6717ab44ab51fd6dc60a941ffb | [] | no_license | hcyuser/NTU_Digital_Humanities_2016 | https://github.com/hcyuser/NTU_Digital_Humanities_2016 | cc4483c061be7ce028f4de4e20945123ac0bbe22 | 0e95912a4d788e3b626f4a6c80910ac1780a411b | refs/heads/master | 2021-06-08T17:09:07.280000 | 2016-12-05T07:08:31 | 2016-12-05T07:08:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Fre {
int counter;
String name;
Fre(String name,int c){
this.name = name;
counter = c;
}
public int getCounter(){
return counter;
}
public void setCounter(int c){
counter = c;
}
public String getName(){
return name;
}
}
| UTF-8 | Java | 255 | java | Fre.java | Java | [] | null | [] |
public class Fre {
int counter;
String name;
Fre(String name,int c){
this.name = name;
counter = c;
}
public int getCounter(){
return counter;
}
public void setCounter(int c){
counter = c;
}
public String getName(){
return name;
}
}
| 255 | 0.643137 | 0.643137 | 17 | 13.941176 | 9.238479 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.647059 | false | false | 14 |
9b54bc01d5c5cb78745fbe8c4b2ab95916a7f730 | 22,041,772,227,266 | 4d5e501d014a7cf53176390472710feb3495028b | /src/com/grayWidjaya/dao/RoleDaolmpl.java | c1797054722a875e7fa9a2bcb0f7ad38bb556305 | [] | no_license | graywidjaya/PBO2_Project_01 | https://github.com/graywidjaya/PBO2_Project_01 | 9141db3fa3006889f78d7e0deeac64cad038ad88 | 48573f2ea52bed2c6aed148db2b801026d3b0c05 | refs/heads/master | 2021-10-11T04:38:25.707000 | 2021-10-01T04:58:45 | 2021-10-01T04:58:45 | 121,521,838 | 0 | 0 | null | false | 2021-10-01T04:58:45 | 2018-02-14T14:46:38 | 2021-09-22T01:58:20 | 2021-10-01T04:58:45 | 239 | 0 | 0 | 0 | Java | false | false | package com.grayWidjaya.dao;
import com.grayWidjaya.Entity.Role;
import com.grayWidjaya.utility.DBUtil;
import com.grayWidjaya.utility.DaoService;
import com.grayWidjaya.utility.ViewUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.control.Alert;
/**
*
* @author G'ray Widjaya
*/
public class RoleDaolmpl implements DaoService<Role> {
@Override
public int addData(Role object) {
int result = 0;
try {
Connection connection = DBUtil.createMySQLConnection();
String query = "INSERT INTO role (id, name) VALUES(?,?)";
try (PreparedStatement ps = connection.prepareStatement(query)) {
ps.setInt(1, object.getId());
ps.setString(2, object.getName());
if (ps.executeUpdate() != 0) {
connection.commit();
result = 1;
}
}
} catch (ClassNotFoundException | SQLException ex) {
ViewUtil.showAlert(Alert.AlertType.ERROR, "Error", ex.getMessage());
}
return result;
}
@Override
public int deleteData(Role object) {
int result = 0;
try {
// try{
Connection connection = DBUtil.createMySQLConnection();
String query = "Delete FROM role WHERE id = ? ";
PreparedStatement ps = connection.prepareStatement(query);
ps.setInt(1, object.getId());
if (ps.executeUpdate() != 0) {
connection.commit();
result = 1;
}
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(RoleDaolmpl.class.getName()).
log(Level.SEVERE, null, ex);
}
return result;
}
@Override
public int updateData(Role object) {
int result = 0;
try {
Connection connection = DBUtil.createMySQLConnection();
String query = "UPDATE role SET name = ? WHERE id = ?";
try (PreparedStatement ps = connection.prepareStatement(query)) {
ps.setString(1, object.getName());
ps.setInt(2, object.getId());
if (ps.executeUpdate() != 0) {
connection.commit();
result = 1;
}
}
} catch (ClassNotFoundException | SQLException ex) {
ViewUtil.showAlert(Alert.AlertType.ERROR, "Error", ex.getMessage());
}
return result;
}
@Override
public List<Role> showAllData() {
List<Role> roles = new ArrayList<>();
try {
Connection connection = DBUtil.createMySQLConnection();
String query = "SELECT * FROM role ORDER BY id";
try (PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
Role role = new Role();
role.setId(rs.getInt("id"));
role.setName(rs.getString("name"));
roles.add(role);
}
}
} catch (ClassNotFoundException | SQLException ex) {
ViewUtil.showAlert(Alert.AlertType.ERROR, "Error", ex.getMessage());
}
return roles;
}
}
| UTF-8 | Java | 3,523 | java | RoleDaolmpl.java | Java | [
{
"context": "ort javafx.scene.control.Alert;\n\n/**\n *\n * @author G'ray Widjaya\n */\npublic class RoleDaolmpl implements DaoServic",
"end": 492,
"score": 0.999879002571106,
"start": 479,
"tag": "NAME",
"value": "G'ray Widjaya"
}
] | null | [] | package com.grayWidjaya.dao;
import com.grayWidjaya.Entity.Role;
import com.grayWidjaya.utility.DBUtil;
import com.grayWidjaya.utility.DaoService;
import com.grayWidjaya.utility.ViewUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.control.Alert;
/**
*
* @author <NAME>
*/
public class RoleDaolmpl implements DaoService<Role> {
@Override
public int addData(Role object) {
int result = 0;
try {
Connection connection = DBUtil.createMySQLConnection();
String query = "INSERT INTO role (id, name) VALUES(?,?)";
try (PreparedStatement ps = connection.prepareStatement(query)) {
ps.setInt(1, object.getId());
ps.setString(2, object.getName());
if (ps.executeUpdate() != 0) {
connection.commit();
result = 1;
}
}
} catch (ClassNotFoundException | SQLException ex) {
ViewUtil.showAlert(Alert.AlertType.ERROR, "Error", ex.getMessage());
}
return result;
}
@Override
public int deleteData(Role object) {
int result = 0;
try {
// try{
Connection connection = DBUtil.createMySQLConnection();
String query = "Delete FROM role WHERE id = ? ";
PreparedStatement ps = connection.prepareStatement(query);
ps.setInt(1, object.getId());
if (ps.executeUpdate() != 0) {
connection.commit();
result = 1;
}
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(RoleDaolmpl.class.getName()).
log(Level.SEVERE, null, ex);
}
return result;
}
@Override
public int updateData(Role object) {
int result = 0;
try {
Connection connection = DBUtil.createMySQLConnection();
String query = "UPDATE role SET name = ? WHERE id = ?";
try (PreparedStatement ps = connection.prepareStatement(query)) {
ps.setString(1, object.getName());
ps.setInt(2, object.getId());
if (ps.executeUpdate() != 0) {
connection.commit();
result = 1;
}
}
} catch (ClassNotFoundException | SQLException ex) {
ViewUtil.showAlert(Alert.AlertType.ERROR, "Error", ex.getMessage());
}
return result;
}
@Override
public List<Role> showAllData() {
List<Role> roles = new ArrayList<>();
try {
Connection connection = DBUtil.createMySQLConnection();
String query = "SELECT * FROM role ORDER BY id";
try (PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
Role role = new Role();
role.setId(rs.getInt("id"));
role.setName(rs.getString("name"));
roles.add(role);
}
}
} catch (ClassNotFoundException | SQLException ex) {
ViewUtil.showAlert(Alert.AlertType.ERROR, "Error", ex.getMessage());
}
return roles;
}
}
| 3,516 | 0.556344 | 0.55237 | 108 | 31.620371 | 23.11754 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.648148 | false | false | 14 |
9a788b210f6e4595c835c5f7d37cd78216060963 | 17,944,373,377,171 | 7da8c5866b91f742f5ac233fff7f60d641eaccc7 | /Site/Trabalho interdisciplinar - V10 - FINAL - Copia/src/java/controle/UsuarioDAO.java | f4cbdff94d386c055274c85518955151e820b808 | [] | no_license | mateusfilipe/VFeRoma | https://github.com/mateusfilipe/VFeRoma | 008207c6d536849ba4cc26d134ca95b35b0ef400 | c9af0456cd62a8891c3bb1a06b2675f9949dfefa | refs/heads/master | 2023-06-22T10:32:22.509000 | 2023-06-16T12:08:37 | 2023-06-16T12:08:37 | 221,236,957 | 4 | 2 | null | false | 2023-06-16T12:08:38 | 2019-11-12T14:26:54 | 2023-03-15T17:13:27 | 2023-06-16T12:08:38 | 161,769 | 3 | 2 | 0 | HTML | false | false | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controle;
import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import modelo.UsuarioBean;
import controle.Conexao;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
/**
*
* @author aluno
*/
public class UsuarioDAO {
public String salvar(UsuarioBean usuario) {
try {
Connection conexao = Conexao.getConexao();
if(new UsuarioDAO().buscar(usuario.getLogin())==null){
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Usuario Não Cadastrado.", ""));
return "cadastro";
}else{
PreparedStatement ps = (PreparedStatement) conexao.prepareCall("INSERT INTO `usuario`(`usuario`,`email`,`senha`,`confirmaSenha`,`adm`,`nome`)VALUES(?,?,?,?,?,?)");
ps.setString(1,usuario.getLogin());
ps.setString(2,usuario.getEmail());
ps.setString(3,usuario.getSenha());
ps.setString(4,usuario.getConfirmaSenha());
ps.setBoolean(5,false);
ps.setString(6,usuario.getNome());
ps.execute();
Conexao.fecharConexao();}
} catch (SQLException ex) {
Logger.getLogger(InstitutoDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return "sucesso";
}
public List<UsuarioBean> buscarTodos()
{
try {
Connection conexao = Conexao.getConexao();
java.sql.PreparedStatement ps =conexao.prepareStatement("select * from usuario");
ResultSet resultado = ps.executeQuery();
List<UsuarioBean> usuarios = new ArrayList<>();
while(resultado.next()){
UsuarioBean usuario = new UsuarioBean();
usuario.setAdm(resultado.getBoolean("adm"));
usuario.setCargo(resultado.getString("cargo"));
usuario.setConfirmaSenha(resultado.getString("confirmaSenha"));
usuario.setCpf(resultado.getString("cpf"));
usuario.setEmail(resultado.getString("email"));
usuario.setInstituto(resultado.getInt("instituto_Id_Instituto"));
usuario.setLogin(resultado.getString("usuario"));
usuario.setNome(resultado.getString("nome"));
usuario.setSenha(resultado.getString("senha"));
usuarios.add(usuario);
}
return usuarios;
} catch (SQLException ex) {
Logger.getLogger(InstitutoDAO.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
public UsuarioBean buscar(String login){
try {
Connection conexao = Conexao.getConexao();
String logon = "'"+
login+ "'";
// System.out.println(logon);
String sql = "select * from usuario u where u.usuario = "+logon;
java.sql.PreparedStatement ps =conexao.prepareStatement(sql);
ResultSet resultado = ps.executeQuery();
UsuarioBean usuario = new UsuarioBean();
while(resultado.next()){
if(resultado.getString("usuario").equals(login)){
usuario.setAdm(resultado.getBoolean("adm"));
usuario.setCargo(resultado.getString("cargo"));
usuario.setConfirmaSenha(resultado.getString("confirmaSenha"));
usuario.setCpf(resultado.getString("cpf"));
usuario.setEmail(resultado.getString("email"));
usuario.setInstituto(resultado.getInt("instituto_Id_Instituto"));
usuario.setLogin(resultado.getString("usuario"));
usuario.setNome(resultado.getString("nome"));
usuario.setSenha(resultado.getString("senha"));
}
}
return usuario;
} catch (SQLException ex) {
Logger.getLogger(InstitutoDAO.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}
| UTF-8 | Java | 4,497 | java | UsuarioDAO.java | Java | [
{
"context": "vax.faces.context.FacesContext;\n\n/**\n *\n * @author aluno\n */\npublic class UsuarioDAO {\n\n public String ",
"end": 608,
"score": 0.998272180557251,
"start": 603,
"tag": "USERNAME",
"value": "aluno"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controle;
import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import modelo.UsuarioBean;
import controle.Conexao;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
/**
*
* @author aluno
*/
public class UsuarioDAO {
public String salvar(UsuarioBean usuario) {
try {
Connection conexao = Conexao.getConexao();
if(new UsuarioDAO().buscar(usuario.getLogin())==null){
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Usuario Não Cadastrado.", ""));
return "cadastro";
}else{
PreparedStatement ps = (PreparedStatement) conexao.prepareCall("INSERT INTO `usuario`(`usuario`,`email`,`senha`,`confirmaSenha`,`adm`,`nome`)VALUES(?,?,?,?,?,?)");
ps.setString(1,usuario.getLogin());
ps.setString(2,usuario.getEmail());
ps.setString(3,usuario.getSenha());
ps.setString(4,usuario.getConfirmaSenha());
ps.setBoolean(5,false);
ps.setString(6,usuario.getNome());
ps.execute();
Conexao.fecharConexao();}
} catch (SQLException ex) {
Logger.getLogger(InstitutoDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return "sucesso";
}
public List<UsuarioBean> buscarTodos()
{
try {
Connection conexao = Conexao.getConexao();
java.sql.PreparedStatement ps =conexao.prepareStatement("select * from usuario");
ResultSet resultado = ps.executeQuery();
List<UsuarioBean> usuarios = new ArrayList<>();
while(resultado.next()){
UsuarioBean usuario = new UsuarioBean();
usuario.setAdm(resultado.getBoolean("adm"));
usuario.setCargo(resultado.getString("cargo"));
usuario.setConfirmaSenha(resultado.getString("confirmaSenha"));
usuario.setCpf(resultado.getString("cpf"));
usuario.setEmail(resultado.getString("email"));
usuario.setInstituto(resultado.getInt("instituto_Id_Instituto"));
usuario.setLogin(resultado.getString("usuario"));
usuario.setNome(resultado.getString("nome"));
usuario.setSenha(resultado.getString("senha"));
usuarios.add(usuario);
}
return usuarios;
} catch (SQLException ex) {
Logger.getLogger(InstitutoDAO.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
public UsuarioBean buscar(String login){
try {
Connection conexao = Conexao.getConexao();
String logon = "'"+
login+ "'";
// System.out.println(logon);
String sql = "select * from usuario u where u.usuario = "+logon;
java.sql.PreparedStatement ps =conexao.prepareStatement(sql);
ResultSet resultado = ps.executeQuery();
UsuarioBean usuario = new UsuarioBean();
while(resultado.next()){
if(resultado.getString("usuario").equals(login)){
usuario.setAdm(resultado.getBoolean("adm"));
usuario.setCargo(resultado.getString("cargo"));
usuario.setConfirmaSenha(resultado.getString("confirmaSenha"));
usuario.setCpf(resultado.getString("cpf"));
usuario.setEmail(resultado.getString("email"));
usuario.setInstituto(resultado.getInt("instituto_Id_Instituto"));
usuario.setLogin(resultado.getString("usuario"));
usuario.setNome(resultado.getString("nome"));
usuario.setSenha(resultado.getString("senha"));
}
}
return usuario;
} catch (SQLException ex) {
Logger.getLogger(InstitutoDAO.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}
| 4,497 | 0.597865 | 0.59653 | 107 | 41.018692 | 29.075788 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.869159 | false | false | 14 |
e95817276f9d524367ae1b25a828a6dd815cc80f | 23,063,974,384,288 | 5e393191c7556b583c30a73ccfe62545e76b3404 | /server/test/repository/ApiKeyRepositoryTest.java | fe06f64d1c7f4f0b09cc2a909fbddee2471bf5ec | [
"CC0-1.0",
"Apache-2.0"
] | permissive | seattle-uat/universal-application-tool | https://github.com/seattle-uat/universal-application-tool | aff0f8a0834b2ecf2105caa68a3c21d131cf1e9e | 8a7cfa79adffb98cb7051dd41c6e825387cf7493 | refs/heads/main | 2023-03-20T02:21:14.572000 | 2023-03-17T22:57:48 | 2023-03-17T22:57:48 | 327,165,048 | 9 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null | package repository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import auth.ApiKeyGrants;
import io.ebean.DataIntegrityException;
import java.time.Instant;
import java.util.concurrent.CompletionException;
import models.ApiKey;
import org.junit.Before;
import org.junit.Test;
public class ApiKeyRepositoryTest extends ResetPostgres {
private ApiKeyRepository repo;
@Before
public void setUp() {
repo = instanceOf(ApiKeyRepository.class);
}
@Test
public void insert_persistsANewKey() {
ApiKey foundKey;
ApiKeyGrants grants = new ApiKeyGrants();
grants.grantProgramPermission("program-a", ApiKeyGrants.Permission.READ);
ApiKey apiKey = new ApiKey(grants);
apiKey
.setName("key name")
.setKeyId("key-id")
.setCreatedBy("test@example.com")
.setSaltedKeySecret("secret")
.setSubnet("0.0.0.0/32")
.setExpiration(Instant.ofEpochSecond(100));
ApiKeyRepository repo = instanceOf(ApiKeyRepository.class);
repo.insert(apiKey).toCompletableFuture().join();
long id = apiKey.id;
foundKey = repo.lookupApiKey(id).toCompletableFuture().join().get();
assertThat(foundKey.id).isEqualTo(id);
foundKey = repo.lookupApiKey("key-id").toCompletableFuture().join().get();
assertThat(foundKey.id).isEqualTo(id);
assertThat(foundKey.getName()).isEqualTo("key name");
assertThat(foundKey.getKeyId()).isEqualTo("key-id");
assertThat(foundKey.getCreatedBy()).isEqualTo("test@example.com");
assertThat(foundKey.getSaltedKeySecret()).isEqualTo("secret");
assertThat(foundKey.getSubnet()).isEqualTo("0.0.0.0/32");
assertThat(foundKey.getExpiration()).isEqualTo(Instant.ofEpochSecond(100));
assertThat(foundKey.getGrants().hasProgramPermission("program-a", ApiKeyGrants.Permission.READ))
.isTrue();
}
@Test
public void insert_missingRequiredAttributes_raisesAnException() {
ApiKeyGrants grants = new ApiKeyGrants();
ApiKey apiKey = new ApiKey(grants);
assertThatThrownBy(() -> repo.insert(apiKey).toCompletableFuture().join())
.isInstanceOf(CompletionException.class)
.cause()
.isInstanceOf(DataIntegrityException.class)
.hasMessageContaining("violates not-null constraint");
}
}
| UTF-8 | Java | 2,339 | java | ApiKeyRepositoryTest.java | Java | [
{
"context": " .setKeyId(\"key-id\")\n .setCreatedBy(\"test@example.com\")\n .setSaltedKeySecret(\"secret\")\n .",
"end": 879,
"score": 0.9999209642410278,
"start": 863,
"tag": "EMAIL",
"value": "test@example.com"
},
{
"context": " assertThat(foundKey.get... | null | [] | package repository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import auth.ApiKeyGrants;
import io.ebean.DataIntegrityException;
import java.time.Instant;
import java.util.concurrent.CompletionException;
import models.ApiKey;
import org.junit.Before;
import org.junit.Test;
public class ApiKeyRepositoryTest extends ResetPostgres {
private ApiKeyRepository repo;
@Before
public void setUp() {
repo = instanceOf(ApiKeyRepository.class);
}
@Test
public void insert_persistsANewKey() {
ApiKey foundKey;
ApiKeyGrants grants = new ApiKeyGrants();
grants.grantProgramPermission("program-a", ApiKeyGrants.Permission.READ);
ApiKey apiKey = new ApiKey(grants);
apiKey
.setName("key name")
.setKeyId("key-id")
.setCreatedBy("<EMAIL>")
.setSaltedKeySecret("secret")
.setSubnet("0.0.0.0/32")
.setExpiration(Instant.ofEpochSecond(100));
ApiKeyRepository repo = instanceOf(ApiKeyRepository.class);
repo.insert(apiKey).toCompletableFuture().join();
long id = apiKey.id;
foundKey = repo.lookupApiKey(id).toCompletableFuture().join().get();
assertThat(foundKey.id).isEqualTo(id);
foundKey = repo.lookupApiKey("key-id").toCompletableFuture().join().get();
assertThat(foundKey.id).isEqualTo(id);
assertThat(foundKey.getName()).isEqualTo("key name");
assertThat(foundKey.getKeyId()).isEqualTo("key-id");
assertThat(foundKey.getCreatedBy()).isEqualTo("<EMAIL>");
assertThat(foundKey.getSaltedKeySecret()).isEqualTo("secret");
assertThat(foundKey.getSubnet()).isEqualTo("0.0.0.0/32");
assertThat(foundKey.getExpiration()).isEqualTo(Instant.ofEpochSecond(100));
assertThat(foundKey.getGrants().hasProgramPermission("program-a", ApiKeyGrants.Permission.READ))
.isTrue();
}
@Test
public void insert_missingRequiredAttributes_raisesAnException() {
ApiKeyGrants grants = new ApiKeyGrants();
ApiKey apiKey = new ApiKey(grants);
assertThatThrownBy(() -> repo.insert(apiKey).toCompletableFuture().join())
.isInstanceOf(CompletionException.class)
.cause()
.isInstanceOf(DataIntegrityException.class)
.hasMessageContaining("violates not-null constraint");
}
}
| 2,321 | 0.723814 | 0.716118 | 68 | 33.39706 | 26.231514 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529412 | false | false | 14 |
db543592aecac921daabc6a00f29d7b3d966ce01 | 9,998,683,925,659 | f8320bba421f7deef8f1442145381dc1379377ab | /app/models/geo/GeometryCollection.java | 0daaf2bfc75981ea32eb61e4a624df44cb298980 | [
"Apache-2.0"
] | permissive | midas-isg/ls | https://github.com/midas-isg/ls | ef4dcf17f82e80b51e72e35a014a3e16584a8faa | 04ad56f7d3a3fbce99364354f3fea36a40890cda | refs/heads/master | 2020-05-21T13:48:08.272000 | 2019-04-11T21:08:48 | 2019-04-11T21:08:48 | 60,782,964 | 2 | 0 | NOASSERTION | false | 2019-04-11T21:08:49 | 2016-06-09T14:55:33 | 2019-03-29T21:28:23 | 2019-04-11T21:08:49 | 44,293 | 2 | 0 | 16 | JavaScript | false | false | package models.geo;
import java.util.List;
public class GeometryCollection extends FeatureGeometry {
private List<FeatureGeometry> geometries;
public GeometryCollection() {
setType(GeometryCollection.class.getSimpleName());
return;
}
public List<FeatureGeometry> getGeometries() {
return geometries;
}
public void setGeometries(List<FeatureGeometry> geometries) {
this.geometries = geometries;
return;
}
@Override
public String toString() {
return "GeometryCollection (" + geometries.size() + " Polygon/s)";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((geometries == null) ? 0 : geometries.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GeometryCollection other = (GeometryCollection) obj;
if (geometries == null) {
if (other.geometries != null)
return false;
} else if (!geometries.equals(other.geometries))
return true; // false; TODO why geometries are not equal
return true;
}
}
| UTF-8 | Java | 1,167 | java | GeometryCollection.java | Java | [] | null | [] | package models.geo;
import java.util.List;
public class GeometryCollection extends FeatureGeometry {
private List<FeatureGeometry> geometries;
public GeometryCollection() {
setType(GeometryCollection.class.getSimpleName());
return;
}
public List<FeatureGeometry> getGeometries() {
return geometries;
}
public void setGeometries(List<FeatureGeometry> geometries) {
this.geometries = geometries;
return;
}
@Override
public String toString() {
return "GeometryCollection (" + geometries.size() + " Polygon/s)";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((geometries == null) ? 0 : geometries.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GeometryCollection other = (GeometryCollection) obj;
if (geometries == null) {
if (other.geometries != null)
return false;
} else if (!geometries.equals(other.geometries))
return true; // false; TODO why geometries are not equal
return true;
}
}
| 1,167 | 0.689803 | 0.686375 | 53 | 21.018867 | 19.364908 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.90566 | false | false | 14 |
4b592d1094ad8fdc11118f0367c6960f3ea9c710 | 33,122,787,800,104 | 0e775a708f97082322c2a41be2700928980ed2e4 | /CodeSnippets/Java/Strings/StringCheck.java | a04b7b78562fbd509317f7474de5edebce85ade3 | [] | no_license | shahhardik/Repo | https://github.com/shahhardik/Repo | 6257278cc8370cf8a220602d1200f19f201dde10 | d2cbbf3a90f7e4a39e42990038c3e97d40a550cd | refs/heads/master | 2023-03-23T02:58:21.073000 | 2021-03-11T19:16:54 | 2021-03-11T19:16:54 | 241,337,259 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package in.shahhardik;
import java.text.Collator;
public class StringCheck {
public static void main(String args[]) {
Collator collator = Collator.getInstance();
String a = "Hello";
String b = "Hello";
String c = new String("Hello");
String d = new String("Hello");
System.out.println(a==b);
System.out.println(b==c);
System.out.println(c==d);
System.out.println(a==d);
System.out.println(b==d);
System.out.println("**************");
System.out.println(System.identityHashCode(a));
System.out.println(System.identityHashCode(b));
System.out.println(System.identityHashCode(c));
System.out.println(System.identityHashCode(d));
System.out.println(System.identityHashCode(c.intern()));
System.out.println("**************");
System.out.println(a.equals(b));
System.out.println(b.equals(c));
System.out.println(c.equals(d));
System.out.println(a.equals(d));
System.out.println(b.equals(d));
System.out.println("**************");
System.out.println(a.compareTo(b));
System.out.println(b.compareTo(c));
System.out.println(c.compareTo(d));
System.out.println(a.compareTo(d));
System.out.println(b.compareTo(d));
System.out.println("**************");
System.out.println(collator.compare(a,b));
System.out.println(collator.compare(b,c));
System.out.println(collator.compare(c,d));
System.out.println(collator.compare(a,d));
System.out.println(collator.compare(b,d));
}
}
| UTF-8 | Java | 1,653 | java | StringCheck.java | Java | [] | null | [] | package in.shahhardik;
import java.text.Collator;
public class StringCheck {
public static void main(String args[]) {
Collator collator = Collator.getInstance();
String a = "Hello";
String b = "Hello";
String c = new String("Hello");
String d = new String("Hello");
System.out.println(a==b);
System.out.println(b==c);
System.out.println(c==d);
System.out.println(a==d);
System.out.println(b==d);
System.out.println("**************");
System.out.println(System.identityHashCode(a));
System.out.println(System.identityHashCode(b));
System.out.println(System.identityHashCode(c));
System.out.println(System.identityHashCode(d));
System.out.println(System.identityHashCode(c.intern()));
System.out.println("**************");
System.out.println(a.equals(b));
System.out.println(b.equals(c));
System.out.println(c.equals(d));
System.out.println(a.equals(d));
System.out.println(b.equals(d));
System.out.println("**************");
System.out.println(a.compareTo(b));
System.out.println(b.compareTo(c));
System.out.println(c.compareTo(d));
System.out.println(a.compareTo(d));
System.out.println(b.compareTo(d));
System.out.println("**************");
System.out.println(collator.compare(a,b));
System.out.println(collator.compare(b,c));
System.out.println(collator.compare(c,d));
System.out.println(collator.compare(a,d));
System.out.println(collator.compare(b,d));
}
}
| 1,653 | 0.586207 | 0.586207 | 52 | 30.788462 | 20.140217 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.788462 | false | false | 14 |
e658279316cd8c243baf8a18662abb485c485964 | 10,831,907,543,553 | 01cd85a66afd7ab37331d65e562b212cbef9effa | /src/StringPair.java | 1797645d8f93db981c82a13364a4a429b2d0a411 | [] | no_license | fwu1/TestJavaHash | https://github.com/fwu1/TestJavaHash | f0b7236aa507e959efe1580396f92c3fa58f2d50 | 6095034895192a0d327dc0334999d9727dc2c0c6 | refs/heads/master | 2020-07-05T04:07:26.043000 | 2014-11-12T00:42:31 | 2014-11-12T00:42:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// a object that uses 2 strings to present,
// not sequence sensitive, not case sensitive
public class StringPair {
String[] values;
StringPair() {
init("","");
}
StringPair(String v1,String v2) {
init(v1,v2);
}
void init(String v1,String v2)
{
values = new String[2];
values[0]=v1;
values[1]=v2;
}
public int hashCode()
{
return values[0].toUpperCase().hashCode()+values[1].toUpperCase().hashCode();
}
public boolean equals(Object obj) {
if(obj instanceof StringPair) {
StringPair gt=(StringPair)obj;
if( values[0].equalsIgnoreCase(gt.values[0]) && values[1].equalsIgnoreCase(gt.values[1]) ||
values[0].equalsIgnoreCase(gt.values[1]) && values[1].equalsIgnoreCase(gt.values[0]) ) {
return true;
}
}
return false;
}
public String toString(){
return values[0]+"/"+values[1];
}
public static void main(String[] args) {
StringPair gt1 = new StringPair("GAAC","C");
System.out.printf("hash 1=%d\n", gt1.hashCode());
StringPair gt2 = new StringPair("c","gaac");
System.out.printf("hash 2=%d\n", gt2.hashCode());
if(gt1.equals(gt2)) {
System.out.printf("Same\n");
}
else
System.out.printf("Different\n");
}
}
| UTF-8 | Java | 1,253 | java | StringPair.java | Java | [] | null | [] |
// a object that uses 2 strings to present,
// not sequence sensitive, not case sensitive
public class StringPair {
String[] values;
StringPair() {
init("","");
}
StringPair(String v1,String v2) {
init(v1,v2);
}
void init(String v1,String v2)
{
values = new String[2];
values[0]=v1;
values[1]=v2;
}
public int hashCode()
{
return values[0].toUpperCase().hashCode()+values[1].toUpperCase().hashCode();
}
public boolean equals(Object obj) {
if(obj instanceof StringPair) {
StringPair gt=(StringPair)obj;
if( values[0].equalsIgnoreCase(gt.values[0]) && values[1].equalsIgnoreCase(gt.values[1]) ||
values[0].equalsIgnoreCase(gt.values[1]) && values[1].equalsIgnoreCase(gt.values[0]) ) {
return true;
}
}
return false;
}
public String toString(){
return values[0]+"/"+values[1];
}
public static void main(String[] args) {
StringPair gt1 = new StringPair("GAAC","C");
System.out.printf("hash 1=%d\n", gt1.hashCode());
StringPair gt2 = new StringPair("c","gaac");
System.out.printf("hash 2=%d\n", gt2.hashCode());
if(gt1.equals(gt2)) {
System.out.printf("Same\n");
}
else
System.out.printf("Different\n");
}
}
| 1,253 | 0.616121 | 0.590583 | 55 | 20.745455 | 22.873739 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.036364 | false | false | 14 |
315583813dc1102e507b6e48166823ec6f965fb8 | 6,210,522,710,865 | ff7ab42ffac7d8cdc1520b3899bb5c60136e3664 | /src/com/gbg/util/HostPageNavigation.java | 789345ba9e69efcba001e51056c8f87686aef7a2 | [] | no_license | didhomin/gabogga | https://github.com/didhomin/gabogga | 5a78363a12bfdbad4bddda46dd95b669ddc29532 | 51c1c0a53d97304a84f8e1945b39e334a7c82306 | refs/heads/master | 2021-01-01T16:22:12.789000 | 2017-08-12T13:42:55 | 2017-08-12T13:42:55 | 97,813,796 | 5 | 2 | null | false | 2017-07-23T17:00:58 | 2017-07-20T08:59:03 | 2017-07-21T03:58:22 | 2017-07-23T17:00:57 | 2,967 | 1 | 0 | 0 | Java | null | null | package com.gbg.util;
public class HostPageNavigation {
private String root;
private boolean nowFirst;// 이전관리
private boolean nowEnd;// 다음관리
private int newArticleCount;// 새글수
private int totalArticleCount;// 전체글수
private int totalPageCount;// 전체페이지수
private int pageNo;// 현재페이지
private String navigator;// 페이징
public String getRoot() {
return root;
}
public void setRoot(String root) {
this.root = root;
}
public boolean isNowFirst() {
return nowFirst;
}
public void setNowFirst(boolean nowFirst) {
this.nowFirst = nowFirst;
}
public boolean isNowEnd() {
return nowEnd;
}
public void setNowEnd(boolean nowEnd) {
this.nowEnd = nowEnd;
}
public int getNewArticleCount() {
return newArticleCount;
}
public void setNewArticleCount(int newArticleCount) {
this.newArticleCount = newArticleCount;
}
public int getTotalArticleCount() {
return totalArticleCount;
}
public void setTotalArticleCount(int totalArticleCount) {
this.totalArticleCount = totalArticleCount;
}
public int getTotalPageCount() {
return totalPageCount;
}
public void setTotalPageCount(int totalPageCount) {
this.totalPageCount = totalPageCount;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public String getNavigator() {
return navigator;
}
public void setNavigator() {
StringBuffer tmpNavigator = new StringBuffer();
int prePage = (pageNo - 1) / BoardConstance.PAGE_SIZE * BoardConstance.PAGE_SIZE;
tmpNavigator.append("<navv align="+"center"+">\n");
tmpNavigator.append(" <ul class="+"pagination"+">\n");
if (this.isNowFirst()) {
tmpNavigator.append(" <li class="+"page-item disabled"+">\n");
tmpNavigator.append(" <a class="+"page-link"+" href="+"#"+" tabindex="+-1+" aria-label="+"Previous"+">\n");
tmpNavigator.append(" <span aria-hidden="+true+">«</span>\n");
tmpNavigator.append(" </a></li>\n");
} else {
tmpNavigator.append(" <li class="+"page-item disabled"+">\n");
tmpNavigator.append(" <a class="+"page-link"+" href='javascript:firstArticle();' tabindex="+-1+" aria-label="+"Previous"+">\n");
tmpNavigator.append(" <span aria-hidden="+true+">«</span>\n");
tmpNavigator.append(" </a></li>\n");
}
int startPage = prePage + 1;
int endPage = startPage + (BoardConstance.PAGE_SIZE - 1);
if(endPage > totalPageCount)
endPage = totalPageCount;
for (int i = startPage; i <= endPage; i++) {
if (pageNo == i) {
tmpNavigator.append(" <li class="+"page-item"+"><a class="+"page-link"+">"+i+"</a></li>" +"\n");
} else {
tmpNavigator.append(" <li class="+"page-item"+"><a class="+"page-link"+" href='javascript:page(" + i + ");'>"+i+"</a></li>" +"\n");
}
}
if (this.isNowEnd()) {
tmpNavigator.append(" <li class="+"page-item"+">\n");
tmpNavigator.append(" <a class="+"page-link"+" href="+"#"+" aria-label="+"Next"+">\n");
tmpNavigator.append(" <span aria-hidden="+true+">»</span>\n");
tmpNavigator.append(" </a>\n");
tmpNavigator.append(" </li>\n");
} else {
int nextPage = prePage + BoardConstance.PAGE_SIZE + 1;
tmpNavigator.append(" <li class="+"page-item"+">\n");
tmpNavigator.append(" <a class="+"page-link"+" href='javascript:page(" + nextPage + ");' aria-label="+"Next"+">\n");
tmpNavigator.append(" <span aria-hidden="+true+">»</span>\n");
tmpNavigator.append(" </a>\n");
tmpNavigator.append(" </li>\n");
}
tmpNavigator.append(" </ul>\n");
tmpNavigator.append(" </navv>\n");
this.navigator = tmpNavigator.toString();
}
} | UTF-8 | Java | 4,516 | java | HostPageNavigation.java | Java | [] | null | [] | package com.gbg.util;
public class HostPageNavigation {
private String root;
private boolean nowFirst;// 이전관리
private boolean nowEnd;// 다음관리
private int newArticleCount;// 새글수
private int totalArticleCount;// 전체글수
private int totalPageCount;// 전체페이지수
private int pageNo;// 현재페이지
private String navigator;// 페이징
public String getRoot() {
return root;
}
public void setRoot(String root) {
this.root = root;
}
public boolean isNowFirst() {
return nowFirst;
}
public void setNowFirst(boolean nowFirst) {
this.nowFirst = nowFirst;
}
public boolean isNowEnd() {
return nowEnd;
}
public void setNowEnd(boolean nowEnd) {
this.nowEnd = nowEnd;
}
public int getNewArticleCount() {
return newArticleCount;
}
public void setNewArticleCount(int newArticleCount) {
this.newArticleCount = newArticleCount;
}
public int getTotalArticleCount() {
return totalArticleCount;
}
public void setTotalArticleCount(int totalArticleCount) {
this.totalArticleCount = totalArticleCount;
}
public int getTotalPageCount() {
return totalPageCount;
}
public void setTotalPageCount(int totalPageCount) {
this.totalPageCount = totalPageCount;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public String getNavigator() {
return navigator;
}
public void setNavigator() {
StringBuffer tmpNavigator = new StringBuffer();
int prePage = (pageNo - 1) / BoardConstance.PAGE_SIZE * BoardConstance.PAGE_SIZE;
tmpNavigator.append("<navv align="+"center"+">\n");
tmpNavigator.append(" <ul class="+"pagination"+">\n");
if (this.isNowFirst()) {
tmpNavigator.append(" <li class="+"page-item disabled"+">\n");
tmpNavigator.append(" <a class="+"page-link"+" href="+"#"+" tabindex="+-1+" aria-label="+"Previous"+">\n");
tmpNavigator.append(" <span aria-hidden="+true+">«</span>\n");
tmpNavigator.append(" </a></li>\n");
} else {
tmpNavigator.append(" <li class="+"page-item disabled"+">\n");
tmpNavigator.append(" <a class="+"page-link"+" href='javascript:firstArticle();' tabindex="+-1+" aria-label="+"Previous"+">\n");
tmpNavigator.append(" <span aria-hidden="+true+">«</span>\n");
tmpNavigator.append(" </a></li>\n");
}
int startPage = prePage + 1;
int endPage = startPage + (BoardConstance.PAGE_SIZE - 1);
if(endPage > totalPageCount)
endPage = totalPageCount;
for (int i = startPage; i <= endPage; i++) {
if (pageNo == i) {
tmpNavigator.append(" <li class="+"page-item"+"><a class="+"page-link"+">"+i+"</a></li>" +"\n");
} else {
tmpNavigator.append(" <li class="+"page-item"+"><a class="+"page-link"+" href='javascript:page(" + i + ");'>"+i+"</a></li>" +"\n");
}
}
if (this.isNowEnd()) {
tmpNavigator.append(" <li class="+"page-item"+">\n");
tmpNavigator.append(" <a class="+"page-link"+" href="+"#"+" aria-label="+"Next"+">\n");
tmpNavigator.append(" <span aria-hidden="+true+">»</span>\n");
tmpNavigator.append(" </a>\n");
tmpNavigator.append(" </li>\n");
} else {
int nextPage = prePage + BoardConstance.PAGE_SIZE + 1;
tmpNavigator.append(" <li class="+"page-item"+">\n");
tmpNavigator.append(" <a class="+"page-link"+" href='javascript:page(" + nextPage + ");' aria-label="+"Next"+">\n");
tmpNavigator.append(" <span aria-hidden="+true+">»</span>\n");
tmpNavigator.append(" </a>\n");
tmpNavigator.append(" </li>\n");
}
tmpNavigator.append(" </ul>\n");
tmpNavigator.append(" </navv>\n");
this.navigator = tmpNavigator.toString();
}
} | 4,516 | 0.524899 | 0.523553 | 128 | 32.84375 | 31.390295 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 14 |
d71a7f728f01dcda03e9dea26566fb893bb16c19 | 21,835,613,784,310 | 67f1cfb838914b0c19bbdfd2bbcd873d2a922da9 | /src/main/java/com/pruebapost/dummy/restController/DummyRestController.java | b7c72959dc589400747f8e183edf30ba11cb3773 | [] | no_license | SoniaGama/mockTest | https://github.com/SoniaGama/mockTest | 957a0e52377def34cc8ae1c18a291a76fab5f2d8 | 4f4fb0b5a287ac8768268b1fe885dc0a21a1cd4a | refs/heads/master | 2020-06-23T10:21:18.966000 | 2019-07-24T09:09:02 | 2019-07-24T09:09:02 | 198,595,576 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pruebapost.dummy.restController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.pruebapost.dummy.model.ModelEntity;
@RestController
public class DummyRestController {
@RequestMapping(method = RequestMethod.POST, value = "/entity")
@ResponseStatus(value = HttpStatus.OK)
public String entity(@RequestParam(value = "postTest", required = true) @RequestBody ModelEntity entity) {
return "respuesta dummy de test post C:";
}
}
| UTF-8 | Java | 826 | java | DummyRestController.java | Java | [] | null | [] | package com.pruebapost.dummy.restController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.pruebapost.dummy.model.ModelEntity;
@RestController
public class DummyRestController {
@RequestMapping(method = RequestMethod.POST, value = "/entity")
@ResponseStatus(value = HttpStatus.OK)
public String entity(@RequestParam(value = "postTest", required = true) @RequestBody ModelEntity entity) {
return "respuesta dummy de test post C:";
}
}
| 826 | 0.820823 | 0.820823 | 22 | 36.545456 | 29.506128 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.818182 | false | false | 14 |
60545e3eecfd863db3cbffd4709346d17cf8cbf4 | 21,423,296,874,135 | d921b5e532529792838dce21647411f9bfa0fa0f | /WeX5/src/main/java/com/zlzkj/app/util/ExcelTransport.java | f12276e078f1739de3bd0433cbabe73aae1dd9f0 | [] | no_license | jijianfeng/WeX5 | https://github.com/jijianfeng/WeX5 | 207182547942d956742cf73e04523b56a34059b9 | 8cc56993700acd1e5324baaab503fcfea64f907d | refs/heads/master | 2020-12-25T13:34:15.440000 | 2017-02-20T12:20:36 | 2017-02-20T12:20:36 | 61,274,041 | 3 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zlzkj.app.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.zlzkj.core.sql.Row;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class ExcelTransport {
/**
* Read data from a excel file
*/
public static List<Object> readExcel(String excelFileName, int sheetNum, String keys){
Workbook workbook = null;
try {
workbook = Workbook.getWorkbook(new File(excelFileName));
} catch (Exception e) {
}
Sheet sheet = workbook.getSheet(sheetNum);
Cell cell = null;
int number = sheet.getColumns();//列数
//System.out.println("列数:"+number);
int rowCount=sheet.getRows();
//System.out.println("行数"+rowCount);
String[] key = keys.split(",");
if(number!=key.length){
return null;
}
// System.out.println(key.length+"keylength");
// System.out.println("key::"+key[1]);
List<Object> list = new ArrayList<Object>();
for (int i = 1; i <rowCount; i++) {
Map dbo = new HashMap();
for (int j = 0; j <key.length; j++) {
// System.out.println(j+":::"+i);
cell=sheet.getCell(j, i);
//System.out.println(cell.getContents()+"嵇建峰");
if(j==0&&cell.getContents().equals("")){
System.out.println(cell.getContents()+"嵇建峰");
break;
}
dbo.put(key[j], (cell.getContents()));
}
if(dbo.size()!=0){
list.add(dbo);
}
}
workbook.close();
return list;
}
/**
* 创建一个Excel文件
* @param excelFileName Excel文件名
* @param sheetName Excel页名
* @param headerNames 标题名(用逗号分隔)
* @param keys 键名(用逗号分隔)
* @param list 数据
* @return
* @throws Exception
*/
public static void createMainExcelFile(String excelFileName, String sheetName, String headerNames, String keys, List<Row> list) throws Exception{
String filePath = "D:\\" + excelFileName;
File file = new File(filePath);
try{
WritableWorkbook wwb = Workbook.createWorkbook(file);
WritableSheet ws = wwb.createSheet(sheetName,0);
String[] aheaderName = headerNames.split(",");
String[] akey = keys.split(",");
if(akey.length != aheaderName.length)
throw new CustomerException("键名个数和标题个数必须一样!");
for(int col = 0; col < aheaderName.length; col++){
Label header = new Label(col, 0, aheaderName[col]);
ws.addCell(header);
}
try {
for(int row=0; row<list.size(); row++)
{
Map obj = (Map) list.get(row);
for(int col=0; col<akey.length; col++)
{
Label body = new Label(col, row+1, StringUtil.objectToString(obj.get(akey[col])));
ws.addCell(body);
}
}
} catch (Exception e) {
e.printStackTrace();
}
wwb.write();
wwb.close();
}catch(IOException e){
e.printStackTrace();
}
catch(WriteException e){
e.printStackTrace();
}
}
public static void main(String args[]){
String file = "M:\\tomcat\\webapps\\Thesis\\file\\20150810\\venjligcMF_!!23552.xls";
List<Object> list = readExcel(file,0,"论文标题,论文编号,要求返回时间,论文类型,论文文件名");
System.out.println(list.toString());
}
}
| UTF-8 | Java | 3,780 | java | ExcelTransport.java | Java | [] | null | [] | package com.zlzkj.app.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.zlzkj.core.sql.Row;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class ExcelTransport {
/**
* Read data from a excel file
*/
public static List<Object> readExcel(String excelFileName, int sheetNum, String keys){
Workbook workbook = null;
try {
workbook = Workbook.getWorkbook(new File(excelFileName));
} catch (Exception e) {
}
Sheet sheet = workbook.getSheet(sheetNum);
Cell cell = null;
int number = sheet.getColumns();//列数
//System.out.println("列数:"+number);
int rowCount=sheet.getRows();
//System.out.println("行数"+rowCount);
String[] key = keys.split(",");
if(number!=key.length){
return null;
}
// System.out.println(key.length+"keylength");
// System.out.println("key::"+key[1]);
List<Object> list = new ArrayList<Object>();
for (int i = 1; i <rowCount; i++) {
Map dbo = new HashMap();
for (int j = 0; j <key.length; j++) {
// System.out.println(j+":::"+i);
cell=sheet.getCell(j, i);
//System.out.println(cell.getContents()+"嵇建峰");
if(j==0&&cell.getContents().equals("")){
System.out.println(cell.getContents()+"嵇建峰");
break;
}
dbo.put(key[j], (cell.getContents()));
}
if(dbo.size()!=0){
list.add(dbo);
}
}
workbook.close();
return list;
}
/**
* 创建一个Excel文件
* @param excelFileName Excel文件名
* @param sheetName Excel页名
* @param headerNames 标题名(用逗号分隔)
* @param keys 键名(用逗号分隔)
* @param list 数据
* @return
* @throws Exception
*/
public static void createMainExcelFile(String excelFileName, String sheetName, String headerNames, String keys, List<Row> list) throws Exception{
String filePath = "D:\\" + excelFileName;
File file = new File(filePath);
try{
WritableWorkbook wwb = Workbook.createWorkbook(file);
WritableSheet ws = wwb.createSheet(sheetName,0);
String[] aheaderName = headerNames.split(",");
String[] akey = keys.split(",");
if(akey.length != aheaderName.length)
throw new CustomerException("键名个数和标题个数必须一样!");
for(int col = 0; col < aheaderName.length; col++){
Label header = new Label(col, 0, aheaderName[col]);
ws.addCell(header);
}
try {
for(int row=0; row<list.size(); row++)
{
Map obj = (Map) list.get(row);
for(int col=0; col<akey.length; col++)
{
Label body = new Label(col, row+1, StringUtil.objectToString(obj.get(akey[col])));
ws.addCell(body);
}
}
} catch (Exception e) {
e.printStackTrace();
}
wwb.write();
wwb.close();
}catch(IOException e){
e.printStackTrace();
}
catch(WriteException e){
e.printStackTrace();
}
}
public static void main(String args[]){
String file = "M:\\tomcat\\webapps\\Thesis\\file\\20150810\\venjligcMF_!!23552.xls";
List<Object> list = readExcel(file,0,"论文标题,论文编号,要求返回时间,论文类型,论文文件名");
System.out.println(list.toString());
}
}
| 3,780 | 0.587894 | 0.580984 | 124 | 27.17742 | 22.301832 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.572581 | false | false | 14 |
b5777174629bee30512760b5cb3e818e7cc7cb9a | 24,129,126,336,918 | b938c48135c0d35267f7941e8da41a4a1605e54f | /app/src/main/java/com/edomar/battleship/engines/BattleFieldBroadcaster.java | 23176c638432f99588019581fcb0cff6be480385 | [] | no_license | EdoardoMarchetti/BattleShip | https://github.com/EdoardoMarchetti/BattleShip | 5759dd9e165f7df134ba0437bc30978f1cc9683a | 33a80c139ef97a8444f963483de1b1fefd573447 | refs/heads/main | 2022-12-28T23:27:47.384000 | 2022-08-23T15:55:36 | 2022-08-23T15:55:36 | 305,448,825 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.edomar.battleship.engines;
import com.edomar.battleship.entities.InputObserver;
public interface BattleFieldBroadcaster {
void addObserver(InputObserver o);
}
| UTF-8 | Java | 178 | java | BattleFieldBroadcaster.java | Java | [] | null | [] | package com.edomar.battleship.engines;
import com.edomar.battleship.entities.InputObserver;
public interface BattleFieldBroadcaster {
void addObserver(InputObserver o);
}
| 178 | 0.814607 | 0.814607 | 8 | 21.25 | 21.393633 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 14 |
62d4da4202be1890e26bbdd43ac5219aee72b003 | 29,446,295,783,690 | 12722bec9e357a8c6748d1694f5e540585a110e7 | /src/main/java/com/windf/module/priority/service/impl/MenuServiceImpl.java | f3fc37809cddd3c5348c6666ae2ed16ad37cdf5b | [] | no_license | windfChen/windf | https://github.com/windfChen/windf | eeb2e27e666f98a5184a7ff712878d3caae94586 | 68ffe0d309446c7d001304826abd8bfab7f4f9fb | refs/heads/master | 2021-01-01T04:32:12.165000 | 2017-10-10T09:02:46 | 2017-10-10T09:02:46 | 97,186,138 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.windf.module.priority.service.impl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.windf.core.util.CollectionUtil;
import com.windf.module.priority.dao.MenuDao;
import com.windf.module.priority.entity.PriorityMenu;
import com.windf.module.priority.entity.vo.MenuVO;
import com.windf.module.priority.service.MenuService;
@Service
public class MenuServiceImpl implements MenuService {
@Resource
private MenuDao menuDao;
@Override
public List<MenuVO> findChildrenTree(Integer id) {
return findChildrenSubTree(id);
}
/**
* 递归查询
* @param id
* @return
*/
private List<MenuVO> findChildrenSubTree(Integer id) {
// 查询直接子节点
List<PriorityMenu> menuList = menuDao.findChildren(id);
/*
* 构建树,递归查询
*/
List<MenuVO> result = new ArrayList<MenuVO>();
for (PriorityMenu m : menuList) {
MenuVO menuVO = new MenuVO();
menuVO.setId(m.getId());
menuVO.setCode(m.getCode());
menuVO.setText(m.getName());
menuVO.setSort(m.getSort());
menuVO.setUrl(m.getUrl());
List<MenuVO> menuVoList = findChildrenSubTree(m.getId());
if (CollectionUtil.isEmpty(menuVoList)) {
menuVO.setLeaf(true);
} else {
menuVO.setChildren(menuVoList);
menuVO.setLeaf(false);
}
result.add(menuVO);
}
return result;
}
}
| UTF-8 | Java | 1,487 | java | MenuServiceImpl.java | Java | [] | null | [] | package com.windf.module.priority.service.impl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.windf.core.util.CollectionUtil;
import com.windf.module.priority.dao.MenuDao;
import com.windf.module.priority.entity.PriorityMenu;
import com.windf.module.priority.entity.vo.MenuVO;
import com.windf.module.priority.service.MenuService;
@Service
public class MenuServiceImpl implements MenuService {
@Resource
private MenuDao menuDao;
@Override
public List<MenuVO> findChildrenTree(Integer id) {
return findChildrenSubTree(id);
}
/**
* 递归查询
* @param id
* @return
*/
private List<MenuVO> findChildrenSubTree(Integer id) {
// 查询直接子节点
List<PriorityMenu> menuList = menuDao.findChildren(id);
/*
* 构建树,递归查询
*/
List<MenuVO> result = new ArrayList<MenuVO>();
for (PriorityMenu m : menuList) {
MenuVO menuVO = new MenuVO();
menuVO.setId(m.getId());
menuVO.setCode(m.getCode());
menuVO.setText(m.getName());
menuVO.setSort(m.getSort());
menuVO.setUrl(m.getUrl());
List<MenuVO> menuVoList = findChildrenSubTree(m.getId());
if (CollectionUtil.isEmpty(menuVoList)) {
menuVO.setLeaf(true);
} else {
menuVO.setChildren(menuVoList);
menuVO.setLeaf(false);
}
result.add(menuVO);
}
return result;
}
}
| 1,487 | 0.68091 | 0.68091 | 63 | 21.031746 | 19.136078 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.904762 | false | false | 14 |
1c0d5f19c31c63a2fd2ce261770f512b672180a8 | 29,446,295,782,355 | 6f2e20e201d5029c5a6d80bf24a4afa19d29c4ea | /IFT1135/Devoir3corneauf/app/src/main/java/com/udem/corneau/devoir3corneauf/ViewClassmatesActivity.java | bec821ba699bef2b939672467b99967fba2ccc1a | [] | no_license | DatCorno/university_homeworks | https://github.com/DatCorno/university_homeworks | 5e1c7ecf6f12b5fb87607ee2eb9e2689e6bbb80e | 7970cbe851c4e726b1e936dc9f538df8741e2b34 | refs/heads/master | 2021-08-23T18:12:57.364000 | 2017-12-06T01:35:06 | 2017-12-06T01:35:06 | 112,354,383 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.udem.corneau.devoir3corneauf;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class ViewClassmatesActivity extends AppCompatActivity {
public final static String NAME_TAG = "NAME";
public final static int GET_NOTE = 1000;
private int[] grades;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_classmates);
//We have three students, so no real need to make it scalable
grades = new int[3];
//Create an adapter that will fill the ListView with the classmates_string_list found in arrays.xml resource file
((ListView)findViewById(R.id.classmates_list_id)).setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.classmates_string_list)));
//Recover the name given by the user and display it
Intent intent = getIntent();
String name = intent.getStringExtra(NAME_TAG);
((TextView)findViewById(R.id.name_textview_id)).setText(name);
//Create an Adapter to handle the items' click inside the ListView
ListView ls = (ListView)findViewById(R.id.classmates_list_id);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(ViewClassmatesActivity.this, ViewClassmateDetailsActivity.class);
intent.putExtra("position", i); //We give the item's position as extra since ViewClassmateDetailsActivity needs it to find its data
startActivityForResult(intent, ViewClassmateDetailsActivity.GET_STUDENT_GRADE_CODE);
}
});
}
public void viewClassmatesBackClick(View view) {
Intent result_intent = new Intent();
//When we return to the MainActivity we need to sum up all grades
int sum = 0;
for(int i : grades)
sum += i;
result_intent.putExtra("grade", sum);
//Add the total to the intent and tell MainActivity we completed succesfuly
setResult(Activity.RESULT_OK, result_intent);
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ViewClassmateDetailsActivity.GET_STUDENT_GRADE_CODE) {
if(resultCode == Activity.RESULT_OK){
int index = data.getIntExtra("index", 0); //Position inside the grade array
int grade = data.getIntExtra("grade", 0); //Value of the given student's grade
grades[index] = grade;
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
}
| UTF-8 | Java | 2,904 | java | ViewClassmatesActivity.java | Java | [] | null | [] | package com.udem.corneau.devoir3corneauf;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class ViewClassmatesActivity extends AppCompatActivity {
public final static String NAME_TAG = "NAME";
public final static int GET_NOTE = 1000;
private int[] grades;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_classmates);
//We have three students, so no real need to make it scalable
grades = new int[3];
//Create an adapter that will fill the ListView with the classmates_string_list found in arrays.xml resource file
((ListView)findViewById(R.id.classmates_list_id)).setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.classmates_string_list)));
//Recover the name given by the user and display it
Intent intent = getIntent();
String name = intent.getStringExtra(NAME_TAG);
((TextView)findViewById(R.id.name_textview_id)).setText(name);
//Create an Adapter to handle the items' click inside the ListView
ListView ls = (ListView)findViewById(R.id.classmates_list_id);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(ViewClassmatesActivity.this, ViewClassmateDetailsActivity.class);
intent.putExtra("position", i); //We give the item's position as extra since ViewClassmateDetailsActivity needs it to find its data
startActivityForResult(intent, ViewClassmateDetailsActivity.GET_STUDENT_GRADE_CODE);
}
});
}
public void viewClassmatesBackClick(View view) {
Intent result_intent = new Intent();
//When we return to the MainActivity we need to sum up all grades
int sum = 0;
for(int i : grades)
sum += i;
result_intent.putExtra("grade", sum);
//Add the total to the intent and tell MainActivity we completed succesfuly
setResult(Activity.RESULT_OK, result_intent);
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ViewClassmateDetailsActivity.GET_STUDENT_GRADE_CODE) {
if(resultCode == Activity.RESULT_OK){
int index = data.getIntExtra("index", 0); //Position inside the grade array
int grade = data.getIntExtra("grade", 0); //Value of the given student's grade
grades[index] = grade;
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
}
| 2,904 | 0.730372 | 0.726584 | 81 | 33.851852 | 33.093998 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.024691 | false | false | 14 |
86ee0d69921d302bbf616a9eab1bbc78c632fa36 | 21,749,714,407,715 | f55580e75aba266281bfc7fa36f81b9dc4277a96 | /src/java/com/planit/smsrenta/modelos/SmsCostosservicios.java | 6c1a097cde5a57c3a62412e59c9f9528fca18f43 | [] | no_license | CristianRestrepo/SMSRenta_Actualizado | https://github.com/CristianRestrepo/SMSRenta_Actualizado | add0b4690406246457dcd8c9070e227db899d53b | 776dcfe4dd7c3dcff988f8cef180c9ec363c687c | refs/heads/master | 2021-01-17T15:14:36.778000 | 2016-10-27T22:49:15 | 2016-10-27T22:49:15 | 52,380,442 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.planit.smsrenta.modelos;
// Generated 02-mar-2016 12:47:17 by Hibernate Tools 4.3.1
/**
* SmsCostosservicios generated by hbm2java
*/
public class SmsCostosservicios implements java.io.Serializable {
private Integer idCostosServicio;
private SmsCategoria smsCategoria;
private SmsLugares smsLugaresByIdLugarInicio;
private SmsLugares smsLugaresByIdLugarDestino;
private SmsServicios smsServicios;
private int costoServicioPrecio;
public SmsCostosservicios() {
this.smsCategoria = new SmsCategoria();
this.smsServicios = new SmsServicios();
this.costoServicioPrecio = 0;
}
public SmsCostosservicios(SmsCategoria smsCategoria, SmsServicios smsServicios, int costoServicioPrecio) {
this.smsCategoria = smsCategoria;
this.smsServicios = smsServicios;
this.costoServicioPrecio = costoServicioPrecio;
}
public SmsCostosservicios(SmsCategoria smsCategoria, SmsLugares smsLugaresByIdLugarInicio, SmsLugares smsLugaresByIdLugarDestino, SmsServicios smsServicios, int costoServicioPrecio) {
this.smsCategoria = smsCategoria;
this.smsLugaresByIdLugarInicio = smsLugaresByIdLugarInicio;
this.smsLugaresByIdLugarDestino = smsLugaresByIdLugarDestino;
this.smsServicios = smsServicios;
this.costoServicioPrecio = costoServicioPrecio;
}
public Integer getIdCostosServicio() {
return this.idCostosServicio;
}
public void setIdCostosServicio(Integer idCostosServicio) {
this.idCostosServicio = idCostosServicio;
}
public SmsCategoria getSmsCategoria() {
return this.smsCategoria;
}
public void setSmsCategoria(SmsCategoria smsCategoria) {
this.smsCategoria = smsCategoria;
}
public SmsLugares getSmsLugaresByIdLugarInicio() {
return this.smsLugaresByIdLugarInicio;
}
public void setSmsLugaresByIdLugarInicio(SmsLugares smsLugaresByIdLugarInicio) {
this.smsLugaresByIdLugarInicio = smsLugaresByIdLugarInicio;
}
public SmsLugares getSmsLugaresByIdLugarDestino() {
return this.smsLugaresByIdLugarDestino;
}
public void setSmsLugaresByIdLugarDestino(SmsLugares smsLugaresByIdLugarDestino) {
this.smsLugaresByIdLugarDestino = smsLugaresByIdLugarDestino;
}
public SmsServicios getSmsServicios() {
return this.smsServicios;
}
public void setSmsServicios(SmsServicios smsServicios) {
this.smsServicios = smsServicios;
}
public int getCostoServicioPrecio() {
return this.costoServicioPrecio;
}
public void setCostoServicioPrecio(int costoServicioPrecio) {
this.costoServicioPrecio = costoServicioPrecio;
}
}
| UTF-8 | Java | 2,781 | java | SmsCostosservicios.java | Java | [] | null | [] | package com.planit.smsrenta.modelos;
// Generated 02-mar-2016 12:47:17 by Hibernate Tools 4.3.1
/**
* SmsCostosservicios generated by hbm2java
*/
public class SmsCostosservicios implements java.io.Serializable {
private Integer idCostosServicio;
private SmsCategoria smsCategoria;
private SmsLugares smsLugaresByIdLugarInicio;
private SmsLugares smsLugaresByIdLugarDestino;
private SmsServicios smsServicios;
private int costoServicioPrecio;
public SmsCostosservicios() {
this.smsCategoria = new SmsCategoria();
this.smsServicios = new SmsServicios();
this.costoServicioPrecio = 0;
}
public SmsCostosservicios(SmsCategoria smsCategoria, SmsServicios smsServicios, int costoServicioPrecio) {
this.smsCategoria = smsCategoria;
this.smsServicios = smsServicios;
this.costoServicioPrecio = costoServicioPrecio;
}
public SmsCostosservicios(SmsCategoria smsCategoria, SmsLugares smsLugaresByIdLugarInicio, SmsLugares smsLugaresByIdLugarDestino, SmsServicios smsServicios, int costoServicioPrecio) {
this.smsCategoria = smsCategoria;
this.smsLugaresByIdLugarInicio = smsLugaresByIdLugarInicio;
this.smsLugaresByIdLugarDestino = smsLugaresByIdLugarDestino;
this.smsServicios = smsServicios;
this.costoServicioPrecio = costoServicioPrecio;
}
public Integer getIdCostosServicio() {
return this.idCostosServicio;
}
public void setIdCostosServicio(Integer idCostosServicio) {
this.idCostosServicio = idCostosServicio;
}
public SmsCategoria getSmsCategoria() {
return this.smsCategoria;
}
public void setSmsCategoria(SmsCategoria smsCategoria) {
this.smsCategoria = smsCategoria;
}
public SmsLugares getSmsLugaresByIdLugarInicio() {
return this.smsLugaresByIdLugarInicio;
}
public void setSmsLugaresByIdLugarInicio(SmsLugares smsLugaresByIdLugarInicio) {
this.smsLugaresByIdLugarInicio = smsLugaresByIdLugarInicio;
}
public SmsLugares getSmsLugaresByIdLugarDestino() {
return this.smsLugaresByIdLugarDestino;
}
public void setSmsLugaresByIdLugarDestino(SmsLugares smsLugaresByIdLugarDestino) {
this.smsLugaresByIdLugarDestino = smsLugaresByIdLugarDestino;
}
public SmsServicios getSmsServicios() {
return this.smsServicios;
}
public void setSmsServicios(SmsServicios smsServicios) {
this.smsServicios = smsServicios;
}
public int getCostoServicioPrecio() {
return this.costoServicioPrecio;
}
public void setCostoServicioPrecio(int costoServicioPrecio) {
this.costoServicioPrecio = costoServicioPrecio;
}
}
| 2,781 | 0.731032 | 0.724919 | 84 | 32.083332 | 31.346834 | 187 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.440476 | false | false | 14 |
5f8161a3a50e753aefc9bbc9981564ae1dcc8d08 | 26,766,236,211,217 | f33b1a05ddc8d411b2348f00267fbba07620d62d | /src/test/java/com/learnautomation/pages/BaseClass.java | 40de829648f7fed9671aa0ea94436d392acefde0 | [] | no_license | sagarroy2709/HybridFrameworkbyMukeshOtwani | https://github.com/sagarroy2709/HybridFrameworkbyMukeshOtwani | ed038777630b1f6fd2af1593b6f233afd96a105e | 97784148a95be9a346a36a18a702f4ea40db0a1d | refs/heads/master | 2022-05-20T20:09:56.774000 | 2020-04-24T12:24:52 | 2020-04-24T12:24:52 | 260,395,792 | 1 | 0 | null | true | 2020-05-01T06:38:37 | 2020-05-01T06:38:36 | 2020-04-24T12:24:55 | 2020-04-24T12:24:52 | 7,551 | 0 | 0 | 0 | null | false | false | package com.learnautomation.pages;
import java.io.IOException;
import javax.naming.spi.DirStateFactory.Result;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.MediaEntityModelProvider;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.learnautomation.utility.BrowserFactory;
import com.learnautomation.utility.ConfigDataProvider;
import com.learnautomation.utility.ExcelDataProvider;
import com.learnautomation.utility.Helper;
public class BaseClass {
public WebDriver driver;
public ExcelDataProvider exeldata;
public ConfigDataProvider confdata;
public ExtentReports reports;
public ExtentTest logger;
@BeforeSuite///All the TestNG Annotation being used and its importance
public void SetupSuite(){
Reporter.log("Setting up the reports and test is getting ready", true);//This is for our reference
exeldata=new ExcelDataProvider();
confdata=new ConfigDataProvider();
ExtentHtmlReporter extent=new ExtentHtmlReporter("./Reports/PrimusBank_"+Helper.getcurrentDateTime()+".html");
reports=new ExtentReports();
reports.attachReporter(extent);
Reporter.log("Settup completed and Test can be started", true);
}
@BeforeClass
public void setup(){
Reporter.log("Starting the browser and application is getting ready", true);
driver=BrowserFactory.start_application(driver,confdata.getBrowser(),confdata.getStagingurl());
Reporter.log("Browser and Application is up and running", true);
}
@AfterMethod
public void teardownmethod(ITestResult result) throws IOException{
Reporter.log("Test is about to end", true);
if(result.getStatus()==ITestResult.FAILURE)
{
//Helper.TakeScreenshot(driver,result.getName());
try {
logger.fail(result.getName()+" Testcase is failed",
MediaEntityBuilder.createScreenCaptureFromPath("."+Helper.TakeScreenshot(driver, result.getName())).build());
} catch (Exception e) {
System.out.println("The screenshot is not available"+e.getMessage());
}
}else
if(result.getStatus()==ITestResult.SUCCESS)
{
logger.pass(result.getName()+" Test is Passed ");
}else
if(result.getStatus()==ITestResult.SKIP)
{
logger.skip(result.getName()+" For somereason the testcase skipped ");
}
reports.flush();
Reporter.log("Test completed and reports are generated ", true);
}
@AfterClass
public void teartown(){
BrowserFactory.stop_application(driver);
}
}
| UTF-8 | Java | 2,854 | java | BaseClass.java | Java | [] | null | [] | package com.learnautomation.pages;
import java.io.IOException;
import javax.naming.spi.DirStateFactory.Result;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.MediaEntityModelProvider;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.learnautomation.utility.BrowserFactory;
import com.learnautomation.utility.ConfigDataProvider;
import com.learnautomation.utility.ExcelDataProvider;
import com.learnautomation.utility.Helper;
public class BaseClass {
public WebDriver driver;
public ExcelDataProvider exeldata;
public ConfigDataProvider confdata;
public ExtentReports reports;
public ExtentTest logger;
@BeforeSuite///All the TestNG Annotation being used and its importance
public void SetupSuite(){
Reporter.log("Setting up the reports and test is getting ready", true);//This is for our reference
exeldata=new ExcelDataProvider();
confdata=new ConfigDataProvider();
ExtentHtmlReporter extent=new ExtentHtmlReporter("./Reports/PrimusBank_"+Helper.getcurrentDateTime()+".html");
reports=new ExtentReports();
reports.attachReporter(extent);
Reporter.log("Settup completed and Test can be started", true);
}
@BeforeClass
public void setup(){
Reporter.log("Starting the browser and application is getting ready", true);
driver=BrowserFactory.start_application(driver,confdata.getBrowser(),confdata.getStagingurl());
Reporter.log("Browser and Application is up and running", true);
}
@AfterMethod
public void teardownmethod(ITestResult result) throws IOException{
Reporter.log("Test is about to end", true);
if(result.getStatus()==ITestResult.FAILURE)
{
//Helper.TakeScreenshot(driver,result.getName());
try {
logger.fail(result.getName()+" Testcase is failed",
MediaEntityBuilder.createScreenCaptureFromPath("."+Helper.TakeScreenshot(driver, result.getName())).build());
} catch (Exception e) {
System.out.println("The screenshot is not available"+e.getMessage());
}
}else
if(result.getStatus()==ITestResult.SUCCESS)
{
logger.pass(result.getName()+" Test is Passed ");
}else
if(result.getStatus()==ITestResult.SKIP)
{
logger.skip(result.getName()+" For somereason the testcase skipped ");
}
reports.flush();
Reporter.log("Test completed and reports are generated ", true);
}
@AfterClass
public void teartown(){
BrowserFactory.stop_application(driver);
}
}
| 2,854 | 0.765592 | 0.765592 | 95 | 29.042105 | 28.286844 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.936842 | false | false | 14 |
3ed50546a606aafa99a338e5d23af3959acaab87 | 25,237,227,898,962 | ac9fb0e69a28cbc580cba64f70dd5799e9e4bd34 | /CrossVal/src/util/Utility.java | 36d158cc648e298de0028f66d953a54f47a7d654 | [] | no_license | prafullasurve/SarcasmSVM | https://github.com/prafullasurve/SarcasmSVM | 5c60879577a72af098db151e02012f6acde74d0e | 35b801433072f79de65f640b2b709576d9e508eb | refs/heads/master | 2016-08-04T04:50:03.249000 | 2013-04-28T06:41:39 | 2013-04-28T06:41:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import stubs.TokenComparator;
import stubs.TokenComparatorCount;
import stubs.TokenDetails;
public class Utility {
public static boolean isDebugging = true;
public static final int optionLines = 1;
public static final int optionString = 2;
public static final String space =" ";
public static final String newLine ="\n";
public static final String emptyLine ="";
public static final String delim = "<delim>";
public static final String positive = "+";
public static final String negative = "-";
public static final double probabilityThreshold = 0.60;
public static final int countThreshold =3;
public static HashMap<String, String> specialSymbolsMap = new HashMap<String,String>();
static
{
init();
}
public static void init()
{
specialSymbolsMap.put(":)", positive);
specialSymbolsMap.put(":')", positive);
specialSymbolsMap.put(":]", positive);
specialSymbolsMap.put(":=)", positive);
specialSymbolsMap.put(":-)", positive);
specialSymbolsMap.put(";)", positive);
specialSymbolsMap.put(";-)", positive);
specialSymbolsMap.put("<3", positive);
specialSymbolsMap.put(":D", positive);
specialSymbolsMap.put(":d", positive);
specialSymbolsMap.put(":-D", positive);
specialSymbolsMap.put("-_-", positive);
specialSymbolsMap.put("=D", positive);
specialSymbolsMap.put(":-*", positive);
specialSymbolsMap.put(":*", positive);
specialSymbolsMap.put(":p", positive);
specialSymbolsMap.put(":P", positive);
specialSymbolsMap.put(":-p", positive);
specialSymbolsMap.put(":-P", positive);
specialSymbolsMap.put(";p", positive);
specialSymbolsMap.put("[P", positive);
specialSymbolsMap.put(";-p", positive);
specialSymbolsMap.put(";-P", positive);
specialSymbolsMap.put("\\m/", positive);
specialSymbolsMap.put("o_v_oxo", positive);
specialSymbolsMap.put(":/", negative);
specialSymbolsMap.put(":-/", negative);
specialSymbolsMap.put(">:o", negative);
specialSymbolsMap.put(">:-o", negative);
specialSymbolsMap.put(":-(", negative);
specialSymbolsMap.put(":(", negative);
specialSymbolsMap.put(":=(", negative);
specialSymbolsMap.put(":[", negative);
}
public static String processToken(String token)
{
if(token == null)
return null;
token = token.toLowerCase();
if(specialSymbolsMap.containsKey(token))
return token;
//if(token.contains("#sarcasm") || token.contains("#sarcastic") || token.startsWith("http:")||token.startsWith("@")|| token.equalsIgnoreCase(""))
//return null;
StringBuilder sb = new StringBuilder();
char[] letters = token.toCharArray();
sb = new StringBuilder();
boolean charActive = false;
for(Character c : letters)
{
if(!isSymbol(c))
{
sb.append(c);
charActive= true;
}
else
{
if(charActive)
sb.append(" ");
charActive = false;
}
}
token = Utility.processForNumericValue(sb.toString().trim());
return token;
}
public static boolean passesSpecificWordTest(String tweet, String word)
{
String tokens [] = tweet.split(space);
for(String token: tokens)
{
if(token.equalsIgnoreCase(word))
return true;
}
return false;
}
public static boolean isSymbol(char c)
{
//following symbols will be ignored
if(c=='"' || c == '?'|| c== '.' || c== ',' || c== '!' || c==':' || c ==';' || c == '-' || c== '(' || c== ')'||c=='/'
|| c=='!' || c=='=' || c=='$' || c=='%' || c== '|' || c== '[' || c==']' || c=='*' || c=='+'||c =='_' || c == '<' || c =='>')
return true;
return false;
}
public static ArrayList<String> readFile(String name)
{
ArrayList<String> sentences = new ArrayList<String>();;
StringBuffer sentence = new StringBuffer();
try{
FileInputStream fileStream = new FileInputStream(name);
DataInputStream inputStream = new DataInputStream(fileStream);
BufferedReader bufferdReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
sentences.clear();
while ((line = bufferdReader.readLine()) != null)
{
sentences.add(line);
}
inputStream.close();
}catch (Exception e){
System.err.print("Could not read file specified:" +name);
System.exit(1);
}
return sentences;
}
public static String getCurrentExecutionPath()
{
return System.getProperty("user.dir");
}
public static void writeFile(String name, ArrayList<String> data)
{
try{
// Create file
//name = getCurrentExecutionPath() +"/"+ name;
System.out.println("Name to print:"+name);
FileWriter fstream = new FileWriter(name);
BufferedWriter out = new BufferedWriter(fstream);
int size = data.size();
for(int i=0;i<size;i++)
out.write(data.get(i)+"\n");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static String removeExtraSpaces(String t)
{
if(t == null)
return null;
String words [] = t.split(space);
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<words.length;i++)
{
if(!words[i].equalsIgnoreCase(""))
list.add(words[i]);
}
int size = list.size();
StringBuilder sb = new StringBuilder();
for(int i=0;i<size;i++)
sb.append(list.get(i)).append(space);
return sb.toString().trim();
}
public static String returnFirstNWords(String t, int n)
{
if(t == null)
return null;
String words [] = t.split(space);
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<words.length;i++)
{
if(!words[i].equalsIgnoreCase(""))
list.add(words[i]);
}
int size = list.size();
if(size < n)
return null;
else
{
StringBuilder sb = new StringBuilder();
for(int i=0;i<n;i++)
sb.append(list.get(i)).append(space);
return sb.toString().trim();
}
}
public static String RemoveHashTags(String t)
{
String words [] = t.split(space);
StringBuilder sb = new StringBuilder();
for(String word : words)
{
if(!word.startsWith("#"))
sb.append(word).append(space);
}
return sb.toString().trim();
}
public static int getHighestNumerIndex(float one, float two, float three)
{
if(one >= two)
{
if(one >= three)
return 1;
return 3;
}
if(two >= three)
return 2;
return 3;
}
public static ArrayList<TokenDetails> copyList(ArrayList<TokenDetails> src, ArrayList<TokenDetails> dest)
{
for(TokenDetails td: src)
dest.add(td);
return dest;
}
public static String processForNumericValue(String word)
{
String regex = "[0-9]+";
String numberReplacement = "${Number}";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(word);
StringBuilder sb = new StringBuilder();
char [] chars = word.toCharArray();
int i=0;
boolean found = false;
while(m.find())
{
found = true;
int start = m.start();
int end = m.end();
//System.out.println(m.group()+","+m.start()+","+m.end());
while(i < start)
{
sb.append(chars[i]);
i = i+1;
}
i = end;
sb.append(numberReplacement);
}
if(!found)
return word;
return sb.toString().trim();
}
public static void printList(ArrayList<TokenDetails> tdList, String fileName)
{
try{
// Create file
fileName = getCurrentExecutionPath() +"/"+ fileName;
System.out.print("\n printing to File:"+fileName);
FileWriter fstream = new FileWriter(fileName);
BufferedWriter out = new BufferedWriter(fstream);
int size = tdList.size();
for(int i=0;i<size;i++)
{
TokenDetails td = tdList.get(i);
if(i<size-1)
out.write(td.getToken()+"\n");
else
out.write(td.getToken());
}
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void printMap(HashMap<String, TokenDetails> map, int mode, String filename)
{
Iterator <Map.Entry<String, TokenDetails>> it = map.entrySet().iterator();
ArrayList<TokenDetails> tdList = new ArrayList<TokenDetails>();
while(it.hasNext())
{
Map.Entry<String, TokenDetails> pair = (Map.Entry<String, TokenDetails>)it.next();
TokenDetails td = pair.getValue();
//System.out.print("\n"+td.getToken());
tdList.add(td);
}
if(mode == 1)
{
TokenComparator tc = new TokenComparator();
Collections.sort(tdList, tc);
}
else if (mode == 2)
{
TokenComparatorCount tc = new TokenComparatorCount();
Collections.sort(tdList, tc);
}
printList(tdList, filename);
}
public static HashMap<String, TokenDetails> convertMapToTokens(HashMap<String, Integer> map)
{
Iterator <Entry<String, Integer>> it = map.entrySet().iterator();
HashMap<String, TokenDetails> tokenMap = new HashMap<String, TokenDetails>();
while(it.hasNext())
{
Map.Entry<String, Integer> pair = it.next();
String token = pair.getKey();
int count = pair.getValue();
TokenDetails t = new TokenDetails();
t.setCount(count);
t.setToken(token);
tokenMap.put(token, t);
}
return tokenMap;
}
/*public static int substringStartIndex(String src, String part)
{
int i=0;
int j=0;
char [] srcArray = src.toCharArray();
char [] partArray = part.toCharArray();
int start =0;
while(i<src.length())
{
if(srcArray[i] == partArray[j])
{
if(start ==-1)
start =i;
if(j == partArray.length -1)
return start;
i = i+1;
j= j+1;
}
else
{
start =-1;
j =0;
i = i+1;
}
}
if(j == partArray.length -1)
return start;
else
return -1;
}*/
public static int substringStartIndex(String src, String part)
{
String [] srcTokens = src.split(space);
String [] partTokens = part.split(space);
int i=0;
int j=0;
int start =-1;
boolean found = false;
while(i<srcTokens.length)
{
if(srcTokens[i].equalsIgnoreCase(partTokens[j]))
{
if(start == -1)
start = i;
if(j == partTokens.length -1)
{
found = true;
break;
}
i = i+1;
j= j+1;
}
else
{
start =-1;
j = 0;
i = i+1;
}
}
if(found)
{
if(start==0)
return 0;
int count =0;
for(i=0;i<start;i++)
{
count = srcTokens[i].length()+ 1 +count;
}
return count-1;
}
else
return -1;
}
public static int substringStartIndexForNegative(String src, String part)
{
String [] srcTokens = src.split(space);
String [] partTokens = part.split(space);
int i=0;
int j=0;
int start =-1;
boolean found = false;
while(i<srcTokens.length)
{
if(srcTokens[i].equalsIgnoreCase(partTokens[j]))
{
if(start == -1)
start = i;
if(j == partTokens.length -1)
{
found = true;
start =i;
break;
}
i = i+1;
j= j+1;
}
else
{
start =-1;
j = 0;
i = i+1;
}
}
if(found)
{
/*if(start==0)
return part.length() +1;*/
int count =0;
for(i=0;i<=start;i++)
{
count = srcTokens[i].length()+ 1 +count;
}
System.out.println("Start:"+start);
return count;
}
else
return -1;
}
public static void addFromMaptoFile(HashMap<String, TokenDetails> map, String fileName)
{
ArrayList<TokenDetails> tokens = new ArrayList<TokenDetails>();
Iterator <Entry<String, TokenDetails>> it = map.entrySet().iterator();
while(it.hasNext())
{
Map.Entry<String, TokenDetails> pair = (Map.Entry<String, TokenDetails>)it.next();
String key = pair.getKey();
TokenDetails td = pair.getValue();
tokens.add(td);
}
addToFile(tokens, fileName);
}
public static void addToFile(ArrayList<TokenDetails> data, String filename)
{
try{
//String filename = "files/usedConcepts";
ArrayList<String> lines = readFile(filename);
for(int i=0;i<data.size();i++)
lines.add(data.get(i).getToken());
FileWriter fstream = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(fstream);
int size = lines.size();
for(int i=0;i<size;i++)
{
if(i<size-1)
out.write(lines.get(i)+"\n");
else
out.write(lines.get(i));
}
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void appendToFile(ArrayList<String> data, String filename)
{
try{
//String filename = "files/usedConcepts";
ArrayList<String> lines = readFile(filename);
for(int i=0;i<data.size();i++)
lines.add(data.get(i));
FileWriter fstream = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(fstream);
int size = lines.size();
for(int i=0;i<size;i++)
{
if(i<size-1)
out.write(lines.get(i)+"\n");
else
out.write(lines.get(i));
}
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static boolean containsSymbol(String s, String symbol)
{
Iterator <Entry<String, String>> it = specialSymbolsMap.entrySet().iterator();
while(it.hasNext())
{
Map.Entry<String, String> pair = (Map.Entry<String, String>)it.next();
String key = pair.getKey();
if(s.contains(key))
{
String polarity = specialSymbolsMap.get(key);
if(polarity.equalsIgnoreCase(symbol))
return true;
}
}
return false;
}
public static String getNgramToLearnNegativeConcepts(String t, int n)
{
String [] tokens = t.split(Utility.space);
StringBuilder sb = new StringBuilder();
String ngram = null;
int addedWords =0 ;
for(int i=0;i<tokens.length;i++)
{
String token = tokens[i];
sb.append(token).append(Utility.space);
addedWords = addedWords +1;
if(addedWords == n)
break;
}
if(addedWords == n)
ngram = sb.toString().trim();
return ngram;
}
public static String getNgramToLearnPositiveConcepts(String t, int n)
{
String [] tokens = t.split(Utility.space);
int startPoint = tokens.length -n;
if(startPoint <0)
return null;
String ngram = null;
StringBuilder sb = new StringBuilder();
int addedWords =0;
for(int i= startPoint ;i<tokens.length;i++)
{
String token = tokens[i];
sb.append(token).append(Utility.space);
addedWords = addedWords +1;
if(addedWords == n)
break;
}
if(addedWords == n)
ngram = sb.toString().trim();
return ngram;
}
public static String getStringAfterLove(String txt)
{
String searchCriteria = " love ";
if(txt == null)
return null;
if(!txt.startsWith("love "))
{
String [] tokens = txt.split(searchCriteria);
if(tokens.length >1)
return tokens[1];
}
else
{
String [] tokens = txt.split("love ");
if(tokens.length >1)
return tokens[1];
}
return null;
}
public static void printListOnConsole(ArrayList<String> list)
{
int size = list.size();
System.out.print("\n Printing list:");
System.out.print("\n Size:" +size);
for(int i =0;i<size;i++)
{
System.out.print("\n"+list.get(i));
}
}
public static void printMapOnConsole(HashMap<String, TokenDetails> map)
{
Iterator <Entry<String, TokenDetails>> it = map.entrySet().iterator();
while(it.hasNext())
{
Map.Entry<String, TokenDetails> pair = (Map.Entry<String, TokenDetails>)it.next();
TokenDetails td = pair.getValue();
td.printTokenDetails();
}
}
public static void printStringArray(String [] sArray)
{
System.out.println("Size of the array:"+sArray.length);
for(int i=0;i<sArray.length;i++)
System.out.println(""+sArray[i]);
System.out.println("");
}
public static void printStringList(ArrayList<String> list)
{
int size = list.size();
System.out.println("Size of the list:"+size);
for(int i=0;i<size;i++)
System.out.println(""+list.get(i));
System.out.println("");
}
public static void main(String...strings)
{
String s = "please tell me";
}
}
| UTF-8 | Java | 16,156 | java | Utility.java | Java | [
{
"context": "ey(token))\n\t\t\treturn token;\n\n\t\t//if(token.contains(\"#sarcasm\") || token.contains(\"#sarcastic\") || token.starts",
"end": 2834,
"score": 0.9894550442695618,
"start": 2826,
"tag": "USERNAME",
"value": "#sarcasm"
},
{
"context": "\t//if(token.contains(\"#sarcasm... | null | [] | package util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import stubs.TokenComparator;
import stubs.TokenComparatorCount;
import stubs.TokenDetails;
public class Utility {
public static boolean isDebugging = true;
public static final int optionLines = 1;
public static final int optionString = 2;
public static final String space =" ";
public static final String newLine ="\n";
public static final String emptyLine ="";
public static final String delim = "<delim>";
public static final String positive = "+";
public static final String negative = "-";
public static final double probabilityThreshold = 0.60;
public static final int countThreshold =3;
public static HashMap<String, String> specialSymbolsMap = new HashMap<String,String>();
static
{
init();
}
public static void init()
{
specialSymbolsMap.put(":)", positive);
specialSymbolsMap.put(":')", positive);
specialSymbolsMap.put(":]", positive);
specialSymbolsMap.put(":=)", positive);
specialSymbolsMap.put(":-)", positive);
specialSymbolsMap.put(";)", positive);
specialSymbolsMap.put(";-)", positive);
specialSymbolsMap.put("<3", positive);
specialSymbolsMap.put(":D", positive);
specialSymbolsMap.put(":d", positive);
specialSymbolsMap.put(":-D", positive);
specialSymbolsMap.put("-_-", positive);
specialSymbolsMap.put("=D", positive);
specialSymbolsMap.put(":-*", positive);
specialSymbolsMap.put(":*", positive);
specialSymbolsMap.put(":p", positive);
specialSymbolsMap.put(":P", positive);
specialSymbolsMap.put(":-p", positive);
specialSymbolsMap.put(":-P", positive);
specialSymbolsMap.put(";p", positive);
specialSymbolsMap.put("[P", positive);
specialSymbolsMap.put(";-p", positive);
specialSymbolsMap.put(";-P", positive);
specialSymbolsMap.put("\\m/", positive);
specialSymbolsMap.put("o_v_oxo", positive);
specialSymbolsMap.put(":/", negative);
specialSymbolsMap.put(":-/", negative);
specialSymbolsMap.put(">:o", negative);
specialSymbolsMap.put(">:-o", negative);
specialSymbolsMap.put(":-(", negative);
specialSymbolsMap.put(":(", negative);
specialSymbolsMap.put(":=(", negative);
specialSymbolsMap.put(":[", negative);
}
public static String processToken(String token)
{
if(token == null)
return null;
token = token.toLowerCase();
if(specialSymbolsMap.containsKey(token))
return token;
//if(token.contains("#sarcasm") || token.contains("#sarcastic") || token.startsWith("http:")||token.startsWith("@")|| token.equalsIgnoreCase(""))
//return null;
StringBuilder sb = new StringBuilder();
char[] letters = token.toCharArray();
sb = new StringBuilder();
boolean charActive = false;
for(Character c : letters)
{
if(!isSymbol(c))
{
sb.append(c);
charActive= true;
}
else
{
if(charActive)
sb.append(" ");
charActive = false;
}
}
token = Utility.processForNumericValue(sb.toString().trim());
return token;
}
public static boolean passesSpecificWordTest(String tweet, String word)
{
String tokens [] = tweet.split(space);
for(String token: tokens)
{
if(token.equalsIgnoreCase(word))
return true;
}
return false;
}
public static boolean isSymbol(char c)
{
//following symbols will be ignored
if(c=='"' || c == '?'|| c== '.' || c== ',' || c== '!' || c==':' || c ==';' || c == '-' || c== '(' || c== ')'||c=='/'
|| c=='!' || c=='=' || c=='$' || c=='%' || c== '|' || c== '[' || c==']' || c=='*' || c=='+'||c =='_' || c == '<' || c =='>')
return true;
return false;
}
public static ArrayList<String> readFile(String name)
{
ArrayList<String> sentences = new ArrayList<String>();;
StringBuffer sentence = new StringBuffer();
try{
FileInputStream fileStream = new FileInputStream(name);
DataInputStream inputStream = new DataInputStream(fileStream);
BufferedReader bufferdReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
sentences.clear();
while ((line = bufferdReader.readLine()) != null)
{
sentences.add(line);
}
inputStream.close();
}catch (Exception e){
System.err.print("Could not read file specified:" +name);
System.exit(1);
}
return sentences;
}
public static String getCurrentExecutionPath()
{
return System.getProperty("user.dir");
}
public static void writeFile(String name, ArrayList<String> data)
{
try{
// Create file
//name = getCurrentExecutionPath() +"/"+ name;
System.out.println("Name to print:"+name);
FileWriter fstream = new FileWriter(name);
BufferedWriter out = new BufferedWriter(fstream);
int size = data.size();
for(int i=0;i<size;i++)
out.write(data.get(i)+"\n");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static String removeExtraSpaces(String t)
{
if(t == null)
return null;
String words [] = t.split(space);
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<words.length;i++)
{
if(!words[i].equalsIgnoreCase(""))
list.add(words[i]);
}
int size = list.size();
StringBuilder sb = new StringBuilder();
for(int i=0;i<size;i++)
sb.append(list.get(i)).append(space);
return sb.toString().trim();
}
public static String returnFirstNWords(String t, int n)
{
if(t == null)
return null;
String words [] = t.split(space);
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<words.length;i++)
{
if(!words[i].equalsIgnoreCase(""))
list.add(words[i]);
}
int size = list.size();
if(size < n)
return null;
else
{
StringBuilder sb = new StringBuilder();
for(int i=0;i<n;i++)
sb.append(list.get(i)).append(space);
return sb.toString().trim();
}
}
public static String RemoveHashTags(String t)
{
String words [] = t.split(space);
StringBuilder sb = new StringBuilder();
for(String word : words)
{
if(!word.startsWith("#"))
sb.append(word).append(space);
}
return sb.toString().trim();
}
public static int getHighestNumerIndex(float one, float two, float three)
{
if(one >= two)
{
if(one >= three)
return 1;
return 3;
}
if(two >= three)
return 2;
return 3;
}
public static ArrayList<TokenDetails> copyList(ArrayList<TokenDetails> src, ArrayList<TokenDetails> dest)
{
for(TokenDetails td: src)
dest.add(td);
return dest;
}
public static String processForNumericValue(String word)
{
String regex = "[0-9]+";
String numberReplacement = "${Number}";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(word);
StringBuilder sb = new StringBuilder();
char [] chars = word.toCharArray();
int i=0;
boolean found = false;
while(m.find())
{
found = true;
int start = m.start();
int end = m.end();
//System.out.println(m.group()+","+m.start()+","+m.end());
while(i < start)
{
sb.append(chars[i]);
i = i+1;
}
i = end;
sb.append(numberReplacement);
}
if(!found)
return word;
return sb.toString().trim();
}
public static void printList(ArrayList<TokenDetails> tdList, String fileName)
{
try{
// Create file
fileName = getCurrentExecutionPath() +"/"+ fileName;
System.out.print("\n printing to File:"+fileName);
FileWriter fstream = new FileWriter(fileName);
BufferedWriter out = new BufferedWriter(fstream);
int size = tdList.size();
for(int i=0;i<size;i++)
{
TokenDetails td = tdList.get(i);
if(i<size-1)
out.write(td.getToken()+"\n");
else
out.write(td.getToken());
}
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void printMap(HashMap<String, TokenDetails> map, int mode, String filename)
{
Iterator <Map.Entry<String, TokenDetails>> it = map.entrySet().iterator();
ArrayList<TokenDetails> tdList = new ArrayList<TokenDetails>();
while(it.hasNext())
{
Map.Entry<String, TokenDetails> pair = (Map.Entry<String, TokenDetails>)it.next();
TokenDetails td = pair.getValue();
//System.out.print("\n"+td.getToken());
tdList.add(td);
}
if(mode == 1)
{
TokenComparator tc = new TokenComparator();
Collections.sort(tdList, tc);
}
else if (mode == 2)
{
TokenComparatorCount tc = new TokenComparatorCount();
Collections.sort(tdList, tc);
}
printList(tdList, filename);
}
public static HashMap<String, TokenDetails> convertMapToTokens(HashMap<String, Integer> map)
{
Iterator <Entry<String, Integer>> it = map.entrySet().iterator();
HashMap<String, TokenDetails> tokenMap = new HashMap<String, TokenDetails>();
while(it.hasNext())
{
Map.Entry<String, Integer> pair = it.next();
String token = pair.getKey();
int count = pair.getValue();
TokenDetails t = new TokenDetails();
t.setCount(count);
t.setToken(token);
tokenMap.put(token, t);
}
return tokenMap;
}
/*public static int substringStartIndex(String src, String part)
{
int i=0;
int j=0;
char [] srcArray = src.toCharArray();
char [] partArray = part.toCharArray();
int start =0;
while(i<src.length())
{
if(srcArray[i] == partArray[j])
{
if(start ==-1)
start =i;
if(j == partArray.length -1)
return start;
i = i+1;
j= j+1;
}
else
{
start =-1;
j =0;
i = i+1;
}
}
if(j == partArray.length -1)
return start;
else
return -1;
}*/
public static int substringStartIndex(String src, String part)
{
String [] srcTokens = src.split(space);
String [] partTokens = part.split(space);
int i=0;
int j=0;
int start =-1;
boolean found = false;
while(i<srcTokens.length)
{
if(srcTokens[i].equalsIgnoreCase(partTokens[j]))
{
if(start == -1)
start = i;
if(j == partTokens.length -1)
{
found = true;
break;
}
i = i+1;
j= j+1;
}
else
{
start =-1;
j = 0;
i = i+1;
}
}
if(found)
{
if(start==0)
return 0;
int count =0;
for(i=0;i<start;i++)
{
count = srcTokens[i].length()+ 1 +count;
}
return count-1;
}
else
return -1;
}
public static int substringStartIndexForNegative(String src, String part)
{
String [] srcTokens = src.split(space);
String [] partTokens = part.split(space);
int i=0;
int j=0;
int start =-1;
boolean found = false;
while(i<srcTokens.length)
{
if(srcTokens[i].equalsIgnoreCase(partTokens[j]))
{
if(start == -1)
start = i;
if(j == partTokens.length -1)
{
found = true;
start =i;
break;
}
i = i+1;
j= j+1;
}
else
{
start =-1;
j = 0;
i = i+1;
}
}
if(found)
{
/*if(start==0)
return part.length() +1;*/
int count =0;
for(i=0;i<=start;i++)
{
count = srcTokens[i].length()+ 1 +count;
}
System.out.println("Start:"+start);
return count;
}
else
return -1;
}
public static void addFromMaptoFile(HashMap<String, TokenDetails> map, String fileName)
{
ArrayList<TokenDetails> tokens = new ArrayList<TokenDetails>();
Iterator <Entry<String, TokenDetails>> it = map.entrySet().iterator();
while(it.hasNext())
{
Map.Entry<String, TokenDetails> pair = (Map.Entry<String, TokenDetails>)it.next();
String key = pair.getKey();
TokenDetails td = pair.getValue();
tokens.add(td);
}
addToFile(tokens, fileName);
}
public static void addToFile(ArrayList<TokenDetails> data, String filename)
{
try{
//String filename = "files/usedConcepts";
ArrayList<String> lines = readFile(filename);
for(int i=0;i<data.size();i++)
lines.add(data.get(i).getToken());
FileWriter fstream = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(fstream);
int size = lines.size();
for(int i=0;i<size;i++)
{
if(i<size-1)
out.write(lines.get(i)+"\n");
else
out.write(lines.get(i));
}
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void appendToFile(ArrayList<String> data, String filename)
{
try{
//String filename = "files/usedConcepts";
ArrayList<String> lines = readFile(filename);
for(int i=0;i<data.size();i++)
lines.add(data.get(i));
FileWriter fstream = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(fstream);
int size = lines.size();
for(int i=0;i<size;i++)
{
if(i<size-1)
out.write(lines.get(i)+"\n");
else
out.write(lines.get(i));
}
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static boolean containsSymbol(String s, String symbol)
{
Iterator <Entry<String, String>> it = specialSymbolsMap.entrySet().iterator();
while(it.hasNext())
{
Map.Entry<String, String> pair = (Map.Entry<String, String>)it.next();
String key = pair.getKey();
if(s.contains(key))
{
String polarity = specialSymbolsMap.get(key);
if(polarity.equalsIgnoreCase(symbol))
return true;
}
}
return false;
}
public static String getNgramToLearnNegativeConcepts(String t, int n)
{
String [] tokens = t.split(Utility.space);
StringBuilder sb = new StringBuilder();
String ngram = null;
int addedWords =0 ;
for(int i=0;i<tokens.length;i++)
{
String token = tokens[i];
sb.append(token).append(Utility.space);
addedWords = addedWords +1;
if(addedWords == n)
break;
}
if(addedWords == n)
ngram = sb.toString().trim();
return ngram;
}
public static String getNgramToLearnPositiveConcepts(String t, int n)
{
String [] tokens = t.split(Utility.space);
int startPoint = tokens.length -n;
if(startPoint <0)
return null;
String ngram = null;
StringBuilder sb = new StringBuilder();
int addedWords =0;
for(int i= startPoint ;i<tokens.length;i++)
{
String token = tokens[i];
sb.append(token).append(Utility.space);
addedWords = addedWords +1;
if(addedWords == n)
break;
}
if(addedWords == n)
ngram = sb.toString().trim();
return ngram;
}
public static String getStringAfterLove(String txt)
{
String searchCriteria = " love ";
if(txt == null)
return null;
if(!txt.startsWith("love "))
{
String [] tokens = txt.split(searchCriteria);
if(tokens.length >1)
return tokens[1];
}
else
{
String [] tokens = txt.split("love ");
if(tokens.length >1)
return tokens[1];
}
return null;
}
public static void printListOnConsole(ArrayList<String> list)
{
int size = list.size();
System.out.print("\n Printing list:");
System.out.print("\n Size:" +size);
for(int i =0;i<size;i++)
{
System.out.print("\n"+list.get(i));
}
}
public static void printMapOnConsole(HashMap<String, TokenDetails> map)
{
Iterator <Entry<String, TokenDetails>> it = map.entrySet().iterator();
while(it.hasNext())
{
Map.Entry<String, TokenDetails> pair = (Map.Entry<String, TokenDetails>)it.next();
TokenDetails td = pair.getValue();
td.printTokenDetails();
}
}
public static void printStringArray(String [] sArray)
{
System.out.println("Size of the array:"+sArray.length);
for(int i=0;i<sArray.length;i++)
System.out.println(""+sArray[i]);
System.out.println("");
}
public static void printStringList(ArrayList<String> list)
{
int size = list.size();
System.out.println("Size of the list:"+size);
for(int i=0;i<size;i++)
System.out.println(""+list.get(i));
System.out.println("");
}
public static void main(String...strings)
{
String s = "please tell me";
}
}
| 16,156 | 0.639639 | 0.63413 | 729 | 21.161865 | 21.759405 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.633745 | false | false | 14 |
a432cb043edd08cfce2bdc584616a6ef5bb75e73 | 6,451,040,887,445 | 2489f7c9ee1080a3cc2f4fdf69a4ac2831096e17 | /doc/zem/EM.java | 0a604fabd129ff1b1326b95fbcaa4411c98fc8d6 | [] | no_license | asvcer/em-algorithm | https://github.com/asvcer/em-algorithm | 722a1bdce23e4de2d9e27884a740fbb44d19b307 | 888bcfad7ce22b600d9291a0e4ed1e0ada1e4619 | refs/heads/master | 2019-01-26T12:00:53.753000 | 2017-03-25T07:15:08 | 2017-03-25T07:15:08 | 86,139,636 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // EM.java
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
// Primary author contact info: www.idiom.com/~zilla zilla@computer.org
package ZS;
import java.awt.*; // for algorithm debug only
import VisualNumerics.math.*; // for testing inverse
import zlib.*;
/**
* P(m|d) = P(d|m) P(m) / P(d)
*
* P(d|m) is the likelihood, it is the probability of the data assigned
* by this model.
*
* P(m|d) is the posterior, it is the probability of
* this model given that the data has been observed.
*
* ndata - number of data items, each of nd dimensions
* nmix - number of gaussians in the mixture model
*
* @param data[ndata][nd]
* @param means[nmix][]
* @param covariances[nmix][nd][nd]
* @param priors[nmix]
* @param posteriors[ndata][nmix]
*/
final public class EM
{
final static int verbose = 1;
public static void em(double[][] data,
int nsteps,
double[][] means,
double[][][] covariances,
double[] priors,
double[][] posteriors)
throws Exception
{
int ndata = data.length;
int nmix = means.length;
zliberror.assert(covariances.length == nmix, "em1");
zliberror.assert(priors.length == nmix, "em2");
zliberror.assert(posteriors.length == ndata, "em3");
zliberror.assert(posteriors[0].length == nmix, "em4");
init(data, means, covariances, priors);
for(int step = 0; step < nsteps; step++) {
estep(data, means, covariances, priors, posteriors);
mstep(data, means, covariances, priors, posteriors);
}
} //em
/**
* initialize means, covariances, priors to reasonable starting values
*/
public static void init(double[][] data,
double[][] means,
double[][][] covariances,
double[] priors)
{
int ndata = data.length;
int nmix = means.length;
int nd = means[0].length;
zliberror.assert(covariances[0].length == nd);
zliberror.assert(covariances[0][0].length == nd);
double[][] bounds = new double[nd][2];
matrix.getNDBounds(data, bounds);
double[] del = new double[nd];
for(int id = 0; id < nd; id++) {
if (verbose > 0)
System.out.println("data bounds: " + bounds[id][0] + ".." + bounds[id][1]);
del[id] = bounds[id][1] - bounds[id][0];
}
for(int im = 0; im < nmix; im++) {
for(int id = 0; id < nd; id++) {
means[im][id] = bounds[id][0] + rnd.rndf() * del[id];
}
matrix.setIdentity(covariances[im]);
priors[im] = 1. / nd;
}
} //init
/**
* Calculate posterior probabilities.
*/
public static void estep(double[][] data,
double[][] means,
double[][][] covariances,
double[] priors,
double[][] posteriors)
throws Exception
{
int ndata = data.length;
int nmix = means.length;
zliberror.assert(posteriors.length == ndata, "estep0");
zliberror.assert(posteriors[0].length == nmix, "estep1");
for(int ip = 0; ip < ndata; ip++) {
double norm = 0.f;
for(int im = 0; im < nmix; im++) {
// TODO: pull the im loop outside ip, then can evaluate gscale
// once per model
// double gscale = gaussEvalScale(means[im], covariances[im]);
double g = zmath.gaussEval(data[ip], means[im], covariances[im]);
norm += priors[im] * g;
}
for(int im = 0; im < nmix; im++) {
double g = zmath.gaussEval(data[ip], means[im], covariances[im]);
posteriors[ip][im] = (priors[im] * g) / norm;
}
}
} //estep
public static void mstep(double[][] data,
double[][] means,
double[][][] covariances,
double[] priors,
double[][] posteriors)
throws Exception
{
int ndata = data.length;
int nmix = means.length;
int nd = means[0].length;
// prior probability for a particular gaussian is its
// posterior probability summed over all data points.
for(int im = 0; im < nmix; im++) {
double sum = 0.;
for(int ip = 0; ip < ndata; ip++) {
sum += posteriors[ip][im];
}
priors[im] = sum / ndata;
}
// each mean is a weighted sum of the data points,
// weighted by the convex normalized posterior probability for that G
for(int im = 0; im < nmix; im++) {
// zero this mean
for(int id = 0; id < nd; id++) {
means[im][id] = 0.;
}
// accumulate
double sumposterior = 0.;
for(int ip = 0; ip < ndata; ip++) {
double pw = posteriors[ip][im];
sumposterior += pw;
for(int id = 0; id < nd; id++) {
means[im][id] += (pw * data[ip][id]);
}
} //ip
double oosumposterior = 1. / sumposterior;
for(int id = 0; id < nd; id++) {
means[im][id] *= oosumposterior;
} //id
} //im
// lastly, covariance is weighted sum of outer products
// of the de-meaned data, as weighted by the normalized posteriors
for(int im = 0; im < nmix; im++) {
double[][] cov = covariances[im];
double[] mean = means[im];
// zero this covariance
for(int id = 0; id < nd; id++) {
for(int jd = 0; jd < nd; jd++) {
cov[id][jd] = 0.;
}
}
// accumulated weighted sum of outer product of de-meaned data
double sumposterior = 0.;
for(int ip = 0; ip < ndata; ip++) {
double[] d = data[ip];
double pw = posteriors[ip][im];
sumposterior += pw;
for(int id = 0; id < nd; id++) {
for(int jd = 0; jd < nd; jd++) {
cov[id][jd] += (pw * (d[id] - mean[id]) * (d[jd] - mean[jd]));
}
}
} //ip
// normalize the posterior weighting
double oosumposterior = 1. / sumposterior;
for(int id = 0; id < nd; id++) {
for(int jd = 0; jd < nd; jd++) {
cov[id][jd] *= oosumposterior;
}
}
// and invert, because in e step it is ony used in the gaussEval
// TODO: yuck garbage
covariances[im] = DoubleMatrix.inverse(cov);
} //im
} //mstep
//----------------------------------------------------------------
// plotting code below.
//----------------------------------------------------------------
static final int RES = 400;
static final int RESo2 = RES/2;
static Frame _f;
static Graphics _g;
static void plot(double[][] data, double[][] means, double[][][] covariances)
{
int ndata = data.length;
int nmix = means.length;
int nd = means[0].length;
_g.clearRect(0,0,RES,RES);
_g.setColor(Color.blue);
for( int ip=0; ip < ndata; ip++ ) {
drawpt(data[ip][0],data[ip][1]);
}
_g.setColor(Color.red);
for( int im=0; im < nmix; im++ ) {
drawpt(means[im][0],means[im][1]);
// vis of covariance:
// cov is pos def, find set of x s.t. x C x = k
int npts = 21;
double k = 1.;
for( int ip=0; ip < npts; ip++ ) {
double angle = 2. * Math.PI * (ip / (double)(npts-1));
double x = Math.cos(angle);
double y = Math.sin(angle);
double r = findroot(covariances[im], x, y, k);
drawto(means[im][0] + r*x, means[im][1] + r*y, (ip==0));
}
} //nmix
} //plot
// x ( C11 x + C12 y ) + y ( C21 x + C22 y ) = k
// y/x = s
//
// y = x*s
// x ( C11 x + C12 x*s ) + x*s ( C21 x + C22 x*s ) = k
// C11 x^2 + C12 s x^2 + C21 x^2 s + C22 x^2 s^2 = k
// x^2 ( C11 + C12 s + C21 s + C22 s^2 ) = k
// x = sqrt( k / ( C11 + C12 s + C21 s + C22 s^2 ) )
static double findroot(double[][] cov, double x, double y, double k)
{
double s = y / x; // beware x 0
double den = cov[0][0] + cov[0][1]*s + cov[1][0]*s + cov[1][1]*s*s;
if (den < 0.) den = - den;
double x1 = Math.sqrt(k / den);
return x1 / Math.abs(x); // ratio
} //findroot
static final int toscreen(double d)
{
return RESo2 + (int)(RESo2 * d);
}
static void drawpt(double dx, double dy)
{
int ix = toscreen(dx);
int iy = toscreen(dy);
_g.drawLine(ix-5, iy-5, ix+5, iy+5);
_g.drawLine(ix+5, iy-5, ix-5, iy+5);
}
static int _lx = 0;
static int _ly = 0;
static void drawto(double dx, double dy, boolean moveto)
{
int ix = toscreen(dx);
int iy = toscreen(dy);
if (!moveto) {
_g.drawLine(_lx, _ly, ix, iy);
}
_lx = ix;
_ly = iy;
}
static void drawpt(int ix, int iy)
{
_g.drawLine(ix-5, iy-5, ix+5, iy+5);
_g.drawLine(ix+5, iy-5, ix-5, iy+5);
}
static void simpleTest()
throws Exception
{
int ndata = 100;
int nd = 2;
int nmix = 2;
double[][] data = new double[ndata][2];
for(int ip = 0; ip < ndata; ip++) {
double angle = 2. * Math.PI * (ip / (double)ndata);
data[ip][0] = 0.5 * Math.cos(angle) + 0.05 * rnd.rndf11();
data[ip][1] = 0.5 * Math.sin(angle) + 0.05 * rnd.rndf11();
}
double[][] means = new double[nmix][nd];
double[][][] covariances = new double[nmix][nd][nd];
double[] priors = new double[nmix];
double[][] posteriors = new double[ndata][nmix];
int nsteps = 100;
init(data, means, covariances, priors);
for(int istep = 0; istep < nsteps; istep++) {
estep(data, means, covariances, priors, posteriors);
mstep(data, means, covariances, priors, posteriors);
if (istep%3 == 0) {
plot(data, means, covariances);
zlib.more();
}
}
} //simpleTest
public static void main(String[] cmdline)
{
try {
_f = new Frame();
_f.setSize(RES,RES);
_f.setVisible(true);
_g = _f.getGraphics();
simpleTest();
}
catch(Exception x) { zliberror.die(x); }
} //main
} //EM
| UTF-8 | Java | 10,024 | java | EM.java | Java | [
{
"context": "rimary author contact info: www.idiom.com/~zilla zilla@computer.org\n\npackage ZS;\n\nimport java.awt.*;\t\t// for algorith",
"end": 830,
"score": 0.9998893737792969,
"start": 812,
"tag": "EMAIL",
"value": "zilla@computer.org"
}
] | null | [] | // EM.java
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
// Primary author contact info: www.idiom.com/~zilla <EMAIL>
package ZS;
import java.awt.*; // for algorithm debug only
import VisualNumerics.math.*; // for testing inverse
import zlib.*;
/**
* P(m|d) = P(d|m) P(m) / P(d)
*
* P(d|m) is the likelihood, it is the probability of the data assigned
* by this model.
*
* P(m|d) is the posterior, it is the probability of
* this model given that the data has been observed.
*
* ndata - number of data items, each of nd dimensions
* nmix - number of gaussians in the mixture model
*
* @param data[ndata][nd]
* @param means[nmix][]
* @param covariances[nmix][nd][nd]
* @param priors[nmix]
* @param posteriors[ndata][nmix]
*/
final public class EM
{
final static int verbose = 1;
public static void em(double[][] data,
int nsteps,
double[][] means,
double[][][] covariances,
double[] priors,
double[][] posteriors)
throws Exception
{
int ndata = data.length;
int nmix = means.length;
zliberror.assert(covariances.length == nmix, "em1");
zliberror.assert(priors.length == nmix, "em2");
zliberror.assert(posteriors.length == ndata, "em3");
zliberror.assert(posteriors[0].length == nmix, "em4");
init(data, means, covariances, priors);
for(int step = 0; step < nsteps; step++) {
estep(data, means, covariances, priors, posteriors);
mstep(data, means, covariances, priors, posteriors);
}
} //em
/**
* initialize means, covariances, priors to reasonable starting values
*/
public static void init(double[][] data,
double[][] means,
double[][][] covariances,
double[] priors)
{
int ndata = data.length;
int nmix = means.length;
int nd = means[0].length;
zliberror.assert(covariances[0].length == nd);
zliberror.assert(covariances[0][0].length == nd);
double[][] bounds = new double[nd][2];
matrix.getNDBounds(data, bounds);
double[] del = new double[nd];
for(int id = 0; id < nd; id++) {
if (verbose > 0)
System.out.println("data bounds: " + bounds[id][0] + ".." + bounds[id][1]);
del[id] = bounds[id][1] - bounds[id][0];
}
for(int im = 0; im < nmix; im++) {
for(int id = 0; id < nd; id++) {
means[im][id] = bounds[id][0] + rnd.rndf() * del[id];
}
matrix.setIdentity(covariances[im]);
priors[im] = 1. / nd;
}
} //init
/**
* Calculate posterior probabilities.
*/
public static void estep(double[][] data,
double[][] means,
double[][][] covariances,
double[] priors,
double[][] posteriors)
throws Exception
{
int ndata = data.length;
int nmix = means.length;
zliberror.assert(posteriors.length == ndata, "estep0");
zliberror.assert(posteriors[0].length == nmix, "estep1");
for(int ip = 0; ip < ndata; ip++) {
double norm = 0.f;
for(int im = 0; im < nmix; im++) {
// TODO: pull the im loop outside ip, then can evaluate gscale
// once per model
// double gscale = gaussEvalScale(means[im], covariances[im]);
double g = zmath.gaussEval(data[ip], means[im], covariances[im]);
norm += priors[im] * g;
}
for(int im = 0; im < nmix; im++) {
double g = zmath.gaussEval(data[ip], means[im], covariances[im]);
posteriors[ip][im] = (priors[im] * g) / norm;
}
}
} //estep
public static void mstep(double[][] data,
double[][] means,
double[][][] covariances,
double[] priors,
double[][] posteriors)
throws Exception
{
int ndata = data.length;
int nmix = means.length;
int nd = means[0].length;
// prior probability for a particular gaussian is its
// posterior probability summed over all data points.
for(int im = 0; im < nmix; im++) {
double sum = 0.;
for(int ip = 0; ip < ndata; ip++) {
sum += posteriors[ip][im];
}
priors[im] = sum / ndata;
}
// each mean is a weighted sum of the data points,
// weighted by the convex normalized posterior probability for that G
for(int im = 0; im < nmix; im++) {
// zero this mean
for(int id = 0; id < nd; id++) {
means[im][id] = 0.;
}
// accumulate
double sumposterior = 0.;
for(int ip = 0; ip < ndata; ip++) {
double pw = posteriors[ip][im];
sumposterior += pw;
for(int id = 0; id < nd; id++) {
means[im][id] += (pw * data[ip][id]);
}
} //ip
double oosumposterior = 1. / sumposterior;
for(int id = 0; id < nd; id++) {
means[im][id] *= oosumposterior;
} //id
} //im
// lastly, covariance is weighted sum of outer products
// of the de-meaned data, as weighted by the normalized posteriors
for(int im = 0; im < nmix; im++) {
double[][] cov = covariances[im];
double[] mean = means[im];
// zero this covariance
for(int id = 0; id < nd; id++) {
for(int jd = 0; jd < nd; jd++) {
cov[id][jd] = 0.;
}
}
// accumulated weighted sum of outer product of de-meaned data
double sumposterior = 0.;
for(int ip = 0; ip < ndata; ip++) {
double[] d = data[ip];
double pw = posteriors[ip][im];
sumposterior += pw;
for(int id = 0; id < nd; id++) {
for(int jd = 0; jd < nd; jd++) {
cov[id][jd] += (pw * (d[id] - mean[id]) * (d[jd] - mean[jd]));
}
}
} //ip
// normalize the posterior weighting
double oosumposterior = 1. / sumposterior;
for(int id = 0; id < nd; id++) {
for(int jd = 0; jd < nd; jd++) {
cov[id][jd] *= oosumposterior;
}
}
// and invert, because in e step it is ony used in the gaussEval
// TODO: yuck garbage
covariances[im] = DoubleMatrix.inverse(cov);
} //im
} //mstep
//----------------------------------------------------------------
// plotting code below.
//----------------------------------------------------------------
static final int RES = 400;
static final int RESo2 = RES/2;
static Frame _f;
static Graphics _g;
static void plot(double[][] data, double[][] means, double[][][] covariances)
{
int ndata = data.length;
int nmix = means.length;
int nd = means[0].length;
_g.clearRect(0,0,RES,RES);
_g.setColor(Color.blue);
for( int ip=0; ip < ndata; ip++ ) {
drawpt(data[ip][0],data[ip][1]);
}
_g.setColor(Color.red);
for( int im=0; im < nmix; im++ ) {
drawpt(means[im][0],means[im][1]);
// vis of covariance:
// cov is pos def, find set of x s.t. x C x = k
int npts = 21;
double k = 1.;
for( int ip=0; ip < npts; ip++ ) {
double angle = 2. * Math.PI * (ip / (double)(npts-1));
double x = Math.cos(angle);
double y = Math.sin(angle);
double r = findroot(covariances[im], x, y, k);
drawto(means[im][0] + r*x, means[im][1] + r*y, (ip==0));
}
} //nmix
} //plot
// x ( C11 x + C12 y ) + y ( C21 x + C22 y ) = k
// y/x = s
//
// y = x*s
// x ( C11 x + C12 x*s ) + x*s ( C21 x + C22 x*s ) = k
// C11 x^2 + C12 s x^2 + C21 x^2 s + C22 x^2 s^2 = k
// x^2 ( C11 + C12 s + C21 s + C22 s^2 ) = k
// x = sqrt( k / ( C11 + C12 s + C21 s + C22 s^2 ) )
static double findroot(double[][] cov, double x, double y, double k)
{
double s = y / x; // beware x 0
double den = cov[0][0] + cov[0][1]*s + cov[1][0]*s + cov[1][1]*s*s;
if (den < 0.) den = - den;
double x1 = Math.sqrt(k / den);
return x1 / Math.abs(x); // ratio
} //findroot
static final int toscreen(double d)
{
return RESo2 + (int)(RESo2 * d);
}
static void drawpt(double dx, double dy)
{
int ix = toscreen(dx);
int iy = toscreen(dy);
_g.drawLine(ix-5, iy-5, ix+5, iy+5);
_g.drawLine(ix+5, iy-5, ix-5, iy+5);
}
static int _lx = 0;
static int _ly = 0;
static void drawto(double dx, double dy, boolean moveto)
{
int ix = toscreen(dx);
int iy = toscreen(dy);
if (!moveto) {
_g.drawLine(_lx, _ly, ix, iy);
}
_lx = ix;
_ly = iy;
}
static void drawpt(int ix, int iy)
{
_g.drawLine(ix-5, iy-5, ix+5, iy+5);
_g.drawLine(ix+5, iy-5, ix-5, iy+5);
}
static void simpleTest()
throws Exception
{
int ndata = 100;
int nd = 2;
int nmix = 2;
double[][] data = new double[ndata][2];
for(int ip = 0; ip < ndata; ip++) {
double angle = 2. * Math.PI * (ip / (double)ndata);
data[ip][0] = 0.5 * Math.cos(angle) + 0.05 * rnd.rndf11();
data[ip][1] = 0.5 * Math.sin(angle) + 0.05 * rnd.rndf11();
}
double[][] means = new double[nmix][nd];
double[][][] covariances = new double[nmix][nd][nd];
double[] priors = new double[nmix];
double[][] posteriors = new double[ndata][nmix];
int nsteps = 100;
init(data, means, covariances, priors);
for(int istep = 0; istep < nsteps; istep++) {
estep(data, means, covariances, priors, posteriors);
mstep(data, means, covariances, priors, posteriors);
if (istep%3 == 0) {
plot(data, means, covariances);
zlib.more();
}
}
} //simpleTest
public static void main(String[] cmdline)
{
try {
_f = new Frame();
_f.setSize(RES,RES);
_f.setVisible(true);
_g = _f.getGraphics();
simpleTest();
}
catch(Exception x) { zliberror.die(x); }
} //main
} //EM
| 10,013 | 0.567837 | 0.547885 | 374 | 25.802139 | 21.517395 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.034759 | false | false | 14 |
c5b02116da0122a026ce98db1e0236c63cb4ec5d | 18,064,632,517,544 | 2294d375c2d28c74447cdfeb5f452d74ec6f9a28 | /dungeoncrawler/src/main/java/whatexe/dungeoncrawler/entities/behavior/collision/PlayerCollisionBehavior.java | ba929fda4fd52c3c097f17777c69c0fb18ce3d32 | [] | no_license | Russell-Newton/NotMalware-Game | https://github.com/Russell-Newton/NotMalware-Game | f035f1341b45e514a5b50db92e12d478d5d52321 | 5e30eecfeaacb7546df5bb8b10acdc7d65906dcc | refs/heads/master | 2023-07-18T07:41:39.489000 | 2021-04-27T02:36:21 | 2021-04-27T02:36:21 | 399,507,704 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package whatexe.dungeoncrawler.entities.behavior.collision;
import whatexe.dungeoncrawler.entities.Entity;
import whatexe.dungeoncrawler.entities.doors.Door;
import whatexe.dungeoncrawler.entities.doors.ExitLevelDoor;
import whatexe.dungeoncrawler.entities.player.Player;
import java.util.ArrayList;
import java.util.List;
public class PlayerCollisionBehavior extends CollisionBehavior<Player> {
public PlayerCollisionBehavior(Player owningEntity) {
super(owningEntity);
}
@Override
public void handleCollisionWithEntity(Entity otherEntity) {
}
@Override
public List<? extends Entity> getPossibleCollisionTargets() {
List<Door> lockedDoors = new ArrayList<>();
for (Door door : owningEntity.getOwningRoom().getDoors()) {
if (!(door instanceof ExitLevelDoor) && door.isLocked()) {
lockedDoors.add(door);
}
}
return lockedDoors;
}
@Override
public void handleCollisionWithBoundary() {
}
}
| UTF-8 | Java | 1,019 | java | PlayerCollisionBehavior.java | Java | [] | null | [] | package whatexe.dungeoncrawler.entities.behavior.collision;
import whatexe.dungeoncrawler.entities.Entity;
import whatexe.dungeoncrawler.entities.doors.Door;
import whatexe.dungeoncrawler.entities.doors.ExitLevelDoor;
import whatexe.dungeoncrawler.entities.player.Player;
import java.util.ArrayList;
import java.util.List;
public class PlayerCollisionBehavior extends CollisionBehavior<Player> {
public PlayerCollisionBehavior(Player owningEntity) {
super(owningEntity);
}
@Override
public void handleCollisionWithEntity(Entity otherEntity) {
}
@Override
public List<? extends Entity> getPossibleCollisionTargets() {
List<Door> lockedDoors = new ArrayList<>();
for (Door door : owningEntity.getOwningRoom().getDoors()) {
if (!(door instanceof ExitLevelDoor) && door.isLocked()) {
lockedDoors.add(door);
}
}
return lockedDoors;
}
@Override
public void handleCollisionWithBoundary() {
}
}
| 1,019 | 0.707556 | 0.707556 | 36 | 27.305555 | 25.494902 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.305556 | false | false | 14 |
71c578d462c0f84fbfad09a1747b50df04500c53 | 21,492,016,415,823 | 172463dadd739279ecc9e11d3c2aff910097f1ff | /src/com/advance/MultiThread3/MyThread/MyThread34_1.java | e68df2da34ba60dd4cc554c5e7bf12f820708c88 | [] | no_license | mingge12321/Java_Advanced_Knowledge | https://github.com/mingge12321/Java_Advanced_Knowledge | 2aa44f153b28895e166966d7dd1da3f36eb26ede | 23584e253271f0860c3838872d04690865589cdd | refs/heads/master | 2022-06-23T04:27:26.500000 | 2019-11-03T17:14:09 | 2019-11-03T17:14:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.advance.MultiThread3.MyThread;
/**
* @Author: 谷天乐
* @Date: 2019/7/15 18:50
* @Description:
*/
public class MyThread34_1 extends Thread{
private Object lock;
public MyThread34_1(Object lock)
{
this.lock = lock;
}
public void run()
{
synchronized (lock)
{
lock.notifyAll();
}
}
} | UTF-8 | Java | 375 | java | MyThread34_1.java | Java | [
{
"context": "m.advance.MultiThread3.MyThread;\n\n/**\n * @Author: 谷天乐\n * @Date: 2019/7/15 18:50\n * @Description:\n */\npu",
"end": 63,
"score": 0.9995372891426086,
"start": 60,
"tag": "NAME",
"value": "谷天乐"
}
] | null | [] | package com.advance.MultiThread3.MyThread;
/**
* @Author: 谷天乐
* @Date: 2019/7/15 18:50
* @Description:
*/
public class MyThread34_1 extends Thread{
private Object lock;
public MyThread34_1(Object lock)
{
this.lock = lock;
}
public void run()
{
synchronized (lock)
{
lock.notifyAll();
}
}
} | 375 | 0.555556 | 0.506775 | 24 | 14.416667 | 13.465749 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 14 |
06ef09439e14f05eb8e9f41b7c8a62707f7cffc0 | 15,298,673,574,653 | dff938312a130b66748e10600b5fd6fbc7aa132b | /app/src/main/java/com/jere/test/article/view/completeproject/CompleteProjectArticleFragment.java | 4bf595b11e9d8bd5e42c13c3791451935c5221aa | [] | no_license | JereChen11/JereTestApp | https://github.com/JereChen11/JereTestApp | c503ba678464c8bd32fe123086c72a57aaafd203 | e2c117b95e51d1965deb34c4ddcec516b49b1ce4 | refs/heads/master | 2020-08-10T01:22:20.828000 | 2020-07-10T13:03:48 | 2020-07-10T13:03:48 | 214,220,709 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jere.test.article.view.completeproject;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.jere.test.R;
import com.jere.test.article.modle.beanfiles.completeproject.ProjectTreeItem;
import com.jere.test.article.view.ProjectItemListActivity;
import com.jere.test.article.viewmodel.completeproject.ProjectTreeItemViewModel;
import com.jere.test.home.HomeActivity;
import com.jere.test.util.RecyclerItemClickListener;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
/**
* @author jere
*/
public class CompleteProjectArticleFragment extends Fragment {
public static final String PROJECT_ITEM_ID_KEY = "PROJECT_ITEM_ID";
private ProjectTreeItemAdapter mProjectTreeItemAdapter;
private ArrayList<ProjectTreeItem.ProjectItem> mProjectItems = new ArrayList<>();
private RecyclerView mProjectTreeItemRecyclerView;
public CompleteProjectArticleFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_complete_project, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ProjectTreeItemViewModel projectTreeItemVm = new ViewModelProvider(this).get(ProjectTreeItemViewModel.class);
projectTreeItemVm.getProjectTreeItemsLd().observe(getViewLifecycleOwner(), projectItemsObserver);
projectTreeItemVm.setProjectTreeItemsLd();
mProjectTreeItemAdapter = new ProjectTreeItemAdapter(mProjectItems);
mProjectTreeItemRecyclerView = view.findViewById(R.id.projectTreeItemsRcv);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
mProjectTreeItemRecyclerView.setLayoutManager(layoutManager);
mProjectTreeItemRecyclerView.setAdapter(mProjectTreeItemAdapter);
mProjectTreeItemRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(),
mProjectTreeItemRecyclerView,
new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
ProjectTreeItem.ProjectItem projectItem = mProjectItems.get(position);
Intent intent = new Intent(getActivity(), ProjectItemListActivity.class);
intent.putExtra(PROJECT_ITEM_ID_KEY, projectItem.getId());
startActivity(intent);
}
@Override
public void onLongItemClick(View view, int position) {
//todo need to handle onLongItemClick event.
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
}));
}
private Observer<ArrayList<ProjectTreeItem.ProjectItem>> projectItemsObserver = new Observer<ArrayList<ProjectTreeItem.ProjectItem>>() {
@Override
public void onChanged(@Nullable ArrayList<ProjectTreeItem.ProjectItem> projectItems) {
if (projectItems != null) {
mProjectItems.addAll(projectItems);
mProjectTreeItemAdapter.setData(mProjectItems);
}
}
};
}
| UTF-8 | Java | 3,995 | java | CompleteProjectArticleFragment.java | Java | [
{
"context": "recyclerview.widget.RecyclerView;\n\n\n/**\n * @author jere\n */\npublic class CompleteProjectArticleFragment e",
"end": 888,
"score": 0.995091438293457,
"start": 884,
"tag": "USERNAME",
"value": "jere"
},
{
"context": " final String PROJECT_ITEM_ID_KEY = \"PROJECT_ITEM... | null | [] | package com.jere.test.article.view.completeproject;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.jere.test.R;
import com.jere.test.article.modle.beanfiles.completeproject.ProjectTreeItem;
import com.jere.test.article.view.ProjectItemListActivity;
import com.jere.test.article.viewmodel.completeproject.ProjectTreeItemViewModel;
import com.jere.test.home.HomeActivity;
import com.jere.test.util.RecyclerItemClickListener;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
/**
* @author jere
*/
public class CompleteProjectArticleFragment extends Fragment {
public static final String PROJECT_ITEM_ID_KEY = "PROJECT_ITEM_ID";
private ProjectTreeItemAdapter mProjectTreeItemAdapter;
private ArrayList<ProjectTreeItem.ProjectItem> mProjectItems = new ArrayList<>();
private RecyclerView mProjectTreeItemRecyclerView;
public CompleteProjectArticleFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_complete_project, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ProjectTreeItemViewModel projectTreeItemVm = new ViewModelProvider(this).get(ProjectTreeItemViewModel.class);
projectTreeItemVm.getProjectTreeItemsLd().observe(getViewLifecycleOwner(), projectItemsObserver);
projectTreeItemVm.setProjectTreeItemsLd();
mProjectTreeItemAdapter = new ProjectTreeItemAdapter(mProjectItems);
mProjectTreeItemRecyclerView = view.findViewById(R.id.projectTreeItemsRcv);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
mProjectTreeItemRecyclerView.setLayoutManager(layoutManager);
mProjectTreeItemRecyclerView.setAdapter(mProjectTreeItemAdapter);
mProjectTreeItemRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(),
mProjectTreeItemRecyclerView,
new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
ProjectTreeItem.ProjectItem projectItem = mProjectItems.get(position);
Intent intent = new Intent(getActivity(), ProjectItemListActivity.class);
intent.putExtra(PROJECT_ITEM_ID_KEY, projectItem.getId());
startActivity(intent);
}
@Override
public void onLongItemClick(View view, int position) {
//todo need to handle onLongItemClick event.
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
}));
}
private Observer<ArrayList<ProjectTreeItem.ProjectItem>> projectItemsObserver = new Observer<ArrayList<ProjectTreeItem.ProjectItem>>() {
@Override
public void onChanged(@Nullable ArrayList<ProjectTreeItem.ProjectItem> projectItems) {
if (projectItems != null) {
mProjectItems.addAll(projectItems);
mProjectTreeItemAdapter.setData(mProjectItems);
}
}
};
}
| 3,995 | 0.707635 | 0.707384 | 98 | 39.765305 | 33.758991 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612245 | false | false | 14 |
b304a329afbb6e56bc1780ec7f5bdc5af1e4a1d1 | 22,780,506,559,004 | c3598e2cd45ae6d23e56cdaa4652efee26895c7c | /Directory.java | 556ffd7fd4af9ca94fcc55768d57c6d6a5450fc5 | [] | no_license | ssechoss/FileSystemSimulation | https://github.com/ssechoss/FileSystemSimulation | a2c1c33d38b69e8afaf568b1dabcaadce809ab5f | 3aef66b13b076c399be3929fc7bce129555ec11d | refs/heads/master | 2021-05-03T10:38:52.582000 | 2018-02-07T00:16:51 | 2018-02-07T00:16:51 | 120,539,511 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fileSystemSimulation;
import static fileSystemSimulation.Command.NAME_SIZE;
public class Directory {
private char type;
private char[] name;
private Sector link;// block number of first block of files.
private int size;
public Directory() {
type = 'f';
name = new char[NAME_SIZE];
size = 0;
}
public void intialize() {
type = 'f';
name = new char[NAME_SIZE];
size = 0;
}
public void setDirectory(char type, String name, Sector link) {
this.type = type;
this.name = new char[NAME_SIZE];
System.arraycopy(name.toCharArray(), 0, this.name, 0,
Math.min(name.length(), NAME_SIZE));
this.link = link;
}
public char getType() {
return type;
}
public void setType(char type) {
this.type = type;
}
public char[] getName() {
return name;
}
public void setName(char[] name) {
this.name = name;
}
public Sector getLink() {
return link;
}
public void setLink(Sector link) {
this.link = link;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public boolean hasSameName(String n) {
int i;
for (i = 0; i < n.length(); i++) {
if ((n.charAt(i) != name[i])) {
return false;
}
}
if (name[n.length()] != '\u0000') {
return false;
}
return true;
}
}
| UTF-8 | Java | 1,643 | java | Directory.java | Java | [] | null | [] | package fileSystemSimulation;
import static fileSystemSimulation.Command.NAME_SIZE;
public class Directory {
private char type;
private char[] name;
private Sector link;// block number of first block of files.
private int size;
public Directory() {
type = 'f';
name = new char[NAME_SIZE];
size = 0;
}
public void intialize() {
type = 'f';
name = new char[NAME_SIZE];
size = 0;
}
public void setDirectory(char type, String name, Sector link) {
this.type = type;
this.name = new char[NAME_SIZE];
System.arraycopy(name.toCharArray(), 0, this.name, 0,
Math.min(name.length(), NAME_SIZE));
this.link = link;
}
public char getType() {
return type;
}
public void setType(char type) {
this.type = type;
}
public char[] getName() {
return name;
}
public void setName(char[] name) {
this.name = name;
}
public Sector getLink() {
return link;
}
public void setLink(Sector link) {
this.link = link;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public boolean hasSameName(String n) {
int i;
for (i = 0; i < n.length(); i++) {
if ((n.charAt(i) != name[i])) {
return false;
}
}
if (name[n.length()] != '\u0000') {
return false;
}
return true;
}
}
| 1,643 | 0.493609 | 0.488131 | 76 | 19.618422 | 17.068722 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.486842 | false | false | 14 |
91f85f5825b6abee2b37f5a3ee7545acde746f32 | 26,139,171,032,507 | 6adbda9f6faa1dc86e766d1b82fe3f9c77ad6c75 | /igloo/igloo-components/igloo-component-wicket-more/src/main/java/org/iglooproject/wicket/more/export/SimpleFileDownloadAjaxLink.java | 730cab7cb7b6a92c8e64e0080c61e41f5b5a5690 | [
"Apache-2.0"
] | permissive | igloo-project/igloo-parent | https://github.com/igloo-project/igloo-parent | 61219a09d14b8968838362d76ff77dfdd0cf5e01 | 65e3e8da61e7c07584596b2ad4dc2af3b627a0f0 | refs/heads/dev | 2023-08-17T23:32:47.163000 | 2023-08-10T13:54:18 | 2023-08-10T14:04:50 | 101,907,993 | 20 | 6 | Apache-2.0 | false | 2023-08-10T14:00:32 | 2017-08-30T17:09:22 | 2023-06-09T17:12:19 | 2023-08-10T14:00:30 | 43,672 | 17 | 5 | 9 | Java | false | false | package org.iglooproject.wicket.more.export;
import java.io.File;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.iglooproject.commons.util.mime.MediaType;
import org.iglooproject.wicket.more.export.util.ExportFileUtils;
import org.javatuples.LabelValue;
import igloo.bootstrap.modal.AbstractFileDownloadAjaxLink;
import igloo.bootstrap.modal.WorkInProgressPopup;
public abstract class SimpleFileDownloadAjaxLink extends AbstractFileDownloadAjaxLink {
private static final long serialVersionUID = -1855491000516928812L;
private final IModel<String> fileNameModel;
public SimpleFileDownloadAjaxLink(String id, WorkInProgressPopup loadingPopup, String fileNamePrefix, MediaType mediaType) {
this(id, loadingPopup, Model.of(fileNamePrefix), Model.of(mediaType));
}
public SimpleFileDownloadAjaxLink(String id, WorkInProgressPopup loadingPopup, IModel<String> fileNamePrefixModel, IModel<MediaType> mediaTypeModel) {
this(id, loadingPopup, ExportFileUtils.getFileNameMediaTypeModel(fileNamePrefixModel, mediaTypeModel));
}
public SimpleFileDownloadAjaxLink(String id, WorkInProgressPopup loadingPopup, IModel<String> fileNameModel) {
super(id, loadingPopup);
this.fileNameModel = fileNameModel;
}
@Override
protected LabelValue<String, File> generateFileInformation() {
return LabelValue.with(
fileNameModel.getObject(),
generateFile()
);
}
protected abstract File generateFile();
}
| UTF-8 | Java | 1,463 | java | SimpleFileDownloadAjaxLink.java | Java | [] | null | [] | package org.iglooproject.wicket.more.export;
import java.io.File;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.iglooproject.commons.util.mime.MediaType;
import org.iglooproject.wicket.more.export.util.ExportFileUtils;
import org.javatuples.LabelValue;
import igloo.bootstrap.modal.AbstractFileDownloadAjaxLink;
import igloo.bootstrap.modal.WorkInProgressPopup;
public abstract class SimpleFileDownloadAjaxLink extends AbstractFileDownloadAjaxLink {
private static final long serialVersionUID = -1855491000516928812L;
private final IModel<String> fileNameModel;
public SimpleFileDownloadAjaxLink(String id, WorkInProgressPopup loadingPopup, String fileNamePrefix, MediaType mediaType) {
this(id, loadingPopup, Model.of(fileNamePrefix), Model.of(mediaType));
}
public SimpleFileDownloadAjaxLink(String id, WorkInProgressPopup loadingPopup, IModel<String> fileNamePrefixModel, IModel<MediaType> mediaTypeModel) {
this(id, loadingPopup, ExportFileUtils.getFileNameMediaTypeModel(fileNamePrefixModel, mediaTypeModel));
}
public SimpleFileDownloadAjaxLink(String id, WorkInProgressPopup loadingPopup, IModel<String> fileNameModel) {
super(id, loadingPopup);
this.fileNameModel = fileNameModel;
}
@Override
protected LabelValue<String, File> generateFileInformation() {
return LabelValue.with(
fileNameModel.getObject(),
generateFile()
);
}
protected abstract File generateFile();
}
| 1,463 | 0.818182 | 0.805195 | 43 | 33.023254 | 38.152382 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.534884 | false | false | 14 |
30412ec1e1b5b3daebdce6aeb8884a491033ca0a | 21,225,728,377,953 | 357688b297d4cc4564c3e979839d69bd3225fa19 | /app/src/main/java/com/openclassrooms/entrevoisins/ui/neighbour_list/DetailActivity.java | dc99c5e43c5a1f4b4c94ce38e1786cc7a74c5f2d | [] | no_license | lioneldg/entrevoisins | https://github.com/lioneldg/entrevoisins | d98b13aead599e3645f553a85241258e487b0048 | cb4b3f77763ac55caedcba45940eeee89824b99c | refs/heads/master | 2023-01-14T11:08:54.644000 | 2020-11-15T09:30:32 | 2020-11-15T09:30:32 | 308,913,562 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.openclassrooms.entrevoisins.ui.neighbour_list;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.openclassrooms.entrevoisins.R;
import com.openclassrooms.entrevoisins.di.DI;
import com.openclassrooms.entrevoisins.model.Neighbour;
public class DetailActivity extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_neighbour);
Long id = getIntent().getLongExtra("id", 999);
String name = getIntent().getStringExtra("name");
String address = getIntent().getStringExtra("address");
String phoneNumber = getIntent().getStringExtra("phoneNumber");
String aboutMe = getIntent().getStringExtra("aboutMe");
String avatarUrl = getIntent().getStringExtra("avatarUrl");
final Boolean[] isFavorite = {DI.getNeighbourApiService().isFavoriteNeighbour(id)};
ImageView avatar;
ImageButton backButton;
FloatingActionButton favorite;
TextView firstName, firstNameInWhiteView, addressTextView, phoneNumberTextView, aboutMeTextView, facebook;
avatar = (ImageView) findViewById(R.id.photo);
Glide.with(avatar.getContext())
.load(avatarUrl)
.apply(RequestOptions.centerCropTransform())
.into(avatar);
backButton = (ImageButton) findViewById(R.id.backButton);
backButton.getBackground().setAlpha(0);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
favorite = (FloatingActionButton) findViewById(R.id.favoriteButton);
favorite.setImageResource(isFavorite[0] ? R.drawable.ic_star_white_24dp : R.drawable.ic_star_border_white_24dp);
favorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isFavorite[0] = !isFavorite[0];
favorite.setImageResource(isFavorite[0] ? R.drawable.ic_star_white_24dp : R.drawable.ic_star_border_white_24dp);
Neighbour neighbour = DI.getNeighbourApiService().findNeighbourById(id); //retrouve ce contact grace à l'id
if(isFavorite[0]){ //ajoute ou supprime de la liste en fct de isFavorite[0]
DI.getNeighbourApiService().addFavoriteNeighbour(neighbour);
}
else{
DI.getNeighbourApiService().deleteFavoriteNeighbour(neighbour);
}
}
});
firstName = (TextView)findViewById(R.id.firstName);
firstName.setText(name);
firstNameInWhiteView = (TextView) findViewById(R.id.firstNameInViewWhite);
firstNameInWhiteView.setText(name);
addressTextView = (TextView) findViewById(R.id.address);
addressTextView.setText(" "+address);
phoneNumberTextView = (TextView)findViewById(R.id.phoneNumber);
phoneNumberTextView.setText(" "+phoneNumber);
aboutMeTextView = (TextView)findViewById(R.id.description);
aboutMeTextView.setText(aboutMe);
facebook = (TextView) findViewById(R.id.facebook);
facebook.setText(" www.facebook.fr/"+name.toLowerCase());
}
}
| UTF-8 | Java | 4,079 | java | DetailActivity.java | Java | [] | null | [] | package com.openclassrooms.entrevoisins.ui.neighbour_list;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.openclassrooms.entrevoisins.R;
import com.openclassrooms.entrevoisins.di.DI;
import com.openclassrooms.entrevoisins.model.Neighbour;
public class DetailActivity extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_neighbour);
Long id = getIntent().getLongExtra("id", 999);
String name = getIntent().getStringExtra("name");
String address = getIntent().getStringExtra("address");
String phoneNumber = getIntent().getStringExtra("phoneNumber");
String aboutMe = getIntent().getStringExtra("aboutMe");
String avatarUrl = getIntent().getStringExtra("avatarUrl");
final Boolean[] isFavorite = {DI.getNeighbourApiService().isFavoriteNeighbour(id)};
ImageView avatar;
ImageButton backButton;
FloatingActionButton favorite;
TextView firstName, firstNameInWhiteView, addressTextView, phoneNumberTextView, aboutMeTextView, facebook;
avatar = (ImageView) findViewById(R.id.photo);
Glide.with(avatar.getContext())
.load(avatarUrl)
.apply(RequestOptions.centerCropTransform())
.into(avatar);
backButton = (ImageButton) findViewById(R.id.backButton);
backButton.getBackground().setAlpha(0);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
favorite = (FloatingActionButton) findViewById(R.id.favoriteButton);
favorite.setImageResource(isFavorite[0] ? R.drawable.ic_star_white_24dp : R.drawable.ic_star_border_white_24dp);
favorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isFavorite[0] = !isFavorite[0];
favorite.setImageResource(isFavorite[0] ? R.drawable.ic_star_white_24dp : R.drawable.ic_star_border_white_24dp);
Neighbour neighbour = DI.getNeighbourApiService().findNeighbourById(id); //retrouve ce contact grace à l'id
if(isFavorite[0]){ //ajoute ou supprime de la liste en fct de isFavorite[0]
DI.getNeighbourApiService().addFavoriteNeighbour(neighbour);
}
else{
DI.getNeighbourApiService().deleteFavoriteNeighbour(neighbour);
}
}
});
firstName = (TextView)findViewById(R.id.firstName);
firstName.setText(name);
firstNameInWhiteView = (TextView) findViewById(R.id.firstNameInViewWhite);
firstNameInWhiteView.setText(name);
addressTextView = (TextView) findViewById(R.id.address);
addressTextView.setText(" "+address);
phoneNumberTextView = (TextView)findViewById(R.id.phoneNumber);
phoneNumberTextView.setText(" "+phoneNumber);
aboutMeTextView = (TextView)findViewById(R.id.description);
aboutMeTextView.setText(aboutMe);
facebook = (TextView) findViewById(R.id.facebook);
facebook.setText(" www.facebook.fr/"+name.toLowerCase());
}
}
| 4,079 | 0.665768 | 0.660863 | 95 | 41.926315 | 33.830303 | 180 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.694737 | false | false | 14 |
855cf49289bbd8c56c48c11a5509f4fa925a4450 | 11,501,922,482,627 | 8ea5843290044aa9319e16ff531205f8b7093542 | /Exabit/src/main/java/com/exabit/Services/MessagePropertiesEntityServiceImpl.java | 66d996491587aad943c836818d67b4445d2bd600 | [
"Apache-2.0"
] | permissive | Casperinous/Exabit | https://github.com/Casperinous/Exabit | 5fb068cbd88e6dec12698128c457c7d5c841a5b2 | 0af440d900196353d6609b107d20c36de0379a44 | refs/heads/master | 2020-03-21T09:05:02.191000 | 2018-06-23T07:56:31 | 2018-06-23T07:56:31 | 138,380,871 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.java.com.exabit.Services;
import main.java.com.exabit.Entities.MessagePropertiesEntity;
import main.java.com.exabit.Repositories.MessagePropertiesEntityRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
@Transactional
@Service
public class MessagePropertiesEntityServiceImpl implements MessagePropertiesEntityService {
private static final Logger LOGGER = LoggerFactory.getLogger(MessagePropertiesEntityServiceImpl.class);
@Resource
private MessagePropertiesEntityRepository repository;
public MessagePropertiesEntity create(MessagePropertiesEntity messagepropertiesentity) {
return repository.save(messagepropertiesentity);
}
public void delete(Integer id) {
repository.delete(id);
}
public List<MessagePropertiesEntity> findAll() {
return (List<MessagePropertiesEntity>) repository.findAll();
}
public MessagePropertiesEntity findById(Integer id) {
return repository.findOne(id);
}
public MessagePropertiesEntity update(MessagePropertiesEntity messagepropertiesentity) {
return repository.save(messagepropertiesentity);
}
public List<MessagePropertiesEntity> findByidMessageAndidUser(int idMessage, int idUser) {
return repository.findByIdMessageAndIdUser(idMessage,idUser);
}
@Override
public Long countByidUser(int idUser) {
return repository.countByidUser(idUser);
}
@Override
public List<MessagePropertiesEntity> findByIdUser(int idUser) {
return repository.findByIdUser(idUser);
}
}
| UTF-8 | Java | 1,864 | java | MessagePropertiesEntityServiceImpl.java | Java | [] | null | [] | package main.java.com.exabit.Services;
import main.java.com.exabit.Entities.MessagePropertiesEntity;
import main.java.com.exabit.Repositories.MessagePropertiesEntityRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
@Transactional
@Service
public class MessagePropertiesEntityServiceImpl implements MessagePropertiesEntityService {
private static final Logger LOGGER = LoggerFactory.getLogger(MessagePropertiesEntityServiceImpl.class);
@Resource
private MessagePropertiesEntityRepository repository;
public MessagePropertiesEntity create(MessagePropertiesEntity messagepropertiesentity) {
return repository.save(messagepropertiesentity);
}
public void delete(Integer id) {
repository.delete(id);
}
public List<MessagePropertiesEntity> findAll() {
return (List<MessagePropertiesEntity>) repository.findAll();
}
public MessagePropertiesEntity findById(Integer id) {
return repository.findOne(id);
}
public MessagePropertiesEntity update(MessagePropertiesEntity messagepropertiesentity) {
return repository.save(messagepropertiesentity);
}
public List<MessagePropertiesEntity> findByidMessageAndidUser(int idMessage, int idUser) {
return repository.findByIdMessageAndIdUser(idMessage,idUser);
}
@Override
public Long countByidUser(int idUser) {
return repository.countByidUser(idUser);
}
@Override
public List<MessagePropertiesEntity> findByIdUser(int idUser) {
return repository.findByIdUser(idUser);
}
}
| 1,864 | 0.757511 | 0.756438 | 55 | 31.890909 | 31.044058 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 14 |
60d054e293b1be6cbb06e689f8596253c381543f | 171,798,697,900 | a7b5d9fee7ecbb6acb9d4515805cceb599a5e928 | /Java/lab5/zadanie5_Maciej_Michalec.java | 5c58a6b9365499050527e1a757e0a549be476f9a | [] | no_license | trivelt/academic-projects | https://github.com/trivelt/academic-projects | 942246d636f8554e623638e2ce24de062faea9ce | a862251d2ac9b7e6cd609182a348b9aa58c88591 | refs/heads/master | 2021-09-11T01:33:46.060000 | 2018-04-05T19:28:54 | 2018-04-05T19:28:54 | 68,510,744 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Move2D implements Move2DInterface {
double krok;
int licznik=0;
double posX=0;
double posY=0;
boolean setStep=false;
public void setStep( double step ){
krok = step;
setStep=true;
}
public void north(){
if(setStep==true){
posY=posY+krok;
licznik++;
}
}
public void south(){
if(setStep==true){
posY=posY-krok;
licznik++;
}
}
public void east(){
if(setStep==true){
posX=posX+krok;
licznik++;
}
}
public void west(){
if(setStep==true){
posX=posX-krok;
licznik++;
}
}
public int getSteps(){
return licznik;
}
public double getDistance(){
return Math.sqrt((Math.pow(posX,2) + Math.pow(posY,2)));
}
public double getSumAbsDistance(){
return Math.abs(posX)+Math.abs(posY);
}
}
| UTF-8 | Java | 743 | java | zadanie5_Maciej_Michalec.java | Java | [] | null | [] | class Move2D implements Move2DInterface {
double krok;
int licznik=0;
double posX=0;
double posY=0;
boolean setStep=false;
public void setStep( double step ){
krok = step;
setStep=true;
}
public void north(){
if(setStep==true){
posY=posY+krok;
licznik++;
}
}
public void south(){
if(setStep==true){
posY=posY-krok;
licznik++;
}
}
public void east(){
if(setStep==true){
posX=posX+krok;
licznik++;
}
}
public void west(){
if(setStep==true){
posX=posX-krok;
licznik++;
}
}
public int getSteps(){
return licznik;
}
public double getDistance(){
return Math.sqrt((Math.pow(posX,2) + Math.pow(posY,2)));
}
public double getSumAbsDistance(){
return Math.abs(posX)+Math.abs(posY);
}
}
| 743 | 0.643338 | 0.633917 | 53 | 13.018867 | 12.463517 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.471698 | false | false | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.