blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
132 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
75cc28c34e28f3e7bf485825800e4971a5de246d
540d56e24fa1d5c3875bb80a36d416ee4a5d26e8
/commonlib/src/main/java/com/leifu/commonlib/view/dialog/LoadingUtil.java
57875154dd71bd76f0ff664c790767899ddf804b
[]
no_license
leifu1107/CommonLibDemo
f44e7b29aa68ce6dbb673f01712c206ba00d1886
14ec822400678b25e402d03f0273376cf3e0f323
refs/heads/master
2020-09-13T18:17:10.463701
2020-08-28T09:15:40
2020-08-28T09:15:40
222,865,651
1
0
null
null
null
null
UTF-8
Java
false
false
1,435
java
package com.leifu.commonlib.view.dialog; import android.app.Activity; import java.lang.ref.WeakReference; /** * 控制一个页面不能有多个Dialog */ public class LoadingUtil { private static WeakReference<Activity> mThreadActivityRef; private static WeakReference<LoadingDialog> waitDialog; /** * 自定义用于等待的dialog,有动画和message提示 * 调用stopWaitDialog()方法来取消 * * @param activity * @param message */ public static void showLoading(Activity activity, String message) { if (waitDialog != null && waitDialog.get() != null && waitDialog.get().isShowing()) { waitDialog.get().dismiss(); } if (activity == null || activity.isFinishing()) { return; } mThreadActivityRef = new WeakReference<>(activity); waitDialog = new WeakReference<>(new LoadingDialog(mThreadActivityRef.get(), message)); if (waitDialog.get() != null && !waitDialog.get().isShowing()) { // waitDialog.get().setCanceledOnTouchOutside(false); // waitDialog.get().setCancelable(false); waitDialog.get().show(); // } } /** * 取消等待dialog */ public static void dismissLoading() { if (waitDialog != null && waitDialog.get() != null && waitDialog.get().isShowing()) { waitDialog.get().dismiss(); } } }
[ "leilifu@landsky.cn" ]
leilifu@landsky.cn
fe7423ae5b9bfb1c4f2b85693279531dc77ea61f
0c464a18a90dd3cf80213ff4dad3d7b361d44b39
/app/src/main/java/common/jlt/com/testdemo/customviewpager/CustomHorizontalActivity.java
801f0ccef1b090ba7da15d324117326571767b0e
[]
no_license
NavyLegend/TestDemo
c4be440e7cca2457ff8066fef911b1835b2dd851
bd0d442cde823cb829d73e06ad78d7864dd1e04b
refs/heads/master
2021-01-21T06:39:27.455795
2018-03-31T11:56:26
2018-03-31T11:56:26
83,257,408
0
0
null
null
null
null
UTF-8
Java
false
false
880
java
package common.jlt.com.testdemo.customviewpager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import common.jlt.com.testdemo.R; public class CustomHorizontalActivity extends AppCompatActivity { private CustomHorizontalView container; private int[] imageRes={R.mipmap.pic_1,R.mipmap.pic_2,R.mipmap.pic_6,R.mipmap.pic_4,R.mipmap.pic_5}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_horizontal); container = ((CustomHorizontalView) findViewById(R.id.container)); for (int i = 0; i <imageRes.length ; i++) { ImageView imageView=new ImageView(this); imageView.setImageResource(imageRes[i]); container.addView(imageView); } } }
[ "1593025619@qq.com" ]
1593025619@qq.com
0b67a90ae59ae3a207516456c0f45e6e8e431e9e
342774807fd35ccede7d3ef8b1bf3c9dee18f153
/app/src/main/java/co/gofun/funanimation/MathUtil.java
5c5b8cfd9251a38f7d57ba0cdcbb72ab5eadaefc
[]
no_license
StayZeal/FunAnimation
5749350897081a079b5fb73382781e5603a4c51f
e9e236a42ebe6c3ce4f5b174d8c36fa664606d9b
refs/heads/master
2021-01-01T18:36:18.823414
2018-10-26T11:06:42
2018-10-26T11:08:22
98,376,660
0
0
null
null
null
null
UTF-8
Java
false
false
1,495
java
package co.gofun.funanimation; import android.util.Log; import android.util.SparseArray; public class MathUtil { public static final String TAG = "MathUtil"; /** * * @param x * @param offsetX * @return */ public static double getY(float x, float offsetX,float amplitude ) { // x = x * Math.PI / 180;//转化为弧度 double x45 = Math.pow(4 / (Math.pow(x, 4) + 4), 2.5); double result = amplitude * x45 * Math.sin(0.75 * Math.PI * x - Math.PI * offsetX); // Log.i(TAG, "Result:" + result); return result; } /** * 计算波形函数中x对应的y值 * * @param mapX 换算到[-2,2]之间的x值 * @param offset 偏移量 * @return */ public static double calcValue(float mapX, float offset) { int keyX = (int) (mapX * 1000); offset %= 2; double sinFunc = Math.sin(0.75 * Math.PI * mapX - offset * Math.PI); double recessionFunc; if (recessionFuncs.indexOfKey(keyX) >= 0) { recessionFunc = recessionFuncs.get(keyX); } else { recessionFunc = Math.pow(4 / (4 + Math.pow(mapX, 4)), 2.5); recessionFuncs.put(keyX, recessionFunc); } double amplitude = 0.5; double result = amplitude * sinFunc * recessionFunc; Log.i(TAG, "calcValue result:" + result); return result; } static SparseArray<Double> recessionFuncs = new SparseArray<>(); }
[ "yangfeng@xiniubox.com" ]
yangfeng@xiniubox.com
f7edf2575818985f88ed7f11401ff17248ec219d
4bd60a4243f613873102b8135ca771363161a07d
/temp/src/main/java/com/iteco/temp/controller/MainController.java
e04f658eb6f5ede157e5ace1d2f26bbf79f85fbf
[]
no_license
Lupachik/testiteco
32ba58b124fe3f620bdef146ce3c466fdc5e87e2
50bee7398ffd8baec733de80fe043b3c03d20483
refs/heads/master
2020-12-08T15:30:20.552513
2020-01-10T14:05:10
2020-01-10T14:05:10
233,017,995
0
0
null
null
null
null
UTF-8
Java
false
false
981
java
package com.iteco.temp.controller; import com.iteco.temp.repos.TaskRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class MainController { @Autowired private TaskRepo taskRepo; // ("/temp") меняем на корень("/") @GetMapping("/") public String temp(Model model) { return "temp"; } // вместо Model model, можно указать Map<String, Object> model // соответственно вместо model.addAttribute будет model.put // не указывая в скобках ссылку подразумеваем корневую страницу // 4 этап выводим ее в отдельную страницу @GetMapping("/main") public String main(Model model){ return "main"; } }
[ "lupachik@gmail.com" ]
lupachik@gmail.com
1b3d04f0b5f5183bb875634a8b93efa8ac4da299
b68f98d5771fea532e7e30fe2e7ecdb06ec0f68f
/src/basics/methods/MethodsMain.java
bcacbf4cabacbc567f707b4113f55250dc4a7b82
[]
no_license
SubhasmitaBehera/java-practice
e65e19d659daf01f2f7a5b41d158434ee5799107
8a0d75e2aa24b881b854cb91b0b472a8cde372e5
refs/heads/master
2023-02-21T09:30:24.415508
2021-01-20T17:39:39
2021-01-20T17:39:39
298,865,398
1
0
null
null
null
null
UTF-8
Java
false
false
352
java
package basics.methods; public class MethodsMain { public static void rite(){ System.out.println("My name is Ritz"); } public static void main(String[] args) { rite(); MyMethod obj = new MyMethod(); obj.meth(); } } class MyMethod{ public void meth(){ System.out.println("Hello"); } }
[ "beherasubhasmita1999@gmail.com" ]
beherasubhasmita1999@gmail.com
19147cf206e3fb855e213ffe9569b2cd3d536624
fee0576ee6f23f8f969ae3750402cd8b25e37474
/demo-service/src/test/com/hzq/demo/threads/PriorityDemo.java
67cb8d699164ab30ab8f81d26a025dc750c6a4ec
[]
no_license
xingxingshi/demo-parent
31696f4cd2de169b87078f9ee7aef9e713fa0fbf
e498732111208f51ecab3682bb5902081fbd8ddb
refs/heads/master
2023-08-03T04:22:40.886707
2022-05-19T06:46:44
2022-05-19T06:46:44
214,148,356
0
0
null
2023-07-22T18:23:43
2019-10-10T10:01:06
Java
UTF-8
Java
false
false
737
java
package com.hzq.demo.threads; import java.util.stream.IntStream; /** * @author HZQ * @description * @Date: 3/10/21 * @Time: 6:18 PM */ public class PriorityDemo { public static class T1 extends Thread { @Override public void run() { super.run(); System.out.println(String.format("当前执行的线程是:%s,优先级:%d", Thread.currentThread().getName(), Thread.currentThread().getPriority())); } } public static void main(String[] args) { IntStream.range(1, 10).forEach(i -> { Thread thread = new Thread(new T1()); thread.setPriority(i); thread.start(); }); } }
[ "huangziqiang@souche.com" ]
huangziqiang@souche.com
48b4fa790d335f4c098f652fdc3de253bda1f71c
027082c8e57797443240fc4d88a65f95ae2e15c0
/backend-api/src/main/java/ru/students/lab/weblab4/security/jwt/JwtUtils.java
8ac5c287c057de760af2aa0dac846af7ef668112
[]
no_license
joseortiz9/WebLab4
6b7ed9a63154760e86db0a0ba05a23e1e875f2fe
acf2b5cefa8798dd1ca273ea45a62bb0f93a8431
refs/heads/main
2023-02-19T21:19:03.321905
2021-01-23T06:43:58
2021-01-23T06:43:58
319,239,389
1
3
null
null
null
null
UTF-8
Java
false
false
2,546
java
package ru.students.lab.weblab4.security.jwt; import io.jsonwebtoken.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import ru.students.lab.weblab4.exceptions.JwtTokenValidationException; import java.util.Date; @Component public class JwtUtils { private static final Logger LOG = LoggerFactory.getLogger(JwtUtils.class); private static final SignatureAlgorithm HASH_ALGO = SignatureAlgorithm.HS512; @Value("${weblab.app.jwtSecret}") private String jwtSecret; @Value("${weblab.app.jwtExpirationMs}") private int jwtExpirationMs; public String parseJwt(String headerRequest) { if (StringUtils.hasText(headerRequest) && headerRequest.startsWith("Bearer ")) { return headerRequest.substring(7); } return null; } public String generateJwtToken(Authentication authentication) { return Jwts.builder() .setSubject(((User) authentication.getPrincipal()).getUsername()) .setIssuedAt(new Date()) .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs)) .signWith(HASH_ALGO, jwtSecret) .compact(); } public String getUserNameFromJwtToken(String token) { return Jwts.parser() .setSigningKey(jwtSecret) .parseClaimsJws(token) .getBody().getSubject(); } public void validateJwtToken(String authToken) { try { Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken); } catch (SignatureException e) { throw new JwtTokenValidationException("Invalid JWT signature: " + e.getMessage(), e); } catch (MalformedJwtException e) { throw new JwtTokenValidationException("Invalid JWT token: " + e.getMessage(), e); } catch (ExpiredJwtException e) { throw new JwtTokenValidationException("JWT token is expired: " + e.getMessage(), e); } catch (UnsupportedJwtException e) { throw new JwtTokenValidationException("JWT token is unsupported: " + e.getMessage(), e); } catch (IllegalArgumentException e) { throw new JwtTokenValidationException("JWT claims string is empty: " + e.getMessage(), e); } } }
[ "joseco04@live.com" ]
joseco04@live.com
e55e1e81eea30c219bfef0217764c500e19c01b2
7bd6c40b2cfa30536894f3f77dc4ce055a274f21
/src/main/java/com/tess/entities/OrderE.java
60933e574e9dd7a5061d35e12014b415d1c21a7a
[]
no_license
onesunvan/PizzaDelivery
2005d6427850e0b8b911c2cf018ba5a5123e51a1
45e167e9044372319dcfe9a09857fef7ae8f2eab
refs/heads/master
2021-01-17T06:34:38.917275
2015-04-21T01:28:11
2015-04-21T01:28:11
32,591,127
0
0
null
null
null
null
UTF-8
Java
false
false
3,829
java
package com.tess.entities; import com.tess.annotations.OrderAnno; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.MapKeyJoinColumn; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.springframework.context.annotation.Scope; /** * * @author ivan */ @OrderAnno @Scope(value = "prototype") @Entity @Table(name = "orders") @NamedQueries({ @NamedQuery(name = "Order.findAll", query = "SELECT o FROM OrderE o"), @NamedQuery(name = "Order.findCustomerPeriod", query = "SELECT o FROM OrderE o " + "WHERE o.customer=:customer AND " + "o.date > :minDate AND o.date < :maxDate") }) public class OrderE implements Serializable { @Id @GeneratedValue private Long id; @Temporal(TemporalType.DATE) private Date date; private String name; private Double price = 0.; @Enumerated(EnumType.STRING) private OrderStatus status; // @OneToMany(fetch = FetchType.EAGER) // @JoinColumn(name = "order_id") // private Set<PizzaOrder> pizzaOrders = new LinkedHashSet<>(); @ElementCollection @CollectionTable(name = "pizza_orders", joinColumns = @JoinColumn(name = "order_id")) @MapKeyJoinColumn(name = "pizza_id", referencedColumnName = "id") @Column(name = "amount") private Map<Pizza, Integer> pizzas = new HashMap<>(); @ManyToOne @JoinColumn(name = "customer_id") private Customer customer; public OrderE(Long id, Date date, String name) { this.id = id; this.date = date; this.name = name; } public OrderE() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getName() { return name; } public void setName(String name) { this.name = name; } // public Set<PizzaOrder> getPizzaOrders() { // return pizzaOrders; // } // // public void setPizzaOrders(Set<PizzaOrder> pizzaOrders) { // this.pizzaOrders = pizzaOrders; // } // // public Double getPrice() { // return price; // } // // public void addPizzaOrder(PizzaOrder pizzaOrder) { // pizzaOrders.add(pizzaOrder); // price += pizzaOrder.getPizza().getPrice(); // } @Override public String toString() { return "OrderE{" + "id=" + id + ", date=" + date + ", name=" + name + ", price=" + price + ", status=" + status + ", pizzas=" + pizzas + ", customer=" + customer + '}'; } public OrderStatus getStatus() { return status; } public void setStatus(OrderStatus status) { this.status = status; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Map<Pizza, Integer> getPizzas() { return pizzas; } public void setPizzas(Map<Pizza, Integer> pizzas) { this.pizzas = pizzas; } }
[ "onesunvan@gmail.com" ]
onesunvan@gmail.com
8c5173f7c9d3b82c32834eb10eb2114ccf86d3f8
5530b6e6f955980eea2c9ecbb2c18282c42ef897
/src/main/java/ua/edu/npu/thread/MyThread.java
3facf1bd86e623c875579cb085e590825b14972d
[]
no_license
powerex/ThreadDemo
5f67a310492b221788fe58a1bcd8b0944baa7c50
f4aa8f48296320c85f2ee141f149977a8e68b5a9
refs/heads/master
2020-06-13T06:15:15.672958
2019-07-03T11:23:31
2019-07-03T11:23:31
194,567,158
0
0
null
null
null
null
UTF-8
Java
false
false
547
java
package ua.edu.npu.thread; public class MyThread extends Thread{ @Override public void run() { try { System.out.println("I am demon " + this.isDaemon()); Thread.sleep(3000); System.out.println(Thread.currentThread().getName() + " running myThread"); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + " I am interrupted! ******"); } //System.out.println(Thread.currentThread().getName() + " running myThread"); } }
[ "flaxazbest@gmail.com" ]
flaxazbest@gmail.com
6e290ef7e7d45a64c1bc01c39b2f3f76a60ac2bb
10453af683a820da106c803e58a4b7a1dec0d2ec
/src/test/java/com/automation/integration/CaseOneIT.java
b8bc2b3625c2abc7e0dfedc71168864e4cb2d9e3
[]
no_license
tanki60/SeleniumDev
9237c283e2406a753d4359f9b63035f775a5d95f
9cd1426e641f57956b69d99f176febc2bd40a241
refs/heads/master
2021-01-25T08:00:58.982758
2017-08-04T03:11:16
2017-08-04T03:11:16
93,697,710
0
0
null
null
null
null
UTF-8
Java
false
false
1,220
java
package com.automation.integration; import java.util.Date; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; import com.automation.dto.RegisterNewUser; import com.automation.dto.UpdateNewUserProfile; import com.automation.dto.UserSignIn; import com.automation.dto.UserSignOut; public class CaseOneIT extends BaseSuiteIT { UserSignIn signIn; UpdateNewUserProfile updateProfile; UserSignOut userEndSession; RegisterNewUser newUser; SoftAssert softAssert = null; Date date; @BeforeMethod public void logStartTimeForEachTest() { // add time for performance } @Test(priority = 1) public void register() { newUser = new RegisterNewUser(driver, extentLogger); newUser.registerUser(); } @Test(priority = 2, dependsOnMethods = { "register" }) public void updateProfile() { updateProfile = new UpdateNewUserProfile(driver, extentLogger); updateProfile.updateProfile(); } @Test(priority = 3) public void signOut() { userEndSession = new UserSignOut(driver, extentLogger); } @AfterMethod public void logEndTimeForEachTest() { // add time for performance } }
[ "tanki60@gmail.com" ]
tanki60@gmail.com
8fb089536a02d465beeda67c6391a65e79aa56a8
03539dfb4d2448426c9ddd8fe8813586b960cd3b
/groza-common/transport/src/main/java/com/sanshengshui/server/common/transport/quota/QuotaService.java
f54e71018aa20a9c2f1bc2f034582ea30d15eb51
[ "Apache-2.0" ]
permissive
tonyshen277/Groza
a7ce34ad6b361bf02ce26d85552f8b68d9d8ba2e
0ed5fdd7de27b6d0e546342a3615182fc23cbb8e
refs/heads/master
2020-05-02T03:21:33.061286
2019-05-24T03:59:16
2019-05-24T03:59:16
177,726,695
0
0
Apache-2.0
2019-05-24T03:59:17
2019-03-26T06:19:52
Java
UTF-8
Java
false
false
189
java
package com.sanshengshui.server.common.transport.quota; /** * @author james mu * @date 19-1-23 下午3:30 */ public interface QuotaService { boolean isQuotaExceeded(String key); }
[ "lovewsic@gmail.com" ]
lovewsic@gmail.com
c0dbd1e8e58053adaee5375e5aa1fb8ca6c704eb
dbed19795a1e0ebe40446fb7fe92c1c1b60725ad
/src/main/java/com/sivserver/example/security/SecurityStudentOutPass.java
956d7c00f8172fa1667d201246ac916cfa89b637
[]
no_license
vinothrajux/SIVServer
7aaf1eadd3a76aa2aca58ac45bdcc1b1c61c6173
bb35fd8e815e2f22a1e01767bbefe768e6206bdf
refs/heads/master
2020-03-28T19:51:32.068965
2019-03-31T10:28:09
2019-03-31T10:28:09
94,603,926
0
0
null
null
null
null
UTF-8
Java
false
false
3,044
java
package com.sivserver.example.security; import org.springframework.web.bind.annotation.GetMapping; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import java.util.Date; /** * Created by GBCorp on 03/08/2017. */ @Entity @Table(name = "securitystudentoutpass") public class SecurityStudentOutPass { @Id private String outpassid; private Date currentdate; private String typeofperson; @Column(name="regno") private String regno; private String branchcode; private String batch; private Integer semester; private String academicyear; private Integer nooftimesmonth; private Integer nooftimesoverall; private String reason; private String timeout; private String loginuser; public SecurityStudentOutPass() { } public String getOutpassid() { return outpassid; } public void setOutpassid(String outpassid) { this.outpassid = outpassid; } public Date getCurrentdate() { return currentdate; } public void setCurrentdate(Date currentdate) { this.currentdate = currentdate; } public String getTypeofperson() { return typeofperson; } public void setTypeofperson(String typeofperson) { this.typeofperson = typeofperson; } public String getRegno() { return regno; } public void setRegno(String regno) { this.regno = regno; } public String getBranchcode() { return branchcode; } public void setBranchcode(String branchcode) { this.branchcode = branchcode; } public String getBatch() { return batch; } public void setBatch(String batch) { this.batch = batch; } public Integer getSemester() { return semester; } public void setSemester(Integer semester) { this.semester = semester; } public String getAcademicyear() { return academicyear; } public void setAcademicyear(String academicyear) { this.academicyear = academicyear; } public Integer getNooftimesmonth() { return nooftimesmonth; } public void setNooftimesmonth(Integer nooftimesmonth) { this.nooftimesmonth = nooftimesmonth; } public Integer getNooftimesoverall() { return nooftimesoverall; } public void setNooftimesoverall(Integer nooftimesoverall) { this.nooftimesoverall = nooftimesoverall; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getTimeout() { return timeout; } public void setTimeout(String timeout) { this.timeout = timeout; } public String getLoginuser() { return loginuser; } public void setLoginuser(String loginuser) { this.loginuser = loginuser; } }
[ "informkamalakannan@gmail.com" ]
informkamalakannan@gmail.com
08ee40eb55812bd076f8b21dbae30ea560131cbe
9843a2eb193ff613518b0ee7af6cc136f14e839c
/src/test/java/uz/pdp/HotelApplicationTests.java
6a4627c90d36378f331c3f2b89e46f11353b795e
[]
no_license
Erlan01/Hotel
b96d56de8f134da6955df0340ddb1c4a45f75fbb
93d03653fa6fa56360b8344f86e1f58ef3ffe8d7
refs/heads/master
2023-08-14T05:07:01.063957
2021-09-16T08:22:14
2021-09-16T08:22:14
406,462,702
0
0
null
null
null
null
UTF-8
Java
false
false
206
java
package uz.pdp; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class HotelApplicationTests { @Test void contextLoads() { } }
[ "sultamuratoverlan@gmail.com" ]
sultamuratoverlan@gmail.com
883a3fc7ada04259c78d19ecf77541e8569205d7
80dbb5aa30b58deb884a7a941ec069ba1bbe64c1
/SpringBoot_G11/src/main/java/com/ezen/spg11/controller/UserController.java
888bbfb1d00ac900e29be8c17301ad61342bdc89
[]
no_license
hyezzzzziiiii/academy-Springboot
6a8800dabb0fe1f47d4dc6225a7ae1d30c6adedf
6a88f11a116e95a842513beada22f5072c42917b
refs/heads/master
2023-07-25T16:22:22.302739
2021-09-02T07:13:15
2021-09-02T07:13:15
399,137,026
0
0
null
null
null
null
UTF-8
Java
false
false
577
java
package com.ezen.spg11.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.ezen.spg11.dao.IUserDao; import com.ezen.spg11.dto.UserDto; @Controller public class UserController { @Autowired IUserDao udao; @RequestMapping("/") public String root(Model model){ List<UserDto> list = udao.list(); model.addAttribute("users", list); return "userlist"; } }
[ "hyezzzzziiiii@gnmail.com" ]
hyezzzzziiiii@gnmail.com
27ca1f520677fb9406756a85e9b17db9ebeed8ee
4f013ffc7f817a6bd5a9a8c25c9582944994416d
/respository/5iyoumei/src/com/iyoumei/entity/constant/UserRewardLogConstant.java
8a98c128f343a9e9051c2a7682de77fa8026ad82
[]
no_license
yunchan86/5iym
eceda484cbca76058510c55c557fc01207a2c6cc
4d6518ca4872c38d783c630b5ad6c478ad1f7054
refs/heads/master
2018-12-28T21:16:13.140194
2015-05-20T08:57:17
2015-05-20T08:57:17
34,985,540
0
0
null
null
null
null
UTF-8
Java
false
false
240
java
package com.iyoumei.entity.constant; public class UserRewardLogConstant { public final static String STATUS_DO_NOTHING = "0" ; public final static String STATUS_DO_OK = "1" ; public final static String STATUS_INVALID = "2" ; }
[ "yunchan86@163.com" ]
yunchan86@163.com
45ca92daec427c97ffbcaa953a3a14a4015202d6
69ee0508bf15821ea7ad5139977a237d29774101
/cmis-core/src/main/java/vmware/vim25/ArrayOfAlarmAction.java
c496717190b1eb9013a4b40bfe901763159c486a
[]
no_license
bhoflack/cmis
b15bac01a30ee1d807397c9b781129786eba4ffa
09e852120743d3d021ec728fac28510841d5e248
refs/heads/master
2021-01-01T05:32:17.872620
2014-11-17T15:00:47
2014-11-17T15:00:47
8,852,575
0
0
null
null
null
null
UTF-8
Java
false
false
1,892
java
package vmware.vim25; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ArrayOfAlarmAction complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ArrayOfAlarmAction"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="AlarmAction" type="{urn:vim25}AlarmAction" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ArrayOfAlarmAction", propOrder = { "alarmAction" }) public class ArrayOfAlarmAction { @XmlElement(name = "AlarmAction") protected List<AlarmAction> alarmAction; /** * Gets the value of the alarmAction property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the alarmAction property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAlarmAction().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AlarmAction } * * */ public List<AlarmAction> getAlarmAction() { if (alarmAction == null) { alarmAction = new ArrayList<AlarmAction>(); } return this.alarmAction; } }
[ "brh@melexis.com" ]
brh@melexis.com
f9b0dbb22e74dd09609e25c3ed1340b8bedc12ae
2246623d541429e693930ac7ac71b265dae7e08e
/src/com/gmail/filoghost/ultrahardcore/utils/scatter/SquareSpotsGenerator.java
b3322027ed9a0cfa269a6cee21f391fdde2510d8
[ "BSD-2-Clause" ]
permissive
UnfireGames/UltraHardcore
578ea78c419cf049009bf5bdcabccf639bbf40c5
245f50430140d83960842a80d2f47db2b0e5f8c3
refs/heads/master
2022-04-11T17:16:45.616765
2020-04-01T14:31:55
2020-04-01T14:31:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,512
java
/* * Copyright (c) 2020, Wild Adventure * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * 4. Redistribution of this software in source or binary forms shall be free * of all charges or fees to the recipient of this software. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.gmail.filoghost.ultrahardcore.utils.scatter; import lombok.AllArgsConstructor; import lombok.Getter; public class SquareSpotsGenerator { private int startSide; private Integer[] sideCoords; public SquareSpotsGenerator(int side) { startSide = side; } public XZ[] generate() { if (sideCoords == null) { sideCoords = new Integer[] {-startSide, startSide}; return new XZ[] { new XZ(startSide, startSide), new XZ(startSide, -startSide), new XZ(-startSide, startSide), new XZ(-startSide, -startSide), }; } Integer[] oldSideCoords = sideCoords; sideCoords = new Integer[oldSideCoords.length * 2 - 1]; Integer[] addedCoords = new Integer[sideCoords.length - oldSideCoords.length]; int index = 0; for (int i = 0; i < oldSideCoords.length; i++) { if (i * 2 < sideCoords.length) { sideCoords[i * 2] = oldSideCoords[i]; } } for (int i = 0; i < sideCoords.length; i++) { if (sideCoords[i] == null) { if (i > 0 && i < sideCoords.length - 1) { sideCoords[i] = (sideCoords[i - 1] + sideCoords[i + 1]) / 2; addedCoords[index++] = sideCoords[i]; } } } return generateSpecular(addedCoords); } private XZ[] generateSpecular(Integer[] side) { XZ[] specular = new XZ[side.length * 4]; for (int i = 0; i < side.length; i++) { int value = side[i]; specular[i * 4] = new XZ(startSide, value); specular[i * 4 + 1] = new XZ(- startSide, value); specular[i * 4 + 2] = new XZ(value, startSide); specular[i * 4 + 3] = new XZ(value, - startSide); } return specular; } @AllArgsConstructor @Getter public static class XZ { private int x, z; @Override public String toString() { return "XY[x=" + x + ", z=" + z + "]"; } } }
[ "admin@wildadventure.it" ]
admin@wildadventure.it
0efb761f1b640bdac892ed2768ebe5ecc1bd4987
c34860246f8b4af629741be1ca9c1c05619af977
/book-author-demo-provider/src/main/java/cn/edu/hfut/xc/bookauthordemo/provider/dao/BookWithNationalityMapper.java
8468286d11221b85ef35ebcffeff2c76d933c755
[]
no_license
hahaxiaowei/Book-Author-demo
8a9fa20dec4ad20fcc13227d8636c66ce049471e
36c35b6767274adf3d5196e04d4755cdc140b48b
refs/heads/master
2021-09-06T20:58:10.984503
2018-02-11T08:47:43
2018-02-11T08:47:43
113,283,612
1
0
null
null
null
null
UTF-8
Java
false
false
885
java
package cn.edu.hfut.xc.bookauthordemo.provider.dao; import cn.edu.hfut.xc.bookauthordemo.common.model.Author; import cn.edu.hfut.xc.bookauthordemo.common.model.BookWithNationality; import cn.edu.hfut.xc.bookauthordemo.common.model.BookWithNationalityExample; import java.util.List; public interface BookWithNationalityMapper { long countByExample(BookWithNationalityExample example); int deleteByPrimaryKey(String id); int insert(BookWithNationality record); int insertSelective(BookWithNationality record); List<BookWithNationality> selectByExample(BookWithNationalityExample example); BookWithNationality selectByPrimaryKey(String id); int updateByPrimaryKeySelective(BookWithNationality record); int updateByPrimaryKey(BookWithNationality record); /** * 查询所有作者信息 */ List<BookWithNationality> selectAll(); }
[ "1103361580@qq.com" ]
1103361580@qq.com
4c3a1794fb1660f2caf81f9d8ade38be14c70075
f64c132172f3e1cd0b5f461823b57e2bd5210650
/src/main/java/codegym/service/AppUserService.java
ebb0db163fe9e667b64e424890ce0edf62836b2e
[]
no_license
toannvph05233/DEMO_Spring_JWT
aa2f275d27060306da6c98576ee99ed822e3cce5
b93700ea15c71e50f2410062df4bb4dc79ac11cd
refs/heads/master
2023-07-05T04:39:51.032192
2021-09-01T09:54:10
2021-09-01T09:54:10
402,011,159
0
0
null
null
null
null
UTF-8
Java
false
false
1,385
java
package codegym.service; import codegym.model.AppUser; import codegym.repository.IAppUserRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class AppUserService implements UserDetailsService { @Autowired IAppUserRepo iAppUserRepo; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { AppUser user = iAppUserRepo.findByUsername(username); List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(user.getRole()); UserDetails userDetails = new User( user.getUsername(), user.getPassword(), authorities ); return userDetails ; } public AppUser findByUsername(String username){ return iAppUserRepo.findByUsername(username); } public AppUser save(AppUser appUser){ return iAppUserRepo.save(appUser); } }
[ "johntoan98@gmail.com" ]
johntoan98@gmail.com
f78f185fd93c854c0a6828a82ec1252a1bca4cf4
02cccb69fb8fe937d8a12bbe26694aebe9e31184
/app/src/main/java/com/example/federico/fedextest/MapsActivity.java
b3074bff71537950119fdd14a4ea9de981e939a7
[]
no_license
fmelet/FedexTest
00e6ab4d66285c95b531c203da99c70b494c3fcd
6e22bbee158b026cb52852ddd0825e62ff5749c1
refs/heads/master
2021-01-10T11:42:35.494949
2015-06-06T16:25:28
2015-06-06T16:25:28
36,977,194
0
0
null
null
null
null
UTF-8
Java
false
false
2,649
java
package com.example.federico.fedextest; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity { private GoogleMap mMap; // Might be null if Google Play services APK is not available. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); setUpMapIfNeeded(); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } /** * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly * installed) and the map has not already been instantiated.. This will ensure that we only ever * call {@link #setUpMap()} once when {@link #mMap} is not null. * <p/> * If it isn't installed {@link SupportMapFragment} (and * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to * install/update the Google Play services APK on their device. * <p/> * A user can return to this FragmentActivity after following the prompt and correctly * installing/updating/enabling the Google Play services. Since the FragmentActivity may not * have been completely destroyed during this process (it is likely that it would only be * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this * method in {@link #onResume()} to guarantee that it will be called. */ private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } /** * This is where we can add markers or lines, add listeners or move the camera. In this case, we * just add a marker near Africa. * <p/> * This should only be called once and when we are sure that {@link #mMap} is not null. */ private void setUpMap() { mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker")); } }
[ "fmelet@gmail.com" ]
fmelet@gmail.com
08e2b22cb7da60e9bf528df06835c30918b7d2e5
60771a4f3498b8ddca3f65e5259f20ceb3708006
/src/com/rxjava/chapter3/examples/ErrorOperatorLauncher.java
c53a2711ffcdd6730fe9d8897af2085ff5e7345c
[]
no_license
mikesanchez11/LearningRxJava
69171a2cf71bbc0d01908f8aa030cd7f2eb94292
debf053e7b8910fb8f2039de4d0a7eb4940a74ee
refs/heads/master
2020-04-08T14:01:07.791222
2018-11-28T00:21:34
2018-11-28T00:21:34
159,418,418
0
0
null
null
null
null
UTF-8
Java
false
false
1,214
java
package com.rxjava.chapter3.examples; import io.reactivex.Observable; public class ErrorOperatorLauncher { public static void main(String[] args) { onErrorReturnItemOperator(); retryOperator(); } /* This will retry x amount you want, or indefinite if you don't include the x value. */ private static void retryOperator() { System.out.println("Retry Operator: "); Observable.just(5, 2, 4, 0, 3, 2, 8) .map(i -> 10 / i) .retry(2) .subscribe(i -> System.out.println("RECEIVED: " + i), e -> System.out.println("RECEIVED ERROR: " + e)); System.out.println(); } /* Will return a default value that you give it when an error occurs */ private static void onErrorReturnItemOperator() { System.out.println("On Error Return Item Operator: "); Observable.just(5, 2, 4, 0, 3, 2, 8) .map(i -> 10 / i) .onErrorReturnItem(-1) .subscribe(i -> System.out.println("RECEIVED: " + i), e -> System.out.println("RECEIVED ERROR: " + e)); System.out.println(); } }
[ "michael.sanchez@uber.com" ]
michael.sanchez@uber.com
6e0ccc4e8af9c3b9d1a80297783cb244cae906e5
e20f608607c4f922a186bf8b245f6a2c2ee314d8
/src/zeprs/org/cidrz/webapp/dynasite/utils/SqlGenerator.java
d5d3a0425981dc5e039c0d9e5b1a3d453e242116
[ "Apache-2.0" ]
permissive
rashaatef/zeprs
cb6292f99f81a60d9637a9621f580af5a9d79c98
6ea42325332aab8a331b7683df042b7360b87991
refs/heads/master
2020-05-18T13:46:45.858449
2014-11-04T14:32:06
2014-11-04T14:32:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
28,344
java
/* * Copyright 2003, 2004, 2005, 2006 Research Triangle Institute * * 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 */ package org.cidrz.webapp.dynasite.utils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.cidrz.webapp.dynasite.dao.FormDisplayDAO; import org.cidrz.webapp.dynasite.valueobject.Form; import org.cidrz.webapp.dynasite.valueobject.FormField; import org.cidrz.webapp.dynasite.valueobject.PageItem; import org.cidrz.webapp.dynasite.valueobject.DynaSiteObjects; import org.cidrz.webapp.dynasite.exception.ObjectNotFoundException; import org.cidrz.webapp.dynasite.exception.PersistenceException; import org.cidrz.webapp.dynasite.Constants; import org.cidrz.project.zeprs.valueobject.partograph.PartographMapping; import javax.servlet.ServletException; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.sql.SQLException; import java.sql.Connection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.HashMap; /** * @author <a href="mailto:ckelley@rti.org">Chris Kelley</a> * Date: Jun 13, 2005 * Time: 6:50:04 PM */ public class SqlGenerator { private Log log = LogFactory.getFactory().getInstance(this.getClass().getName()); /** * Iterates through the forms from the database and makes sql files used by dynasite. * @param dev */ public void createSourceFiles(Boolean dev) throws ServletException, PersistenceException, IOException, SQLException { String sqlPathname = null; //sqlPathname = System.getProperty("CATALINA_HOME") + File.pathSeparator + "webapps" + File.pathSeparator + "zeprs" + File.pathSeparator + "WEB-INF" + File.pathSeparator + "classes" + File.pathSeparator + "org" + File.pathSeparator + "cidrz" + File.pathSeparator + "project" + File.pathSeparator + "zeprs" + File.pathSeparator + "valueobject"; if (dev) { sqlPathname = Constants.DEV_RESOURCES_PATH + "generatedSQL.properties"; } else { sqlPathname = Constants.DYNASITE_RESOURCES_PATH + "generatedSQL.properties"; } log.info("generating output SQL file: " + sqlPathname); try { Connection conn = DatabaseUtils.getAdminConnection(); List dbForms = new ArrayList(); List forms = FormDisplayDAO.getAllFormIds(conn); for (Iterator iterator = forms.iterator(); iterator.hasNext();) { Form form = (Form) iterator.next(); Form wholeForm = (Form) FormDisplayDAO.getFormGraph(conn, form.getId()); dbForms.add(wholeForm); } Form form = null; BufferedWriter writer = new BufferedWriter(new FileWriter(sqlPathname)); for (int i = 0; i < dbForms.size(); i++) { form = (Form) dbForms.get(i); //String classname = StringManipulation.fixClassname(form.getName()); String tableName = form.getName().toLowerCase(); try { Iterator dbPageItems2 = form.getPageItems().iterator(); int piCount = 0; while (dbPageItems2.hasNext()) { PageItem pageItem2 = (PageItem) dbPageItems2.next(); FormField formField2 = pageItem2.getForm_field(); if (formField2.isEnabled()) { if (!formField2.getType().equals("Display") && !pageItem2.getInputType().equals("multiselect_enum")) { piCount++; } } } Iterator dbPageItems = form.getPageItems().iterator(); FormField formField = null; // String insertPagerSelect = DatabaseCompatability.insertPagerSelect(databaseType, "?", null); String insertPagerSelect = "SELECT id, "; // setup the auto-generated sql StringBuffer sbufInserts1 = new StringBuffer(2048); StringBuffer sbufInserts2 = new StringBuffer(2048); StringBuffer sbufSelects = new StringBuffer(2048); StringBuffer sbufSelectsPregs = new StringBuffer(2048); // all pregnancies for patient StringBuffer sbufSelectsId = new StringBuffer(2048); StringBuffer sbufSelectsReportId = new StringBuffer(2048); // by id, reports - uses starschemaname StringBuffer sbufSelectsAll = new StringBuffer(2048); // used to generate xml from reports StringBuffer sbufSelectsReport = new StringBuffer(2048); // takes date range and site id StringBuffer sbufSelectsReportAllSites = new StringBuffer(2048); // takes date range only StringBuffer sbufSelectsReportPregs = new StringBuffer(2048); // all pregs. for patient, with report fields StringBuffer sbufSelectsReportPatient = new StringBuffer(2048); // for patient, this pregnancy, with report fields - takes patient id and pregnancy id StringBuffer sBufSelectAllAdminNoEncounterPager = new StringBuffer(2048); // does not join w/ the encounter table sbufInserts1.append("SQL_CREATE" + form.getId() + "=INSERT INTO " + tableName + "(id, "); sbufSelects.append("SQL_RETRIEVE" + form.getId() + "=SELECT encounter.id AS id, "); sbufSelectsPregs.append("SQL_RETRIEVEPREGS" + form.getId() + "=SELECT encounter.id AS id, "); sbufSelectsId.append("SQL_RETRIEVEID" + form.getId() + "=SELECT encounter.id AS id, "); sbufSelectsReportId.append("SQL_RETRIEVE_REPORT_ID" + form.getId() + "=SELECT encounter.id AS id, "); sbufSelectsAll.append("SQL_RETRIEVEALL" + form.getId() + "=SELECT encounter.id AS id, "); sbufSelectsReport.append("SQL_RETRIEVE_REPORT" + form.getId() + "=SELECT encounter.id AS id, "); sbufSelectsReportAllSites.append("SQL_RETRIEVE_REPORT_SITES" + form.getId() + "=SELECT encounter.id AS id, "); sbufSelectsReportPregs.append("SQL_RETRIEVE_REPORT_PREGS" + form.getId() + "=SELECT encounter.id AS id, "); sbufSelectsReportPatient.append("SQL_RETRIEVE_REPORT_PATIENT" + form.getId() + "=SELECT encounter.id AS id, "); if (form.getFormTypeId() == 5 || form.getFormTypeId() == 9 || form.getFormTypeId() == 10 || form.getFormTypeId() == 11) { //admin or header table sBufSelectAllAdminNoEncounterPager.append("SQL_RETRIEVE_ALL_ADMIN_PAGER" + form.getId() + "=" + insertPagerSelect); } int j = 0; // int dbPageItemsSize = form.getPageItems().size(); while (dbPageItems.hasNext()) { PageItem pageItem = (PageItem) dbPageItems.next(); formField = pageItem.getForm_field(); if (formField.isEnabled()) { if (!formField.getType().equals("Display") && !pageItem.getInputType().equals("multiselect_enum")) { j++; String columnName = ""; if (formField.getStarSchemaName().equals("")) { columnName = "field" + formField.getId(); } else { columnName = formField.getStarSchemaName(); } String fieldName = "field" + formField.getId(); sbufInserts1.append(columnName); sbufInserts2.append("? "); sbufSelects.append(columnName + " AS " + fieldName); sbufSelectsPregs.append(columnName + " AS " + fieldName); sbufSelectsId.append(columnName + " AS " + fieldName); sbufSelectsReportId.append(tableName + "." + columnName + " AS " + columnName+"R"); sbufSelectsAll.append(columnName + " AS " + fieldName); sbufSelectsReport.append(tableName + "." + columnName + " AS " + columnName); sbufSelectsReportAllSites.append(tableName + "." + columnName + " AS " + columnName); sbufSelectsReportPregs.append(columnName + " AS " + columnName +"R"); sbufSelectsReportPatient.append(columnName + " AS " + columnName +"R"); if (form.getFormTypeId() == 5 || form.getFormTypeId() == 9 || form.getFormTypeId() == 10 || form.getFormTypeId() == 11) { //admin or header table sBufSelectAllAdminNoEncounterPager.append(columnName + " AS " + fieldName); } if (j < piCount) { sbufInserts1.append(", "); sbufInserts2.append(", "); sbufSelects.append(", "); sbufSelectsPregs.append(", "); sbufSelectsId.append(", "); sbufSelectsReportId.append(", "); sbufSelectsAll.append(", "); sbufSelectsReport.append(", "); sbufSelectsReportAllSites.append(", "); sbufSelectsReportPregs.append(", "); sbufSelectsReportPatient.append(", "); if (form.getFormTypeId() == 5 || form.getFormTypeId() == 9 || form.getFormTypeId() == 10 || form.getFormTypeId() == 11) { //admin or header table sBufSelectAllAdminNoEncounterPager.append(", "); } } } } } sbufSelects.append(", patient_id AS patientId, " + "form_id AS formId, flow_id AS flowId, date_visit AS dateVisit, pregnancy_id AS pregnancyId, " + "last_modified AS lastModified, created AS created, last_modified_by AS lastModifiedBy, " + "created_by AS createdBy, site_id AS siteId, site_name AS siteName, " + "CONCAT_WS(', ', u2.lastname, u2.firstname) AS lastModifiedByName, uuid " + "FROM " + tableName + ", encounter " + "LEFT JOIN site ON site.id=encounter.site_id " + "LEFT JOIN userdata.address u2 ON u2.nickname =encounter.last_modified_by " + "WHERE encounter.id = " + tableName + ".id " + "AND encounter.patient_id=? AND encounter.pregnancy_id=?"); sbufSelectsPregs.append(", patient_id AS patientId, " + "form_id AS formId, flow_id AS flowId, date_visit AS dateVisit, pregnancy_id AS pregnancyId, " + "last_modified AS lastModified, created AS created, last_modified_by AS lastModifiedBy, " + "created_by AS createdBy, site_id AS siteId, site_name AS siteName, " + "CONCAT_WS(', ', u2.lastname, u2.firstname) AS lastModifiedByName, uuid " + "FROM " + tableName + ", encounter " + "LEFT JOIN site ON site.id=encounter.site_id " + "LEFT JOIN userdata.address u2 ON u2.nickname =encounter.last_modified_by " + "WHERE encounter.id = " + tableName + ".id " + "AND encounter.patient_id=?"); sbufSelectsId.append(", patient_id AS patientId, " + "form_id AS formId, flow_id AS flowId, date_visit AS dateVisit, pregnancy_id AS pregnancyId, " + "last_modified AS lastModified, created AS created, last_modified_by AS lastModifiedBy, " + "created_by AS createdBy, site_id AS siteId, site_name AS siteName, " + "CONCAT_WS(', ', u.lastname, u.firstname) AS createdByName, " + "CONCAT_WS(', ', u2.lastname, u2.firstname) AS lastModifiedByName, uuid " + "FROM " + tableName + ", encounter " + "LEFT JOIN site ON site.id=encounter.site_id " + "LEFT JOIN userdata.address u ON u.nickname =encounter.created_by " + "LEFT JOIN userdata.address u2 ON u2.nickname =encounter.last_modified_by " + "WHERE encounter.id = " + tableName + ".id " + "AND encounter.id=?"); sbufSelectsReportId.append(", patient_id AS patientId, " + "form_id AS formId, flow_id AS flowId, date_visit AS dateVisit, pregnancy_id AS pregnancyId, " + "last_modified AS lastModified, created AS created, last_modified_by AS lastModifiedBy, " + "created_by AS createdBy, site_id AS siteId, site_name AS siteName, " + "CONCAT_WS(', ', u.lastname, u.firstname) AS createdByName, " + "CONCAT_WS(', ', u2.lastname, u2.firstname) AS lastModifiedByName " + "FROM " + tableName + ", encounter " + "LEFT JOIN site ON site.id=encounter.site_id " + "LEFT JOIN userdata.address u ON u.nickname =encounter.created_by " + "LEFT JOIN userdata.address u2 ON u2.nickname =encounter.last_modified_by " + "WHERE encounter.id = " + tableName + ".id " + "AND encounter.id=?"); sbufSelectsAll.append(", patient_id AS patientId, " + "form_id AS formId, flow_id AS flowId, date_visit AS dateVisit, pregnancy_id AS pregnancyId, " + "last_modified AS lastModified, created AS created, last_modified_by AS lastModifiedBy, " + "created_by AS createdBy, site_id AS siteId, uuid " + " FROM " + tableName + ", encounter " + "WHERE encounter.id = " + tableName + ".id "); sbufSelectsReport.append(", patient_id AS patientId, " + "encounter.form_id AS formId, encounter.flow_id AS flowId, encounter.date_visit AS dateVisit, encounter.pregnancy_id AS pregnancyId, " + "encounter.last_modified AS lastModified, encounter.created AS created, encounter.last_modified_by AS lastModifiedBy, " + "encounter.created_by AS createdBy, encounter.site_id AS site, " + "patient.surname as surname, patient.first_name AS firstName, " + "patient.district_patient_id AS zeprsId, patient.parent_id AS parentId, " + "CONCAT_WS(',',userdata.address.lastname,userdata.address.firstname) AS staffName " + " FROM " + tableName + ", encounter, patient, userdata.address " + "WHERE encounter.id = " + tableName + ".id " + "AND patient.id = encounter.patient_id " + "AND date_visit >= ? AND date_visit <= ? " + "AND userdata.address.nickname = encounter.last_modified_by " + "AND encounter.site_id = ? " + "ORDER BY date_visit"); sbufSelectsReportAllSites.append(", patient_id AS patientId, " + "encounter.form_id AS formId, encounter.flow_id AS flowId, encounter.date_visit AS dateVisit, encounter.pregnancy_id AS pregnancyId, " + "encounter.last_modified AS lastModified, encounter.created AS created, encounter.last_modified_by AS lastModifiedBy, " + "encounter.created_by AS createdBy, encounter.site_id AS site, " + "patient.surname as surname, patient.first_name AS firstName, " + "patient.district_patient_id AS zeprsId, patient.parent_id AS parentId, " + "CONCAT_WS(',',userdata.address.lastname,userdata.address.firstname) AS staffName " + " FROM " + tableName + ", encounter, patient, userdata.address " + "WHERE encounter.id = " + tableName + ".id " + "AND patient.id = encounter.patient_id " + "AND date_visit >= ? AND date_visit <= ? " + "AND userdata.address.nickname = encounter.last_modified_by " + "ORDER BY date_visit"); sbufSelectsReportPregs.append(", patient_id AS patientId, " + "form_id AS formId, flow_id AS flowId, date_visit AS dateVisit, pregnancy_id AS pregnancyId, " + "last_modified AS lastModified, created AS created, last_modified_by AS lastModifiedBy, " + "created_by AS createdBy, site_id AS siteId, site_name AS siteName, " + "CONCAT_WS(', ', u2.lastname, u2.firstname) AS lastModifiedByName " + "FROM " + tableName + ", encounter " + "LEFT JOIN site ON site.id=encounter.site_id " + "LEFT JOIN userdata.address u2 ON u2.nickname =encounter.last_modified_by " + "WHERE encounter.id = " + tableName + ".id " + "AND encounter.patient_id=?"); sbufSelectsReportPatient.append(", patient_id AS patientId, " + "form_id AS formId, flow_id AS flowId, date_visit AS dateVisit, pregnancy_id AS pregnancyId, " + "last_modified AS lastModified, created AS created, last_modified_by AS lastModifiedBy, " + "created_by AS createdBy, site_id AS siteId, site_name AS siteName, " + "CONCAT_WS(', ', u2.lastname, u2.firstname) AS lastModifiedByName " + "FROM " + tableName + ", encounter " + "LEFT JOIN site ON site.id=encounter.site_id " + "LEFT JOIN userdata.address u2 ON u2.nickname =encounter.last_modified_by " + "WHERE encounter.id = " + tableName + ".id " + "AND encounter.patient_id=? AND encounter.pregnancy_id=?"); if (form.getFormTypeId() == 5 || form.getFormTypeId() == 9 || form.getFormTypeId() == 10 || form.getFormTypeId() == 11) { //admin or header table if (form.getName().equals("user_info")) { sBufSelectAllAdminNoEncounterPager.append(" FROM " + tableName); } } writer.write(sbufInserts1.toString() + ") VALUES (LAST_INSERT_ID(), " + sbufInserts2.toString() + ")"); writer.write("\n"); writer.write(sbufSelects.toString()); writer.write("\n"); writer.write(sbufSelectsPregs.toString()); writer.write("\n"); writer.write(sbufSelectsId.toString()); writer.write("\n"); writer.write(sbufSelectsReportId.toString()); writer.write("\n"); writer.write(sbufSelectsAll.toString()); writer.write("\n"); writer.write(sbufSelectsReport.toString()); writer.write("\n"); writer.write(sbufSelectsReportAllSites.toString()); writer.write("\n"); writer.write(sbufSelectsReportPregs.toString()); writer.write("\n"); writer.write(sbufSelectsReportPatient.toString()); writer.write("\n"); if (form.getFormTypeId() == 5 || form.getFormTypeId() == 9 || form.getFormTypeId() == 10 || form.getFormTypeId() == 11) { //admin or header table writer.write(sBufSelectAllAdminNoEncounterPager.toString()); writer.write("\n"); } } catch (IOException e) { e.printStackTrace(); // System.exit(1); } } HashMap partoQueries = DynaSiteObjects.getPartoQueries(); List classNames = PartographMapping.partoClassNameList(); for (int i = 0; i < classNames.size(); i++) { String className = (String) classNames.get(i); String query = (String) partoQueries.get(className); StringBuffer sbuf = new StringBuffer(2048); sbuf.append("SQL_CREATE_PARTO_" + className.toUpperCase() + "="); sbuf.append(query); writer.write(sbuf.toString()); writer.write("\n"); } writer.close(); if (dev) { sqlPathname = Constants.DEV_RESOURCES_PATH + "generatedSQL.properties"; String sqlPathname2 = Constants.DYNASITE_RESOURCES_PATH + "generatedSQL.properties"; FileUtils.copyQuick(sqlPathname, sqlPathname2); } log.debug("done with generation of SQL"); } catch (NullPointerException e) { log.fatal("caught null pointer exception when building SQL from database. Likely database connection problem. Message: " + e.getMessage()); log.fatal("Also check the file path: " + sqlPathname); throw new ServletException(e); } catch (ObjectNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * Iterates through the forms from the database and makes sql delete script for cleaning up the db. * Only useful in dev mode. * @throws ServletException * @throws PersistenceException * @throws IOException * @throws SQLException */ public void createSqlDeleteScript() throws ServletException, PersistenceException, IOException, SQLException { String sqlScript = null; Boolean dev = DynaSiteObjects.getDev(); if (dev) { sqlScript = Constants.LOCAL_DEV_PATH + "conf\\template\\sql\\deleteGen.sql"; log.info("generating SQL clean file: " + sqlScript); try { Connection conn = DatabaseUtils.getAdminConnection(); List dbForms = new ArrayList(); List forms = FormDisplayDAO.getAllFormIds(conn); for (Iterator iterator = forms.iterator(); iterator.hasNext();) { Form form = (Form) iterator.next(); Form wholeForm = FormDisplayDAO.getFormGraph(conn, form.getId()); dbForms.add(wholeForm); } StringBuffer sbufSql = new StringBuffer(2048); StringBuffer sbufSqlGen = new StringBuffer(2048); sbufSql.append("SET FOREIGN_KEY_CHECKS = 0;\n" + "\n"); sbufSql.append("TRUNCATE TABLE comment;\n" + "TRUNCATE TABLE anteexamvisits;\n" + "TRUNCATE TABLE archivelog;\n" + "TRUNCATE TABLE client_setting;\n" + "TRUNCATE TABLE hiv_report;\n" + "TRUNCATE TABLE infantproblem;\n" + "TRUNCATE TABLE safemotherhood;\n" + "TRUNCATE TABLE subscription;\n" + "TRUNCATE TABLE ttimmunisation;\n" + "TRUNCATE TABLE updatelog;\n" + "TRUNCATE TABLE district_id;\n" + "TRUNCATE TABLE encounter;\n" + // "TRUNCATE TABLE encounter_record;\n" + // "TRUNCATE TABLE encounter_value;\n" + "TRUNCATE TABLE encounter_value_archive;\n" + "TRUNCATE TABLE encounter_archive;\n" + // "TRUNCATE TABLE `info_outcome`;\n" + "TRUNCATE TABLE `outcome_archive`;\n" + "TRUNCATE TABLE `outcome`;\n" + "TRUNCATE TABLE `parto_blood_pressure`;\n" + "TRUNCATE TABLE `parto_cervix`;\n" + "TRUNCATE TABLE `parto_contractions`;\n" + "TRUNCATE TABLE `parto_descent`;\n" + "TRUNCATE TABLE `parto_drugs_dispensed`;\n" + "TRUNCATE TABLE `parto_fetal_hr`;\n" + "TRUNCATE TABLE `parto_liquor`;\n" + "TRUNCATE TABLE `parto_moulding`;\n" + "TRUNCATE TABLE `parto_oxytocin`;\n" + "TRUNCATE TABLE `parto_pulse`;\n" + "TRUNCATE TABLE `parto_respiration`;\n" + "TRUNCATE TABLE `parto_temperature`;\n" + "TRUNCATE TABLE `parto_urinalysis_acetone`;\n" + "TRUNCATE TABLE `parto_urinalysis_glucose`;\n" + "TRUNCATE TABLE `parto_urinalysis_protein`;\n" + "TRUNCATE TABLE `parto_urine_amount`;\n" + "TRUNCATE TABLE `parto_vaginal_exam`;\n" + "TRUNCATE TABLE `partographstatus`;\n" + "TRUNCATE TABLE `patient`;\n" + // "TRUNCATE TABLE `patient_labs`;\n" + "TRUNCATE TABLE `patient_status`;\n" + "TRUNCATE TABLE `pregnancy`;\n" + "TRUNCATE TABLE `problem`;\n" + "TRUNCATE TABLE `problem_archive`;\n" + "TRUNCATE TABLE `referral`;\n" + "TRUNCATE TABLE `referral_reasons`;\n" + "TRUNCATE TABLE `user_group_membership`;\n"); Form form = null; BufferedWriter writer = new BufferedWriter(new FileWriter(sqlScript)); writer.write(sbufSql.toString()); for (int i = 0; i < dbForms.size(); i++) { form = (Form) dbForms.get(i); String tableName = form.getName().toLowerCase(); sbufSqlGen.append("TRUNCATE TABLE " + tableName + ";\n"); } writer.write(sbufSqlGen.toString()); writer.close(); log.debug("done with generation of SQL"); } catch (NullPointerException e) { log.fatal("caught null pointer exception when building SQL from database. Likely database connection problem. Message: " + e.getMessage()); log.fatal("Also check the file path: " + sqlScript); throw new ServletException(e); } catch (ObjectNotFoundException e) { e.printStackTrace(); } } } }
[ "chris@vetula.com" ]
chris@vetula.com
477cdb6f586a3ce749170cbeb5a6fb674b35eadf
c59576925fefe00f891da12171a4f9f580298080
/src/main/java/pack/model/Director.java
e516f2b689d809813bbe5ad5f9dc2949ef3f3992
[]
no_license
Rumorarmonio/SpringDataIMDB
d9ff527cfdd2a705251791104127d8947acabcdf
f70e2170ee6deaa99da87cb8937b4b50fd20a54c
refs/heads/master
2023-02-03T08:27:52.674978
2020-12-23T11:00:53
2020-12-23T11:00:53
320,587,871
0
0
null
null
null
null
UTF-8
Java
false
false
1,656
java
package pack.model; import lombok.*; import javax.persistence.*; import java.util.List; import java.util.Set; @Data // = @Getter + @Setter + @ToString + @RequiredArgsConstructor + @EqualsAndHashCode @NoArgsConstructor @AllArgsConstructor @Entity //даёт понять спрингу, что это сущность, которую нужно сохранять в базе данных @Table(name = "directors") /*Указывает гибернейту, с какой именно таблицей необходимо связать (map) данный класс*/ public class Director { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) /*стратегия генерации первичного ключа, автоинкремент, автогенерация*/ private Integer id; //имя и фамилия режиссёра @Column(name = "first_name") /*определяет, к какому столбцу в таблице БД относится конкретное поле класса (аттрибут класса)*/ private String firstName; @Column(name = "last_name") private String lastName; @ElementCollection(fetch = FetchType.EAGER) //отношение "один ко многим", genres - вложенный @JoinTable(name = "directors_genres") private List<DirectorsGenre> directorsGenres; @ManyToMany(fetch = FetchType.EAGER) //отношение "многие ко многим" @JoinTable(name = "movies_directors", joinColumns = @JoinColumn(name = "director_id"), inverseJoinColumns = @JoinColumn(name = "movie_id")) private Set<Movie> movies; }
[ "yxllwllxy@gmail.com" ]
yxllwllxy@gmail.com
dedfd780e0f8575c7e5306ca43ddcc1d87554ec2
c9b1ef2a4070a9329da6a208005420793efbf49e
/KahIT/app/src/main/java/com/god/kahit/model/VanityItem.java
e6c3fb937aaf561d3a7d444ca340d40c078b96f0
[]
no_license
MiztaOak/OOProjectGoD
b3e9d49bf689c715c82faec1cd45859f11411d54
27f93a2aebd296a7effa4a847d2a62e6703943a6
refs/heads/master
2020-07-18T17:40:06.256698
2019-10-25T22:25:27
2019-10-25T22:25:27
206,285,194
4
3
null
null
null
null
UTF-8
Java
false
false
428
java
package com.god.kahit.model; /** * responsibility: This class is responsible for the cosmetic items in the game. * used-by: This class is used in the following classes: * Player, QuizGame, ItemFactory, Store, ItemDataLoaderRealtime and IItemDataLoader. * * @author Anas Alkoutli */ public class VanityItem extends Item { public VanityItem(int price, String name, String id) { super(price, name, id); } }
[ "peterpirat95@hotmail.com" ]
peterpirat95@hotmail.com
8bdc0927cf32e72cf6580576c2575f6626628b9b
c20e4dad598e04f9fcb65520a1cb23679d721c61
/MyRMIDemo/src/RMIDemoServer.java
0233a20e3020c82fb06935c11b10e83acbd3bc1e
[]
no_license
mosfet386/Discover
4f036b85f23a5efc16c6730cc5433a2568781a90
c25161204d7d608da44980312eb56c4a0c687b03
refs/heads/master
2020-05-16T22:52:07.284821
2014-03-18T01:18:18
2014-03-18T01:18:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
324
java
import java.net.InetAddress; import java.rmi.Naming; public class RMIDemoServer { public static void main(String[] args) throws Exception { RMIDemoImp rmiDemoImp=new RMIDemoImp(); Naming.rebind("RMIDemo", rmiDemoImp); System.out.println("RMIDemo object bound to the name 'RMIDemo' and is ready for use..."); } }
[ "mosfet386@gmail.com" ]
mosfet386@gmail.com
44de9eae6e347679f87c3840c0687a3269f4d1a7
b1cf5bc71d5f225ba3d5c9ed350ab71e01c64d47
/Hackrank/src/GrapTheory/JourneyToMoon.java
d230a82044a138c3c97d9d4ae197f0f4ca1f5624
[]
no_license
rishikyamaji/sample
02c6cd528c60dc7d333a22f62ba63039655a7f12
02c8843e45ebaaa112e5a9e041b8bc36a10cf8e3
refs/heads/master
2021-01-13T04:39:41.588547
2017-01-18T09:50:52
2017-01-18T09:50:52
79,325,990
0
0
null
null
null
null
UTF-8
Java
false
false
584
java
package GrapTheory; import java.util.Arrays; import java.util.Scanner; public class JourneyToMoon { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sn= new Scanner(System.in); int n=sn.nextInt(); int[] array=new int[n]; int i=sn.nextInt(); for(int p=0;p<i*2;p++) { array[p]=sn.nextInt(); } System.out.println(Arrays.asList(array).contains(0)); int count=0; for(int x=0;x<n;x++,x++) { for(int y=x;y<x+2;y++) { for(int z=x+2;z<n;z++) { count++; } } } System.out.println(count); } }
[ "kyamajir@gmail.com" ]
kyamajir@gmail.com
6548740df6e1a280f28603a9e2026dd13aef73fe
a0edc36653932cb16ecee92b2231871208a7b9ac
/app/src/main/java/com/athreyaanand/notescanner/GalleryGridActivity.java
886654c0a7192293e8fefe9603cd6ef504700bec
[]
no_license
athreyaanand/note-scanner
324a1763797a709c40f12eb054eca7571727b6d9
6c3b51365e76ee45d2db167622f715a67f0a6819
refs/heads/master
2021-09-03T09:49:02.611881
2018-01-08T05:38:18
2018-01-08T05:38:18
113,117,537
0
0
null
null
null
null
UTF-8
Java
false
false
11,719
java
package com.athreyaanand.notescanner; // based on http://android-er.blogspot.com.br/2012/07/gridview-loading-photos-from-sd-card.html import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentManager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.afollestad.dragselectrecyclerview.DragSelectRecyclerView; import com.afollestad.dragselectrecyclerview.DragSelectRecyclerViewAdapter; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageSize; import com.athreyaanand.notescanner.helpers.AboutFragment; import com.athreyaanand.notescanner.helpers.Utils; import java.io.File; import java.util.ArrayList; public class GalleryGridActivity extends AppCompatActivity implements ClickListener, DragSelectRecyclerViewAdapter.SelectionListener { private static final String TAG = "GalleryGridActivity"; private MenuItem mShare; private MenuItem mTag; private MenuItem mDelete; private DragSelectRecyclerView recyclerView; private AlertDialog.Builder deleteConfirmBuilder; private boolean selectionMode = false; private ImageLoader mImageLoader; private ImageSize mTargetSize; private SharedPreferences mSharedPref; @Override public void onClick(int index) { if (selectionMode) { myThumbAdapter.toggleSelected(index); } else { Intent i = new Intent(this, FullScreenViewActivity.class); i.putExtra("position", index); this.startActivity(i); } } @Override public void onLongClick(int index) { if (!selectionMode) { setSelectionMode(true); } recyclerView.setDragSelectActive(true, index); } private void setSelectionMode(boolean selectionMode) { if (mShare !=null && mDelete != null ) { mShare.setVisible(selectionMode); mTag.setVisible(selectionMode); mDelete.setVisible(selectionMode); } this.selectionMode = selectionMode; } @Override public void onDragSelectionChanged(int i) { Log.d(TAG, "DragSelectionChanged: "+i); setSelectionMode(i>0); } public class ThumbAdapter extends DragSelectRecyclerViewAdapter<ThumbAdapter.ThumbViewHolder> { private final ClickListener mCallback; ArrayList<String> itemList = new ArrayList<>(); // Constructor takes click listener callback protected ThumbAdapter(GalleryGridActivity activity, ArrayList<String> files) { super(); mCallback = activity; for (String file : files){ add(file); } setSelectionListener(activity); } void add(String path){ itemList.add(path); } @Override public ThumbViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_item, parent, false); return new ThumbViewHolder(v); } @Override public void onBindViewHolder(ThumbViewHolder holder, int position) { super.onBindViewHolder(holder, position); // this line is important! String filename = itemList.get(position); if ( !filename.equals(holder.filename)) { // remove previous image holder.image.setImageBitmap(null); // Load image, decode it to Bitmap and return Bitmap to callback mImageLoader.displayImage("file:///"+filename, holder.image, mTargetSize); // holder.image.setImageBitmap(decodeSampledBitmapFromUri(filename, 220, 220)); holder.filename = filename; } if (isIndexSelected(position)) { holder.image.setColorFilter(Color.argb(300, 139, 209, 243)); } else { holder.image.setColorFilter(Color.argb(0, 0, 0, 0)); } } @Override public int getItemCount() { return itemList.size(); } public ArrayList<String> getSelectedFiles() { ArrayList<String> selection = new ArrayList<>(); for ( Integer i: getSelectedIndices() ) { selection.add(itemList.get(i)); } return selection; } public class ThumbViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{ public final ImageView image; public String filename; public ThumbViewHolder(View itemView) { super(itemView); this.image = (ImageView) itemView.findViewById(R.id.gallery_image); this.image.setScaleType(ImageView.ScaleType.CENTER_CROP); // this.image.setPadding(8, 8, 8, 8); this.itemView.setOnClickListener(this); this.itemView.setOnLongClickListener(this); } @Override public void onClick(View v) { // Forwards to the adapter's constructor callback if (mCallback != null) mCallback.onClick(getAdapterPosition()); } @Override public boolean onLongClick(View v) { // Forwards to the adapter's constructor callback if (mCallback != null) mCallback.onLongClick(getAdapterPosition()); return true; } } } ThumbAdapter myThumbAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSharedPref = PreferenceManager.getDefaultSharedPreferences(this); setContentView(R.layout.activity_gallery); ActionBar actionBar = getSupportActionBar(); assert actionBar != null; actionBar.setDisplayShowHomeEnabled(true); actionBar.setTitle(null); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back_24dp); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build(); mImageLoader = ImageLoader.getInstance(); mImageLoader.init(config); mTargetSize = new ImageSize(220, 220); // result Bitmap will be fit to this size ArrayList<String> ab = new ArrayList<>(); myThumbAdapter = new ThumbAdapter(this, ab ); // new Utils(getApplicationContext()).getFilePaths();); recyclerView = (DragSelectRecyclerView) findViewById(R.id.recyclerview); recyclerView.setLayoutManager(new GridLayoutManager(this, 3)); recyclerView.setAdapter(myThumbAdapter); deleteConfirmBuilder = new AlertDialog.Builder(this); deleteConfirmBuilder.setTitle(getString(R.string.confirm_title)); deleteConfirmBuilder.setMessage(getString(R.string.confirm_delete_multiple_text)); deleteConfirmBuilder.setPositiveButton(getString(R.string.answer_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { deleteImage(); dialog.dismiss(); } }); deleteConfirmBuilder.setNegativeButton(getString(R.string.answer_no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } private void reloadAdapter() { recyclerView.setAdapter(null); // ArrayList<String> ab = new ArrayList<>(); myThumbAdapter = new ThumbAdapter(this, new Utils(getApplicationContext()).getFilePaths()); recyclerView.setAdapter(myThumbAdapter); recyclerView.invalidate(); setSelectionMode(false); } @Override public void onResume() { super.onResume(); reloadAdapter(); } private void deleteImage() { for ( String filePath: myThumbAdapter.getSelectedFiles() ) { final File photoFile = new File(filePath); if (photoFile.delete()) { Utils.removeImageFromGallery(filePath,this); Log.d(TAG,"Removed file: "+filePath); } } reloadAdapter(); } @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_gallery, menu); mShare = menu.findItem(R.id.action_share); mShare.setVisible(false); mTag = menu.findItem(R.id.action_tag); // mTag.setVisible(false); mDelete = menu.findItem(R.id.action_delete); mDelete.setVisible(false); invalidateOptionsMenu(); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch(id) { case android.R.id.home: finish(); break; case R.id.action_share: shareImages(); return true; case R.id.action_tag: break; case R.id.action_delete: deleteConfirmBuilder.create().show(); return true; case R.id.action_about: FragmentManager fm = getSupportFragmentManager(); AboutFragment aboutDialog = new AboutFragment(); aboutDialog.show(fm, "about_view"); break; default: break; } return super.onOptionsItemSelected(item); } public void shareImages() { ArrayList<String> selectedFiles = myThumbAdapter.getSelectedFiles(); if (selectedFiles.size() == 1) { /* Only one scanned document selected: ACTION_SEND intent */ final Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("image/jpg"); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + selectedFiles.get(0))); startActivity(Intent.createChooser(shareIntent, getString(R.string.share_snackbar))); } else { ArrayList<Uri> filesUris = new ArrayList<>(); for (String i : myThumbAdapter.getSelectedFiles()) { filesUris.add(Uri.parse("file://" + i)); } final Intent shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE); shareIntent.setType("image/jpg"); shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, filesUris); startActivity(Intent.createChooser(shareIntent, getString(R.string.share_snackbar))); } } }
[ "31478366+athreyaanand@users.noreply.github.com" ]
31478366+athreyaanand@users.noreply.github.com
5428ddbb99fe18de8fc1481e5050474da6d60947
5487fc6f461799dc55da6e9213f89d234cdf5f15
/td_secu_nomade/src/smali/SmaliAnalyse.java
44c17591ebfcac42fd043912d98ece085ff5f958
[]
no_license
ElodieBouyer/td_secu_nomade
635d816e051cb9d85022e31eb0e2088f370ddd35
6560b79e66a308566a32eb5a8dea4bcaee01f545
refs/heads/master
2020-05-17T23:21:50.712619
2014-11-10T12:02:43
2014-11-10T12:02:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,927
java
package smali; import java.io.BufferedReader; import java.io.IOException; public class SmaliAnalyse { private InformationClass infoClass; private BufferedReader buffer; static private String name = ".class"; static private String method = ".method"; static private String field = ".field"; static private String mstatic = "static"; public SmaliAnalyse() { super(); this.infoClass = new InformationClass(); } public String getInfo(BufferedReader buffer) { this.buffer = buffer; findInfo(); return infoClass.getInfo(); } private void findInfo() { String line = ""; try { while( (line = buffer.readLine()) != null) { if( line.contains(name) ) { while( line.contains(" ") ) { line = line.substring(line.indexOf(" ")+1); } this.infoClass.setName(line.substring(0, line.length()-1)); } else if( line.contains(method)) { line = line.substring(method.length()+1); String access = line.substring(0,line.indexOf(' ')); line = line.substring(access.length()+1); String name; name = line.substring(0,line.indexOf(')')+1); if( name.equals(mstatic)) { access += " "; access += mstatic; line = line.substring(mstatic.length()+1); name = line.substring(0,line.indexOf(')')+1); } this.infoClass.addMethod(name, access); } else if( line.contains(field)) { line = line.substring(field.length()+1); String access = line.substring(0,line.indexOf(' ')); line = line.substring(access.length()+1); if( line.contains(mstatic) ) { access += " "; access += mstatic; line = line.substring(mstatic.length()+1); } String name = line.substring(0,line.indexOf(':')); String type = line.substring(line.indexOf(':')+1); this.infoClass.addField(name, access, type); } } } catch (IOException e) { e.printStackTrace(); } } }
[ "elodie.bouyer@hotmail.fr" ]
elodie.bouyer@hotmail.fr
a8e1b01e0470cbdbf037ac2c41cde5571ad61526
6b1dae6d253b7f273df762b75defb30415d0edce
/src/com/views/dao/impl/UserDaoImpl.java
3bb91932394a75d90c72f409dbeaab62c8903914
[]
no_license
blankorghost/ylb
29c461d6572bf568fb73d266f6971b27e03be342
77bc728dce7d7ba0779ac8b6bb9a22b17584c717
refs/heads/master
2020-03-23T23:31:44.979115
2018-07-25T03:04:50
2018-07-25T03:04:50
142,234,060
0
0
null
null
null
null
UTF-8
Java
false
false
3,778
java
package com.views.dao.impl; import com.views.dao.UserDao; import com.views.entity.User; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.sql.Timestamp; import java.util.Calendar; import java.util.Iterator; import java.util.List; import static com.views.util.viewsUtils.messd; @Transactional(rollbackFor = Exception.class) @Repository("userDao") //进行注入 public class UserDaoImpl implements UserDao { @Resource(name = "sessionFactory") private SessionFactory sessionFactory; @Override public void add(User user) { try { String encodeStr = messd(user.getPassword()); user.setPassword(encodeStr); user.setUserPhoto("user_photo.jpg"); user.setRegistTime(new Timestamp(Calendar.getInstance().getTimeInMillis())); sessionFactory.getCurrentSession().save(user); } catch (Exception e) { throw new RuntimeException(e); } } @Override public boolean login(User user) { try { String encodeStr = messd(user.getPassword()); System.out.println(encodeStr); Iterator<User> it; String hsql = "FROM User where email=? and password=?"; // System.out.println(hsql); Query query = sessionFactory.getCurrentSession().createQuery(hsql); query.setParameter(0, user.getEmail()); query.setParameter(1, encodeStr); System.out.println("1"); System.out.println(user.getEmail()); System.out.println("1"); it = query.iterate(); if (it.hasNext()) { System.out.println("true"); return true; } else { System.out.println("false"); return false; } } catch (Exception e) { throw new RuntimeException(e); } } @Override public List getUser() { return sessionFactory.getCurrentSession().createQuery("FROM User").getResultList(); } @Override public User getUser(int id) { return (User) sessionFactory.getCurrentSession().get(User.class, id); } @Override public List<User> getUser(String email, String password) { Query q = sessionFactory.getCurrentSession().createQuery("FROM User u where u.email = ? and u.password = ?"); q.setParameter(0, email); q.setParameter(1, password); q.setMaxResults(1); return q.getResultList(); } @Override public User getUserByName(String name) { System.out.println(name); Query q = sessionFactory.getCurrentSession().createQuery("FROM User u where u.username = ?"); q.setParameter(0,name); List<User> list = q.list(); if (list.size() > 0){ return list.get(0); } return null; } @Override public User getUserByEmail(String email) { Query q = sessionFactory.getCurrentSession().createQuery("FROM User u where u.email = ?"); q.setParameter(0,email); System.out.println(email); List<User> list = q.list(); if (list.size() > 0){ return list.get(0); } return null; } @Override public void update(User user) { sessionFactory.getCurrentSession().update(user); } @Override public void delete(int id) { sessionFactory.getCurrentSession().delete( sessionFactory.getCurrentSession().get(User.class, id) ); } }
[ "2242546095@qq.com" ]
2242546095@qq.com
c40c35b3b0c35d8ce7c546e9ecff8a33c5895b3b
54af5598de8f8b3d6ba357d9317eac1e61a6e927
/egg-nio/src/main/java/com/egg/integration/eggnio/config/Client.java
7a1d53ed568fc6d8ed56013c03f9a901ecc1b120
[]
no_license
adanli/egg-learn
71710723b5f8bf3e29106836e40cd5df21163538
c875c82bd982f7c432a2864788ad4bfcc4e3ad92
refs/heads/master
2022-12-24T21:01:24.884224
2020-10-02T16:15:58
2020-10-02T16:15:58
298,786,776
0
0
null
null
null
null
UTF-8
Java
false
false
5,026
java
package com.egg.integration.eggnio.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.couchbase.CouchbaseProperties; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; /** * nio client */ public class Client { private static final Logger logger = LoggerFactory.getLogger(Client.class); private static final String remoteServerAddress = "localhost"; private static final int remoteServerPort = 8098; private static final int BUFFER_LENGTH = 1024; private static final byte[] PACKAGE_LENGTH = "Length: ".getBytes(Charset.defaultCharset()); public static void main(String[] args) { int index = 0; SocketChannel client = null; try { client = SocketChannel.open(); client.configureBlocking(false); logger.info("client channel is register: {}", client.isRegistered()); SocketAddress remoteAddress = new InetSocketAddress(remoteServerAddress, remoteServerPort); boolean connect = client.connect(remoteAddress); logger.info("connect {}:{} {}", remoteServerAddress, remoteServerPort, connect); } catch (IOException e) { logger.error("create client error", e); } /*while (true) { if (client != null) { try { client.close(); client = null; }catch (IOException e) { } } }*/ try { while (client!=null && client.finishConnect()) { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_LENGTH); String msg = "hello, i am client"+(index++); buffer.put(msg.getBytes()); buffer.flip(); try { client.write(buffer); }catch (IOException e) { logger.error("", e); } // receive message from server buffer.clear(); try { client.read(buffer); } catch (IOException e) { logger.info("read from server error", e); } buffer.flip(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); logger.info("receive from server: {}", new String(bytes, Charset.defaultCharset())); try { Thread.sleep(5000); }catch (Exception e) { logger.error("", e); } } } catch (IOException e) { logger.error("", e); } finally { if(client != null) try { client.close(); logger.info("close client channel success"); } catch (IOException e) { logger.error("close client channel error", e); } } } /** * like * Length: 1\r\n`${content}\r\n * @param buffer * @param bytes */ private static void write(SocketChannel channel, ByteBuffer buffer, byte[] bytes) { int byteLength = bytes.length; int lengthOfContentLength = length(byteLength); byte[] bs = new byte[PACKAGE_LENGTH.length + 2 + lengthOfContentLength + bytes.length + 2]; int i = 0; for (; i< PACKAGE_LENGTH.length; i++) { bs[i] = PACKAGE_LENGTH[i]; } byte[] bytesOfLengthOfContentLength = new byte[lengthOfContentLength]; convertLengthOfByteLengthIntoBytes(bytes, byteLength); for(int j=0; j<bytesOfLengthOfContentLength.length; j++) { bs[i++] = bytesOfLengthOfContentLength[j]; } bs[i++] = '\r'; bs[i++] = '\n'; for(int j=0; j< bytes.length; j++) { bs[i++] = bytes[j]; } bs[i++] = '\r'; bs[i] = '\n'; buffer.put(bs); buffer.flip(); try { channel.write(buffer); } catch (IOException e) { logger.error("", e); } } /** * convert byte.length.length into byte[] * like 12345 into byte[]{1, 2, 3, 4, 5}, then the length of byte is 5 * @param a * @return */ private static void convertLengthOfByteLengthIntoBytes(byte[] bytes, int a) { for(int i= bytes.length-1; i>=0; i--) { bytes[i] = (byte) (a%10); a = a - a%10; } } private static int length(int a) { if(a == 0) return 0; return length(a/10)+1; } }
[ "adanli@126.com" ]
adanli@126.com
1689f9143860fdee90ac8576013969b0ddb907c5
02191ba00ddfeb1a2fead8db09ab6e3e98ce8967
/sandbox/src/main/java/ru/javajuly/sandbox/Rectangle.java
5e0a2c111b2548b7f650115fb834bb9f124e4fbf
[ "Apache-2.0" ]
permissive
nyohisi/java_july
61a69de6e31bcb45d436be6daa64beaee3344ebc
fa5b8eae72f5831dc76f147065294c1199639f4e
refs/heads/main
2023-07-15T13:57:01.452805
2021-08-27T07:57:24
2021-08-27T07:57:24
385,691,980
0
0
null
null
null
null
UTF-8
Java
false
false
252
java
package ru.javajuly.sandbox; public class Rectangle { public double a; public double b; public Rectangle(double a, double b) { this.a = a; this.b = b; } public double area() { return this.a * this.b; } }
[ "79828785+nyohisi@users.noreply.github.com" ]
79828785+nyohisi@users.noreply.github.com
73ea872b85b842c837d091b018636ced759af792
32d860c3aee52e0c7d525181a61473a95d24f894
/app/src/main/java/sakura/printersakura/Bean/CmdEvent.java
6c6b2c315b0d0bfae175c6583c3993583f4c8102
[]
no_license
zhaolei9527/PrinterSakura-master
f6651f92fc247a09ea42265736cd6e78aa549c2a
dfc75a010cd0d4d313757c479cfd70b9a1576248
refs/heads/master
2020-03-09T21:20:27.145538
2018-04-10T23:28:52
2018-04-10T23:28:52
129,006,530
0
0
null
null
null
null
UTF-8
Java
false
false
601
java
package sakura.printersakura.Bean; /** * sakura.printersakura.Bean * * @author 赵磊 * @date 2018/1/10 * 功能描述: */ public class CmdEvent { private String mMsg; private String mType; public CmdEvent(String msg) { // TODO Auto-generated constructor stub mMsg = msg; mType = ""; } public CmdEvent(String msg, String type) { // TODO Auto-generated constructor stub mMsg = msg; mType = type; } public String getMsg() { return mMsg; } public String getmType() { return mType; } }
[ "sakura@zhaoleideMacBook-Pro.local" ]
sakura@zhaoleideMacBook-Pro.local
a375fa631dd6e332fae93002a19c4d69693efa57
ca821d7d8a0aaddf2f607c37dc1ce9dc4f8e6d8d
/src/com/mistong/interfacetest/testcases/apple/apple_004_orderdata_test.java
68c2d99dcb687ab743a6f8bc61de26cf7029e13f
[]
no_license
kaikela/interfacetest
93fd741468e6806ef90b9d1bcd454e400bc37bd4
d064e010cbb4187e163e1198ed4d9d21cffb9e57
refs/heads/master
2020-12-02T21:12:39.023122
2017-07-05T03:39:28
2017-07-05T03:39:28
96,271,172
0
0
null
null
null
null
UTF-8
Java
false
false
1,660
java
package com.mistong.interfacetest.testcases.apple; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; import org.apache.log4j.Logger; import org.testng.ITestContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.mistong.interfacetest.util.DBHelper; import com.mistong.interfacetest.util.UnirestUtil; import com.mistong.interfacetest.base.BaseParpare; /** * @接口 /api/request.do?msgId=10004 * @描述 IOS订单处理 * @author YY * */ public class apple_004_orderdata_test extends BaseParpare { String memberId = null; // 输出本页面日志 初始化 static Logger logger = Logger.getLogger(apple_004_orderdata_test.class .getName()); @BeforeClass /**接口测试前准备工作*/ public void startTest(ITestContext context) { moduleName = getModuleName(); functionName = getFunctionName(); caseNum = getCaseNum(); // 查询用户的memberId // String qsql1 = "select id from T_MEMBER where MOBILE_NO= '13900000001'"; // ResultSet qrs1 = DBHelper.executeQuery("ikukocesi", qsql1); // try { // while (qrs1.next()) { // memberId = qrs1.getString(1); // } // } catch (SQLException e) { // e.printStackTrace(); // } logger.info(moduleName + "模块" + functionName + "功能" + caseNum + "接口测试开始"); } @Test(dataProvider = "testData") public void testCase(Map<String, String> data) { //进行接口测试,并验证测试结果 UnirestUtil.InterfaceTest(url, StrToMap(data.get("msgId")), // StrToJson(data.get("json").replace("{memberId}", memberId)), StrToJson(data.get("json")), data.get("expect")); } }
[ "yangye@kaike.la" ]
yangye@kaike.la
c9aa5febc04d33e268fc56e9754a95a73691f08b
97e813cafdee389ff8c94c86eba5ff0a524aebf5
/shop-api-order/src/main/java/com/memory/shop/api/order/service/IOrderActionService.java
cff404337e41803ae05cbad5871eea706dcb87ba
[]
no_license
UnknownWall-Z/Model-Shop
b1c39f73bcd9043db735cb3e376370b2183e3733
024edef10f5506d7017d28a66198093ffc390421
refs/heads/master
2021-07-23T04:04:20.878882
2017-10-30T14:54:47
2017-10-30T14:54:47
108,865,250
0
0
null
null
null
null
UTF-8
Java
false
false
253
java
package com.memory.shop.api.order.service; import com.memory.shop.api.order.domain.OrderAction; import java.util.List; /** * Created by 76585 on 2017/10/10. */ public interface IOrderActionService { List<OrderAction> queryByOrderId(Long id); }
[ "564658746@qq.com" ]
564658746@qq.com
9c89ed5de5b4a0dbcddf76b21431dfa034fe557f
a1a7f8ae2dc82943f1c6d6eea23112e8999c326a
/boot-1/src/main/java/com/xyh/boot1/config/MyConfig.java
3449b8cdd792d352e4592cd4b90aae13e97d76f3
[]
no_license
xiayuhu0414/SpringBoot
24c119d3ed7a132af30daa43e715c6c015a315ce
4ca48b1371458f7a6efae6089ab1942cadb33510
refs/heads/master
2023-08-24T14:04:28.314870
2021-10-26T11:02:50
2021-10-26T11:02:50
416,278,766
0
0
null
null
null
null
UTF-8
Java
false
false
2,095
java
package com.xyh.boot1.config; import com.xyh.boot1.bean.Car; import com.xyh.boot1.bean.Pet; import com.xyh.boot1.bean.User; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.ImportResource; /** * @author xyh * @date 2021/10/14 13:42 */ /* * 1.配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的 * 2.配置类本身也是组件 * 3.ProxyBeanMethods:代理Bean的方法 * Full(proxyBeanMethods = true) * Lite(proxyBeanMethods = flase) * 组件依赖 * 4、@Import({User.class,}) * 给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名 * * 5.@ImportResource("classpath:beans.xml")导入spring的配置文件, * */ @Import({User.class,}) @Configuration(proxyBeanMethods = true) //这是一个配置类 //@ConditionalOnBean(name = "tom") @ImportResource("classpath:beans.xml") @EnableConfigurationProperties(Car.class)//1.开启Car配置绑定功能 2.把Car这个组件自动注册到容器中 public class MyConfig { /* * 外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象 * */ //@ConditionalOnBean(name = "tom")//条件装配:当容器中有名为“tom”的组件才会注册组件,也可以标注在类上 //@ConditionalOnMissingBean(name = "tom")// 没有的时候才会装配 @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例。 public User user01(){ User xiayuhu=new User(); //user 组件依赖了Pet组件 xiayuhu.setPet(tomcatPet()); return xiayuhu; } // @Bean("tom") public Pet tomcatPet(){ return new Pet("cat"); } }
[ "jshzxiayuhu@126.com" ]
jshzxiayuhu@126.com
1626b2b02e9000bfebb9b08a1f5da435c2ef7e69
894cac7b94c5515525e6110b62c6a74ff24e22fb
/back-end/src/main/java/com/jcart/modules/config/AuditingConfig.java
6465f279aa97a695b74da5890846803f276a4ff6
[]
no_license
dmfullstack/jcart
7a50a9415bce096cbfe7fe47bf4332394bae8c65
cc4a73614aab6d2ad3e58dc610d4e6b3269ef099
refs/heads/master
2020-03-20T21:23:11.783746
2018-05-31T22:53:33
2018-05-31T22:53:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,346
java
package com.jcart.modules.config; import com.jcart.modules.security.auth.UserPrincipal; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.AuditorAware; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import java.util.Optional; @Configuration @EnableJpaAuditing public class AuditingConfig { @Bean public AuditorAware<Long> auditorProvider() { return new SpringSecurityAuditAwareImpl(); } } class SpringSecurityAuditAwareImpl implements AuditorAware<Long> { @Override public Optional<Long> getCurrentAuditor() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || !authentication.isAuthenticated() || authentication instanceof AnonymousAuthenticationToken) { return Optional.empty(); } UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal(); return Optional.ofNullable(userPrincipal.getId()); } }
[ "frank.mwesigwa1@gmail.com" ]
frank.mwesigwa1@gmail.com
92ad9a8b6188c602ff8d798f618ded3bd469ea9c
dd2571844392a2befb1fd1d85b14f4144a8aa3f6
/DM::OJ/VMSS_Warmup/2_-_Tomb_Robbing/Solution.java
2a32f58b49682a8e02b8d659b8c8bdb6cc95276e
[]
no_license
LamhotJM/Competitive-Programming
5b69a5108cdef525ca518bd97bae526d72c36637
81e9f0f5912d1fd6dfd05b083995ffcbb24b3573
refs/heads/master
2021-01-15T14:23:58.018197
2016-08-24T23:18:05
2016-08-24T23:18:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,116
java
import java.util.*; import java.io.*; public class Solution { static char[][] grid; static int total = 0; static int r; static int c; public static void dfs(int row, int col) { if (row >= r || col >= c || row < 0 || col < 0 || grid[row][col] != '.') return; else { grid[row][col] = '-'; dfs(row, col + 1); dfs(row + 1, col); dfs(row, col - 1); dfs(row - 1, col); } return; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] line = br.readLine().split(" "); r = Integer.parseInt(line[0]); c = Integer.parseInt(line[1]); grid = new char[r][c]; char[] gridLine; for (int i = 0; i < r; i++) { gridLine = br.readLine().toCharArray(); for (int j = 0; j < c; j++) { grid[i][j] = gridLine[j]; } } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (grid[i][j] == '.') { total++; dfs(i, j); } } } System.out.println(total); } }
[ "nonis@protonmail.com" ]
nonis@protonmail.com
94433afcd2fbcec0d08ffb56b761d4d44a995c02
dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9
/data_defect4j/preprossed_method_corpus/Math/4/org/apache/commons/math3/random/RandomDataGenerator_nextGamma_487.java
32b8fbbe72a43655cb4bcdbc49b078ba3c816a7c
[]
no_license
hvdthong/NetML
dca6cf4d34c5799b400d718e0a6cd2e0b167297d
9bb103da21327912e5a29cbf9be9ff4d058731a5
refs/heads/master
2021-06-30T15:03:52.618255
2020-10-07T01:58:48
2020-10-07T01:58:48
150,383,588
1
1
null
2018-09-26T07:08:45
2018-09-26T07:08:44
null
UTF-8
Java
false
false
3,658
java
org apach common math3 random implement link random data randomdata link random gener randomgener instanc gener secur data link java secur secur random securerandom instanc provid data code secur xxx nextsecurexxx code method code random gener randomgener code provid constructor link well19937c gener plug implement implement code random gener randomgener code directli extend link abstract random gener abstractrandomgener support reseed underli pseudo random number gener prng code secur provid securityprovid code code algorithm code code secur random securerandom code instanc reset detail prn prng link java util random link java secur secur random securerandom strong usag note strong instanc variabl maintain code random gener randomgener code code secur random securerandom code instanc data gener gener random sequenc valu string strong strong code random data impl randomdataimpl code instanc repeatedli secur method slower cryptograph secur random sequenc requir secur random sequenc sequenc pseudo random valu addit dispers subsequ valu subsequ length addit properti knowledg valu gener point sequenc make easier predict subsequ valu code random data impl randomdataimpl code creat underli random number gener strong strong initi explicitli seed secur gener seed current time millisecond system ident hash code hold secur gener provid code random gener randomgener code constructor gener reseed constructor reseed code seed rese code code seed secur reseedsecur code method deleg method underli code random gener randomgener code code secur random securerandom code instanc code seed rese code fulli reset initi state secur random number gener reseed specif result subsequ random sequenc seed secur reseedsecur strong strong reiniti secur random number gener secur sequenc start call rese secur reseedsecur ident implement underli code random gener randomgener code code secur random securerandom code instanc synchron guarante thread safe instanc concurr util multipl thread respons client code synchron access seed data gener method version random data gener randomdatagener random data randomdata serializ gener random link org apach common math3 distribut gamma distribut gammadistribut gamma distribut implement algorithm shape ahren dieter comput method sampl gamma beta poisson binomi distribut comput shape marsaglia tsang simpl method gener gamma variabl acm transact mathemat softwar volum issu septemb param shape median gamma distribut param scale scale paramet gamma distribut random sampl gamma shape scale distribut strictli posit except notstrictlypositiveexcept code shape code scale gamma nextgamma shape scale strictli posit except notstrictlypositiveexcept gamma distribut gammadistribut random gener getrandomgener shape scale gamma distribut gammadistribut default invers absolut accuraci sampl
[ "hvdthong@gmail.com" ]
hvdthong@gmail.com
9fc70930825e8fbeb26cbf559583965d0e478044
b6457e182acfe91242bb62328a85f5053de2f581
/src/main/java/rocks/massi/controller/commands/UpdateAllUsersCommand.java
f2743a003b0359ea8babf9c505391ccba60f5a76
[]
no_license
massix/TrollsCli
71709e1086530e25730ee835faff60fa2450a4b5
5349698ef4ba526af26b01c95abca4871ff09623
refs/heads/master
2021-08-10T09:15:51.710696
2017-11-12T12:30:12
2017-11-12T12:30:12
108,025,014
0
0
null
null
null
null
UTF-8
Java
false
false
2,371
java
package rocks.massi.controller.commands; import feign.Response; import org.apache.commons.cli.ParseException; import rocks.massi.controller.authorization.JWTToken; import rocks.massi.controller.data.trolls.Queue; import rocks.massi.controller.data.trolls.User; import java.util.List; public class UpdateAllUsersCommand extends Command { @Override public void run(String[] args) throws ParseException, HelpRequestedException { List<User> users = connector.getAllUsers(); for (User u : users) { Response r = connector.crawlCollection(JWTToken.getInstance().getHeadersMap(), u.getBggNick()); if (r.headers().containsKey("location")) { String location = (String) r.headers().get("location").toArray()[0]; String locationSplit[] = location.split("/"); int queueId = Integer.valueOf(locationSplit[locationSplit.length - 1]); System.out.printf(" -> Monitoring Queue %d\n", queueId); Queue queue = connector.getQueue(JWTToken.getInstance().getHeadersMap(), queueId); while (queue.isRunning()) { System.out.printf("\033[1K\r"); System.out.flush(); System.out.printf(" -> (%d/%d) [%d failed] [%d cache hit]", queue.getCrawled() + queue.getCacheHit(), queue.getTotal(), queue.getFailed(), queue.getCacheHit()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } queue = connector.getQueue(JWTToken.getInstance().getHeadersMap(), queueId); } System.out.printf("\033[1K\r"); System.out.flush(); System.out.printf(" -> (%d/%d) [%d cache hit]\n\n", queue.getCrawled() + queue.getCacheHit(), queue.getTotal(), queue.getCacheHit()); } else { System.err.printf("Something wrong might have happened, I don't have a queue id. Stopping here.\n"); return; } } } @Override public String getName() { return "update-users"; } @Override public String help() { return "update-users\tRecrawl all users"; } }
[ "massimo.gengarelli@gmail.com" ]
massimo.gengarelli@gmail.com
685db14ff5668e34c9512125fcc65b422f1d532f
ba097eb1ba1ebc58468f75640e9c9995fda12fa8
/HuntTheWumpus/src/main/java/com/wumpus/shoot/Shoot.java
e7cc4d67439eb095444ec322b7aad41e6d5819ed
[]
no_license
iscatovic/UncleBob2016
a75bda97c5671252c95b1f8c9194c1cf9f8eb049
f42e7c27bf1a30a03ad173b63a477dbeb6267c6e
refs/heads/master
2021-01-10T10:25:11.705120
2016-03-11T11:55:22
2016-03-11T11:55:22
53,145,265
0
0
null
null
null
null
UTF-8
Java
false
false
163
java
package com.wumpus.shoot; public class Shoot { public static void main(String[] args) { System.out.println("Now we can shoot! Pew Pew, Rambo Rambo!"); } }
[ "kcoles@users.noreply.github.com" ]
kcoles@users.noreply.github.com
7442066670efa987b39b4f82fed8c3de41a4f07a
5fdb04e13f5ea3cddcdf56ab14afa3f308a8a2af
/src/main/java/cn/xawl/by/pojo/Team.java
9a82cadd2d2c3a68feb0fac687d3830c5ee7b922
[]
no_license
DT0814/by
26b60024ec1501adf3013be4749a55aead146141
6f8f8ad02b09027d1008225165f4bd2296e1f244
refs/heads/master
2021-03-30T22:02:54.536472
2018-04-20T02:36:02
2018-04-20T02:36:02
124,543,487
1
0
null
null
null
null
UTF-8
Java
false
false
2,623
java
package cn.xawl.by.pojo; import javax.persistence.*; import java.io.Serializable; @Entity @Table( name = "team" ) public class Team implements Serializable { private String tid; private String name; private String account; private String pass; private String introduce; @Id @Column( name = "TID" ) public String getTid() { return tid; } public void setTid(String tid) { this.tid = tid; } @Basic @Column( name = "name" ) public String getName() { return name; } public void setName(String name) { this.name = name; } @Basic @Column( name = "account" ) public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } @Basic @Column( name = "pass" ) public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } @Basic @Column( name = "introduce" ) public String getIntroduce() { return introduce; } public void setIntroduce(String introduce) { this.introduce = introduce; } @Override public boolean equals(Object o) { if ( this == o ) return true; if ( o == null || getClass() != o.getClass() ) return false; Team team = (Team) o; if ( tid != null ? !tid.equals(team.tid) : team.tid != null ) return false; if ( name != null ? !name.equals(team.name) : team.name != null ) return false; if ( account != null ? !account.equals(team.account) : team.account != null ) return false; if ( pass != null ? !pass.equals(team.pass) : team.pass != null ) return false; if ( introduce != null ? !introduce.equals(team.introduce) : team.introduce != null ) return false; return true; } @Override public int hashCode() { int result = tid != null ? tid.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (account != null ? account.hashCode() : 0); result = 31 * result + (pass != null ? pass.hashCode() : 0); result = 31 * result + (introduce != null ? introduce.hashCode() : 0); return result; } @Override public String toString() { return "Team{" + "tid='" + tid + '\'' + ", name='" + name + '\'' + ", account='" + account + '\'' + ", pass='" + pass + '\'' + ", introduce='" + introduce + '\'' + '}'; } }
[ "729742011@qq.com" ]
729742011@qq.com
d71158dbb0252b6908254b27284de9563eb3efb9
2fc4c7f4762306c5734394566cb47e1f9d733c66
/src/examProject/ui/editUserInfo/EditUserInfoPanel.java
ecc528b014ac33e695c7d43c941f4131f893d68c
[]
no_license
ntn11phm/Exam-Personel-Assignment-Project
47841f1f275c6f63e5d56ad545cece9e4fa74fe7
6f8217fb95caaebc97b33ed4b069ccc8675c5f4a
refs/heads/master
2021-01-02T09:44:07.820878
2015-02-01T19:48:11
2015-02-01T19:48:11
27,164,855
0
0
null
null
null
null
UTF-8
Java
false
false
5,813
java
package examProject.ui.editUserInfo; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import examProject.logic.BackendFacade; import javax.swing.JLabel; import javax.swing.JTextField; public class EditUserInfoPanel extends JPanel { private static final long serialVersionUID = 1L; private JScrollPane scrollPane = new JScrollPane(); private JPanel innerPanel = new JPanel(); private JList<String> hostList = new JList<String>(); private JLabel lblFirstName = new JLabel("Förnamn"); private JLabel lblLastName = new JLabel("Efternamn"); private JLabel lblHosts = new JLabel("Värdar"); private JLabel lblAddress = new JLabel("Adress"); private JLabel lblZip = new JLabel("Postnr"); private JLabel lblCity = new JLabel("Ort"); private JLabel lblPhone = new JLabel("Telenr"); private JLabel lblMobile = new JLabel("Mobilnr"); private JLabel lblEmail = new JLabel("E-post"); private JLabel lblVerEmail = new JLabel("Validera E-post"); private JLabel lblCivic = new JLabel("Person nr"); private JLabel lblStatus = new JLabel(); private JTextField tbFirstName = new JTextField(); private JTextField tbLastName = new JTextField(); private JTextField tbAddress = new JTextField(); private JTextField tbZip = new JTextField(); private JTextField tbCity = new JTextField(); private JTextField tbPhone = new JTextField(); private JTextField tbMobile = new JTextField(); private JTextField tbEmail = new JTextField(); private JTextField tbVerEmail = new JTextField(); private JTextField tbCivic = new JTextField(); private JButton btnUpdate = new JButton("Spara"); private JButton btnRefreashHost = new JButton("Läs om Värdar"); private JCheckBox cbIsActive = new JCheckBox("Aktiv"); private JCheckBox cbIsAdmin = new JCheckBox("Administratör"); public EditUserInfoPanel(BackendFacade backendFacade) { setLayout(null); setBounds(); addCtrls(); EditUserInfoListener eu = new EditUserInfoListener(backendFacade, this); eu.createButtonListeners(); } public void setAdminMode() { lblCivic.setVisible(true); tbCivic.setVisible(true); lblVerEmail.setVisible(true); tbVerEmail.setVisible(true); cbIsAdmin.setVisible(true); cbIsActive.setVisible(true); btnUpdate.setVisible(true); tbFirstName.setEditable(true); tbLastName.setEditable(true); tbAddress.setEditable(true); tbZip.setEditable(true); tbCity.setEditable(true); tbPhone.setEditable(true); tbMobile.setEditable(true); tbEmail.setEditable(true); } public void setHostMode(){ lblCivic.setVisible(false); tbCivic.setVisible(false); lblVerEmail.setVisible(false); tbVerEmail.setVisible(false); cbIsAdmin.setVisible(false); cbIsActive.setVisible(false); btnUpdate.setVisible(false); tbFirstName.setEditable(false); tbLastName.setEditable(false); tbAddress.setEditable(false); tbZip.setEditable(false); tbCity.setEditable(false); tbPhone.setEditable(false); tbMobile.setEditable(false); tbEmail.setEditable(false); } public JList<String> getHostList() { return hostList; } public JLabel getLblStatus() { return lblStatus; } public JTextField getTbFirstName() { return tbFirstName; } public JTextField getTbLastName() { return tbLastName; } public JTextField getTbAddress() { return tbAddress; } public JTextField getTbZip() { return tbZip; } public JTextField getTbCity() { return tbCity; } public JTextField getTbPhone() { return tbPhone; } public JTextField getTbMobile() { return tbMobile; } public JTextField getTbEmail() { return tbEmail; } public JTextField getTbVerEmail() { return tbVerEmail; } public JTextField getTbCivic() { return tbCivic; } public JButton getBtnUpdate() { return btnUpdate; } public JButton getBtnRefreash() { return btnRefreashHost; } public JCheckBox getCbIsActive() { return cbIsActive; } public JCheckBox getCbIsAdmin() { return cbIsAdmin; } private void setBounds() { lblHosts.setBounds(10, 10, 200, 20); scrollPane.setBounds(10, 40, 200, 600); lblFirstName.setBounds(220, 10, 150, 20); tbFirstName.setBounds(220, 40, 150, 20); lblLastName.setBounds(380, 10, 150, 20); tbLastName.setBounds(380, 40, 150, 20); lblAddress.setBounds(220, 70, 310, 20); tbAddress.setBounds(220, 100, 310, 20); lblZip.setBounds(220, 130, 100, 20); tbZip.setBounds(220, 160, 100, 20); lblCity.setBounds(330, 130, 200, 20); tbCity.setBounds(330, 160, 200, 20); lblPhone.setBounds(220, 190, 150, 20); tbPhone.setBounds(220, 220, 150, 20); lblMobile.setBounds(380, 190, 150, 20); tbMobile.setBounds(380, 220, 150, 20); lblEmail.setBounds(220, 250, 310, 20); tbEmail.setBounds(220, 280, 310, 20); lblVerEmail.setBounds(220, 310, 310, 20); tbVerEmail.setBounds(220, 340, 310, 20); lblCivic.setBounds(220, 370, 200, 20); tbCivic.setBounds(220, 400, 200, 20); cbIsActive.setBounds(220, 430, 310, 20); cbIsAdmin.setBounds(220, 460, 310, 20); btnUpdate.setBounds(220, 490, 100, 25); btnRefreashHost.setBounds(220, 586, 150, 23); lblStatus.setBounds(220, 620, 310, 20); } private void addCtrls() { innerPanel.setLayout(null); hostList.setBounds(0,0, 200, 600); innerPanel.add(hostList); scrollPane.setViewportView(innerPanel); add(scrollPane); add(lblHosts); add(lblFirstName); add(tbFirstName); add(lblLastName); add(tbLastName); add(lblAddress); add(tbAddress); add(lblZip); add(tbZip); add(lblCity); add(tbCity); add(lblPhone); add(tbPhone); add(lblMobile); add(tbMobile); add(lblEmail); add(tbEmail); add(lblVerEmail); add(tbVerEmail); add(lblCivic); add(tbCivic); add(cbIsActive); add(cbIsAdmin); add(btnUpdate); add(btnRefreashHost); add(lblStatus); } }
[ "ntn11phm@student.hig.se" ]
ntn11phm@student.hig.se
928d86b427ba63a0d25c7fe33d4f300a86f0c7e0
c60c1edc06117e0ef29975e14cbddd9c870f1ed1
/src/main/java/com/enzo/userservice/domain/User.java
eb630238a81d36bec689e93605e3b9f509925ca3
[]
no_license
django123/userservice
5cb1cf93a64cd04a57da5f3b1e36ae1eb0b3b121
c18425d83455c961b924fd17854d6603d77c7289
refs/heads/master
2023-08-16T23:57:35.857449
2021-09-21T20:22:48
2021-09-21T20:22:48
408,423,603
0
0
null
null
null
null
UTF-8
Java
false
false
635
java
package com.enzo.userservice.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.ManyToAny; import javax.persistence.*; import java.util.ArrayList; import java.util.Collection; import static javax.persistence.FetchType.EAGER; @Entity @Data @NoArgsConstructor @AllArgsConstructor public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String username; private String name; private String password; @ManyToMany(fetch = EAGER) private Collection<Role> roles = new ArrayList<>(); }
[ "edougajean@gmail.com" ]
edougajean@gmail.com
51c80389b7079b4b719a67a99c0298c10abe8c0b
b93bb44a7eb8a2581a1ac296a8278ab2f7c5920a
/src/test/java/com/example/restful/services/util/EmployeeMapperTest.java
8ad03e25dbe23523f218f05033392350a97d3260
[]
no_license
whalewalker/restfulApi
64a35eb42f2fd06a527c6cd3279b5cef87f0d47b
52211544d0144914c3ce73e6d356a099d999b9a9
refs/heads/main
2023-05-27T17:56:53.672833
2021-06-17T16:39:30
2021-06-17T16:39:30
377,798,512
0
0
null
null
null
null
UTF-8
Java
false
false
1,763
java
package com.example.restful.services.util; import com.example.restful.data.model.Employee; import com.example.restful.web.dto.EmployeeDto; import org.apache.catalina.mapper.Mapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers; import static org.assertj.core.api.Assertions.assertThat; class EmployeeMapperTest { EmployeeMapper employeeMapper; @BeforeEach void setUp() { employeeMapper = Mappers.getMapper(EmployeeMapper.class); } @Test void givenEmployeeDtoSourceWhenMappedThenMapCorrectlyTest(){ EmployeeDto employeeDto = new EmployeeDto(); employeeDto.setFirstName("John"); employeeDto.setLastName("Mike"); employeeDto.setRole("Accountant"); Employee employee = new Employee(); employeeMapper.updateEmployeeFromDto(employeeDto, employee); assertThat(employee.getFirstName()).isEqualTo(employeeDto.getFirstName()); assertThat(employee.getLastName()).isEqualTo(employeeDto.getLastName()); assertThat(employee.getRole()).isEqualTo(employeeDto.getRole()); } @Test void nullTest(){ EmployeeDto employeeDto = new EmployeeDto(); employeeDto.setFirstName("John"); employeeDto.setLastName(null); employeeDto.setRole(null); Employee employee = new Employee(); employee.setLastName("Bob"); employee.setFirstName("Dan"); employee.setRole("Mister"); employeeMapper.updateEmployeeFromDto(employeeDto, employee); assertThat(employee.getFirstName()).isEqualTo("John"); assertThat(employee.getLastName()).isEqualTo("Bob"); assertThat(employee.getRole()).isEqualTo("Mister"); } }
[ "mongodbms@gmail.com" ]
mongodbms@gmail.com
18f856b4ea06f31a549728109ff67b95b7742391
bf21b1390cc8974679e4f591a5a7afd83d2b4721
/cucumber/src/cucumber/TestExecution.java
db58ab51765298e4960538e44a44aec6e47d8486
[]
no_license
HimajaReddyYerrabolu/cucumberfirst
28b6c063d8867a32644e495f2245583db7854ed1
9f410e91d8f2a172c112055db9a62228b6b840ea
refs/heads/master
2021-01-17T23:31:01.463093
2016-06-06T02:44:17
2016-06-06T02:44:17
60,396,930
0
0
null
null
null
null
UTF-8
Java
false
false
2,347
java
package cucumber; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class TestExecution { public WebDriver driver; @Given("^user in Kexim Home page$") public void user_in_Kexim_Home_page() { driver = new FirefoxDriver(); driver.get("http://srssprojects.in"); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @When("^user entered valid user name and valid password$") public void user_entered_valid_user_name_and_valid_password() { driver.findElement(By.id("txtuId")).sendKeys("Admin"); driver.findElement(By.id("txtPword")).sendKeys("Admin"); } @When("^user clicked on login button$") public void user_clicked_on_login_button() { driver.findElement(By.id("login")).click(); } @Then("^user get Admin home page with welecome to admin message$") public void user_get_Admin_home_page_with_welecome_to_admin_message() { if (driver.findElement(By.xpath("//img[@src,images/admin_but_03.jpg]")).isDisplayed()) { System.out.println("test passed"); driver.close(); } } @Given("^user is in Kexim Home page$") public void user_is_in_Kexim_Home_page() { // Write code here that turns the phrase above into concrete actions driver = new FirefoxDriver(); driver.get("http://srssprojects.in"); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @When("^user entered valid username$") public void user_entered_valid_username() { // Write code here that turns the phrase above into concrete actions driver.findElement(By.id("txtuId")).sendKeys("Admin"); } @When("^user entered invalid password$") public void user_entered_invalid_password() { driver.findElement(By.id("txtPword")).sendKeys("Adminn"); } @When("^user click on login button$") public void user_click_on_login_button() { driver.findElement(By.id("login")).click(); } @Then("^user get an alert message as invalid username/password$") public void user_get_an_alert_message_as_invalid_username_password() { String text = driver.switchTo().alert().getText(); if(text.contains("invalid")){ System.out.println("test is passed"); } } }
[ "himajamca74@gmail.com" ]
himajamca74@gmail.com
bded90e91ba8d393d330b4b5c66dc5655e5f1cbd
b9cda73f759b80eac1d37b169c76cc90dba059a9
/src/day11/StringEqualityPractice_Condition2.java
57e0a9460b1c962220823292321f59707d5368c5
[]
no_license
musajojo/Moses_CyberTek
07ce383eb2bad72b9601c71bb47ff9d2bc8c6e49
97d8d423d454fdba6ee0ffa3b5d818a51663d97e
refs/heads/master
2020-11-28T13:59:37.913082
2020-06-15T03:52:02
2020-06-15T03:52:02
229,839,863
1
0
null
null
null
null
UTF-8
Java
false
false
569
java
package day11; public class StringEqualityPractice_Condition2 { public static void main(String[] args) { /* *check the value of myStr * if it is Java -->> correct word * if it is Cava -->> Pumpkin!! */ String myString ="cava"; if (myString.equals("java")) { System.out.println(" Say correct word"); } else if ( myString.equals("cava")){ System.out.println(" Say Pumpkin "); } else { System.out.println(" Say not Java nor pumpkin"); } } }
[ "58441332+musajojo@users.noreply.github.com" ]
58441332+musajojo@users.noreply.github.com
fbfc86ada652e494f5f869c5a23e00aec2b2be17
79b8049e04ad322dbf6c7d8b0e3ff55fdb533a4f
/src/main/java/com/sanley/coronavirus/entity/IndexInfo.java
997fccd3f0f8fa34e8f9aa58da57f0d1cfd5d572
[]
no_license
songHai-Henry/Coronavirus
bdfd5b0d824aa3b2656c7b9081cc73adaca93149
598812a494d2980423f3cc77412281803dd6e8d3
refs/heads/master
2023-08-15T20:13:54.801476
2021-10-13T09:48:00
2021-10-13T09:48:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
637
java
package com.sanley.coronavirus.entity;/* Created by shkstart on 2020/3/13. */ import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.util.List; @NoArgsConstructor @Data @Accessors(chain=true) public class IndexInfo { private int currentPatientNumber; private int sumPatientNumber; private int deadNumber; private double deadRate; private int cureNumber; private double cureRate; private int sumTouchNumber; private int currentTouchNumber; private List dates; private List patientNums; private List cureNums; private String username; }
[ "786836525@qq.com" ]
786836525@qq.com
5bd24c2e087f0a8c45cb316b99b9265663b13839
c8412c01ac07271af40ff508109b673aa2caaf5b
/web/src/main/java/com/whiteplanet/web/entry/doctor/DoctorIllnessBean.java
484960d958d2ffce157a2ca48ffaf51aad8f7f3c
[]
no_license
brayJava/bray
d40c1878d4b93def8a1991261965663e91804643
3ffd52b13a1447bc94f24320607fa535df1a7a4e
refs/heads/master
2020-03-24T20:28:39.281546
2018-07-31T08:45:16
2018-07-31T08:45:16
142,980,114
0
0
null
null
null
null
UTF-8
Java
false
false
1,064
java
package com.whiteplanet.web.entry.doctor; /** * @author:wuzhiyuan * @description: 医生擅长的疾病bean * @date: Created in 10:13 2017/12/26 * @modified By: */ public class DoctorIllnessBean { /** * 功能科室id */ private String departmentFunctionId; /** * 功能科室名称 */ private String departmentFunctionName; /** * 疾病名称bean */ private IllnessBean illness; public String getDepartmentFunctionId() { return departmentFunctionId; } public void setDepartmentFunctionId(String departmentFunctionId) { this.departmentFunctionId = departmentFunctionId; } public String getDepartmentFunctionName() { return departmentFunctionName; } public void setDepartmentFunctionName(String departmentFunctionName) { this.departmentFunctionName = departmentFunctionName; } public IllnessBean getIllness() { return illness; } public void setIllness(IllnessBean illness) { this.illness = illness; } }
[ "1318134732@qq.com" ]
1318134732@qq.com
36563d9d2c02224947a9584d38409e29d6ef2517
7c5ac4aca76f26e38f0701f44b4f80d071c1bd8c
/app/src/main/java/www/fiberathome/com/parkingapp/utils/AppConfig.java
ea536c7c2c505eb3b7f496196d039d9bf6d371a8
[]
no_license
sakhawat19/ParkingApp
3acc17bdd63e32a14183fc045cbb985d95c6c4ea
3fee91df2c8165c57717487f425134ada40f6a08
refs/heads/master
2020-03-12T14:50:08.391050
2018-07-26T10:14:22
2018-07-26T10:14:22
130,675,145
0
0
null
null
null
null
UTF-8
Java
false
false
969
java
package www.fiberathome.com.parkingapp.utils; public class AppConfig { // ROOT URL private static final String ROOT_URL = "http://163.47.157.195/cportal/parkingapp/"; public static final String URL_REGISTER = ROOT_URL + "request_sms.php"; public static final String URL_LOGIN = ROOT_URL + "verify_user.php"; public static final String URL_VERIFY_OTP = ROOT_URL + "verify_otp.php"; public static final String IMAGES_URL = "http://163.47.157.195/cportal/parkingapp/uploads/"; // Retrofit URLs public static final String URL_CHANGE_PASSWORD = ROOT_URL + "change_password.php/"; // SMS provider identification // It should match with your SMS gateway origin // You can use MSGIND, TESTER and ALERTS as sender ID // If you want custom sender Id, approve Msg91 to get one public static final String SMS_ORIGIN = "PARKINGAPP_"; public static final String SHARED_PREFERENCES = ""; }
[ "you@example.com" ]
you@example.com
dd3ec3669b45848c642d2242da9d59bb52d60b12
3c244340c7b4f508b221c1eae0839a96d49188c4
/Max Points on a Line.java
f95bbda4cc0e9d9d975cc442cc5cabdcfd1e0ea9
[]
no_license
liuyingchao/my
d6b89341b1b332517cf09b67f9633be15b929875
16b705b13567c00a2698f9de1a68dc197d547f03
refs/heads/master
2021-07-08T19:09:08.119184
2021-04-19T05:17:13
2021-04-19T05:17:13
14,101,663
0
0
null
null
null
null
UTF-8
Java
false
false
1,227
java
/** Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. Copied from https://github.com/mengli/leetcode/blob/master/MaxPointsOnALine.java * Definition for a point. * class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */ public class Solution { public int maxPoints(Point[] points) { Map<Double, Integer> map = new HashMap<Double, Integer>(); int ret = 0; int size = points.length; for (int i = 0; i < size; i++) { int invalidK = 0; int add = 1; for (int j = i + 1; j < size; j++) { if (points[j].x == points[i].x) { if (points[j].y == points[i].y) { add++; } else { invalidK++; } continue; } double k = points[j].y == points[i].y ? 0.0 : (1.0 * (points[j].y - points[i].y)) / (points[j].x - points[i].x); if (map.containsKey(k)) { int count = map.get(k); map.put(k, count + 1); } else { map.put(k, 1); } } for (Integer it : map.values()) { if (it + add > ret) { ret = it.intValue() + add; } } ret = Math.max(invalidK + add, ret); map.clear(); } return ret; } }
[ "liuyingchao@users.noreply.github.com" ]
liuyingchao@users.noreply.github.com
984e40bc309148606f675759ae8c0c27b98fe844
ce2714fd47415c3dbb22d3dec24a797945fd5f42
/src/com/桥接模式高淇/Dell.java
5a2fa8e6067bccc4670fdd32131a3045ce84827b
[]
no_license
flying81621/design-pattern
02fc543a7ae4caf1fd6e3dda925c24b59c076cd5
aeb80870629cb623cfaf7d22dd25ded934c8b7f0
refs/heads/master
2020-06-30T07:47:17.579415
2019-08-06T03:33:43
2019-08-06T03:33:43
200,769,936
0
0
null
null
null
null
UTF-8
Java
false
false
267
java
package com.桥接模式高淇; /** * * @createTime 2018年3月3日 上午10:24:38 * @author MrWang */ public class Dell implements Brand { @Override public void sale() { // TODO Auto-generated method stub System.out.println("销售戴尔电脑"); } }
[ "wangyafei02@meicai.cn" ]
wangyafei02@meicai.cn
98d2e30d0a619033af77ae607a3ecba310caff27
ed14f2dc0ce1a671f3742cf6c99433cf82663964
/src/main/java/fr/ariouz/ultimateutilities/utils/MessageUtils.java
7979a05e7a6211adb68cb51acc413cbad7121def
[]
no_license
Ariouz/UltimateUtilities
8b1670e660e3f4c8b95d0d30e9ed7681c273dd3d
6891f04eba35aa1adf007dd6dbf73cd51ede41cb
refs/heads/main
2023-04-14T18:27:28.556899
2021-04-26T14:00:40
2021-04-26T14:00:40
361,753,441
1
0
null
null
null
null
UTF-8
Java
false
false
1,201
java
package fr.ariouz.ultimateutilities.utils; import fr.ariouz.ultimateutilities.UltimateUtilities; import fr.ariouz.ultimateutilities.managers.config.ConfigPaths; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.ArrayList; public class MessageUtils { private final UltimateUtilities ultimateUtilities; public MessageUtils(UltimateUtilities ultimateUtilities){ this.ultimateUtilities = ultimateUtilities; } public ArrayList<String> getMessages(CommandSender commandSender, ConfigPaths path){ ArrayList<String> l = new ArrayList<>(); ultimateUtilities.getMessagesConfig().getList(path.getPath()).forEach(t -> l.add(ChatColor.translateAlternateColorCodes('&', t.toString()))); return l; } public ArrayList<String> getMessages(Player player, ConfigPaths path){ ArrayList<String> l = new ArrayList<>(); ultimateUtilities.getMessagesConfig().getList(path.getPath()).forEach(t -> l.add(ChatColor.translateAlternateColorCodes('&', PlaceholderAPI.setPlaceholders(player, t.toString())))); return l; } }
[ "unconfigured@null.spigotmc.org" ]
unconfigured@null.spigotmc.org
1cfbc2ca1d1b73b777636e82784788d567353ac8
40d38003df4807bf1f00ed1ebcf29d4ce444460d
/src/com/jeta/abeille/gui/main/AboutView.java
3b3d5aa2f67e52e2f58b5413955ddb76902125fc
[]
no_license
jeff-tassin/abeilledb
c869dbd95fc229abc88b7f3938cd932dcedd8099
94ffd3d3dff345e35ed64173833d254685af13a1
refs/heads/master
2023-08-10T16:36:08.328238
2022-01-31T19:46:41
2022-01-31T19:46:41
225,102,904
2
1
null
null
null
null
UTF-8
Java
false
false
7,052
java
package com.jeta.abeille.gui.main; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Insets; import java.awt.LayoutManager; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import com.jeta.foundation.gui.components.TSPanel; import com.jeta.foundation.gui.utils.TSGuiToolbox; import com.jeta.foundation.interfaces.license.LicenseUtils; import com.jeta.foundation.i18n.I18N; /** * This view shows the about information for the product. * * @author Jeff Tassin */ public class AboutView extends TSPanel { /** data model for this view */ private AboutModel m_model; /** size of the splash screen image */ private Dimension m_imagesize; /** the panel that contains the info labels */ private JPanel m_infopanel; private JLabel m_image; private JLabel m_jetaware; /** about labels */ private JLabel[] m_labels; /** about controls */ private JComponent[] m_controls; private static Color m_jetablue = new Color(42, 61, 170); int Y_PADDING = 1; /** * ctor */ public AboutView(AboutModel model) { m_model = model; createView(); loadModel(); revalidate(); doLayout(); } /** * Creates the panel at the bottom of the view showing * license/version/copyright information Licensed To: Serial Number: * Version: www.jetaware.com Copyright 2002 Jeta Software Inc. Copyright � * 2002 JETA Software Inc. All Rights Reserved */ private JPanel createInfoPanel() { JPanel panel = new InfoPanel(new InfoLayout()); panel.setOpaque(true); panel.setBackground(Color.white); if (LicenseUtils.isEvaluation()) { m_labels = new JLabel[2]; m_labels[0] = new JLabel(I18N.getLocalizedDialogLabel("License")); m_labels[1] = new JLabel(I18N.getLocalizedDialogLabel("Version")); m_controls = new JComponent[2]; m_controls[0] = new JLabel(m_model.getLicenseType()); m_controls[1] = new JLabel(m_model.getVersion()); } else { m_labels = new JLabel[4]; m_labels[0] = new JLabel(I18N.getLocalizedDialogLabel("Licensed To")); m_labels[1] = new JLabel(I18N.getLocalizedDialogLabel("Serial Number")); m_labels[2] = new JLabel(I18N.getLocalizedDialogLabel("License")); m_labels[3] = new JLabel(I18N.getLocalizedDialogLabel("Version")); JLabel serial_no = new JLabel(m_model.getSerialNumber()); m_controls = new JComponent[4]; m_controls[0] = new JLabel(m_model.getLicensee()); m_controls[1] = serial_no; m_controls[2] = new JLabel(m_model.getLicenseType()); m_controls[3] = new JLabel(m_model.getVersion()); } java.awt.Font f = javax.swing.UIManager.getFont("Table.font"); for (int index = 0; index < m_labels.length; index++) { m_labels[index].setFont(f); m_controls[index].setFont(f); panel.add(m_labels[index]); panel.add(m_controls[index]); } panel.doLayout(); return panel; } /** * Creates the panel that contains the main image for the about * * @return the panel */ private void createView() { ImageIcon icon = TSGuiToolbox.loadImage("jeta_about.png"); m_imagesize = new Dimension(icon.getIconWidth(), icon.getIconHeight()); setLayout(new AboutViewLayout()); m_image = new JLabel(icon); m_image.setBorder(BorderFactory.createLineBorder(Color.black)); add(m_image); m_infopanel = createInfoPanel(); add(m_infopanel); ImageIcon bottomicon = TSGuiToolbox.loadImage("about_bottom.png"); m_jetaware = new JLabel(bottomicon); m_jetaware.setBorder(BorderFactory.createLineBorder(Color.black)); m_jetaware.setSize(new Dimension(400, 24)); add(m_jetaware); setOpaque(true); setBackground(m_jetablue); } /** * @return the preferred size for this panel */ public Dimension getPreferredSize() { Dimension d = new Dimension(m_imagesize); d.height = d.height + m_infopanel.getPreferredSize().height + m_jetaware.getPreferredSize().height; // d.height = d.height + m_jetaware.getY() + m_jetaware.getHeight() + // 10; return d; } /** * Loads the datamodel into the view */ private void loadModel() { } public class AboutViewLayout implements LayoutManager { public void addLayoutComponent(String name, Component comp) { } public void layoutContainer(Container parent) { m_image.setSize(new Dimension(parent.getWidth(), m_imagesize.height)); // int x = (parent.getWidth() - m_imagesize.width)/2; // if ( x < 0 ) int x = 0; m_image.setLocation(x, 0); m_infopanel.setLocation(0, m_image.getHeight()); m_infopanel.setSize(new Dimension(parent.getWidth(), m_infopanel.getPreferredSize().height)); // Font f = m_jetaware.getFont(); // FontMetrics metrics = m_jetaware.getFontMetrics(f); // int jware_height = metrics.getHeight() + Y_PADDING + 10; int jware_height = m_jetaware.getHeight(); m_jetaware.setLocation(0, m_infopanel.getY() + m_infopanel.getHeight()); m_jetaware.setSize(new java.awt.Dimension(parent.getWidth(), jware_height)); m_jetaware.setPreferredSize(m_jetaware.getSize()); } public Dimension minimumLayoutSize(Container parent) { return new Dimension(50, 50); } public Dimension preferredLayoutSize(Container parent) { return getPreferredSize(); } public void removeLayoutComponent(Component comp) { } } public class InfoLayout implements LayoutManager { public void addLayoutComponent(String name, Component comp) { } public void layoutContainer(Container parent) { int max_label_width = 0; Font f = m_labels[0].getFont(); FontMetrics metrics = m_labels[0].getFontMetrics(f); int x = 10; int y = 10; for (int index = 0; index < m_labels.length; index++) { JLabel label = m_labels[index]; label.setSize(label.getPreferredSize()); int label_width = metrics.stringWidth(label.getText()); if (label_width > max_label_width) max_label_width = label_width; label.setLocation(x, y); JComponent comp = m_controls[index]; comp.setLocation(x, y); y += label.getHeight() + Y_PADDING; } max_label_width += 20; for (int index = 0; index < m_labels.length; index++) { JComponent comp = m_controls[index]; int comp_width = parent.getWidth() - max_label_width - 10; comp.setSize(new Dimension(comp_width, m_controls[0].getPreferredSize().height)); comp.setLocation(max_label_width, comp.getY()); } } public Dimension minimumLayoutSize(Container parent) { return new Dimension(50, 50); } public Dimension preferredLayoutSize(Container parent) { return getPreferredSize(); } public void removeLayoutComponent(Component comp) { } } public class InfoPanel extends JPanel { public InfoPanel(LayoutManager layout) { super(layout); } public Dimension getPreferredSize() { JLabel label = m_labels[0]; return new Dimension(100, label.getHeight() * (m_labels.length + 1) + 10); } } }
[ "jtassin@zco.tech" ]
jtassin@zco.tech
fad738ec53cb75ce6a42cbd4bcc1059725cd68ae
882e77219bce59ae57cbad7e9606507b34eebfcf
/mi2s_10_miui12/src/main/java/com/android/server/usb/UsbUserSettingsManager.java
88ce2513aeac0435b51c5913dc7f29a3a626dfd3
[]
no_license
CrackerCat/XiaomiFramework
17a12c1752296fa1a52f61b83ecf165f328f4523
0b7952df317dac02ebd1feea7507afb789cef2e3
refs/heads/master
2022-06-12T03:30:33.285593
2020-05-06T11:30:54
2020-05-06T11:30:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
19,949
java
package com.android.server.usb; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.hardware.usb.AccessoryFilter; import android.hardware.usb.DeviceFilter; import android.hardware.usb.UsbAccessory; import android.hardware.usb.UsbDevice; import android.os.UserHandle; import android.util.Slog; import com.android.internal.util.dump.DualDumpOutputStream; import com.android.internal.util.dump.DumpUtils; import com.android.server.inputmethod.MiuiSecurityInputMethodHelper; import com.android.server.pm.CloudControlPreinstallService; import com.android.server.pm.PackageManagerService; import com.android.server.slice.SliceClientPermissions; import java.util.ArrayList; import java.util.List; class UsbUserSettingsManager { private static final boolean DEBUG = false; private static final String TAG = UsbUserSettingsManager.class.getSimpleName(); private final Object mLock = new Object(); private final PackageManager mPackageManager; private final UsbPermissionManager mUsbPermissionManager; private final UserHandle mUser; private final Context mUserContext; UsbUserSettingsManager(Context context, UserHandle user, UsbPermissionManager usbPermissionManager) { try { this.mUserContext = context.createPackageContextAsUser(PackageManagerService.PLATFORM_PACKAGE_NAME, 0, user); this.mPackageManager = this.mUserContext.getPackageManager(); this.mUser = user; this.mUsbPermissionManager = usbPermissionManager; } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException("Missing android package"); } } /* access modifiers changed from: package-private */ public void removeDevicePermissions(UsbDevice device) { this.mUsbPermissionManager.removeDevicePermissions(device); } /* access modifiers changed from: package-private */ public void removeAccessoryPermissions(UsbAccessory accessory) { this.mUsbPermissionManager.removeAccessoryPermissions(accessory); } private boolean isCameraDevicePresent(UsbDevice device) { if (device.getDeviceClass() == 14) { return true; } for (int i = 0; i < device.getInterfaceCount(); i++) { if (device.getInterface(i).getInterfaceClass() == 14) { return true; } } return false; } private boolean isCameraPermissionGranted(String packageName, int uid) { try { ApplicationInfo aInfo = this.mPackageManager.getApplicationInfo(packageName, 0); if (aInfo.uid != uid) { String str = TAG; Slog.i(str, "Package " + packageName + " does not match caller's uid " + uid); return false; } else if (aInfo.targetSdkVersion < 28 || -1 != this.mUserContext.checkCallingPermission("android.permission.CAMERA")) { return true; } else { Slog.i(TAG, "Camera permission required for USB video class devices"); return false; } } catch (PackageManager.NameNotFoundException e) { Slog.i(TAG, "Package not found, likely due to invalid package name!"); return false; } } public boolean hasPermission(UsbDevice device, String packageName, int uid) { if (!isCameraDevicePresent(device) || isCameraPermissionGranted(packageName, uid)) { return this.mUsbPermissionManager.hasPermission(device, uid); } return false; } public boolean hasPermission(UsbAccessory accessory, int uid) { return this.mUsbPermissionManager.hasPermission(accessory, uid); } public void checkPermission(UsbDevice device, String packageName, int uid) { if (!hasPermission(device, packageName, uid)) { throw new SecurityException("User has not given " + uid + SliceClientPermissions.SliceAuthority.DELIMITER + packageName + " permission to access device " + device.getDeviceName()); } } public void checkPermission(UsbAccessory accessory, int uid) { if (!hasPermission(accessory, uid)) { throw new SecurityException("User has not given " + uid + " permission to accessory " + accessory); } } /* Debug info: failed to restart local var, previous not found, register: 12 */ private void requestPermissionDialog(UsbDevice device, UsbAccessory accessory, boolean canBeDefault, String packageName, PendingIntent pi, int uid) { String str = packageName; int i = uid; try { if (this.mPackageManager.getApplicationInfo(str, 0).uid == i) { this.mUsbPermissionManager.requestPermissionDialog(device, accessory, canBeDefault, packageName, uid, this.mUserContext, pi); return; } throw new IllegalArgumentException("package " + str + " does not match caller's uid " + i); } catch (PackageManager.NameNotFoundException e) { throw new IllegalArgumentException("package " + str + " not found"); } } public void requestPermission(UsbDevice device, String packageName, PendingIntent pi, int uid) { Intent intent = new Intent(); if (hasPermission(device, packageName, uid)) { intent.putExtra(CloudControlPreinstallService.ConnectEntity.DEVICE, device); intent.putExtra("permission", true); try { pi.send(this.mUserContext, 0, intent); } catch (PendingIntent.CanceledException e) { } } else if (!isCameraDevicePresent(device) || isCameraPermissionGranted(packageName, uid)) { requestPermissionDialog(device, (UsbAccessory) null, canBeDefault(device, packageName), packageName, pi, uid); } else { intent.putExtra(CloudControlPreinstallService.ConnectEntity.DEVICE, device); intent.putExtra("permission", false); try { pi.send(this.mUserContext, 0, intent); } catch (PendingIntent.CanceledException e2) { } } } public void requestPermission(UsbAccessory accessory, String packageName, PendingIntent pi, int uid) { if (hasPermission(accessory, uid)) { Intent intent = new Intent(); intent.putExtra("accessory", accessory); intent.putExtra("permission", true); try { pi.send(this.mUserContext, 0, intent); } catch (PendingIntent.CanceledException e) { } } else { requestPermissionDialog((UsbDevice) null, accessory, canBeDefault(accessory, packageName), packageName, pi, uid); } } public void grantDevicePermission(UsbDevice device, int uid) { this.mUsbPermissionManager.grantDevicePermission(device, uid); } public void grantAccessoryPermission(UsbAccessory accessory, int uid) { this.mUsbPermissionManager.grantAccessoryPermission(accessory, uid); } /* access modifiers changed from: package-private */ public List<ResolveInfo> queryIntentActivities(Intent intent) { return this.mPackageManager.queryIntentActivitiesAsUser(intent, 128, this.mUser.getIdentifier()); } /* Debug info: failed to restart local var, previous not found, register: 9 */ /* JADX WARNING: Code restructure failed: missing block: B:28:0x004d, code lost: r6 = move-exception; */ /* JADX WARNING: Code restructure failed: missing block: B:30:?, code lost: $closeResource(r5, r4); */ /* JADX WARNING: Code restructure failed: missing block: B:31:0x0051, code lost: throw r6; */ /* Code decompiled incorrectly, please refer to instructions dump. */ private boolean canBeDefault(android.hardware.usb.UsbDevice r10, java.lang.String r11) { /* r9 = this; android.content.pm.ActivityInfo[] r0 = r9.getPackageActivities(r11) if (r0 == 0) goto L_0x0070 int r1 = r0.length r2 = 0 L_0x0008: if (r2 >= r1) goto L_0x0070 r3 = r0[r2] android.content.pm.PackageManager r4 = r9.mPackageManager // Catch:{ Exception -> 0x0052 } java.lang.String r5 = "android.hardware.usb.action.USB_DEVICE_ATTACHED" android.content.res.XmlResourceParser r4 = r3.loadXmlMetaData(r4, r5) // Catch:{ Exception -> 0x0052 } r5 = 0 if (r4 != 0) goto L_0x001d if (r4 == 0) goto L_0x006d $closeResource(r5, r4) // Catch:{ Exception -> 0x0052 } goto L_0x006d L_0x001d: com.android.internal.util.XmlUtils.nextElement(r4) // Catch:{ all -> 0x004b } L_0x0020: int r6 = r4.getEventType() // Catch:{ all -> 0x004b } r7 = 1 if (r6 == r7) goto L_0x0047 java.lang.String r6 = "usb-device" java.lang.String r8 = r4.getName() // Catch:{ all -> 0x004b } boolean r6 = r6.equals(r8) // Catch:{ all -> 0x004b } if (r6 == 0) goto L_0x0043 android.hardware.usb.DeviceFilter r6 = android.hardware.usb.DeviceFilter.read(r4) // Catch:{ all -> 0x004b } boolean r8 = r6.matches(r10) // Catch:{ all -> 0x004b } if (r8 == 0) goto L_0x0043 $closeResource(r5, r4) // Catch:{ Exception -> 0x0052 } return r7 L_0x0043: com.android.internal.util.XmlUtils.nextElement(r4) // Catch:{ all -> 0x004b } goto L_0x0020 L_0x0047: $closeResource(r5, r4) // Catch:{ Exception -> 0x0052 } goto L_0x006d L_0x004b: r5 = move-exception throw r5 // Catch:{ all -> 0x004d } L_0x004d: r6 = move-exception $closeResource(r5, r4) // Catch:{ Exception -> 0x0052 } throw r6 // Catch:{ Exception -> 0x0052 } L_0x0052: r4 = move-exception java.lang.String r5 = TAG java.lang.StringBuilder r6 = new java.lang.StringBuilder r6.<init>() java.lang.String r7 = "Unable to load component info " r6.append(r7) java.lang.String r7 = r3.toString() r6.append(r7) java.lang.String r6 = r6.toString() android.util.Slog.w(r5, r6, r4) L_0x006d: int r2 = r2 + 1 goto L_0x0008 L_0x0070: r1 = 0 return r1 */ throw new UnsupportedOperationException("Method not decompiled: com.android.server.usb.UsbUserSettingsManager.canBeDefault(android.hardware.usb.UsbDevice, java.lang.String):boolean"); } private static /* synthetic */ void $closeResource(Throwable x0, AutoCloseable x1) { if (x0 != null) { try { x1.close(); } catch (Throwable th) { x0.addSuppressed(th); } } else { x1.close(); } } /* Debug info: failed to restart local var, previous not found, register: 9 */ /* JADX WARNING: Code restructure failed: missing block: B:28:0x004d, code lost: r6 = move-exception; */ /* JADX WARNING: Code restructure failed: missing block: B:30:?, code lost: $closeResource(r5, r4); */ /* JADX WARNING: Code restructure failed: missing block: B:31:0x0051, code lost: throw r6; */ /* Code decompiled incorrectly, please refer to instructions dump. */ private boolean canBeDefault(android.hardware.usb.UsbAccessory r10, java.lang.String r11) { /* r9 = this; android.content.pm.ActivityInfo[] r0 = r9.getPackageActivities(r11) if (r0 == 0) goto L_0x0070 int r1 = r0.length r2 = 0 L_0x0008: if (r2 >= r1) goto L_0x0070 r3 = r0[r2] android.content.pm.PackageManager r4 = r9.mPackageManager // Catch:{ Exception -> 0x0052 } java.lang.String r5 = "android.hardware.usb.action.USB_ACCESSORY_ATTACHED" android.content.res.XmlResourceParser r4 = r3.loadXmlMetaData(r4, r5) // Catch:{ Exception -> 0x0052 } r5 = 0 if (r4 != 0) goto L_0x001d if (r4 == 0) goto L_0x006d $closeResource(r5, r4) // Catch:{ Exception -> 0x0052 } goto L_0x006d L_0x001d: com.android.internal.util.XmlUtils.nextElement(r4) // Catch:{ all -> 0x004b } L_0x0020: int r6 = r4.getEventType() // Catch:{ all -> 0x004b } r7 = 1 if (r6 == r7) goto L_0x0047 java.lang.String r6 = "usb-accessory" java.lang.String r8 = r4.getName() // Catch:{ all -> 0x004b } boolean r6 = r6.equals(r8) // Catch:{ all -> 0x004b } if (r6 == 0) goto L_0x0043 android.hardware.usb.AccessoryFilter r6 = android.hardware.usb.AccessoryFilter.read(r4) // Catch:{ all -> 0x004b } boolean r8 = r6.matches(r10) // Catch:{ all -> 0x004b } if (r8 == 0) goto L_0x0043 $closeResource(r5, r4) // Catch:{ Exception -> 0x0052 } return r7 L_0x0043: com.android.internal.util.XmlUtils.nextElement(r4) // Catch:{ all -> 0x004b } goto L_0x0020 L_0x0047: $closeResource(r5, r4) // Catch:{ Exception -> 0x0052 } goto L_0x006d L_0x004b: r5 = move-exception throw r5 // Catch:{ all -> 0x004d } L_0x004d: r6 = move-exception $closeResource(r5, r4) // Catch:{ Exception -> 0x0052 } throw r6 // Catch:{ Exception -> 0x0052 } L_0x0052: r4 = move-exception java.lang.String r5 = TAG java.lang.StringBuilder r6 = new java.lang.StringBuilder r6.<init>() java.lang.String r7 = "Unable to load component info " r6.append(r7) java.lang.String r7 = r3.toString() r6.append(r7) java.lang.String r6 = r6.toString() android.util.Slog.w(r5, r6, r4) L_0x006d: int r2 = r2 + 1 goto L_0x0008 L_0x0070: r1 = 0 return r1 */ throw new UnsupportedOperationException("Method not decompiled: com.android.server.usb.UsbUserSettingsManager.canBeDefault(android.hardware.usb.UsbAccessory, java.lang.String):boolean"); } private ActivityInfo[] getPackageActivities(String packageName) { try { return this.mPackageManager.getPackageInfo(packageName, MiuiSecurityInputMethodHelper.TEXT_PASSWORD).activities; } catch (PackageManager.NameNotFoundException e) { return null; } } public void dump(DualDumpOutputStream dump, String idName, long id) { int numDeviceAttachedActivities; DualDumpOutputStream dualDumpOutputStream = dump; long token = dump.start(idName, id); synchronized (this.mLock) { dualDumpOutputStream.write("user_id", 1120986464257L, this.mUser.getIdentifier()); this.mUsbPermissionManager.dump(dualDumpOutputStream); List<ResolveInfo> deviceAttachedActivities = queryIntentActivities(new Intent("android.hardware.usb.action.USB_DEVICE_ATTACHED")); int numDeviceAttachedActivities2 = deviceAttachedActivities.size(); for (int activityNum = 0; activityNum < numDeviceAttachedActivities2; activityNum++) { ResolveInfo deviceAttachedActivity = deviceAttachedActivities.get(activityNum); long deviceAttachedActivityToken = dualDumpOutputStream.start("device_attached_activities", 2246267895812L); DumpUtils.writeComponentName(dualDumpOutputStream, "activity", 1146756268033L, new ComponentName(deviceAttachedActivity.activityInfo.packageName, deviceAttachedActivity.activityInfo.name)); ArrayList<DeviceFilter> deviceFilters = UsbProfileGroupSettingsManager.getDeviceFilters(this.mPackageManager, deviceAttachedActivity); if (deviceFilters != null) { int numDeviceFilters = deviceFilters.size(); int filterNum = 0; while (filterNum < numDeviceFilters) { deviceFilters.get(filterNum).dump(dualDumpOutputStream, "filters", 2246267895810L); filterNum++; deviceFilters = deviceFilters; numDeviceFilters = numDeviceFilters; } int i = numDeviceFilters; } dualDumpOutputStream.end(deviceAttachedActivityToken); } List<ResolveInfo> accessoryAttachedActivities = queryIntentActivities(new Intent("android.hardware.usb.action.USB_ACCESSORY_ATTACHED")); int numAccessoryAttachedActivities = accessoryAttachedActivities.size(); int activityNum2 = 0; while (activityNum2 < numAccessoryAttachedActivities) { ResolveInfo accessoryAttachedActivity = accessoryAttachedActivities.get(activityNum2); long accessoryAttachedActivityToken = dualDumpOutputStream.start("accessory_attached_activities", 2246267895813L); List<ResolveInfo> deviceAttachedActivities2 = deviceAttachedActivities; int numDeviceAttachedActivities3 = numDeviceAttachedActivities2; List<ResolveInfo> accessoryAttachedActivities2 = accessoryAttachedActivities; DumpUtils.writeComponentName(dualDumpOutputStream, "activity", 1146756268033L, new ComponentName(accessoryAttachedActivity.activityInfo.packageName, accessoryAttachedActivity.activityInfo.name)); ArrayList<AccessoryFilter> accessoryFilters = UsbProfileGroupSettingsManager.getAccessoryFilters(this.mPackageManager, accessoryAttachedActivity); if (accessoryFilters != null) { int numAccessoryFilters = accessoryFilters.size(); int filterNum2 = 0; while (filterNum2 < numAccessoryFilters) { accessoryFilters.get(filterNum2).dump(dualDumpOutputStream, "filters", 2246267895810L); filterNum2++; numDeviceAttachedActivities3 = numDeviceAttachedActivities3; accessoryFilters = accessoryFilters; numAccessoryFilters = numAccessoryFilters; } numDeviceAttachedActivities = numDeviceAttachedActivities3; ArrayList<AccessoryFilter> arrayList = accessoryFilters; int i2 = numAccessoryFilters; } else { numDeviceAttachedActivities = numDeviceAttachedActivities3; ArrayList<AccessoryFilter> arrayList2 = accessoryFilters; } dualDumpOutputStream.end(accessoryAttachedActivityToken); activityNum2++; accessoryAttachedActivities = accessoryAttachedActivities2; numDeviceAttachedActivities2 = numDeviceAttachedActivities; deviceAttachedActivities = deviceAttachedActivities2; } int i3 = numDeviceAttachedActivities2; List<ResolveInfo> list = accessoryAttachedActivities; } dualDumpOutputStream.end(token); } }
[ "sanbo.xyz@gmail.com" ]
sanbo.xyz@gmail.com
4877c5b897b57dd9ea4d5629b94dcf5e00f41a75
34a9d7507dbe1d014da027aa304b5390bce2793e
/src/demo5/AsAd.java
a346ffcbb9bf23eddded3a9b3cc68288def550bf
[]
no_license
19980115/Javase1
9b249db8f37637d8c697bd8876b323aa399a4ab8
bd1979917f82d854dcb3c0dc4ed3a4517f183304
refs/heads/master
2020-06-06T09:07:09.442588
2019-06-21T12:11:16
2019-06-21T12:11:16
192,696,677
0
0
null
null
null
null
UTF-8
Java
false
false
188
java
package demo5; public class AsAd { public static void main(String[]args){ int i=1; while (i<=5){ System.out.println(i); i++; } } }
[ "2812144956@qq.com" ]
2812144956@qq.com
ab43e82df93a1d720aeab989f95f2b303d594f88
cbfd78557b48c54487d2a50e769db87620ce34be
/src/abstraction_Concept/Base_7.java
bcbba09b8a931681d853251c6c285257aa3048a6
[]
no_license
manishkumarmishralive/Java
ebe86d79dc5ee7eaae16ad5e9ab44f268710afcd
9b65b1f57c240b4e03775b496b5113dfaae7a2bc
refs/heads/master
2022-02-19T19:48:55.096732
2019-09-17T09:27:33
2019-09-17T09:27:33
209,011,750
0
0
null
null
null
null
UTF-8
Java
false
false
123
java
package abstraction_Concept; public abstract class Base_7 { final void fun() { System.out.println("Hello final"); } }
[ "manishmishralive@gmail.com" ]
manishmishralive@gmail.com
f03ff933772328c6b0f97dafc84cbd4f459d7fd8
6482753b5eb6357e7fe70e3057195e91682db323
/org/apache/logging/log4j/core/jmx/Server.java
f0355a4fa0867df1c745e0be5060e2b4f573f87b
[]
no_license
TheShermanTanker/Server-1.16.3
45cf9996afa4cd4d8963f8fd0588ae4ee9dca93c
48cc08cb94c3094ebddb6ccfb4ea25538492bebf
refs/heads/master
2022-12-19T02:20:01.786819
2020-09-18T21:29:40
2020-09-18T21:29:40
296,730,962
0
1
null
null
null
null
UTF-8
Java
false
false
14,809
java
package org.apache.logging.log4j.core.jmx; import org.apache.logging.log4j.core.appender.AsyncAppender; import org.apache.logging.log4j.core.Appender; import java.util.Map; import org.apache.logging.log4j.core.async.AsyncLoggerConfig; import org.apache.logging.log4j.core.config.LoggerConfig; import java.util.Set; import javax.management.InstanceNotFoundException; import javax.management.QueryExp; import javax.management.ObjectName; import javax.management.NotCompliantMBeanException; import javax.management.MBeanRegistrationException; import javax.management.InstanceAlreadyExistsException; import org.apache.logging.log4j.spi.LoggerContextFactory; import org.apache.logging.log4j.core.impl.Log4jContextFactory; import org.apache.logging.log4j.LogManager; import java.util.Iterator; import java.util.List; import org.apache.logging.log4j.core.selector.ContextSelector; import org.apache.logging.log4j.core.async.AsyncLoggerContext; import org.apache.logging.log4j.core.LoggerContext; import javax.management.MBeanServer; import java.lang.management.ManagementFactory; import java.util.concurrent.ThreadFactory; import java.util.concurrent.Executors; import org.apache.logging.log4j.core.util.Log4jThreadFactory; import org.apache.logging.log4j.util.PropertiesUtil; import org.apache.logging.log4j.core.util.Constants; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executor; import org.apache.logging.log4j.status.StatusLogger; public final class Server { public static final String DOMAIN = "org.apache.logging.log4j2"; private static final String PROPERTY_DISABLE_JMX = "log4j2.disable.jmx"; private static final String PROPERTY_ASYNC_NOTIF = "log4j2.jmx.notify.async"; private static final String THREAD_NAME_PREFIX = "jmx.notif"; private static final StatusLogger LOGGER; static final Executor executor; private Server() { } private static ExecutorService createExecutor() { final boolean defaultAsync = !Constants.IS_WEB_APP; final boolean async = PropertiesUtil.getProperties().getBooleanProperty("log4j2.jmx.notify.async", defaultAsync); return async ? Executors.newFixedThreadPool(1, (ThreadFactory)Log4jThreadFactory.createDaemonThreadFactory("jmx.notif")) : null; } public static String escape(final String name) { final StringBuilder sb = new StringBuilder(name.length() * 2); boolean needsQuotes = false; for (int i = 0; i < name.length(); ++i) { final char c = name.charAt(i); switch (c) { case '\"': case '*': case '?': case '\\': { sb.append('\\'); needsQuotes = true; break; } case ',': case ':': case '=': { needsQuotes = true; break; } case '\r': { continue; } case '\n': { sb.append("\\n"); needsQuotes = true; continue; } } sb.append(c); } if (needsQuotes) { sb.insert(0, '\"'); sb.append('\"'); } return sb.toString(); } private static boolean isJmxDisabled() { return PropertiesUtil.getProperties().getBooleanProperty("log4j2.disable.jmx"); } public static void reregisterMBeansAfterReconfigure() { if (isJmxDisabled()) { Server.LOGGER.debug("JMX disabled for Log4j2. Not registering MBeans."); return; } final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); reregisterMBeansAfterReconfigure(mbs); } public static void reregisterMBeansAfterReconfigure(final MBeanServer mbs) { if (isJmxDisabled()) { Server.LOGGER.debug("JMX disabled for Log4j2. Not registering MBeans."); return; } try { final ContextSelector selector = getContextSelector(); if (selector == null) { Server.LOGGER.debug("Could not register MBeans: no ContextSelector found."); return; } Server.LOGGER.trace("Reregistering MBeans after reconfigure. Selector={}", selector); final List<LoggerContext> contexts = selector.getLoggerContexts(); int i = 0; for (final LoggerContext ctx : contexts) { Server.LOGGER.trace("Reregistering context ({}/{}): '{}' {}", (++i), contexts.size(), ctx.getName(), ctx); unregisterLoggerContext(ctx.getName(), mbs); final LoggerContextAdmin mbean = new LoggerContextAdmin(ctx, Server.executor); register(mbs, mbean, mbean.getObjectName()); if (ctx instanceof AsyncLoggerContext) { final RingBufferAdmin rbmbean = ((AsyncLoggerContext)ctx).createRingBufferAdmin(); if (rbmbean.getBufferSize() > 0L) { register(mbs, rbmbean, rbmbean.getObjectName()); } } registerStatusLogger(ctx.getName(), mbs, Server.executor); registerContextSelector(ctx.getName(), selector, mbs, Server.executor); registerLoggerConfigs(ctx, mbs, Server.executor); registerAppenders(ctx, mbs, Server.executor); } } catch (Exception ex) { Server.LOGGER.error("Could not register mbeans", (Throwable)ex); } } public static void unregisterMBeans() { if (isJmxDisabled()) { Server.LOGGER.debug("JMX disabled for Log4j2. Not unregistering MBeans."); return; } final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); unregisterMBeans(mbs); } public static void unregisterMBeans(final MBeanServer mbs) { unregisterStatusLogger("*", mbs); unregisterContextSelector("*", mbs); unregisterContexts(mbs); unregisterLoggerConfigs("*", mbs); unregisterAsyncLoggerRingBufferAdmins("*", mbs); unregisterAsyncLoggerConfigRingBufferAdmins("*", mbs); unregisterAppenders("*", mbs); unregisterAsyncAppenders("*", mbs); } private static ContextSelector getContextSelector() { final LoggerContextFactory factory = LogManager.getFactory(); if (factory instanceof Log4jContextFactory) { final ContextSelector selector = ((Log4jContextFactory)factory).getSelector(); return selector; } return null; } public static void unregisterLoggerContext(final String loggerContextName) { if (isJmxDisabled()) { Server.LOGGER.debug("JMX disabled for Log4j2. Not unregistering MBeans."); return; } final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); unregisterLoggerContext(loggerContextName, mbs); } public static void unregisterLoggerContext(final String contextName, final MBeanServer mbs) { final String search = String.format("org.apache.logging.log4j2:type=%s", new Object[] { escape(contextName), "*" }); unregisterAllMatching(search, mbs); unregisterStatusLogger(contextName, mbs); unregisterContextSelector(contextName, mbs); unregisterLoggerConfigs(contextName, mbs); unregisterAppenders(contextName, mbs); unregisterAsyncAppenders(contextName, mbs); unregisterAsyncLoggerRingBufferAdmins(contextName, mbs); unregisterAsyncLoggerConfigRingBufferAdmins(contextName, mbs); } private static void registerStatusLogger(final String contextName, final MBeanServer mbs, final Executor executor) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { final StatusLoggerAdmin mbean = new StatusLoggerAdmin(contextName, executor); register(mbs, mbean, mbean.getObjectName()); } private static void registerContextSelector(final String contextName, final ContextSelector selector, final MBeanServer mbs, final Executor executor) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { final ContextSelectorAdmin mbean = new ContextSelectorAdmin(contextName, selector); register(mbs, mbean, mbean.getObjectName()); } private static void unregisterStatusLogger(final String contextName, final MBeanServer mbs) { final String search = String.format("org.apache.logging.log4j2:type=%s,component=StatusLogger", new Object[] { escape(contextName), "*" }); unregisterAllMatching(search, mbs); } private static void unregisterContextSelector(final String contextName, final MBeanServer mbs) { final String search = String.format("org.apache.logging.log4j2:type=%s,component=ContextSelector", new Object[] { escape(contextName), "*" }); unregisterAllMatching(search, mbs); } private static void unregisterLoggerConfigs(final String contextName, final MBeanServer mbs) { final String pattern = "org.apache.logging.log4j2:type=%s,component=Loggers,name=%s"; final String search = String.format("org.apache.logging.log4j2:type=%s,component=Loggers,name=%s", new Object[] { escape(contextName), "*" }); unregisterAllMatching(search, mbs); } private static void unregisterContexts(final MBeanServer mbs) { final String pattern = "org.apache.logging.log4j2:type=%s"; final String search = String.format("org.apache.logging.log4j2:type=%s", new Object[] { "*" }); unregisterAllMatching(search, mbs); } private static void unregisterAppenders(final String contextName, final MBeanServer mbs) { final String pattern = "org.apache.logging.log4j2:type=%s,component=Appenders,name=%s"; final String search = String.format("org.apache.logging.log4j2:type=%s,component=Appenders,name=%s", new Object[] { escape(contextName), "*" }); unregisterAllMatching(search, mbs); } private static void unregisterAsyncAppenders(final String contextName, final MBeanServer mbs) { final String pattern = "org.apache.logging.log4j2:type=%s,component=AsyncAppenders,name=%s"; final String search = String.format("org.apache.logging.log4j2:type=%s,component=AsyncAppenders,name=%s", new Object[] { escape(contextName), "*" }); unregisterAllMatching(search, mbs); } private static void unregisterAsyncLoggerRingBufferAdmins(final String contextName, final MBeanServer mbs) { final String pattern1 = "org.apache.logging.log4j2:type=%s,component=AsyncLoggerRingBuffer"; final String search1 = String.format("org.apache.logging.log4j2:type=%s,component=AsyncLoggerRingBuffer", new Object[] { escape(contextName) }); unregisterAllMatching(search1, mbs); } private static void unregisterAsyncLoggerConfigRingBufferAdmins(final String contextName, final MBeanServer mbs) { final String pattern2 = "org.apache.logging.log4j2:type=%s,component=Loggers,name=%s,subtype=RingBuffer"; final String search2 = String.format("org.apache.logging.log4j2:type=%s,component=Loggers,name=%s,subtype=RingBuffer", new Object[] { escape(contextName), "*" }); unregisterAllMatching(search2, mbs); } private static void unregisterAllMatching(final String search, final MBeanServer mbs) { try { final ObjectName pattern = new ObjectName(search); final Set<ObjectName> found = (Set<ObjectName>)mbs.queryNames(pattern, (QueryExp)null); if (found.isEmpty()) { Server.LOGGER.trace("Unregistering but no MBeans found matching '{}'", search); } else { Server.LOGGER.trace("Unregistering {} MBeans: {}", found.size(), found); } for (final ObjectName objectName : found) { mbs.unregisterMBean(objectName); } } catch (InstanceNotFoundException ex) { Server.LOGGER.debug("Could not unregister MBeans for " + search + ". Ignoring " + ex); } catch (Exception ex2) { Server.LOGGER.error("Could not unregister MBeans for " + search, (Throwable)ex2); } } private static void registerLoggerConfigs(final LoggerContext ctx, final MBeanServer mbs, final Executor executor) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { final Map<String, LoggerConfig> map = ctx.getConfiguration().getLoggers(); for (final String name : map.keySet()) { final LoggerConfig cfg = (LoggerConfig)map.get(name); final LoggerConfigAdmin mbean = new LoggerConfigAdmin(ctx, cfg); register(mbs, mbean, mbean.getObjectName()); if (cfg instanceof AsyncLoggerConfig) { final AsyncLoggerConfig async = (AsyncLoggerConfig)cfg; final RingBufferAdmin rbmbean = async.createRingBufferAdmin(ctx.getName()); register(mbs, rbmbean, rbmbean.getObjectName()); } } } private static void registerAppenders(final LoggerContext ctx, final MBeanServer mbs, final Executor executor) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { final Map<String, Appender> map = ctx.getConfiguration().getAppenders(); for (final String name : map.keySet()) { final Appender appender = (Appender)map.get(name); if (appender instanceof AsyncAppender) { final AsyncAppender async = (AsyncAppender)appender; final AsyncAppenderAdmin mbean = new AsyncAppenderAdmin(ctx.getName(), async); register(mbs, mbean, mbean.getObjectName()); } else { final AppenderAdmin mbean2 = new AppenderAdmin(ctx.getName(), appender); register(mbs, mbean2, mbean2.getObjectName()); } } } private static void register(final MBeanServer mbs, final Object mbean, final ObjectName objectName) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { Server.LOGGER.debug("Registering MBean {}", objectName); mbs.registerMBean(mbean, objectName); } static { LOGGER = StatusLogger.getLogger(); executor = (Executor)(isJmxDisabled() ? null : createExecutor()); } }
[ "tanksherman27@gmail.com" ]
tanksherman27@gmail.com
1b7078915c5ac7ad8519426ee23908fdb0aaf837
6df6fe96e74fd01586a35d5e5ee084c9046b7f42
/20200710/src/DSASign.java
d80383f03e0e41bb0fce484fa2edbdd2d7e78472
[]
no_license
zhaoyanyan10t/zhaoyanyan
6dd105443174760e10bd9c5dfb212855e8efc809
38635112b89bd635c934b00e029649930e654e80
refs/heads/master
2021-07-07T05:24:08.088338
2020-11-15T13:17:55
2020-11-15T13:17:55
209,076,394
0
0
null
null
null
null
UTF-8
Java
false
false
2,522
java
import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Random; public class DSASign { public BigInteger p,q,g; public BigInteger x,y; public BigInteger _randomInZq(){ BigInteger r= null; do { System.out.print("."); r = new BigInteger(160, new SecureRandom()); }while(r.compareTo(q) >=0); System.out.print("."); return r; } public BigInteger _hashInZq(byte m[]){ MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); md.update(m); byte b[] = new byte[17]; System.arraycopy(md.digest(), 0, b, 1, 16); return new BigInteger(b); }catch (NoSuchAlgorithmException e){ System.out.print("This cannot happen!"); } return null; } public void initKeys(){ q = new BigInteger(160, 100, new SecureRandom()); do { BigInteger t = new BigInteger(512, new SecureRandom()); p = t.multiply(q).add(BigInteger.ONE); }while(!p.isProbablePrime(100)); BigInteger h = _randomInZq(); g = h.modPow(p.subtract(BigInteger.ONE).divide(q), p); x = _randomInZq(); y = g.modPow(x, p); System.out.println("p : " + p); System.out.println("q : " + q); System.out.println("g : " + g); System.out.println("x : " + x); System.out.println("y : " + y); } public BigInteger[] signature(byte m[]){ BigInteger k = _randomInZq(); BigInteger sig[] = new BigInteger[2]; sig[0] = g.modPow(k, p).mod(q); sig[1] = _hashInZq(m).add(x.multiply(sig[0])).mod(q) .multiply(k.modInverse(q)).mod(q); return sig; } public boolean verify(byte m[], BigInteger sig[]){ BigInteger w = sig[1].modInverse(q); BigInteger u1 = _hashInZq(m).multiply(w).mod(q); BigInteger u2 = sig[0].multiply(w).mod(q); BigInteger v = g.modPow(u1, p).multiply(y.modPow(u2, p)).mod(p).mod(q); System.out.println("v = " + v); System.out.println("r = " + sig[0]); return v.compareTo(sig[0]) == 0; } public static void main(String args[]){ DSASign dsa = new DSASign(); dsa.initKeys(); String message = "My name is yuanbang, my student number is 41709010121."; System.out.println(message); BigInteger sig[] = dsa.signature(message.getBytes()); System.out.println("DSASignture verifies result:" + dsa.verify(message.getBytes(),sig) ); } }
[ "1670787414@qq.com" ]
1670787414@qq.com
620a3c4bb31860c964c055652ead843fb9e40b2a
07af209df92e6c247d12f76b91f2f2e2edfb46f0
/SchildtExamples/Java 7 Schildt/6/6_ErrMsg/src/ErrMsg.java
c44418197a2fd80143dd7f83e782c18095470b7c
[]
no_license
michaelzherdev/Java
7d19bf3358ce5d4cbb4774cdf86488aef9d26bb4
5b71e9b42814304d1128d696c91bb97f301a5d99
refs/heads/master
2021-01-10T06:31:36.341504
2015-10-15T19:31:46
2015-10-15T19:31:46
44,328,179
0
0
null
null
null
null
WINDOWS-1251
Java
false
false
581
java
// Возврат объекта типа String class ErrorMsg { String msgs[] = { "Output Error", "Input Error", "Disk Full", "Index Out-Of-Bounds" }; // возвратить объект типа String в виде сообщения об ошибке String getErrorMsg(int i) { if(i >= 0 & i < msgs.length) return msgs[i]; else return "Invalid Error Code"; } } public class ErrMsg { public static void main(String[] args) { ErrorMsg err = new ErrorMsg(); System.out.println(err.getErrorMsg(2)); System.out.println(err.getErrorMsg(19)); } }
[ "michaelzherdev@gmail.com" ]
michaelzherdev@gmail.com
5f5fbe4a34a7471ec2283bf1e178158999f9a35c
39569e64516592b509bc3cb1edc6b3126601f708
/src/main/java/tuilakhanh/db/Utils/RequestUtils.java
36a370be2cc501ff6f23ac825cf9faa7521652da
[]
no_license
tuilakhanh/NapTheNgay.com-Nukkit-API
66561640a9ac770af7b88c4bb908facbe8f731ca
e5addd6e911e7d3ca7b0ed0db6ee92c50624749d
refs/heads/master
2022-11-24T12:12:55.638499
2020-07-27T15:39:59
2020-07-27T15:39:59
282,937,416
0
0
null
null
null
null
UTF-8
Java
false
false
4,264
java
package tuilakhanh.db.Utils; import javax.net.ssl.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; public class RequestUtils { public static void installAllTrustManager() { TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } }}; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection .setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection .setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String urlHostname, SSLSession _session) { return true; } }); } catch (Exception e) { e.printStackTrace(); } } public static String createRequests(Map<String, String> map) { String url_params = ""; for (Map.Entry entry : map.entrySet()) { url_params += entry.getKey() + "=" + entry.getValue() + "&"; } return url_params.substring(0, url_params.length() - 1); } public static String post(String link, String data) { try { RequestUtils.installAllTrustManager(); URL url = new URL(link); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setInstanceFollowRedirects(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-length", String.valueOf(data.length())); conn.setUseCaches(false); conn.setConnectTimeout(12000); //set time out conn.setReadTimeout(12000); PrintWriter post = new PrintWriter(conn.getOutputStream()); post.print(data); post.close(); if (conn.getResponseCode() != 200 && conn.getResponseCode() != 422) { return null; } BufferedReader in = new BufferedReader(new InputStreamReader(conn.getResponseCode() == 200 ? conn.getInputStream() : conn.getErrorStream())); StringBuilder result = new StringBuilder(); String line; while ((line = in.readLine()) != null) { result.append(line); } return result.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } public static String get(String link) { try { RequestUtils.installAllTrustManager(); URL url = new URL(link); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setUseCaches(false); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); if (conn.getResponseCode() != 200) { return null; } StringBuilder result = new StringBuilder(); String line; while ((line = in.readLine()) != null) { result.append(line); } return result.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } }
[ "bacdau852@gmail.com" ]
bacdau852@gmail.com
b358e608df97c1555455725847c4e20cfd7bf368
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/4/4_427f64d2c97ad2541d538f8cfb42ef47ead28dfb/WebUtil/4_427f64d2c97ad2541d538f8cfb42ef47ead28dfb_WebUtil_t.java
072f2f813a50cb548ea7491279339216efdd3e0e
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
25,708
java
/******************************************************************************* * Copyright (c) 2004, 2009 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.commons.net; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Socket; import java.net.Proxy.Type; import java.text.ParseException; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.swing.text.html.HTML.Tag; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpConnectionManager; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.NTCredentials; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.DefaultHttpParams; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.httpclient.util.IdleConnectionTimeoutThread; import org.apache.commons.lang.StringEscapeUtils; import org.eclipse.core.net.proxy.IProxyData; import org.eclipse.core.net.proxy.IProxyService; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Plugin; import org.eclipse.mylyn.commons.net.HtmlStreamTokenizer.Token; import org.eclipse.mylyn.internal.commons.net.AuthenticatedProxy; import org.eclipse.mylyn.internal.commons.net.CloneableHostConfiguration; import org.eclipse.mylyn.internal.commons.net.CommonsNetPlugin; import org.eclipse.mylyn.internal.commons.net.MonitoredRequest; import org.eclipse.mylyn.internal.commons.net.PollingInputStream; import org.eclipse.mylyn.internal.commons.net.PollingProtocolSocketFactory; import org.eclipse.mylyn.internal.commons.net.PollingSslProtocolSocketFactory; import org.eclipse.mylyn.internal.commons.net.TimeoutInputStream; /** * @author Mik Kersten * @author Steffen Pingel * @author Rob Elves * @since 3.0 * @noinstantiate This class is not intended to be instantiated by clients. */ public class WebUtil { /** * like Mylyn/2.1.0 (Rally Connector 1.0) Eclipse/3.3.0 (JBuilder 2007) HttpClient/3.0.1 Java/1.5.0_11 (Sun) * Linux/2.6.20-16-lowlatency (i386; en) */ private static final String USER_AGENT; private static final int CONNNECT_TIMEOUT = 60 * 1000; private static final int SOCKET_TIMEOUT = 3 * 60 * 1000; private static final int HTTP_PORT = 80; private static final int HTTPS_PORT = 443; private static final int POLL_INTERVAL = 1000; private static final int POLL_ATTEMPTS = SOCKET_TIMEOUT / POLL_INTERVAL; private static final String USER_AGENT_PREFIX; private static final String USER_AGENT_POSTFIX; private static final int BUFFER_SIZE = 4096; /** * Do not block. */ private static final long CLOSE_TIMEOUT = -1; /** * @see IdleConnectionTimeoutThread#setTimeoutInterval(long) */ private static final long CONNECTION_TIMEOUT_INTERVAL = 30 * 1000; static { initCommonsLoggingSettings(); StringBuilder sb = new StringBuilder(); sb.append("Mylyn"); //$NON-NLS-1$ sb.append(getBundleVersion(CommonsNetPlugin.getDefault())); USER_AGENT_PREFIX = sb.toString(); sb.setLength(0); if (System.getProperty("org.osgi.framework.vendor") != null) { //$NON-NLS-1$ sb.append(" "); //$NON-NLS-1$ sb.append(System.getProperty("org.osgi.framework.vendor")); //$NON-NLS-1$ sb.append(stripQualifier(System.getProperty("osgi.framework.version"))); //$NON-NLS-1$ if (System.getProperty("eclipse.product") != null) { //$NON-NLS-1$ sb.append(" ("); //$NON-NLS-1$ sb.append(System.getProperty("eclipse.product")); //$NON-NLS-1$ sb.append(")"); //$NON-NLS-1$ } } sb.append(" "); //$NON-NLS-1$ sb.append(DefaultHttpParams.getDefaultParams().getParameter(HttpMethodParams.USER_AGENT).toString().split("-")[1]); //$NON-NLS-1$ sb.append(" Java/"); //$NON-NLS-1$ sb.append(System.getProperty("java.version")); //$NON-NLS-1$ sb.append(" ("); //$NON-NLS-1$ sb.append(System.getProperty("java.vendor").split(" ")[0]); //$NON-NLS-1$ //$NON-NLS-2$ sb.append(") "); //$NON-NLS-1$ sb.append(System.getProperty("os.name")); //$NON-NLS-1$ sb.append("/"); //$NON-NLS-1$ sb.append(System.getProperty("os.version")); //$NON-NLS-1$ sb.append(" ("); //$NON-NLS-1$ sb.append(System.getProperty("os.arch")); //$NON-NLS-1$ if (System.getProperty("osgi.nl") != null) { //$NON-NLS-1$ sb.append("; "); //$NON-NLS-1$ sb.append(System.getProperty("osgi.nl")); //$NON-NLS-1$ } sb.append(")"); //$NON-NLS-1$ USER_AGENT_POSTFIX = sb.toString(); USER_AGENT = USER_AGENT_PREFIX + USER_AGENT_POSTFIX; } private static IdleConnectionTimeoutThread idleConnectionTimeoutThread; private static MultiThreadedHttpConnectionManager connectionManager; private static ProtocolSocketFactory sslSocketFactory = new PollingSslProtocolSocketFactory(); private static PollingProtocolSocketFactory socketFactory = new PollingProtocolSocketFactory(); /** * @since 3.0 */ public static void configureHttpClient(HttpClient client, String userAgent) { client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); client.getParams().setParameter(HttpMethodParams.USER_AGENT, getUserAgent(userAgent)); client.getParams().setConnectionManagerTimeout(CONNECTION_TIMEOUT_INTERVAL); // TODO consider setting this as the default //client.getParams().setCookiePolicy(CookiePolicy.RFC_2109); configureHttpClientConnectionManager(client); } private static void configureHttpClientConnectionManager(HttpClient client) { client.getHttpConnectionManager().getParams().setSoTimeout(WebUtil.SOCKET_TIMEOUT); client.getHttpConnectionManager().getParams().setConnectionTimeout(WebUtil.CONNNECT_TIMEOUT); // FIXME fix connection leaks client.getHttpConnectionManager().getParams().setMaxConnectionsPerHost( HostConfiguration.ANY_HOST_CONFIGURATION, 100); client.getHttpConnectionManager().getParams().setMaxTotalConnections(1000); } private static void configureHttpClientProxy(HttpClient client, HostConfiguration hostConfiguration, AbstractWebLocation location) { String host = WebUtil.getHost(location.getUrl()); Proxy proxy; if (WebUtil.isRepositoryHttps(location.getUrl())) { proxy = location.getProxyForHost(host, IProxyData.HTTPS_PROXY_TYPE); } else { proxy = location.getProxyForHost(host, IProxyData.HTTP_PROXY_TYPE); } if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) { InetSocketAddress address = (InetSocketAddress) proxy.address(); hostConfiguration.setProxy(address.getHostName(), address.getPort()); if (proxy instanceof AuthenticatedProxy) { AuthenticatedProxy authProxy = (AuthenticatedProxy) proxy; Credentials credentials = getCredentials(authProxy.getUserName(), authProxy.getPassword(), address.getAddress()); AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(), AuthScope.ANY_REALM); client.getState().setProxyCredentials(proxyAuthScope, credentials); } } else { hostConfiguration.setProxyHost(null); } } /** * @since 3.0 */ public static void connect(final Socket socket, final InetSocketAddress address, final int timeout, IProgressMonitor monitor) throws IOException { Assert.isNotNull(socket); WebRequest<?> executor = new WebRequest<Object>() { @Override public void abort() { try { socket.close(); } catch (IOException e) { // ignore } } public Object call() throws Exception { socket.connect(address, timeout); return null; } }; executeInternal(monitor, executor); } /** * @since 3.0 */ public static HostConfiguration createHostConfiguration(HttpClient client, AbstractWebLocation location, IProgressMonitor monitor) { Assert.isNotNull(client); Assert.isNotNull(location); String url = location.getUrl(); String host = WebUtil.getHost(url); int port = WebUtil.getPort(url); configureHttpClientConnectionManager(client); HostConfiguration hostConfiguration = new CloneableHostConfiguration(); configureHttpClientProxy(client, hostConfiguration, location); AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.HTTP); if (credentials != null) { AuthScope authScope = new AuthScope(host, port, AuthScope.ANY_REALM); client.getState().setCredentials(authScope, getHttpClientCredentials(credentials, host)); } if (WebUtil.isRepositoryHttps(url)) { Protocol protocol = new Protocol("https", sslSocketFactory, HTTPS_PORT); //$NON-NLS-1$ hostConfiguration.setHost(host, port, protocol); } else { Protocol protocol = new Protocol("http", socketFactory, HTTP_PORT); //$NON-NLS-1$ hostConfiguration.setHost(host, port, protocol); } return hostConfiguration; } /** * @since 3.0 */ public static int execute(final HttpClient client, final HostConfiguration hostConfiguration, final HttpMethod method, IProgressMonitor monitor) throws IOException { return execute(client, hostConfiguration, method, null, monitor); } /** * @since 3.1 */ public static int execute(final HttpClient client, final HostConfiguration hostConfiguration, final HttpMethod method, final HttpState state, IProgressMonitor monitor) throws IOException { Assert.isNotNull(client); Assert.isNotNull(method); monitor = Policy.monitorFor(monitor); MonitoredRequest<Integer> executor = new MonitoredRequest<Integer>(monitor) { @Override public void abort() { super.abort(); method.abort(); } @Override public Integer execute() throws Exception { return client.executeMethod(hostConfiguration, method, state); } }; return executeInternal(monitor, executor); } /** * @since 3.0 */ public static <T> T execute(IProgressMonitor monitor, WebRequest<T> request) throws Throwable { monitor = Policy.monitorFor(monitor); Future<T> future = CommonsNetPlugin.getExecutorService().submit(request); while (true) { if (monitor.isCanceled()) { request.abort(); // wait for executor to finish future.cancel(false); try { if (!future.isCancelled()) { future.get(); } } catch (CancellationException e) { // ignore } catch (InterruptedException e) { // ignore } catch (ExecutionException e) { // ignore } throw new OperationCanceledException(); } try { return future.get(POLL_INTERVAL, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw e.getCause(); } catch (TimeoutException ignored) { } } } @SuppressWarnings("unchecked") private static <T> T executeInternal(IProgressMonitor monitor, WebRequest<?> request) throws IOException { try { return (T) execute(monitor, request); } catch (IOException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch (Throwable e) { throw new RuntimeException(e); } } private static String getBundleVersion(Plugin plugin) { if (null == plugin) { return ""; //$NON-NLS-1$ } Object bundleVersion = plugin.getBundle().getHeaders().get("Bundle-Version"); //$NON-NLS-1$ if (null == bundleVersion) { return ""; //$NON-NLS-1$ } return stripQualifier((String) bundleVersion); } /** * @since 3.0 */ public static int getConnectionTimeout() { return CONNNECT_TIMEOUT; } static Credentials getCredentials(final String username, final String password, final InetAddress address) { int i = username.indexOf("\\"); //$NON-NLS-1$ if (i > 0 && i < username.length() - 1 && address != null) { return new NTCredentials(username.substring(i + 1), password, address.getHostName(), username.substring(0, i)); } else { return new UsernamePasswordCredentials(username, password); } } /** * @since 3.0 */ public static String getHost(String repositoryUrl) { String result = repositoryUrl; int colonSlashSlash = repositoryUrl.indexOf("://"); //$NON-NLS-1$ if (colonSlashSlash >= 0) { result = repositoryUrl.substring(colonSlashSlash + 3); } int colonPort = result.indexOf(':'); int requestPath = result.indexOf('/'); int substringEnd; // minimum positive, or string length if (colonPort > 0 && requestPath > 0) { substringEnd = Math.min(colonPort, requestPath); } else if (colonPort > 0) { substringEnd = colonPort; } else if (requestPath > 0) { substringEnd = requestPath; } else { substringEnd = result.length(); } return result.substring(0, substringEnd); } /** * @since 2.2 */ public static Credentials getHttpClientCredentials(AuthenticationCredentials credentials, String host) { String username = credentials.getUserName(); String password = credentials.getPassword(); int i = username.indexOf("\\"); //$NON-NLS-1$ if (i > 0 && i < username.length() - 1 && host != null) { return new NTCredentials(username.substring(i + 1), password, host, username.substring(0, i)); } else { return new UsernamePasswordCredentials(username, password); } } /** * @since 2.0 */ public static int getPort(String repositoryUrl) { int colonSlashSlash = repositoryUrl.indexOf("://"); //$NON-NLS-1$ int firstSlash = repositoryUrl.indexOf("/", colonSlashSlash + 3); //$NON-NLS-1$ int colonPort = repositoryUrl.indexOf(':', colonSlashSlash + 1); if (firstSlash == -1) { firstSlash = repositoryUrl.length(); } if (colonPort < 0 || colonPort > firstSlash) { return isRepositoryHttps(repositoryUrl) ? HTTPS_PORT : HTTP_PORT; } int requestPath = repositoryUrl.indexOf('/', colonPort + 1); int end = requestPath < 0 ? repositoryUrl.length() : requestPath; String port = repositoryUrl.substring(colonPort + 1, end); if (port.length() == 0) { return isRepositoryHttps(repositoryUrl) ? HTTPS_PORT : HTTP_PORT; } return Integer.parseInt(port); } /** * @since 2.0 */ public static String getRequestPath(String repositoryUrl) { int colonSlashSlash = repositoryUrl.indexOf("://"); //$NON-NLS-1$ int requestPath = repositoryUrl.indexOf('/', colonSlashSlash + 3); if (requestPath < 0) { return ""; //$NON-NLS-1$ } else { return repositoryUrl.substring(requestPath); } } public static InputStream getResponseBodyAsStream(HttpMethodBase method, IProgressMonitor monitor) throws IOException { // return method.getResponseBodyAsStream(); monitor = Policy.monitorFor(monitor); return new PollingInputStream(new TimeoutInputStream(method.getResponseBodyAsStream(), BUFFER_SIZE, POLL_INTERVAL, CLOSE_TIMEOUT), POLL_ATTEMPTS, monitor); } /** * @since 3.0 */ public static int getSocketTimeout() { return SOCKET_TIMEOUT; } /** * Returns the title of a web page. * * @throws IOException * if a network occurs * @return the title; null, if the title could not be determined; * @since 3.0 */ public static String getTitleFromUrl(AbstractWebLocation location, IProgressMonitor monitor) throws IOException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask("Retrieving " + location.getUrl(), IProgressMonitor.UNKNOWN); //$NON-NLS-1$ HttpClient client = new HttpClient(); WebUtil.configureHttpClient(client, ""); //$NON-NLS-1$ GetMethod method = new GetMethod(location.getUrl()); try { HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, monitor); int result = WebUtil.execute(client, hostConfiguration, method, monitor); if (result == HttpStatus.SC_OK) { InputStream in = WebUtil.getResponseBodyAsStream(method, monitor); try { BufferedReader reader = new BufferedReader(new InputStreamReader(in, method.getResponseCharSet())); HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(reader, null); try { for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == Tag.TITLE) { String text = getText(tokenizer); text = text.replaceAll("\n", ""); //$NON-NLS-1$ //$NON-NLS-2$ text = text.replaceAll("\\s+", " "); //$NON-NLS-1$ //$NON-NLS-2$ return text.trim(); } } } } catch (ParseException e) { throw new IOException("Error reading url"); //$NON-NLS-1$ } } finally { in.close(); } } } finally { method.releaseConnection(); } } finally { monitor.done(); } return null; } private static String getText(HtmlStreamTokenizer tokenizer) throws IOException, ParseException { StringBuilder sb = new StringBuilder(); for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TEXT) { sb.append(token.toString()); } else if (token.getType() == Token.COMMENT) { // ignore } else { break; } } return StringEscapeUtils.unescapeHtml(sb.toString()); } /** * Returns a user agent string that contains information about the platform and operating system. The * <code>product</code> parameter allows to additional specify custom text that is inserted into the returned * string. The exact return value depends on the environment. * <p> * Examples: * <ul> * <li>Headless: <code>Mylyn MyProduct HttpClient/3.1 Java/1.5.0_13 (Sun) Linux/2.6.22-14-generic (i386)</code> * <li>Eclipse: * <code>Mylyn/2.2.0 Eclipse/3.4.0 (org.eclipse.sdk.ide) HttpClient/3.1 Java/1.5.0_13 (Sun) Linux/2.6.22-14-generic (i386; en_CA)</code> * * @param product * an identifier that is inserted into the returned user agent string * @return a user agent string * @since 2.3 */ public static String getUserAgent(String product) { if (product != null && product.length() > 0) { StringBuilder sb = new StringBuilder(); sb.append(USER_AGENT_PREFIX); sb.append(" "); //$NON-NLS-1$ sb.append(product); sb.append(USER_AGENT_POSTFIX); return sb.toString(); } else { return USER_AGENT; } } public static void init() { // initialization is done in the static initializer } /** * Disables logging by default. Set these system properties on launch enables verbose logging of HTTP communication: * * <pre> * -Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog * -Dorg.apache.commons.logging.simplelog.showlogname=true * -Dorg.apache.commons.logging.simplelog.defaultlog=off * -Dorg.apache.commons.logging.simplelog.log.httpclient.wire=debug * -Dorg.apache.commons.logging.simplelog.log.org.apache.commons.httpclient=off * -Dorg.apache.commons.logging.simplelog.log.org.apache.axis.message=debug * </pre> */ private static void initCommonsLoggingSettings() { defaultSystemProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog"); //$NON-NLS-1$ //$NON-NLS-2$ } /** * Only sets system property if they are not already set to a value. */ private static void defaultSystemProperty(String key, String defaultValue) { if (System.getProperty(key) == null) { System.setProperty(key, defaultValue); } } private static boolean isRepositoryHttps(String repositoryUrl) { return repositoryUrl.matches("https.*"); //$NON-NLS-1$ } private static String stripQualifier(String longVersion) { if (longVersion == null) { return ""; //$NON-NLS-1$ } String parts[] = longVersion.split("\\."); //$NON-NLS-1$ StringBuilder version = new StringBuilder(); if (parts.length > 0) { version.append("/"); //$NON-NLS-1$ version.append(parts[0]); if (parts.length > 1) { version.append("."); //$NON-NLS-1$ version.append(parts[1]); if (parts.length > 2) { version.append("."); //$NON-NLS-1$ version.append(parts[2]); } } } return version.toString(); } /** * For standalone applications that want to provide a global proxy service. * * @param proxyService * the proxy service * @since 3.0 */ public static void setProxyService(IProxyService proxyService) { CommonsNetPlugin.setProxyService(proxyService); } /** * @since 3.1 */ public static IProxyService getProxyService() { return CommonsNetPlugin.getProxyService(); } /** * @since 3.1 */ public synchronized static void addConnectionManager(HttpConnectionManager connectionManager) { if (idleConnectionTimeoutThread == null) { idleConnectionTimeoutThread = new IdleConnectionTimeoutThread(); idleConnectionTimeoutThread.setTimeoutInterval(CONNECTION_TIMEOUT_INTERVAL); idleConnectionTimeoutThread.setConnectionTimeout(CONNNECT_TIMEOUT); idleConnectionTimeoutThread.start(); } idleConnectionTimeoutThread.addConnectionManager(connectionManager); } /** * @since 3.1 */ public synchronized static HttpConnectionManager getConnectionManager() { if (connectionManager == null) { connectionManager = new MultiThreadedHttpConnectionManager(); addConnectionManager(connectionManager); } return connectionManager; } /** * @since 3.1 */ public synchronized static void removeConnectionManager(HttpConnectionManager connectionManager) { if (idleConnectionTimeoutThread == null) { return; } idleConnectionTimeoutThread.removeConnectionManager(connectionManager); } /** * @since 3.1 */ @SuppressWarnings("deprecation") public static Proxy getProxy(String host, String proxyType) { Assert.isNotNull(host); Assert.isNotNull(proxyType); IProxyService service = CommonsNetPlugin.getProxyService(); if (service != null && service.isProxiesEnabled()) { // TODO e3.5 move to new proxy API IProxyData data = service.getProxyDataForHost(host, proxyType); if (data != null && data.getHost() != null) { String proxyHost = data.getHost(); int proxyPort = data.getPort(); // change the IProxyData default port to the Java default port if (proxyPort == -1) { proxyPort = 0; } AuthenticationCredentials credentials = null; if (data.isRequiresAuthentication()) { credentials = new AuthenticationCredentials(data.getUserId(), data.getPassword()); } return createProxy(proxyHost, proxyPort, credentials); } } return null; } /** * @since 3.1 */ public static Proxy getProxy(String host, Proxy.Type proxyType) { Assert.isNotNull(host); Assert.isNotNull(proxyType); return getProxy(host, getPlatformProxyType(proxyType)); } // private static Type getJavaProxyType(String type) { // return (IProxyData.SOCKS_PROXY_TYPE.equals(type)) ? Proxy.Type.SOCKS : Proxy.Type.HTTP; // } private static String getPlatformProxyType(Type type) { return type == Type.SOCKS ? IProxyData.SOCKS_PROXY_TYPE : IProxyData.HTTP_PROXY_TYPE; } /** * @since 3.1 */ public static Proxy createProxy(String proxyHost, int proxyPort, AuthenticationCredentials credentials) { String proxyUsername = ""; //$NON-NLS-1$ String proxyPassword = ""; //$NON-NLS-1$ if (credentials != null) { proxyUsername = credentials.getUserName(); proxyPassword = credentials.getPassword(); } if (proxyHost != null && proxyHost.length() > 0) { InetSocketAddress sockAddr = new InetSocketAddress(proxyHost, proxyPort); boolean authenticated = (proxyUsername != null && proxyPassword != null && proxyUsername.length() > 0 && proxyPassword.length() > 0); if (authenticated) { return new AuthenticatedProxy(Type.HTTP, sockAddr, proxyUsername, proxyPassword); } else { return new Proxy(Type.HTTP, sockAddr); } } return Proxy.NO_PROXY; } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
fe2adb9498ec2b546394446e801e5d3a7069b20a
cdb1f06611ef3cb7eb146209b079da7866289b4c
/zjy_blog/src/com/itzjy/service/Articleservice.java
f45301946fb956f9d461ddcdb23ba8d126124b4f
[]
no_license
BeanListHandler/Personal-projects
eac6ab40fb73b9a8dba3035fd2c060c63a6055c7
186dea8327d4d4d27f2759ece116bd9ffef2f196
refs/heads/master
2022-07-17T12:50:55.128233
2020-05-20T02:09:13
2020-05-20T02:09:13
262,686,734
0
0
null
null
null
null
UTF-8
Java
false
false
1,013
java
package com.itzjy.service; import com.itzjy.domian.Article; import com.itzjy.domian.Classification; import com.itzjy.domian.PageBean; import org.hibernate.criterion.DetachedCriteria; import java.util.List; public interface Articleservice { /** * 所有文章 */ List<Article> getallArticle(); /** * 获取pagebean * @param detachedCriteria * @param currPage * @param pageSize * @return */ PageBean getpageData(DetachedCriteria detachedCriteria, Integer currPage, int pageSize); /** * 删除文章 * @param article */ void del(Article article); /** * 根据id获取分类 * @return */ List<Classification> getcAtegory(Integer parentid); /** * 保存文章 * @param article */ void save(Article article); /** * 查询文章 * @param article_id * @return */ Article saveclass(Integer article_id); //修改文章 void update(Article article); }
[ "451388703@qq.com" ]
451388703@qq.com
0d968a24b1d31e2dccb869119a068e3642952d2c
b5f2b5011c2ac231aaa6e90ab28c9aa569c4b08a
/1181 단어정렬/Main.java
30f0df5abbfc89c53c56dda950dcf0740fecf0bd
[]
no_license
wjdtj9656/backjoon
2073a75239d02afc4c3e5ec1b1c545b7dc71aac7
0950da2651a1edf2d7e13be5857192c94a3bcf45
refs/heads/master
2023-06-14T18:29:22.058220
2023-06-10T09:33:03
2023-06-10T09:33:03
203,933,013
0
0
null
null
null
null
UTF-8
Java
false
false
1,052
java
package Baekjoon; import java.awt.desktop.SystemEventListener; import java.io.*; import java.math.*; import java.util.*; public class Main { /* 1181 problem */ public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int num = Integer.parseInt(br.readLine()); ArrayList<String> list = new ArrayList<>(); for(int i=0; i<num; i++) { String str = br.readLine(); //if(!list.contains(str)) list.add(str); } int size = list.size(); Collections.sort(list,new Comparator<String>() { public int compare(String s1, String s2) { if(s1.length() > s2.length()) return 1; else if(s1.length() < s2.length()) return -1; else return s1.compareTo(s2); } }); for(int i=0; i<size; i++) { bw.write(list.get(i)+"\n"); } bw.flush(); br.close(); bw.close(); } }
[ "wjdtj9656@naver.com" ]
wjdtj9656@naver.com
b4168a1194d9c23eb617b36b551f0dcb3c0e28dc
6f35b1143323636fc7c925e1b480d3f3670d2ec8
/src/main/java/foo/bar/springfunctionalwebvalidation/App.java
ad03a9429c52d816f2fc69b00e45ccdd457baf3c
[]
no_license
jeroenbellen/Validate-functional-endpoints-in-Spring
8b2b10a3f88bf32f1d723293136255e3339e859b
54c788f98c73fca63cee0e74d072a956925f85b8
refs/heads/master
2021-10-25T13:52:11.336937
2017-11-21T20:14:39
2017-11-21T20:14:39
111,596,776
12
5
null
2021-11-16T09:16:34
2017-11-21T20:17:00
Java
UTF-8
Java
false
false
408
java
package foo.bar.springfunctionalwebvalidation; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; @SpringBootApplication public class App { public static void main(String[] args) { new SpringApplicationBuilder() .sources(App.class) .build() .run(args); } }
[ "bellenjeroen@gmail.com" ]
bellenjeroen@gmail.com
cc3194de3a4924626f7ad1f3b98b11d70912470b
05eda76ac7ae31eea323ba08c130af42b1987a6b
/src/test/java/appmanager/page/HomePage.java
534ee8076086706db1417e584a8449c50ad98081
[]
no_license
SPerepelitsa1988/Testing
11231f1f7cdf3577bceaaf1256d96ca80da7e044
fb71d892b01f670313550953080ce311f008c66d
refs/heads/master
2021-04-15T13:10:29.104991
2018-03-21T15:16:09
2018-03-21T15:16:09
126,197,655
0
0
null
null
null
null
UTF-8
Java
false
false
440
java
package appmanager.page; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class HomePage extends BasePage{ @FindBy(linkText = "Sign in") private WebElement signInLink; public HomePage(WebDriver driver) { super(driver); } public LoginPage goToLoginPage() { signInLink.click(); return new LoginPage(driver); } }
[ "svetlana.perepelitsa1988@gmail.com" ]
svetlana.perepelitsa1988@gmail.com
6853256f7b9ace0fe50ce9cc9967ceaf1b686e11
5c126ac6b8cdeeac87f715bc20ecd8d1c5ebe263
/src/main/java/org/slevin/dao/cbs/istanbul/ArnavutkoyParserDao.java
440f790b87b2fe00c401865dff4a6bb0fd38fdb0
[]
no_license
ramazanfirin/cbsparser
00a2b08aa6c28de9049a521a28f026bd7563abde
1e4866a7f3a59ed3cbb2348877cb11018e8cd837
refs/heads/master
2020-06-07T02:50:35.085343
2015-06-15T21:38:40
2015-06-15T21:38:40
37,492,716
0
0
null
null
null
null
UTF-8
Java
false
false
146
java
package org.slevin.dao.cbs.istanbul; import org.slevin.dao.BaseParserDao; public interface ArnavutkoyParserDao extends BaseParserDao{ }
[ "ETR00529@TTKGBCONS45.turkcell.entp.tgc" ]
ETR00529@TTKGBCONS45.turkcell.entp.tgc
f6c654ef2b80bf0beee1996cd2d419c845563193
0436f24085de077802383bd6fc6a368a4d1c1b9f
/missing-module-info/j2objc.annotations/module-info.java
143723e3bc2c785827a701b498a5f129bdef7ca4
[ "Apache-2.0" ]
permissive
prodriguezdefino/bq-throttled-extraction
17547a107169af1a31f34884339d960eea478820
2e6410b06aaee34848db36784f3f0de3f15ff3a2
refs/heads/master
2022-12-24T15:29:00.976003
2020-06-24T00:02:26
2020-06-24T00:02:26
265,945,566
0
0
Apache-2.0
2020-10-13T22:11:08
2020-05-21T20:30:56
Java
UTF-8
Java
false
false
74
java
module j2objc.annotations { exports com.google.j2objc.annotations; }
[ "prodriguezdefino@gmail.com" ]
prodriguezdefino@gmail.com
fa83e7da5a3e2463f7ed638efdb7bbe635f7b393
a0ad1ce0adcaabde1ad0278df88f7b1bb8806cc0
/app/src/main/java/com/wr/demo/modules/news/videos/VideosPresenter.java
3f64cfb7d821e2fd50c60fc8ce4d872c781c3653
[]
no_license
Virenz/RxJava2-Okhttp
36c63ac25bcda73e75e7730f2fa2071b366c8f7b
a17603ba3f49e308f58057b50a6a4b37863c0d35
refs/heads/main
2023-02-17T22:12:41.380315
2021-01-18T06:31:11
2021-01-18T06:31:11
330,575,092
0
0
null
null
null
null
UTF-8
Java
false
false
7,508
java
package com.wr.demo.modules.news.videos; import com.wr.demo.CustomApplication; import com.wr.demo.api.ApiManager; import com.wr.demo.config.Constants; import com.wr.demo.disklrucache.DiskCacheManager; import com.wr.demo.utils.douyin.DouyinSign; import com.wr.demo.utils.magicrecyclerView.BaseItem; import com.wr.demo.modules.BasePresenter; import com.wr.demo.modules.ImpBaseView; import com.wr.demo.modules.news.NewsContract; import java.util.ArrayList; import java.util.List; import java.util.Map; import io.reactivex.Observable; import io.reactivex.SingleObserver; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Function; import io.reactivex.functions.Predicate; import io.reactivex.schedulers.Schedulers; /** * Created by weir on 2020/12/23. */ class VideosPresenter extends BasePresenter implements NewsContract.Presenter { private NewsContract.View mNewsListFrag; private String params; private Map<String, Object> headers; @Override public void refreshNews() { if (headers != null) headers.clear(); long _rticket = System.currentTimeMillis(); params = DouyinSign.get_params(_rticket); headers = DouyinSign.get_headers(params, _rticket); mNewsListFrag.showRefreshBar(); ApiManager.getInstence().getDouyinVideosServie() .getDouyinVideos(headers, params) .map(new Function<VideosNewsList, ArrayList<VideosBean>>() { @Override public ArrayList<VideosBean> apply(VideosNewsList videosNewsList) { return videosNewsList.getVideosArrayList(); } }) .flatMap(new Function<ArrayList<VideosBean>, Observable<VideosBean>>() { @Override public Observable<VideosBean> apply(ArrayList<VideosBean> topNewses) throws Exception { return Observable.fromIterable(topNewses); } }) .filter(new Predicate<VideosBean>() { @Override public boolean test(VideosBean topNews) throws Exception { return topNews != null || topNews.getVideo().getPlay_addr() != null; } }) .map(new Function<VideosBean, BaseItem>() { @Override public BaseItem apply(VideosBean topNews) { BaseItem<VideosBean> baseItem = new BaseItem<>(); baseItem.setData(topNews); return baseItem; } }) .toList() //将 List 转为ArrayList 缓存存储 ArrayList Serializable对象 .map(new Function<List<BaseItem>, ArrayList<BaseItem>>() { @Override public ArrayList<BaseItem> apply(List<BaseItem> baseItems) { ArrayList<BaseItem> items = new ArrayList<>(); items.addAll(baseItems); return items; } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new SingleObserver<ArrayList<BaseItem>>() { @Override public void onSubscribe(Disposable d) { addDisposable(d); } @Override public void onSuccess(ArrayList<BaseItem> value) { DiskCacheManager manager = new DiskCacheManager(CustomApplication.getContext(), Constants.CACHE_DOUYIN_FILE); manager.put(Constants.CACHE_DOUYIN_VIDEOS, value); mNewsListFrag.hideRefreshBar(); mNewsListFrag.refreshNewsSuccessed(value); } @Override public void onError(Throwable e) { mNewsListFrag.hideRefreshBar(); mNewsListFrag.refreshNewsFail(e.getMessage()); } }); } //两个方法没区别,只是刷新会重新赋值 @Override public void loadMore() { if (headers != null) headers.clear(); long _rticket = System.currentTimeMillis(); params = DouyinSign.get_params(_rticket); headers = DouyinSign.get_headers(params, _rticket); ApiManager.getInstence().getDouyinVideosServie() .getDouyinVideos(headers, params) .map(new Function<VideosNewsList, ArrayList<VideosBean>>() { @Override public ArrayList<VideosBean> apply(VideosNewsList videosNewsList) { return videosNewsList.getVideosArrayList(); } }) .flatMap(new Function<ArrayList<VideosBean>, Observable<VideosBean>>() { @Override public Observable<VideosBean> apply(ArrayList<VideosBean> topNewses) { return Observable.fromIterable(topNewses); } }) .filter(new Predicate<VideosBean>() { @Override public boolean test(VideosBean topNews) throws Exception { return topNews != null || topNews.getVideo().getPlay_addr() != null; } }) .map(new Function<VideosBean, BaseItem>() { @Override public BaseItem apply(VideosBean topNews) { BaseItem<VideosBean> baseItem = new BaseItem<>(); baseItem.setData(topNews); return baseItem; } }) .toList() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new SingleObserver<List<BaseItem>>() { @Override public void onSubscribe(Disposable d) { addDisposable(d); } @Override public void onSuccess(List<BaseItem> value) { if (value != null && value.size() > 0) { mNewsListFrag.loadMoreSuccessed((ArrayList<BaseItem>) value); } } @Override public void onError(Throwable e) { mNewsListFrag.loadMoreFail(e.getMessage()); } }); } /** * 读取缓存 */ public void loadCache() { DiskCacheManager manager = new DiskCacheManager(CustomApplication.getContext(), Constants.CACHE_DOUYIN_FILE); ArrayList<BaseItem> topNews = manager.getSerializable(Constants.CACHE_DOUYIN_VIDEOS); if (topNews != null) { mNewsListFrag.refreshNewsSuccessed(topNews); } } @Override public void bindView(ImpBaseView view) { mNewsListFrag = (NewsContract.View) view; } @Override public void unbindView() { dispose(); } @Override public void onDestory() { mNewsListFrag = null; } }
[ "weir@getui.com" ]
weir@getui.com
de607de59b3a372cadf786e5fc539b7ec6ab77bb
d61f0355bfefebbe7e9839a279a8c977ee712ba2
/src/main/java/com/tmwj/demo/apiManager/MeetingServiceImpl.java
aed355f25d76bd206a252f5b1ee89b23512d1219
[ "Apache-2.0" ]
permissive
zjy369/TMWJ
371ea02ac56ec24d8e0577ea6274289eb466077c
408c92bce939835b4129d2057407895ab498cf9a
refs/heads/main
2023-04-26T03:05:47.804757
2021-05-28T09:04:55
2021-05-28T09:04:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,945
java
package com.tmwj.demo.apiManager; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.tmwj.demo.Meeting.*; import com.tmwj.demo.MeetingUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.nio.charset.StandardCharsets; import java.text.ParseException; import java.util.*; /** * description: * * @author: Victor * @date 2021/1/12 14:25 **/ @Service @Slf4j public class MeetingServiceImpl extends ServiceImpl<MeetingMapper, Meeting> implements IMeetingService { @Autowired private MeetingMapper mapper; @Autowired HttpServletRequest request; //这里可以获取到request //会议管理的域名 private static String meeting_uri = "/v1/meetings"; //用户管理的域名 private static String user_uri = "/v1/users"; @Override public String callbackMeetingEvent(CallbackMeetingParam entity){ String notifyBase64 = entity.getData(); if(MeetingUtil.validateSign(request,notifyBase64)) { return "failed!"; } final Base64.Decoder decoder = Base64.getDecoder(); String notifyJsonStr=new String(decoder.decode(notifyBase64), StandardCharsets.UTF_8);//Base64解码后为json字符串 String resJson = ""; System.out.println("{腾讯会议结束回调}接收到的报文:" + notifyJsonStr); JSONObject notifyJson = JSONObject.parseObject(notifyJsonStr);//fastjson转换 System.out.println("开始执行我的业务逻辑"); //不同事件执行不同逻辑 switch (notifyJson.getString("event")) { case "meeting.end": String meetingId=notifyJson .getJSONArray("payload") .getJSONObject(0) .getJSONObject("meeting_info") .getString("meeting_id"); handleMeetingEnd(meetingId); break; default: //有空了放异常处理 break; } return "successfully received callback"; } public void handleMeetingEnd(String mid) { UpdateWrapper<Meeting> updateWrapper=new UpdateWrapper<>(); updateWrapper.lambda() .set(Meeting::getCallback,1) .in(Meeting::getId,mid); mapper.update(null,updateWrapper); } @Override public String callbackCheck(String check_str) { if(MeetingUtil.validateSign(request,check_str)) { final Base64.Decoder decoder = Base64.getDecoder(); return new String(decoder.decode(check_str), StandardCharsets.UTF_8);//Base64解码后为json字符串 } return "failed!"; } @Override public String newMeetingUser(UpdateMeetingUser user) { String body = JSON.toJSONString(user); String result = MeetingUtil.requestPost(body,user_uri); if(result.equals("{}")){ return "success"; }else { return "error_message:"+result; } } @Override public String updateMeetingUser(UpdateMeetingUser user) { String body = JSON.toJSONString(user); String uri = user_uri+"/"+user.getUserid(); log.info(uri); String result = MeetingUtil.requestPut(body,uri); if(result.equals("{}")){ return "success"; }else { return "error_message:"+result; } } @Override public QueryUserInfoResVo getUserInfo(String userId) { String body = ""; String uri = user_uri+"/"+userId; String result = MeetingUtil.requestGet(body,uri); return JSON.parseObject(result, QueryUserInfoResVo.class); } @Override public QueryUserInfoList queryUserInfoList(Integer page, Integer pageSize) { String body = ""; String uri = user_uri+"/list?page="+page+"&page_size="+pageSize; log.info(uri); String result = MeetingUtil.requestGet(body,uri); return JSON.parseObject(result, QueryUserInfoList.class); } @Override public String deleteUser(String userId) { String body = ""; String uri = user_uri+"/"+userId; String result = MeetingUtil.requestDelete(body,uri); if(result.equals("{}")){ return "success"; }else { return "error_message:"+result; } } @Override public QueryMeetingInfoResVo scheduleMeeting(ScheduleMeetingRegVo scheduleMeetingRegVo) { String body = JSON.toJSONString(scheduleMeetingRegVo); String result = MeetingUtil.requestPost(body,meeting_uri); log.info("request body --->" + body); return JSON.parseObject(result, QueryMeetingInfoResVo.class); } @Override public QueryMeetingInfoResVo quickStart(QuickMeeting entity) { Long startTime = System.currentTimeMillis()/1000; Long endTime = startTime+7200; entity.setStart_time(String.valueOf(startTime)); entity.setEnd_time(String.valueOf(endTime)); entity.setType(1); String body = JSON.toJSONString(entity); System.out.println(body); String result = MeetingUtil.requestPost(body,meeting_uri); return JSON.parseObject(result,QueryMeetingInfoResVo.class); } @Override public QueryMeetingInfoResVo queryMeetingInfo(QueryMeetingByIdRegVo entity) { String body = ""; String uri = meeting_uri+"/"+entity.getMeetingId()+"?userid="+entity.getUserId()+"&instanceid="+entity.getInstanceId(); String result = MeetingUtil.requestGet(body,uri); return JSON.parseObject(result,QueryMeetingInfoResVo.class); } @Override public String cancelMeeting(CancelMeetingRegVo cancelMeetingRegVo, String meetingId) { String body = JSON.toJSONString(cancelMeetingRegVo); String uri = meeting_uri+"/"+meetingId+"/cancel"; String result = MeetingUtil.requestPost(body,uri); if(result.equals("{}")){ return "success"; }else { return "error_message:"+result; } } @Override public String endMeeting(EndMeetingVo entity) { String body = JSON.toJSONString(entity); String uri = meeting_uri+"/"+entity.getMeetingId()+"/dismiss"; String result = MeetingUtil.requestPost(body,uri); if(result.equals("{}")){ return "success"; }else { return "error_message:"+result; } } @Override public EditMeetingInfoResVo editMeeting(EditMeetingRegVo editMeetingRegVo, String meetingId) { String body = JSON.toJSONString(editMeetingRegVo); log.info("request body --->" + body); String uri = meeting_uri+"/"+meetingId; String result = MeetingUtil.requestPut(body,uri); return JSON.parseObject(result, EditMeetingInfoResVo.class); } @Override public QueryMeetingParticipantsResVo queryMeetingParticipants(QueryMeetingParticipantsReqVo entity) { String body = ""; String uri = meeting_uri+"/"+entity.getMeetingId()+"/participants?userid="+entity.getUserId(); String result = MeetingUtil.requestGet(body,uri); return JSON.parseObject(result, QueryMeetingParticipantsResVo.class); } @Override public QueryMeetingInfoResVo queryMeetingInfoList(QueryMeetingInfoListVo entity) { String body = ""; String uri = meeting_uri+"?userid="+entity.getUserId()+"&instanceid="+entity.getInstanceId(); String result = MeetingUtil.requestGet(body,uri); return JSON.parseObject(result,QueryMeetingInfoResVo.class); } }
[ "105361zhhZHH" ]
105361zhhZHH
fef3d0d89504e4dfc12f29d7cd01a5cd596ad487
27bc86fab2e4ab37a18989dd0ba97297553efeb2
/src/main/java/com/hzero/demo/mybatis/App.java
a5fe08008dd11476211cb4e043fce0d51ce5a0eb
[]
no_license
AES0P/SpringWithMyBatisDemo
b97ee503c48548392e25c8f189e05b64640cc358
e4e6f45bdf42534b20dc8f3bbc097813f27b0d0b
refs/heads/master
2023-05-04T18:50:49.818840
2019-11-21T03:53:14
2019-11-21T03:53:14
222,921,324
1
0
null
2023-04-17T19:42:21
2019-11-20T11:22:43
Java
UTF-8
Java
false
false
1,821
java
package com.hzero.demo.mybatis; import com.hzero.demo.mybatis.pojo.User; import com.hzero.demo.mybatis.service.impl.UserServiceImpl; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Hello world! */ public class App { public static void main(String[] args) { UserServiceImpl userService = (UserServiceImpl) new ClassPathXmlApplicationContext("ApplicationContext.xml") .getBean("userService"); User user = new User(); user.setName("Aesop"); user.setPassword("123456"); user.setAddress("haven"); user.setPhone(1383838); userService.insertUser(user); System.out.println("查询插入的数据:"); System.out.println(toString(user)); user.setId(user.getId()); user.setName("Aesop 1"); user.setPassword("54321"); user.setAddress("hhh"); user.setPhone(1388888); userService.updateUser(user); System.out.println("查询更新的数据:"); System.out.println(toString(user)); System.out.println("删除前的数据:"); for (User userCase : userService.findAllUser()) { System.out.println(toString(userCase)); } //删除本次插入的数据 userService.deleteUserById(user.getId()); System.out.println("删除后的数据:"); for (User userCase : userService.findAllUser()) { System.out.println(toString(userCase)); } } public static String toString(User user) { return "id: " + user.getId() + " " + "name: " + user.getName() + " " + "password: " + user.getPassword() + " " + "address: " + user.getAddress() + " " + "phone: " + user.getPhone(); } }
[ "wentao.tian@hand-china.com" ]
wentao.tian@hand-china.com
62ca387784135ae1826423c943007db6d5adf4f0
044b84e2384dfa07ccc8a18a7878ea1c3db44c67
/src/main/java/com/example/demo/controller/BuildingQueryController.java
406f1b0af4cc9ed4349e272db8e196b07889d797
[]
no_license
noisyboy25/spring-building-xml-demo
ccbc0e249b2e2f488d432c0178c6534f8c1879f2
dd12df17d3fd645eaf4d7206600863d8529fa044
refs/heads/main
2023-06-17T14:03:07.666218
2021-07-17T18:48:22
2021-07-17T18:48:22
383,904,422
0
2
null
2021-07-15T00:21:52
2021-07-07T19:25:40
Java
UTF-8
Java
false
false
1,843
java
package com.example.demo.controller; import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.UUID; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import com.example.demo.lib.XmlDatabase; import com.example.demo.model.Building; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class BuildingQueryController { final XmlDatabase<Building> buildingDb = new XmlDatabase<>("building.xml", Building.class); @GetMapping(value = "/q/building/read/{id}", produces = "application/json") public Optional<Building> oneBuilding(@PathVariable String id) throws IOException { return buildingDb.findFirst(UUID.fromString(id)); } @GetMapping(value = "/q/building/read", produces = "application/json") public List<Building> allBuildings() throws IOException { return buildingDb.findAll(); } /* * e.g. http://localhost:8080/q/building/create?propertyType=private& * street=lol&number=11&commissioningDate=today&storeysNumber=5&owner=10 */ @GetMapping(value = "/q/building/create", produces = "application/json") public void addBuilding(@Valid Building newBuilding, BindingResult bindingResult, HttpServletResponse response) throws IOException { if (!bindingResult.hasErrors()) { buildingDb.save(newBuilding); } response.sendRedirect("/"); } @GetMapping(value = "/q/building/delete/{id}", produces = "application/json") public void deleteBuilding(@PathVariable String id, HttpServletResponse response) throws IOException { buildingDb.delete(UUID.fromString(id)); response.sendRedirect("/"); } }
[ "dj402and@gmail.com" ]
dj402and@gmail.com
b4f969fd7b2f89eb24fda23fa0f78ac5785ac260
a52d6bb42e75ef0678cfcd291e5696a9e358fc4d
/af_webapp/src/main/java/org/kuali/kfs/fp/businessobject/DisbursementVoucherNonEmployeeTravel.java
81a640b1fc969e7ddd03de0c965ff13cd717397d
[]
no_license
Ariah-Group/Finance
894e39cfeda8f6fdb4f48a4917045c0bc50050c5
ca49930ca456799f99aad57e1e974453d8fe479d
refs/heads/master
2021-01-21T12:11:40.987504
2016-03-24T14:22:40
2016-03-24T14:22:40
26,879,430
0
0
null
null
null
null
UTF-8
Java
false
false
24,746
java
/* * Copyright 2005-2006 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.fp.businessobject; import java.sql.Timestamp; import java.text.ParseException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import org.kuali.kfs.sys.KFSPropertyConstants; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.rice.core.api.datetime.DateTimeService; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.krad.bo.PersistableBusinessObjectBase; import org.kuali.rice.krad.util.ObjectUtils; /** * This class is used to represent a non-employee trip for a disbursement voucher . */ public class DisbursementVoucherNonEmployeeTravel extends PersistableBusinessObjectBase { private String documentNumber; private String disbVchrTravelFromCityName; private String disbVchrTravelFromStateCode; private String dvTravelFromCountryCode; private String disbVchrTravelToCityName; private String disbVchrTravelToStateCode; private String disbVchrTravelToCountryCode; private Timestamp dvPerdiemStartDttmStamp; private Timestamp dvPerdiemEndDttmStamp; private KualiDecimal disbVchrPerdiemCalculatedAmt; private KualiDecimal disbVchrPerdiemActualAmount; private String dvPerdiemChangeReasonText; private String disbVchrServicePerformedDesc; private String dvServicePerformedLocName; private String dvServiceRegularEmprName; private String disbVchrAutoFromCityName; private String disbVchrAutoFromStateCode; private String disbVchrAutoToCityName; private String disbVchrAutoToStateCode; private boolean disbVchrAutoRoundTripCode; private Integer dvPersonalCarMileageAmount; private KualiDecimal disbVchrPersonalCarRate; private KualiDecimal disbVchrPersonalCarAmount; private boolean disbVchrExceptionCode; private Integer financialDocumentNextLineNbr; private String disbVchrNonEmpTravelerName; private KualiDecimal disbVchrPerdiemRate; private String disbVchrPerdiemCategoryName; private KualiDecimal disbVchrMileageCalculatedAmt; private KualiDecimal totalTravelAmount; private List dvNonEmployeeExpenses; private List dvPrePaidEmployeeExpenses; /** * Default no-arg constructor. */ public DisbursementVoucherNonEmployeeTravel() { dvNonEmployeeExpenses = new ArrayList<DisbursementVoucherNonEmployeeExpense>(); dvPrePaidEmployeeExpenses = new ArrayList<DisbursementVoucherNonEmployeeExpense>(); financialDocumentNextLineNbr = new Integer(1); } /** * Gets the documentNumber attribute. * * @return Returns the documentNumber */ public String getDocumentNumber() { return documentNumber; } /** * Sets the documentNumber attribute. * * @param documentNumber The documentNumber to set. */ public void setDocumentNumber(String documentNumber) { this.documentNumber = documentNumber; } /** * Gets the disbVchrTravelFromCityName attribute. * * @return Returns the disbVchrTravelFromCityName */ public String getDisbVchrTravelFromCityName() { return disbVchrTravelFromCityName; } /** * Sets the disbVchrTravelFromCityName attribute. * * @param disbVchrTravelFromCityName The disbVchrTravelFromCityName to set. */ public void setDisbVchrTravelFromCityName(String disbVchrTravelFromCityName) { this.disbVchrTravelFromCityName = disbVchrTravelFromCityName; } /** * Gets the disbVchrTravelFromStateCode attribute. * * @return Returns the disbVchrTravelFromStateCode */ public String getDisbVchrTravelFromStateCode() { return disbVchrTravelFromStateCode; } /** * Sets the disbVchrTravelFromStateCode attribute. * * @param disbVchrTravelFromStateCode The disbVchrTravelFromStateCode to set. */ public void setDisbVchrTravelFromStateCode(String disbVchrTravelFromStateCode) { this.disbVchrTravelFromStateCode = disbVchrTravelFromStateCode; } /** * Gets the dvTravelFromCountryCode attribute. * * @return Returns the dvTravelFromCountryCode */ public String getDvTravelFromCountryCode() { return dvTravelFromCountryCode; } /** * Sets the dvTravelFromCountryCode attribute. * * @param dvTravelFromCountryCode The dvTravelFromCountryCode to set. */ public void setDvTravelFromCountryCode(String dvTravelFromCountryCode) { this.dvTravelFromCountryCode = dvTravelFromCountryCode; } /** * Gets the disbVchrTravelToCityName attribute. * * @return Returns the disbVchrTravelToCityName */ public String getDisbVchrTravelToCityName() { return disbVchrTravelToCityName; } /** * Sets the disbVchrTravelToCityName attribute. * * @param disbVchrTravelToCityName The disbVchrTravelToCityName to set. */ public void setDisbVchrTravelToCityName(String disbVchrTravelToCityName) { this.disbVchrTravelToCityName = disbVchrTravelToCityName; } /** * Gets the disbVchrTravelToStateCode attribute. * * @return Returns the disbVchrTravelToStateCode */ public String getDisbVchrTravelToStateCode() { return disbVchrTravelToStateCode; } /** * Sets the disbVchrTravelToStateCode attribute. * * @param disbVchrTravelToStateCode The disbVchrTravelToStateCode to set. */ public void setDisbVchrTravelToStateCode(String disbVchrTravelToStateCode) { this.disbVchrTravelToStateCode = disbVchrTravelToStateCode; } /** * Gets the disbVchrTravelToCountryCode attribute. * * @return Returns the disbVchrTravelToCountryCode */ public String getDisbVchrTravelToCountryCode() { return disbVchrTravelToCountryCode; } /** * Sets the disbVchrTravelToCountryCode attribute. * * @param disbVchrTravelToCountryCode The disbVchrTravelToCountryCode to set. */ public void setDisbVchrTravelToCountryCode(String disbVchrTravelToCountryCode) { this.disbVchrTravelToCountryCode = disbVchrTravelToCountryCode; } /** * Gets the dvPerdiemStartDttmStamp attribute. * * @return Returns the dvPerdiemStartDttmStamp */ public Timestamp getDvPerdiemStartDttmStamp() { return dvPerdiemStartDttmStamp; } /** * Sets the dvPerdiemStartDttmStamp attribute. * * @param dvPerdiemStartDttmStamp The dvPerdiemStartDttmStamp to set. */ public void setDvPerdiemStartDttmStamp(Timestamp dvPerdiemStartDttmStamp) { this.dvPerdiemStartDttmStamp = dvPerdiemStartDttmStamp; } /** * Gets the dvPerdiemEndDttmStamp attribute. * * @return Returns the dvPerdiemEndDttmStamp */ public Timestamp getDvPerdiemEndDttmStamp() { return dvPerdiemEndDttmStamp; } /** * Sets the dvPerdiemEndDttmStamp attribute. * * @param dvPerdiemEndDttmStamp The dvPerdiemEndDttmStamp to set. */ public void setDvPerdiemEndDttmStamp(Timestamp dvPerdiemEndDttmStamp) { this.dvPerdiemEndDttmStamp = dvPerdiemEndDttmStamp; } /** * Gets the disbVchrPerdiemCalculatedAmt attribute. * * @return Returns the disbVchrPerdiemCalculatedAmt */ public KualiDecimal getDisbVchrPerdiemCalculatedAmt() { return disbVchrPerdiemCalculatedAmt; } /** * Sets the disbVchrPerdiemCalculatedAmt attribute. * * @param disbVchrPerdiemCalculatedAmt The disbVchrPerdiemCalculatedAmt to set. */ public void setDisbVchrPerdiemCalculatedAmt(KualiDecimal disbVchrPerdiemCalculatedAmt) { this.disbVchrPerdiemCalculatedAmt = disbVchrPerdiemCalculatedAmt; } /** * Gets the disbVchrPerdiemActualAmount attribute. * * @return Returns the disbVchrPerdiemActualAmount */ public KualiDecimal getDisbVchrPerdiemActualAmount() { return disbVchrPerdiemActualAmount; } /** * Sets the disbVchrPerdiemActualAmount attribute. * * @param disbVchrPerdiemActualAmount The disbVchrPerdiemActualAmount to set. */ public void setDisbVchrPerdiemActualAmount(KualiDecimal disbVchrPerdiemActualAmount) { this.disbVchrPerdiemActualAmount = disbVchrPerdiemActualAmount; } /** * Gets the dvPerdiemChangeReasonText attribute. * * @return Returns the dvPerdiemChangeReasonText */ public String getDvPerdiemChangeReasonText() { return dvPerdiemChangeReasonText; } /** * Sets the dvPerdiemChangeReasonText attribute. * * @param dvPerdiemChangeReasonText The dvPerdiemChangeReasonText to set. */ public void setDvPerdiemChangeReasonText(String dvPerdiemChangeReasonText) { this.dvPerdiemChangeReasonText = dvPerdiemChangeReasonText; } /** * Gets the disbVchrServicePerformedDesc attribute. * * @return Returns the disbVchrServicePerformedDesc */ public String getDisbVchrServicePerformedDesc() { return disbVchrServicePerformedDesc; } /** * Sets the disbVchrServicePerformedDesc attribute. * * @param disbVchrServicePerformedDesc The disbVchrServicePerformedDesc to set. */ public void setDisbVchrServicePerformedDesc(String disbVchrServicePerformedDesc) { this.disbVchrServicePerformedDesc = disbVchrServicePerformedDesc; } /** * Gets the dvServicePerformedLocName attribute. * * @return Returns the dvServicePerformedLocName */ public String getDvServicePerformedLocName() { return dvServicePerformedLocName; } /** * Sets the dvServicePerformedLocName attribute. * * @param dvServicePerformedLocName The dvServicePerformedLocName to set. */ public void setDvServicePerformedLocName(String dvServicePerformedLocName) { this.dvServicePerformedLocName = dvServicePerformedLocName; } /** * Gets the dvServiceRegularEmprName attribute. * * @return Returns the dvServiceRegularEmprName */ public String getDvServiceRegularEmprName() { return dvServiceRegularEmprName; } /** * Sets the dvServiceRegularEmprName attribute. * * @param dvServiceRegularEmprName The dvServiceRegularEmprName to set. */ public void setDvServiceRegularEmprName(String dvServiceRegularEmprName) { this.dvServiceRegularEmprName = dvServiceRegularEmprName; } /** * Gets the disbVchrAutoFromCityName attribute. * * @return Returns the disbVchrAutoFromCityName */ public String getDisbVchrAutoFromCityName() { return disbVchrAutoFromCityName; } /** * Sets the disbVchrAutoFromCityName attribute. * * @param disbVchrAutoFromCityName The disbVchrAutoFromCityName to set. */ public void setDisbVchrAutoFromCityName(String disbVchrAutoFromCityName) { this.disbVchrAutoFromCityName = disbVchrAutoFromCityName; } /** * Gets the disbVchrAutoFromStateCode attribute. * * @return Returns the disbVchrAutoFromStateCode */ public String getDisbVchrAutoFromStateCode() { return disbVchrAutoFromStateCode; } /** * Sets the disbVchrAutoFromStateCode attribute. * * @param disbVchrAutoFromStateCode The disbVchrAutoFromStateCode to set. */ public void setDisbVchrAutoFromStateCode(String disbVchrAutoFromStateCode) { this.disbVchrAutoFromStateCode = disbVchrAutoFromStateCode; } /** * Gets the disbVchrAutoToCityName attribute. * * @return Returns the disbVchrAutoToCityName */ public String getDisbVchrAutoToCityName() { return disbVchrAutoToCityName; } /** * Sets the disbVchrAutoToCityName attribute. * * @param disbVchrAutoToCityName The disbVchrAutoToCityName to set. */ public void setDisbVchrAutoToCityName(String disbVchrAutoToCityName) { this.disbVchrAutoToCityName = disbVchrAutoToCityName; } /** * Gets the disbVchrAutoToStateCode attribute. * * @return Returns the disbVchrAutoToStateCode */ public String getDisbVchrAutoToStateCode() { return disbVchrAutoToStateCode; } /** * Sets the disbVchrAutoToStateCode attribute. * * @param disbVchrAutoToStateCode The disbVchrAutoToStateCode to set. */ public void setDisbVchrAutoToStateCode(String disbVchrAutoToStateCode) { this.disbVchrAutoToStateCode = disbVchrAutoToStateCode; } /** * Gets the disbVchrAutoRoundTripCode attribute. * * @return Returns the disbVchrAutoRoundTripCode */ public boolean getDisbVchrAutoRoundTripCode() { return disbVchrAutoRoundTripCode; } /** * Sets the disbVchrAutoRoundTripCode attribute. * * @param disbVchrAutoRoundTripCode The disbVchrAutoRoundTripCode to set. */ public void setDisbVchrAutoRoundTripCode(boolean disbVchrAutoRoundTripCode) { this.disbVchrAutoRoundTripCode = disbVchrAutoRoundTripCode; } /** * Gets the dvPersonalCarMileageAmount attribute. * * @return Returns the dvPersonalCarMileageAmount */ public Integer getDvPersonalCarMileageAmount() { return dvPersonalCarMileageAmount; } /** * Sets the dvPersonalCarMileageAmount attribute. * * @param dvPersonalCarMileageAmount The dvPersonalCarMileageAmount to set. */ public void setDvPersonalCarMileageAmount(Integer dvPersonalCarMileageAmount) { this.dvPersonalCarMileageAmount = dvPersonalCarMileageAmount; } /** * Gets the disbVchrPersonalCarRate attribute. * * @return Returns the disbVchrPersonalCarRate */ public KualiDecimal getDisbVchrPersonalCarRate() { return disbVchrPersonalCarRate; } /** * Sets the disbVchrPersonalCarRate attribute. * * @param disbVchrPersonalCarRate The disbVchrPersonalCarRate to set. */ public void setDisbVchrPersonalCarRate(KualiDecimal disbVchrPersonalCarRate) { this.disbVchrPersonalCarRate = disbVchrPersonalCarRate; } /** * Gets the disbVchrPersonalCarAmount attribute. * * @return Returns the disbVchrPersonalCarAmount */ public KualiDecimal getDisbVchrPersonalCarAmount() { return dvPersonalCarMileageAmount == null ? null : disbVchrPersonalCarAmount; } /** * Sets the disbVchrPersonalCarAmount attribute. * * @param disbVchrPersonalCarAmount The disbVchrPersonalCarAmount to set. */ public void setDisbVchrPersonalCarAmount(KualiDecimal disbVchrPersonalCarAmount) { this.disbVchrPersonalCarAmount = disbVchrPersonalCarAmount; } /** * Gets the disbVchrExceptionCode attribute. * * @return Returns the disbVchrExceptionCode */ public boolean getDisbVchrExceptionCode() { return disbVchrExceptionCode; } /** * Sets the disbVchrExceptionCode attribute. * * @param disbVchrExceptionCode The disbVchrExceptionCode to set. */ public void setDisbVchrExceptionCode(boolean disbVchrExceptionCode) { this.disbVchrExceptionCode = disbVchrExceptionCode; } /** * Gets the financialDocumentNextLineNbr attribute. * * @return Returns the financialDocumentNextLineNbr */ public Integer getFinancialDocumentNextLineNbr() { return financialDocumentNextLineNbr; } /** * Sets the financialDocumentNextLineNbr attribute. * * @param financialDocumentNextLineNbr The financialDocumentNextLineNbr to set. */ public void setFinancialDocumentNextLineNbr(Integer financialDocumentNextLineNbr) { this.financialDocumentNextLineNbr = financialDocumentNextLineNbr; } /** * Gets the disbVchrNonEmpTravelerName attribute. * * @return Returns the disbVchrNonEmpTravelerName */ public String getDisbVchrNonEmpTravelerName() { return disbVchrNonEmpTravelerName; } /** * Sets the disbVchrNonEmpTravelerName attribute. * * @param disbVchrNonEmpTravelerName The disbVchrNonEmpTravelerName to set. */ public void setDisbVchrNonEmpTravelerName(String disbVchrNonEmpTravelerName) { this.disbVchrNonEmpTravelerName = disbVchrNonEmpTravelerName; } /** * Gets the disbVchrPerdiemRate attribute. * * @return Returns the disbVchrPerdiemRate */ public KualiDecimal getDisbVchrPerdiemRate() { return disbVchrPerdiemRate; } /** * Sets the disbVchrPerdiemRate attribute. * * @param disbVchrPerdiemRate The disbVchrPerdiemRate to set. */ public void setDisbVchrPerdiemRate(KualiDecimal disbVchrPerdiemRate) { this.disbVchrPerdiemRate = disbVchrPerdiemRate; } /** * Gets the disbVchrPerdiemCategoryName attribute. * * @return Returns the disbVchrPerdiemCategoryName */ public String getDisbVchrPerdiemCategoryName() { return disbVchrPerdiemCategoryName; } /** * Sets the disbVchrPerdiemCategoryName attribute. * * @param disbVchrPerdiemCategoryName The disbVchrPerdiemCategoryName to set. */ public void setDisbVchrPerdiemCategoryName(String disbVchrPerdiemCategoryName) { this.disbVchrPerdiemCategoryName = disbVchrPerdiemCategoryName; } /** * Gets the disbVchrMileageCalculatedAmt attribute. * * @return Returns the disbVchrMileageCalculatedAmt */ public KualiDecimal getDisbVchrMileageCalculatedAmt() { return dvPersonalCarMileageAmount == null ? null : disbVchrMileageCalculatedAmt; } /** * Sets the disbVchrMileageCalculatedAmt attribute. * * @param disbVchrMileageCalculatedAmt The disbVchrMileageCalculatedAmt to set. */ public void setDisbVchrMileageCalculatedAmt(KualiDecimal disbVchrMileageCalculatedAmt) { this.disbVchrMileageCalculatedAmt = disbVchrMileageCalculatedAmt; } /** * Gets the dvNonEmployeeExpenses attribute. * * @return Returns the dvNonEmployeeExpenses. */ public List getDvNonEmployeeExpenses() { return dvNonEmployeeExpenses; } /** * Sets the dvNonEmployeeExpenses attribute value. * * @param dvNonEmployeeExpenses The dvNonEmployeeExpenses to set. */ public void setDvNonEmployeeExpenses(List dvNonEmployeeExpenses) { this.dvNonEmployeeExpenses = dvNonEmployeeExpenses; } /** * @return Returns the dvPrePaidEmployeeExpenses. */ public List getDvPrePaidEmployeeExpenses() { return dvPrePaidEmployeeExpenses; } /** * @param dvPrePaidEmployeeExpenses The dvPrePaidEmployeeExpenses to set. */ public void setDvPrePaidEmployeeExpenses(List dvPrePaidEmployeeExpenses) { this.dvPrePaidEmployeeExpenses = dvPrePaidEmployeeExpenses; } /** * Adds a dv non employee expense line * * @param line */ public void addDvNonEmployeeExpenseLine(DisbursementVoucherNonEmployeeExpense line) { line.setFinancialDocumentLineNumber(getFinancialDocumentNextLineNbr()); this.dvNonEmployeeExpenses.add(line); this.financialDocumentNextLineNbr = new Integer(getFinancialDocumentNextLineNbr().intValue() + 1); } /** * Adds a dv pre paid expense line * * @param line */ public void addDvPrePaidEmployeeExpenseLine(DisbursementVoucherNonEmployeeExpense line) { line.setFinancialDocumentLineNumber(getFinancialDocumentNextLineNbr()); this.dvPrePaidEmployeeExpenses.add(line); this.financialDocumentNextLineNbr = new Integer(getFinancialDocumentNextLineNbr().intValue() + 1); } /** * Returns the per diem start date time as a string representation. * * @return */ public String getPerDiemStartDateTime() { return SpringContext.getBean(DateTimeService.class).toDateTimeString(dvPerdiemStartDttmStamp); } /** * Sets the per diem start timestamp from the string representation. * * @param perDiemStartDateTime */ public void setPerDiemStartDateTime(String perDiemStartDateTime) { try { this.dvPerdiemStartDttmStamp = SpringContext.getBean(DateTimeService.class).convertToSqlTimestamp(perDiemStartDateTime); } catch (ParseException e) { this.dvPerdiemStartDttmStamp = null; } } /** * Returns the per diem end date time as a string representation. * * @return String */ public String getPerDiemEndDateTime() { return SpringContext.getBean(DateTimeService.class).toDateTimeString(dvPerdiemEndDttmStamp); } /** * Sets the per diem start timestamp from the string representation. * * @param perDiemEndDateTime */ public void setPerDiemEndDateTime(String perDiemEndDateTime) { try { this.dvPerdiemEndDttmStamp = SpringContext.getBean(DateTimeService.class).convertToSqlTimestamp(perDiemEndDateTime); } catch (ParseException e) { this.dvPerdiemEndDttmStamp = null; } } /** * Calculates the total pre paid expense amount * * @return KualiDecimal */ public KualiDecimal getTotalPrePaidAmount() { KualiDecimal totalPrePaidAmount = KualiDecimal.ZERO; if (dvPrePaidEmployeeExpenses != null) { for (Iterator iter = dvPrePaidEmployeeExpenses.iterator(); iter.hasNext();) { DisbursementVoucherNonEmployeeExpense element = (DisbursementVoucherNonEmployeeExpense) iter.next(); if (ObjectUtils.isNotNull(element.getDisbVchrExpenseAmount())) { totalPrePaidAmount = totalPrePaidAmount.add(element.getDisbVchrExpenseAmount()); } } } return totalPrePaidAmount; } /** * Calculates the total expense amount * * @return KualiDecimal */ public KualiDecimal getTotalExpenseAmount() { KualiDecimal totalExpenseAmount = KualiDecimal.ZERO; if (dvNonEmployeeExpenses != null) { for (Iterator iter = dvNonEmployeeExpenses.iterator(); iter.hasNext();) { DisbursementVoucherNonEmployeeExpense element = (DisbursementVoucherNonEmployeeExpense) iter.next(); if (ObjectUtils.isNotNull(element.getDisbVchrExpenseAmount())) { totalExpenseAmount = totalExpenseAmount.add(element.getDisbVchrExpenseAmount()); } } } return totalExpenseAmount; } /** * Calculates the total travel amount. * * @return KualiDecimal */ public KualiDecimal getTotalTravelAmount() { KualiDecimal travelAmount = KualiDecimal.ZERO; // get non paid expenses first travelAmount = travelAmount.add(getTotalExpenseAmount()); // add in per diem amount if (disbVchrPerdiemActualAmount != null) { travelAmount = travelAmount.add(disbVchrPerdiemActualAmount); } // add in personnal car amount if (disbVchrPersonalCarAmount != null) { travelAmount = travelAmount.add(disbVchrPersonalCarAmount); } return travelAmount; } /** * @param totalTravelAmount The totalTravelAmount to set. */ public void setTotalTravelAmount(KualiDecimal totalTravelAmount) { this.totalTravelAmount = totalTravelAmount; } /** * @see org.kuali.rice.krad.bo.BusinessObjectBase#toStringMapper() */ protected LinkedHashMap toStringMapper_RICE20_REFACTORME() { LinkedHashMap m = new LinkedHashMap(); m.put(KFSPropertyConstants.DOCUMENT_NUMBER, this.documentNumber); return m; } }
[ "code@ariahgroup.org" ]
code@ariahgroup.org
06fbd72dc273fa9d4e64a47ebdfec3c5be3fccd3
58ca741cdadd8e0d9914f1fee418f0da34b5b5df
/superToasts/src/main/java/com/github/johnpersano/supertoasts/SuperCardToast.java
9eb728bf085b4249fe987c995dfe1de6accfa7d1
[]
no_license
wangwindlong/FBReader-as
d32944bb1b4e03253ce114b8170546dc14691a41
cccb52bb120d695c82a3541b438331e7f2f88110
refs/heads/master
2020-12-02T07:45:51.861789
2018-01-02T04:07:19
2018-01-02T04:07:19
96,722,287
10
4
null
null
null
null
UTF-8
Java
false
false
58,751
java
/** * Copyright 2014 John Persano * * 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.github.johnpersano.supertoasts; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.os.*; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.*; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.github.johnpersano.supertoasts.SuperToast.Animations; import com.github.johnpersano.supertoasts.SuperToast.IconPosition; import com.github.johnpersano.supertoasts.SuperToast.Type; import com.github.johnpersano.supertoasts.util.*; import java.util.LinkedList; /** * SuperCardToasts are designed to be used inside of activities. SuperCardToasts * are designed to be displayed at the top of an activity to display messages. */ @SuppressWarnings("UnusedDeclaration") public class SuperCardToast { private static final String TAG = "SuperCardToast"; private static final String MANAGER_TAG = "SuperCardToast Manager"; private static final String ERROR_ACTIVITYNULL = " - You cannot pass a null Activity as a parameter."; private static final String ERROR_CONTAINERNULL = " - You must have a LinearLayout with the id of card_container in your layout!"; private static final String ERROR_VIEWCONTAINERNULL = " - Either the View or Container was null when trying to dismiss."; private static final String ERROR_NOTBUTTONTYPE = " is only compatible with BUTTON type SuperCardToasts."; private static final String ERROR_NOTPROGRESSHORIZONTALTYPE = " is only compatible with PROGRESS_HORIZONTAL type SuperCardToasts."; private static final String WARNING_PREHONEYCOMB = "Swipe to dismiss was enabled but the SDK version is pre-Honeycomb"; /* Bundle tag with a hex as a string so it can't interfere with other tags in the bundle */ private static final String BUNDLE_TAG = "0x532e432e542e"; private Activity mActivity; private Animations mAnimations = Animations.FADE; private boolean mIsIndeterminate; private boolean mIsTouchDismissible; private boolean mIsSwipeDismissible; private boolean isProgressIndeterminate; private boolean showImmediate; private Button mButton; private Handler mHandler; private IconPosition mIconPosition; private int mDuration = SuperToast.Duration.SHORT; private int mIcon; private int mBackground = (R.drawable.background_standard_gray); private int mTypeface = Typeface.NORMAL; private int mButtonTypefaceStyle = Typeface.BOLD; private int mButtonIcon = SuperToast.Icon.Dark.UNDO; private int mDividerColor = Color.DKGRAY; private LayoutInflater mLayoutInflater; private LinearLayout mRootLayout; private OnDismissWrapper mOnDismissWrapper; private OnClickWrapper mOnClickWrapper; private Parcelable mToken; private ProgressBar mProgressBar; private String mOnClickWrapperTag; private String mOnDismissWrapperTag; private TextView mMessageTextView; private Type mType = Type.STANDARD; private ViewGroup mViewGroup; private View mToastView; private View mDividerView; /** * Instantiates a new {@value #TAG}. * * @param activity {@link android.app.Activity} */ @SuppressWarnings("ConstantConditions") public SuperCardToast(Activity activity) { if (activity == null) { throw new IllegalArgumentException(TAG + ERROR_ACTIVITYNULL); } this.mActivity = activity; this.mType = Type.STANDARD; mLayoutInflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mViewGroup = (LinearLayout) activity .findViewById(R.id.card_container); if (mViewGroup == null) { throw new IllegalArgumentException(TAG + ERROR_CONTAINERNULL); } mToastView = mLayoutInflater .inflate(R.layout.supercardtoast, mViewGroup, false); mMessageTextView = (TextView) mToastView.findViewById(R.id.message_textview); mRootLayout = (LinearLayout) mToastView.findViewById(R.id.root_layout); } /** * Instantiates a new {@value #TAG} with a specified default style. * * @param activity {@link android.app.Activity} * @param style {@link com.github.johnpersano.supertoasts.util.Style} */ @SuppressWarnings("ConstantConditions") public SuperCardToast(Activity activity, Style style) { if (activity == null) { throw new IllegalArgumentException(TAG + ERROR_ACTIVITYNULL); } this.mActivity = activity; this.mType = Type.STANDARD; mLayoutInflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mViewGroup = (LinearLayout) activity .findViewById(R.id.card_container); if (mViewGroup == null) { throw new IllegalArgumentException(TAG + ERROR_CONTAINERNULL); } mToastView = mLayoutInflater .inflate(R.layout.supercardtoast, mViewGroup, false); mMessageTextView = (TextView) mToastView.findViewById(R.id.message_textview); mRootLayout = (LinearLayout) mToastView.findViewById(R.id.root_layout); this.setStyle(style); } /** * Instantiates a new {@value #TAG} with a type. * * @param activity {@link android.app.Activity} * @param type {@link com.github.johnpersano.supertoasts.SuperToast.Type} */ @SuppressWarnings("ConstantConditions") public SuperCardToast(Activity activity, Type type) { if (activity == null) { throw new IllegalArgumentException(TAG + ERROR_ACTIVITYNULL); } this.mActivity = activity; this.mType = type; mLayoutInflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mViewGroup = (LinearLayout) activity .findViewById(R.id.card_container); if (mViewGroup == null) { throw new IllegalArgumentException(TAG + ERROR_CONTAINERNULL); } if (type == Type.BUTTON) { mToastView = mLayoutInflater .inflate(R.layout.supercardtoast_button, mViewGroup, false); mButton = (Button) mToastView.findViewById(R.id.button); mDividerView = mToastView.findViewById(R.id.divider); mButton.setOnClickListener(mButtonListener); } else if (type == Type.PROGRESS) { mToastView = mLayoutInflater .inflate(R.layout.supercardtoast_progresscircle, mViewGroup, false); mProgressBar = (ProgressBar) mToastView.findViewById(R.id.progress_bar); } else if (type == Type.PROGRESS_HORIZONTAL) { mToastView = mLayoutInflater .inflate(R.layout.supercardtoast_progresshorizontal, mViewGroup, false); mProgressBar = (ProgressBar) mToastView.findViewById(R.id.progress_bar); } else { mToastView = mLayoutInflater .inflate(R.layout.supercardtoast, mViewGroup, false); } mMessageTextView = (TextView) mToastView.findViewById(R.id.message_textview); mRootLayout = (LinearLayout) mToastView.findViewById(R.id.root_layout); } /** * Instantiates a new {@value #TAG} with a type and a specified style. * * @param activity {@link android.app.Activity} * @param type {@link com.github.johnpersano.supertoasts.SuperToast.Type} * @param style {@link com.github.johnpersano.supertoasts.util.Style} */ @SuppressWarnings("ConstantConditions") public SuperCardToast(Activity activity, Type type, Style style) { if (activity == null) { throw new IllegalArgumentException(TAG + ERROR_ACTIVITYNULL); } this.mActivity = activity; this.mType = type; mLayoutInflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mViewGroup = (LinearLayout) activity .findViewById(R.id.card_container); if (mViewGroup == null) { throw new IllegalArgumentException(TAG + ERROR_CONTAINERNULL); } if (type == Type.BUTTON) { mToastView = mLayoutInflater .inflate(R.layout.supercardtoast_button, mViewGroup, false); mButton = (Button) mToastView.findViewById(R.id.button); mDividerView = mToastView.findViewById(R.id.divider); mButton.setOnClickListener(mButtonListener); } else if (type == Type.PROGRESS) { mToastView = mLayoutInflater .inflate(R.layout.supercardtoast_progresscircle, mViewGroup, false); mProgressBar = (ProgressBar) mToastView.findViewById(R.id.progress_bar); } else if (type == Type.PROGRESS_HORIZONTAL) { mToastView = mLayoutInflater .inflate(R.layout.supercardtoast_progresshorizontal, mViewGroup, false); mProgressBar = (ProgressBar) mToastView.findViewById(R.id.progress_bar); } else { mToastView = mLayoutInflater .inflate(R.layout.supercardtoast, mViewGroup, false); } mMessageTextView = (TextView) mToastView.findViewById(R.id.message_textview); mRootLayout = (LinearLayout) mToastView.findViewById(R.id.root_layout); this.setStyle(style); } /** * Shows the {@value #TAG}. If another {@value #TAG} is showing than * this one will be added underneath. */ public void show() { ManagerSuperCardToast.getInstance().add(this); if (!mIsIndeterminate) { mHandler = new Handler(); mHandler.postDelayed(mHideRunnable, mDuration); } mViewGroup.addView(mToastView); if (!showImmediate) { final Animation animation = this.getShowAnimation(); /* Invalidate the ViewGroup after the show animation completes **/ animation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationEnd(Animation arg0) { /* Must use Handler to modify ViewGroup in onAnimationEnd() **/ Handler mHandler = new Handler(); mHandler.post(mInvalidateRunnable); } @Override public void onAnimationRepeat(Animation arg0) { /* Do nothing */ } @Override public void onAnimationStart(Animation arg0) { /* Do nothing */ } }); mToastView.startAnimation(animation); } } /** * Returns the {@link com.github.johnpersano.supertoasts.SuperToast.Type} of {@value #TAG}. * * @return {@link com.github.johnpersano.supertoasts.SuperToast.Type} */ public Type getType() { return mType; } /** * Sets the message text of the {@value #TAG}. * * @param text {@link CharSequence} */ public void setText(CharSequence text) { mMessageTextView.setText(text); } /** * Returns the message text of the {@value #TAG}. * * @return {@link CharSequence} */ public CharSequence getText() { return mMessageTextView.getText(); } /** * Sets the message {@link android.graphics.Typeface} style of the {@value #TAG}. * * @param typeface {@link android.graphics.Typeface} */ public void setTypefaceStyle(int typeface) { mTypeface = typeface; mMessageTextView.setTypeface(mMessageTextView.getTypeface(), typeface); } /** * Returns the message {@link android.graphics.Typeface} style of the {@value #TAG}. * * @return int */ public int getTypefaceStyle() { return mTypeface; } /** * Sets the message text color of the {@value #TAG}. * * @param textColor {@link android.graphics.Color} */ public void setTextColor(int textColor) { mMessageTextView.setTextColor(textColor); } /** * Returns the message text color of the {@value #TAG}. * * @return int */ public int getTextColor() { return mMessageTextView.getCurrentTextColor(); } /** * Sets the text size of the {@value #TAG} message. * * @param textSize int */ public void setTextSize(int textSize) { mMessageTextView.setTextSize(textSize); } /** * Used by orientation change recreation */ private void setTextSizeFloat(float textSize) { mMessageTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); } /** * Returns the text size of the {@value #TAG} message in pixels. * * @return float */ public float getTextSize() { return mMessageTextView.getTextSize(); } /** * Sets the duration that the {@value #TAG} will show. * * @param duration {@link com.github.johnpersano.supertoasts.SuperToast.Duration} */ public void setDuration(int duration) { this.mDuration = duration; } /** * Returns the duration of the {@value #TAG}. * * @return int */ public int getDuration() { return this.mDuration; } /** * If true will show the {@value #TAG} for an indeterminate time period and ignore any set duration. * * @param isIndeterminate boolean */ public void setIndeterminate(boolean isIndeterminate) { this.mIsIndeterminate = isIndeterminate; } /** * Returns true if the {@value #TAG} is indeterminate. * * @return boolean */ public boolean isIndeterminate() { return this.mIsIndeterminate; } /** * Sets an icon resource to the {@value #TAG} with a specified position. * * @param icon {@link com.github.johnpersano.supertoasts.SuperToast.Icon} * @param iconPosition {@link com.github.johnpersano.supertoasts.SuperToast.IconPosition} */ public void setIcon(int icon, IconPosition iconPosition) { this.mIcon = icon; this.mIconPosition = iconPosition; if (iconPosition == IconPosition.BOTTOM) { mMessageTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, mActivity.getResources().getDrawable(icon)); } else if (iconPosition == IconPosition.LEFT) { mMessageTextView.setCompoundDrawablesWithIntrinsicBounds(mActivity.getResources() .getDrawable(icon), null, null, null); } else if (iconPosition == IconPosition.RIGHT) { mMessageTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, mActivity.getResources().getDrawable(icon), null); } else if (iconPosition == IconPosition.TOP) { mMessageTextView.setCompoundDrawablesWithIntrinsicBounds(null, mActivity.getResources().getDrawable(icon), null, null); } } /** * Returns the icon position of the {@value #TAG}. * * @return {@link com.github.johnpersano.supertoasts.SuperToast.IconPosition} */ public IconPosition getIconPosition() { return this.mIconPosition; } /** * Returns the icon resource of the {@value #TAG}. * * @return int */ public int getIconResource() { return this.mIcon; } /** * Sets the background resource of the {@value #TAG}. The KitKat style backgrounds * included with this library are NOT compatible with {@value #TAG}. * * @param background {@link com.github.johnpersano.supertoasts.SuperToast.Background} */ public void setBackground(int background) { this.mBackground = checkForKitKatBackgrounds(background); mRootLayout.setBackgroundResource(mBackground); } /** * Make sure KitKat style backgrounds are not used with {@value #TAG}. * * @return int */ private int checkForKitKatBackgrounds(int background) { if(background == R.drawable.background_kitkat_black) { return (R.drawable.background_standard_black); } else if(background == R.drawable.background_kitkat_blue) { return (R.drawable.background_standard_blue); } else if(background == R.drawable.background_kitkat_gray) { return (R.drawable.background_standard_gray); } else if(background == R.drawable.background_kitkat_green) { return (R.drawable.background_standard_green); } else if(background == R.drawable.background_kitkat_orange) { return (R.drawable.background_standard_orange); } else if(background == R.drawable.background_kitkat_purple) { return (R.drawable.background_standard_purple); } else if(background == R.drawable.background_kitkat_red) { return (R.drawable.background_standard_red); } else if(background == R.drawable.background_kitkat_white) { return (R.drawable.background_standard_white); } else { return background; } } /** * Returns the background resource of the {@value #TAG}. * * @return int */ public int getBackgroundResource() { return this.mBackground; } /** * Sets the show/hide animations of the {@value #TAG}. * * @param animations {@link com.github.johnpersano.supertoasts.SuperToast.Animations} */ public void setAnimations(Animations animations) { this.mAnimations = animations; } /** * Returns the show/hide animations of the {@value #TAG}. * * @return {@link com.github.johnpersano.supertoasts.SuperToast.Animations} */ public Animations getAnimations() { return this.mAnimations; } /** * If true will show the {@value #TAG} without animation. * * @param showImmediate boolean */ public void setShowImmediate(boolean showImmediate) { this.showImmediate = showImmediate; } /** * Returns true if the {@value #TAG} is set to show without animation. * * @return boolean */ public boolean getShowImmediate() { return this.showImmediate; } /** * If true will dismiss the {@value #TAG} if the user touches it. * * @param touchDismiss boolean */ public void setTouchToDismiss(boolean touchDismiss) { this.mIsTouchDismissible = touchDismiss; if (touchDismiss) { mToastView.setOnTouchListener(mTouchDismissListener); } else { mToastView.setOnTouchListener(null); } } /** * Returns true if the {@value #TAG} is touch dismissible. * * @return boolean */ public boolean isTouchDismissible() { return this.mIsTouchDismissible; } /** * If true will dismiss the {@value #TAG} if the user swipes it. * * @param swipeDismiss boolean */ public void setSwipeToDismiss(boolean swipeDismiss) { this.mIsSwipeDismissible = swipeDismiss; if (swipeDismiss) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1) { final SwipeDismissListener swipeDismissListener = new SwipeDismissListener( mToastView, new SwipeDismissListener.OnDismissCallback() { @Override public void onDismiss(View view) { dismissImmediately(); } }); mToastView.setOnTouchListener(swipeDismissListener); } else { Log.w(TAG, WARNING_PREHONEYCOMB); } } else { mToastView.setOnTouchListener(null); } } /** * Returns true if the {@value #TAG} is swipe dismissible. * * @return boolean */ public boolean isSwipeDismissible() { return mIsSwipeDismissible; } /** * Sets an OnDismissWrapper defined in this library * to the {@value #TAG}. * * @param onDismissWrapper {@link com.github.johnpersano.supertoasts.util.OnDismissWrapper} */ public void setOnDismissWrapper(OnDismissWrapper onDismissWrapper) { this.mOnDismissWrapper = onDismissWrapper; this.mOnDismissWrapperTag = onDismissWrapper.getTag(); } /** * Used in {@value #MANAGER_TAG}. */ protected OnDismissWrapper getOnDismissWrapper() { return this.mOnDismissWrapper; } /** * Used in orientation change recreation. */ private String getDismissListenerTag() { return mOnDismissWrapperTag; } /** * Dismisses the {@value #TAG}. */ public void dismiss() { ManagerSuperCardToast.getInstance().remove(this); dismissWithAnimation(); } /** * Dismisses the SuperCardToast without an animation. */ public void dismissImmediately() { ManagerSuperCardToast.getInstance().remove(this); if (mHandler != null) { mHandler.removeCallbacks(mHideRunnable); mHandler.removeCallbacks(mHideWithAnimationRunnable); mHandler = null; } if (mToastView != null && mViewGroup != null) { mViewGroup.removeView(mToastView); if (mOnDismissWrapper != null) { mOnDismissWrapper.onDismiss(getView()); } mToastView = null; } else { Log.e(TAG, ERROR_VIEWCONTAINERNULL); } } /** * Hide the SuperCardToast and animate the Layout. Post Honeycomb only. * */ @SuppressLint("NewApi") private void dismissWithLayoutAnimation() { if (mToastView != null) { mToastView.setVisibility(View.INVISIBLE); final ViewGroup.LayoutParams layoutParams = mToastView.getLayoutParams(); final int originalHeight = mToastView.getHeight(); ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1) .setDuration(mActivity.getResources().getInteger(android.R.integer.config_shortAnimTime)); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { Handler mHandler = new Handler(); mHandler.post(mHideImmediateRunnable); } }); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override @SuppressWarnings("ConstantConditions") public void onAnimationUpdate(ValueAnimator valueAnimator) { if (mToastView != null) { try { layoutParams.height = (Integer) valueAnimator.getAnimatedValue(); mToastView.setLayoutParams(layoutParams); } catch (NullPointerException e) { /* Do nothing */ } } } }); animator.start(); } else { dismissImmediately(); } } @SuppressLint("NewApi") @SuppressWarnings("deprecation") private void dismissWithAnimation() { Animation animation = this.getDismissAnimation(); animation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationEnd(Animation animation) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { /* Must use Handler to modify ViewGroup in onAnimationEnd() **/ Handler handler = new Handler(); handler.post(mHideWithAnimationRunnable); } else { /* Must use Handler to modify ViewGroup in onAnimationEnd() **/ Handler handler = new Handler(); handler.post(mHideImmediateRunnable); } } @Override public void onAnimationRepeat(Animation animation) { /* Do nothing */ } @Override public void onAnimationStart(Animation animation) { /* Do nothing */ } }); if (mToastView != null) { mToastView.startAnimation(animation); } } /** * Sets an OnClickWrapper to the button in a * a BUTTON {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @param onClickWrapper {@link com.github.johnpersano.supertoasts.util.OnClickWrapper} */ public void setOnClickWrapper(OnClickWrapper onClickWrapper) { if (mType != Type.BUTTON) { Log.w(TAG, "setOnClickListenerWrapper()" + ERROR_NOTBUTTONTYPE); } this.mOnClickWrapper = onClickWrapper; this.mOnClickWrapperTag = onClickWrapper.getTag(); } /** * Sets an OnClickWrapper with a parcelable object to the button in a BUTTON * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @param onClickWrapper {@link com.github.johnpersano.supertoasts.util.OnClickWrapper} * @param token {@link android.os.Parcelable} */ public void setOnClickWrapper(OnClickWrapper onClickWrapper, Parcelable token) { if (mType != Type.BUTTON) { Log.e(TAG, "setOnClickListenerWrapper()" + ERROR_NOTBUTTONTYPE); } onClickWrapper.setToken(token); this.mToken = token; this.mOnClickWrapper = onClickWrapper; this.mOnClickWrapperTag = onClickWrapper.getTag(); } /** * Used in orientation change recreation. */ private Parcelable getToken(){ return mToken; } /** * Used in orientation change recreation. */ private String getOnClickWrapperTag() { return mOnClickWrapperTag; } /** * Sets the icon resource of the button in * a BUTTON {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @param buttonIcon {@link com.github.johnpersano.supertoasts.SuperToast.Icon} */ public void setButtonIcon(int buttonIcon) { if (mType != Type.BUTTON) { Log.w(TAG, "setButtonIcon()" + ERROR_NOTBUTTONTYPE); } this.mButtonIcon = buttonIcon; if (mButton != null) { mButton.setCompoundDrawablesWithIntrinsicBounds(mActivity .getResources().getDrawable(buttonIcon), null, null, null); } } /** * Sets the icon resource and text of the button in * a BUTTON {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @param buttonIcon {@link com.github.johnpersano.supertoasts.SuperToast.Icon} * @param buttonText {@link CharSequence} */ public void setButtonIcon(int buttonIcon, CharSequence buttonText) { if (mType != Type.BUTTON) { Log.w(TAG, "setButtonIcon()" + ERROR_NOTBUTTONTYPE); } this.mButtonIcon = buttonIcon; if (mButton != null) { mButton.setCompoundDrawablesWithIntrinsicBounds(mActivity .getResources().getDrawable(buttonIcon), null, null, null); mButton.setText(buttonText); } } /** * Returns the icon resource of the button in * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @return int */ public int getButtonIcon() { return this.mButtonIcon; } /** * Sets the divider color of a BUTTON * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @param dividerColor int */ public void setDividerColor(int dividerColor) { if (mType != Type.BUTTON) { Log.w(TAG, "setDivider()" + ERROR_NOTBUTTONTYPE); } this.mDividerColor = dividerColor; if (mDividerView != null) { mDividerView.setBackgroundColor(dividerColor); } } /** * Returns the divider color of a BUTTON * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @return int */ public int getDividerColor() { return this.mDividerColor; } /** * Sets the button text of a BUTTON * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @param buttonText {@link CharSequence} */ public void setButtonText(CharSequence buttonText) { if (mType != Type.BUTTON) { Log.w(TAG, "setButtonText()" + ERROR_NOTBUTTONTYPE); } if (mButton != null) { mButton.setText(buttonText); } } /** * Returns the button text of a BUTTON * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @return {@link CharSequence} */ public CharSequence getButtonText() { if(mButton != null) { return mButton.getText(); } else { Log.e(TAG, "getButtonText()" + ERROR_NOTBUTTONTYPE); return ""; } } /** * Sets the typeface style of the button in a BUTTON * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @param typefaceStyle {@link android.graphics.Typeface} */ public void setButtonTypefaceStyle(int typefaceStyle) { if (mType != Type.BUTTON) { Log.w(TAG, "setButtonTypefaceStyle()" + ERROR_NOTBUTTONTYPE); } if (mButton != null) { mButtonTypefaceStyle = typefaceStyle; mButton.setTypeface(mButton.getTypeface(), typefaceStyle); } } /** * Returns the typeface style of the button in a BUTTON * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @return int */ public int getButtonTypefaceStyle() { return this.mButtonTypefaceStyle; } /** * Sets the button text color of a BUTTON * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @param buttonTextColor {@link android.graphics.Color} */ public void setButtonTextColor(int buttonTextColor) { if (mType != Type.BUTTON) { Log.w(TAG, "setButtonTextColor()" + ERROR_NOTBUTTONTYPE); } if (mButton != null) { mButton.setTextColor(buttonTextColor); } } /** * Returns the button text color of a BUTTON * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @return int */ public int getButtonTextColor() { if(mButton != null) { return mButton.getCurrentTextColor(); } else { Log.e(TAG, "getButtonTextColor()" + ERROR_NOTBUTTONTYPE); return 0; } } /** * Sets the button text size of a BUTTON * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @param buttonTextSize int */ public void setButtonTextSize(int buttonTextSize) { if (mType != Type.BUTTON) { Log.w(TAG, "setButtonTextSize()" + ERROR_NOTBUTTONTYPE); } if (mButton != null) { mButton.setTextSize(buttonTextSize); } } /** * Used by orientation change recreation */ private void setButtonTextSizeFloat(float buttonTextSize) { mButton.setTextSize(TypedValue.COMPLEX_UNIT_PX, buttonTextSize); } /** * Returns the button text size of a BUTTON * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @return float */ public float getButtonTextSize() { if(mButton != null){ return mButton.getTextSize(); } else { Log.e(TAG, "getButtonTextSize()" + ERROR_NOTBUTTONTYPE); return 0.0f; } } /** * Sets the progress of the progressbar in a PROGRESS_HORIZONTAL * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @param progress int */ public void setProgress(int progress) { if (mType != Type.PROGRESS_HORIZONTAL) { Log.w(TAG, "setProgress()" + ERROR_NOTPROGRESSHORIZONTALTYPE); } if (mProgressBar != null) { mProgressBar.setProgress(progress); } } /** * Returns the progress of the progressbar in a PROGRESS_HORIZONTAL * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @return int */ public int getProgress() { if(mProgressBar != null) { return mProgressBar.getProgress(); } else { Log.e(TAG, "ProgressBar" + ERROR_NOTPROGRESSHORIZONTALTYPE); return 0; } } /** * Sets the maximum value of the progressbar in a PROGRESS_HORIZONTAL * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @param maxProgress int */ public void setMaxProgress(int maxProgress) { if (mType != Type.PROGRESS_HORIZONTAL) { Log.e(TAG, "setMaxProgress()" + ERROR_NOTPROGRESSHORIZONTALTYPE); } if (mProgressBar != null) { mProgressBar.setMax(maxProgress); } } /** * Returns the maximum value of the progressbar in a PROGRESS_HORIZONTAL * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @return int */ public int getMaxProgress() { if(mProgressBar != null){ return mProgressBar.getMax(); } else { Log.e(TAG, "getMaxProgress()" + ERROR_NOTPROGRESSHORIZONTALTYPE); return mProgressBar.getMax(); } } /** * Sets an indeterminate value to the progressbar of a PROGRESS * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @param isIndeterminate boolean */ public void setProgressIndeterminate(boolean isIndeterminate) { if (mType != Type.PROGRESS_HORIZONTAL) { Log.e(TAG, "setProgressIndeterminate()" + ERROR_NOTPROGRESSHORIZONTALTYPE); } this.isProgressIndeterminate = isIndeterminate; if (mProgressBar != null) { mProgressBar.setIndeterminate(isIndeterminate); } } /** * Returns an indeterminate value to the progressbar of a PROGRESS * {@link com.github.johnpersano.supertoasts.SuperToast.Type} {@value #TAG}. * * @return boolean */ public boolean getProgressIndeterminate() { return this.isProgressIndeterminate; } /** * Returns the {@value #TAG} message textview. * * @return {@link android.widget.TextView} */ public TextView getTextView() { return mMessageTextView; } /** * Returns the {@value #TAG} view. * * @return {@link android.view.View} */ public View getView() { return mToastView; } /** * Returns true if the {@value #TAG} is showing. * * @return boolean */ public boolean isShowing() { return mToastView != null && mToastView.isShown(); } /** * Returns the calling activity of the {@value #TAG}. * * @return {@link android.app.Activity} */ public Activity getActivity() { return mActivity; } /** * Returns the viewgroup that the {@value #TAG} is attached to. * * @return {@link android.view.ViewGroup} */ public ViewGroup getViewGroup() { return mViewGroup; } /** * Private method used to set a default style to the {@value #TAG} */ private void setStyle(Style style) { this.setAnimations(style.animations); this.setTypefaceStyle(style.typefaceStyle); this.setTextColor(style.textColor); this.setBackground(style.background); if(this.mType == Type.BUTTON) { this.setDividerColor(style.dividerColor); this.setButtonTextColor(style.buttonTextColor); } } /** * Runnable to dismiss the {@value #TAG} with animation. */ private final Runnable mHideRunnable = new Runnable() { @Override public void run() { dismiss(); } }; /** * Runnable to dismiss the {@value #TAG} without animation. */ private final Runnable mHideImmediateRunnable = new Runnable() { @Override public void run() { dismissImmediately(); } }; /** * Runnable to dismiss the {@value #TAG} with layout animation. */ private final Runnable mHideWithAnimationRunnable = new Runnable() { @Override public void run() { dismissWithLayoutAnimation(); } }; /** * Runnable to invalidate the layout containing the {@value #TAG}. */ private final Runnable mInvalidateRunnable = new Runnable() { @Override public void run() { if (mViewGroup != null) { mViewGroup.postInvalidate(); } } }; private Animation getShowAnimation() { if (this.getAnimations() == Animations.FLYIN) { TranslateAnimation translateAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.75f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f); AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1f); AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(translateAnimation); animationSet.addAnimation(alphaAnimation); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setDuration(250); return animationSet; } else if (this.getAnimations() == Animations.SCALE) { ScaleAnimation scaleAnimation = new ScaleAnimation(0.9f, 1.0f, 0.9f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1f); AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(scaleAnimation); animationSet.addAnimation(alphaAnimation); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setDuration(250); return animationSet; } else if (this.getAnimations() == Animations.POPUP) { TranslateAnimation translateAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.1f, Animation.RELATIVE_TO_SELF, 0.0f); AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1f); AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(translateAnimation); animationSet.addAnimation(alphaAnimation); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setDuration(250); return animationSet; } else { Animation animation = new AlphaAnimation(0f, 1f); animation.setDuration(500); animation.setInterpolator(new DecelerateInterpolator()); return animation; } } private Animation getDismissAnimation() { if (this.getAnimations() == Animations.FLYIN) { TranslateAnimation translateAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, .75f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f); AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f); AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(translateAnimation); animationSet.addAnimation(alphaAnimation); animationSet.setInterpolator(new AccelerateInterpolator()); animationSet.setDuration(250); return animationSet; } else if (this.getAnimations() == Animations.SCALE) { ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 0.9f, 1.0f, 0.9f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f); AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(scaleAnimation); animationSet.addAnimation(alphaAnimation); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setDuration(250); return animationSet; } else if (this.getAnimations() == Animations.POPUP) { TranslateAnimation translateAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.1f); AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f); AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(translateAnimation); animationSet.addAnimation(alphaAnimation); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setDuration(250); return animationSet; } else { AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f); alphaAnimation.setDuration(500); alphaAnimation.setInterpolator(new AccelerateInterpolator()); return alphaAnimation; } } /** * Returns a standard {@value #TAG}. * <br> * IMPORTANT: Activity layout should contain a linear layout * with the id card_container * <br> * * @param activity {@link android.app.Activity} * @param textCharSequence {@link CharSequence} * @param durationInteger {@link com.github.johnpersano.supertoasts.SuperToast.Duration} * * @return SuperCardToast */ public static SuperCardToast create(Activity activity, CharSequence textCharSequence, int durationInteger) { SuperCardToast superCardToast = new SuperCardToast(activity); superCardToast.setText(textCharSequence); superCardToast.setDuration(durationInteger); return superCardToast; } /** * Returns a standard {@value #TAG} with specified animations. * <br> * IMPORTANT: Activity layout should contain a linear layout * with the id card_container * <br> * * @param activity {@link android.app.Activity} * @param textCharSequence {@link CharSequence} * @param durationInteger {@link com.github.johnpersano.supertoasts.SuperToast.Duration} * @param animations {@link com.github.johnpersano.supertoasts.SuperToast.Animations} * * @return SuperCardToast */ public static SuperCardToast create(Activity activity, CharSequence textCharSequence, int durationInteger, Animations animations) { SuperCardToast superCardToast = new SuperCardToast(activity); superCardToast.setText(textCharSequence); superCardToast.setDuration(durationInteger); superCardToast.setAnimations(animations); return superCardToast; } /** * Returns a {@value #TAG} with a specified style. * <br> * IMPORTANT: Activity layout should contain a linear layout * with the id card_container * <br> * * @param activity {@link android.app.Activity} * @param textCharSequence {@link CharSequence} * @param durationInteger {@link com.github.johnpersano.supertoasts.SuperToast.Duration} * @param style {@link com.github.johnpersano.supertoasts.util.Style} * * @return SuperCardToast */ public static SuperCardToast create(Activity activity, CharSequence textCharSequence, int durationInteger, Style style) { SuperCardToast superCardToast = new SuperCardToast(activity); superCardToast.setText(textCharSequence); superCardToast.setDuration(durationInteger); superCardToast.setStyle(style); return superCardToast; } /** * Dismisses and removes all showing/pending SuperCardToasts. */ public static void cancelAllSuperCardToasts() { ManagerSuperCardToast.getInstance().cancelAllSuperActivityToasts(); } /** * Saves pending/shown SuperCardToasts to a bundle. * * @param bundle Use onSaveInstanceState() bundle */ public static void onSaveState(Bundle bundle) { ReferenceHolder[] list = new ReferenceHolder[ManagerSuperCardToast .getInstance().getList().size()]; LinkedList<SuperCardToast> lister = ManagerSuperCardToast .getInstance().getList(); for (int i = 0; i < list.length; i++) { list[i] = new ReferenceHolder(lister.get(i)); } bundle.putParcelableArray(BUNDLE_TAG, list); SuperCardToast.cancelAllSuperCardToasts(); } /** * Returns and shows pending/shown SuperCardToasts from orientation change. * * @param bundle Use onCreate() bundle * @param activity The current activity */ public static void onRestoreState(Bundle bundle, Activity activity) { if (bundle == null) { return; } Parcelable[] savedArray = bundle.getParcelableArray(BUNDLE_TAG); int i = 0; if (savedArray != null) { for (Parcelable parcelable : savedArray) { i++; new SuperCardToast(activity, (ReferenceHolder) parcelable, null, i); } } } /** * Returns and shows pending/shown {@value #TAG} from orientation change and * reattaches any OnClickWrappers/OnDismissWrappers. * * @param bundle Use onCreate() bundle * @param activity The current activity * @param wrappers {@link com.github.johnpersano.supertoasts.util.Wrappers} */ public static void onRestoreState(Bundle bundle, Activity activity, Wrappers wrappers) { if (bundle == null) { return; } Parcelable[] savedArray = bundle.getParcelableArray(BUNDLE_TAG); int i = 0; if (savedArray != null) { for (Parcelable parcelable : savedArray) { i++; new SuperCardToast(activity, (ReferenceHolder) parcelable, wrappers, i); } } } /** * Method used to recreate {@value #TAG} after orientation change */ private SuperCardToast(Activity activity, ReferenceHolder referenceHolder, Wrappers wrappers, int position) { SuperCardToast superCardToast; if(referenceHolder.mType == Type.BUTTON) { superCardToast = new SuperCardToast(activity, Type.BUTTON); superCardToast.setButtonText(referenceHolder.mButtonText); superCardToast.setButtonTextSizeFloat(referenceHolder.mButtonTextSize); superCardToast.setButtonTextColor(referenceHolder.mButtonTextColor); superCardToast.setButtonIcon(referenceHolder.mButtonIcon); superCardToast.setDividerColor(referenceHolder.mButtonDivider); superCardToast.setButtonTypefaceStyle(referenceHolder.mButtonTypefaceStyle); if(wrappers != null) { for (OnClickWrapper onClickWrapper : wrappers.getOnClickWrappers()) { if (onClickWrapper.getTag().equalsIgnoreCase(referenceHolder.mClickListenerTag)) { superCardToast.setOnClickWrapper(onClickWrapper, referenceHolder.mToken); } } } } else if (referenceHolder.mType == Type.PROGRESS) { /* PROGRESS style SuperCardToasts should be managed by the developer */ return; } else if (referenceHolder.mType == Type.PROGRESS_HORIZONTAL) { /* PROGRESS_HORIZONTAL style SuperCardToasts should be managed by the developer */ return; } else { superCardToast = new SuperCardToast(activity); } if (wrappers != null) { for (OnDismissWrapper onDismissListenerWrapper : wrappers.getOnDismissWrappers()) { if (onDismissListenerWrapper.getTag().equalsIgnoreCase(referenceHolder.mDismissListenerTag)) { superCardToast.setOnDismissWrapper(onDismissListenerWrapper); } } } superCardToast.setAnimations(referenceHolder.mAnimations); superCardToast.setText(referenceHolder.mText); superCardToast.setTypefaceStyle(referenceHolder.mTypefaceStyle); superCardToast.setDuration(referenceHolder.mDuration); superCardToast.setTextColor(referenceHolder.mTextColor); superCardToast.setTextSizeFloat(referenceHolder.mTextSize); superCardToast.setIndeterminate(referenceHolder.mIsIndeterminate); superCardToast.setIcon(referenceHolder.mIcon, referenceHolder.mIconPosition); superCardToast.setBackground(referenceHolder.mBackground); /* Must use if else statements here to prevent erratic behavior */ if (referenceHolder.mIsTouchDismissible) { superCardToast.setTouchToDismiss(true); } else if (referenceHolder.mIsSwipeDismissible) { superCardToast.setSwipeToDismiss(true); } superCardToast.setShowImmediate(true); superCardToast.show(); } /* This OnTouchListener handles the setTouchToDismiss() function */ private OnTouchListener mTouchDismissListener = new OnTouchListener() { int timesTouched; @Override public boolean onTouch(View view, MotionEvent motionEvent) { /* Hack to prevent repeat touch events causing erratic behavior */ if (timesTouched == 0) { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { dismiss(); } } timesTouched++; return false; } }; /* This OnClickListener handles the button click event */ private View.OnClickListener mButtonListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mOnClickWrapper != null) { mOnClickWrapper.onClick(view, mToken); } dismiss(); /* Make sure the button cannot be clicked multiple times */ mButton.setClickable(false); } }; /** * Parcelable class that saves all data on orientation change */ private static class ReferenceHolder implements Parcelable { Animations mAnimations; boolean mIsIndeterminate; boolean mIsTouchDismissible; boolean mIsSwipeDismissible; float mTextSize; float mButtonTextSize; IconPosition mIconPosition; int mDuration; int mTextColor; int mIcon; int mBackground; int mTypefaceStyle; int mButtonTextColor; int mButtonIcon; int mButtonDivider; int mButtonTypefaceStyle; Parcelable mToken; String mText; String mButtonText; String mClickListenerTag; String mDismissListenerTag; Type mType; public ReferenceHolder(SuperCardToast superCardToast) { mType = superCardToast.getType(); if (mType == Type.BUTTON) { mButtonText = superCardToast.getButtonText().toString(); mButtonTextSize = superCardToast.getButtonTextSize(); mButtonTextColor = superCardToast.getButtonTextColor(); mButtonIcon = superCardToast.getButtonIcon(); mButtonDivider = superCardToast.getDividerColor(); mClickListenerTag = superCardToast.getOnClickWrapperTag(); mButtonTypefaceStyle = superCardToast.getButtonTypefaceStyle(); mToken = superCardToast.getToken(); } if (superCardToast.getIconResource() != 0 && superCardToast.getIconPosition() != null) { mIcon = superCardToast.getIconResource(); mIconPosition = superCardToast.getIconPosition(); } mDismissListenerTag = superCardToast.getDismissListenerTag(); mAnimations = superCardToast.getAnimations(); mText = superCardToast.getText().toString(); mTypefaceStyle = superCardToast.getTypefaceStyle(); mDuration = superCardToast.getDuration(); mTextColor = superCardToast.getTextColor(); mTextSize = superCardToast.getTextSize(); mIsIndeterminate = superCardToast.isIndeterminate(); mBackground = superCardToast.getBackgroundResource(); mIsTouchDismissible = superCardToast.isTouchDismissible(); mIsSwipeDismissible = superCardToast.isSwipeDismissible(); } public ReferenceHolder(Parcel parcel) { mType = Type.values()[parcel.readInt()]; if (mType == Type.BUTTON) { mButtonText = parcel.readString(); mButtonTextSize = parcel.readFloat(); mButtonTextColor = parcel.readInt(); mButtonIcon = parcel.readInt(); mButtonDivider = parcel.readInt(); mButtonTypefaceStyle = parcel.readInt(); mClickListenerTag = parcel.readString(); mToken = parcel.readParcelable(((Object) this).getClass().getClassLoader()); } boolean hasIcon = parcel.readByte() != 0; if (hasIcon) { mIcon = parcel.readInt(); mIconPosition = IconPosition.values()[parcel.readInt()]; } mDismissListenerTag = parcel.readString(); mAnimations = Animations.values()[parcel.readInt()]; mText = parcel.readString(); mTypefaceStyle = parcel.readInt(); mDuration = parcel.readInt(); mTextColor = parcel.readInt(); mTextSize = parcel.readFloat(); mIsIndeterminate = parcel.readByte() != 0; mBackground = parcel.readInt(); mIsTouchDismissible = parcel.readByte() != 0; mIsSwipeDismissible = parcel.readByte() != 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(mType.ordinal()); if (mType == Type.BUTTON) { parcel.writeString(mButtonText); parcel.writeFloat(mButtonTextSize); parcel.writeInt(mButtonTextColor); parcel.writeInt(mButtonIcon); parcel.writeInt(mButtonDivider); parcel.writeInt(mButtonTypefaceStyle); parcel.writeString(mClickListenerTag); parcel.writeParcelable(mToken, 0); } if (mIcon != 0 && mIconPosition != null) { parcel.writeByte((byte) 1); parcel.writeInt(mIcon); parcel.writeInt(mIconPosition.ordinal()); } else { parcel.writeByte((byte) 0); } parcel.writeString(mDismissListenerTag); parcel.writeInt(mAnimations.ordinal()); parcel.writeString(mText); parcel.writeInt(mTypefaceStyle); parcel.writeInt(mDuration); parcel.writeInt(mTextColor); parcel.writeFloat(mTextSize); parcel.writeByte((byte) (mIsIndeterminate ? 1 : 0)); parcel.writeInt(mBackground); parcel.writeByte((byte) (mIsTouchDismissible ? 1 : 0)); parcel.writeByte((byte) (mIsSwipeDismissible ? 1 : 0)); } @Override public int describeContents() { return 0; } public static final Creator CREATOR = new Creator() { public ReferenceHolder createFromParcel(Parcel parcel) { return new ReferenceHolder(parcel); } public ReferenceHolder[] newArray(int size) { return new ReferenceHolder[size]; } }; } }
[ "yunlong782@126.com" ]
yunlong782@126.com
a56c1f9b997c6d8f69f90f09f7687c62be28b439
de25e6cca6f902b64afd2e37baa38a5098a8fae7
/filecoin/src/main/java/com/eth/filecoin/common/crypto/cryptohash/Digest.java
3eeca956ef4f6cbe58dd8923a50cd5cf4cb3e1cc
[]
no_license
stylehuan/wallet-filcoin
1c659318e2f06d2dc0d1531663661fe6e8f2f649
47a18e48016c9fa500d6b5bd03e06da94b1624cf
refs/heads/master
2023-06-28T17:12:57.638179
2021-08-02T02:09:37
2021-08-02T02:09:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,086
java
package com.eth.filecoin.common.crypto.cryptohash;/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ /** * Copyright (c) 2007-2010 Projet RNRT SAPHIR * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public interface Digest { /** * Insert one more input data byte. * * @param in the input byte */ void update(byte in); /** * Insert some more bytes. * * @param inbuf the data bytes */ void update(byte[] inbuf); /** * Insert some more bytes. * * @param inbuf the data buffer * @param off the data offset in {@code inbuf} * @param len the data length (in bytes) */ void update(byte[] inbuf, int off, int len); /** * Finalize the current hash computation and return the hash value in a newly-allocated array. The * object is resetted. * * @return the hash output */ byte[] digest(); /** * Input some bytes, then finalize the current hash computation and return the hash value in a * newly-allocated array. The object is resetted. * * @param inbuf the input data * @return the hash output */ byte[] digest(byte[] inbuf); /** * Finalize the current hash computation and store the hash value in the provided output buffer. * The {@code len} parameter contains the maximum number of bytes that should be written; no more * bytes than the natural hash function output length will be produced. If {@code len} is smaller * than the natural hash output length, the hash output is truncated to its first {@code len} * bytes. The object is resetted. * * @param outbuf the output buffer * @param off the output offset within {@code outbuf} * @param len the requested hash output length (in bytes) * @return the number of bytes actually written in {@code outbuf} */ int digest(byte[] outbuf, int off, int len); /** * Get the natural hash function output length (in bytes). * * @return the digest output length (in bytes) */ int getDigestLength(); /** * Reset the object: this makes it suitable for a new hash computation. The current computation, * if any, is discarded. */ void reset(); /** * Clone the current state. The returned object evolves independantly of this object. * * @return the clone */ Digest copy(); /** * <p>Return the "block length" for the hash function. This value is naturally defined for * iterated hash functions (Merkle-Damgard). It is used in HMAC (that's what the <a * href="http://tools.ietf.org/html/rfc2104">HMAC specification</a> names the "{@code B}" * parameter).</p> <p> <p>If the function is "block-less" then this function may return {@code -n} * where {@code n} is an integer such that the block length for HMAC ("{@code B}") will be * inferred from the key length, by selecting the smallest multiple of {@code n} which is no * smaller than the key length. For instance, for the Fugue-xxx hash functions, this function * returns -4: the virtual block length B is the HMAC key length, rounded up to the next multiple * of 4.</p> * * @return the internal block length (in bytes), or {@code -n} */ int getBlockLength(); /** * <p>Get the display name for this function (e.g. {@code "SHA-1"} for SHA-1).</p> * * @see Object */ @Override String toString(); }
[ "schooljavaian@gmail.com" ]
schooljavaian@gmail.com
6b59600ce12b5512ad5755ededa328be8f9a4b80
386e57be11a383303ab2aeff73db6779a2d17c55
/src/main/java/com/example/securingweb/model/ReportedUser.java
6aaeb6e38438275bd39bbdbd3eec310e8441d085
[]
no_license
RomanAuersvald/Reported
0af1a5d2de25246d81ce8c740692abb153a2fa5e
4843646dd671958179607cc10634f2ce4e8ec0ca
refs/heads/master
2023-04-25T10:17:31.925053
2021-05-06T12:50:00
2021-05-06T12:50:00
331,935,598
0
0
null
null
null
null
UTF-8
Java
false
false
3,883
java
package com.example.securingweb.model; import com.fasterxml.jackson.annotation.JsonIgnore; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.validation.annotation.Validated; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Transient; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; @Validated @Document(collection = "users") public class ReportedUser implements UserDetails { public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Id private String id; @NotEmpty(message="Name cannot be empty") private String firstName; @NotEmpty(message="Last name cannot be empty") private String lastName; @NotEmpty(message="username cannot be empty") private String username; @Size(min = 5, message = "Password must be at least 5 characters long") private String password; private String role; public String getBankAccount() { return bankAccount; } public void setBankAccount(String bankAccount) { this.bankAccount = bankAccount; } private String bankAccount; public ReportedUser() {} public ReportedUser(String username, String password, String role, String name, String surname){ this.username = username; this.password = password; this.role = role; this.firstName = name; this.lastName = surname; } @Override public String toString() { return String.format( "User[firstName='%s', lastName='%s', role='%s', username='%s']", firstName, lastName, role, username); } public String getNiceNameAndLastname(){ return String.format( "%s %s", firstName, lastName); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> authorities = new ArrayList<>(); getRoleList().forEach(p -> {GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + p); authorities.add(authority); }); return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public void setUsername(String username){ this.username = username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } @JsonIgnore public List<String> getRoleList(){ if(this.role.length() > 0) { return Arrays.asList(this.role.split(",")); } return new ArrayList<>(); } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
[ "roman.auersvald@ororo.cz" ]
roman.auersvald@ororo.cz
d90c98fe60ebab4da903d2f3c1affc17c651885e
51114303d9af09c887e3fbf90d91b01729ef7447
/src/main/AllMain.java
7c2a62bc914bbbadb6392d8580bc16cbb11e8a69
[]
no_license
jiaohu/MyFace
85f6807370c95a5520fd425de2ae7c47aa2e9d1d
6bf548cef8c4e4bd3de4bbb2b9e6186174088106
refs/heads/master
2021-01-19T11:58:16.330593
2017-05-17T03:25:09
2017-05-17T03:25:09
88,010,912
0
0
null
null
null
null
GB18030
Java
false
false
4,189
java
package main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import params.Img; import Jama.Matrix; import function.DetectFaceDemo; import function.Pca; import function.Pretreatment; public class AllMain { static Vector<double[]> model = new Vector<double[]>(); public static void main(String args[]) throws Exception { getModal(); double[][] md = (double[][]) model.toArray(new double[0][0]); int n1 = md.length; int p1 = md[0].length; for (int i = 0; i < n1; i++) { for (int j = 0; j < p1; j++) { System.out.print(md[i][j] + " "); } System.out.print("\n"); } System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Vector<double[]> modelOFace = new Vector<double[]>(); List<Img> imageurls = new ArrayList<Img>(); File file = new File("./data/ForTraining.txt"); Img imgfirst = null; int line = 1; BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String temp = null; String url = null; String id; while ((temp = reader.readLine()) != null) { String[] tokens = temp.split(" "); id = tokens[0]; Pretreatment pre = new Pretreatment(); url = "./ForTestImage/" + tokens[2]; Mat image = Imgcodecs.imread(url); if (image.empty()) continue; DetectFaceDemo face = new DetectFaceDemo(); face.detectface(url); Img img = pre.prepare(url, id); if (tokens[2].equals("AverageMaleFace.jpg")) { System.out.println("this is the first"); imgfirst = img; } modelOFace.add(img.getPiexl()); imageurls.add(img); line++; } // System.out.println(line); reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } double[][] faces = (double[][]) modelOFace.toArray(new double[0][0]); Matrix A = new Matrix(faces); Matrix B = new Matrix(md); Matrix C = A.times(B);// 投影矩阵 double[] ans = new double[faces.length]; double[][] D = C.getArray(); String console = "./modal.txt"; BufferedWriter cons = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(console, true))); for (int i = 0; i < D.length; i++) { for (int j = 0; j < D[0].length; j++) { cons.append(D[i][j] + " "); } cons.append("\n"); } cons.close(); int k = 0; String urls = "./data.txt"; BufferedWriter in = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(urls, true))); double temp = 0; double abs = 0; double max = 0; double cos = 0; for (int i = 0; i < D.length; i++) { for (int j = 0; j < D[0].length; j++) { ans[i] += (D[k][j] - D[i][j]) * (D[k][j] - D[i][j]); } ans[i] = Math.sqrt(ans[i]); temp = ans[i] % 20 - 10; cos = 1 / (1 + Math.pow(Math.E, temp)); // compareFace cpFace = new compareFace(); // cos = cpFace.compare(cpFace.getData(imageurls.get(k).getPath()), // cpFace.getData(imageurls.get(i).getPath())); System.out.println("距离" + ans[i] + "相似度" + cos + "为第" + i + "张人脸" + "路由" + imageurls.get(i).getPath()); String contain = "距离" + ans[i] + "相似度" + cos + "路由" + "src" + imageurls.get(k).getPath() + "tar" + imageurls.get(i).getPath(); in.write(contain + "\n"); } in.close(); } private static void getModal() throws IOException { // TODO Auto-generated method stub File file = new File("./YaleModal.txt"); BufferedReader reader = new BufferedReader(new FileReader(file)); String temp = null; int k = 0; while ((temp = reader.readLine()) != null) { String[] tokens = temp.split(" "); double[] ans = new double[tokens.length]; for (int i = 0; i < tokens.length; i++) { ans[i] = Double.parseDouble(tokens[i]); } model.add(ans); k++; } } }
[ "1175474595@qq.com" ]
1175474595@qq.com
6d1547884d3ad1372158c4d36c08020f3d58dd39
363cd89e5112d98b4055e22cf6e3e40c66757370
/app/src/main/java/com/example/myweather/bo/Main.java
54bdd833552aef6b625a2de86398dd4848c2b3de
[]
no_license
PierreAmbeza/MyWeatherApp
1f897a7871ac072106542d85dd095cf46d81c34e
927a202aa78c54f384559147127086170e5d9a75
refs/heads/master
2023-01-12T16:55:32.955808
2020-11-16T17:17:45
2020-11-16T17:17:45
311,942,125
0
0
null
null
null
null
UTF-8
Java
false
false
1,109
java
package com.example.myweather.bo; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.squareup.moshi.Json; import retrofit2.http.Field; //Class corresponding to the "main" field provide by the api, with all temperatures public class Main { @Json(name = "temp") private Double temp; @Json(name = "feels_like") private Double feelsLike; @Json(name = "temp_min") private Double tempMin; @Json(name = "temp_max") private Double tempMax; public Double getTemp() { return temp; } public void setTemp(Double temp) { this.temp = temp; } public Double getFeelsLike() { return feelsLike; } public void setFeelsLike(Double feelsLike) { this.feelsLike = feelsLike; } public Double getTempMin() { return tempMin; } public void setTempMin(Double tempMin) { this.tempMin = tempMin; } public Double getTempMax() { return tempMax; } public void setTempMax(Double tempMax) { this.tempMax = tempMax; } }
[ "pierre.ambeza@efrei.net" ]
pierre.ambeza@efrei.net
f85178016d22c5e217b20c8287065c7dd9cb0f9e
1c5fd654b46d3fb018032dc11aa17552b64b191c
/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java
6e59d740f24ab58f43bc056d11cd4fee2bbf5fb8
[ "Apache-2.0" ]
permissive
yangfancoming/spring-boot-build
6ce9b97b105e401a4016ae4b75964ef93beeb9f1
3d4b8cbb8fea3e68617490609a68ded8f034bc67
refs/heads/master
2023-01-07T11:10:28.181679
2021-06-21T11:46:46
2021-06-21T11:46:46
193,871,877
0
0
Apache-2.0
2022-12-27T14:52:46
2019-06-26T09:19:40
Java
UTF-8
Java
false
false
780
java
package org.springframework.boot.ansi; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.boot.ansi.AnsiOutput.Enabled; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AnsiOutput}. * * @author Phillip Webb */ public class AnsiOutputTests { @BeforeClass public static void enable() { AnsiOutput.setEnabled(Enabled.ALWAYS); } @AfterClass public static void reset() { AnsiOutput.setEnabled(Enabled.DETECT); } @Test public void encoding() { String encoded = AnsiOutput.toString("A", AnsiColor.RED, AnsiStyle.BOLD, "B", AnsiStyle.NORMAL, "D", AnsiColor.GREEN, "E", AnsiStyle.FAINT, "F"); assertThat(encoded).isEqualTo("ABDEF"); } }
[ "34465021+jwfl724168@users.noreply.github.com" ]
34465021+jwfl724168@users.noreply.github.com
9a6fbdc970eca362c53b53171c3e9d32ef9f240d
ebcb8e1955e3f1a933bebb95c3e89ee5d1e15a2e
/src/main/java/com/coxautoinc/sfdc/newdealerrequest/NewDealerRequestSelector.java
3259cddbd8abf4a96e190cc5e8c443d364da6350
[]
no_license
reachshyam80/teelstng
03c263a06f27b9192c9561bb1f6e50ebb6263eb6
e2b7964b4fa85b3315fd91433d025d7696adfdc1
refs/heads/master
2021-04-27T19:38:34.885144
2018-02-21T16:49:16
2018-02-21T16:49:16
122,359,838
0
0
null
null
null
null
UTF-8
Java
false
false
2,842
java
package com.coxautoinc.sfdc.newdealerrequest; import org.openqa.selenium.By; public class NewDealerRequestSelector { private By newDlrReqLink; private By selectUrgReq; private By checkSubmit; private By selectOwnershipChange; private By accntName; private By selDealerGrp; private By dealerGrpAccnt; private By dealerType; private By namePlate; private By addNamePlateBtn; private By custWebsiteUrl; private By custType; private By lotSizeNew; private By lotSizeUsed; private By physLocPhone; private By physLocStreet1; private By physLocCity; private By selectphysLocState; private By physLocZip; private By selectPhysAddSameAsBilling; NewDealerRequestSelector(){ init(); } public By getNewDlrReqLink() { return newDlrReqLink; } public By getSelectUrgReq() { return selectUrgReq; } public By getCheckSubmit() { return checkSubmit; } public By getSelectOwnershipChange() { return selectOwnershipChange; } public By getAccntName() { return accntName; } public By getSelDealerGrp() { return selDealerGrp; } public By getDealerGrpAccnt() { return dealerGrpAccnt; } public By getDealerType() { return dealerType; } public By getNamePlate() { return namePlate; } public By getAddNamePlateBtn() { return addNamePlateBtn; } public By getCustWebsiteUrl() { return custWebsiteUrl; } public By getCustType() { return custType; } public By getLotSizeNew() { return lotSizeNew; } public By getLotSizeUsed() { return lotSizeUsed; } public By getPhysLocPhone() { return physLocPhone; } public By getPhysLocStreet1() { return physLocStreet1; } public By getPhysLocCity() { return physLocCity; } public By getSelectphysLocState() { return selectphysLocState; } public By getPhysLocZip() { return physLocZip; } public By getSelectPhysAddSameAsBilling() { return selectPhysAddSameAsBilling; } private void init(){ newDlrReqLink = By.linkText("New Dealer Request"); selectUrgReq = By.id("00Nj000000C1bRV"); checkSubmit = By.id("00Nj000000C14Ox"); selectOwnershipChange = By.id("00Nj000000C1bRK"); accntName = By.id("00Nj000000C14OY"); selDealerGrp = By.id("00Nj000000C1bRJ"); dealerGrpAccnt = By.id("CF00Nj000000C14Ty"); dealerType = By.id("00Nj000000C1bRI"); namePlate = By.id("00Nj000000C1bRN_unselected"); addNamePlateBtn = By.xpath("//a[@title = 'Add']"); custWebsiteUrl = By.id("00Nj000000C1bRH"); custType = By.id("00Nj000000C1bRG"); lotSizeNew = By.id("00Nj000000C1bRL"); lotSizeUsed = By.id("00Nj000000C1bRM"); physLocPhone = By.id("00Nj000000C1bRP"); physLocStreet1 = By.id("00Nj000000C1bRS"); physLocCity = By.id("00Nj000000C1bRO"); selectphysLocState = By.id("00Nj000000C1bRR"); physLocZip = By.id("00Nj000000C1bRQ"); selectPhysAddSameAsBilling = By.id("00Nj000000C1bR8"); } }
[ "asreekanta@cai-c02sg3srfvh6lt.na.autotrader.int" ]
asreekanta@cai-c02sg3srfvh6lt.na.autotrader.int
f3f1f89d73fb8ba1e933e6a54f625fc98eb64b20
249d43c9f1d99104921a7e9590133fd14c2b2269
/src/main/java/io/ebean/MergeOptionsBuilder.java
c17b2d88daebfd89e2d56ce3f2f1e51fdb3d3bfa
[ "Apache-2.0" ]
permissive
kevinobama/ebeanTesting
a7c42109a3a879ee7041aa5d1341bacdf273aad2
0aff81116e72abf7b4888c6dd516b1ee1b345f7f
refs/heads/master
2020-03-19T13:40:44.125150
2018-06-08T08:28:22
2018-06-08T08:28:22
136,590,085
0
0
null
null
null
null
UTF-8
Java
false
false
1,994
java
package io.ebean; import java.util.LinkedHashSet; import java.util.Set; /** * Builds a MergeOptions which is immutable and thread safe. */ public class MergeOptionsBuilder { private Set<String> paths = new LinkedHashSet<>(); private boolean clientGeneratedIds; private boolean deletePermanent = true; /** * Add a path that will included in the merge. * * @param path The path relative to the root type. * @return The builder to chain another addPath() or build(). */ public MergeOptionsBuilder addPath(String path) { paths.add(path); return this; } /** * Set to true if Id values are supplied by the client. * <p> * This would be the case when for example a mobile creates data in it's own local database * and then sync's. In this case often the id values are UUID. */ public MergeOptionsBuilder setClientGeneratedIds() { this.clientGeneratedIds = true; return this; } /** * Set that deletions should use delete permanent (rather than default which allows soft deletes). */ public MergeOptionsBuilder setDeletePermanent() { this.deletePermanent = true; return this; } /** * Build and return the MergeOptions instance. */ public MOptions build() { return new MOptions(paths, clientGeneratedIds, deletePermanent); } private static class MOptions implements MergeOptions { private final boolean clientGeneratedIds; private final boolean deletePermanent; private final Set<String> paths; private MOptions(Set<String> paths, boolean clientGeneratedIds, boolean deletePermanent) { this.paths = paths; this.clientGeneratedIds = clientGeneratedIds; this.deletePermanent = deletePermanent; } public Set<String> paths() { return paths; } @Override public boolean isClientGeneratedIds() { return clientGeneratedIds; } @Override public boolean isDeletePermanent() { return deletePermanent; } } }
[ "kevinobamatheus@gmail.com" ]
kevinobamatheus@gmail.com
664f899f5c293f22fa2ac3b6b23099c94c568162
14a6c22c533cb910b9895af954205fb0348f37d6
/app/src/main/java/com/pmfis/cinemaapp/retrofit/APIInterface.java
fd03547f2b5bf0795bc1672b076d92cb68d9cc95
[]
no_license
nemanjagajic/CinemaAppAndroid
0218d6608bb70855786e933d08d11b5fd61aa6c7
8190bbabea3ee3b3087a7cd6c73486509886671b
refs/heads/master
2021-09-05T02:43:09.167222
2018-01-23T18:23:11
2018-01-23T18:23:11
118,644,512
0
0
null
null
null
null
UTF-8
Java
false
false
2,039
java
package com.pmfis.cinemaapp.retrofit; import com.pmfis.cinemaapp.retrofit.pojo.MovieRequest; import com.pmfis.cinemaapp.retrofit.pojo.MovieResponse; import com.pmfis.cinemaapp.retrofit.pojo.PersonRequest; import com.pmfis.cinemaapp.retrofit.pojo.PersonResponse; import com.pmfis.cinemaapp.retrofit.pojo.ReservationRequest; import com.pmfis.cinemaapp.retrofit.pojo.ReservationResponse; import java.util.List; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; public interface APIInterface { // Movie @GET("/movie/getAll") Call<List<MovieResponse>> getAllMovies(); @GET("/movie/getMovie/{id}") Call<MovieResponse> getMovieById(@Path("id") int id); @POST("/movie/add") Call<MovieResponse> addMovie(@Body MovieRequest movieToAdd); @DELETE("/movie/delete/{id}") Call<MovieResponse> deleteMovie(@Path("id") int id); // Person @GET("/person/getAll") Call<List<PersonResponse>> getAllPersons(); @GET("/person/get/{id}") Call<PersonResponse> getPersonById(@Path("id") int id); @GET("/person/getUser/{username}") Call<PersonResponse> getPersonByUsername(@Path("username") String username); @POST("/person/add") Call<PersonResponse> addPerson(@Body PersonRequest personToAdd); @DELETE("/person/delete/{id}") Call<PersonResponse> deletePerson(@Path("id") int id); // Reservation @GET("movie/reservation/getMovies/{id}") Call<List<MovieResponse>> getMoviesForPerson(@Path("id") int id); @POST("/movie/reservation/add") Call<ReservationResponse> makeReservation(@Body ReservationRequest reservationRequest); @GET("movie/reservation/getPersons/{movieId}") Call<List<PersonResponse>> getPersonsWhoReservedMovie(@Path("movieId") int movieId); @DELETE("movie/reservation/delete/{idMovie}/{idPerson}") Call<ReservationResponse> deleteReservation(@Path("idMovie") int idMovie, @Path("idPerson") int idPerson); }
[ "Nemanja.gajicru96@gmail.com" ]
Nemanja.gajicru96@gmail.com
835e97011c6821dd76bb34f12b4bddb61c9b08fc
8b5ab5803d2d19e75d0539fc0e2cde5b1a09ac5f
/src/main/java/ua/daleondeveloper/sao_site/exception/NoAccess.java
49bfb75bc526bc2b6993b55d5c3d99c351a8fdd7
[]
no_license
daleondeveloper/anime_sao_site
2fabe7929da0aa569db4c39f2a3785d6fb0fbaea
6bfc07b9e8234ba3df2bc4ba2673c0182979605d
refs/heads/master
2022-06-02T01:05:14.877971
2020-08-20T18:54:01
2020-08-20T18:54:01
237,059,994
0
0
null
2020-07-10T18:52:34
2020-01-29T19:03:47
HTML
UTF-8
Java
false
false
258
java
package ua.daleondeveloper.sao_site.exception; public class NoAccess extends RuntimeException { public NoAccess(String message){ super(message); } public NoAccess(String message, Throwable cause){ super(message,cause); } }
[ "daleonandra0206@ukr.net" ]
daleonandra0206@ukr.net
36ed478c9f769d4443c5f52a72f5363f834a249d
a0f20c4cf3b03863b1d10fa49c1156317c953e0d
/Lab1/ColorModelPanel.java
9681c87cbe8cee5c0c0ec325f4c58737b88b609f
[]
no_license
CG2017/Yakovtseva14
117c6ced10d7f476a6d1d3b7bf9ed33cc06655ad
d540fd57de07802766f15eae4c326b94bf1ece8c
refs/heads/master
2020-05-27T14:30:22.398611
2017-05-15T21:32:50
2017-05-15T21:32:50
82,559,874
0
0
null
null
null
null
UTF-8
Java
false
false
3,906
java
import javax.swing.*; import java.awt.*; abstract class ColorModelPanel extends JPanel { JSlider slider1; JSlider slider2; JSlider slider3; boolean notifyListener; JLabel icon1; JLabel icon2; JLabel icon3; private JSpinner spinner1; private JSpinner spinner2; private JSpinner spinner3; ColorModelPanel(ColorModelListener listener, int min1, int max1, int min2, int max2, int min3, int max3, String[] name) { Dimension size = new Dimension(500, 200); setSize(size); setMaximumSize(size); setMinimumSize(size); JLabel label0 = new JLabel(String.format("%s model", String.join("", (CharSequence[]) name))); JLabel label1 = new JLabel(name[0]); JLabel label2 = new JLabel(name[1]); JLabel label3 = new JLabel(name[2]); spinner1 = new JSpinner(new SpinnerNumberModel(min1, min1, max1, 1)); spinner2 = new JSpinner(new SpinnerNumberModel(min2, min2, max2, 1)); spinner3 = new JSpinner(new SpinnerNumberModel(min3, min3, max3, 1)); slider1 = new JSlider(min1, max1, min1); slider2 = new JSlider(min3, max2, min2); slider3 = new JSlider(min3, max2, min3); icon1 = new JLabel(UIManager.getIcon("OptionPane.warningIcon")); icon2 = new JLabel(UIManager.getIcon("OptionPane.warningIcon")); icon3 = new JLabel(UIManager.getIcon("OptionPane.warningIcon")); icon1.setEnabled(false); icon2.setEnabled(false); icon3.setEnabled(false); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(label0); JPanel foo = new JPanel(); foo.setOpaque(false); foo.add(label1); foo.add(spinner1); foo.add(slider1); foo.add(icon1); add(foo); JPanel bar = new JPanel(); bar.setOpaque(false); bar.add(label2); bar.add(spinner2); bar.add(slider2); bar.add(icon2); add(bar); JPanel lala = new JPanel(); lala.setOpaque(false); lala.add(label3); lala.add(spinner3); lala.add(slider3); lala.add(icon3); add(lala); spinner1.addChangeListener(e -> { slider1.setValue((Integer) spinner1.getValue()); if (notifyListener) { listener.colorChanged(getRGB(), this); } }); spinner2.addChangeListener(e -> { slider2.setValue((Integer) spinner2.getValue()); if (notifyListener) { listener.colorChanged(getRGB(), this); } }); spinner3.addChangeListener(e -> { slider3.setValue((Integer) spinner3.getValue()); if (notifyListener) { listener.colorChanged(getRGB(), this); } }); slider1.addChangeListener(e -> { spinner1.setValue(slider1.getValue()); if (notifyListener) { listener.colorChanged(getRGB(), this); } }); slider2.addChangeListener(e -> { spinner2.setValue(slider2.getValue()); if (notifyListener) { listener.colorChanged(getRGB(), this); } }); slider3.addChangeListener(e -> { spinner3.setValue(slider3.getValue()); if (notifyListener) { listener.colorChanged(getRGB(), this); } }); setOpaque(false); notifyListener = true; } ColorModelPanel(ColorModelListener listener, int min, int max, String[] name) { this(listener, min, max, min, max, min, max, name); } void disableIcons(){ icon1.setEnabled(false); icon2.setEnabled(false); icon3.setEnabled(false); } abstract double[] getRGB(); abstract void setColorFromRGB(double[] RGB); }
[ "sashayakovtseva@gmail.com" ]
sashayakovtseva@gmail.com
4d9e47ed8646f35418b6fb965b5211decbaa8aaa
1efb57c74ad9b65b65dec1693cd4d51bf53947c0
/src/main/java/com/kcribs/Configuration/JwtAuthenticationFilter.java
0ca42942bd6143d7a7d6344fa067df9ffa159378
[]
no_license
Treasureworth/worksplugRepo
2217d9d6c4e05acbfa9c3b3ff1d443d604299c4c
f3eaf87682a38d22740e5f5a5b87b8d09c17df04
refs/heads/master
2020-05-07T21:13:45.704535
2019-04-12T00:06:36
2019-04-12T00:06:36
180,896,363
0
0
null
null
null
null
UTF-8
Java
false
false
3,115
java
package com.kcribs.Configuration; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.SignatureException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static com.kcribs.Constants.Constants.HEADER_STRING; import static com.kcribs.Constants.Constants.TOKEN_PREFIX; public class JwtAuthenticationFilter extends OncePerRequestFilter { @Autowired private UserDetailsService userDetailsService; @Autowired private TokenProvider jwtTokenUtil; @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { String header = req.getHeader(HEADER_STRING); String username = null; String authToken = null; if (header != null && header.startsWith(TOKEN_PREFIX)) { authToken = header.replace(TOKEN_PREFIX,""); try { username = jwtTokenUtil.getUsernameFromToken(authToken); } catch (IllegalArgumentException e) { logger.error("an error occured during getting username from token", e); } catch (ExpiredJwtException e) { logger.warn("the token is expired and not valid anymore", e); } catch(SignatureException e){ logger.error("Authentication Failed. Username or Password not valid."); } } else { logger.warn("couldn't find bearer string, will ignore the header"); } if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (jwtTokenUtil.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = jwtTokenUtil.getAuthentication(authToken, SecurityContextHolder.getContext().getAuthentication(), userDetails); //UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"))); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req)); logger.info("authenticated user " + username + ", setting security context"); SecurityContextHolder.getContext().setAuthentication(authentication); } } chain.doFilter(req, res); } }
[ "odunayooni@Odunayos-MacBook-Pro.local" ]
odunayooni@Odunayos-MacBook-Pro.local
4b1c10b360802da375a9d0cae7aeb454843a5da0
e61338ad27b44250cc6570c6347c4b4faae6162c
/app/src/main/java/at/stefanirndorfer/bakingapp/view/RecipeDetailFragment.java
41180a488d793c9701c24f3168d14379f8f09fed
[]
no_license
silentLOL/Baking-App
02130f8ef0d48d20d1c1b8b42fd64b7aa6a66f88
0310e547a07f145a26e1c374db22156222baeec9
refs/heads/master
2020-03-31T06:30:36.837980
2018-11-10T20:35:30
2018-11-10T20:35:30
151,985,513
0
0
null
null
null
null
UTF-8
Java
false
false
3,876
java
package at.stefanirndorfer.bakingapp.view; import android.arch.lifecycle.ViewModelProviders; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.Objects; import at.stefanirndorfer.bakingapp.R; import at.stefanirndorfer.bakingapp.adapter.StepsRecyclerViewAdapter; import at.stefanirndorfer.bakingapp.databinding.FragmentRecipeDetailBinding; import at.stefanirndorfer.bakingapp.view.input.StepItemUserActionListener; import at.stefanirndorfer.bakingapp.viewmodel.StepsViewModel; import at.stefanirndorfer.bakingapp.viewmodel.ViewModelFactory; import timber.log.Timber; /** * provides a button to view the ingredients and a list of the steps below */ public class RecipeDetailFragment extends Fragment { private int mRecipeId; FragmentRecipeDetailBinding mFragmentBinding; private StepsViewModel mViewModel; private StepItemUserActionListener mListener; private RecyclerView mRecyclerViewSteps; private LinearLayoutManager mLinearLayoutManagerSteps; private StepsRecyclerViewAdapter mStepsRecyclerViewAdapter; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mFragmentBinding = FragmentRecipeDetailBinding.inflate(inflater, container, false); // createViewModel mViewModel = obtainViewModel(Objects.requireNonNull(this.getActivity())); mFragmentBinding.setViewModel(mViewModel); Bundle extras = getActivity().getIntent().getExtras(); int recipeId = (int) extras.get(DetailActivity.RECIPE_ID_EXTRA); mViewModel.start(recipeId); // hide ingredients button on tablets if (getResources().getBoolean(R.bool.isTablet)){ mFragmentBinding.ingredientsBt.setVisibility(View.GONE); } return mFragmentBinding.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setupStepRecyclerViewAdapter(); } private void setupStepRecyclerViewAdapter() { Timber.d( "Setting up RecyclerView"); mRecyclerViewSteps = mFragmentBinding.recyclerViewStepsRv; mLinearLayoutManagerSteps = new LinearLayoutManager(this.getActivity()); mRecyclerViewSteps.setLayoutManager(mLinearLayoutManagerSteps); mRecyclerViewSteps.setHasFixedSize(true); mStepsRecyclerViewAdapter = new StepsRecyclerViewAdapter(mViewModel, mListener, this.getActivity().getApplication()); mRecyclerViewSteps.setAdapter(mStepsRecyclerViewAdapter); } @Override public void onAttach(Context context) { super.onAttach(context); try { mListener = (StepItemUserActionListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " must implement StepItemUserActionListener"); } } @Override public void onDestroyView() { super.onDestroyView(); mViewModel.getSteps().removeObservers(this); } public static StepsViewModel obtainViewModel(FragmentActivity activity) { // Use a Factory to inject dependencies into the ViewModel ViewModelFactory factory = ViewModelFactory.getInstance(activity.getApplication()); StepsViewModel viewModel = ViewModelProviders.of(activity, factory).get(StepsViewModel.class); return viewModel; } }
[ "stefan.irndorfer@gmail.com" ]
stefan.irndorfer@gmail.com
95ced5db43579075147f6bcbc62d24927b7f2a4f
7d7c531ea7eabe25819e586cfffd9fbde4a615fc
/app/src/main/java/com/xht/meizhi/bean/MeizhiWithVideoInfo.java
34086ca370301fa57778f084223544a9fd1dcc53
[]
no_license
xhthh/MeizhiGank
b690201f8626ce1b74a4d7752ef2774394f0694e
dbe21fe528c8fc7f4f84c28368f8fb86b183e624
refs/heads/master
2021-01-22T02:39:15.555761
2017-11-02T08:14:57
2017-11-02T08:14:57
81,061,386
3
0
null
null
null
null
UTF-8
Java
false
false
876
java
package com.xht.meizhi.bean; /** * Created by xht on 2016/11/3 10:34. */ public class MeizhiWithVideoInfo { private String desc; private String publishedAt; private String url; @Override public String toString() { return "MeizhiWithVideoInfo{" + "desc='" + desc + '\'' + ", publishedAt='" + publishedAt + '\'' + ", url='" + url + '\'' + '}'; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getPublishedAt() { return publishedAt; } public void setPublishedAt(String publishedAt) { this.publishedAt = publishedAt; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
[ "1399535513@qq.com" ]
1399535513@qq.com
840ce9465b4098ddc4e59e8945e44a29d00d96d3
2415850be1a65a5f546c0e4ad0a30913a5547b03
/java/com/android/dialer/voicemail/settings/RecordVoicemailGreetingActivity.java
89e45dca7f67db1bc53c2eb0edc9eb9f48764151
[ "Apache-2.0" ]
permissive
LineageOS/android_packages_apps_Dialer
fb5a262b9dc983bb665a968e6a6e8bca3a4d1420
3ff6f1dfe79ceff169131c7203f8394f0f973c0f
refs/heads/lineage-18.1
2023-09-01T13:18:46.937045
2023-08-01T18:25:41
2023-08-01T18:25:41
75,641,878
48
339
NOASSERTION
2021-04-24T19:04:15
2016-12-05T15:59:32
Java
UTF-8
Java
false
false
3,823
java
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.dialer.voicemail.settings; import android.app.Activity; import android.os.Bundle; import android.support.annotation.IntDef; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** Activity for recording a new voicemail greeting */ public class RecordVoicemailGreetingActivity extends Activity implements OnClickListener { /** Possible states of RecordButton and RecordVoicemailGreetingActivity */ @Retention(RetentionPolicy.SOURCE) @IntDef({ RECORD_GREETING_INIT, RECORD_GREETING_RECORDING, RECORD_GREETING_RECORDED, RECORD_GREETING_PLAYING_BACK }) public @interface ButtonState {} public static final int RECORD_GREETING_INIT = 1; public static final int RECORD_GREETING_RECORDING = 2; public static final int RECORD_GREETING_RECORDED = 3; public static final int RECORD_GREETING_PLAYING_BACK = 4; public static final int MAX_GREETING_DURATION_MS = 45000; private int currentState; private int duration; private RecordButton recordButton; private Button saveButton; private Button redoButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_record_voicemail_greeting); recordButton = findViewById(R.id.record_button); saveButton = findViewById(R.id.save_button); redoButton = findViewById(R.id.redo_button); duration = 0; setState(RECORD_GREETING_INIT); recordButton.setOnClickListener(this); } @Override public void onClick(View v) { if (v == recordButton) { switch (currentState) { case RECORD_GREETING_INIT: setState(RECORD_GREETING_RECORDING); break; case RECORD_GREETING_RECORDED: setState(RECORD_GREETING_PLAYING_BACK); break; case RECORD_GREETING_RECORDING: case RECORD_GREETING_PLAYING_BACK: setState(RECORD_GREETING_RECORDED); break; default: break; } } } private void setState(@ButtonState int state) { currentState = state; switch (state) { case RECORD_GREETING_INIT: recordButton.setState(state); recordButton.setTracks(0, 0); setSaveRedoButtonsEnabled(false); break; case RECORD_GREETING_PLAYING_BACK: case RECORD_GREETING_RECORDED: recordButton.setState(state); recordButton.setTracks(0, (float) duration / MAX_GREETING_DURATION_MS); setSaveRedoButtonsEnabled(true); break; case RECORD_GREETING_RECORDING: recordButton.setState(state); recordButton.setTracks(0, 1f); setSaveRedoButtonsEnabled(false); break; default: break; } } /** Enables/Disables save and redo buttons in the layout */ private void setSaveRedoButtonsEnabled(boolean enabled) { if (enabled) { saveButton.setVisibility(View.VISIBLE); redoButton.setVisibility(View.VISIBLE); } else { saveButton.setVisibility(View.GONE); redoButton.setVisibility(View.GONE); } } }
[ "copybara-piper@google.com" ]
copybara-piper@google.com
9ef7bf68b06e24bf8b4af7bf1f6113ea82eda377
b9f368cfac08576f6ec7ea6cacd74948b9aa27fd
/src/view/action/newactions/NewFSAAction.java
0829bf565dbe904cc5731a72a84b49d0a2a0feec
[]
no_license
karma-biatch/JFLAP_v8.0
5223e1c8eb2875af880b7cbdc21020863806bc29
074fe13b3c24439bd50bddd5b081629b7db583b7
refs/heads/master
2021-05-28T04:30:54.137017
2014-07-25T19:54:02
2014-07-25T19:54:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
394
java
package view.action.newactions; import model.automata.acceptors.fsa.FiniteStateAcceptor; public class NewFSAAction extends NewFormalDefinitionAction<FiniteStateAcceptor>{ public NewFSAAction() { super("Finite Automaton"); // TODO Auto-generated constructor stub } @Override public FiniteStateAcceptor createDefinition() { return new FiniteStateAcceptor(); } }
[ "justlah@gmail.com" ]
justlah@gmail.com
cc4fb09ba1ef91b3489eb2aacb2cd32fb09d4688
d454b3c2b4b34171fc69275e53d8058da4aee20b
/Chain.java
04ee169286607fcb635e888fac63e9c915db9df1
[]
no_license
AlAmincseru/java-lab-chain-repo-of-design-pattern
d7853f381609d42dfcdd59a63f1e0c1b72da26a6
3a1fa2c4a54b88770239e3c8a18e53a8466460b7
refs/heads/master
2020-04-05T17:38:26.207114
2018-11-11T10:55:14
2018-11-11T10:55:14
157,069,567
0
0
null
null
null
null
UTF-8
Java
false
false
134
java
package chapter09; public interface Chain { public void setNextChain(Chain NextChain); public void calculate(Numbers requests); }
[ "alamin54648@gmail.com" ]
alamin54648@gmail.com
44eca3c6b59890d64d1a29844dea0d6dce4d5267
2b5a246535f88505968ff7d219472656f9f08cb6
/app/src/main/java/com/androidmodule/lastfm/ui/main/viewmodel/MainViewModel.java
7ba36a56ff6a82298f44c51ca3637fb5708101d3
[]
no_license
namratavip/LastFM
15f3646b00721a9cae3ad64142d0652e8bf74727
741ce9024abf944707c3d90ccf1d7d544549ad84
refs/heads/master
2022-12-02T03:45:25.007328
2020-08-18T10:33:28
2020-08-18T10:33:28
287,802,365
0
0
null
null
null
null
UTF-8
Java
false
false
2,375
java
package com.androidmodule.lastfm.ui.main.viewmodel; import android.util.Log; import com.androidmodule.lastfm.data.api.ApiHelper; import com.androidmodule.lastfm.data.model.Album; import com.androidmodule.lastfm.data.model.Response; import com.androidmodule.lastfm.util.Constant; import com.androidmodule.lastfm.util.Resource; import java.util.List; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.observers.DisposableObserver; import io.reactivex.schedulers.Schedulers; public class MainViewModel extends ViewModel { private ApiHelper apiHelper; private MutableLiveData<Resource<List<Album>>> albumList; private CompositeDisposable compositeDisposable; public MainViewModel(ApiHelper apiHelper) { this.apiHelper = apiHelper; albumList = new MutableLiveData<>(); compositeDisposable = new CompositeDisposable(); } public void searchKey(String key) { searchAlbum(key); } private void searchAlbum(String searchKey) { albumList.postValue(Resource.loading(null)); compositeDisposable.add(apiHelper.getResponse(searchKey,Constant.API_KEY,"json") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(getObserver())); } private DisposableObserver<Response> getObserver() { return new DisposableObserver<Response>() { @Override public void onNext(Response response) { Log.d("albumSize",""+response.getResults().getAlbumMatches().getAlbum().size()); albumList.postValue(Resource.success(response.getResults().getAlbumMatches().getAlbum())); } @Override public void onError(Throwable e) { Log.d("Error*",""+e.getMessage()); albumList.postValue(Resource.error(e.toString(), null)); } @Override public void onComplete() { } }; } @Override protected void onCleared() { super.onCleared(); compositeDisposable.clear(); } public MutableLiveData<Resource<List<Album>>> getAlbums() { return albumList; } }
[ "nikitavipulwar@gmail.com" ]
nikitavipulwar@gmail.com
f4e3fafd8a0617e9c54b2880c83e57ebc44b3029
6ad72af6450dbffdbf1d7555efbdee8610ccefb9
/wgProject01/src/wgProject01/ingameState/view/package-info.java
3066beeb5bf040ce58a51e9cf9fc107d2281c0ee
[]
no_license
Waog/minecraft-clone
2f2c096380502b778cc667b867edb30041d07540
b6ccd12e83ab02aacbdbc4f9cb255eb6e301ec3b
refs/heads/master
2020-12-31T04:42:26.055377
2016-05-02T14:42:46
2016-05-02T14:42:46
57,894,874
0
0
null
null
null
null
UTF-8
Java
false
false
118
java
/** * Contains the classes connecting the model and the nifty GUI view. */ package wgProject01.ingameState.view;
[ "oliver.stadie@gmail.com" ]
oliver.stadie@gmail.com
189fdd7808cf62593c1315ba7ca63cf3b1762b19
6b338e41da75a6c9a7144b0d3c022afd5e702343
/app/src/main/java/com/example/saimo/insight/Grevideolectures.java
bd2fd91d7876c52b4bbfac75279d7bf0456d564a
[]
no_license
vamsiatom/Insight
318b8eb8e752ce36647ca39d128d0967ddfc819f
5a2f5243d1acb1944367e86f02237476631f3266
refs/heads/master
2021-01-10T02:04:07.978947
2016-01-03T06:09:31
2016-01-03T06:09:31
48,936,129
0
0
null
null
null
null
UTF-8
Java
false
false
354
java
package com.example.saimo.insight; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class Grevideolectures extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grevideolectures); } }
[ "sai mohana vamsi krishna MADDI" ]
sai mohana vamsi krishna MADDI
f0f9193bf1287045c5d4b396e8a645e698d82750
2a040f5cb47915a58ff47e3a95fbb8e53ce09b5a
/app/src/main/java/com/farm/ui/Fragment_CommandDetail.java
61b53917a02cf8488bf7e402589d92b16353677e
[]
no_license
githubwithme/farm
7ad23f520f289de716c76baa93e9b6f8427da5ce
34827ce4eb2db66c5057c384cc79344d91c85710
refs/heads/master
2020-12-12T13:56:05.409508
2016-02-26T08:03:37
2016-02-26T08:03:37
48,423,210
0
0
null
null
null
null
UTF-8
Java
false
false
5,166
java
package com.farm.ui; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.alibaba.fastjson.JSON; import com.farm.R; import com.farm.adapter.Command_ExecuteArea_Adapter; import com.farm.app.AppConfig; import com.farm.app.AppContext; import com.farm.bean.Result; import com.farm.bean.commandtab; import com.farm.bean.commembertab; import com.farm.common.utils; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.RequestParams; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.ViewById; import java.util.ArrayList; import java.util.List; /** * Created by ${hmj} on 2016/1/20. */ @EFragment public class Fragment_CommandDetail extends Fragment { Command_ExecuteArea_Adapter listAdapter; commandtab commandtab; @ViewById LinearLayout ll_flyl; @ViewById ListView lv; @ViewById TextView tv_zyts; @ViewById TextView tv_cmdname; @ViewById TextView tv_yl; @ViewById TextView tv_note; @ViewById TextView tv_qx; @AfterViews void afterOncreate() { getListData(); showData(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_commanddetail, container, false); commandtab = getArguments().getParcelable("bean"); return rootView; } private void getListData() { commembertab commembertab = AppContext.getUserInfo(getActivity()); RequestParams params = new RequestParams(); params.addQueryStringParameter("comID", commandtab.getId()); params.addQueryStringParameter("userid", commembertab.getId()); params.addQueryStringParameter("uid", commembertab.getuId()); params.addQueryStringParameter("username", commembertab.getuserName()); params.addQueryStringParameter("page_size", "10"); params.addQueryStringParameter("page_index", "10"); params.addQueryStringParameter("action", "commandGetListBycomID"); HttpUtils http = new HttpUtils(); http.send(HttpRequest.HttpMethod.POST, AppConfig.testurl, params, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { String a = responseInfo.result; List<commandtab> listNewData = null; Result result = JSON.parseObject(responseInfo.result, Result.class); if (result.getResultCode() == 1)// -1出错;0结果集数量为0;结果列表 { if (result.getAffectedRows() != 0) { listNewData = JSON.parseArray(result.getRows().toJSONString(), commandtab.class); listAdapter = new Command_ExecuteArea_Adapter(getActivity(), listNewData); lv.setAdapter(listAdapter); utils.setListViewHeight(lv); } else { listNewData = new ArrayList<commandtab>(); } } else { AppContext.makeToast(getActivity(), "error_connectDataBase"); return; } } @Override public void onFailure(HttpException e, String s) { } }); } private void showData() { String[] nongzi = commandtab.getnongziName().split(","); String flyl = ""; for (int i = 0; i < nongzi.length; i++) { flyl = flyl + nongzi[i] + " ; "; } tv_note.setText(commandtab.getcommNote()); tv_yl.setText(flyl); tv_zyts.setText(commandtab.getcommDays() + "天"); tv_qx.setText(commandtab.getcommComDate()); if (commandtab.getstdJobType().equals("-1")) { ll_flyl.setVisibility(View.GONE); if (commandtab.getcommNote().equals("")) { tv_cmdname.setText("暂无说明"); } else { tv_cmdname.setText(commandtab.getcommNote()); } } else if (commandtab.getstdJobType().equals("0")) { if (commandtab.getcommNote().equals("")) { tv_cmdname.setText("暂无说明"); } else { tv_cmdname.setText(commandtab.getcommNote()); } } else { tv_cmdname.setText(commandtab.getstdJobTypeName() + "——" + commandtab.getstdJobName()); } } }
[ "1655815015@qq.com" ]
1655815015@qq.com
72a4c6ac12f34e2459d58f3d17f6fef171c86436
d4ae952d7d9cb11dd319adc55a3f95d3523beaaf
/src/main/java/com/ezycoding/sbgp/PubSubConfig.java
b2853608c47efa09323bd8507f3f13ff0bf0bf49
[]
no_license
kaushik-talukder/spring-boot-gcp-publish
0dcb5046a1b22985e3a543092c33161b44ca20ff
72432997d99931443bcef8f3c38ff09227db5d4f
refs/heads/master
2022-09-22T21:25:09.369130
2020-06-06T13:46:32
2020-06-06T13:46:32
266,673,898
0
0
null
null
null
null
UTF-8
Java
false
false
2,213
java
package com.ezycoding.sbgp; import org.springframework.cloud.gcp.pubsub.core.PubSubTemplate; import org.springframework.cloud.gcp.pubsub.integration.outbound.PubSubMessageHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.messaging.MessageHandler; /* import org.springframework.integration.channel.DirectChannel; import org.springframework.messaging.MessageChannel; import org.springframework.cloud.gcp.pubsub.support.BasicAcknowledgeablePubsubMessage; import org.springframework.cloud.gcp.pubsub.support.GcpPubSubHeaders; import org.springframework.cloud.gcp.pubsub.integration.AckMode; import org.springframework.cloud.gcp.pubsub.integration.inbound.PubSubInboundChannelAdapter; import org.springframework.beans.factory.annotation.Qualifier; */ @Configuration public class PubSubConfig { /* @Bean public MessageChannel pubsubInputChannel() { return new DirectChannel(); } @Bean public PubSubInboundChannelAdapter messageChannelAdapter( @Qualifier("pubsubInputChannel") MessageChannel inputChannel, PubSubTemplate pubSubTemplate) { PubSubInboundChannelAdapter adapter = new PubSubInboundChannelAdapter(pubSubTemplate, "employees-sub"); adapter.setOutputChannel(inputChannel); adapter.setAckMode(AckMode.MANUAL); return adapter; } @Bean @ServiceActivator(inputChannel = "pubsubInputChannel") public MessageHandler messageReceiver() { return message -> { LOGGER.info("Message arrived! Payload: " + new String((byte[]) message.getPayload())); BasicAcknowledgeablePubsubMessage originalMessage = message.getHeaders().get(GcpPubSubHeaders.ORIGINAL_MESSAGE, BasicAcknowledgeablePubsubMessage.class); originalMessage.ack(); }; }*/ @Bean @ServiceActivator(inputChannel = "pubsubOutputChannel") public MessageHandler messageSender(PubSubTemplate pubsubTemplate) { return new PubSubMessageHandler(pubsubTemplate, "employees"); } }
[ "kaushik.talukder@gmail.com" ]
kaushik.talukder@gmail.com
a75ec1296eaf7906062de8b81255ef08c349343b
2abd1166c2e061f6c6bf3665e1fdf44f9c14ae13
/fichiersNecesairesPourLeProjet2/OutilsProjet2Exemples/boitesDeDialogue/src/application/Main.java
7f57f7667ffe7e5bb44ee3d7ddc5b3c98453d411
[]
no_license
gabb134/Projet2Objet2
d509a169c8ba5d49fc045ea34e613178ea5bc6ef
e6a6c4e3be5531a9afec51c09156d125afcb6650
refs/heads/master
2020-08-27T11:23:29.721201
2019-11-22T04:39:57
2019-11-22T04:39:57
217,350,073
1
0
null
null
null
null
ISO-8859-1
Java
false
false
4,908
java
package application; import java.util.ArrayList; import java.util.Optional; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Orientation; import javafx.stage.Stage; import javafx.stage.WindowEvent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.ChoiceDialog; import javafx.scene.control.DialogEvent; import javafx.scene.control.TextInputDialog; import javafx.scene.layout.BorderPane; import javafx.scene.layout.TilePane; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; public class Main extends Application { @Override public void start(Stage primaryStage) { try { TilePane root = new TilePane(Orientation.VERTICAL); root.setVgap(20); Scene scene = new Scene(root); scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); root.setPadding(new Insets(10)); Button btnAfficher = new Button ("Afficher boite de dialogue"); Button btnAfficherTextInput = new Button ("Afficher boite entrée de text"); btnAfficher.setFont(Font.font("Arial", FontWeight.BOLD, 20)); btnAfficherTextInput.setFont(Font.font("Arial", FontWeight.BOLD, 20)); Button btnAfficherBoiteChoix = new Button ("Afficher boite de choix"); btnAfficherBoiteChoix.setFont(Font.font("Arial", FontWeight.BOLD, 20)); btnAfficherBoiteChoix.setMaxWidth(Double.MAX_VALUE); btnAfficher.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { // TODO Auto-generated method stub Optional<ButtonType> retour =null; //retour =afficherBoiteInfo(AlertType.INFORMATION); //retour = afficherBoiteInfo(AlertType.WARNING); //retour = afficherBoiteInfo(AlertType.ERROR); retour = afficherBoiteInfo(AlertType.CONFIRMATION); if (retour.isPresent()) if (retour.get() == ButtonType.OK){ System.out.println("Ok est choisi"); } else { System.out.println("Ok non est choisi"); } } }); btnAfficherTextInput.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { // TODO Auto-generated method stub TextInputDialog txtDialogue = new TextInputDialog("Votre nom"); txtDialogue.setHeaderText(null); txtDialogue.setTitle("boite d'entrée de texte"); txtDialogue.setContentText("Entrer votre nom:"); // Traditional way to get the response value. Optional<String> retour = txtDialogue.showAndWait(); if (retour.isPresent()){ System.out.println("Votre nom est: " + retour.get()); } } }); btnAfficherBoiteChoix.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { // TODO Auto-generated method stub ArrayList<String> lstChoix = new ArrayList<String> (); lstChoix.add("choix 1"); lstChoix.add("choix 2"); lstChoix.add("choix 3"); lstChoix.add("choix 4"); ChoiceDialog<String> boiteChoix = new ChoiceDialog<>(lstChoix.get(0), lstChoix); boiteChoix.setTitle("Boite de choix"); boiteChoix.setHeaderText(null); boiteChoix.setContentText("Choisir une valeur"); // Traditional way to get the response value. Optional<String> retour = boiteChoix.showAndWait(); if (retour.isPresent()){ System.out.println("Votre choix est: " + retour.get()); } } }); root.getChildren().addAll(btnAfficher,btnAfficherTextInput,btnAfficherBoiteChoix); primaryStage.setScene(scene); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } } public Optional<ButtonType> afficherBoiteInfo(AlertType type) { String entete=null; String texte=null; String titre = null; Alert alert= null; switch (type) { case INFORMATION: alert = new Alert (AlertType.INFORMATION); titre = " boite d'information"; texte = "Ceci est un message d'information"; break; case WARNING: alert = new Alert (AlertType.WARNING); titre = " boite d'averissement"; texte = "Ceci est un message d'avertissement"; break; case ERROR: alert = new Alert (AlertType.ERROR); titre = " boite d'erreur"; texte = "attention! vous avez un erreur"; break; case CONFIRMATION: alert = new Alert (AlertType.CONFIRMATION); titre = " boite de confirmation"; texte = "êtes vous d'accord pour.... "; break; default: break; } alert.setTitle(titre); alert.setHeaderText(entete); alert.setContentText(texte); return alert.showAndWait(); } public static void main(String[] args) { launch(args); } }
[ "cg.marrero@cgodin.qc.ca" ]
cg.marrero@cgodin.qc.ca
d89fb096571b2e48f91e2e5b347e37df4f8fbfa1
b3ad513a6083d21cbfc21938a6fc01b58feaff95
/app/src/main/java/com/appjumper/silkscreen/ui/home/exhibition/ExhibitionActivity.java
e5bfc74fcd7f6294f672868ea4192d228be62ec7
[]
no_license
beyondbox/net
e0d9b12b8d5e45d31f6a1430a9399ccc2c6a249a
5c2bbc2f1e77a75dc541ac58192fd7361a4603d6
refs/heads/master
2021-01-20T14:29:34.517648
2018-03-20T08:13:03
2018-03-20T08:13:03
90,618,930
0
1
null
null
null
null
UTF-8
Java
false
false
8,715
java
package com.appjumper.silkscreen.ui.home.exhibition; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import com.appjumper.silkscreen.R; import com.appjumper.silkscreen.base.BaseActivity; import com.appjumper.silkscreen.bean.Exhibition; import com.appjumper.silkscreen.bean.ExhibitionListResponse; import com.appjumper.silkscreen.net.CommonApi; import com.appjumper.silkscreen.net.HttpUtil; import com.appjumper.silkscreen.net.JsonParser; import com.appjumper.silkscreen.net.MyHttpClient; import com.appjumper.silkscreen.net.Url; import com.appjumper.silkscreen.ui.common.WebViewActivity; import com.appjumper.silkscreen.ui.home.adapter.ExhibitionListViewAdapter; import com.appjumper.silkscreen.view.pulltorefresh.PagedListView; import com.appjumper.silkscreen.view.pulltorefresh.PullToRefreshBase; import com.appjumper.silkscreen.view.pulltorefresh.PullToRefreshPagedListView; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.apache.http.Header; import org.apache.http.message.BasicNameValuePair; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by yc on 2016/11/11. * 展会信息 */ public class ExhibitionActivity extends BaseActivity { @Bind(R.id.listview) PullToRefreshPagedListView pullToRefreshView; private PagedListView listView; private View mEmptyLayout; private String pagesize = "30"; private int pageNumber = 1; private List<Exhibition> list; private ExhibitionListViewAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exhibition); initBack(); initTitle("展会信息"); ButterKnife.bind(this); listView = pullToRefreshView.getRefreshableView(); listView.onFinishLoading(false); mEmptyLayout = LayoutInflater.from(this).inflate(R.layout.pull_listitem_empty_padding, null); pullToRefreshView.setEmptyView(mEmptyLayout); refresh(); initListener(); } private void refresh() { pullToRefreshView.setRefreshing(); new Thread(run).start(); } public void initListener() { listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (checkLogined()) { getDetail(list.get(i-1).getId()); start_Activity(ExhibitionActivity.this, WebViewActivity.class,new BasicNameValuePair("url",list.get(i-1).getUrl()),new BasicNameValuePair("title","详情")); list.get(i - 1).setIs_read(true); adapter.notifyDataSetChanged(); CommonApi.addLiveness(getUserID(), 8); } } }); listView.setOnLoadMoreListener(new PagedListView.OnLoadMoreListener() { @Override public void onLoadMoreItems() { new Thread(pageRun).start(); } }); pullToRefreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() { @Override public void onPullDownToRefresh() { new Thread(run).start(); } @Override public void onPullUpToRefresh() { } }); } private Runnable run = new Runnable() { public void run() { ExhibitionListResponse response = null; try { HashMap<String, String> data = new HashMap<String, String>(); data.put("uid", getUserID()); data.put("pagesize", pagesize); data.put("page", "1"); data.put("lat", getLat()); data.put("lng", getLng()); response = JsonParser.getExhibitionListResponse(HttpUtil.getMsg(Url.EXPOLIST + "?" + HttpUtil.getData(data))); } catch (Exception e) { e.printStackTrace(); } if (response != null) { handler.sendMessage(handler.obtainMessage( NETWORK_SUCCESS_DATA_RIGHT, response)); } else { handler.sendEmptyMessage(NETWORK_FAIL); } } }; private Runnable pageRun = new Runnable() { @SuppressWarnings("unchecked") public void run() { ExhibitionListResponse response = null; try { HashMap<String, String> data = new HashMap<String, String>(); data.put("uid", getUserID()); data.put("pagesize", pagesize); data.put("page", "" + pageNumber); data.put("lat", getLat()); data.put("lng", getLng()); response = JsonParser.getExhibitionListResponse(HttpUtil.getMsg(Url.EXPOLIST + "?" + HttpUtil.getData(data))); } catch (Exception e) { e.printStackTrace(); } if (response != null) { handler.sendMessage(handler.obtainMessage(NETWORK_SUCCESS_PAGER_RIGHT, response)); } else { handler.sendEmptyMessage(NETWORK_FAIL); } } }; public MyHandler handler = new MyHandler(this); public class MyHandler extends Handler { private WeakReference<Context> reference; public MyHandler(Context context) { reference = new WeakReference<Context>(context); } @Override public void handleMessage(Message msg) { final ExhibitionActivity activity = (ExhibitionActivity) reference.get(); if (activity == null) { return; } if (isDestroyed()) return; pullToRefreshView.onRefreshComplete(); switch (msg.what) { case NETWORK_SUCCESS_DATA_RIGHT: ExhibitionListResponse response = (ExhibitionListResponse) msg.obj; if (response.isSuccess()) { list = response.getData().getItems(); adapter = new ExhibitionListViewAdapter(ExhibitionActivity.this,list); activity.listView.onFinishLoading(response.getData().hasMore()); activity.listView.setAdapter(adapter); activity.pageNumber = 2; activity.pullToRefreshView.setEmptyView(activity.list.isEmpty() ? activity.mEmptyLayout : null); } else { activity.listView.onFinishLoading(false); activity.showErrorToast(response.getError_desc()); } break; case NETWORK_SUCCESS_PAGER_RIGHT: ExhibitionListResponse pageResponse = (ExhibitionListResponse) msg.obj; if (pageResponse.isSuccess()) { List<Exhibition> tempList = pageResponse.getData() .getItems(); activity.list.addAll(tempList); activity.adapter.notifyDataSetChanged(); activity.listView.onFinishLoading(pageResponse.getData().hasMore()); activity.pageNumber++; } else { activity.listView.onFinishLoading(false); activity.showErrorToast(pageResponse.getError_desc()); } break; default: activity.showErrorToast(); activity.listView.onFinishLoading(false); break; } } } /** * 详情接口,调一下消除未读 */ private void getDetail(String id) { RequestParams params = MyHttpClient.getApiParam("expo", "details"); params.put("id", id); params.put("uid", getUserID()); MyHttpClient.getInstance().get(Url.HOST, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } }); } }
[ "363843073@qq.com" ]
363843073@qq.com
0f2ccc4778c7b9da663181ca68eb4707382d4655
edeaf5c5ac8b50dca8acaedae08bc192a0246414
/src/main/java/com/guineapigsanctuary/demo/service/AnimalService.java
448c0f40f3de7a13045339b2f17424fc211c1b4d
[]
no_license
IndigoDreams88/TamesideRescueWebsiteBE
c83118304413eb2f6e6afa2290a924ce9958d07c
7ea771927fee5a3ba7562a5714c335a527084681
refs/heads/master
2022-11-23T07:38:16.635204
2020-06-17T09:27:08
2020-06-17T09:27:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,119
java
package com.guineapigsanctuary.demo.service; import com.guineapigsanctuary.demo.dao.Animaldao; import com.guineapigsanctuary.demo.model.Animal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.UUID; @Service public class AnimalService { private final Animaldao animaldao; @Autowired public AnimalService(@Qualifier("postgres") Animaldao animaldao) { this.animaldao = animaldao; } public int insertAnimal(Animal animal) { return animaldao.insertAnimal(animal); } public List<Animal> getAllAnimals() { return animaldao.selectAllAnimals(); } public Optional<Animal> getAnimalById(UUID id) { return animaldao.selectAnimalById(id); } public int deleteAnimal(UUID id) { return animaldao.deleteAnimalById(id); } public int updateAnimal(UUID id, Animal newAnimal) { return animaldao.updateAnimalById(id, newAnimal); } }
[ "roberthaworth1234@hotmail.com" ]
roberthaworth1234@hotmail.com
51cffe2ff98a6d73ac89d1fd31509ef70efeea71
ddf0951348da24313e02b72cb08f73700cc99843
/src/java/servelets/address.java
a27f10374919ff259f39ad4b8b651b1b4de65802
[]
no_license
chalascs/onlineshoestore
3a5b1891177bcef542a608d5789d7019e5fcb13b
243dfa59b577ca5a1d4c526b0b212745638e635e
refs/heads/master
2020-05-30T07:12:37.905860
2016-12-22T09:02:11
2016-12-22T09:02:11
68,888,228
0
0
null
null
null
null
UTF-8
Java
false
false
4,808
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package servelets; import DB.Address; import DB.City; import DB.Province; import connection.NewHibernateUtil; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; /** * * @author Shanaka */ @WebServlet(name = "address", urlPatterns = {"/address"}) public class address extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { // System.out.println("called"); String add1 = request.getParameter("add1"); String add2 = request.getParameter("add2"); String province = request.getParameter("province"); String district = request.getParameter("district"); String city = request.getParameter("city"); String type = request.getParameter("type"); // System.out.println(add1); if (type.equals("save")) { System.out.println(add1 + add2 + province + district + city); Session ses = NewHibernateUtil.getSessionFactory().openSession(); DB.User us = (DB.User) request.getSession().getAttribute("user"); int uid = us.getUid(); Criteria cr = ses.createCriteria(DB.User.class); cr.add(Restrictions.eq("uid", uid)); DB.User u = (DB.User) cr.uniqueResult(); DB.Address ad = new Address(); ad.setUser(u); ad.setAddress1(add1); ad.setAddress2(add2); Criteria cr1 = ses.createCriteria(DB.Province.class); cr1.add(Restrictions.eq("province", province)); DB.Province p = (DB.Province) cr1.uniqueResult(); ad.setProvince(p); Criteria cr2 = ses.createCriteria(DB.District.class); cr2.add(Restrictions.eq("district", district)); DB.District d = (DB.District) cr2.uniqueResult(); ad.setDistrict(d); Criteria cr4 = ses.createCriteria(DB.City.class); cr4.add(Restrictions.eq("cityname", city)); DB.City ctt = (DB.City) cr4.uniqueResult(); ad.setCity(ctt); ses.save(ad); ses.beginTransaction().commit(); } } catch (Exception e) { e.printStackTrace(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
[ "Shanaka@DESKTOP-SJDE62F" ]
Shanaka@DESKTOP-SJDE62F
064fbe036574ff0b736c2121bf7a5c9f51202f8a
d193bb140ce2cbef18f0fbe2ff6c995cfe3156b7
/frame-service/src/main/java/xyz/frame/rbac/mapper/RbacPermissionMapper.java
cfbe03e0771c57f8fc33da1806a6001cf149a190
[]
no_license
soogbo/xyz-frame
4a82358aea9dcc3e369d6633a68b865e82df1424
db6c1de2ef7585279c479e881bcbe082c78f2870
refs/heads/master
2022-12-10T04:03:15.605303
2019-12-18T11:44:19
2019-12-18T11:44:19
112,169,073
2
0
null
2022-12-06T00:32:09
2017-11-27T08:32:08
HTML
UTF-8
Java
false
false
814
java
package xyz.frame.rbac.mapper; import java.util.List; import org.apache.ibatis.annotations.Select; import xyz.frame.rbac.pojo.po.RbacPermission; import xyz.frame.rbac.pojo.po.RbacRolePermission; import xyz.frame.utils.FrameMapper; public interface RbacPermissionMapper extends FrameMapper<RbacPermission> { @Select(value = { "<script>", "select ", RbacPermission.COLUMN_LIST_ALIAS_T, " from ", RbacPermission.TABLE_NAME, " t, ", RbacRolePermission.TABLE_NAME, " y ", " where y.role_id in ", "<foreach item=\"item\" index=\"index\" collection=\"roleIdList\" open=\"(\" separator =\",\" close=\")\">#{item}</foreach>", " and y.permission_id=t.id and t.valid=1", "</script>" }) List<RbacPermission> selectByRoleIds(List<Long> roleIdList); }
[ "shisp@2345.com" ]
shisp@2345.com
0902dbbf8c21206621a630c9cd63ed33518067bc
d06c314a69f91abfe41e8592a6de2bdc11201959
/BookSolution/Chapter 20/Question20_1/Question.java
28ca648a77d89ab6ea17e60dea9a75d6ab6649cf
[]
no_license
pseudoPixels/CCI
99a8107c77d5951090536de8bc535a18b23d017d
b6d334a8f0d3e7ee884863ab472a1cdd5fc8529c
refs/heads/master
2020-04-17T20:52:06.405801
2019-01-25T00:25:36
2019-01-25T00:25:36
166,924,254
0
0
null
null
null
null
UTF-8
Java
false
false
573
java
public class Question { public static int add_no_arithm(int a, int b) { if (b == 0) return a; int sum = a ^ b; // add without carrying int carry = (a & b) << 1; // carry, but don�t add return add_no_arithm(sum, carry); // recurse } public static int randomInt(int n) { return (int) (Math.random() * n); } public static void main(String[] args) { for (int i = 0; i < 100; i++) { int a = randomInt(10); int b = randomInt(10); int sum = add_no_arithm(a, b); System.out.println(a + " + " + b + " = " + sum); } } }
[ "golam.mostaeen@usask.ca" ]
golam.mostaeen@usask.ca