blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cbaf8adcf62ba6e66d099ef79bf52bd12e21cea1 | c6a9df9c0d02ca46fab8842276e81d53779f66c2 | /Shiro/shiro-simple-webapp/src/main/java/sos/haruhi/shiro/model/RoleRes.java | aa69ea46c5c645f10c9b275e3cbc3bf4370b6750 | [] | no_license | laoniutoushx/Venus | bff61096de52a514f514a0eba8454673e54b9c62 | 0dfb24ae8d0d7d9afc36873bdaeef14c45b2ed28 | refs/heads/master | 2021-05-15T00:02:08.174006 | 2019-01-22T14:21:48 | 2019-01-22T14:21:48 | 103,881,285 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 786 | java | package sos.haruhi.shiro.model;
import javax.persistence.*;
/**
* @ClassName RoleRes
* @Description 资源-角色
* @Author Suzumiya Haruhi
* @Date 2018/9/18 20:07
* @Version 10032
**/
@Entity
@Table(name = "t_role_res")
public class RoleRes {
private int id;
private int roleId;
private int resId;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "role_id")
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
@Column(name = "res_id")
public int getResId() {
return resId;
}
public void setResId(int resId) {
this.resId = resId;
}
}
| [
"[email protected]"
] | |
ac4d7e9a27640a92433d1ba63f99c7d8d7df0daf | e14e452ca97a8f81895abdb0f5e271666478d63f | /src/visa/net/authorize/api/contract/v1/DeleteCustomerProfileRequest.java | 2a4678bd3bac7f30c0c7a5334a7b43e6a2b63297 | [] | no_license | Skillpier/Skillpier-Server-Dev | 6ea0e061a897b97da49af539f27018ce0ec988c9 | d0a966579e13a9ec91168f37c3dd177017a9abb9 | refs/heads/master | 2021-01-19T07:49:50.488101 | 2017-04-07T18:27:00 | 2017-04-07T18:27:00 | 87,575,144 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,060 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.08.11 at 11:22:30 PM IST
//
package net.authorize.api.contract.v1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{AnetApi/xml/v1/schema/AnetApiSchema.xsd}ANetApiRequest">
* <sequence>
* <element name="customerProfileId" type="{AnetApi/xml/v1/schema/AnetApiSchema.xsd}numericString"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"customerProfileId"
})
@XmlRootElement(name = "deleteCustomerProfileRequest")
public class DeleteCustomerProfileRequest
extends ANetApiRequest
{
@XmlElement(required = true)
protected String customerProfileId;
/**
* Gets the value of the customerProfileId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCustomerProfileId() {
return customerProfileId;
}
/**
* Sets the value of the customerProfileId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCustomerProfileId(String value) {
this.customerProfileId = value;
}
}
| [
"[email protected]"
] | |
62932dbefbb3c0fe98b8726cb3853cebab041a5a | 81129ae654ecab19e76d34948c25762fc435bf2a | /src/action/video/VideoAdd.java | c8aa0db926b6146d5e5634236662546561fc1066 | [] | no_license | jyma1991/SimpleVideoWebsite | c15b728ef0c872f13039f4d4601fa88caac9eaf7 | dac87145654490dddb9e0f77783a136f67c5ed5d | refs/heads/master | 2020-12-14T09:02:05.527431 | 2015-06-01T04:23:06 | 2015-06-01T04:23:06 | 36,637,661 | 7 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,097 | java | package action.video;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import service.BaseService;
import bean.Category;
import bean.Configure;
import bean.Video;
import bean.Videostate;
import com.opensymphony.xwork2.ActionSupport;
/**
* @author ������
* �����Ƶ��Action
*/
public class VideoAdd extends ActionSupport {
private static final int FILE_SIZE=16*1024;
private String name;
private String intro;
private File videofile;
private String videofileFileName;
private String videofileContentType;
private BaseService baseService;
private int islive;
private String url;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public BaseService getBaseService() {
return baseService;
}
public void setBaseService(BaseService baseService) {
this.baseService = baseService;
}
public File getVideofile() {
return videofile;
}
public void setVideofile(File videofile) {
this.videofile = videofile;
}
public String getVideofileFileName() {
return videofileFileName;
}
public void setVideofileFileName(String videofileFileName) {
this.videofileFileName = videofileFileName;
}
public String getVideofileContentType() {
return videofileContentType;
}
public void setVideofileContentType(String videofileContentType) {
this.videofileContentType = videofileContentType;
}
public int getIslive() {
return islive;
}
public void setIslive(int islive) {
this.islive = islive;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
/**
* д���ļ�ʱ���õ��ĺ���
* @param source Դ�ļ�
* @param target Ŀ���ļ�
*/
public void upLoadFile(File source,File target){
InputStream in=null;
OutputStream out=null;
try{
in=new BufferedInputStream(new FileInputStream(source),FILE_SIZE);
out=new BufferedOutputStream(new FileOutputStream(target),FILE_SIZE);
//in-->image-->out
byte[] buffer=new byte[FILE_SIZE];
while(in.read(buffer)>0){
out.write(buffer);
}
}catch(IOException ex){
ex.printStackTrace();
}finally{
try{
in.close();
out.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
public String execute(){
try{
int order=1;
Video video=new Video();
video.setName(name);
video.setIntro(intro);
video.setEdittime(new Timestamp(new Date().getTime()));
Configure folder_videoori_cfg=(Configure) baseService.ReadSingle("Configure", "name", "folder_videoori");
Configure folder_thumbnail_cfg=(Configure) baseService.ReadSingle("Configure", "name", "folder_thumbnail");
if(islive==0){
//�㲥
String oriurl=folder_videoori_cfg.getVal()+"/"+videofileFileName;
video.setOriurl(oriurl);
Category category=(Category) baseService.ReadSingle("Category", "id", 1);
video.setCategory(category);
//״̬���ã��ȴ��ϴ�
Videostate videostate=(Videostate) baseService.ReadSingle("Videostate", "order", order);
video.setVideostate(videostate);
video.setIslive(0);
//Default Thumbnail
String defaultthumbnail=folder_thumbnail_cfg.getVal()+"/default.jpg";
video.setThumbnailurl(defaultthumbnail);
baseService.save(video);
//�ϴ���Ƶ�ļ�
String realfileoriDir=ServletActionContext.getServletContext().getRealPath(folder_videoori_cfg.getVal()).replace('\\', '/');
//Check
File realfileoriDirFile =new File(realfileoriDir);
if(!realfileoriDirFile.exists() && !realfileoriDirFile.isDirectory()){
System.out.println("Directory not exist. Create it.");
System.out.println(realfileoriDirFile);
realfileoriDirFile.mkdir();
}
String realfileoriPath=realfileoriDir+"/"+videofileFileName;
File targetFile=new File(realfileoriPath);
upLoadFile(videofile,targetFile);
//�ȴ��ͼ
videostate=(Videostate) baseService.ReadSingle("Videostate", "order", order+1);
video.setVideostate(videostate);
baseService.update(video);
}else{
//ֱ��
Category category=(Category) baseService.ReadSingle("Category", "id", 2);
video.setCategory(category);
video.setUrl(url);
video.setIslive(1);
//�ȴ��ͼ
Videostate videostate=(Videostate) baseService.ReadSingle("Videostate", "order", order+1);
video.setVideostate(videostate);
//Default Thumbnail
String defaultthumbnail=folder_thumbnail_cfg.getVal()+"/default.jpg";
video.setThumbnailurl(defaultthumbnail);
baseService.save(video);
}
return SUCCESS;
}
catch(Exception ex){
ex.printStackTrace();
return ERROR;
}
}
}
| [
"[email protected]"
] | |
2e60aee2c927b8ef1961fa6b736e5b14097cd71a | 76d0570d00a76c51f790a2098bf77a605e471358 | /travelSmart-J2ME/travelSmart/build/preprocessed/travelsmart/entities/Guide.java | aa12c121314d56f11b770a6bbb04253eec549497 | [] | no_license | hedifriha/TravelSmart | 953b3b46ca7c7440a237023d7b24ce2dedaa2477 | c48f8537a9a44b9b063f31dd5c60fac3daa80f2c | refs/heads/master | 2021-01-18T23:39:04.378640 | 2016-11-03T13:37:31 | 2016-11-03T13:37:31 | 72,739,908 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,382 | 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 travelsmart.entities;
/**
*
* @author Amri
*/
public class Guide {
private int id;
private String titre;
private String destination1;
private String desc1;
private String destination2;
private String desc2;
private String destination3;
private String desc3;
private String destination4;
private String desc4;
private String destination5;
private String desc5;
private String chemin;
public Guide() {
}
public Guide(int id, String titre, String destination1, String desc1, String destination2, String desc2, String destination3, String desc3, String destination4, String desc4, String destination5, String desc5, String chemin) {
this.id = id;
this.titre = titre;
this.destination1 = destination1;
this.desc1 = desc1;
this.destination2 = destination2;
this.desc2 = desc2;
this.destination3 = destination3;
this.desc3 = desc3;
this.destination4 = destination4;
this.desc4 = desc4;
this.destination5 = destination5;
this.desc5 = desc5;
this.chemin = chemin;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getDestination1() {
return destination1;
}
public void setDestination1(String destination1) {
this.destination1 = destination1;
}
public String getDesc1() {
return desc1;
}
public void setDesc1(String desc1) {
this.desc1 = desc1;
}
public String getDestination2() {
return destination2;
}
public void setDestination2(String destination2) {
this.destination2 = destination2;
}
public String getDesc2() {
return desc2;
}
public void setDesc2(String desc2) {
this.desc2 = desc2;
}
public String getDestination3() {
return destination3;
}
public void setDestination3(String destination3) {
this.destination3 = destination3;
}
public String getDesc3() {
return desc3;
}
public void setDesc3(String desc3) {
this.desc3 = desc3;
}
public String getDestination4() {
return destination4;
}
public void setDestination4(String destination4) {
this.destination4 = destination4;
}
public String getDesc4() {
return desc4;
}
public void setDesc4(String desc4) {
this.desc4 = desc4;
}
public String getDestination5() {
return destination5;
}
public void setDestination5(String destination5) {
this.destination5 = destination5;
}
public String getDesc5() {
return desc5;
}
public void setDesc5(String desc5) {
this.desc5 = desc5;
}
public String getChemin() {
return chemin;
}
public void setChemin(String chemin) {
this.chemin = chemin;
}
}
| [
"hedi friha"
] | hedi friha |
19ec3d65ad20d970c4148c9081c473f90d77cfba | ea4da81a69a300624a46fce9e64904391c37267c | /src/main/java/com/alipay/api/response/KoubeiRetailWmsProducerQueryResponse.java | d8c32cc9dceaf3a273482d016a11742bd203b5a7 | [
"Apache-2.0"
] | permissive | shiwei1024/alipay-sdk-java-all | 741cc3cb8cf757292b657ce05958ff9ad8ecf582 | d6a051fd47836c719a756607e6f84fee2b26ecb4 | refs/heads/master | 2022-12-29T18:46:53.195585 | 2020-10-09T06:34:30 | 2020-10-09T06:34:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,074 | java | package com.alipay.api.response;
import java.util.List;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
import com.alipay.api.domain.ProducerVO;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: koubei.retail.wms.producer.query response.
*
* @author auto create
* @since 1.0, 2019-01-07 20:51:15
*/
public class KoubeiRetailWmsProducerQueryResponse extends AlipayResponse {
private static final long serialVersionUID = 2411494615944687982L;
/**
* 生产厂商信息
*/
@ApiListField("producers")
@ApiField("producer_v_o")
private List<ProducerVO> producers;
/**
* 记录总数
*/
@ApiField("total_count")
private Long totalCount;
public void setProducers(List<ProducerVO> producers) {
this.producers = producers;
}
public List<ProducerVO> getProducers( ) {
return this.producers;
}
public void setTotalCount(Long totalCount) {
this.totalCount = totalCount;
}
public Long getTotalCount( ) {
return this.totalCount;
}
}
| [
"[email protected]"
] | |
272c848a1b4644e8f1d48051d7bae3bdec549899 | 9bfa71d23e70e514dd9be5f47781b1178833130d | /SQLPlugin/gen/com/sqlplugin/psi/impl/SqlOldOrNewValuesAliasListImpl.java | f1252888b1717fd4e57c420d330f5bcf03b23619 | [
"MIT"
] | permissive | smoothwind/SQL-IDEAplugin | de341884b77c2c61e0b4d6ceefd7c16ff3b7b469 | 3efa434095b4cac4772a0a7df18b34042a4c7557 | refs/heads/master | 2020-04-16T22:37:44.776363 | 2019-01-28T09:43:25 | 2019-01-28T09:43:25 | 165,976,439 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | true | 1,060 | java | // This is a generated file. Not intended for manual editing.
package com.sqlplugin.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.sqlplugin.psi.SqlTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.sqlplugin.psi.*;
public class SqlOldOrNewValuesAliasListImpl extends ASTWrapperPsiElement implements SqlOldOrNewValuesAliasList {
public SqlOldOrNewValuesAliasListImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(@NotNull SqlVisitor visitor) {
visitor.visitOldOrNewValuesAliasList(this);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof SqlVisitor) accept((SqlVisitor)visitor);
else super.accept(visitor);
}
@Override
@NotNull
public SqlOldOrNewValuesAlias getOldOrNewValuesAlias() {
return findNotNullChildByClass(SqlOldOrNewValuesAlias.class);
}
}
| [
"[email protected]"
] | |
089d8b8e005624653aa546fd2ae7202ad143bb1f | 72e7f69b97a53159a2db225a0e20244d3717b74c | /src/com/guddqs/monkeycomputer/other/entity/Computerknowledge.java | 9ff0cfe47bf6b642c786fe14b63661e2ff61c75a | [] | no_license | gudqs7/monkeycomputer | 26c8ac58c9984c44aa45df0c07bdae887a567dad | ef05b422305537dd34d1408992c94b9f07f59900 | refs/heads/master | 2020-12-31T00:00:47.527980 | 2017-02-01T07:56:03 | 2017-02-01T07:56:03 | 80,600,100 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 974 | java | package com.guddqs.monkeycomputer.other.entity;
public class Computerknowledge {
private Integer id;
private String title;
private String detail;
private Integer needful;
private Integer badful;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail == null ? null : detail.trim();
}
public Integer getNeedful() {
return needful;
}
public void setNeedful(Integer needful) {
this.needful = needful;
}
public Integer getBadful() {
return badful;
}
public void setBadful(Integer badful) {
this.badful = badful;
}
} | [
"[email protected]"
] | |
3b3ed0a7370adb2ef30447d41058dcb7a03e2a94 | 5a90b254035ca7d28d67ad2b6c0144f2d72cb168 | /src/main/java/com/recruit/domain/Resume.java | b6eec61ccc7a16b038ea2c94676f3b0eec21e049 | [] | no_license | yuan1/recruit | 4424a0c2287bde161581081c9e56bedffdf6bad1 | fc6acb24c2af1da76c6ee2a32108df1ebcba1eb2 | refs/heads/master | 2021-06-28T02:01:10.002610 | 2018-05-04T16:13:28 | 2018-05-04T16:13:28 | 131,558,871 | 0 | 1 | null | 2020-09-18T14:26:59 | 2018-04-30T05:22:52 | JavaScript | UTF-8 | Java | false | false | 7,509 | java | package com.recruit.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
import java.time.Instant;
import java.util.Objects;
/**
* A Resume.
*/
@Entity
@Table(name = "resume")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "resume")
public class Resume extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "sex")
private String sex;
@Column(name = "birth")
private Instant birth;
@Column(name = "email")
private String email;
@Column(name = "wechat")
private String wechat;
@Column(name = "state")
private String state;
@Column(name = "advantage")
private String advantage;
@Column(name = "target_place")
private String targetPlace;
@Column(name = "work_time")
private Instant workTime;
@Column(name = "experience")
private String experience;
@Column(name = "undergo")
private String undergo;
@Column(name = "education")
private String education;
@Column(name = "target_salary")
private String targetSalary;
@Column(name = "target_position")
private String targetPosition;
@Column(name = "user_id")
private Long userId;
@Column(name = "enclosure")
private String enclosure;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public Resume name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public Resume sex(String sex) {
this.sex = sex;
return this;
}
public void setSex(String sex) {
this.sex = sex;
}
public Instant getBirth() {
return birth;
}
public Resume birth(Instant birth) {
this.birth = birth;
return this;
}
public void setBirth(Instant birth) {
this.birth = birth;
}
public String getEmail() {
return email;
}
public Resume email(String email) {
this.email = email;
return this;
}
public void setEmail(String email) {
this.email = email;
}
public String getWechat() {
return wechat;
}
public Resume wechat(String wechat) {
this.wechat = wechat;
return this;
}
public void setWechat(String wechat) {
this.wechat = wechat;
}
public String getState() {
return state;
}
public Resume state(String state) {
this.state = state;
return this;
}
public void setState(String state) {
this.state = state;
}
public String getAdvantage() {
return advantage;
}
public Resume advantage(String advantage) {
this.advantage = advantage;
return this;
}
public void setAdvantage(String advantage) {
this.advantage = advantage;
}
public String getTargetPlace() {
return targetPlace;
}
public Resume targetPlace(String targetPlace) {
this.targetPlace = targetPlace;
return this;
}
public void setTargetPlace(String targetPlace) {
this.targetPlace = targetPlace;
}
public Instant getWorkTime() {
return workTime;
}
public Resume workTime(Instant workTime) {
this.workTime = workTime;
return this;
}
public void setWorkTime(Instant workTime) {
this.workTime = workTime;
}
public String getExperience() {
return experience;
}
public Resume experience(String experience) {
this.experience = experience;
return this;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getUndergo() {
return undergo;
}
public Resume undergo(String undergo) {
this.undergo = undergo;
return this;
}
public void setUndergo(String undergo) {
this.undergo = undergo;
}
public String getEducation() {
return education;
}
public Resume education(String education) {
this.education = education;
return this;
}
public void setEducation(String education) {
this.education = education;
}
public String getTargetSalary() {
return targetSalary;
}
public Resume targetSalary(String targetSalary) {
this.targetSalary = targetSalary;
return this;
}
public void setTargetSalary(String targetSalary) {
this.targetSalary = targetSalary;
}
public String getTargetPosition() {
return targetPosition;
}
public Resume targetPosition(String targetPosition) {
this.targetPosition = targetPosition;
return this;
}
public void setTargetPosition(String targetPosition) {
this.targetPosition = targetPosition;
}
public Long getUserId() {
return userId;
}
public Resume userId(Long userId) {
this.userId = userId;
return this;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getEnclosure() {
return enclosure;
}
public Resume enclosure(String enclosure) {
this.enclosure = enclosure;
return this;
}
public void setEnclosure(String enclosure) {
this.enclosure = enclosure;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Resume resume = (Resume) o;
if (resume.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), resume.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Resume{" +
"id=" + getId() +
", name='" + getName() + "'" +
", sex='" + getSex() + "'" +
", birth='" + getBirth() + "'" +
", email='" + getEmail() + "'" +
", wechat='" + getWechat() + "'" +
", state='" + getState() + "'" +
", advantage='" + getAdvantage() + "'" +
", targetPlace='" + getTargetPlace() + "'" +
", workTime='" + getWorkTime() + "'" +
", experience='" + getExperience() + "'" +
", undergo='" + getUndergo() + "'" +
", education='" + getEducation() + "'" +
", targetSalary='" + getTargetSalary() + "'" +
", targetPosition='" + getTargetPosition() + "'" +
", userId=" + getUserId() +
", enclosure='" + getEnclosure() + "'" +
"}";
}
}
| [
"[email protected]"
] | |
fc390b8901991d6af84cdbf25265fceda87459e6 | e399b84680c8ad08243b8fd266f8bc187be21cbb | /xs2a-server-api/src/main/java/de/adorsys/psd2/model/TppMessage406PIS.java | 9d77875d36ef370d18459e83828b44cd5b10a7a3 | [
"Apache-2.0"
] | permissive | hpgft/xs2a | 7d7b0555ade3bfea639a9c80df44c03627e4ecc4 | 6ced2f845bbb4115556c57a0535d770979cbfe79 | refs/heads/master | 2021-03-26T11:18:51.582129 | 2020-03-13T08:59:47 | 2020-03-13T08:59:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,116 | java | /*
* Copyright 2018-2019 adorsys GmbH & Co KG
*
* 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 de.adorsys.psd2.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Objects;
/**
* TppMessage406PIS
*/
@Validated
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2019-12-26T15:06:21.086+02:00[Europe/Kiev]")
public class TppMessage406PIS {
@JsonProperty("category")
private TppMessageCategory category = null;
@JsonProperty("code")
private String code = null;
@JsonProperty("path")
private String path = null;
@JsonProperty("text")
private String text = null;
public TppMessage406PIS category(TppMessageCategory category) {
this.category = category;
return this;
}
/**
* Get category
* @return category
**/
@ApiModelProperty(required = true, value = "")
@NotNull
@Valid
@JsonProperty("category")
public TppMessageCategory getCategory() {
return category;
}
public void setCategory(TppMessageCategory category) {
this.category = category;
}
public TppMessage406PIS code(String code) {
this.code = code;
return this;
}
/**
* Get code
* @return code
**/
@ApiModelProperty(required = true, value = "")
@NotNull
@JsonProperty("code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public TppMessage406PIS path(String path) {
this.path = path;
return this;
}
/**
* Get path
* @return path
**/
@ApiModelProperty(value = "")
@JsonProperty("path")
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public TppMessage406PIS text(String text) {
this.text = text;
return this;
}
/**
* Get text
* @return text
**/
@ApiModelProperty(value = "")
@Size(max=500)
@JsonProperty("text")
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
} TppMessage406PIS tppMessage406PIS = (TppMessage406PIS) o;
return Objects.equals(this.category, tppMessage406PIS.category) &&
Objects.equals(this.code, tppMessage406PIS.code) &&
Objects.equals(this.path, tppMessage406PIS.path) &&
Objects.equals(this.text, tppMessage406PIS.text);
}
@Override
public int hashCode() {
return Objects.hash(category, code, path, text);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TppMessage406PIS {\n");
sb.append(" category: ").append(toIndentedString(category)).append("\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" path: ").append(toIndentedString(path)).append("\n");
sb.append(" text: ").append(toIndentedString(text)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| [
"[email protected]"
] | |
6540bfddeb8e04bee19cfdf2c98aa510241d86ca | 2aa75a953d5a52471b444117636b1fcb8cb0d4b4 | /SpiderMan-plugin-template/src/test/java/TestAsm.java | 0baf3f0952692b699144d3d2bd9626f3cc984d18 | [
"Apache-2.0"
] | permissive | bugyun/SpiderMan | 06028a0ce702f3bc76ed89fedcc7ce17f46ace1e | ae4890ec0c2b13ed2a0599aaf63dcb3d97959588 | refs/heads/master | 2020-08-09T19:28:57.048196 | 2020-03-16T05:21:14 | 2020-03-16T05:21:14 | 214,154,834 | 8 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,397 | java | import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.util.TraceClassVisitor;
import vip.ruoyun.template.asm.AsmClassVisitor;
public class TestAsm {
@Test
public void testAsm() throws IOException {
//reader
// ClassReader classReader = new ClassReader("java.lang.String");//className
ClassReader classReader = new ClassReader("vip.ruoyun.java.TestJava");//className
//writer
ClassWriter classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_FRAMES);
//打印输出,查看结果
PrintWriter printWriter = new PrintWriter("./src/test/java/testAsm.text");//
TraceClassVisitor traceClassVisitor = new TraceClassVisitor(classWriter, printWriter);//用来输出生成的代码 text
//visitor
AsmClassVisitor asmClassVisitor = new AsmClassVisitor(traceClassVisitor);
//转换
classReader.accept(asmClassVisitor, ClassReader.EXPAND_FRAMES);
//输出字节码
final byte[] bytes = classWriter.toByteArray();
traceClassVisitor.p.print(printWriter);//输出代码
}
//=====---------- visitMethod ----------=====
//methodName: <init>
//methodDes: ()V
//=====---------- visitMethod ----------=====
//methodName: registerNatives
//methodDes: ()V
//=====---------- visitMethod ----------=====
//methodName: getClass
//methodDes: ()Ljava/lang/Class;
//=====---------- visitMethod ----------=====
//methodName: hashCode
//methodDes: ()I
//=====---------- visitMethod ----------=====
//methodName: equals
//methodDes: (Ljava/lang/Object;)Z
//=====---------- visitMethod ----------=====
//methodName: clone
//methodDes: ()Ljava/lang/Object;
//=====---------- visitMethod ----------=====
//methodName: toString
//methodDes: ()Ljava/lang/String;
//=====---------- visitMethod ----------=====
//methodName: notify
//methodDes: ()V
//=====---------- visitMethod ----------=====
//methodName: notifyAll
//methodDes: ()V
//=====---------- visitMethod ----------=====
//methodName: wait
//methodDes: (J)V
//=====---------- visitMethod ----------=====
//methodName: wait
//methodDes: (JI)V
//=====---------- visitMethod ----------=====
//methodName: wait
//methodDes: ()V
//=====---------- visitMethod ----------=====
//methodName: finalize
//methodDes: ()V
//=====---------- visitMethod ----------=====
//methodName: <clinit>
//methodDes: ()V
//栅栏的方式,先执行 1 2 ,然后阻塞,然后才开始执行 3 4
@Test
public void testC() throws InterruptedException {
ForkJoinPool executor = new ForkJoinPool(Runtime.getRuntime().availableProcessors(),
ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true);
executor.execute(() -> {
System.out.println("1 begin");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1 end");
});
executor.execute(() -> {
System.out.println("2 begin");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2 end");
});
executor.awaitQuiescence(1, TimeUnit.MINUTES);
System.out.println("开始");
executor.execute(() -> {
System.out.println("3 begin");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("3 end");
});
executor.execute(() -> {
System.out.println("4 begin");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("4 end");
});
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("结束");
}
}
| [
"[email protected]"
] | |
ea656ce2e807764d603c617b0cf5a45c86a368c4 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/20/20_6815fb87def575dffec16f3e4a049b263d4e2a82/HttpRequests/20_6815fb87def575dffec16f3e4a049b263d4e2a82_HttpRequests_s.java | feeead8fd3ffd558f706c36b63fbedfae20053b5 | [] | 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 | 4,734 | java | package com.example.friendzyapp;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.osmdroid.util.GeoPoint;
import android.util.Log;
/*
* A non-static container for all the request objects.
*
* Refactored out here so initServer can access them in a non-android environment
* for Robotium testing.
*/
public class HttpRequests {
private static final String TAG = "HttpRequests";
public static class LoginRequest {
public LoginRequest(String _userID, List<String> _facebookFriends, String ri, String pn) {
userID = _userID;
facebookFriends = _facebookFriends;
this.regId = ri;
this.phone_number = pn;
}
public String userID;
public List<String> facebookFriends;
public String regId;
public String phone_number;
}
public static class PostStatusRequest {
public String userID;
public String status;
public String is_public;
public PostStatusRequest(String userID, String status) {
this.userID = userID;
this.status = status;
this.is_public = "true";
}
}
public static class AcceptMatchRequest {
public String userID;
public String friendID;
public Map<String, String> userLocation;
public AcceptMatchRequest(String userID, String friendID, Map<String, String> userLocation) {
this.userID = userID;
this.friendID = friendID;
this.userLocation = userLocation;
}
}
public static class PostMsgRequest {
public String userID;
public String friendID;
public String msg;
public ServerMeetupLocation meetup_location; // make an object for this!!
public PostMsgRequest(String userID, String friendID, String msg, ServerMeetupLocation meetup_location) {
Log.d(TAG, "I'm user :" + userID);
this.userID = userID;
this.friendID = friendID;
this.msg = msg;
this.meetup_location = meetup_location;
}
}
/*
* To be jsoned and sent to server only
*/
public static class ServerMeetupLocation {
public String meeting_name;
public newLocation meeting_location;
public ServerMeetupLocation(String meeting_name, newLocation meeting_location) {
this.meeting_name = meeting_name;
this.meeting_location = meeting_location;
}
public ServerMeetupLocation() {
//emtpy one; don't update the sever
}
}
public static class newLocation {
public String latitude;
public String longitude;
public newLocation(String latitude, String longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
}
/*
* To be used in receiving only
*/
public static class MeetupLocation implements Serializable {
private static final long serialVersionUID = 1L;
public String meetingName;
public GeoPoint meetingLocation;
public MeetupLocation(String meetingName, GeoPoint meetingLocation) {
Log.d(TAG, "Someone is trying to instantiate a MeetupLocation!");
this.meetingName = meetingName;
this.meetingLocation = meetingLocation;
}
public MeetupLocation() {
// empty one used for if location is not set.
}
}
public static class SubUpdateRequest {
public String userID;
public String type; // available types: "add", "delete"
public String subscribe_topic;
public List<String> subscribe_to;
public SubUpdateRequest(String userID, String type, String subscribe_topic, List<String> subscribe_to) {
Log.wtf(TAG, "I'm user :" + userID);
this.userID = userID;
this.type = type;
this.subscribe_topic = subscribe_topic;
this.subscribe_to = subscribe_to;
}
}
public static class SetSMSRequest {
public String userID;
public Boolean sms;
public SetSMSRequest(String userID, Boolean sms) {
this.userID = userID;
this.sms = sms;
}
}
public static class GetEventsRequest {
public String userID;
public Map<String, String> userLocation;
public GetEventsRequest(String userID, Map<String, String> userLocation) {
this.userID = userID;
this.userLocation = userLocation;
}
}
}
| [
"[email protected]"
] | |
b389ad5c97da0784357fcab6188d8007f534c7b5 | 3597b87dee5a87e068c5cb3be9da81c0e58c82e5 | /10 Days of Statistics/Day 0- Weighted Mean/Solution.java | 5fbc5d9502511b36f0aad746f6544bbd49a50c26 | [
"Unlicense"
] | permissive | poojasethia/HackerRank-in-Java | f2b8563b146d49a9884bfb1e5f2b6d0c9512be3f | 07de8ddd7ecbf4a2b067209a412bb6c68d62b5dc | refs/heads/master | 2020-03-31T18:45:23.666168 | 2018-10-04T17:15:57 | 2018-10-04T17:15:57 | 152,471,267 | 0 | 1 | Unlicense | 2018-10-10T18:32:33 | 2018-10-10T18:32:32 | null | UTF-8 | Java | false | false | 824 | java | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
int [] elements = new int[size];
int [] weights = new int[size];
for (int i = 0; i < size; i++) {
elements[i] = scan.nextInt();
}
for (int i = 0; i < size; i++) {
weights[i] = scan.nextInt();
}
scan.close();
/* Calculate weighted mean */
int total = 0;
int totalWeights = 0;
for (int i = 0; i < size; i++) {
total += elements[i] * weights[i];
totalWeights += weights[i];
}
double weightedMean = (double) total / totalWeights;
System.out.format("%.1f", weightedMean);
}
}
| [
"[email protected]"
] | |
8363a0327c02a7f36dd9da2706c2c877619653c6 | 7a33586ec57bf0c2f927d694c33894af6d4c5f53 | /hrbm-framework/src/main/java/com/xunfeng/core/util/DateUtil.java | 563673a0c14bdf8a674b22e725d08c519436b2a3 | [] | no_license | zhang765959964/hrbm | c86b8b8f1cbd159bee4b35d1068afdc34b16f1d8 | d034c43516f92e8433016ec4db3d910cc5d06881 | refs/heads/master | 2021-05-11T23:39:36.723156 | 2018-01-15T08:40:02 | 2018-01-15T08:40:02 | 117,515,559 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,561 | java | package com.xunfeng.core.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @company: 河南讯丰信息技术有限公司
* @Description: 日期操作类
* @author wanghan
* @createDate 2015年4月23日-上午11:42:56
* @version V1.0
*/
public class DateUtil {
private static final Log logger = LogFactory.getLog(DateUtil.class);
/**
* 设置当前时间为当天的最初时间(即00时00分00秒)
*
* @param cal
* @return
*/
public static Calendar setStartDay1(Calendar cal) {
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal;
}
public static Calendar setEndDay(Calendar cal) {
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal;
}
/**
* 把源日历的年月日设置到目标日历对象中
* @param destCal
* @param sourceCal
*/
public static void copyYearMonthDay(Calendar destCal,Calendar sourceCal){
destCal.set(Calendar.YEAR, sourceCal.get(Calendar.YEAR));
destCal.set(Calendar.MONTH, sourceCal.get(Calendar.MONTH));
destCal.set(Calendar.DAY_OF_MONTH, sourceCal.get(Calendar.DAY_OF_MONTH));
}
/**
* 格式化日期为
*
* @return
*/
public static String formatEnDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
return sdf.format(date).replaceAll("上午", "AM").replaceAll("下午", "PM");
}
public static Date parseDate(String dateString) {
dateString=dateString.replaceAll("—", "-");
Date date = null;
try {
date = DateUtils.parseDate(dateString, new String[]{StringPool.DATE_FORMAT_DATETIME,StringPool.DATE_FORMAT_DATE});
} catch (Exception ex) {
logger.error("Pase the Date(" + dateString + ") occur errors:"
+ ex.getMessage());
throw new RuntimeException("日期格式错误");
}
return date;
}
/**日期加月,
* @param date
* @param formater 格式化
* @param addStep 增加月数
* @return
*/
public static String addMonth(String date,String formater,int addStep){
if(StringUtil.isEmpty(date))return null;
DateFormat format=new SimpleDateFormat(formater);
Calendar calendar=Calendar.getInstance();
String tmpDate=null;
try {
Date dd=format.parse(date);
calendar.setTime(dd);
calendar.add(Calendar.MONTH,addStep);
tmpDate = format.format(calendar.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return tmpDate;
}
/**
* 日期加一天
* @param date
* @return
*/
public static String addOneDay(String date){
DateFormat format=new SimpleDateFormat(StringPool.DATE_FORMAT_DATE);
Calendar calendar=Calendar.getInstance();
try {
Date dd=format.parse(date);
calendar.setTime(dd);
calendar.add(Calendar.DAY_OF_MONTH,1);
} catch (ParseException e) {
e.printStackTrace();
}
String tmpDate = format.format(calendar.getTime());
return tmpDate.substring(5,7)+"/"+tmpDate.substring(8,10)
+"/"+tmpDate.substring(0,4);
}
/**
* 加一小时
* @param date
* @return
*/
public static String addOneHour(String date){
String amPm = date.substring(20,22);
DateFormat format=new SimpleDateFormat(StringPool.DATE_FORMAT_DATETIME);
Calendar calendar=Calendar.getInstance();
int hour = Integer.parseInt(date.substring(11,13));
try {
if(amPm.equals("PM")){
hour+=12;
}
date = date.substring(0,11)+(hour>=10?hour:"0"+hour)+date.substring(13,19);
Date dd=format.parse(date);
calendar.setTime(dd);
calendar.add(Calendar.HOUR_OF_DAY,1);
} catch (ParseException e) {
e.printStackTrace();
}
String tmpDate = format.format(calendar.getTime());
hour = Integer.parseInt(tmpDate.substring(11,13));
amPm = hour>=12&&hour!=0?"PM":"AM";
if(amPm.equals("PM")){
hour-=12;
}
tmpDate = tmpDate.substring(5,7)+"/"+tmpDate.substring(8,10)+"/"+tmpDate.substring(0,4)
+" "+(hour>=10?hour:"0"+hour)+tmpDate.substring(13, tmpDate.length())+" "+amPm;
return tmpDate;
}
/**
* 标准时间格式转为时间字符格式
* @param timeStr eg:Mon Feb 06 00:00:00 CST 2012
* @return
*/
public static String timeStrToDateStr(String timeStr){
String dateStr=timeStr.substring(24, 28)+"-";
String mon = timeStr.substring(4, 7);
if(mon.equals("Jan")){
dateStr+="01";
}else if(mon.equals("Feb")){
dateStr+="02";
}else if(mon.equals("Mar")){
dateStr+="03";
}else if(mon.equals("Apr")){
dateStr+="04";
}else if(mon.equals("May")){
dateStr+="05";
}else if(mon.equals("Jun")){
dateStr+="06";
}else if(mon.equals("Jul")){
dateStr+="07";
}else if(mon.equals("Aug")){
dateStr+="08";
}else if(mon.equals("Sep")){
dateStr+="09";
}else if(mon.equals("Oct")){
dateStr+="10";
}else if(mon.equals("Nov")){
dateStr+="11";
}else if(mon.equals("Dec")){
dateStr+="12";
}
dateStr+="-"+timeStr.substring(8, 10);
return dateStr;
}
/**
* 根据日期得到星期多余天数
* @param sDate
* @return
*/
public static int getExtraDayOfWeek(String sDate){
try{
SimpleDateFormat format = new SimpleDateFormat(StringPool.DATE_FORMAT_DATE);
Date date=format.parse(sDate);
String weekday = date.toString().substring(0,3);
if(weekday.equals("Mon")){
return 1;
}else if(weekday.equals("Tue")){
return 2;
}else if(weekday.equals("Wed")){
return 3;
}else if(weekday.equals("Thu")){
return 4;
}else if(weekday.equals("Fri")){
return 5;
}else if(weekday.equals("Sat")){
return 6;
}else{
return 0;
}
}catch(Exception ex){
return 0;
}
}
/**
* 根据日期得到星期多余天数
* @param sDate
* @return
*/
public static String getDateWeekDay(String sDate){
try{
SimpleDateFormat format = new SimpleDateFormat(StringPool.DATE_FORMAT_DATE);
Date date=format.parse(sDate);
String weekday = date.toString().substring(0,3);
// format.format(date)+" "+
return weekday;
}catch(Exception ex){
return "";
}
}
/**
* 取得上下五年
* @param cal
* @return
*/
public static List<String> getUpDownFiveYear(Calendar cal){
List<String> yearlist = new ArrayList<String>();
int curyear = cal.get(Calendar.YEAR);
yearlist.add(String.valueOf(curyear-2));
yearlist.add(String.valueOf(curyear-1));
yearlist.add(String.valueOf(curyear));
yearlist.add(String.valueOf(curyear+1));
yearlist.add(String.valueOf(curyear+2));
return yearlist;
}
/**
* 取得12个月
* @param cal
* @return
*/
public static List<String> getTwelveMonth(){
List<String> monthlist = new ArrayList<String>();
for(int idx=1;idx<=12;idx++){
monthlist.add(String.valueOf(idx));
}
return monthlist;
}
/**
* 得到两日期间所有日期
* @param startTime
* @param endTime
* @return
* @throws Exception
*/
public static String[] getDaysBetweenDate(String stime, String etime){
String[] dateArr = null;
try {
// String stime = timeStrToDateStr(startTime);
// String etime = timeStrToDateStr(endTime);
//日期相减算出秒的算法
Date date1 = new SimpleDateFormat(StringPool.DATE_FORMAT_DATE).parse(stime);
Date date2 = new SimpleDateFormat(StringPool.DATE_FORMAT_DATE).parse(etime);
long day = (date1.getTime()-date2.getTime())/(24*60*60*1000)>0 ? (date1.getTime()-date2.getTime())/(24*60*60*1000):
(date2.getTime()-date1.getTime())/(24*60*60*1000);
dateArr = new String[Integer.valueOf(String.valueOf(day+1))];
for(int idx=0;idx<dateArr.length;idx++){
if(idx==0){
dateArr[idx] = stime;
}else{
stime = addOneDay(stime);
stime = stime.substring(6,10)+"-"+stime.substring(0,2)
+"-"+stime.substring(3,5);
dateArr[idx] = stime;
}
}
} catch (ParseException e) {
e.printStackTrace();
}
return dateArr;
}
/**
* 推迟的天数
* String formatter 返回格式化的时间
* int delayDate 负数为推迟的的时间 整数为往后的时间 eg 当前时间为2016-04-05 -1 2016-04-04 1 2016-04-06
* @return
*/
public static String getDelayDate(int delayDate,String formatter){
if(formatter == null || formatter.equals("")){
formatter="yyyy-MM-dd";
}
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE,calendar.get(Calendar.DATE)+delayDate);
date = calendar.getTime();
SimpleDateFormat dateFormater=new SimpleDateFormat(formatter);
return dateFormater.format(date);
}
/**
* 推迟的天数
* String formatter 返回时间类型
* int delayDate 负数为推迟的的时间 整数为往后的时间 eg 当前时间为2016-04-05 -1 2016-04-04 1 2016-04-06
* @return
*/
public static Date getDelayDayDateBy(int delayDate){
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE,calendar.get(Calendar.DATE)+delayDate);
date = calendar.getTime();
return date;
}
/**
* 推迟的月数
* String formatter 返回格式化的时间
* int delayDate 负数为推迟的的时间 整数为往后的时间 eg 当前时间为2016-04-05 -1 2016-03-05 1 2016-05-05
* @return
*/
public static String getDelayMonth(int delayMonth,String formatter){
if(formatter == null || formatter.equals("")){
formatter="yyyy-MM-dd";
}
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(calendar.MONTH, delayMonth); //设置为前3月
date = calendar.getTime();
SimpleDateFormat dateFormater=new SimpleDateFormat(formatter);
return dateFormater.format(date);
}
/**
* 获得格式化后的时间
* @param args
*/
public static String getformatterDate(Date date,String formatter){
if(formatter == null || formatter.equals("")){
formatter="yyyy-MM-dd";
}
SimpleDateFormat dateFormater=new SimpleDateFormat(formatter);
return dateFormater.format(date);
}
/**
* 获得格式化后的当前时间
* @param args
*/
public static String getformatterCurrentDate(String formatter){
if(formatter == null || formatter.equals("")){
formatter="yyyy-MM-dd";
}
SimpleDateFormat dateFormater=new SimpleDateFormat(formatter);
return dateFormater.format(new Date());
}
/**
* 获得两个开始时间相差的年数
* @param start
* @param end
* @return
*/
public static Long getIntervalYear(Date start,Date end){
long i= (end.getTime() - start.getTime())/(1000*60*60*24);
return i/365;
}
/**
* 获得两个开始时间相差的月数
/**
*
* @param date1 <String>
* @param date2 <String>
* @return int
* @throws ParseException
*/
public static int getMonthSpace(String date1, String date2)
{
int result = 0;
SimpleDateFormat sdf = new SimpleDateFormat(StringPool.DATE_FORMAT_MONTH);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
try {
c1.setTime(sdf.parse(date1));
c2.setTime(sdf.parse(date2));
} catch (ParseException e) {
e.printStackTrace();
logger.error("Pase the Date occur errors:"
+ e.getMessage());
}
int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
int month = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
result=year*12+month;
return result;
}
public static int compare(String s1, String s2,String formatter) {
int flag = 0;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatter);
try {
Date d1 = simpleDateFormat.parse(s1);
Date d2 = simpleDateFormat.parse(s2);
if (d1.getTime() > d2.getTime()) {
flag = 1;
}else if(d1.getTime() == d2.getTime()){
flag = 0;
}else{
flag = -1;
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
public static void main(String[] args) throws ParseException {
// String dsd="2015-05-02";
// String dsds=DateUtil.addMonth(dsd, "yyyy-MM", 1);
// String ds="";
String sartDate="2015-10-10", endDate="2016-5-10";
int dsd=DateUtil.getMonthSpace(sartDate, endDate);
String ds="";
}
}
| [
"[email protected]"
] | |
f404eb24c8bd0ccc330cc869cf6ddbc0da169fdf | e0e76e0d32bc696b67d4af0f6b4ae1ae917e1dcc | /JankenGame/src/se/t1835039/janken/entity/RockStrategy.java | ad530c8896c2322d1c7dfa21d0564f18b84f77fc | [] | no_license | terakawakohei/software-dev | 973021488647130a7a1080bcc955f8f590c76d00 | eee6d034ed0abcc2e6d6ca66c0f5d5d048f94b2b | refs/heads/main | 2023-04-17T12:42:53.533333 | 2021-05-07T10:02:48 | 2021-05-07T10:02:48 | 365,191,120 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 142 | java | package se.t1835039.janken.entity;
public class RockStrategy implements Strategy{
public int getHand(int playerHandNum) {
return 0;
}
}
| [
"[email protected]"
] | |
11f3bafdf85d263d9c525495365b1ddbfc0fcb8e | 4eea13dc72e0ff8ec79c7a94deca38e55868b603 | /chapter9/RanderFactory.java | c411914348d2f2713b11ece2800c49767fd47313 | [
"Apache-2.0"
] | permissive | helloShen/thinkinginjava | 1a9bfad9afa68b226684f6e063e9fa2ae36d898c | 8986b74b2b7ea1753df33af84cd56287b21b4239 | refs/heads/master | 2021-01-11T20:38:09.259654 | 2017-03-07T03:52:54 | 2017-03-07T03:52:54 | 79,158,702 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 535 | java | /**
* Chapter 9 - Exercise 19
* @author [email protected]
* @version 1.0
*/
package com.ciaoshen.thinkinjava.chapter9;
import java.util.*;
/**
* Only package access
*/
interface RanderFactory {
/**
* PUBLIC PROXY OF CONSTUCTOR
*/
/**
* METHODS
*/
public Rander getRander();
/**
* PRIVATE CONSTRUCTOR
*/
/**
* PRIVATE FIELDS
*/
/**
* MAIN void
*/
public static void main(String[] args){
}
} | [
"[email protected]"
] | |
8967e273eeddfdfecb3152f720b9b1b57f3fa479 | dcaa50a2d98d42b5f72dcef67b24f65ca30c2519 | /app/src/main/java/com/xxp/zcoder/miaomusic/classify/view/ClassifyDeletegate.java | 96c39f793eb57fb99f3e2061f476cdee22e09605 | [] | no_license | miaoMiaoDaShi/MiaoMusic | b7abf1b8ea15d858ab138ce1cf6dd042cfc87928 | 52031a3195ecbe15b9cb2aaca847e4bbc1b2a48c | refs/heads/master | 2020-03-28T20:48:50.895796 | 2017-06-18T02:41:45 | 2017-06-18T02:41:45 | 94,615,230 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 431 | java | package com.xxp.zcoder.miaomusic.classify.view;
import com.xxp.zcoder.miaomusic.R;
import com.xxp.zcoder.mvp.view.AppDelegate;
/**
* Created by Zcoder
* Email : [email protected]
* Time : 2017/6/14
* Description :
*/
public class ClassifyDeletegate extends AppDelegate {
@Override
public void initView() {
}
@Override
protected int getRootLayoutId() {
return R.layout.fragment_home;
}
}
| [
"[email protected]"
] | |
cb4f684fdbd536eae0c69b7f4e35ed45ff0b1bda | aa7ae88b5d6aeae4c73b944e4f44191558f5b9e4 | /src/test/java/com/evil/concurrency/BoundedBufferTest.java | 7e93ea0d5ce63fe2b00f3aea375e36c7f294dc72 | [] | no_license | abchyw/lab | da0524998430a94ab06509de5619ee0e5d6068fb | 86d2d19eeb1490ced8dd6fe43ae90d7723cc3674 | refs/heads/main | 2023-06-13T02:17:34.966423 | 2021-07-10T11:07:19 | 2021-07-10T11:07:19 | 382,810,311 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,692 | java | package com.evil.concurrency;
import lombok.val;
import org.junit.jupiter.api.Test;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
class BoundedBufferTest {
private static final long LOCKUP_DETECT_TIMEOUT = 5;
@Test
void isEmptyWhenConstructed() {
// when
val bb = new BoundedBuffer<Integer>(10);
// then
assertThat(bb.isEmpty()).isTrue();
assertThat(bb.isFull()).isFalse();
}
@Test
void isFullWhenPuts() throws InterruptedException, BrokenBarrierException {
// when
val barrier = new CyclicBarrier(3);
val bb = new BoundedBuffer<Integer>(10);
new Thread(() -> {
try {
barrier.await();
} catch (Exception e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 5; i++) {
try {
bb.put(i);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
try {
barrier.await();
} catch (Exception e) {
throw new RuntimeException(e);
}
}).start();
new Thread(() -> {
try {
barrier.await();
} catch (Exception e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 5; i++) {
try {
bb.put(i);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
try {
barrier.await();
} catch (Exception e) {
throw new RuntimeException(e);
}
}).start();
barrier.await();
barrier.await();
// then
assertThat(bb.isFull()).isTrue();
assertThat(bb.isEmpty()).isFalse();
}
@Test
void takeCanBeBlockedWhenEmpty() {
val buff = new BoundedBuffer<Integer>(10);
// when
val taker = new Thread(() -> {
try {
int unused = buff.take();
fail();
} catch (InterruptedException success) {
}
});
try {
taker.start();
Thread.sleep(LOCKUP_DETECT_TIMEOUT);
taker.interrupt();
taker.join(LOCKUP_DETECT_TIMEOUT);
assertThat(taker.isAlive()).isFalse();
} catch (Exception unexpected) {
fail();
}
}
} | [
"[email protected]"
] | |
9a48aa19c4d328501fa3ba09f4f71bae438ea112 | c380c589201236cf8a3b9236f08907b1825c6086 | /src/main/java/entities/CovidStatsResponse.java | 45b8499b358e1b7e1ff78c3e88bb285eea327323 | [] | no_license | pavankumar-cse88/covid-stats | fd268f5a16b220db41b3cfb3133a97b272f34e50 | 544657dcc8a148c64c34739263ec8678320a1d25 | refs/heads/master | 2023-04-29T04:56:23.205473 | 2021-05-16T14:15:29 | 2021-05-16T14:15:29 | 367,575,784 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,711 | java | package entities;
import com.google.gson.annotations.SerializedName;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class CovidStatsResponse {
private String lastupdated;
@SerializedName("Andaman and Nicobar Islands")
private AndamanandNicobarIslands andamanandNicobarIslands;
@SerializedName("Andhra Pradesh")
private AndhraPradesh andhraPradesh;
@SerializedName("Assam")
private Assam assam;
@SerializedName("Bihar")
private Bihar bihar;
@SerializedName("Chandigarh")
private Chandigarh chandigarh;
@SerializedName("Chhattisgarh")
private Chhattisgarh chhattisgarh;
@SerializedName("Dadra and Nagar Haveli and Daman and Diu")
private DadraAndNagarHaveliAndDamanAndDiu dadraAndNagarHaveliAndDamanAndDiu;
@SerializedName("Delhi")
private Delhi delhi;
@SerializedName("Goa")
private Goa goa;
@SerializedName("Gujarat")
private Gujarat gujarat;
@SerializedName("Haryana")
private Haryana haryana;
@SerializedName("Himachal Pradesh")
private HimachalPradesh himachalPradesh;
@SerializedName("Jammu and Kashmir")
private JammuAndKashmir jammuAndKashmir;
@SerializedName("Jharkhand")
private Jharkhand jharkhand;
@SerializedName("Karnataka")
private Karnataka karnataka;
@SerializedName("Kerala")
private Kerala kerala;
@SerializedName("Ladakh")
private Ladakh ladakh;
@SerializedName("Lakshadweep")
private Lakshadweep lakshadweep;
@SerializedName("Madhya Pradesh")
private MadhyaPradesh madhyaPradesh;
@SerializedName("Maharashtra")
private Maharashtra maharashtra;
@SerializedName("Manipur")
private Manipur manipur;
@SerializedName("Meghalaya")
private Meghalaya meghalaya;
@SerializedName("Mizoram")
private Mizoram mizoram;
@SerializedName("Nagaland")
private Nagaland nagaland;
@SerializedName("Odisha")
private Odisha odisha;
@SerializedName("Puducherry")
private Puducherry puducherry;
@SerializedName("Punjab")
private Punjab punjab;
@SerializedName("Rajasthan")
private Rajasthan rajasthan;
@SerializedName("Sikkim")
private Sikkim sikkim;
@SerializedName("Tamil Nadu")
private TamilNadu tamilNadu;
@SerializedName("Telangana")
private Telangana telangana;
@SerializedName("Total")
private Total total;
@SerializedName("Tripura")
private Tripura tripura;
@SerializedName("Uttarakhand")
private Uttarakhand uttarakhand;
@SerializedName("Uttar Pradesh")
private UttarPradesh uttarPradesh;
@SerializedName("West Bengal")
private WestBengal westBengal;
}
| [
"[email protected]"
] | |
018f7bdfe829faa5011b310dcbc44d6fed8b7632 | 8cc62826d237e7e9dcb77b9fc349d64c899f849e | /kawal-kabinet/src/java/km/login.java | 848ae6917a95361ee3d0f624b212a288bb5e276a | [] | no_license | thorgio/kawalmenteri | d26f7930edcb883e59b7f418fa382473c7a45e4f | 0571d2897af97b1b4d3df2426db6052852e06035 | refs/heads/master | 2020-04-06T04:38:45.888419 | 2014-11-04T15:44:01 | 2014-11-04T15:44:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,227 | java | package km;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.RequestToken;
import facebook4j.Facebook;
import facebook4j.FacebookFactory;
import facebook4j.conf.ConfigurationBuilder;
public class login
extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String form_action = request.getParameter("form_action");
if (form_action == null) {
form_action = "";
}
PrintWriter out = response.getWriter();
if (form_action.equalsIgnoreCase("getStart")) {
StringBuffer sb = new StringBuffer();
LinkedHashMap record = new LinkedHashMap();
record.put("status", "NOTOK");
record.put("login", "NOTOK");
record.put("user", new LinkedHashMap());
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String uploadurl = blobstoreService.createUploadUrl("/upload");
record.put("uploadurl", uploadurl);
JSONObject user;
try {
user = common.getUserAccount(request);
common.putTable(user);
} catch (Exception e) {
user = null;
}
if (user == null) {
record.put("login", "NOTOK");
} else {
record.put("login", "OK");
}
record.put("user", user);
try {
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
JSONArray input = (JSONArray) JSONValue.parse(sb.toString());
int i = Integer.parseInt(input.get(0).toString());
int y = Integer.parseInt(input.get(1).toString());
getIKM(record, i, y);
record.put("status", "OK");
} catch (Exception e) {
}
response.setContentType("text/html;charset=UTF-8");
out.print(JSONValue.toJSONString(record));
out.flush();
}
if (form_action.equalsIgnoreCase("cekauth")) {
JSONObject user = new JSONObject();
user.put("status", "NOTOK");
LinkedHashMap record = new LinkedHashMap();
try {
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
user.put("id", Long.valueOf(twitter.getId()));
user.put("ScreenName", twitter.getScreenName());
User u = twitter.showUser(twitter.getId());
user.put("BiggerProfileImageURL", u.getBiggerProfileImageURL());
user.put("Description", u.getDescription());
user.put("first_name", u.getName());
user.put("name", u.getName());
user.put("last_name", "");
user.put("timezone", u.getTimeZone());
user.put("locale", u.getLang());
user.put("type", "t");
user.put("Location", u.getLocation());
user.put("url", u.getURL());
user.put("link", "https://twitter.com/" + twitter.getScreenName());
user.put("email", "");
user.put("status", "OK");
getIKM(record, 0, 0);
} catch (Exception e) {
request.getSession().removeAttribute("twitter");
}
record.put("user", user);
out.print(JSONValue.toJSONString(record));
out.flush();
}
if (form_action.equalsIgnoreCase("login")) {
Twitter twitter = new TwitterFactory().getInstance();
request.getSession().setAttribute("userAccount", twitter);
String rurl = request.getParameter("rurl");
try {
StringBuffer callbackURL = request.getRequestURL();
int index = callbackURL.lastIndexOf("/");
callbackURL.replace(index, callbackURL.length(), "").append("/callback?rurl=" + rurl);
RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
request.getSession().setAttribute("requestToken", requestToken);
response.sendRedirect(requestToken.getAuthenticationURL());
} catch (TwitterException e) {
request.getSession().removeAttribute("twitter");
}
}
if (form_action.equalsIgnoreCase("loginfb")) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setRestBaseURL("https://graph.facebook.com/v2.1/")
.setOAuthAppId("1519572904939148")
.setOAuthAppSecret("eb21d4f9e1aa2b4e02b510ecd3d71eb1")
.setUseSSL(true)
.setJSONStoreEnabled(true)
.setOAuthPermissions("email,public_profile,user_friends,publish_actions");
Facebook facebook = new FacebookFactory(cb.build()).getInstance();
request.getSession().setAttribute("userAccount", facebook);
StringBuffer callbackURL = request.getRequestURL();
int index = callbackURL.lastIndexOf("/");
callbackURL.replace(index, callbackURL.length(), "").append("/callbackfb");
response.sendRedirect(facebook.getOAuthAuthorizationURL(callbackURL.toString()) + "&display=popup");
}
if (form_action.equalsIgnoreCase("logout")) {
JSONObject user = common.getUserAccount(request);
request.getSession().invalidate();
if (user.get("type").toString().equalsIgnoreCase("fb")) {
response.setContentType("text/html;charset=UTF-8");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<link href=\"images/icon3_1.png\" rel=\"shortcut icon\" type=\"image/x-icon\" /><title>KawalMenteri #MengawalMandatRakyat</title>");
out.println("<script src=\"/js/logout.js\"></script>");
out.println("</head>");
out.println("<body>Sedang Log Out...</body>");
out.println("</html>");
} else {
response.sendRedirect("/");
}
}
}
private void getIKM(LinkedHashMap record, int i, int y) {
try {
if (i == 0) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query query = new Query("indexKM");
List<Entity> from = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
Gson gson = new Gson();
record.put("indexKM", JSONValue.parse(gson.toJson(from)));
}
} catch (Exception e) {
}
try {
if (y == 0) {
InputStream feedStream = new FileInputStream("data/base.json");
InputStreamReader is = new InputStreamReader(feedStream);
StringBuilder sb1 = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while (read != null) {
sb1.append(read);
read = br.readLine();
}
Object obj0 = JSONValue.parse(sb1.toString());
JSONArray bases = (JSONArray) obj0;
record.put("bases", bases);
}
} catch (Exception e) {
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}
}
| [
"[email protected]"
] | |
c4a3260e94ef6dbbfc48e2cec0e5abea55e7e407 | c17ee24560d628942911b7b5c87f06dadca7fb6a | /src/com/tasks/task_6/Cargo.java | 974e2ad0234026eb0d9ef042d3f981906599ab2f | [] | no_license | KaPToLLIkA/SENLA_tasks_2020 | b28d5547a291e12f6bcf8c02e8da7efd8f878a04 | 292895cda62cef964a5abc6c4d657ca35d6b189a | refs/heads/master | 2022-07-06T10:18:02.800317 | 2020-05-10T14:41:36 | 2020-05-10T14:41:36 | 262,784,469 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 546 | java | package com.tasks.task_6;
import java.util.ArrayList;
class Cargo {
private ArrayList<Item> items = new ArrayList<>();
public Cargo(Cargo oldCargo) {
this.items = new ArrayList<>(oldCargo.items);
}
public Cargo() {}
public Item getItem(int index) {
return items.get(index);
}
public void addItem(Item newItem) {
items.add(newItem);
}
public int getSize() {
return items.size();
}
@Override
public String toString() {
return items.toString();
}
}
| [
"[email protected]"
] | |
30ba67840c27327bee8f84b67f1e00ec8375d30c | 589e632364685e653d248d11e9b23e61a74578f2 | /tnt-bms-pusher/src/main/java/com/lvmama/bms/pusher/protocol/domain/PusherLoader.java | 2e68ac150560b2648a97fc8a1fa87d7947649694 | [] | no_license | wang-shun/push-plat | e94ebb7f8db4a5272b9b402562044d01b19cb70e | 8eabd192d8e51c6d0368c4627623f22d8a1ce9d1 | refs/heads/master | 2020-03-29T10:01:07.467156 | 2018-09-21T08:40:05 | 2018-09-21T08:40:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 821 | java | package com.lvmama.bms.pusher.protocol.domain;
public class PusherLoader {
private String targetClass;
private ClassLoader classLoader;
private Integer version;
public String getTargetClass() {
return targetClass;
}
public void setTargetClass(String targetClass) {
this.targetClass = targetClass;
}
public ClassLoader getClassLoader() {
return classLoader;
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
@Override
public String toString() {
return "targetClass=" + targetClass +
"|version=" + version;
}
}
| [
"[email protected]"
] | |
ef5b9954a89b507f28ba2598f6ca288cb874d054 | b30578997715217ded97f32f49b08916277402af | /app/src/main/java/com/example/bankproject/DAO/BTransDAO.java | 6d3b6483e49592b4d2f26ae06458a8f142636b65 | [] | no_license | g84silva/android-bank-project | 477a8f9ca2f393757132c9ea1836ed884c30fd75 | e8ab934e746c5bb539df496a660ce620281433fb | refs/heads/master | 2022-12-03T23:48:44.554310 | 2020-08-26T04:27:05 | 2020-08-26T04:27:05 | 288,877,045 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 847 | java | package com.example.bankproject.DAO;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import com.example.bankproject.Model.BankTransaction;
import java.util.List;
@Dao
public interface BTransDAO {
@Insert(onConflict = OnConflictStrategy.IGNORE)
void insertAllBTransDAO(List<BankTransaction> bankTransactions);
@Insert(onConflict = OnConflictStrategy.IGNORE)
void insertBTransDAO(BankTransaction bankTransaction);
@Query("SELECT * FROM TransBancaria")
List<BankTransaction> getAllBTransDAO();
// @Query("SELECT * FROM ContaBancaria WHERE bTransServer_id LIKE :bTransServer_id")
// BankTransaction getBTransDAO(String bTransServer_id);
@Update
void updateAccDAO(BankTransaction bankTransaction);
}
| [
"[email protected]"
] | |
b311bf422d76c82106206e7e28abe743a044a649 | a630af9c3edf50d0739a977ef84b7aad9f3207ad | /FinaliseAndroidApp/src/com/coursesexempted/Model.java | b0ab6b5202b795d6a8ed30f6d694b20640c437c1 | [] | no_license | vantuantran/OnlineProjects | 72aaf7f88cf8be0a5180e082ba30929524df511e | 4290f845f3f4759dccc2b44083f3bf3d3ddea70c | refs/heads/master | 2016-08-02T23:30:17.525396 | 2012-09-12T15:40:54 | 2012-09-12T15:40:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 444 | java | package com.coursesexempted;
public class Model {
private String name;
private boolean selected;
public Model(String name) {
this.name = name;
selected = false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
| [
"[email protected]"
] | |
69fcba5243fa790d49345af7d4fe8cf7d83a152d | 4129d2355c7bc2fde0be94a5f4bb3e470a40674b | /driver/src/test/java/org/neo4j/driver/internal/value/ListValueTest.java | aaf4c9a4d84b0adead6acaa0a5cc280cfe2238e9 | [
"Apache-2.0"
] | permissive | RagnarW/neo4j-java-driver | f817683093fc64055087641695e4b139c75068c0 | 93c26a19cab85501b9fc101bd6acffceee5528ce | refs/heads/1.0 | 2020-12-03T06:37:19.670958 | 2015-12-11T16:39:35 | 2015-12-11T16:39:35 | 48,048,327 | 0 | 0 | null | 2015-12-15T14:35:43 | 2015-12-15T14:35:43 | null | UTF-8 | Java | false | false | 2,370 | java | /**
* Copyright (c) 2002-2015 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neo4j.driver.internal.value;
import org.junit.Test;
import org.neo4j.driver.internal.types.InternalTypeSystem;
import org.neo4j.driver.v1.Value;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.neo4j.driver.v1.Values.value;
public class ListValueTest
{
@Test
public void shouldHaveSensibleToString() throws Throwable
{
ListValue listValue = listValue( value( 1 ), value( 2 ), value( 3 ) );
assertThat( listValue.toString(), equalTo( "[1, 2, 3] :: LIST OF ANY?" ) );
}
@Test
public void shouldHaveCorrectType() throws Throwable
{
ListValue listValue = listValue();
assertThat(listValue.type(), equalTo( InternalTypeSystem.TYPE_SYSTEM.LIST() ));
}
@Test
public void testConversionsFromListValue() throws Throwable
{
ListValue listValue = listValue( value( 1 ), value( 2 ), value( 3 ) );
assertThat( listValue.asArray(), equalTo( new Value[]{value( 1 ), value( 2 ), value( 3 )} ) );
assertThat( listValue.asByteArray(), equalTo( new byte[]{1, 2, 3} ) );
assertThat( listValue.asDoubleArray(), equalTo( new double[]{1D, 2D, 3D} ) );
assertThat( listValue.asFloatArray(), equalTo( new float[]{1F, 2F, 3F} ) );
assertThat( listValue.asIntArray(), equalTo( new int[]{1, 2, 3} ) );
assertThat( listValue.asLongArray(), equalTo( new long[]{1L, 2L, 3L} ) );
assertThat( listValue.asShortArray(), equalTo( new short[]{1, 2, 3} ) );
}
private ListValue listValue( Value... values )
{
return new ListValue( values );
}
}
| [
"[email protected]"
] | |
fc76fe679128f9a64a58fae8c26c2cec0b580aa7 | 35d8fd9143c2aba153469551c73094ce7b8af344 | /Core/src/main/java/com/rob/core/repositories/RoleRepository.java | cf9182f21d332701693e3361def244c7b739a8da | [] | no_license | Rob097/MyPortfolio-Backend | ec02b3b020cd360b5bf94a432ffc9e9201c34b92 | ce79c68567e5a75e8ff2eae320faba09ca61e3dc | refs/heads/master | 2023-09-02T18:50:50.282958 | 2021-11-23T11:21:33 | 2021-11-23T11:21:33 | 402,863,659 | 0 | 0 | null | 2021-09-11T14:30:12 | 2021-09-03T18:24:59 | Java | UTF-8 | Java | false | false | 3,791 | java | package com.rob.core.repositories;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Repository;
import com.rob.core.database.RoleManagerQuery;
import com.rob.core.database.RoleSearchCriteria;
import com.rob.core.fetch.RoleFetchHandler;
import com.rob.core.fetch.modules.Fetch;
import com.rob.core.fetch.modules.FetchBuilder;
import com.rob.core.models.SYS.Role;
import com.rob.core.utils.db.PreparedStatementBuilder;
@Repository
public class RoleRepository implements IRoleRepository {
@Autowired
private DataSource dataSource;
private final RoleManagerQuery queryFactory;
@Autowired
private RoleFetchHandler fetchHandler;
public RoleRepository() {
queryFactory = new RoleManagerQuery();
}
@Override
public Role findById(Integer id) throws SQLException {
Validate.notNull(id, "Parametro obbligatorio mancante: identificativo ruolo.");
return this.findById(id, FetchBuilder.none());
}
@Override
public Role findById(Integer id, Fetch fetch) throws SQLException {
Validate.notNull(id, "Parametro obbligatorio mancante: identificativo utente.");
RoleSearchCriteria criteria = new RoleSearchCriteria();
criteria.setId(id);
criteria.setFetch(fetch);
return this.findSingleByCriteria(criteria);
}
@Override
public Role findSingleByCriteria(RoleSearchCriteria criteria) throws SQLException {
Validate.notNull(criteria, "Parametro obbligatorio mancante.");
if(criteria.getRange() == null) {
criteria.setMaxRows(1);
}
List<Role> results = this.findByCriteria(criteria);
if (results != null && !results.isEmpty()) {
return results.iterator().next();
}
return null;
}
@Override
public List<Role> findByCriteria(RoleSearchCriteria criteria) throws SQLException {
Validate.notNull(criteria, "Parametro obbligatorio mancante.");
List<Role> results = new ArrayList<>();
Fetch fetch = criteria.getFetch();
try(
PreparedStatementBuilder bld = queryFactory.sqlFindByCriteria(criteria);
Connection conn = DataSourceUtils.getConnection(dataSource);
ResultSet rst = bld.executeQuery(conn);
){
while(rst.next()) {
Role role = new Role(rst);
fetchHandler.handle(role, fetch, rst);
results.add(role);
}
}
return results;
}
@Override
public Role create(Role data) throws SQLException {
Validate.notNull(data, "Oggetto non valido.");
Validate.notNull(data.getId(), "Parametro obbligatorio mancante: Identificativo ruolo");
/*String id = this.sysModuleService.getCounterMaster(SYSCounterEnum.LOG_ID.getId(), 100);
data.setId(id);*/
try
(PreparedStatementBuilder psb = this.queryFactory.sqlCreate(data))
{
Connection con = DataSourceUtils.getConnection(dataSource);
psb.executeUpdate(con);
}
return data;
}
@Override
public int createPermissionsRelations(int roleId, int permissionId) throws SQLException {
int created = 0;
try
(PreparedStatementBuilder psb = this.queryFactory.sqlCreatePermissionsRelations(roleId, permissionId))
{
Connection con = DataSourceUtils.getConnection(dataSource);
created = psb.executeUpdate(con);
}
return created;
}
@Override
public int deleteAllPermissionsRelations(int roleId) throws SQLException {
int created = 0;
try
(PreparedStatementBuilder psb = this.queryFactory.sqlDeleteAllPermissionsRelations(roleId))
{
Connection con = DataSourceUtils.getConnection(dataSource);
created = psb.executeUpdate(con);
}
return created;
}
}
| [
"[email protected]"
] | |
2466433cfac7628b3d5bf898fc91017dd293f327 | 4d101850b278fe19cb8ec186fcb54ee5313772c8 | /app/src/main/java/com/example/ktsdemo/util/FileUtils.java | 3f2dee17f7fe20378e082a3bdf74356bc06c17b8 | [
"Apache-2.0"
] | permissive | merlin720/ktsTest | 1101e6c7c64449d91bccbe78d39cc127e97e02e0 | f1a57a57d609bccf33004d21916ae784a83fa7d5 | refs/heads/master | 2020-06-22T07:58:44.737523 | 2019-08-30T05:51:39 | 2019-08-30T05:51:39 | 197,676,574 | 0 | 0 | null | 2019-07-31T07:58:20 | 2019-07-19T00:54:25 | Java | UTF-8 | Java | false | false | 4,525 | java | package com.example.ktsdemo.util;
import android.content.res.AssetManager;
import android.util.Log;
import com.github.mikephil.charting.data.Entry;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import lecho.lib.hellocharts.model.PointValue;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author merlin720
* @date 2019-07-13
* @mail [email protected]
* @description
*/
public class FileUtils {
/**
* 项目里assets文件里的内容
*
* @param am manager
* @param path 路径 就是名字
* @return 返回list
*/
public static List<PointValue> load1Data(AssetManager am, String path) {
List<PointValue> entries = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(am.open(path), "UTF-8"));
String line = reader.readLine();
while (null != line) {
String s = line.replace("\t", "#");
String[] split = s.split("#");
//Log.e("merlin", split.length+"" + split[0]);
entries.add(new PointValue(Float.parseFloat(split[0]), Float.parseFloat(split[1])));
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e("merlin", e.toString());
}
}
}
return entries;
}
public static List<Entry> loadData(AssetManager am, String path) {
List<Entry> entries = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(am.open(path), "UTF-8"));
String line = reader.readLine();
while (null != line) {
String s = line.replace("\t", "#");
String[] split = s.split("#");
//Log.e("merlin", split.length+"" + split[0]);
entries.add(new Entry(Float.parseFloat(split[0]), Float.parseFloat(split[1])));
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e("merlin", e.toString());
}
}
}
return entries;
}
/**
* 把返回结果转换成list
*/
public static List<Entry> loadData(String str) {
List<Entry> entries = new ArrayList<>();
try {
Type type = new TypeToken<ArrayList<String>>() {
}.getType();
Gson gson = new Gson();
Log.e("merlin", str);
List<String> list = gson.fromJson(str, type);
for (String line : list) {
String s = line.replace("\t", "#");
String[] split = s.split("#");
if (null != split[0] && null != split[1]) {
entries.add(new Entry(Float.parseFloat(split[0]), Float.parseFloat(split[1])));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return entries;
}
/**
* 把返回结果转换成list
*/
public static List<Entry> loadData(List<String> list) {
List<Entry> entries = new ArrayList<>();
try {
for (String line : list) {
String s = line.replace("\t", "#");
String[] split = s.split("#");
if (null != split[0] && null != split[1]) {
entries.add(new Entry(Float.parseFloat(split[0]), Float.parseFloat(split[1])));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return entries;
}
public static List<String> getFilesInPath(String path) {
List<String> list = new ArrayList<>();
File file = new File(path);
File[] array = file.listFiles();
for (int i = 0; i < array.length; i++) {
if (array[i].isFile()) {
String name = array[i].getName();
if (name.endsWith(".dat")) {
list.add(array[i].getName());
}
// only take file name
System.out.println("^^^^^" + array[i].getName());
// take file path and name
System.out.println("#####" + array[i]);
// take file path and name
System.out.println("*****" + array[i].getPath());
} else if (array[i].isDirectory()){
getFilesInPath(array[i].getPath());
}
}
return list;
}
}
| [
"[email protected]"
] | |
2156896a560a4b8789f15f771a2079494f49c7de | cbdd1768cd6747cee6d91c42c62b9913ddfbcb24 | /src/test/java/org/osgl/issues/g79/Bean.java | 640b777f3c51cfd232d430c16edf2ec3d1ec0fd2 | [
"Apache-2.0"
] | permissive | osglworks/java-tool | 4df56e65dd1cfe4e18f19f852139c079a64f7feb | 3e60f5b35b18c0ba75c664b24a70e2cdb79ac15c | refs/heads/master | 2022-11-29T17:12:14.508458 | 2022-11-25T23:23:26 | 2022-11-25T23:23:26 | 10,664,256 | 60 | 21 | Apache-2.0 | 2022-11-25T20:17:36 | 2013-06-13T10:52:28 | Java | UTF-8 | Java | false | false | 810 | java | package org.osgl.issues.g79;
/*-
* #%L
* Java Tool
* %%
* Copyright (C) 2014 - 2018 OSGL (Open Source General Library)
* %%
* 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.
* #L%
*/
import java.util.List;
import java.util.Map;
public class Bean {
public Map<String, List<Bar>> barMap;
}
| [
"[email protected]"
] | |
b594fa1777a1706a919ea2a86cd474f5bc9d0d9a | 9a69e47b85adcb0c3c0092719a7d4570755747b1 | /selva/src/style.java | 97242bc0a2db1b49c038ec7d38d39e1c7c55ae03 | [] | no_license | brahimcah/SELVA | ac233f68c71ca6fced150a35b03babe2b3f14c51 | a119a45ec637411b4d4265fcf26d9218bdc4dfea | refs/heads/main | 2023-08-24T01:57:42.782560 | 2021-11-01T00:02:52 | 2021-11-01T00:02:52 | 421,840,227 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 134 | java | import acm.graphics.*;
import acm.program.*;
import acm.util.*;
import java.awt.*;
public class style extends GraphicsProgram {
}
| [
"[email protected]"
] | |
0ffe7d5c448f332a075fe8d5db697efb176d42e3 | be73270af6be0a811bca4f1710dc6a038e4a8fd2 | /crash-reproduction-moho/results/XWIKI-13138-17-4-NSGA_II-LineCoverage:ExceptionType:StackTraceSimilarity/org/xwiki/job/AbstractJob_ESTest_scaffolding.java | d1d245cdb008662bdcd5ee60177a11e311909920 | [] | no_license | STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application | cf118b23ecb87a8bf59643e42f7556b521d1f754 | 3bb39683f9c343b8ec94890a00b8f260d158dfe3 | refs/heads/master | 2022-07-29T14:44:00.774547 | 2020-08-10T15:14:49 | 2020-08-10T15:14:49 | 285,804,495 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 429 | java | /**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Tue Apr 07 07:02:08 UTC 2020
*/
package org.xwiki.job;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
@EvoSuiteClassExclude
public class AbstractJob_ESTest_scaffolding {
// Empty scaffolding for empty test suite
}
| [
"[email protected]"
] | |
1d6130debd87739bce52fb733b4e7e186b73d267 | c3702a95221e70394f431efdf458ca489ea6c3d6 | /src/gui/ProdutosListController.java | e2c5907a719a7e0dec5f925fdcbc1c7c1e7a4b1e | [] | no_license | ravel-andrade/SIG-prototype | 218a9ff1e02298ea8eca9aba260b21f28029cffc | 1f56f22576d7ff58646a31800da890ed37c72474 | refs/heads/master | 2023-03-03T20:53:22.706713 | 2021-02-04T19:11:16 | 2021-02-04T19:11:16 | 315,397,815 | 0 | 0 | null | null | null | null | WINDOWS-1250 | Java | false | false | 5,420 | java | package gui;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import application.Main;
import db.DbIntegrityException;
import gui.listeners.DataChangeListener;
import gui.util.Alerts;
import gui.util.Utils;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.Pane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import model.Entities.Produtos;
import model.services.ProdutosService;
public class ProdutosListController implements Initializable, DataChangeListener {
private ProdutosService service;
@FXML
private TableView<Produtos> tableViewProdutos;
@FXML
private TableColumn<Produtos, String> tableColumnNome;
@FXML
private TableColumn<Produtos, Integer> tableColumnId;
@FXML
private TableColumn<Produtos, Double> tableColumnCustoVarDireto;
@FXML
private TableColumn<Produtos, Double> tableColumnCustoVarIndireto;
@FXML
private TableColumn<Produtos, Produtos> tableColumnEDIT;
@FXML
private TableColumn<Produtos, Produtos> tableColumnREMOVE;
@FXML
private Button btNew;
private ObservableList<Produtos> obsList;
@FXML
public void onBtNewAction(ActionEvent event) {
Stage parentStage = Utils.currentStage(event);
Produtos obj = new Produtos();
createDialogForm(obj, "/gui/ProdutosForm.fxml", parentStage);
}
public void setProdutosService(ProdutosService service) {
this.service = service;
}
@Override
public void initialize(URL url, ResourceBundle rb) {
initializeNodes();
}
private void initializeNodes() {
tableColumnId.setCellValueFactory(new PropertyValueFactory<>("id"));
tableColumnNome.setCellValueFactory(new PropertyValueFactory<>("nome"));
tableColumnCustoVarDireto.setCellValueFactory(new PropertyValueFactory<>("custoVarDireto"));
tableColumnCustoVarIndireto.setCellValueFactory(new PropertyValueFactory<>("custoVarIndireto"));
Stage stage = (Stage) Main.getMainScene().getWindow();
tableViewProdutos.prefHeightProperty().bind(stage.heightProperty());
}
public void updateTableView() {
if (service == null) {
throw new IllegalStateException("Service was null");
}
List<Produtos> list = service.findAll();
obsList = FXCollections.observableArrayList(list);
tableViewProdutos.setItems(obsList);
initEditButtons();
initRemoveButtons();
}
private void createDialogForm(Produtos obj, String absoluteName, Stage parentStage) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource(absoluteName));
Pane pane = loader.load();
ProdutosFormController controller = loader.getController();
controller.setProdutos(obj);
controller.setProdutosService(new ProdutosService());
controller.subscribeDataChangeListener(this);
controller.updateFormData();
Stage dialogStage = new Stage();
dialogStage.setTitle("Adicione os dados do funcionário");
dialogStage.setScene(new Scene(pane));
dialogStage.setResizable(false);
dialogStage.initOwner(parentStage);
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.showAndWait();
} catch (IOException e) {
Alerts.showAlert("IO Exception", "Error loading view", e.getMessage(), AlertType.ERROR);
}
}
@Override
public void onDataChanged() {
updateTableView();
}
private void initEditButtons() {
tableColumnEDIT.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue()));
tableColumnEDIT.setCellFactory(param -> new TableCell<Produtos, Produtos>() {
private final Button button = new Button("Editar");
@Override
protected void updateItem(Produtos obj, boolean empty) {
super.updateItem(obj, empty);
if (obj == null) {
setGraphic(null);
return;
}
setGraphic(button);
button.setOnAction(
event -> createDialogForm(obj, "/gui/ProdutosForm.fxml", Utils.currentStage(event)));
}
});
}
private void initRemoveButtons() {
tableColumnREMOVE.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue()));
tableColumnREMOVE.setCellFactory(param -> new TableCell<Produtos, Produtos>() {
private final Button button = new Button("Remover");
@Override
protected void updateItem(Produtos obj, boolean empty) {
super.updateItem(obj, empty);
if (obj == null) {
setGraphic(null);
return;
}
setGraphic(button);
button.setOnAction(event -> removeEntity(obj));
}
});
}
private void removeEntity(Produtos obj) {
Optional<ButtonType> result = Alerts.showConfirmation("Confirmation", "Are you sure to delete?");
if (result.get() == ButtonType.OK) {
if (service == null) {
throw new IllegalStateException("Service was null");
}
try {
service.remove(obj);
updateTableView();
}
catch (DbIntegrityException e) {
Alerts.showAlert("Error removing object", null, e.getMessage(), AlertType.ERROR);
}
}
}
}
| [
"[email protected]"
] | |
4a09dd5d689a0ea04927cc24bdd1bf7a33c21194 | 77b28adf409319d78c7cc6021693958b20f5d412 | /src/tags/search/SearchMatrix.java | 8d90c3455bb760e3e81f9ce55f5f3fdf7d339a1b | [] | no_license | iam91/interview | 90d4f9a4fd68dd0513fd293ccf8c57c454a172b3 | a9b8accf50eb709d026c0db8c8beeea352e22296 | refs/heads/master | 2021-09-12T12:02:47.126647 | 2018-04-16T14:21:37 | 2018-04-16T14:21:37 | 122,419,909 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,671 | java | package tags.search;
public class SearchMatrix {
// https://leetcode.com/problems/search-a-2d-matrix/description/
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
return searchAll(matrix, target, 0, matrix.length - 1);
}
private boolean searchAll(int[][] matrix, int target, int l, int r) {
if(l > r) return false;
int mid = (l + r) / 2;
if(matrix[mid][0] > target) {
if(l >= mid) return false;
else if(l == mid - 1) return searchRow(matrix[l], target, 0, matrix[l].length - 1);
else if(l < mid - 1) return searchAll(matrix, target, l, mid - 1);
} else if(matrix[mid][0] < target) {
if(r >= mid) return searchRow(matrix[mid], target, 0, matrix[r].length - 1)
|| searchAll(matrix, target, mid + 1, r);
}
return true;
}
private boolean searchRow(int[] arr, int target, int l, int r) {
if(l > r) return false;
int mid = (l + r) / 2;
if(arr[mid] > target) {
return searchRow(arr, target, l, mid - 1);
} else if(arr[mid] < target) {
return searchRow(arr, target, mid + 1, r);
} else {
return true;
}
}
public static void main(String[] args) {
SearchMatrix c = new SearchMatrix();
// int[][] matrix = {
// {1, 3, 5, 7},
// {10, 11, 16, 20},
// {23, 30, 34, 50}
// };
int[][] matrix = {{1}};
System.out.println(c.searchMatrix(matrix, 2));
}
}
| [
"[email protected]"
] | |
fb04bfbe9d79de1536239e36081e1196b3ff6e2a | b5f8ce4f162e41501d71aabf480bb9b8df94201b | /src/main/java/sn/seysoo/web/rest/TroupeauResource.java | 990148299961df04bf1a1dfde43fe9c173bb291c | [] | no_license | abdoulayeyoussoufa/betail | 56b589928844939a02a00b429f91471228f96000 | ddc8274f002f9e3d8618514f55b857fe79e31268 | refs/heads/master | 2020-03-23T08:09:43.006792 | 2017-05-11T12:00:29 | 2017-05-11T12:00:29 | 141,308,588 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,575 | java | package sn.seysoo.web.rest;
import com.codahale.metrics.annotation.Timed;
import sn.seysoo.domain.Troupeau;
import sn.seysoo.repository.TroupeauRepository;
import sn.seysoo.web.rest.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing Troupeau.
*/
@RestController
@RequestMapping("/api")
public class TroupeauResource {
private final Logger log = LoggerFactory.getLogger(TroupeauResource.class);
private static final String ENTITY_NAME = "troupeau";
private final TroupeauRepository troupeauRepository;
public TroupeauResource(TroupeauRepository troupeauRepository) {
this.troupeauRepository = troupeauRepository;
}
/**
* POST /troupeaus : Create a new troupeau.
*
* @param troupeau the troupeau to create
* @return the ResponseEntity with status 201 (Created) and with body the new troupeau, or with status 400 (Bad Request) if the troupeau has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/troupeaus")
@Timed
public ResponseEntity<Troupeau> createTroupeau(@Valid @RequestBody Troupeau troupeau) throws URISyntaxException {
log.debug("REST request to save Troupeau : {}", troupeau);
if (troupeau.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new troupeau cannot already have an ID")).body(null);
}
Troupeau result = troupeauRepository.save(troupeau);
return ResponseEntity.created(new URI("/api/troupeaus/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /troupeaus : Updates an existing troupeau.
*
* @param troupeau the troupeau to update
* @return the ResponseEntity with status 200 (OK) and with body the updated troupeau,
* or with status 400 (Bad Request) if the troupeau is not valid,
* or with status 500 (Internal Server Error) if the troupeau couldnt be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/troupeaus")
@Timed
public ResponseEntity<Troupeau> updateTroupeau(@Valid @RequestBody Troupeau troupeau) throws URISyntaxException {
log.debug("REST request to update Troupeau : {}", troupeau);
if (troupeau.getId() == null) {
return createTroupeau(troupeau);
}
Troupeau result = troupeauRepository.save(troupeau);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, troupeau.getId().toString()))
.body(result);
}
/**
* GET /troupeaus : get all the troupeaus.
*
* @return the ResponseEntity with status 200 (OK) and the list of troupeaus in body
*/
@GetMapping("/troupeaus")
@Timed
public List<Troupeau> getAllTroupeaus() {
log.debug("REST request to get all Troupeaus");
List<Troupeau> troupeaus = troupeauRepository.findAll();
return troupeaus;
}
/**
* GET /troupeaus/:id : get the "id" troupeau.
*
* @param id the id of the troupeau to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the troupeau, or with status 404 (Not Found)
*/
@GetMapping("/troupeaus/{id}")
@Timed
public ResponseEntity<Troupeau> getTroupeau(@PathVariable String id) {
log.debug("REST request to get Troupeau : {}", id);
Troupeau troupeau = troupeauRepository.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(troupeau));
}
/**
* DELETE /troupeaus/:id : delete the "id" troupeau.
*
* @param id the id of the troupeau to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/troupeaus/{id}")
@Timed
public ResponseEntity<Void> deleteTroupeau(@PathVariable String id) {
log.debug("REST request to delete Troupeau : {}", id);
troupeauRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
}
| [
"[email protected]"
] | |
20f68c492c4b89fe91f070355a8768b8015f725c | f0ee0f2331a55d72fc19f9a06083c657608d19d8 | /pharmacy/src/main/java/ftn/isa/team12/pharmacy/dto/ExaminationPriceDTO.java | da7655e4b7e254f9241072b209d885001e5e90bd | [] | no_license | stiven98/ISA | e0659f0fe97dd6f720ba6d03350aac63149bd951 | be1f77a98c6c4d98ebd1aab1defa658f74afced8 | refs/heads/develop | 2023-03-03T07:44:57.070857 | 2021-02-12T22:58:56 | 2021-02-12T22:58:56 | 326,386,114 | 0 | 1 | null | 2021-02-12T17:37:33 | 2021-01-03T11:02:13 | Java | UTF-8 | Java | false | false | 1,151 | java | package ftn.isa.team12.pharmacy.dto;
import ftn.isa.team12.pharmacy.domain.enums.ExaminationType;
import ftn.isa.team12.pharmacy.domain.pharmacy.ExaminationPrice;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Date;
import java.util.UUID;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ExaminationPriceDTO {
private UUID examinationPriceId;
private ExaminationType examinationType;
private double price;
private Date startDate;
private Date endDate;
public ExaminationPriceDTO(ExaminationPrice ex){
this(ex.getExaminationPriceId(),ex.getExaminationType(),ex.getPrice(),ex.getDateOfValidity().getStartDate(),ex.getDateOfValidity().getEndDate());
}
@Override
public String toString() {
return "ExaminationPriceDTO{" +
"examinationPriceId=" + examinationPriceId +
", examinationType=" + examinationType +
", price=" + price +
", startDate=" + startDate +
", endDate=" + endDate +
'}';
}
}
| [
"[email protected]"
] | |
6c0a47a45bdc6c72bba30e1361d6aa36de8783a9 | 08be4f0862fcc8dafc69f6237da9401f152f2c48 | /sprd/UniverseUI/SprdLauncher1/src/com/sprd/sprdlauncher1/effect/FadeEffect.java | d9e39d624582f4add95cf798f62ed9553653e4e7 | [
"Apache-2.0"
] | permissive | harryxiao/Sc7731-Sc8830-Vendor_Source | c41df77c7919c4b50457c3f35b55401d756301c4 | c069804190c37465c27bfd982a9b82e1241795dd | refs/heads/master | 2020-04-19T23:41:32.458177 | 2018-03-01T08:40:31 | 2018-03-01T08:40:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,331 | java | /** Created by Spreadst */
package com.sprd.launcher3.effect;
import android.content.Context;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Transformation;
import android.widget.Scroller;
public class FadeEffect extends EffectInfo{
public FadeEffect(int id) {
super(id);
}
@Override
public boolean getCellLayoutChildStaticTransformation(ViewGroup viewGroup, View viewiew,
Transformation transformation, Camera camera, float offset) {
return false;
}
@Override
public boolean getWorkspaceChildStaticTransformation(ViewGroup viewGroup, View viewiew,
Transformation transformation, Camera camera, float offset) {
if (offset == 0.0F || offset >= 1.0F || offset <= -1.0F)
return false;
Matrix tMatrix = transformation.getMatrix();
float absOffset = Math.abs(offset);
float mAlpha = (1.0F - absOffset) * 0.7F + 0.3F;
transformation.setAlpha(mAlpha);
tMatrix.setScale(mAlpha, mAlpha, viewiew.getWidth()/2.0f, viewiew.getHeight()/2.0f);
transformation.setTransformationType(Transformation.TYPE_BOTH);
// transformation.setTransformationType(Transformation.TYPE_ALPHA);
return true;
}
/* SPRD: Fix bug257614 @{ */
@Override
public void getTransformationMatrix(View view ,float offset, int pageWidth, int pageHeight, boolean overScroll, boolean overScrollLeft){
/* @} */
float absOffset = Math.abs(offset);
float mAlpha = 1.0F - absOffset;
int mViewWidth = pageWidth;
int mViewHeight = pageHeight;
int mViewHalfWidth = mViewWidth >> 1;
int mViewHalfHeight = mViewHeight >> 1;
view.setTranslationX(0f);
view.setPivotY(mViewHalfHeight);
view.setPivotX(mViewHalfWidth);
view.setRotationX(0f);
view.setRotation(0f);
view.setRotationY(0f);
view.setScaleX(1.0f);
view.setScaleY(1.0f);
view.setAlpha(mAlpha);
}
@Override
public Scroller getScroller(Context context) {
// TODO Auto-generated method stub
return new Scroller(context);
}
@Override
public int getSnapTime() {
return 240;
}
}
| [
"[email protected]"
] | |
56bf13896bc82da8d6801a835caca23023988404 | 12e784c639da90b33514ecda20c4dd6b51db50d3 | /src/main/java/brick/Jogo.java | 2203873286ebf860724af712d30cc01d3211a4fe | [] | no_license | BrendonMFO/Brick-Breaker | 8f1134e11af069113b1903ec0e8792980eea32eb | 5f2da7d2bea787a447619b8813d1ffe027fe275d | refs/heads/master | 2023-01-01T10:30:43.478935 | 2020-10-27T18:35:24 | 2020-10-27T18:35:24 | 307,786,899 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,123 | java | package brick;
import java.util.Random;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.Scene;
import java.io.IOException;
import java.util.ArrayList;
import javafx.util.Duration;
import javafx.fxml.FXMLLoader;
import javafx.scene.text.Text;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.animation.Animation;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.AnchorPane;
public class Jogo extends AnchorPane {
@FXML
private GridPane painelVida;
@FXML
private ImageView imgControle, fundo;
@FXML
private Text pontuacao;
private final Level level;
private final Prancha prancha;
private final Bolinha bolinha;
private final Scene scene;
private Timeline atualizar;
private Timeline tempoProtegido;
private Timeline tempoPassar;
private int quantidadeBlocos;
private int vida;
private float multiplicadorPontos;
private boolean protecao;
private boolean passarDireto;
public Jogo(Level _level, Scene _scene) {
this.carregarFXML();
this.scene = _scene;
this.level = _level;
this.protecao = false;
this.passarDireto = false;
this.prancha = new Prancha();
this.bolinha = new Bolinha(this.prancha);
this.quantidadeBlocos = 0;
this.multiplicadorPontos = 1.0f;
this.fundo.setImage(Recursos.getSprite("Fundo_0" + JogoConfiguracao.getInstance().getBackground()));
this.fundo.setFitHeight(1080);
this.fundo.setFitWidth(1920);
this.imgControle.setImage(Recursos.getSprite("Controle"));
this.getChildren().add(bolinha);
this.getChildren().add(prancha);
this.gerarBlocos();
this.setarTimer();
this.listenerTeclado();
this.setVida(6);
}
private void carregarFXML() {
FXMLLoader fXMLLoader = new FXMLLoader(this.getClass().getResource("FXMLBrick.fxml"));
fXMLLoader.setRoot(this);
fXMLLoader.setController(this);
try {
fXMLLoader.load();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
private void setarTimer() {
this.atualizar = new Timeline(new KeyFrame(Duration.seconds(0.016f), ae -> this.update()));
this.atualizar.setCycleCount(Animation.INDEFINITE);
this.atualizar.play();
}
private void gerarBlocos() {
float X, Y = 2;
for (String linha : this.level.getLevelFormat().split("\n")) {
X = 0;
for (char bloco : linha.toCharArray()) {
switch (bloco) {
case 'N':
this.getChildren().add(new Bloco(TipoBloco.NORMAL, X, Y));
this.quantidadeBlocos++;
break;
case 'R':
this.getChildren().add(new Bloco(TipoBloco.REFORCADO, X, Y));
this.quantidadeBlocos++;
break;
case 'I':
this.getChildren().add(new Bloco(TipoBloco.INDESTRUTIVEL, X, Y));
break;
}
X++;
}
Y++;
}
}
private void checarArea() {
if (this.bolinha.getTranslateX() > 636) {
this.bolinha.setTranslateX(635);
this.bolinha.inverterVelocidadeX();
}
if (this.bolinha.getTranslateX() < -100) {
this.bolinha.setTranslateX(-99);
this.bolinha.inverterVelocidadeX();
}
if (this.bolinha.getTranslateY() < -100) {
this.bolinha.setTranslateY(-99);
this.bolinha.inverterVelocidadeY();
}
if (this.bolinha.getBoundsInParent().getMaxY() > 830) {
this.diminuirVida();
}
}
private void diminuirVida() {
if (!this.protecao) {
this.vida--;
this.painelVida.getChildren().remove(this.painelVida.getChildren().get(this.vida));
if (this.vida == 0) {
this.atualizar.stop();
this.removerListenerTeclado();
this.getChildren().add(new Resultado(Resultado.TipoResultado.PERDEU, this.level.getIndexLevel(),
this.pontuacao.getText(), Integer.parseInt(this.pontuacao.getText())));
} else {
this.bolinha.resertarBolinha(this.prancha);
}
} else {
this.bolinha.inverterVelocidadeY();
}
}
private void setVida(int _vida) {
this.vida = _vida;
this.painelVida.getChildren().clear();
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
_vida--;
this.painelVida.add(new ImageView(Recursos.getSprite("Vida")), j, k);
if (_vida == 0) {
return;
}
}
}
}
private void levelSuperado() {
if (this.quantidadeBlocos == 0) {
this.atualizar.stop();
this.removerListenerTeclado();
String pontos = this.pontuacao.getText() + " * " + this.painelVida.getChildren().size() + " = ";
Integer p = Integer.parseInt(this.pontuacao.getText()) * this.painelVida.getChildren().size();
pontos += p;
this.getChildren().add(new Resultado(Resultado.TipoResultado.VENCEU, this.level.getIndexLevel(), pontos, p));
}
}
private void inserirDrop(Bloco _bloco) {
Random gerador = new Random();
switch (_bloco.getTipo()) {
case NORMAL:
if (gerador.nextInt(100) > 80) {
this.getChildren().add(new Drop(_bloco));
}
break;
case REFORCADO:
if (gerador.nextInt(100) > 70) {
this.getChildren().add(new Drop(_bloco));
}
break;
default:
break;
}
}
private void efetuarDrop(Drop _drop) {
switch (_drop.getTipo()) {
case VIDA:
if (this.vida < 9) {
this.setVida(++this.vida);
this.getChildren()
.add(new Animacao(Recursos.getAnimacao("Coracao"), Duration.seconds(.03), null, _drop, 3, 5));
this.pontuacao.setText(String.valueOf(Integer.parseInt(this.pontuacao.getText()) + 150));
}
break;
case ESCUDO:
this.protecao = true;
this.getChildren().add(new Animacao(Recursos.getAnimacao("Escudo"), Duration.seconds(.03), null, _drop, 7, 5));
this.tempoProtegido = new Timeline(new KeyFrame(Duration.seconds(20), lambda -> {
this.protecao = false;
}));
this.tempoProtegido.play();
this.pontuacao.setText(String.valueOf(Integer.parseInt(this.pontuacao.getText()) + 100));
break;
case EXPLODIR:
this.getChildren().add(new Animacao(Recursos.getAnimacao("Fogo"), Duration.seconds(.03), null, _drop, 4, 5));
this.diminuirVida();
this.pontuacao.setText(String.valueOf(Integer.parseInt(this.pontuacao.getText()) + 600));
break;
case ESPECIAL:
if (!this.passarDireto) {
this.passarDireto = true;
this.getChildren().add(new Animacao(Recursos.getAnimacao("Gelo"), Duration.seconds(.03), null, _drop, 5, 5));
this.getChildren().add(new Animacao(Recursos.getAnimacao("Protecao"), Duration.seconds(.03),
Duration.seconds(8), this.bolinha, 6, 5));
this.tempoPassar = new Timeline(new KeyFrame(Duration.seconds(8), lambda -> this.passarDireto = false));
this.tempoPassar.play();
this.pontuacao.setText(String.valueOf(Integer.parseInt(this.pontuacao.getText()) + 400));
}
}
}
private void inserirAnimacoesBloco(Bloco _bloco) {
switch (_bloco.getCor()) {
case "Vermelho":
this.getChildren()
.add(new Animacao(Recursos.getAnimacao("Artificio_Vermelho"), Duration.seconds(.03), null, _bloco, 10, 5));
break;
case "Verde":
this.getChildren()
.add(new Animacao(Recursos.getAnimacao("Artificio_Verde"), Duration.seconds(.03), null, _bloco, 6, 5));
break;
case "Azul":
this.getChildren()
.add(new Animacao(Recursos.getAnimacao("Artificio_Azul"), Duration.seconds(.03), null, _bloco, 8, 5));
}
}
private void listenerTeclado() {
this.scene.setOnKeyPressed(tecla -> {
switch (tecla.getCode()) {
case LEFT:
this.prancha.setarMovimentoTeclado(-7);
break;
case RIGHT:
this.prancha.setarMovimentoTeclado(7);
break;
case E:
this.getChildren()
.add(new Animacao(Recursos.getAnimacao("Fogo"), Duration.seconds(.03), null, this.prancha, 4, 5));
this.diminuirVida();
break;
default:
break;
}
});
this.scene.setOnKeyReleased(tecla -> {
switch (tecla.getCode()) {
case LEFT:
case RIGHT:
this.prancha.setarMovimentoTeclado(0);
break;
default:
break;
}
});
}
private void removerListenerTeclado() {
this.scene.setOnKeyPressed(null);
this.scene.setOnKeyReleased(null);
}
private void aplicarMovimentos() {
this.prancha.movimentoTeclado();
this.bolinha.moverBolinha();
}
private void colisaoPrancha(Node node) {
if (node instanceof Prancha && node.getBoundsInParent().intersects(this.bolinha.getBoundsInParent())) {
this.bolinha.colisaoPrancha(node);
this.multiplicadorPontos = 1.0f;
}
}
private boolean colisaoBloco(Node node) {
if (node instanceof Bloco && node.getBoundsInParent().intersects(this.bolinha.getBoundsInParent())) {
if (!this.passarDireto || ((Bloco) node).getTipo() == TipoBloco.INDESTRUTIVEL) {
this.bolinha.colisaoBloco(node);
}
if (((Bloco) node).diminuirVida()) {
this.inserirAnimacoesBloco((Bloco) node);
this.quantidadeBlocos--;
int pontos = (int) ((100 * this.multiplicadorPontos) + Integer.parseInt(this.pontuacao.getText()));
this.pontuacao.setText(String.valueOf(pontos));
this.multiplicadorPontos += 0.2f;
this.inserirDrop((Bloco) node);
this.levelSuperado();
return true;
}
}
return false;
}
private boolean colisaoDrop(Node node) {
if (node instanceof Drop) {
((Drop) node).moverDrop();
if (node.getBoundsInParent().intersects(this.prancha.getBoundsInParent())) {
this.efetuarDrop((Drop) node);
return true;
} else if (node.getBoundsInParent().getMaxY() > 820) {
return true;
}
}
return false;
}
private void calcularColisoes() {
ArrayList<Node> nodes = new ArrayList<>();
for (int i = 0; i < this.getChildren().size(); i++) {
Node node = this.getChildren().get(i);
this.colisaoPrancha(node);
if (this.colisaoBloco(node)) {
nodes.add(node);
}
if (this.colisaoDrop(node)) {
nodes.add(node);
}
if (node instanceof Animacao) {
if (((Animacao) node).isAnimacaoTerminou()) {
nodes.add(node);
break;
}
}
}
this.getChildren().removeAll(nodes);
}
private void update() {
this.aplicarMovimentos();
this.checarArea();
this.calcularColisoes();
}
}
| [
"[email protected]"
] | |
e27401b59f97df1e48319a61bed7d5e936af52db | 1c7cb3154854a0d5f628c4285aa209affd8d2fc9 | /tripleagent/perturbation_agent/src/main/java/se/kth/chaos/pagent/OperationMode.java | df85c8b2aea5482641d80d0e2ea3f7adc5cad609 | [
"MIT"
] | permissive | ErikNatanael/royal-chaos | fac8e5891044490cd2e61b7367f284d99951d0d1 | a8e763d3720cc3e158e98143cabce8106d8de2aa | refs/heads/master | 2022-07-16T12:21:31.494237 | 2020-05-12T12:50:08 | 2020-05-12T12:50:08 | 263,333,134 | 0 | 0 | MIT | 2020-05-12T12:42:08 | 2020-05-12T12:42:08 | null | UTF-8 | Java | false | false | 2,676 | java | package se.kth.chaos.pagent;
import jdk.internal.org.objectweb.asm.Opcodes;
import jdk.internal.org.objectweb.asm.tree.*;
public enum OperationMode {
ARRAY_ANALYSIS {
@Override
public InsnList generateByteCode(ClassNode classNode, MethodNode method, AgentArguments arguments, PerturbationPoint perturbationPoint) {
InsnList list = new InsnList();
return list;
}
},
ARRAY_PONE {
@Override
public InsnList generateByteCode(ClassNode classNode, MethodNode method, AgentArguments arguments, PerturbationPoint perturbationPoint) {
InsnList list = new InsnList();
list.add(new LdcInsnNode(perturbationPoint.key));
list.add(new MethodInsnNode(
Opcodes.INVOKESTATIC,
"se/kth/chaos/pagent/PAgent",
"pOneArrayReading",
"(ILjava/lang/String;)I",
false // this is not a method on an interface
));
return list;
}
},
TIMEOUT {
@Override
public InsnList generateByteCode(ClassNode classNode, MethodNode method, AgentArguments arguments, PerturbationPoint perturbationPoint) {
InsnList list = new InsnList();
list.add(new LdcInsnNode(perturbationPoint.key));
list.add(new MethodInsnNode(
Opcodes.INVOKESTATIC,
"se/kth/chaos/pagent/PAgent",
"timeoutPerturbation",
"(Ljava/lang/String;)V",
false // this is not a method on an interface
));
return list;
}
},
THROW_E {
@Override
public InsnList generateByteCode(ClassNode classNode, MethodNode method, AgentArguments arguments, PerturbationPoint perturbationPoint) {
InsnList list = new InsnList();
list.add(new LdcInsnNode(perturbationPoint.key));
list.add(new MethodInsnNode(
Opcodes.INVOKESTATIC,
"se/kth/chaos/pagent/PAgent",
"throwExceptionPerturbation",
"(Ljava/lang/String;)V",
false // this is not a method on an interface
));
return list;
}
};
public static OperationMode fromLowerCase(String mode) {
return OperationMode.valueOf(mode.toUpperCase());
}
public abstract InsnList generateByteCode(ClassNode classNode, MethodNode method, AgentArguments arguments, PerturbationPoint perturbationPoint);
}
| [
"[email protected]"
] | |
c80db5c9dc9693364f12b60237b8a262011bb6de | 04fb3cbad106710f5667ac0346a5bbcfa5265eea | /SoundPro/gen/com/example/soundpro/R.java | 06035b2a641df6e3968a10cd269d7e56748c8e57 | [] | no_license | shivalipawar/Sound-Profile | 4a884b3680d1dba228c6c46efe1f667cab88c932 | fd884f15d5b4c657cf174afc60baeef6671c09b7 | refs/heads/master | 2020-12-26T04:37:08.809819 | 2015-04-17T14:03:18 | 2015-04-17T14:03:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,413 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.soundpro;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int an11=0x7f020000;
public static final int and=0x7f020001;
public static final int back=0x7f020002;
public static final int background=0x7f020003;
public static final int bck=0x7f020004;
public static final int ic_launcher=0x7f020005;
public static final int spekr=0x7f020006;
}
public static final class id {
public static final int action_settings=0x7f080007;
public static final int button1=0x7f080004;
public static final int button2=0x7f080005;
public static final int listView1=0x7f080006;
public static final int spinner1=0x7f080003;
public static final int spinner2=0x7f080001;
public static final int timePicker1=0x7f080000;
public static final int timePicker2=0x7f080002;
}
public static final class layout {
public static final int activity_main=0x7f030000;
public static final int activity_main_activity1=0x7f030001;
public static final int spinner_item=0x7f030002;
public static final int view_all=0x7f030003;
}
public static final class menu {
public static final int main=0x7f070000;
public static final int main_activity1=0x7f070001;
}
public static final class string {
public static final int action_settings=0x7f050001;
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050002;
public static final int title_activity_main_activity1=0x7f050003;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
| [
"[email protected]"
] | |
07d2e0c070271c2cf0089abb86af6e3176fcabde | a452b04796e0e0ca3eb85a5f772df650cd903a26 | /311_example_01/app/src/test/java/com/ch/a311_example_01/ExampleUnitTest.java | 1d27f12cce978f244e73bcaefd3c3e155de371cd | [] | no_license | Chsengni/CZL_Android_Examples | a0bfd9041417dd2d07ef7422cbf54b5b64a24040 | 1242de1e2822c17cd9ae157a2778136f40ce8e76 | refs/heads/master | 2020-04-26T16:34:36.846660 | 2019-03-04T06:57:31 | 2019-03-04T06:57:31 | 173,684,090 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 383 | java | package com.ch.a311_example_01;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
c57bb89e59c6badfd6dbcc4064aa4dd265455fac | 988c56e627f6e41f56c60acefc9475df4d149b24 | /src/main/java/com/zzg/spider/MasterApp.java | 49e23846473de215d6eb5b0a00a52d8b9fc8340c | [] | no_license | zhangzeguang88/spider | 65f1d9ddb259e053c06ee99dddd97e449ef073a3 | 1a32d8ee9b6e3f8d81f52b6a8eb1fe71e53781ce | refs/heads/master | 2021-09-05T14:42:26.721142 | 2018-01-29T01:08:39 | 2018-01-29T01:08:39 | 119,313,775 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,719 | java | package com.zzg.spider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.Resource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import com.zzg.spider.cache.RedisUtil;
import com.zzg.spider.parse.BloomFilter;
import com.zzg.spider.parse.LinkFilter;
public class MasterApp {
public static void main(String args[]){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
final LinkFilter linkFilter = (LinkFilter)context.getBean("linkFilter");
List<String> seed = readSeed("D:/spider_init.txt");
for(int i=0;i<seed.size();i++){
RedisUtil.lpush("queue", seed.get(i));
}
// 启动解析线程
ExecutorService pool = Executors.newFixedThreadPool(2);
Runnable ra = new Runnable(){
@Override
public void run() {
while(true){
String source = (String) RedisUtil.rpop("sourceQueue");
if(source == null){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
continue;
}
try {
linkFilter.findLinkByJ(source);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
pool.submit(ra);
//pool.submit(new MasterThreadRunnable());
pool.shutdown();
}
public static List<String> readSeed(String filePath){
List<String> seed= new ArrayList<String>();
try {
String encoding="utf-8";
File file=new File(filePath);
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
seed.add(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return seed;
}
}
| [
"[email protected]"
] | |
4a3653d699215c33e6ef381436689a69994137da | 7991248e6bccacd46a5673638a4e089c8ff72a79 | /web/application/src/main/java/org/artifactory/webapp/servlet/SessionFilter.java | 81213ddba814aa40acd7ca14d7a42c5a684a78b2 | [] | no_license | theoriginalshaheedra/artifactory-oss | 69b7f6274cb35c79db3a3cd613302de2ae019b31 | 415df9a9467fee9663850b4b8b4ee5bd4c23adeb | refs/heads/master | 2023-04-23T15:48:36.923648 | 2021-05-05T06:15:24 | 2021-05-05T06:15:24 | 364,455,815 | 1 | 0 | null | 2021-05-05T07:11:40 | 2021-05-05T03:57:33 | Java | UTF-8 | Java | false | false | 2,173 | java | /*
*
* Artifactory is a binaries repository manager.
* Copyright (C) 2018 JFrog Ltd.
*
* Artifactory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Artifactory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Artifactory. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.artifactory.webapp.servlet;
import org.artifactory.api.context.ArtifactoryContext;
import org.springframework.session.SessionRepository;
import org.springframework.session.web.http.SessionRepositoryFilter;
import javax.servlet.*;
import java.io.IOException;
/**
* Delegating filter from a delayed context filter to {@link SessionRepositoryFilter}
*
* @author Shay Yaakov
*/
public class SessionFilter extends DelayedFilterBase {
private SessionRepositoryFilter delegate;
@Override
public void initLater(FilterConfig filterConfig) throws ServletException {
ServletContext servletContext = filterConfig.getServletContext();
ArtifactoryContext context = RequestUtils.getArtifactoryContext(servletContext);
SessionRepository sessionRepository = context.beanForType(SessionRepository.class);
delegate = new SessionRepositoryFilter(sessionRepository);
delegate.setServletContext(servletContext);
}
@Override
public void destroy() {
if (delegate != null) {
delegate.destroy();
}
}
@Override
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws IOException, ServletException {
if (shouldSkipFilter(req)) {
chain.doFilter(req, resp);
return;
}
delegate.doFilter(req, resp, chain);
}
} | [
"[email protected]"
] | |
09fb7c4fdea50097a3d5f8b56b0f5c78b5ebc0a3 | 22ed3cc12726bd051e365287fc3d2f3acc762349 | /src/main/java/lesson7/lesson/Auditor.java | e72fb39b17886016602b3ac9f611b2ec842d670c | [] | no_license | Ivan31r/Innopolis | fec1e7b37f85fb78a6f83ff0b6cae9cd966d24ff | 2d6d88eea2d9b39129bd4cbb2629c48404e36669 | refs/heads/master | 2022-12-24T18:40:28.890421 | 2020-09-22T20:27:12 | 2020-09-22T20:27:12 | 293,843,774 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 339 | java | package lesson7.lesson;
import java.util.concurrent.Callable;
public class Auditor implements Callable<Integer> {
public Store store;
public Auditor(Store store) {
this.store = store;
}
@Override
public Integer call() throws Exception {
Thread.sleep(10000);
return store.getGoods();
}
}
| [
"[email protected]"
] | |
a4a43f819d06da4798d4f521b755d6d3b01b2433 | 7b8b47b06bb5415fbd476059635a9c71b5e8f430 | /app/src/androidTest/java/org/rdtoolkit/FlatInputTranslatorTest.java | 2aa0186c9c862fa979259ebf522dceb73aa5bccf | [
"Apache-2.0"
] | permissive | cws1121/rd-toolkit | 451758dc2180dbd33e34870fe5c34866cd162634 | f78d019af891968d8de02fd49e6cf8eb71b000d0 | refs/heads/master | 2023-03-03T06:12:18.762161 | 2021-02-02T05:12:31 | 2021-02-02T05:12:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,614 | java | package org.rdtoolkit;
import android.content.Intent;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.rdtoolkit.support.interop.BundleToConfiguration;
import org.rdtoolkit.interop.translator.InteropRepository;
import org.rdtoolkit.support.model.session.ClassifierMode;
import org.rdtoolkit.support.model.session.ProvisionMode;
import org.rdtoolkit.support.model.session.SessionMode;
import org.rdtoolkit.support.model.session.TestSession;
import static org.rdtoolkit.support.interop.IntentObjectMappingsKt.INTENT_EXTRA_RDT_CLASSIFIER_MODE;
import static org.rdtoolkit.support.interop.IntentObjectMappingsKt.INTENT_EXTRA_RDT_CONFIG_SESSION_TYPE;
import static org.rdtoolkit.support.interop.IntentObjectMappingsKt.INTENT_EXTRA_RDT_PROVISION_MODE;
import static org.rdtoolkit.support.interop.IntentObjectMappingsKt.INTENT_EXTRA_RDT_PROVISION_MODE_DATA;
import static org.rdtoolkit.interop.translator.TranslatorsKt.TRANSLATOR_PROVISION_FLAT;
import static org.rdtoolkit.support.interop.RdtIntentBuilder.INTENT_EXTRA_RDT_CONFIG_BUNDLE;
import static org.rdtoolkit.support.model.session.SessionFlagsKt.FLAG_SESSION_NO_EXPIRATION_OVERRIDE;
import static org.rdtoolkit.support.model.session.SessionFlagsKt.FLAG_VALUE_SET;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class FlatInputTranslatorTest {
@Test
public void testStructure() {
Intent testIntent = new Intent();
testIntent.putExtra(INTENT_EXTRA_RDT_PROVISION_MODE, ProvisionMode.TEST_PROFILE.toString());
testIntent.putExtra(INTENT_EXTRA_RDT_PROVISION_MODE_DATA, "TestType");
testIntent.putExtra(INTENT_EXTRA_RDT_CONFIG_SESSION_TYPE, SessionMode.ONE_PHASE.toString());
testIntent.putExtra(INTENT_EXTRA_RDT_CLASSIFIER_MODE, ClassifierMode.PRE_POPULATE.toString());
testIntent.putExtra(FLAG_SESSION_NO_EXPIRATION_OVERRIDE, FLAG_VALUE_SET);
Intent output = new InteropRepository().getTranslator(TRANSLATOR_PROVISION_FLAT).map(testIntent);
Assert.assertTrue(output.hasExtra(INTENT_EXTRA_RDT_CONFIG_BUNDLE));
TestSession.Configuration config =
new BundleToConfiguration().map(output.getBundleExtra(INTENT_EXTRA_RDT_CONFIG_BUNDLE));
Assert.assertEquals(SessionMode.ONE_PHASE, config.getSessionType());
Assert.assertEquals(FLAG_VALUE_SET, config.getFlags().get(FLAG_SESSION_NO_EXPIRATION_OVERRIDE));
}
} | [
"[email protected]"
] | |
29304ae398e1df193e5b92c195f5e9d990534c1b | 123ce15a7c917681a4d48974cda9b41c3b9ca36d | /magic-api/src/main/java/org/ssssssss/magicapi/model/Header.java | e39c7906d645def52da0aab76689e7aaf7a4cf72 | [
"MIT"
] | permissive | ZyGravel/magic-api | c1cbe8c561a9ed832a0289bca2812db832183056 | d0041940ae03c6e0a717b3f71911f41424009b6e | refs/heads/master | 2023-09-02T13:14:24.435243 | 2021-11-21T02:10:34 | 2021-11-21T02:10:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 226 | java | package org.ssssssss.magicapi.model;
/**
* Header参数信息
*
* @author mxd
*/
public class Header extends BaseDefinition {
public Header() {
}
public Header(String name, String value) {
super(name, value);
}
}
| [
"[email protected]"
] | |
ec44204217bd65bceb0d267d51fa0149174b0929 | 0e3afedb74f41d92898c2a2d786d57006b5c3dc1 | /src/main/java/org/yousharp/pointatoffer/linkedlist/DeleteOneNode.java | 452f9e790c3510b69b8e5dada52989a94e14936b | [] | no_license | xianlaioy/my-algorithm-practice | eb6ec9e653ca65713ab6367b6fc2c97a81373705 | 562974c18c3a96b5733004771d63543241ccfff5 | refs/heads/master | 2021-01-17T14:06:48.121011 | 2014-12-15T15:00:07 | 2014-12-15T15:00:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,770 | java | package org.yousharp.pointatoffer.linkedlist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yousharp.ds.ListNode;
/**
* 问题:
* 给定一个链表和其中一个节点,删除该节点;
*
* 思路:
* 节点的差异体现在节点对象的内容不同。要删除当前节点,可以将当前节点与下一节点的值互换,然后删除下一个节点即可;
* 复杂度为O(1);
* 需要注意两种特殊情况:
* - 如果要删除的节点是最后一个节点,没有下一个节点,此时需要从头遍历了;复杂度为O(n);
* - 如果链表只有一个节点,则删除后链表为空;
*
* User: lingguo
* Date: 14-3-10
* Time: 下午11:49
*/
public class DeleteOneNode {
private static Logger logger = LoggerFactory.getLogger(DeleteOneNode.class);
/**
* 从链表中删除某一个节点
*
* @param head 链表的头节点
* @param toDelete 要删除的节点
* @return 头节点
*/
public static ListNode delete(ListNode head, ListNode toDelete) {
// param error
if (head == null || toDelete == null) {
logger.info("param error.");
return null;
}
// 最后一个节点
if (toDelete.next == null) {
// 也是头节点
if (head == toDelete) {
logger.info("deleted the only one node.");
return null;
}
// 遍历查找前一个节点
ListNode node = head;
while (node.next != toDelete) {
node = node.next;
}
node.next = node.next.next;
return head;
}
// 不是最后一个节点,将下一个节点的值覆盖当前节点的值,删除下一个节点
toDelete.value = toDelete.next.value;
toDelete.next = toDelete.next.next;
return head;
}
} | [
"[email protected]"
] | |
7eab9c48ec3d31db8a6f0d01a2ab3e60369ee377 | a62bddb3c9d9a311029a0c547b6c978bbddf3955 | /src/main/java/pl/jkan/weatherapp/Cli.java | 0a2f951ebc343c2ccf0af9f515e21484a4b17251 | [] | no_license | Riserax/weather-station-java | 430b64a0ec866170b470daf78de6da87147c4865 | 99a5f5569bf4690ebe4662de9098d5aca0110dfa | refs/heads/master | 2021-08-19T20:18:59.278857 | 2017-11-27T10:46:36 | 2017-11-27T10:46:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 954 | java | package pl.jkan.weatherapp;
import pl.jkan.http.SimpleBrowser;
import pl.jkan.openweatherapi.ApiClient;
import pl.jkan.openweatherapi.TempParser;
import pl.jkan.weatherstation.WeatherStation;
import pl.jkan.weatherstation.sensors.ApiTempSensor;
import pl.jkan.weatherstation.TempSensor;
public class Cli {
public static void main(String[] args) {
String city = "";
try {
city = args[0];
} catch (ArrayIndexOutOfBoundsException e) {
city = "Krakow";
}
TempSensor tempSensor = new ApiTempSensor(
new ApiClient(
new SimpleBrowser(),
new TempParser(),
city,
System.getenv("OPEN_WEATHER_API_KEY")
)
);
WeatherStation station = new WeatherStation(tempSensor);
Double temp = station.temperature();
System.out.printf("Weather in %s| Temp: %s\n", city, temp);
}
}
| [
"[email protected]"
] | |
2bb62e11a5212e3a4b8f79e232e7e0b75479ebfc | aeada48fb548995312d2117f2a97b05242348abf | /bundles/com.zeligsoft.domain.omg.corba.dsl/src-gen/com/zeligsoft/domain/omg/corba/dsl/idl/Connector.java | d6f29ecf5b9c88ef35c37458967fa20124e44753 | [
"Apache-2.0"
] | permissive | elder4p/CX4CBDDS | 8f103d5375595f583ceb30b343ae4c7cc240f18b | 11296d3076c6d667ad86bc83fa47f708e8b5bf01 | refs/heads/master | 2023-03-16T01:51:59.122707 | 2022-08-04T22:13:10 | 2022-08-04T22:13:10 | 198,875,329 | 0 | 0 | Apache-2.0 | 2019-08-22T17:33:21 | 2019-07-25T17:33:51 | Java | UTF-8 | Java | false | false | 2,299 | java | /**
*/
package com.zeligsoft.domain.omg.corba.dsl.idl;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Connector</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link com.zeligsoft.domain.omg.corba.dsl.idl.Connector#getHeader <em>Header</em>}</li>
* <li>{@link com.zeligsoft.domain.omg.corba.dsl.idl.Connector#getExports <em>Exports</em>}</li>
* </ul>
* </p>
*
* @see com.zeligsoft.domain.omg.corba.dsl.idl.IdlPackage#getConnector()
* @model
* @generated
*/
public interface Connector extends Definition, TemplateDefinition, FixedDefinition
{
/**
* Returns the value of the '<em><b>Header</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Header</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Header</em>' containment reference.
* @see #setHeader(ConnectorHeader)
* @see com.zeligsoft.domain.omg.corba.dsl.idl.IdlPackage#getConnector_Header()
* @model containment="true"
* @generated
*/
ConnectorHeader getHeader();
/**
* Sets the value of the '{@link com.zeligsoft.domain.omg.corba.dsl.idl.Connector#getHeader <em>Header</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Header</em>' containment reference.
* @see #getHeader()
* @generated
*/
void setHeader(ConnectorHeader value);
/**
* Returns the value of the '<em><b>Exports</b></em>' containment reference list.
* The list contents are of type {@link com.zeligsoft.domain.omg.corba.dsl.idl.ConnectorExport}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Exports</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Exports</em>' containment reference list.
* @see com.zeligsoft.domain.omg.corba.dsl.idl.IdlPackage#getConnector_Exports()
* @model containment="true"
* @generated
*/
EList<ConnectorExport> getExports();
} // Connector
| [
"[email protected]"
] | |
0d2f5de4a32e9b66cddf119e290039a00bc844d9 | 9e632588def0ba64442d92485b6d155ccb89a283 | /mx-webadmin/webadmin-dao/src/main/java/com/balicamp/soap/ws/sertifikasi/Inquiry.java | bd8c41bff0a154b370d5ef6f5a57f009409738a6 | [] | no_license | prihako/sims2019 | 6986bccbbd35ec4d1e5741aa77393f01287d752a | f5e82e3d46c405d4c3c34d529c8d67e8627adb71 | refs/heads/master | 2022-12-21T07:38:06.400588 | 2021-04-29T07:30:37 | 2021-04-29T07:30:37 | 212,565,332 | 0 | 0 | null | 2022-12-16T00:41:00 | 2019-10-03T11:41:00 | Java | UTF-8 | Java | false | false | 1,489 | java |
package com.balicamp.soap.ws.sertifikasi;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="req" type="{urn:PaymentManagerControllerwsdl}InquiryRequest"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"req"
})
@XmlRootElement(name = "inquiry")
public class Inquiry {
@XmlElement(required = true, nillable = true)
protected InquiryRequest req;
/**
* Gets the value of the req property.
*
* @return
* possible object is
* {@link InquiryRequest }
*
*/
public InquiryRequest getReq() {
return req;
}
/**
* Sets the value of the req property.
*
* @param value
* allowed object is
* {@link InquiryRequest }
*
*/
public void setReq(InquiryRequest value) {
this.req = value;
}
}
| [
"[email protected]"
] | |
56581ea0840edb0e19bb56dc0da1e38aa2048fee | 92fdf061b26f90bea9e883d302ca3b0f5bb84ff0 | /src/main/java/okkpp/model/investment/RegisteredOfBusiness.java | 91c1f55143ea2fb91dba9ea9f5afacb6a49fcbe2 | [] | no_license | YoYB/CEECDATA | 3fea138cea87925a94d3a82d0d3a0ea0b558ed8e | d1991220a76a9a96dd89de3c3a666643d4b40c5c | refs/heads/master | 2021-01-25T13:17:40.834622 | 2018-03-02T03:04:46 | 2018-03-02T03:04:46 | null | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 1,384 | java | package okkpp.model.investment;
import java.util.Date;
/**
* 新注册企业数
New Businesses Registered
*
* @author wcyong
*
* @date 2018-02-09
*/
public class RegisteredOfBusiness {
private Integer id;
/**
* 国家代码
*/
private String country;
/**
* 年份
*/
private Integer year;
/**
* 新注册企业数(个)
*/
private Integer number;
/**
* 更新时间
*/
private Date update;
/**
* 排序
*/
private Integer sort;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country == null ? null : country.trim();
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Date getUpdate() {
return update;
}
public void setUpdate(Date update) {
this.update = update;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
} | [
"[email protected]"
] | |
9e3d795b834fee71f3242d16bfbb205f8ff2b2a8 | da845f70689a6f45cdc4675d80fa86d150c94fa9 | /src/java/com/twitter/elephantbird/mapred/output/DeprecatedLzoProtobufBlockRecordWriter.java | 3f065f2eb5808a20d43eab4260a806c979735d4c | [
"Apache-2.0"
] | permissive | panisson/elephant-bird | 9baef703e964db8e81551ade830929d383cd1d49 | fe8fa0c79736cd3e6904d726a035f44c7f2a6989 | refs/heads/master | 2021-01-15T21:03:36.947442 | 2012-03-30T21:30:36 | 2012-03-30T21:30:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 535 | java | package com.twitter.elephantbird.mapred.output;
import com.google.protobuf.Message;
import com.twitter.elephantbird.mapreduce.io.ProtobufBlockWriter;
import com.twitter.elephantbird.mapreduce.io.ProtobufWritable;
/**
* A writer for LZO-encoded blocks of Protobuf objects.
*
*/
public class DeprecatedLzoProtobufBlockRecordWriter<M extends Message>
extends DeprecatedLzoBinaryBlockRecordWriter<M, ProtobufWritable<M>> {
public DeprecatedLzoProtobufBlockRecordWriter(ProtobufBlockWriter<M> writer) {
super(writer);
}
}
| [
"[email protected]"
] | |
ff211d7d0001ced7244e221d715aa476bc67cfd5 | 2843dcee70a0a0408eeb46345401b93214071f8b | /app/src/main/java/com/abct/tljr/ui/activity/tools/OneBasis.java | c49c0d0f72cb9d84b88b816fbcca62b25a914c74 | [] | no_license | xiaozhugua/tuling | 16ac6a778e18c99bd1433912195b186a30fbf86a | f3470c5dfca05b47d8d96a9dc33d4738175de59a | refs/heads/master | 2021-01-12T16:42:27.496392 | 2016-10-20T07:00:12 | 2016-10-20T07:00:12 | 71,434,177 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 792 | java | package com.abct.tljr.ui.activity.tools;
/**
* @author xbw
* @version 创建时间:2015年11月14日 下午6:27:45
*/
public class OneBasis {
private long time;
private float basis;
private float close;
private String name;
public long getVolume() {
return volume;
}
public void setVolume(long volume) {
this.volume = volume;
}
private long volume;
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public float getBasis() {
return basis;
}
public void setBasis(float basis) {
this.basis = basis;
}
public float getClose() {
return close;
}
public void setClose(float close) {
this.close = close;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| [
"[email protected]"
] | |
4d6a2abdedb7787fd86403e2a1a79a4923aaf0d4 | 55ef186e267cd0ca525295d6c601044409bca843 | /Json Builder/src/amdocs/iam/pd/webservices/referenceattributevalues/referenceattributevaluesoutput/impl/PopulatedFieldImpl.java | 4987fbd6c6f94cb90601f933bdd4b7c31ef4a0a2 | [] | no_license | gbarsky/OE | 4771d868fb2239fafe058cac92af9bce7f734b5f | 2e2a3e2143ab8ef5e1f09e1c4047793c6dbf7ffa | refs/heads/master | 2020-05-29T22:35:00.138746 | 2013-04-04T02:49:51 | 2013-04-04T02:49:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,457 | java | /*
* XML Type: PopulatedField
* Namespace: http://amdocs/iam/pd/webservices/referenceAttributeValues/ReferenceAttributeValuesOutput
* Java type: amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.PopulatedField
*
* Automatically generated - do not modify.
*/
package amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.impl;
/**
* An XML PopulatedField(@http://amdocs/iam/pd/webservices/referenceAttributeValues/ReferenceAttributeValuesOutput).
*
* This is a complex type.
*/
public class PopulatedFieldImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.PopulatedField
{
public PopulatedFieldImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName ATTRIBUTECODE$0 =
new javax.xml.namespace.QName("", "attributeCode");
private static final javax.xml.namespace.QName POPULATEDCOLUMN$2 =
new javax.xml.namespace.QName("", "populatedColumn");
private static final javax.xml.namespace.QName POPULATEDFIELDCUSTOM$4 =
new javax.xml.namespace.QName("", "PopulatedFieldCustom");
/**
* Gets the "attributeCode" element
*/
public java.lang.String getAttributeCode()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(ATTRIBUTECODE$0, 0);
if (target == null)
{
return null;
}
return target.getStringValue();
}
}
/**
* Gets (as xml) the "attributeCode" element
*/
public org.apache.xmlbeans.XmlString xgetAttributeCode()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlString target = null;
target = (org.apache.xmlbeans.XmlString)get_store().find_element_user(ATTRIBUTECODE$0, 0);
return target;
}
}
/**
* Sets the "attributeCode" element
*/
public void setAttributeCode(java.lang.String attributeCode)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(ATTRIBUTECODE$0, 0);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(ATTRIBUTECODE$0);
}
target.setStringValue(attributeCode);
}
}
/**
* Sets (as xml) the "attributeCode" element
*/
public void xsetAttributeCode(org.apache.xmlbeans.XmlString attributeCode)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlString target = null;
target = (org.apache.xmlbeans.XmlString)get_store().find_element_user(ATTRIBUTECODE$0, 0);
if (target == null)
{
target = (org.apache.xmlbeans.XmlString)get_store().add_element_user(ATTRIBUTECODE$0);
}
target.set(attributeCode);
}
}
/**
* Gets the "populatedColumn" element
*/
public amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column getPopulatedColumn()
{
synchronized (monitor())
{
check_orphaned();
amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column target = null;
target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column)get_store().find_element_user(POPULATEDCOLUMN$2, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "populatedColumn" element
*/
public void setPopulatedColumn(amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column populatedColumn)
{
synchronized (monitor())
{
check_orphaned();
amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column target = null;
target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column)get_store().find_element_user(POPULATEDCOLUMN$2, 0);
if (target == null)
{
target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column)get_store().add_element_user(POPULATEDCOLUMN$2);
}
target.set(populatedColumn);
}
}
/**
* Appends and returns a new empty "populatedColumn" element
*/
public amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column addNewPopulatedColumn()
{
synchronized (monitor())
{
check_orphaned();
amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column target = null;
target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column)get_store().add_element_user(POPULATEDCOLUMN$2);
return target;
}
}
/**
* Gets the "PopulatedFieldCustom" element
*/
public amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom getPopulatedFieldCustom()
{
synchronized (monitor())
{
check_orphaned();
amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom target = null;
target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom)get_store().find_element_user(POPULATEDFIELDCUSTOM$4, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* True if has "PopulatedFieldCustom" element
*/
public boolean isSetPopulatedFieldCustom()
{
synchronized (monitor())
{
check_orphaned();
return get_store().count_elements(POPULATEDFIELDCUSTOM$4) != 0;
}
}
/**
* Sets the "PopulatedFieldCustom" element
*/
public void setPopulatedFieldCustom(amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom populatedFieldCustom)
{
synchronized (monitor())
{
check_orphaned();
amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom target = null;
target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom)get_store().find_element_user(POPULATEDFIELDCUSTOM$4, 0);
if (target == null)
{
target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom)get_store().add_element_user(POPULATEDFIELDCUSTOM$4);
}
target.set(populatedFieldCustom);
}
}
/**
* Appends and returns a new empty "PopulatedFieldCustom" element
*/
public amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom addNewPopulatedFieldCustom()
{
synchronized (monitor())
{
check_orphaned();
amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom target = null;
target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom)get_store().add_element_user(POPULATEDFIELDCUSTOM$4);
return target;
}
}
/**
* Unsets the "PopulatedFieldCustom" element
*/
public void unsetPopulatedFieldCustom()
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_element(POPULATEDFIELDCUSTOM$4, 0);
}
}
}
| [
"[email protected]"
] | |
499288abbeb755e73e0034907fbcc0d4d2c569ec | 39a4e939640d5249f253f8883ed39e1dd3254c94 | /src/test/java/enteties/UserTest.java | a6cd1c3f6b5157a289274389f6a88853fc1d09a3 | [] | no_license | Sendrikz/AdmissionCampaign | b4e759ff721bbe414a4e1771a73404080bf49c8d | 3fb3e1d8421ee0f6f23d524e191abd98fda6a318 | refs/heads/master | 2020-03-23T22:59:06.092759 | 2018-09-09T12:14:01 | 2018-09-09T12:14:01 | 142,210,127 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,090 | java | package enteties;
import model.builder.UserBuilder;
import model.enteties_enum.Users;
import model.enteties.User;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
/**
* @author Olha Yuryeva
* @version 1.0
*/
public class UserTest {
private User user;
@Before
public void setUp() {
user = new UserBuilder().setLastName(Users.KOSTYA.getLastName()).setFirstName(Users.KOSTYA.getFirstName()).setPatronymic(Users.KOSTYA.getPatronymic()).setBirthday(Users.KOSTYA.getBirthday()).setCity(Users.KOSTYA.getCity()).setEmail(Users.KOSTYA.getEmail()).setPassword(Users.KOSTYA.getPassword()).setRole(2).createUser();
}
@Test
public void setLastNameTest() {
user.setLastName(Users.MUHAYLO.getLastName());
assertEquals(Users.MUHAYLO.getLastName(), user.getLastName());
}
@Test
public void setFirstNameTest() {
user.setFirstName(Users.MUHAYLO.getFirstName());
assertEquals(Users.MUHAYLO.getFirstName(), user.getFirstName());
}
@Test
public void setPatronymicTest() {
user.setPatronymic(Users.MUHAYLO.getPatronymic());
assertEquals(Users.MUHAYLO.getPatronymic(), user.getPatronymic());
}
@Test
public void setBirthdayTest() {
user.setBirthday(Users.MUHAYLO.getBirthday());
assertEquals(Users.MUHAYLO.getBirthday(), user.getBirthday());
}
@Test
public void setCityTest() {
user.setCity(Users.MUHAYLO.getCity());
assertEquals(Users.MUHAYLO.getCity(), user.getCity());
}
@Test
public void setRoleTest() {
user.setRole(1);
assertEquals(1, user.getRole());
}
@Test
public void setIdTest() {
user.setId(1);
assertEquals(1, user.getId());
}
@Test
public void setEmailTest() {
user.setEmail(Users.MUHAYLO.getEmail());
assertEquals(Users.MUHAYLO.getEmail(), user.getEmail());
}
@Test
public void setPasswordTest() {
user.setPassword(Users.MUHAYLO.getPassword());
assertEquals(Users.MUHAYLO.getPassword(), user.getPassword());
}
@Test
public void equalsTest() {
User userCopy = new UserBuilder().setLastName(Users.KOSTYA.getLastName()).setFirstName(Users.KOSTYA.getFirstName()).setPatronymic(Users.KOSTYA.getPatronymic()).setBirthday(Users.KOSTYA.getBirthday()).setCity(Users.KOSTYA.getCity()).setEmail(Users.KOSTYA.getEmail()).setPassword(Users.KOSTYA.getPassword()).setRole(2).createUser();
assertEquals(true, user.equals(userCopy));
}
@Test
public void hashCodeTest() {
User userCopy = new UserBuilder().setLastName(Users.KOSTYA.getLastName()).setFirstName(Users.KOSTYA.getFirstName()).setPatronymic(Users.KOSTYA.getPatronymic()).setBirthday(Users.KOSTYA.getBirthday()).setCity(Users.KOSTYA.getCity()).setEmail(Users.KOSTYA.getEmail()).setPassword(Users.KOSTYA.getPassword()).setRole(2).createUser();
assertEquals(user.hashCode(), userCopy.hashCode());
}
@Test
public void notEqualsTest() {
User userCopy = new UserBuilder().setLastName(Users.ANDRIY.getLastName()).setFirstName(Users.ANDRIY.getFirstName()).setPatronymic(Users.ANDRIY.getPatronymic()).setBirthday(Users.ANDRIY.getBirthday()).setCity(Users.ANDRIY.getCity()).setEmail(Users.ANDRIY.getEmail()).setPassword(Users.ANDRIY.getPassword()).setRole(1).createUser();
assertEquals(false, user.equals(userCopy));
}
@Test
public void getString() {
assertEquals("User{" +
"id=" + user.getId() +
", lastName='" + user.getLastName() + '\'' +
", firstName='" + user.getFirstName() + '\'' +
", patronymic='" + user.getPatronymic() + '\'' +
", birthday=" + user.getBirthday() +
", city='" + user.getCity() + '\'' +
", email='" + user.getEmail() + '\'' +
", password='" + user.getPassword() + '\'' +
", role=" + user.getRole() +
'}', user.toString());
}
}
| [
"[email protected]"
] | |
894206f14f08c8c93d88a09cbd0dfae52c6fd963 | 5a47617ff6befde02bd748c99655bbe7f4e6b6f5 | /app/build/generated/source/r/debug/com/google/android/gms/maps/R.java | 89ad251296efaa3ed4618fc04e9b8fb404bd4c0a | [] | no_license | Bubbles2/EasySnap | 13ee7007375d28620fe491ac99432d2f8e9d61b7 | 22172a34d2006d676e17f97daa328adcd23d6fad | refs/heads/master | 2016-09-01T04:17:49.922511 | 2015-10-20T10:01:32 | 2015-10-20T10:01:32 | 44,597,621 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,438 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.google.android.gms.maps;
public final class R {
public static final class attr {
public static final int adSize = 0x7f010026;
public static final int adSizes = 0x7f010027;
public static final int adUnitId = 0x7f010028;
public static final int ambientEnabled = 0x7f01004e;
public static final int appTheme = 0x7f0100e9;
public static final int buyButtonAppearance = 0x7f0100f0;
public static final int buyButtonHeight = 0x7f0100ed;
public static final int buyButtonText = 0x7f0100ef;
public static final int buyButtonWidth = 0x7f0100ee;
public static final int cameraBearing = 0x7f01003f;
public static final int cameraTargetLat = 0x7f010040;
public static final int cameraTargetLng = 0x7f010041;
public static final int cameraTilt = 0x7f010042;
public static final int cameraZoom = 0x7f010043;
public static final int circleCrop = 0x7f01003d;
public static final int environment = 0x7f0100ea;
public static final int fragmentMode = 0x7f0100ec;
public static final int fragmentStyle = 0x7f0100eb;
public static final int imageAspectRatio = 0x7f01003c;
public static final int imageAspectRatioAdjust = 0x7f01003b;
public static final int liteMode = 0x7f010044;
public static final int mapType = 0x7f01003e;
public static final int maskedWalletDetailsBackground = 0x7f0100f3;
public static final int maskedWalletDetailsButtonBackground = 0x7f0100f5;
public static final int maskedWalletDetailsButtonTextAppearance = 0x7f0100f4;
public static final int maskedWalletDetailsHeaderTextAppearance = 0x7f0100f2;
public static final int maskedWalletDetailsLogoImageType = 0x7f0100f7;
public static final int maskedWalletDetailsLogoTextColor = 0x7f0100f6;
public static final int maskedWalletDetailsTextAppearance = 0x7f0100f1;
public static final int uiCompass = 0x7f010045;
public static final int uiMapToolbar = 0x7f01004d;
public static final int uiRotateGestures = 0x7f010046;
public static final int uiScrollGestures = 0x7f010047;
public static final int uiTiltGestures = 0x7f010048;
public static final int uiZoomControls = 0x7f010049;
public static final int uiZoomGestures = 0x7f01004a;
public static final int useViewLifecycle = 0x7f01004b;
public static final int windowTransitionStyle = 0x7f01002f;
public static final int zOrderOnTop = 0x7f01004c;
}
public static final class color {
public static final int common_action_bar_splitter = 0x7f0c0012;
public static final int common_signin_btn_dark_text_default = 0x7f0c0013;
public static final int common_signin_btn_dark_text_disabled = 0x7f0c0014;
public static final int common_signin_btn_dark_text_focused = 0x7f0c0015;
public static final int common_signin_btn_dark_text_pressed = 0x7f0c0016;
public static final int common_signin_btn_default_background = 0x7f0c0017;
public static final int common_signin_btn_light_text_default = 0x7f0c0018;
public static final int common_signin_btn_light_text_disabled = 0x7f0c0019;
public static final int common_signin_btn_light_text_focused = 0x7f0c001a;
public static final int common_signin_btn_light_text_pressed = 0x7f0c001b;
public static final int common_signin_btn_text_dark = 0x7f0c005a;
public static final int common_signin_btn_text_light = 0x7f0c005b;
public static final int wallet_bright_foreground_disabled_holo_light = 0x7f0c0043;
public static final int wallet_bright_foreground_holo_dark = 0x7f0c0044;
public static final int wallet_bright_foreground_holo_light = 0x7f0c0045;
public static final int wallet_dim_foreground_disabled_holo_dark = 0x7f0c0046;
public static final int wallet_dim_foreground_holo_dark = 0x7f0c0047;
public static final int wallet_dim_foreground_inverse_disabled_holo_dark = 0x7f0c0048;
public static final int wallet_dim_foreground_inverse_holo_dark = 0x7f0c0049;
public static final int wallet_highlighted_text_holo_dark = 0x7f0c004a;
public static final int wallet_highlighted_text_holo_light = 0x7f0c004b;
public static final int wallet_hint_foreground_holo_dark = 0x7f0c004c;
public static final int wallet_hint_foreground_holo_light = 0x7f0c004d;
public static final int wallet_holo_blue_light = 0x7f0c004e;
public static final int wallet_link_text_light = 0x7f0c004f;
public static final int wallet_primary_text_holo_light = 0x7f0c005e;
public static final int wallet_secondary_text_holo_dark = 0x7f0c005f;
}
public static final class drawable {
public static final int cast_ic_notification_0 = 0x7f020043;
public static final int cast_ic_notification_1 = 0x7f020044;
public static final int cast_ic_notification_2 = 0x7f020045;
public static final int cast_ic_notification_connecting = 0x7f020046;
public static final int cast_ic_notification_on = 0x7f020047;
public static final int common_full_open_on_phone = 0x7f020048;
public static final int common_ic_googleplayservices = 0x7f020049;
public static final int common_signin_btn_icon_dark = 0x7f02004a;
public static final int common_signin_btn_icon_disabled_dark = 0x7f02004b;
public static final int common_signin_btn_icon_disabled_focus_dark = 0x7f02004c;
public static final int common_signin_btn_icon_disabled_focus_light = 0x7f02004d;
public static final int common_signin_btn_icon_disabled_light = 0x7f02004e;
public static final int common_signin_btn_icon_focus_dark = 0x7f02004f;
public static final int common_signin_btn_icon_focus_light = 0x7f020050;
public static final int common_signin_btn_icon_light = 0x7f020051;
public static final int common_signin_btn_icon_normal_dark = 0x7f020052;
public static final int common_signin_btn_icon_normal_light = 0x7f020053;
public static final int common_signin_btn_icon_pressed_dark = 0x7f020054;
public static final int common_signin_btn_icon_pressed_light = 0x7f020055;
public static final int common_signin_btn_text_dark = 0x7f020056;
public static final int common_signin_btn_text_disabled_dark = 0x7f020057;
public static final int common_signin_btn_text_disabled_focus_dark = 0x7f020058;
public static final int common_signin_btn_text_disabled_focus_light = 0x7f020059;
public static final int common_signin_btn_text_disabled_light = 0x7f02005a;
public static final int common_signin_btn_text_focus_dark = 0x7f02005b;
public static final int common_signin_btn_text_focus_light = 0x7f02005c;
public static final int common_signin_btn_text_light = 0x7f02005d;
public static final int common_signin_btn_text_normal_dark = 0x7f02005e;
public static final int common_signin_btn_text_normal_light = 0x7f02005f;
public static final int common_signin_btn_text_pressed_dark = 0x7f020060;
public static final int common_signin_btn_text_pressed_light = 0x7f020061;
public static final int ic_plusone_medium_off_client = 0x7f02007d;
public static final int ic_plusone_small_off_client = 0x7f02007e;
public static final int ic_plusone_standard_off_client = 0x7f02007f;
public static final int ic_plusone_tall_off_client = 0x7f020080;
public static final int powered_by_google_dark = 0x7f020096;
public static final int powered_by_google_light = 0x7f020097;
}
public static final class id {
public static final int adjust_height = 0x7f0d0018;
public static final int adjust_width = 0x7f0d0019;
public static final int book_now = 0x7f0d0033;
public static final int buyButton = 0x7f0d0030;
public static final int buy_now = 0x7f0d0034;
public static final int buy_with = 0x7f0d0035;
public static final int buy_with_google = 0x7f0d0036;
public static final int cast_notification_id = 0x7f0d0004;
public static final int classic = 0x7f0d003a;
public static final int donate_with = 0x7f0d0037;
public static final int donate_with_google = 0x7f0d0038;
public static final int google_wallet_classic = 0x7f0d003b;
public static final int google_wallet_grayscale = 0x7f0d003c;
public static final int google_wallet_monochrome = 0x7f0d003d;
public static final int grayscale = 0x7f0d003e;
public static final int holo_dark = 0x7f0d002a;
public static final int holo_light = 0x7f0d002b;
public static final int hybrid = 0x7f0d001a;
public static final int logo_only = 0x7f0d0039;
public static final int match_parent = 0x7f0d0032;
public static final int monochrome = 0x7f0d003f;
public static final int none = 0x7f0d000f;
public static final int normal = 0x7f0d000b;
public static final int production = 0x7f0d002c;
public static final int sandbox = 0x7f0d002d;
public static final int satellite = 0x7f0d001b;
public static final int selectionDetails = 0x7f0d0031;
public static final int slide = 0x7f0d0014;
public static final int strict_sandbox = 0x7f0d002e;
public static final int terrain = 0x7f0d001c;
public static final int test = 0x7f0d002f;
public static final int wrap_content = 0x7f0d0024;
}
public static final class integer {
public static final int google_play_services_version = 0x7f0b0004;
}
public static final class raw {
public static final int gtm_analytics = 0x7f060000;
}
public static final class string {
public static final int accept = 0x7f07005a;
public static final int auth_google_play_services_client_facebook_display_name = 0x7f07005b;
public static final int auth_google_play_services_client_google_display_name = 0x7f07005c;
public static final int cast_notification_connected_message = 0x7f07005d;
public static final int cast_notification_connecting_message = 0x7f07005e;
public static final int cast_notification_disconnect = 0x7f07005f;
public static final int common_android_wear_notification_needs_update_text = 0x7f07000d;
public static final int common_android_wear_update_text = 0x7f07000e;
public static final int common_android_wear_update_title = 0x7f07000f;
public static final int common_google_play_services_api_unavailable_text = 0x7f070010;
public static final int common_google_play_services_enable_button = 0x7f070011;
public static final int common_google_play_services_enable_text = 0x7f070012;
public static final int common_google_play_services_enable_title = 0x7f070013;
public static final int common_google_play_services_error_notification_requested_by_msg = 0x7f070014;
public static final int common_google_play_services_install_button = 0x7f070015;
public static final int common_google_play_services_install_text_phone = 0x7f070016;
public static final int common_google_play_services_install_text_tablet = 0x7f070017;
public static final int common_google_play_services_install_title = 0x7f070018;
public static final int common_google_play_services_invalid_account_text = 0x7f070019;
public static final int common_google_play_services_invalid_account_title = 0x7f07001a;
public static final int common_google_play_services_needs_enabling_title = 0x7f07001b;
public static final int common_google_play_services_network_error_text = 0x7f07001c;
public static final int common_google_play_services_network_error_title = 0x7f07001d;
public static final int common_google_play_services_notification_needs_update_title = 0x7f07001e;
public static final int common_google_play_services_notification_ticker = 0x7f07001f;
public static final int common_google_play_services_sign_in_failed_text = 0x7f070020;
public static final int common_google_play_services_sign_in_failed_title = 0x7f070021;
public static final int common_google_play_services_unknown_issue = 0x7f070022;
public static final int common_google_play_services_unsupported_text = 0x7f070023;
public static final int common_google_play_services_unsupported_title = 0x7f070024;
public static final int common_google_play_services_update_button = 0x7f070025;
public static final int common_google_play_services_update_text = 0x7f070026;
public static final int common_google_play_services_update_title = 0x7f070027;
public static final int common_google_play_services_updating_text = 0x7f070028;
public static final int common_google_play_services_updating_title = 0x7f070029;
public static final int common_open_on_phone = 0x7f07002a;
public static final int common_signin_button_text = 0x7f070060;
public static final int common_signin_button_text_long = 0x7f070061;
public static final int create_calendar_message = 0x7f070062;
public static final int create_calendar_title = 0x7f070063;
public static final int decline = 0x7f070064;
public static final int store_picture_message = 0x7f07006a;
public static final int store_picture_title = 0x7f07006b;
public static final int wallet_buy_button_place_holder = 0x7f070031;
}
public static final class style {
public static final int Theme_IAPTheme = 0x7f0900e1;
public static final int WalletFragmentDefaultButtonTextAppearance = 0x7f0900e9;
public static final int WalletFragmentDefaultDetailsHeaderTextAppearance = 0x7f0900ea;
public static final int WalletFragmentDefaultDetailsTextAppearance = 0x7f0900eb;
public static final int WalletFragmentDefaultStyle = 0x7f0900ec;
}
public static final class styleable {
public static final int[] AdsAttrs = { 0x7f010026, 0x7f010027, 0x7f010028 };
public static final int AdsAttrs_adSize = 0;
public static final int AdsAttrs_adSizes = 1;
public static final int AdsAttrs_adUnitId = 2;
public static final int[] CustomWalletTheme = { 0x7f01002f };
public static final int CustomWalletTheme_windowTransitionStyle = 0;
public static final int[] LoadingImageView = { 0x7f01003b, 0x7f01003c, 0x7f01003d };
public static final int LoadingImageView_circleCrop = 2;
public static final int LoadingImageView_imageAspectRatio = 1;
public static final int LoadingImageView_imageAspectRatioAdjust = 0;
public static final int[] MapAttrs = { 0x7f01003e, 0x7f01003f, 0x7f010040, 0x7f010041, 0x7f010042, 0x7f010043, 0x7f010044, 0x7f010045, 0x7f010046, 0x7f010047, 0x7f010048, 0x7f010049, 0x7f01004a, 0x7f01004b, 0x7f01004c, 0x7f01004d, 0x7f01004e };
public static final int MapAttrs_ambientEnabled = 16;
public static final int MapAttrs_cameraBearing = 1;
public static final int MapAttrs_cameraTargetLat = 2;
public static final int MapAttrs_cameraTargetLng = 3;
public static final int MapAttrs_cameraTilt = 4;
public static final int MapAttrs_cameraZoom = 5;
public static final int MapAttrs_liteMode = 6;
public static final int MapAttrs_mapType = 0;
public static final int MapAttrs_uiCompass = 7;
public static final int MapAttrs_uiMapToolbar = 15;
public static final int MapAttrs_uiRotateGestures = 8;
public static final int MapAttrs_uiScrollGestures = 9;
public static final int MapAttrs_uiTiltGestures = 10;
public static final int MapAttrs_uiZoomControls = 11;
public static final int MapAttrs_uiZoomGestures = 12;
public static final int MapAttrs_useViewLifecycle = 13;
public static final int MapAttrs_zOrderOnTop = 14;
public static final int[] WalletFragmentOptions = { 0x7f0100e9, 0x7f0100ea, 0x7f0100eb, 0x7f0100ec };
public static final int WalletFragmentOptions_appTheme = 0;
public static final int WalletFragmentOptions_environment = 1;
public static final int WalletFragmentOptions_fragmentMode = 3;
public static final int WalletFragmentOptions_fragmentStyle = 2;
public static final int[] WalletFragmentStyle = { 0x7f0100ed, 0x7f0100ee, 0x7f0100ef, 0x7f0100f0, 0x7f0100f1, 0x7f0100f2, 0x7f0100f3, 0x7f0100f4, 0x7f0100f5, 0x7f0100f6, 0x7f0100f7 };
public static final int WalletFragmentStyle_buyButtonAppearance = 3;
public static final int WalletFragmentStyle_buyButtonHeight = 0;
public static final int WalletFragmentStyle_buyButtonText = 2;
public static final int WalletFragmentStyle_buyButtonWidth = 1;
public static final int WalletFragmentStyle_maskedWalletDetailsBackground = 6;
public static final int WalletFragmentStyle_maskedWalletDetailsButtonBackground = 8;
public static final int WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance = 7;
public static final int WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance = 5;
public static final int WalletFragmentStyle_maskedWalletDetailsLogoImageType = 10;
public static final int WalletFragmentStyle_maskedWalletDetailsLogoTextColor = 9;
public static final int WalletFragmentStyle_maskedWalletDetailsTextAppearance = 4;
}
}
| [
"[email protected]"
] | |
8641838737d6ec7d9613526d94846a0ab10b61ab | 63e7a50adc729dad1dc8e752c48c501bfc5bdab4 | /src/com/dataStuctureAndAlgorithm/LeetCode/BinaryTree/BalanceBT_110.java | 89c3509dedf90ceaa3cd62590f86149fac442a36 | [] | no_license | weiruchenai/DSandA | 585582b411db70c0f90f82b9f40cc7b8ee6b20ed | 0cf6a30923e122e29376a5d4f3074b56a342ae33 | refs/heads/master | 2023-01-19T22:37:21.725817 | 2020-11-18T05:36:18 | 2020-11-18T05:36:18 | 284,951,968 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,091 | java | package com.dataStuctureAndAlgorithm.LeetCode.BinaryTree;
import com.sun.source.tree.Tree;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/*
* 110. 平衡二叉树
*给定一个二叉树,判断它是否是高度平衡的二叉树(一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1)
*
* 思路,对于一个root而言,找到左子树和右子树的最大深度,两者相减的绝对值大于1则返回false,否则返回true
* */
public class BalanceBT_110 {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
//若当前root的左右子树最大深度差值>1,返回false,否则递归调用
int depthDiffer = Math.abs(getMaxDepth(root.left) - getMaxDepth(root.right));
if(depthDiffer > 1) return false;
return isBalanced(root.left) && isBalanced(root.right);
}
public int getMaxDepth(TreeNode root){
if(root == null) return 0;
int leftHeight = getMaxDepth(root.left);
int rightHeight = getMaxDepth(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}
| [
"[email protected]"
] | |
7b3cdf3f14b1c7c574782b11bfc16e0df37d153a | 7565725272da0b194a7a6b1a06a7037e6e6929a0 | /spring-cql/src/test/java/org/springframework/cassandra/core/ConsistencyLevelResolverUnitTests.java | 12b0b75d335b5f2c6b2d282fa02facd7fdc6d4fd | [
"LicenseRef-scancode-generic-cla"
] | no_license | paulokinho/spring-data-cassandra | 460abd2b3f6160b67464f3a86b1c7171a8e94e35 | 44671e4854e8395ac33efcc144c1de3bd3d3f270 | refs/heads/master | 2020-02-26T16:12:25.391964 | 2017-03-05T22:17:01 | 2017-03-05T22:17:01 | 68,550,589 | 0 | 3 | null | 2017-03-05T22:17:02 | 2016-09-18T22:25:43 | Java | UTF-8 | Java | false | false | 3,462 | java | /*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cassandra.core;
import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* Unit tests for {@link ConsistencyLevelResolver}.
*
* @author Mark Paluch
*/
@RunWith(Parameterized.class)
public class ConsistencyLevelResolverUnitTests {
private final ConsistencyLevel from;
private final com.datastax.driver.core.ConsistencyLevel expected;
public ConsistencyLevelResolverUnitTests(ConsistencyLevel from, com.datastax.driver.core.ConsistencyLevel expected) {
this.from = from;
this.expected = expected;
}
@Parameters(name = "{0}")
public static List<Object[]> parameters() {
Map<ConsistencyLevel, com.datastax.driver.core.ConsistencyLevel> expectations = new LinkedHashMap<ConsistencyLevel, com.datastax.driver.core.ConsistencyLevel>();
expectations.put(ConsistencyLevel.ALL, com.datastax.driver.core.ConsistencyLevel.ALL);
expectations.put(ConsistencyLevel.ANY, com.datastax.driver.core.ConsistencyLevel.ANY);
expectations.put(ConsistencyLevel.QUOROM, com.datastax.driver.core.ConsistencyLevel.QUORUM);
expectations.put(ConsistencyLevel.QUORUM, com.datastax.driver.core.ConsistencyLevel.QUORUM);
expectations.put(ConsistencyLevel.LOCAL_QUOROM, com.datastax.driver.core.ConsistencyLevel.LOCAL_QUORUM);
expectations.put(ConsistencyLevel.LOCAL_QUORUM, com.datastax.driver.core.ConsistencyLevel.LOCAL_QUORUM);
expectations.put(ConsistencyLevel.EACH_QUOROM, com.datastax.driver.core.ConsistencyLevel.EACH_QUORUM);
expectations.put(ConsistencyLevel.EACH_QUORUM, com.datastax.driver.core.ConsistencyLevel.EACH_QUORUM);
expectations.put(ConsistencyLevel.LOCAL_ONE, com.datastax.driver.core.ConsistencyLevel.LOCAL_ONE);
expectations.put(ConsistencyLevel.LOCAL_SERIAL, com.datastax.driver.core.ConsistencyLevel.LOCAL_SERIAL);
expectations.put(ConsistencyLevel.SERIAL, com.datastax.driver.core.ConsistencyLevel.SERIAL);
expectations.put(ConsistencyLevel.ONE, com.datastax.driver.core.ConsistencyLevel.ONE);
expectations.put(ConsistencyLevel.TWO, com.datastax.driver.core.ConsistencyLevel.TWO);
expectations.put(ConsistencyLevel.THREE, com.datastax.driver.core.ConsistencyLevel.THREE);
List<Object[]> parameters = new ArrayList<Object[]>();
for (Entry<ConsistencyLevel, com.datastax.driver.core.ConsistencyLevel> entry : expectations.entrySet()) {
parameters.add(new Object[] { entry.getKey(), entry.getValue() });
}
return parameters;
}
@Test // DATACASS-202
public void shouldResolveCorrectly() {
assertThat(ConsistencyLevelResolver.resolve(from)).isEqualTo(expected);
}
}
| [
"[email protected]"
] | |
213e9262eb2601d8f68137c635dd87a43c2863f4 | 5d18ca56692ee88c53b01137cbaa28df153c85c8 | /STG/GUI.java | eb4399095e1123735b211bd5efe010791ab9d566 | [] | no_license | fullop2/Greenfoot | 319f8af3418d59c97db2b251c206d7cbf0294fe0 | 283bfb192b012393f6690641ba54af78c7e451ee | refs/heads/master | 2021-01-11T06:51:09.184544 | 2016-12-04T15:30:26 | 2016-12-04T15:30:26 | 72,400,270 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 563 | java | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class GUI here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class GUI extends Actor
{
/**
* Act - do whatever the GUI wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
}
public GUI()
{}
public GUI(String location)
{
setImage(location);
}
}
| [
"[email protected]"
] | |
6bc68d457fdedd893314fb1f1d7c0c9b9497b257 | 025cc529c5ccb46db51707d17190b858e062225a | /src/pojo_summoner/SummonersBy.java | 4628be9a18ebdc753fb002b3074b255b5e1b4ea4 | [] | no_license | philzor/Riot-API-Testing | 5c076f5b1c2eda79190d11f3fdfa517a95f127ae | 6186aa1c412f0a4e5e550334dd3bcccf28b41a6c | refs/heads/master | 2021-01-19T06:30:15.480085 | 2014-04-02T20:28:19 | 2014-04-02T20:28:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 393 | java | package pojo_summoner;
public class SummonersBy {
public long id; // Summoner ID.
public String name; // Summoner name.
public int profileIconId; // ID of the summoner icon associated with the summoner.
public long revisionDate; //Date summoner was last modified specified as epoch milliseconds.
public long summonerLevel; //Summoner level associated with the summoner.
}
| [
"[email protected]"
] | |
b29253d55354bee9c21322c7a1cac90dce259e15 | 66ac0f0289e1c2308463f0422a04e100a9a14d98 | /server/modules/platform/api/src/org/labkey/api/query/QueryNestingOption.java | 7a174f3c6aa7284a04a09a01787565855e8add39 | [
"MIT"
] | permissive | praveenmunagapati/ms-registration-server | b4f860978f4b371cfb1fcb3c794d1315298638c2 | 49a851285dfbccbd0dc667f4a5ba1fcdbb2f0665 | refs/heads/master | 2022-04-19T00:15:59.055397 | 2020-04-14T06:12:38 | 2020-04-14T06:12:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,685 | java | /*
* Copyright (c) 2012-2019 LabKey Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.labkey.api.query;
import org.labkey.api.data.*;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.util.ArrayList;
/**
* Configuration for a NestedQueryView that understands which columns should be associated with the outer and inner
* grids. Also tracks the URL at which a specific nested grid can be requested independently via AJAX.
*
* User: jeckels
* Date: Apr 9, 2007
*/
public class QueryNestingOption
{
private FieldKey _rowIdFieldKey;
private FieldKey _aggregateRowIdFieldKey;
private final String _ajaxNestedGridURL;
private DataColumn _groupIdColumn;
/**
* @param aggregateRowIdColumn the column that's an FK to the table that should be shown in the parent grids
* @param rowIdColumn the column that's the PK (the target of the FK from aggregateRowIdColumn)
* @param ajaxNestedGridURL the URL to use to request the child grid via AJAX
*/
public QueryNestingOption(FieldKey aggregateRowIdColumn, FieldKey rowIdColumn, String ajaxNestedGridURL)
{
_aggregateRowIdFieldKey = aggregateRowIdColumn;
_rowIdFieldKey = rowIdColumn;
_ajaxNestedGridURL = ajaxNestedGridURL;
}
public void setupGroupIdColumn(List<DisplayColumn> allColumns, List<DisplayColumn> outerColumns, TableInfo parentTable)
{
if (_groupIdColumn != null)
{
return;
}
Map<FieldKey, ColumnInfo> infos = QueryService.get().getColumns(parentTable, Collections.singleton(_rowIdFieldKey));
assert infos.size() == 1;
ColumnInfo info = infos.values().iterator().next();
_groupIdColumn = new DataColumn(info);
_groupIdColumn.setVisible(false);
allColumns.add(_groupIdColumn);
outerColumns.add(_groupIdColumn);
}
public boolean isNested(List<DisplayColumn> columns)
{
boolean foundInner = false;
boolean foundOuter = false;
for (DisplayColumn column : columns)
{
if (isOuter(column))
{
foundOuter = true;
}
else
{
foundInner = true;
}
}
return foundOuter && foundInner;
}
private boolean isOuter(DisplayColumn column)
{
ColumnInfo colInfo = column.getColumnInfo();
return colInfo != null && isOuter(colInfo.getFieldKey());
}
public boolean isOuter(FieldKey fieldKey)
{
return fieldKey.toString().toLowerCase().startsWith(_aggregateRowIdFieldKey.toString().toLowerCase() + "/");
}
public FieldKey getRowIdFieldKey()
{
return _rowIdFieldKey;
}
public FieldKey getAggregateRowIdFieldKey()
{
return _aggregateRowIdFieldKey;
}
public NestableDataRegion createDataRegion(List<DisplayColumn> originalColumns, String dataRegionName, boolean expanded)
{
List<DisplayColumn> innerColumns = new ArrayList<>();
List<DisplayColumn> outerColumns = new ArrayList<>();
List<DisplayColumn> allColumns = new ArrayList<>(originalColumns);
for (DisplayColumn column : originalColumns)
{
if (isOuter(column))
{
setupGroupIdColumn(allColumns, outerColumns, column.getColumnInfo().getParentTable());
outerColumns.add(column);
}
else
{
innerColumns.add(column);
}
}
NestableDataRegion dataRegion = new NestableDataRegion(allColumns, _groupIdColumn.getColumnInfo().getAlias(), _ajaxNestedGridURL);
// Set the nested button bar as not visible so that we don't render a bunch of nested <form>s which mess up IE.
dataRegion.setButtonBar(new ButtonBar());
dataRegion.setExpanded(expanded);
dataRegion.setRecordSelectorValueColumns(_groupIdColumn.getColumnInfo().getAlias());
DataRegion nestedRgn = new DataRegion()
{
@Override
protected void renderHeaderScript(RenderContext ctx, Writer out, Map<String, String> messages, boolean showRecordSelectors)
{
// Issue 11405: customized grid does not work MS2 query based views.
// Nested DataRegions don't need to re-render the "new LABKEY.DataRegion(...)" script.
}
};
nestedRgn.setName(dataRegionName);
ButtonBar bar = new ButtonBar();
bar.setVisible(false);
nestedRgn.setShowFilterDescription(false);
nestedRgn.setButtonBar(bar);
nestedRgn.setDisplayColumns(innerColumns);
dataRegion.setNestedRegion(nestedRgn);
for (DisplayColumn column : outerColumns)
{
column.setCaption(column.getColumnInfo().getLabel());
}
dataRegion.setDisplayColumns(outerColumns);
return dataRegion;
}
}
| [
"[email protected]"
] | |
337276ddc05486681256e95495e6eab027d1328f | 479a1fd57be306787967c810dee33288b1cda518 | /LAB-5/src/Tile.java | 90dc318b4b249163a998fb6bf90d048887050ff5 | [] | no_license | saksham1210/CSE-201-Adavanced-Programming | 4f658fbe8e89aa32ac010e81813ed0d6ae2a3947 | 30e855c10cdb4d2291ed0dff0a74f78d47e91dc8 | refs/heads/main | 2023-02-01T19:47:46.325938 | 2020-12-21T05:09:47 | 2020-12-21T05:09:47 | 300,389,452 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,109 | java | import java.util.*;
public abstract class Tile
{
private static int snake_bites=0;
private static int cricket_bites=0;
private static int vulture_bites=0;
private static int trampoline_bites=0;
public static void setSnake_bites() {
Tile.snake_bites +=1;
}
public static void setCricket_bites() {
Tile.cricket_bites += 1;
}
public static void setVulture_bites() {
Tile.vulture_bites +=1;
}
public static void setTrampoline_bites() {
Tile.trampoline_bites +=1;
}
public static int getCricket_bites() {
return cricket_bites;
}
public static int getVulture_bites() {
return vulture_bites;
}
public static int getTrampoline_bites() {
return trampoline_bites;
}
public static int getSnake_bites() {
return snake_bites;
}
public abstract boolean getVisited();
public abstract void setVisited(boolean visit);
public abstract int getAttack();
public abstract void shake(int position) throws VulturebiteException, SnakebiteException, CriketbiteException, TrampolineException;
}
class Vulture extends Tile
{
Vulture(int att)
{
attack= att;
}
private int attack;
private boolean visited;
@Override
public boolean getVisited() {
return visited;
}
@Override
public void setVisited(boolean visit) {
visited=visit;
}
public int getAttack() {
return attack;
}
@Override
public void shake(int position) throws VulturebiteException {
System.out.println("Trying to Shake Tile: "+(position+1));
setVulture_bites();
throw new VulturebiteException("Yapping!.... I am Vulture");
}
}
class Snake extends Tile
{
private int attack;
public int getAttack() {
return attack;
}
private boolean visited;
@Override
public boolean getVisited() {
return visited;
}
@Override
public void setVisited(boolean visit) {
visited=visit;
}
Snake(int att)
{
attack= att;
}
@Override
public void shake(int position) throws SnakebiteException {
System.out.println("Trying to Shake Tile: "+(position+1));
setSnake_bites();
throw new SnakebiteException("Hiss.....I am a Snake");
}
}
class Cricket extends Tile
{
private int attack;
public int getAttack() {
return attack;
}
private boolean visited;
@Override
public boolean getVisited() {
return visited;
}
@Override
public void setVisited(boolean visit) {
visited=visit;
}
Cricket(int att)
{
attack= att;
}
@Override
public void shake(int position) throws CriketbiteException {
System.out.println("Trying to Shake Tile: "+(position+1));
setCricket_bites();
throw new CriketbiteException("Chirp!... I am a Cricket");
}
}
class Trampoline extends Tile
{
private int attack;
public int getAttack() {
return attack;
}
private boolean visited;
@Override
public boolean getVisited() {
return visited;
}
@Override
public void setVisited(boolean visit) {
visited=visit;
}
Trampoline(int att)
{
attack= att;
}
@Override
public void shake(int position) throws TrampolineException {
System.out.println("Trying to Shake Tile: "+(position+1));
setTrampoline_bites();
throw new TrampolineException("PingPong! I am a Trampoline");
}
}
class White extends Tile
{
private int attack;
public int getAttack() {
return attack;
}
private boolean visited;
@Override
public boolean getVisited() {
return visited;
}
@Override
public void setVisited(boolean visit) {
visited=visit;
}
White(int att)
{
attack= att;
}
@Override
public void shake(int position) {
System.out.println("Trying to Shake Tile: "+(position+1));
System.out.println("I am a normal Tile");
}
} | [
"[email protected]"
] | |
af4e0c729d02386e616ec900282e48744c789413 | a2de1cb6968bedd3f73cf9533561ce1d4f55f8d3 | /app/src/main/java/com/iiitd/hammad13060/trackme/SourceDestinationClasses/ContactAdapter.java | d68ea4c82097aab482af49afcab340618d703f01 | [] | no_license | hammad13060-zz/TrackMe | a7e5e08bf0d621cb137929e8c342decf0800b883 | e0066e702ac569009d1b1cd9c39f256525184355 | refs/heads/master | 2021-06-05T11:02:41.755335 | 2016-05-18T17:48:53 | 2016-05-18T17:48:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,413 | java | package com.iiitd.hammad13060.trackme.SourceDestinationClasses;
/**
* Created by Pushkin on 02-Feb-16.
*/
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.iiitd.hammad13060.trackme.R;
import com.iiitd.hammad13060.trackme.helpers.Contact;
public class ContactAdapter extends ArrayAdapter<Contact>{
SparseBooleanArray checkContacts;
int layoutResourceId;
public static List<Contact> contList;
public ContactAdapter(Context context, List<Contact> users) {
super(context, 0, users);
contList = users;
}
@Override
public int getCount() {
return contList.size();
}
@Override
public Contact getItem(int position) {
return contList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Contact user = getContact(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_view, parent, false);
}
TextView tvName = (TextView) convertView.findViewById(R.id.name);
CheckBox chk = (CheckBox) convertView.findViewById(R.id.chk_box);
tvName.setText(user.name);
chk.setOnCheckedChangeListener(myCheckChangList);
chk.setTag(position);
chk.setChecked(user.box);
return convertView;
}
Contact getContact(int position)
{
return ((Contact) getItem(position));
}
static List<Contact> getBox() {
List<Contact> box = new ArrayList<>();
for (Contact p : contList) {
if (p.box)
box.add(p);
}
return box;
}
CompoundButton.OnCheckedChangeListener myCheckChangList = new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
getContact((Integer) buttonView.getTag()).box = isChecked;
}
};
}
| [
"[email protected]"
] | |
a0e887e9ed1c6fa7bec7709884e8d18752b47274 | 89b27262a916c413fcb979629cc74d1759f02d75 | /app/src/main/java/com/lite/main/mvvm/repo/Repository.java | 7b71885502723977c520f62d6c524df745cccfb8 | [] | no_license | saketp18/MVVM_Retrofit | bbf04ff3adfcfaec7d135856f794431056995867 | 64dd226f1d90f8e372c15fd10253a1d15de5bc41 | refs/heads/master | 2020-07-07T17:33:24.338661 | 2019-08-21T22:16:13 | 2019-08-21T22:16:13 | 203,423,032 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,054 | java | package com.lite.main.mvvm.repo;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.lite.main.mvvm.models.ErrorResponse;
import com.lite.main.mvvm.models.ImageSource;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import java.util.List;
public class Repository {
private static Repository repository = null;
private MutableLiveData<List<ImageSource>> data = new MutableLiveData<>();
private MutableLiveData<ErrorResponse> error = new MutableLiveData<>();
private Repository() {
}
public static Repository getRepository(){
if(repository == null){
repository = new Repository();
}
return repository;
}
public LiveData<List<ImageSource>> getLiveData(){
return data;
}
public LiveData<ErrorResponse> getError() {
return error;
}
public void getData(int page, int pageSize){
Call<List<ImageSource>> call = RetrofitClientInstance.getClient().getImages(page);
call.enqueue(new Callback<List<ImageSource>>() {
@Override
public void onResponse(Call<List<ImageSource>> call, Response<List<ImageSource>> response) {
if(response.isSuccessful()){
data.setValue(response.body());
}else {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setError(response.errorBody().toString());
errorResponse.setStatus(ErrorResponse.STATUS.RESPONSE_FAIL.ordinal());
error.setValue(errorResponse);
}
}
@Override
public void onFailure(Call<List<ImageSource>> call, Throwable t) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setError(t.getMessage());
errorResponse.setStatus(ErrorResponse.STATUS.FAILURE.ordinal());
error.setValue(errorResponse);
}
});
}
}
| [
"[email protected]"
] | |
cc038c9d249e75bc672e8aac930b4e831d7d081c | 21f0bf27aba68fc2db706b481b31c9728b5e96c4 | /TPs/tp1/TP01Q15 - RECURSIVO - Is em Java/isR.java | a1fc617c1fcd67709570e355296e48281444a57a | [] | no_license | W-F-S/AED2 | 939e91f349b316b43e47945c65d4160202f15517 | 91b77399c2c6b5f189a8a2c0cbbd00b1eac2b0f8 | refs/heads/master | 2023-03-02T20:13:42.580689 | 2021-01-27T16:28:01 | 2021-01-27T16:28:01 | 323,716,396 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,092 | java | class isR{
/**setPalavra(String imput)
*
* Setar a string lida
*
* @param: String imput - string lida
* @return: nda
*/
public static boolean fim(String palavra){
return ((palavra.length() == 3) && (palavra.charAt(0) == 'F') && (palavra.charAt(1) == 'I') && (palavra.charAt(2) == 'M'));//vendo a palavra especial
}
/**
Metodo para verificar se um determinado char e' uma letra
@param: char let: char a ser analizado
@return: true: caso seja uma letra
false: caso nao seja uma letra
*/
public static boolean letra(char let){
return (let >='A' && let <= 'Z' || let >='a' && let <= 'z');//vendo a palavra especial
}
/**
Metodo para escrever na tela um Sim ou Nao
@param: boolean resp;
true: caso resp seja true
false: caso nao seja uma letra
@return: ...
*/
public static void simNao(boolean resp){ //apenas para mover os prints do main para um local mais isolado
if (resp){
System.out.printf("SIM ");
}else{
System.out.printf("NAO ");
}
}
/**
Metodo para ver se um certo char e um numero
@param: char let: char a ser analizado
@return: true: caso seja um numero
false: caso nao seja um numero
*/
public static boolean num(char letra){
return( letra >= '0' && letra <= '9');
}
/**
Function to see if a char is a vowel
//
@param: char let: char a ser analizado
@return: true: caso seja uma vogal
false: caso nao seja uma vogal
*/
public static boolean vol(char let){
return (let == 'a' || let == 'A' || let == 'e' || let == 'E' || let == 'o' || let == 'O' || let == 'i' || let == 'I' || let == 'u' || let == 'U');
}
/**
metodo para ver se e uma consoante
@param: char let: char a ser analizado
@return: true: caso seja uma consoante
false: caso nao seja uma consoante
*/
public static boolean con(char let){
return ( (!vol(let)) && ((let >= 'A' && let <= 'Z') || (let >= 'a' && let <= 'z')) );
}
/**
metodo para ver se e um numero real
@param: string palavra: string a ser analisada
int i : usado para a recursividade, sempre igual a zero
int garantia : usado para garantir que so exista uma , ou .
@return: true: caso seja um numero real
false: caso nao seja um numero real
*/
public static boolean isReal(String palavra, int i, int garantia){
boolean resp = true;
if( i < palavra.length()){
char L = palavra.charAt(i);
if(!(num(L)) ){
if ( (L == '.' || L == ',') && garantia < 1 ){
garantia++;
i++;
resp = isReal(palavra, i, garantia);
}else{
resp = false;
}
}else{
i++;
resp = isReal(palavra, i, garantia);
}
}
return resp;
}
/**
metodo para ver se e um numero inteiro
@param: string palavra: string a ser analisada
int i : usado para a recursividade, sempre igual a zero
@return: true: caso seja um numero inteiro
false: caso nao seja um numero inteiro
*/
public static boolean isInt(String palavra, int i){//funcionando d boa
boolean resp = true;
if(i < palavra.length()){
if( !num(palavra.charAt(i)) ){
//MyIO.println("\nNao e int == "+ palavra.charAt(i));
resp = false;
} else {
resp = isInt(palavra, i+1);
}
}
return (resp);
}
/**
metodo para ver se e uma consoante
@param: string palavra: string a ser analisada
int i : usado para a recursividade, sempre igual a zero
@return: true: caso seja uma consoante
false: caso nao seja uma consoante
*/
public static boolean isConsoantes(String palavra, int i){//funcionando de boa
boolean resp = true;
if(i < palavra.length()){
if( !con(palavra.charAt(i)) ){
//MyIO.println("\nNao e consoante == "+ palavra.charAt(i));
resp = false;
} else {
resp = isConsoantes(palavra, i+1);
}
}
return (resp );
}
/**
metodo para ver se e uma vogal
@param: string palavra: string a ser analisada
int i : usado para a recursividade, sempre igual a zero
@return: true: caso seja uma vogal
false: caso nao seja uma vogal
*/
public static boolean isVogais(String palavra, int i){//ver se vogao
boolean resp = true;
if(i < palavra.length()){
if( !vol(palavra.charAt(i)) ){//ver se e' vogal maiuscula ou minuscula.
// MyIO.println("\nNao e vogal == "+ palavra.charAt(i));
resp = false;
} else {
resp = isVogais(palavra, i+1);
}
}
return resp;//retorna false se nao for vogal
}
public static void main(String[] args){
String palavra = MyIO.readLine();
while(!fim(palavra)){
simNao(isVogais(palavra, 0));
simNao(isConsoantes(palavra, 0));
simNao(isInt(palavra, 0 ));
simNao(isReal(palavra, 0 , 0));
MyIO.print("\n");
palavra = MyIO.readLine();;
}
}
}
| [
"[email protected]"
] | |
2b3e53e5ae6cfec426f89092d975db0c12a64ca3 | 40507d7cead34ca96d808cca0ec4b39685680c9f | /src/main/java/uk/co/businessitsolution/ui/crud/CrudEntityPresenter.java | 1fc8e3e3bf8089cc9cf3a584b6fe76718e4d4e39 | [
"Unlicense"
] | permissive | bits-ltd/RecruitmentSpring | 7addd6f4b947e68349f0741c2d73644152479e7d | f63f508a4ea20257391cb48fd35f62f320219ab7 | refs/heads/master | 2023-01-09T16:40:30.345416 | 2020-02-07T18:02:07 | 2020-02-07T18:02:07 | 229,152,264 | 0 | 0 | Unlicense | 2023-01-07T14:35:56 | 2019-12-19T23:01:20 | Java | UTF-8 | Java | false | false | 2,755 | java | package uk.co.businessitsolution.ui.crud;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.OptimisticLockingFailureException;
import uk.co.businessitsolution.app.HasLogger;
import uk.co.businessitsolution.app.security.CurrentUser;
import uk.co.businessitsolution.backend.entity.AbstractEntity;
import uk.co.businessitsolution.backend.service.CrudService;
import uk.co.businessitsolution.backend.service.UserFriendlyDataException;
import uk.co.businessitsolution.ui.HasNotifications;
import uk.co.businessitsolution.ui.utils.messages.CrudErrorMessage;
import javax.persistence.EntityNotFoundException;
import javax.validation.ConstraintViolationException;
import java.util.function.Consumer;
public class CrudEntityPresenter<E extends AbstractEntity> implements HasLogger {
private final CrudService<E> crudService;
private final CurrentUser currentUser;
private final HasNotifications view;
public CrudEntityPresenter(CrudService<E> crudService, CurrentUser currentUser, HasNotifications view) {
this.crudService = crudService;
this.currentUser = currentUser;
this.view = view;
}
public void delete(E entity, Consumer<E> onSuccess, Consumer<E> onFail) {
if (executeOperation(() -> crudService.delete(currentUser.getUser(), entity))) {
onSuccess.accept(entity);
} else {
onFail.accept(entity);
}
}
public void save(E entity, Consumer<E> onSuccess, Consumer<E> onFail) {
if (executeOperation(() -> saveEntity(entity))) {
onSuccess.accept(entity);
} else {
onFail.accept(entity);
}
}
private boolean executeOperation(Runnable operation) {
try {
operation.run();
return true;
} catch (UserFriendlyDataException e) {
// Commit failed because of application-level data constraints
consumeError(e, e.getMessage(), true);
} catch (DataIntegrityViolationException e) {
// Commit failed because of validation errors
consumeError(
e, CrudErrorMessage.OPERATION_PREVENTED_BY_REFERENCES, true);
} catch (OptimisticLockingFailureException e) {
consumeError(e, CrudErrorMessage.CONCURRENT_UPDATE, true);
} catch (EntityNotFoundException e) {
consumeError(e, CrudErrorMessage.ENTITY_NOT_FOUND, false);
} catch (ConstraintViolationException e) {
consumeError(e, CrudErrorMessage.REQUIRED_FIELDS_MISSING, false);
}
return false;
}
private void consumeError(Exception e, String message, boolean isPersistent) {
getLogger().debug(message, e);
view.showNotification(message, isPersistent);
}
private void saveEntity(E entity) {
crudService.save(currentUser.getUser(), entity);
}
public boolean loadEntity(Long id, Consumer<E> onSuccess) {
return executeOperation(() -> onSuccess.accept(crudService.load(id)));
}
}
| [
"[email protected]"
] | |
abfc5306225ff9e1140f22b2b53698c01254bac9 | 4bb83687710716d91b5da55054c04f430474ee52 | /dsrc/sku.0/sys.server/compiled/game/script/conversation/junk_reggi_nym.java | e33ca3f5284b545a8c9502cd017a5dab4403c5f5 | [] | no_license | geralex/SWG-NGE | 0846566a44f4460c32d38078e0a1eb115a9b08b0 | fa8ae0017f996e400fccc5ba3763e5bb1c8cdd1c | refs/heads/master | 2020-04-06T11:18:36.110302 | 2018-03-19T15:42:32 | 2018-03-19T15:42:32 | 157,411,938 | 1 | 0 | null | 2018-11-13T16:35:01 | 2018-11-13T16:35:01 | null | UTF-8 | Java | false | false | 9,234 | java | package script.conversation;
import script.*;
import script.base_class.*;
import script.combat_engine.*;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Vector;
import script.base_script;
import script.library.ai_lib;
import script.library.chat;
import script.library.smuggler;
import script.library.utils;
public class junk_reggi_nym extends script.base_script
{
public junk_reggi_nym()
{
}
public static String c_stringFile = "conversation/junk_reggi_nym";
public boolean junk_reggi_nym_condition__defaultCondition(obj_id player, obj_id npc) throws InterruptedException
{
return true;
}
public boolean junk_reggi_nym_condition_check_inv(obj_id player, obj_id npc) throws InterruptedException
{
return smuggler.checkInventory(player, npc);
}
public void junk_reggi_nym_action_start_dealing(obj_id player, obj_id npc) throws InterruptedException
{
dictionary params = new dictionary();
params.put("player", player);
messageTo(npc, "startDealing", params, 1.0f, false);
}
public void junk_reggi_nym_action_face_to(obj_id player, obj_id npc) throws InterruptedException
{
faceTo(npc, player);
}
public int junk_reggi_nym_handleBranch1(obj_id player, obj_id npc, string_id response) throws InterruptedException
{
if (response.equals("s_ef8c7236"))
{
if (junk_reggi_nym_condition__defaultCondition(player, npc))
{
string_id message = new string_id(c_stringFile, "s_14e5bdc0");
int numberOfResponses = 0;
boolean hasResponse = false;
boolean hasResponse0 = false;
if (junk_reggi_nym_condition_check_inv(player, npc))
{
++numberOfResponses;
hasResponse = true;
hasResponse0 = true;
}
boolean hasResponse1 = false;
if (junk_reggi_nym_condition__defaultCondition(player, npc))
{
++numberOfResponses;
hasResponse = true;
hasResponse1 = true;
}
if (hasResponse)
{
int responseIndex = 0;
string_id responses[] = new string_id[numberOfResponses];
if (hasResponse0)
{
responses[responseIndex++] = new string_id(c_stringFile, "s_b8e27f3c");
}
if (hasResponse1)
{
responses[responseIndex++] = new string_id(c_stringFile, "s_2e005077");
}
utils.setScriptVar(player, "conversation.junk_reggi_nym.branchId", 2);
npcSpeak(player, message);
npcSetConversationResponses(player, responses);
}
else
{
utils.removeScriptVar(player, "conversation.junk_reggi_nym.branchId");
npcEndConversationWithMessage(player, message);
}
return SCRIPT_CONTINUE;
}
}
if (response.equals("s_53d778d8"))
{
if (junk_reggi_nym_condition__defaultCondition(player, npc))
{
string_id message = new string_id(c_stringFile, "s_f25d9c2");
utils.removeScriptVar(player, "conversation.junk_reggi_nym.branchId");
npcEndConversationWithMessage(player, message);
return SCRIPT_CONTINUE;
}
}
return SCRIPT_DEFAULT;
}
public int junk_reggi_nym_handleBranch2(obj_id player, obj_id npc, string_id response) throws InterruptedException
{
if (response.equals("s_b8e27f3c"))
{
if (junk_reggi_nym_condition__defaultCondition(player, npc))
{
junk_reggi_nym_action_start_dealing(player, npc);
string_id message = new string_id(c_stringFile, "s_5c453a2f");
utils.removeScriptVar(player, "conversation.junk_reggi_nym.branchId");
npcEndConversationWithMessage(player, message);
return SCRIPT_CONTINUE;
}
}
if (response.equals("s_2e005077"))
{
if (junk_reggi_nym_condition__defaultCondition(player, npc))
{
string_id message = new string_id(c_stringFile, "s_233f3214");
utils.removeScriptVar(player, "conversation.junk_reggi_nym.branchId");
npcEndConversationWithMessage(player, message);
return SCRIPT_CONTINUE;
}
}
return SCRIPT_DEFAULT;
}
public int OnInitialize(obj_id self) throws InterruptedException
{
if ((!isMob(self)) || (isPlayer(self)))
{
detachScript(self, "conversation.junk_reggi_nym");
}
setCondition(self, CONDITION_CONVERSABLE);
return SCRIPT_CONTINUE;
}
public int OnAttach(obj_id self) throws InterruptedException
{
setCondition(self, CONDITION_CONVERSABLE);
return SCRIPT_CONTINUE;
}
public int OnObjectMenuRequest(obj_id self, obj_id player, menu_info menuInfo) throws InterruptedException
{
int menu = menuInfo.addRootMenu(menu_info_types.CONVERSE_START, null);
menu_info_data menuInfoData = menuInfo.getMenuItemById(menu);
menuInfoData.setServerNotify(false);
setCondition(self, CONDITION_CONVERSABLE);
return SCRIPT_CONTINUE;
}
public int OnIncapacitated(obj_id self, obj_id killer) throws InterruptedException
{
clearCondition(self, CONDITION_CONVERSABLE);
detachScript(self, "conversation.junk_reggi_nym");
return SCRIPT_CONTINUE;
}
public boolean npcStartConversation(obj_id player, obj_id npc, String convoName, string_id greetingId, prose_package greetingProse, string_id[] responses) throws InterruptedException
{
Object[] objects = new Object[responses.length];
System.arraycopy(responses, 0, objects, 0, responses.length);
return npcStartConversation(player, npc, convoName, greetingId, greetingProse, objects);
}
public int OnStartNpcConversation(obj_id self, obj_id player) throws InterruptedException
{
obj_id npc = self;
if (ai_lib.isInCombat(npc) || ai_lib.isInCombat(player))
{
return SCRIPT_OVERRIDE;
}
if (junk_reggi_nym_condition__defaultCondition(player, npc))
{
junk_reggi_nym_action_face_to(player, npc);
string_id message = new string_id(c_stringFile, "s_60d2f507");
int numberOfResponses = 0;
boolean hasResponse = false;
boolean hasResponse0 = false;
if (junk_reggi_nym_condition__defaultCondition(player, npc))
{
++numberOfResponses;
hasResponse = true;
hasResponse0 = true;
}
boolean hasResponse1 = false;
if (junk_reggi_nym_condition__defaultCondition(player, npc))
{
++numberOfResponses;
hasResponse = true;
hasResponse1 = true;
}
if (hasResponse)
{
int responseIndex = 0;
string_id responses[] = new string_id[numberOfResponses];
if (hasResponse0)
{
responses[responseIndex++] = new string_id(c_stringFile, "s_ef8c7236");
}
if (hasResponse1)
{
responses[responseIndex++] = new string_id(c_stringFile, "s_53d778d8");
}
utils.setScriptVar(player, "conversation.junk_reggi_nym.branchId", 1);
npcStartConversation(player, npc, "junk_reggi_nym", message, responses);
}
else
{
chat.chat(npc, player, message);
}
return SCRIPT_CONTINUE;
}
chat.chat(npc, "Error: All conditions for OnStartNpcConversation were false.");
return SCRIPT_CONTINUE;
}
public int OnNpcConversationResponse(obj_id self, String conversationId, obj_id player, string_id response) throws InterruptedException
{
if (!conversationId.equals("junk_reggi_nym"))
{
return SCRIPT_CONTINUE;
}
obj_id npc = self;
int branchId = utils.getIntScriptVar(player, "conversation.junk_reggi_nym.branchId");
if (branchId == 1 && junk_reggi_nym_handleBranch1(player, npc, response) == SCRIPT_CONTINUE)
{
return SCRIPT_CONTINUE;
}
if (branchId == 2 && junk_reggi_nym_handleBranch2(player, npc, response) == SCRIPT_CONTINUE)
{
return SCRIPT_CONTINUE;
}
chat.chat(npc, "Error: Fell through all branches and responses for OnNpcConversationResponse.");
utils.removeScriptVar(player, "conversation.junk_reggi_nym.branchId");
return SCRIPT_CONTINUE;
}
}
| [
"[email protected]"
] | |
8434fd9b437ae8b129f68b05893c820216c69e6c | 302eae5c4a1ba68d3434f03d9e5e2c4d4add8851 | /app/src/main/java/com/ahuo/myapp2/net/retrfit/FastJsonResponseBodyConverter.java | e3870575046253a3e9dd69377dd6e4e66726e6ef | [] | no_license | wanhuo6/BaseApp | 9a33e9abb801406590da344e6f4ba7fd103e72b9 | f5c65756577d12b5de1ce93e7590ee7561016a61 | refs/heads/master | 2022-02-18T17:11:08.686690 | 2019-07-29T03:06:12 | 2019-07-29T03:06:12 | 104,046,372 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 844 | java | package com.ahuo.myapp2.net.retrfit;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import okio.BufferedSource;
import okio.Okio;
import retrofit2.Converter;
/**
* Created on 17-8-1
*
* @author liuhuijie
*/
public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Type type;
public FastJsonResponseBodyConverter(Type type){
this.type = type;
}
@Override
public T convert(ResponseBody value) throws IOException {
BufferedSource bufferedSource = Okio.buffer(value.source());
String tempStr = bufferedSource.readUtf8();
bufferedSource.close();
Log.e("response-----",tempStr);
return JSON.parseObject(tempStr, type);
}
}
| [
"[email protected]"
] | |
e5e7082ced4fe9794edcbbaf3d7c46989c32e2b1 | b9469e1bde90abece9648eb4f8f343210e0b4a9d | /src/main/java/com/isabo/battletank/repository/UserRepository.java | fc68e4effe57f8794ddba04318896df3a6cb86c9 | [] | no_license | MatthieuBlm/TankDeluxe3000 | d52aabdf62b901d2eec5df7a95550dd45c7b5557 | 0a9391b7ec6846fc58648d11ec6dca425d961db6 | refs/heads/master | 2020-07-31T08:15:53.718888 | 2019-09-23T17:27:28 | 2019-09-23T17:27:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 259 | java | package com.isabo.battletank.repository;
import org.springframework.data.repository.CrudRepository;
import com.isabo.battletank.entity.User;
public interface UserRepository extends CrudRepository<User, Long> {
public User findByLogin(String username);
} | [
"[email protected]"
] | |
3f38659469b5daa46943860a76de9a7a6f30cb5b | 74837bd6f03a44bdae0ca7a3cb9ced88ff4ced51 | /src/com/devol/client/view/uimantprestamo/UIMantPrestamo.java | ad1e5b25ac0b5c9e2a410570454c601acab9b7ed | [] | no_license | jofrantoba/devol | 493f1d5db4c929af420a3151d4e554c97d22f69a | 17b55450e4242273ef94a40fe8d7246b56770047 | refs/heads/master | 2020-04-15T02:35:51.815640 | 2019-11-25T01:32:51 | 2019-11-25T01:32:51 | 40,623,734 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 16,378 | java | package com.devol.client.view.uimantprestamo;
import java.math.BigDecimal;
import com.devol.client.beanproxy.ClienteProxy;
import com.devol.client.beanproxy.PrestamoProxy;
import com.devol.client.beanproxy.UsuarioProxy;
import com.devol.client.model.ContentForm;
import com.devol.client.model.HeaderPanelM;
import com.devol.client.model.TextBoxCalendar;
import com.devol.client.resource.MyResource;
import com.devol.client.util.Notification;
import com.devol.i18n.DevolConstants;
import com.devol.shared.FieldVerifier;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.TouchEndEvent;
import com.google.gwt.event.dom.client.TouchEndHandler;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.googlecode.mgwt.ui.client.MGWT;
import com.googlecode.mgwt.ui.client.MGWTSettings;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
//import com.googlecode.mgwt.ui.client.widget.panel.scroll.ScrollPanel;
public class UIMantPrestamo extends Composite implements InterUIMantPrestamo,
TouchEndHandler,KeyUpHandler,BlurHandler,ClickHandler {
private DevolConstants constants = GWT.create(DevolConstants.class);
private VerticalPanel main;
private HeaderPanelM header;
private Label lblCenter;
private PushButton btnBack;
//private FlowPanel container;
public ScrollPanel scrollPanel;
private FlowPanel contenido;
private FlowPanel pnlForm;
private ContentForm contentForm;
protected TextBox txtCodigo;
protected TextBoxCalendar txtFecha;
protected TextBox txtMonto;
protected TextBox txtTasa;
protected TextBox txtADevolver;
protected TextBox txtDevuelto;
protected TextBox txtCliente;
protected TextBox txtTipoPrestamo;
protected TextBox txtGlosa;
protected Button btnGuardar;
private FlowPanel pnlTxtCliente;
//private FlowPanel pnlTxtCalendar;
private PushButton btnClienteAdd;
//private ButtonBarButtonBase btnCalendarAdd;
private FlexTable flexTable;
//private FlexTable flexTableCalendar;
protected ClienteProxy beanCliente;
protected PrestamoProxy beanPrestamo;
//private UIClienteSelect dialogCliente;
protected String modo;
protected String modoPrestamo;
public UIMantPrestamo() {
init();
initWidgetListener();
style();
reCalcularWindows();
}
private void init() {
beanCliente=null;
main = new VerticalPanel();
initWidget(main);
//Window.addResizeHandler(this);
header = new HeaderPanelM();
lblCenter = new Label(constants.modoNuevo());
header.setCenterWidget(lblCenter);
main.add(header);
btnBack = new PushButton(new Image(MyResource.INSTANCE.getImgBack32()));
header.setLeftWidget(btnBack);
//container = new FlowPanel();
//main.add(container);
scrollPanel = new ScrollPanel();
/*scrollPanel.setScrollingEnabledY(true);
scrollPanel.setScrollingEnabledX(false);
scrollPanel.setAutoHandleResize(true);*/
/*scrollPanel.setScrollingEnabledX(false);
scrollPanel.setScrollingEnabledY(true);
scrollPanel.setAutoHandleResize(true);*/
//scrollPanel.setUsePos(MGWT.getOsDetection().isAndroid());
contenido = new FlowPanel();
scrollPanel.setWidget(contenido);
pnlForm = new FlowPanel();
contenido.add(pnlForm);
contentForm = new ContentForm();
pnlForm.add(contentForm);
txtCodigo = new TextBox();
//contentForm.addWidget("Codigo", txtCodigo);
//pnlTxtCalendar = new FlowPanel();
txtFecha = new TextBoxCalendar();
contentForm.addWidget("* "+constants.fecha(), txtFecha);
//flexTableCalendar = new FlexTable();
//pnlTxtCalendar.add(flexTableCalendar);
//flexTableCalendar.setWidget(0, 0, txtFecha);
//btnCalendarAdd = new ButtonBarButtonBase(
// MyResource.INSTANCE.getImgCalendar32());
//flexTableCalendar.setWidget(0, 1, btnCalendarAdd);
txtMonto = new TextBox();
contentForm.addWidget("* "+constants.monto(), txtMonto);
txtTasa = new TextBox();
contentForm.addWidget("* "+constants.tasa()+"(%) ", txtTasa);
txtADevolver = new TextBox();
contentForm.addWidget(constants.aDevolver(), txtADevolver);
txtDevuelto = new TextBox();
contentForm.addWidget(constants.devuelto(), txtDevuelto);
pnlTxtCliente = new FlowPanel();
contentForm.addWidget("* "+constants.clientes(), pnlTxtCliente);
txtTipoPrestamo=new TextBox();
contentForm.addWidget("Tipo Prestamo", txtTipoPrestamo);
txtGlosa=new TextBox();
contentForm.addWidget("Glosa", txtGlosa);
flexTable = new FlexTable();
pnlTxtCliente.add(flexTable);
txtCliente = new TextBox();
txtCliente.setReadOnly(true);
flexTable.setWidget(0, 0, txtCliente);
btnClienteAdd = new PushButton(
new Image(MyResource.INSTANCE.getImgClieAdd32()));
flexTable.setWidget(0, 1, btnClienteAdd);
btnGuardar = new Button(constants.guardar());
//btnGuardar.setConfirm(true);
contenido.add(btnGuardar);
scrollPanel.setWidget(contenido);
main.add(scrollPanel);
Window.addResizeHandler(new ResizeHandler(){
@Override
public void onResize(ResizeEvent event) {
// TODO Auto-generated method stub
reCalcularWindows();
}});
}
private void reCalcularWindows(){
//setWidthGrid();
setHeightContainer(100);
setWidthPnlFlexTable();
}
private void setWidthPnlFlexTable() {
int width = Window.getClientWidth();
width = width - 20;
// pnlForm.setWidth(width + "px");
}
public void setModo(String modo) {
this.modo = modo;
lblCenter.setText(modo);
}
public void setBean(PrestamoProxy bean) {
this.beanPrestamo = bean;
llenarCampos();
}
private void llenarCampos() {
txtCodigo.setText(beanPrestamo.getIdPrestamo());
txtADevolver.setText(beanPrestamo.getaDevolver().toString());
txtDevuelto.setText(beanPrestamo.getDevuelto().toString());
txtMonto.setText(beanPrestamo.getMonto().toString());
txtTasa.setText(beanPrestamo.getTasa().toString());
DateTimeFormat format = DateTimeFormat.getFormat("dd/MM/yyyy");
String fecha=format.format(beanPrestamo.getFecha());
txtFecha.getTxtFecha().setText(fecha);
txtCliente.setText(beanPrestamo.getBeanCliente().getNombre()+" "+beanPrestamo.getBeanCliente().getApellido());
beanCliente=beanPrestamo.getBeanCliente();
txtTipoPrestamo.setText(beanPrestamo.getTipoPrestamo());
txtGlosa.setText(beanPrestamo.getGlosa());
}
public void activarCampos() {
if(modo.equalsIgnoreCase(constants.modoEliminar())){
txtCodigo.setReadOnly(true);
txtADevolver.setReadOnly(true);
txtDevuelto.setReadOnly(true);
txtMonto.setReadOnly(true);
txtTasa.setReadOnly(true);
txtTipoPrestamo.setReadOnly(true);
txtGlosa.setReadOnly(true);
btnGuardar.setVisible(true);
}else if(modo.equalsIgnoreCase(constants.modoEditar())){
txtCodigo.setReadOnly(true);
txtADevolver.setReadOnly(true);
txtDevuelto.setReadOnly(true);
txtMonto.setReadOnly(false);
txtTasa.setReadOnly(false);
txtTipoPrestamo.setReadOnly(false);
txtGlosa.setReadOnly(false);
if(modoPrestamo.equals("HISTORIAL")){
btnGuardar.setVisible(true);
}else{
btnGuardar.setVisible(true);
}
}else{
txtCodigo.setReadOnly(true);
txtADevolver.setReadOnly(true);
txtDevuelto.setReadOnly(true);
txtMonto.setReadOnly(false);
txtTasa.setReadOnly(false);
txtTipoPrestamo.setReadOnly(false);
txtGlosa.setReadOnly(false);
if(modoPrestamo.equals("HISTORIAL")){
btnGuardar.setVisible(false);
}else{
btnGuardar.setVisible(true);
}
}
}
private void initWidgetListener() {
btnClienteAdd.addClickHandler(this);
btnBack.addClickHandler(this);
txtMonto.addKeyUpHandler(this);
txtMonto.addBlurHandler(this);
txtTasa.addKeyUpHandler(this);
txtTasa.addBlurHandler(this);
btnGuardar.addTouchEndHandler(this);
btnGuardar.addClickHandler(this);
}
protected void setHeightContainer(int heightHeader) {
int height = Window.getClientHeight();
scrollPanel.setHeight((height - heightHeader) + "px");
//this.scrollPanel.refresh();
}
private void style() {
Window.setMargin("0px");
MGWT.applySettings(MGWTSettings.getAppSetting());
btnGuardar.setWidth("97%");
btnGuardar.getElement().getStyle().setMarginBottom(50, Unit.PX);
btnGuardar.getElement().getStyle().setFontSize(2, Style.Unit.EM);
contenido.getElement().getStyle().setTextAlign(Style.TextAlign.CENTER);
MyResource.INSTANCE.getStlModel().ensureInjected();
btnBack.addStyleName(MyResource.INSTANCE.getStlModel().pushButton());
//main.setWidth("100%");
//container.setWidth("100%");
//setHeightContainer(41);
//scrollPanel.setWidth("100%");
//scrollPanel.setHeight("100%");
pnlForm.setWidth("100%");
contenido.setWidth("100%");
//pnlForm.getElement().getStyle().setOverflow(Overflow.HIDDEN);
flexTable.setCellPadding(0);
flexTable.setCellSpacing(0);
flexTable.setWidth("100%");
txtCliente.setWidth("100%");
FlexCellFormatter cellFormatter = flexTable.getFlexCellFormatter();
cellFormatter.setWidth(0, 1, "40");
flexTable.addStyleName(MyResource.INSTANCE.getStlModel()
.flexTableTextBoxCalendar());
txtCliente.addStyleName(MyResource.INSTANCE.getStlModel()
.textBoxFechaTextBoxCalendar());
btnClienteAdd.setHeight("25px");
//btnClienteAdd.getElement().getStyle().setBackgroundColor("#0C0FB8");
/*flexTableCalendar.setCellPadding(0);
flexTableCalendar.setCellSpacing(0);
flexTableCalendar.setWidth("100%");
txtFecha.setWidth("100%");
FlexCellFormatter cellFormatterCal = flexTableCalendar.getFlexCellFormatter();
cellFormatterCal.setWidth(0, 1, "40");
flexTableCalendar.addStyleName(MyResource.INSTANCE.getStlModel()
.flexTableTextBoxCalendar());
txtFecha.addStyleName(MyResource.INSTANCE.getStlModel()
.textBoxFechaTextBoxCalendar());
btnCalendarAdd.setHeight("32px");*/
//btnCalendarAdd.getElement().getStyle().setBackgroundColor("#0C0FB8");
}
/*@Override
public void onResize(ResizeEvent event) {
// TODO Auto-generated method stub
setHeightContainer(41);
setWidthDialog();
}*/
/*public void setWidthDialog(){
int width = Window.getClientWidth();
int height = Window.getClientHeight();
dialogCliente.setWidth((width-60)+"px");
dialogCliente.setHeight((height-80)+"px");
}*/
public void setBeanCliente(ClienteProxy bean){
beanCliente = bean;
txtCliente.setText(beanCliente.getNombre()+" "+beanCliente.getApellido());
}
@Override
public void goToUIPrestamo() {
// TODO Auto-generated method stub
}
@Override
public void registrar() {
// TODO Auto-generated method stub
}
@Override
public void goToUIClienteAdd() {
// TODO Auto-generated method stub
}
protected void calcularMontos(){
String monto=txtMonto.getText();
String tasa=txtTasa.getText();
String devuelto=txtDevuelto.getText();
BigDecimal vMonto=BigDecimal.ZERO;
BigDecimal vTasa=BigDecimal.ZERO;
BigDecimal vAdevolver=BigDecimal.ZERO;
BigDecimal vDevuelto=BigDecimal.ZERO;
if(monto!=null&&!monto.isEmpty()){
try{
if(modo.equalsIgnoreCase(constants.modoNuevo())){
vMonto=BigDecimal.valueOf(Double.parseDouble(monto));
}else if(modo.equalsIgnoreCase(constants.modoEditar())){
vMonto=BigDecimal.valueOf(Double.parseDouble(monto));
vDevuelto=BigDecimal.valueOf(Double.parseDouble(devuelto));
if(vMonto.compareTo(vDevuelto)<0){
vMonto=BigDecimal.valueOf(beanPrestamo.getMonto());
txtMonto.setText(vMonto.toString());
}
}
}catch(Exception ex){
vMonto=BigDecimal.ZERO;
txtMonto.setText(BigDecimal.ZERO.toString());
}
}else{
vMonto=BigDecimal.ZERO;
txtMonto.setText(vMonto.toString());
}
if(tasa!=null&&!tasa.isEmpty()){
try{
vTasa=BigDecimal.valueOf(Double.parseDouble(tasa));
}catch(Exception ex){
vTasa=BigDecimal.ZERO;
txtTasa.setText(vTasa.toString());
}
}else{
vTasa=BigDecimal.ZERO;
txtTasa.setText(vTasa.toString());
}
if(devuelto!=null&&!devuelto.isEmpty()){
try{
vDevuelto=BigDecimal.valueOf(Double.parseDouble(devuelto));
}catch(Exception ex){
vDevuelto=BigDecimal.ZERO;
txtDevuelto.setText(vDevuelto.toString());
}
}else{
vDevuelto=BigDecimal.ZERO;
txtDevuelto.setText(vDevuelto.toString());
}
//vAdevolver=vMonto.add(vTasa.divide(BigDecimal.valueOf(100)).multiply(vMonto)).subtract(vDevuelto);
vAdevolver=vMonto.add(vTasa.divide(BigDecimal.valueOf(100)).multiply(vMonto));
txtADevolver.setText(vAdevolver.toString());
txtDevuelto.setText(vDevuelto.toString());
}
@Override
public void onKeyUp(KeyUpEvent event) {
// TODO Auto-generated method stub
if(event.getSource().equals(txtMonto)||event.getSource().equals(txtTasa))
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
calcularMontos();
}
}
@Override
public void onBlur(BlurEvent event) {
// TODO Auto-generated method stub
if(event.getSource().equals(txtMonto)||event.getSource().equals(txtTasa))
calcularMontos();
}
@Override
public boolean isValidData() {
// TODO Auto-generated method stub
if(!modo.equalsIgnoreCase(constants.modoEliminar())){
if(FieldVerifier.isEmpty(txtFecha.getText())){
//Dialogs.alert("Alerta", "Campos con (*) son obligatorios", null);
//Window.alert(constants.camposObligatorios());
Notification not=new Notification(Notification.ALERT,constants.camposObligatorios());
not.showPopup();
return false;
}else if(FieldVerifier.isEmpty(txtMonto.getText())){
//Dialogs.alert("Alerta", "Campos con (*) son obligatorios", null);
//Window.alert(constants.camposObligatorios());
Notification not=new Notification(Notification.ALERT,constants.camposObligatorios());
not.showPopup();
return false;
}else if(FieldVerifier.isEmpty(txtTasa.getText())){
//Dialogs.alert("Alerta", "Campos con (*) son obligatorios", null);
//Window.alert(constants.camposObligatorios());
Notification not=new Notification(Notification.ALERT,constants.camposObligatorios());
not.showPopup();
return false;
}else if(FieldVerifier.isEmpty(txtCliente.getText())){
//Dialogs.alert("Alerta", "Campos con (*) son obligatorios", null);
//Window.alert(constants.camposObligatorios());
Notification not=new Notification(Notification.ALERT,constants.camposObligatorios());
not.showPopup();
return false;
}
}else{
BigDecimal vDevuelto=BigDecimal.valueOf(Double.valueOf(txtDevuelto.getText()));
if(vDevuelto.compareTo(BigDecimal.ZERO)==1){
//Dialogs.alert("Alerta", "Existen amortizaciones", null);
//Window.alert("Existen amortizaciones");
Notification not=new Notification(Notification.ALERT,"Existen amortizaciones");
not.showPopup();
return false;
}
}
return true;
}
@Override
public void activarModoPrestamo() {
// TODO Auto-generated method stub
}
@Override
public void onTouchEnd(TouchEndEvent event) {
// TODO Auto-generated method stub
if (event.getSource().equals(btnGuardar)) {
registrar();
}
}
@Override
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub
if (event.getSource().equals(btnBack)) {
goToUIPrestamo();
}else if (event.getSource().equals(this.btnClienteAdd)) {
goToUIClienteAdd();
/*dialogCliente = new UIClienteSelect(this);
setWidthDialog();
dialogCliente.center();
dialogCliente.show();*/
}else if (event.getSource().equals(btnGuardar)) {
registrar();
}
}
}
| [
"[email protected]"
] | |
dd9fa645633f9ac45b329eddb93ce85dcabf86a7 | af29b4fb6f754876c376d90b1d940bcd6f06729e | /src/test/java/ar/edu/utn/frro/web/rest/TestUtil.java | b557211951bb2533b997191b387188c6a668e300 | [
"MIT"
] | permissive | iisidro/iisidro-server | 0d0040ba1f7f98ca59f3aa3b5314932c5c5fb00f | ded27b5debb3039ea748274c5cd85e5beef933fa | refs/heads/development | 2021-01-16T23:28:20.453175 | 2017-03-16T00:58:54 | 2017-03-16T00:58:54 | 54,026,785 | 0 | 3 | MIT | 2020-12-01T16:53:49 | 2016-03-16T11:39:04 | Java | UTF-8 | Java | false | false | 2,333 | java | package ar.edu.utn.frro.web.rest;
import ar.edu.utn.frro.domain.util.JSR310DateTimeSerializer;
import ar.edu.utn.frro.domain.util.JSR310LocalDateDeserializer;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.http.MediaType;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
/**
* Utility class for testing REST controllers.
*/
public class TestUtil {
/** MediaType for JSON UTF8 */
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
/**
* Convert an object to JSON byte array.
*
* @param object
* the object to convert
* @return the JSON byte array
* @throws IOException
*/
public static byte[] convertObjectToJsonBytes(Object object)
throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
JavaTimeModule module = new JavaTimeModule();
module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);
mapper.registerModule(module);
return mapper.writeValueAsBytes(object);
}
/**
* Create a byte array with a specific size filled with specified data.
*
* @param size the size of the byte array
* @param data the data to put in the byte array
*/
public static byte[] createByteArray(int size, String data) {
byte[] byteArray = new byte[size];
for (int i = 0; i < size; i++) {
byteArray[i] = Byte.parseByte(data, 2);
}
return byteArray;
}
}
| [
"[email protected]"
] | |
ae5261aabd70a15c200428fe9eaa6108f9de8fd3 | 886ef86d03e51da931bca03d8bbcdd870477c7fb | /TimeTest.java | 96b4a6bbed1983264c737ae3f6c074380ffe7578 | [] | no_license | Wei-Xia/Java_Foundation | 447681c601d262f16c26c2dbe9ed24e1e9fb7ac9 | 1fa612127a749d74d023d2c57b1d25c83e2fa856 | refs/heads/master | 2016-09-06T12:20:08.264777 | 2015-06-30T02:04:54 | 2015-06-30T02:04:54 | 31,133,447 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,858 | java | /*
class Time {
private int hour;
private int minute;
private int second;
public void Time( ) { }
public void setTime(int hr , int min, int sec) { }
public void printTime( ) { }
public void tick( ) {
// tick method defined
}
}
The class Time defines a time object. It represents time (military time) in 2400 hours.
10 AM = 10 hours, 0 minutes and 0 seconds
4 PM = 16 hours, 0 minutes and 0 seconds
7:26PM = 19 hours, 26 minutes and 0 seconds
Assume 0 represents 00 in this case.
1) Implement the constructor Time that will set the instance variables to zero.
2) Implement the setTime method to set the instance variables according to the values passed in.
3) Implement the printTime method to print time in hours:minutes:seconds e.g. 16:37:23
4) Implement the tick( ) method that will increment the time object by one second.
Remember that 60 seconds = 1 minute, 60 minutes = 1 hour, and the max hours is 24.
5) Test the time object.
Increment the Time object by 60 seconds and print out the time.
Repeat question 5 for several different instances of the Time object. Each instance should have a different starting time.
*/
import java.util.*;
public class TimeTest{
public static void main(String args[]) {
Scanner scan = new Scanner (System.in);
Time current = new Time();
System.out.println ("Please enter hour");
int hour=scan.nextInt();
System.out.println ("Please enter minute");
int minute=scan.nextInt();
System.out.println ("Please enter second");
int second=scan.nextInt();
current.setTime(hour,minute,second);
System.out.println ("Please enter ticks");
int ticks = scan.nextInt();
while (ticks !=-1) {
current.tick(ticks);
System.out.println(current.printTime());
System.out.println("Please enter ticks");
ticks = scan.nextInt();
}
}
} | [
"[email protected]"
] | |
f3f57b9ab555d3679194f2eefea4e3a30494f40d | b84437b566fe4083183efca2bb58567bb7dea5ec | /src/pi_from_circle/Double_Thread.java | db006ccd7f8bce8e1e51f5f34ca953c7ab9a4750 | [] | no_license | fmmmlee/Monte-Carlo-Practice | 9435ac82f104ecd7b68519d2c48ba47c7ef7f3d2 | 4f14d218088a1e8360ed8cbfdf80df0684eb991e | refs/heads/master | 2021-06-14T14:29:57.754596 | 2019-07-16T21:54:39 | 2019-07-16T21:54:39 | 187,552,908 | 0 | 0 | null | 2021-04-26T19:11:43 | 2019-05-20T02:13:28 | Java | UTF-8 | Java | false | false | 896 | java | package pi_from_circle;
import java.util.concurrent.atomic.AtomicLong;
/*
*
* Matthew Lee
* Spring 2019
* Practicing Monte Carlo Simulation
*
*
*
* Using double to see how much faster it is
*
*/
public class Double_Thread implements Runnable{
final long ITERATIONS;
int in_circle = 0;
AtomicLong output;
Double_Thread(long iterations, AtomicLong shared_output)
{
ITERATIONS = iterations;
output = shared_output;
}
public void run()
{
/* looping */
for(int i = 0; i <= ITERATIONS; i++)
{
in_circle++;
/*Double x = ThreadLocalRandom.current().nextDouble();
Double y = ThreadLocalRandom.current().nextDouble();
if((x*x)+(y*y) <= 1) //checks if value is within the section, based on the formula for an ellipse
in_circle++;*/
}
/* adding final result of operation to the shared result */
output.getAndAdd(in_circle);
}
} | [
"[email protected]"
] | |
ccb9d4927dc19b0bd17c0f5c30e29de387ce5bd3 | a3548b736c69de0439313765d14a092dae519e09 | /src/main/java/cn/zhr/util/DynamicDataSource.java | a0977bad12248cca6c1d74e7b71901e5c3741d5f | [] | no_license | Fortmrw/activiti | b3a91552ab07edd2c9116386d153ffb1bd30493c | 8c9d32fdb9d7430b6830bb6dd9c5c3f982116e63 | refs/heads/master | 2021-05-14T10:27:30.583472 | 2018-01-05T07:16:06 | 2018-01-05T07:16:06 | 116,353,782 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 302 | java | package cn.zhr.util;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDbType();
}
}
| [
"[email protected]"
] | |
2aba653cd37b0bdfe349812d58adf4e932e686e3 | 065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be | /drjava_cluster/12757/src_1.java | ac877a691c5de4f26bdcbeb581b4af7e8cc62de0 | [] | no_license | martinezmatias/GenPat-data-C3 | 63cfe27efee2946831139747e6c20cf952f1d6f6 | b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4 | refs/heads/master | 2022-04-25T17:59:03.905613 | 2020-04-15T14:41:34 | 2020-04-15T14:41:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,958 | java | /*BEGIN_COPYRIGHT_BLOCK
*
* This file is part of DrJava. Download the current version of this project:
* http://sourceforge.net/projects/drjava/ or http://www.drjava.org/
*
* DrJava Open Source License
*
* Copyright (C) 2001-2003 JavaPLT group at Rice University ([email protected])
* All rights reserved.
*
* Developed by: Java Programming Languages Team
* Rice University
* http://www.cs.rice.edu/~javaplt/
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal with 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:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimers.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimers in the
* documentation and/or other materials provided with the distribution.
* - Neither the names of DrJava, the JavaPLT, Rice University, nor the
* names of its contributors may be used to endorse or promote products
* derived from this Software without specific prior written permission.
* - Products derived from this software may not be called "DrJava" nor
* use the term "DrJava" as part of their names without prior written
* permission from the JavaPLT group. For permission, write to
* [email protected].
*
* 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 CONTRIBUTORS 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 WITH THE SOFTWARE.
*
END_COPYRIGHT_BLOCK*/
package edu.rice.cs.drjava.model.compiler;
import java.io.*;
import junit.framework.*;
import edu.rice.cs.util.classloader.LimitingClassLoader;
import edu.rice.cs.util.ClasspathVector;
import edu.rice.cs.drjava.DrJava;
/**
* Test cases for {@link CompilerRegistry}.
* Here we test that the compiler registry correctly finds
* available compilers.
*
* @version $Id$
*/
public final class CompilerRegistryTest extends TestCase {
private static final CompilerRegistry _registry = CompilerRegistry.ONLY;
private static final String[][] _defaultCompilers
= CompilerRegistry.DEFAULT_COMPILERS;
private static final CompilerInterface[] _allAvailableCompilers
= _registry.getAvailableCompilers();
/**
* Stores the old state of {@link CompilerRegistry#getBaseClassLoader},
* so it can be reset later.
*/
private ClassLoader _oldBaseLoader;
/**
* Constructor.
* @param name
*/
public CompilerRegistryTest(String name) {
super(name);
}
/**
* Creates a test suite for JUnit to run.
* @return a test suite based on the methods in this class
*/
public static Test suite() {
return new TestSuite(CompilerRegistryTest.class);
}
/** Test setup method, which saves the old base class loader. */
public void setUp() {
_oldBaseLoader = _registry.getBaseClassLoader();
_registry.setActiveCompiler(NoCompilerAvailable.ONLY);
}
/** Test teardown method, which restores the old base class loader. */
public void tearDown() {
_registry.setBaseClassLoader(_oldBaseLoader);
}
/**
* Test that the default compilers are available and what we expect.
* This requires the environment (CLASSPATH) to have these compilers
* available. This is OK though, since the build environment needs them!
*
* This test is now commented out because it put too must restriction
* on the developer's build environment. It required them to have all the
* compilers available, which they may not. Oh well. These matters
* of configuration are really hard to test nicely.
*/
/*
public void testExpectedDefaultCompilers() {
CompilerInterface[] compilers = _registry.getAvailableCompilers();
assertEquals("Number of available compilers vs. number of default compilers",
_defaultCompilers.length,
compilers.length);
for (int i = 0; i < compilers.length; i++) {
assertEquals("Name of available compiler #" + i + " is the same as the " +
"name of the corresponding default compiler",
_defaultCompilers[i],
compilers[i].getClass().getName());
}
}
*/
/**
* Tests that list of available compilers effectively is restricted
* when the class is not available.
* Here this is done by limiting the available compilers one at a time.
*/
public void testLimitOneByOne() {
for (int i = 0; i < _allAvailableCompilers.length; i++) {
//CompilerInterface[] compilers =
_getCompilersAfterDisablingOne(i);
// That method includes all the tests we need!
}
}
/**
* Tests that list of available compilers effectively is restricted
* when all default compilers are not available.
*/
public void testLimitAllAtOnce() {
LimitingClassLoader loader = new LimitingClassLoader(_oldBaseLoader);
_registry.setBaseClassLoader(loader);
for (int i = 0; i < _defaultCompilers.length; i++) {
for (int j = 0; j < _defaultCompilers[i].length; j++) {
loader.addToRestrictedList(_defaultCompilers[i][j]);
}
}
CompilerInterface[] compilers = _registry.getAvailableCompilers();
assertEquals("Number of available compilers should be 1 " +
"because all real compilers are restricted.",
1,
compilers.length);
assertEquals("Only available compiler should be NoCompilerAvailable.ONLY",
NoCompilerAvailable.ONLY,
compilers[0]);
assertEquals("Active compiler",
NoCompilerAvailable.ONLY,
_registry.getActiveCompiler());
assertEquals("DrJava.java should not see an available compiler",
false,
DrJava.hasAvailableCompiler());
}
/**
* Tests that DrJava.java can see whether CompilerRegistry has an
* available compiler.
*/
public void testAvailableCompilerSeenByDrJava() {
assertEquals("DrJava.java should agree with CompilerRegistry",
_registry.getActiveCompiler() != NoCompilerAvailable.ONLY,
DrJava.hasAvailableCompiler());
}
/**
* Tests that {@link CompilerRegistry#setActiveCompiler} and
* {@link CompilerRegistry#getActiveCompiler} work.
*/
public void testActiveCompilerAllAvailable() {
CompilerInterface[] compilers = _registry.getAvailableCompilers();
assertEquals("active compiler before any setActive",
compilers[0],
_registry.getActiveCompiler());
for (int i = 0; i < compilers.length; i++) {
// TODO: deal with the problem that sometimes not all compilers avail!
//if (compilers[i].isAvailable()) {
_registry.setActiveCompiler(compilers[i]);
assertEquals("active compiler after setActive",
compilers[i],
_registry.getActiveCompiler());
//}
}
}
/**
* Returns the list of available compilers after disabling one of them.
* This method includes checks for the correctness of the list
* after disabling one.
*
* @param i Index of default compiler to disable.
*/
private CompilerInterface[] _getCompilersAfterDisablingOne(int i) {
return _getCompilersAfterDisablingSome(new int[] { i });
}
/**
* Returns the list of available compilers after disabling some of them.
* This method includes checks for the correctness of the list
* after disabling them.
*
* @param indices Array of ints signifying which of the default compilers
* to disable.
*/
private CompilerInterface[] _getCompilersAfterDisablingSome(int[] indices) {
LimitingClassLoader loader = new LimitingClassLoader(_oldBaseLoader);
_registry.setBaseClassLoader(loader);
//for (int j = 0; j < _allAvailableCompilers.length; j++) {
// System.out.println("all available compilers: " + _allAvailableCompilers[j].getClass().getName());
//}
for (int i = 0; i < indices.length; i++) {
//System.out.println("restricting compiler: " + _allAvailableCompilers[indices[i]].getClass().getName());
loader.addToRestrictedList(_allAvailableCompilers[indices[i]].getClass().getName());
}
CompilerInterface[] compilers = _registry.getAvailableCompilers();
//for (int j = 0; j < compilers.length; j++) {
// System.out.println("available compiler: " + compilers[j].getClass().getName());
//}
// NOTE: 03.28.2004 We don't know how to check this since making the change
// to only display one compiler of each type. JH & NH
// assertEquals("Number of available compilers",
// _allAvailableCompilers.length - indices.length,
// compilers.length);
int indicesIndex = 0;
for (int j = 0; j < _allAvailableCompilers.length; j++) {
if ((indicesIndex < indices.length) && (j == indices[indicesIndex])) {
// this is an index to skip.
indicesIndex++;
continue;
}
// Now indicesIndex is at the number of indices to skip!
int indexInAvailable = j - indicesIndex;
assertEquals("Class of available compiler #" + indexInAvailable,
_allAvailableCompilers[j].getClass().getName(),
compilers[indexInAvailable].getClass().getName());
}
return compilers;
}
/**
* Ensure that the active compiler in the registry cannot be set to null.
*/
public void testCannotSetCompilerToNull() {
try {
_registry.setActiveCompiler(null);
fail("Setting active compiler to null should have caused an exception!");
}
catch (IllegalArgumentException e) {
// Good-- exception was thrown.
}
}
static class Without implements CompilerInterface {
public boolean testField = false;
public Without()
{
testField = true;
}
public void addToBootClassPath(File s) { }
public CompilerError[] compile(File[] sourceRoots, File[] files) { return null; }
public CompilerError[] compile(File sourceRoot, File[] files) { return null; }
public String getName() { return "Without"; }
public boolean isAvailable() { return false; }
public void setAllowAssertions(boolean allow) { }
public void setWarningsEnabled(boolean warningsEnabled) { }
public void setExtraClassPath(String extraClassPath) { }
public void setExtraClassPath(ClasspathVector extraClassPath) { }
public String toString() { return "Without"; }
public void setBuildDirectory(File builddir) { }
}
/**
* Test that createCompiler() does successfully instantiate
* compilers that do not have the ONLY static field, and those which
* do have it.
*/
public void testCreateCompiler() {
try{
_registry.createCompiler(Without.class);
}
catch(Throwable e) {
e.printStackTrace();
fail("testCreateCompiler: Unexpected Exception for class without ONLY field\n" + e);
}
try{
_registry.createCompiler(JavacFromClasspath.ONLY.getClass());
}
catch(Throwable e2) {
fail("testCreateCompiler: Unexpected Exception for class with ONLY field\n" + e2);
}
}
}
| [
"[email protected]"
] | |
a10bcba49de4b25bb13c2f94444503c777357d9b | ec5ff737fbe8eca3075ef5da7dccc3ca7803e1e0 | /src/main/java/tests/DeSerializationToObject.java | ef02d54cc784d4e3c6ec21877120b47603ddfbd5 | [] | no_license | kumzme/Learn_Java | ce0924e8700da93dcb1a43e13c30139aa28a5e98 | b37da0bae6c3e066b36ea67da52cbd16045d7ca4 | refs/heads/master | 2020-03-26T20:50:30.059574 | 2019-03-01T02:58:07 | 2019-03-01T02:58:07 | 145,349,407 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 792 | java | package tests;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeSerializationToObject {
public static Object DeSerailizedtoObject(String fileName) throws Exception{
FileInputStream fin = new FileInputStream(new File(fileName));
ObjectInputStream ObjIn = new ObjectInputStream(fin);
Object deSerialzedObj = ObjIn.readObject();
ObjIn.close();
fin.close();
return deSerialzedObj;
}
public static void main(String args[]) throws Exception {
Serializable_EmployeeClass deSearlizedempC = (Serializable_EmployeeClass) DeSerailizedtoObject("empTest");
System.out.println(deSearlizedempC.getEmpName());
System.out.println(deSearlizedempC.getDeptName());
}
}
| [
"[email protected]"
] | |
4816333ce93ba597566f6d85e5553d3a0bae7e05 | 75de3b3c11eca42afe8a127adc0196cdb5936572 | /src/learning/java/source/concurrent/util/CountDownLatchTest.java | e640b6f07116e7cbcd7617441a9264af6f26ff96 | [] | no_license | zhcwang/learning_javasrc | 3417ee8815cab25feeed4228573006775c30c637 | 22372dbc7cfb504415d313471e8982d96baac8b7 | refs/heads/master | 2020-06-09T01:00:14.288821 | 2019-07-08T12:49:36 | 2019-07-08T12:49:36 | 193,338,843 | 0 | 0 | null | 2019-07-08T12:49:38 | 2019-06-23T11:16:31 | Java | UTF-8 | Java | false | false | 1,809 | java | package learning.java.source.concurrent.util;
import java.util.Random;
import java.util.concurrent.*;
/**
* CountDownLatch主要是用来并行计算,当所有线程都计算完后,主线程再进行其他操作
* 以下测试模仿工作中compare并发从源和目标读数据的相关功能代码
* 在CountDownLatch的源码示例中,还可以通过两个latch让任务同时开始,同时结束
* CountDownLatch是AQS的一个基本应用,原理如下:
* 初始一个状态 = CountDownLatch定义的线程数
* countdown()方法就是CAS state - 1 操作
* await()方法就是自旋阻塞等待state = 0
*/
public class CountDownLatchTest {
static class WaitForTheLast implements Runnable{
private CountDownLatch latch;
public WaitForTheLast(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
// 随机休眠0-5秒
int time = new Random().nextInt(5000);
System.out.println("休眠 " + time + "秒");
Thread.sleep(time);
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(10);
long start = System.currentTimeMillis();
Executor e = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
e.execute(new WaitForTheLast(latch));
}
latch.await();
long duration = System.currentTimeMillis() - start;
// 可以看到duration一定比所有执行线程的最长执行时间略大
System.out.println(duration);
}
}
| [
"[email protected]"
] | |
821e0b79f90b46ad1b6184ef85f2a9710244f14f | e418aaef69d8b5e189ac8e1d8e1e0d0eb14462d2 | /app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/androidx/core/R.java | 7fa760b7339f94b60df81be780de21f325cbbbb7 | [] | no_license | NowGotAMountain/FragmentExampleV2_homework | 389d1b3a41b014d5c8e6e5abe0028242d1ea9026 | 22af83b0911442bfe08892ced3babd61d4cbe03b | refs/heads/master | 2022-11-26T05:51:38.054835 | 2020-08-03T10:17:18 | 2020-08-03T10:17:18 | 284,668,451 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,444 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package androidx.core;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int alpha = 0x7f020027;
public static final int font = 0x7f02007a;
public static final int fontProviderAuthority = 0x7f02007c;
public static final int fontProviderCerts = 0x7f02007d;
public static final int fontProviderFetchStrategy = 0x7f02007e;
public static final int fontProviderFetchTimeout = 0x7f02007f;
public static final int fontProviderPackage = 0x7f020080;
public static final int fontProviderQuery = 0x7f020081;
public static final int fontStyle = 0x7f020082;
public static final int fontVariationSettings = 0x7f020083;
public static final int fontWeight = 0x7f020084;
public static final int ttcIndex = 0x7f02013c;
}
public static final class color {
private color() {}
public static final int notification_action_color_filter = 0x7f040040;
public static final int notification_icon_bg_color = 0x7f040041;
public static final int ripple_material_light = 0x7f04004c;
public static final int secondary_text_default_material_light = 0x7f04004e;
}
public static final class dimen {
private dimen() {}
public static final int compat_button_inset_horizontal_material = 0x7f05004d;
public static final int compat_button_inset_vertical_material = 0x7f05004e;
public static final int compat_button_padding_horizontal_material = 0x7f05004f;
public static final int compat_button_padding_vertical_material = 0x7f050050;
public static final int compat_control_corner_material = 0x7f050051;
public static final int compat_notification_large_icon_max_height = 0x7f050052;
public static final int compat_notification_large_icon_max_width = 0x7f050053;
public static final int notification_action_icon_size = 0x7f050060;
public static final int notification_action_text_size = 0x7f050061;
public static final int notification_big_circle_margin = 0x7f050062;
public static final int notification_content_margin_start = 0x7f050063;
public static final int notification_large_icon_height = 0x7f050064;
public static final int notification_large_icon_width = 0x7f050065;
public static final int notification_main_column_padding_top = 0x7f050066;
public static final int notification_media_narrow_margin = 0x7f050067;
public static final int notification_right_icon_size = 0x7f050068;
public static final int notification_right_side_padding_top = 0x7f050069;
public static final int notification_small_icon_background_padding = 0x7f05006a;
public static final int notification_small_icon_size_as_large = 0x7f05006b;
public static final int notification_subtext_size = 0x7f05006c;
public static final int notification_top_pad = 0x7f05006d;
public static final int notification_top_pad_large_text = 0x7f05006e;
}
public static final class drawable {
private drawable() {}
public static final int notification_action_background = 0x7f060058;
public static final int notification_bg = 0x7f060059;
public static final int notification_bg_low = 0x7f06005a;
public static final int notification_bg_low_normal = 0x7f06005b;
public static final int notification_bg_low_pressed = 0x7f06005c;
public static final int notification_bg_normal = 0x7f06005d;
public static final int notification_bg_normal_pressed = 0x7f06005e;
public static final int notification_icon_background = 0x7f06005f;
public static final int notification_template_icon_bg = 0x7f060060;
public static final int notification_template_icon_low_bg = 0x7f060061;
public static final int notification_tile_bg = 0x7f060062;
public static final int notify_panel_notification_icon_bg = 0x7f060063;
}
public static final class id {
private id() {}
public static final int action_container = 0x7f07000e;
public static final int action_divider = 0x7f070010;
public static final int action_image = 0x7f070011;
public static final int action_text = 0x7f070017;
public static final int actions = 0x7f070018;
public static final int async = 0x7f070020;
public static final int blocking = 0x7f070023;
public static final int chronometer = 0x7f07002c;
public static final int forever = 0x7f070041;
public static final int icon = 0x7f070049;
public static final int icon_group = 0x7f07004a;
public static final int info = 0x7f07004f;
public static final int italic = 0x7f070051;
public static final int line1 = 0x7f070053;
public static final int line3 = 0x7f070054;
public static final int normal = 0x7f07005e;
public static final int notification_background = 0x7f07005f;
public static final int notification_main_column = 0x7f070060;
public static final int notification_main_column_container = 0x7f070061;
public static final int right_icon = 0x7f07006f;
public static final int right_side = 0x7f070070;
public static final int tag_transition_group = 0x7f070091;
public static final int tag_unhandled_key_event_manager = 0x7f070092;
public static final int tag_unhandled_key_listeners = 0x7f070093;
public static final int text = 0x7f070094;
public static final int text2 = 0x7f070095;
public static final int time = 0x7f070098;
public static final int title = 0x7f070099;
}
public static final class integer {
private integer() {}
public static final int status_bar_notification_info_maxnum = 0x7f080004;
}
public static final class layout {
private layout() {}
public static final int notification_action = 0x7f09001f;
public static final int notification_action_tombstone = 0x7f090020;
public static final int notification_template_custom_big = 0x7f090027;
public static final int notification_template_icon_group = 0x7f090028;
public static final int notification_template_part_chronometer = 0x7f09002c;
public static final int notification_template_part_time = 0x7f09002d;
}
public static final class string {
private string() {}
public static final int status_bar_notification_info_overflow = 0x7f0b0035;
}
public static final class style {
private style() {}
public static final int TextAppearance_Compat_Notification = 0x7f0c00ec;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0c00ed;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0c00ef;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0c00f2;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0c00f4;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0c015d;
public static final int Widget_Compat_NotificationActionText = 0x7f0c015e;
}
public static final class styleable {
private styleable() {}
public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f020027 };
public static final int ColorStateListItem_android_color = 0;
public static final int ColorStateListItem_android_alpha = 1;
public static final int ColorStateListItem_alpha = 2;
public static final int[] FontFamily = { 0x7f02007c, 0x7f02007d, 0x7f02007e, 0x7f02007f, 0x7f020080, 0x7f020081 };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f02007a, 0x7f020082, 0x7f020083, 0x7f020084, 0x7f02013c };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_android_ttcIndex = 3;
public static final int FontFamilyFont_android_fontVariationSettings = 4;
public static final int FontFamilyFont_font = 5;
public static final int FontFamilyFont_fontStyle = 6;
public static final int FontFamilyFont_fontVariationSettings = 7;
public static final int FontFamilyFont_fontWeight = 8;
public static final int FontFamilyFont_ttcIndex = 9;
public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 };
public static final int GradientColor_android_startColor = 0;
public static final int GradientColor_android_endColor = 1;
public static final int GradientColor_android_type = 2;
public static final int GradientColor_android_centerX = 3;
public static final int GradientColor_android_centerY = 4;
public static final int GradientColor_android_gradientRadius = 5;
public static final int GradientColor_android_tileMode = 6;
public static final int GradientColor_android_centerColor = 7;
public static final int GradientColor_android_startX = 8;
public static final int GradientColor_android_startY = 9;
public static final int GradientColor_android_endX = 10;
public static final int GradientColor_android_endY = 11;
public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 };
public static final int GradientColorItem_android_color = 0;
public static final int GradientColorItem_android_offset = 1;
}
}
| [
"[email protected]"
] | |
a1249ef747983c30f42fe89008933ad966eead8c | aa10130655e199caab844460ec3a53b8e1947e47 | /Trabajos/cesarvicuna/TrabajoNota/src/pe/eeob/consolidadnotas/dto/consolidadDto.java | 8d89e422ab795e10fd454ea56b37e53f519602f2 | [] | no_license | Vobregon/SISTUNI_PROG_JAVA_003 | 0ace48fbc731798b2565bc970cac93adfa60aff3 | f920a8fd2a63fffeba52575f41d1d897d3c2a456 | refs/heads/master | 2021-01-24T01:30:13.231379 | 2016-02-21T06:14:55 | 2016-02-21T06:14:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,270 | 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 pe.eeob.consolidadnotas.dto;
/**
*
* @author Cesar Vicuña
*/
public class consolidadDto {
public float notaeparcial;
public float notaefinal;
public float notaproyecto;
public int tipo;
public float notafinal;
public consolidadDto() {
}
public float getNotaeparcial() {
return notaeparcial;
}
public void setNotaeparcial(float notaeparcial) {
this.notaeparcial = notaeparcial;
}
public float getNotaefinal() {
return notaefinal;
}
public void setNotaefinal(float notaefinal) {
this.notaefinal = notaefinal;
}
public float getNotaproyecto() {
return notaproyecto;
}
public void setNotaproyecto(float notaproyecto) {
this.notaproyecto = notaproyecto;
}
public int getTipo() {
return tipo;
}
public void setTipo(int tipo) {
this.tipo = tipo;
}
public float getNotafinal() {
return notafinal;
}
public void setNotafinal(float notafinal) {
this.notafinal = notafinal;
}
}
| [
"[email protected]"
] | |
631f611e99fbc6a1771e2c972f4d5d8306a56e5c | 461619a84c6617ceaf2b7913ef58c99ff32c0fb5 | /android/SimpleCursorAdapter/setViewBinder/src/SimpleCursorAdapter/SimpleCursorAdapter_/src/com/bgstation0/android/sample/simplecursoradapter_/MainActivity.java | 13a80ec04ffe6a9e578d869018cdfa85117906ed | [
"MIT"
] | permissive | bg1bgst333/Sample | cf066e48facac8ecd203c56665251fa1aa103844 | 298a4253dd8123b29bc90a3569f2117d7f6858f8 | refs/heads/master | 2023-09-02T00:46:31.139148 | 2023-09-01T02:41:42 | 2023-09-01T02:41:42 | 27,908,184 | 9 | 10 | MIT | 2023-09-06T20:49:55 | 2014-12-12T06:22:49 | Java | SHIFT_JIS | Java | false | false | 4,971 | java | package com.bgstation0.android.sample.simplecursoradapter_;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class MainActivity extends Activity {
// メンバフィールドの定義.
public CustomDBHelper mHlpr = null; // CustomDBHelperオブジェクトmHlprをnullにしておく.
public SQLiteDatabase mSqlite = null; // SQLiteDatabaseオブジェクトmSqliteをnullにしておく.
public SimpleCursorAdapter mAdapter = null; // SimpleCursorAdapterオブジェクトmAdapterをnullにしておく.
public Cursor mCursor = null; // CursorオブジェクトmCursorをnullにしておく.
// Activityが生成されたとき.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ListViewの取得.
ListView listView1 = (ListView)findViewById(R.id.listview1); // listView1を取得.
// DBへの行の挿入.
mCursor = null; // mCursorにnullをセット.
try{
if (mHlpr == null){ // mHlprがnullなら.
mHlpr = new CustomDBHelper(getApplicationContext()); // mHlpr作成.
if (mSqlite == null){ // mSqliteがnullなら.
mSqlite = mHlpr.getWritableDatabase(); // mSqlite取得.
if (mSqlite != null){ // mSqliteが取得できれば.
// 挿入.
ContentValues values1 = new ContentValues(); // values1の生成.
values1.put("name", "Taro"); // キーが"name", 値が"Taro".
values1.put("age", "20"); // キーが"age", 値が"20".
long i = mSqlite.insert("custom", null, values1); // 挿入.
ContentValues values2 = new ContentValues(); // values2の生成.
values2.put("name", "Jiro"); // キーが"name", 値が"Jiro".
values2.put("age", "18"); // キーが"age", 値が"18".
long i2 = mSqlite.insert("custom", null, values2); // 挿入.
ContentValues values3 = new ContentValues(); // values3の生成.
values3.put("name", "Saburo"); // キーが"name", 値が"Saburo".
values3.put("age", "16"); // キーが"age", 値が"16".
long i3 = mSqlite.insert("custom", null, values3); // 挿入.
// 選択.
String[] projection = new String[]{
"_id", // ID.
"name", // 名前.
"age" // 年齢.
};
mCursor = mSqlite.query("custom", projection, null, null, null, null, "age desc"); // クエリ結果をmCursorに格納.
mAdapter = new SimpleCursorAdapter(this, R.layout.list_item, mCursor, new String[]{"name", "age"}, new int[]{R.id.list_item_name, R.id.list_item_age}, 0); // SimpleCursorAdapterオブジェクトmAdapterの生成.
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
// TODO Auto-generated method stub
// カラムが1番目かどうか.(_idが0番目.)
if (columnIndex == 1){ // 1番目.(name)
int color = getResources().getColor(android.R.color.holo_red_light); // 赤のcolor取得.
((TextView)view).setTextColor(color); //viewにセット.
}
else{ // 1番目以外.(age)
int color = getResources().getColor(android.R.color.holo_blue_light); // 青のcolor取得.
((TextView)view).setTextColor(color); //viewにセット.
}
return false;
}
});
listView1.setAdapter(mAdapter); // listView1にmAdapterをセット.
}
}
}
}
catch (Exception ex){ // 例外.
Log.e("SimpleCursorAdapter_", ex.toString()); // ex.toStringをLogに出力.
}
finally{ // 必須処理
if (mSqlite != null){ // mSqliteがあれば.
mSqlite.close(); // 閉じる.
mSqlite = null; // nullをセット.
}
if (mHlpr != null){ // mHlprがあれば.
mHlpr.close(); // 閉じる.
mHlpr = null; // nullをセット.
}
}
}
// Activityが破棄されたとき.
protected void onDestroy() { // onDestroyの定義
// 親クラスの処理
super.onDestroy(); // super.onDestroyで親クラスの既定処理.
// カーソルを閉じる.
if (mCursor != null){ // mCursorがあれば.
mCursor.close(); // 閉じる.
mCursor = null; // nullをセット.
}
}
} | [
"[email protected]"
] | |
d0a070c6b232374819f2aa583342a2a5b9bc9d1f | 6d60a8adbfdc498a28f3e3fef70366581aa0c5fd | /codebase/selected/1047866.java | cec0c8ad33c8fe9bf71b0d93b3b6dce92e112741 | [] | no_license | rayhan-ferdous/code2vec | 14268adaf9022d140a47a88129634398cd23cf8f | c8ca68a7a1053d0d09087b14d4c79a189ac0cf00 | refs/heads/master | 2022-03-09T08:40:18.035781 | 2022-02-27T23:57:44 | 2022-02-27T23:57:44 | 140,347,552 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 10,870 | java | package org.springframework.richclient.table;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelEvent;
import javax.swing.table.TableModel;
import org.springframework.core.style.StylerUtils;
import org.springframework.util.Assert;
import org.springframework.util.comparator.NullSafeComparator;
/**
* A sorter for TableModels. The sorter has a model (conforming to TableModel)
* and itself implements TableModel. TableSorter does not store or copy the
* model in the TableModel, instead it maintains an array of integers which it
* keeps the same size as the number of rows in its model. When the model
* changes it notifies the sorter that something has changed eg. "rowsAdded" so
* that its internal array of integers can be reallocated. As requests are made
* of the sorter (like getValueAt(row, col) it redirects them to its model via
* the mapping array. That way the TableSorter appears to hold another copy of
* the table with the rows in a different order. The sorting algorthm used is
* stable which means that it does not move around rows when its comparison
* function returns 0 to denote that they are equivalent.
*/
public class ShuttleSortableTableModel extends AbstractTableModelFilter implements SortableTableModel {
private static final Comparator OBJECT_COMPARATOR = new NullSafeComparator(ToStringComparator.INSTANCE, true);
private static final Comparator COMPARABLE_COMPARATOR = NullSafeComparator.NULLS_LOW;
private Comparator[] columnComparators;
private List columnsToSort = new ArrayList(4);
private int[] indexes;
private int compares;
private boolean autoSortEnabled = true;
private Runnable notifyTableRunnable = new Runnable() {
public void run() {
fireTableDataChanged();
}
};
public ShuttleSortableTableModel(TableModel model) {
super(model);
allocateIndexes();
resetComparators();
}
private void allocateIndexes() {
int rowCount = filteredModel.getRowCount();
indexes = new int[rowCount];
for (int row = 0; row < rowCount; row++) {
indexes[row] = row;
}
}
public void resetComparators() {
resetComparators(Collections.EMPTY_MAP);
}
/**
* Reset the <code>columnComparartos</code>.<br>
* Useful when the columns of the model were changed, and by consequence
* their comparators.
* @param comparators - map with comparators where the key is the column of
* the comparator.
*/
public void resetComparators(Map comparators) {
int colCount = filteredModel.getColumnCount();
columnComparators = new Comparator[colCount];
Comparator newComparator;
Class clazz;
for (int i = 0; i < columnComparators.length; i++) {
newComparator = (Comparator) comparators.get(Integer.valueOf(i));
if (newComparator != null) setComparator(i, newComparator); else {
clazz = filteredModel.getColumnClass(i);
if (clazz == Object.class || !Comparable.class.isAssignableFrom(clazz)) columnComparators[i] = OBJECT_COMPARATOR;
}
}
}
public boolean isCellEditable(int row, int column) {
return filteredModel.isCellEditable(indexes[row], column);
}
public boolean isAutoSortEnabled() {
return autoSortEnabled;
}
public void setAutoSortEnabled(boolean autoSortEnabled) {
this.autoSortEnabled = autoSortEnabled;
}
public Comparator getComparator(int columnIndex) {
return this.columnComparators[columnIndex];
}
public void setComparator(int columnIndex, Comparator comparator) {
Assert.notNull(comparator);
this.columnComparators[columnIndex] = comparator;
}
public Object getValueAt(int row, int column) {
return filteredModel.getValueAt(indexes[row], column);
}
public void setValueAt(Object value, int row, int column) {
filteredModel.setValueAt(value, indexes[row], column);
}
public void sortByColumn(ColumnToSort columnToSort) {
columnsToSort.clear();
columnsToSort.add(columnToSort);
sort();
SwingUtilities.invokeLater(notifyTableRunnable);
}
public void sortByColumns(ColumnToSort[] columnsToSort) {
this.columnsToSort = Arrays.asList(columnsToSort);
sort();
notifyTableChanged();
}
public int[] sortByColumns(ColumnToSort[] columnsToSort, int[] preSortSelectedRows) {
int[] modelIndexes = new int[preSortSelectedRows.length];
if (logger.isDebugEnabled()) {
logger.debug("Selected row indexes before sort" + StylerUtils.style(preSortSelectedRows));
}
for (int i = 0; i < preSortSelectedRows.length; i++) {
modelIndexes[i] = convertSortedIndexToDataIndex(preSortSelectedRows[i]);
}
this.columnsToSort = Arrays.asList(columnsToSort);
sort();
int[] postSortSelectedRows = new int[modelIndexes.length];
for (int i = 0; i < modelIndexes.length; i++) {
postSortSelectedRows[i] = convertModelToRowIndex(modelIndexes[i]);
}
if (logger.isDebugEnabled()) {
logger.debug("Selected row indexes after sort" + StylerUtils.style(postSortSelectedRows));
}
notifyTableChanged();
return postSortSelectedRows;
}
protected void notifyTableChanged() {
if (!EventQueue.isDispatchThread()) {
SwingUtilities.invokeLater(notifyTableRunnable);
} else {
notifyTableRunnable.run();
}
}
public int convertSortedIndexToDataIndex(int index) {
return indexes[index];
}
public int[] convertSortedIndexesToDataIndexes(int[] indexes) {
int[] converted = new int[indexes.length];
for (int i = 0; i < indexes.length; i++) {
converted[i] = convertSortedIndexToDataIndex(indexes[i]);
}
return converted;
}
public int convertModelToRowIndex(int index) {
for (int i = 0; i < indexes.length; i++) {
if (index == indexes[i]) {
return i;
}
}
return 0;
}
public int[] convertDataIndexesToSortedIndexes(int[] indexes) {
int[] converted = new int[indexes.length];
for (int i = 0; i < indexes.length; i++) {
converted[i] = convertModelToRowIndex(indexes[i]);
}
return converted;
}
private void sort() {
if (columnsToSort.size() > 0) {
checkModel();
compares = 0;
doShuttleSort((int[]) indexes.clone(), indexes, 0, indexes.length);
}
}
private void checkModel() {
if (indexes.length != filteredModel.getRowCount()) {
throw new IllegalStateException("Sorter not informed of a change in model.");
}
}
private void doShuttleSort(int from[], int to[], int low, int high) {
if (high - low < 2) {
return;
}
int middle = (low + high) / 2;
doShuttleSort(to, from, low, middle);
doShuttleSort(to, from, middle, high);
int p = low;
int q = middle;
if (high - low >= 4 && compare(from[middle - 1], from[middle]) <= 0) {
for (int i = low; i < high; i++) {
to[i] = from[i];
}
return;
}
for (int i = low; i < high; i++) {
if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) {
to[i] = from[p++];
} else {
to[i] = from[q++];
}
}
}
public int compare(int row1, int row2) {
compares++;
for (int level = 0; level < columnsToSort.size(); level++) {
ColumnToSort column = (ColumnToSort) columnsToSort.get(level);
int result = compareRowsByColumn(row1, row2, column.getColumnIndex());
if (result != 0) {
return column.getSortOrder() == SortOrder.ASCENDING ? result : -result;
}
}
return 0;
}
private int compareRowsByColumn(int row1, int row2, int column) {
Object o1 = filteredModel.getValueAt(row1, column);
Object o2 = filteredModel.getValueAt(row2, column);
Comparator comparator = columnComparators[column];
if (comparator != null) {
return comparator.compare(o1, o2);
}
return COMPARABLE_COMPARATOR.compare(o1, o2);
}
public void tableChanged(final TableModelEvent e) {
if (e.getType() == TableModelEvent.INSERT) {
if (autoSortEnabled) {
reallocateIndexesOnInsert(e.getFirstRow(), e.getLastRow());
sort();
final int[] insertedRows = new int[e.getLastRow() - e.getFirstRow() + 1];
int row = e.getFirstRow();
for (int i = 0; i < insertedRows.length; i++) {
insertedRows[i] = convertModelToRowIndex(row++);
}
for (int i = 0; i < insertedRows.length; i++) {
fireTableRowsInserted(insertedRows[i], insertedRows[i]);
}
} else {
reallocateIndexesOnInsert(e.getFirstRow(), e.getLastRow());
super.tableChanged(e);
}
} else if (e.getType() == TableModelEvent.DELETE) {
final int[] deletedRows = new int[e.getLastRow() - e.getFirstRow() + 1];
int row = e.getFirstRow();
for (int i = 0; i < deletedRows.length; i++) {
deletedRows[i] = convertModelToRowIndex(row);
row++;
}
allocateIndexes();
for (int i = 0; i < deletedRows.length; i++) {
fireTableRowsDeleted(deletedRows[i], deletedRows[i]);
}
sort();
} else if (e.getType() == TableModelEvent.UPDATE) {
allocateIndexes();
sort();
fireTableDataChanged();
} else {
logger.warn("Doing an unknown table change type: " + e.getType());
allocateIndexes();
sort();
super.tableChanged(e);
}
}
private void reallocateIndexesOnInsert(int firstRow, int lastRow) {
int rowCount = filteredModel.getRowCount();
int[] newIndexes = new int[rowCount];
for (int row = 0; row < indexes.length; row++) {
newIndexes[row] = indexes[row];
}
for (int row = firstRow; row <= lastRow; row++) {
newIndexes[row] = row;
}
indexes = newIndexes;
}
}
| [
"[email protected]"
] | |
04e8f981d33b04e8423dc6844cb6c03bb07d39b1 | 89904f6c80aab728d197f879b5a0167f7198ea96 | /integration-tests/google-cloud-functions-http/src/main/java/io/quarkus/it/gcp/functions/http/GreetingServlet.java | 1065e3f6499e0f51c44e319e794462c8df15b78e | [
"Apache-2.0"
] | permissive | loicmathieu/quarkus | 54b27952bbdbf16772ce52086bed13165a6c0aec | f29b28887af4b50e7484dd1faf252b15f1a9f61a | refs/heads/main | 2023-08-30T23:58:38.586507 | 2022-11-10T15:01:09 | 2022-11-10T15:01:09 | 187,598,844 | 3 | 1 | Apache-2.0 | 2023-03-02T20:56:56 | 2019-05-20T08:23:48 | Java | UTF-8 | Java | false | false | 987 | java | package io.quarkus.it.gcp.functions.http;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "ServletGreeting", urlPatterns = "/servlet/hello")
public class GreetingServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setStatus(200);
resp.addHeader("Content-Type", "text/plain");
resp.getWriter().write("hello");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getReader().readLine();
resp.setStatus(200);
resp.addHeader("Content-Type", "text/plain");
resp.getWriter().write("hello " + name);
}
}
| [
"[email protected]"
] | |
88766418347850daa792d1b682d253f247fe0f21 | 54ced7a1d869bef5a3ccb7c6b0da76fc37eccf7f | /cucumber2/src/test/java/stepDefinations/StepDefination.java | 57c498d59296cc8b13c7d679538c356e9e87def2 | [] | no_license | vibhubrt/QAtest | 9536fe4756a6dd22e1b9f035940c2154d7335495 | 34b83451186927c5faf8e5ebbb3dbd28b9fc8526 | refs/heads/master | 2023-01-07T04:08:21.426571 | 2020-11-06T14:30:14 | 2020-11-06T14:30:14 | 310,475,024 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,348 | java | package stepDefinations;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import static org.junit.Assert.*;
import java.text.ParseException;
import io.restassured.parsing.Parser;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import pojo.GetResponse;
import pojo.InvalidResponse;
import resources.Utils;
import static io.restassured.RestAssured.*;
public class StepDefination extends Utils {
RequestSpecification request;
GetResponse responsebody;
InvalidResponse invalidresponse;
Response resp;
JsonPath js;
// calls requestSpecification method to set base URI and query parameters as latitude and longitude
@Given("valid latitude {double} and longitude {double}")
public void valid_latitude_and_longitude(Double latitude, Double longitude) {
request = given().log().all().spec(requestSpecification(latitude, longitude));
}
// calls requestSpecification method to set base URI and query parameters latitude,longitude,date,format
@Given("valid latitude {double} and longitude {double} and validdate {string} and format {int}")
public void valid_latitude_and_longitude_and_validdate_and_format(Double latitude, Double longitude, String date,
int format) {
request = given().log().all().spec(requestSpecification(latitude, longitude, date, format));
}
// calls requestSpecification method to set base URI and query parameters latitude,longitude,format
@Given("valid latitude {double} and longitude {double} and format {int}")
public void valid_latitude_and_longitude_and_dateformat(Double latitude, Double longitude, int format) {
request = given().log().all().spec(requestSpecification(latitude, longitude, format));
}
// calls requestSpecification method to set base URI and query parameters latitude,longitude,date
@Given("valid latitude {double} and longitude {double} and invaliddate {string}")
public void valid_latitude_and_longitude_and_invaliddate(Double latitude, Double longitude, String date) {
request = given().log().all().spec(requestSpecification(latitude, longitude, date));
}
// Response body which is returned from API is stored in POJO class based on response code
@When("user calls API with get Http request")
public void user_calls_api_with_get_http_request() {
resp = request.when().get("/json").then().extract().response();
if (resp.getStatusCode() == 400) {
invalidresponse = request.expect().defaultParser(Parser.JSON).when().get("/json").as(InvalidResponse.class);
}
else if (resp.getStatusCode() == 200) {
responsebody = request.expect().defaultParser(Parser.JSON).when().get("/json").as(GetResponse.class);
System.out.println(responsebody.getResults().getDay_length());
}
}
//Verifying API response code with expected value
@Then("API call code is {string}")
public void api_call_success_code_is(String code) {
assertEquals(Integer.toString(resp.getStatusCode()), code);
}
//Verifying Status of API with expected value
@Then("{string} in response body is {string}")
public void in_response_body_is(String key, String expectedvalue) {
String response = resp.asString();
System.out.println(response);
js = new JsonPath(response);
assertEquals(js.get(key).toString(), expectedvalue);
}
//Verifies whether sunrise and sunset time are returned for specified location
@Then("verify sunrise and sunset times")
public void verify_sunrise_and_sunset_times() {
assertNotNull(responsebody.getResults().getSunrise());
assertNotNull(responsebody.getResults().getSunset());
}
//To check date returned from response is equal to today's date
@Then("check default date is today")
public void check_default_date_is_today() throws ParseException {
String date =getDatefromResponse(responsebody.getResults().getSunrise());
assertEquals(gettodayUTCDate(), date);
}
//Checks if response body contains date
@Then("verify if data is unformatted")
public void verify_if_data_is_unformatted() throws ParseException {
String date = getDatefromResponse(responsebody.getResults().getSunset());
assertTrue(responsebody.getResults().getSunrise().contains(date));
}
//Sunrise date and sunset date are extracted from response body and compared with inputdate
@Then("check sunrise and sunset of {string}")
public void check_sunrise_and_sunset_of(String inputdate) throws ParseException {
String sunrisedate = getDatefromResponse(responsebody.getResults().getSunset());
String sunsetdate = getDatefromResponse(responsebody.getResults().getSunrise());
assertEquals(sunrisedate,inputdate);
assertEquals(sunsetdate,inputdate);
}
//checks if calculated day length is equal to day length received from response body/payload
@Then("check time between sunrise and sunset is equal to daylength")
public void check_time_between_sunrise_and_sunset_is_equal_to_daylength() {
String daylength = getDaylength(responsebody.getResults().getSunrise(), responsebody.getResults().getSunset());
assertEquals(daylength, responsebody.getResults().getDay_length());
}
}
| [
"[email protected]"
] | |
f09465ccc736891a77c0a237be9a7437d5739e12 | 9254e7279570ac8ef687c416a79bb472146e9b35 | /sae-20190506/src/main/java/com/aliyun/sae20190506/models/ListTagResourcesQuery.java | 085bced636330ce0d9d26b455c8598405d0d524a | [
"Apache-2.0"
] | permissive | lquterqtd/alibabacloud-java-sdk | 3eaa17276dd28004dae6f87e763e13eb90c30032 | 3e5dca8c36398469e10cdaaa34c314ae0bb640b4 | refs/heads/master | 2023-08-12T13:56:26.379027 | 2021-10-19T07:22:15 | 2021-10-19T07:22:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,745 | java | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.sae20190506.models;
import com.aliyun.tea.*;
public class ListTagResourcesQuery extends TeaModel {
@NameInMap("RegionId")
@Validation(required = true)
public String regionId;
@NameInMap("ResourceType")
@Validation(required = true)
public String resourceType;
@NameInMap("NextToken")
public String nextToken;
@NameInMap("ResourceIds")
public String resourceIds;
@NameInMap("Tags")
public String tags;
public static ListTagResourcesQuery build(java.util.Map<String, ?> map) throws Exception {
ListTagResourcesQuery self = new ListTagResourcesQuery();
return TeaModel.build(map, self);
}
public ListTagResourcesQuery setRegionId(String regionId) {
this.regionId = regionId;
return this;
}
public String getRegionId() {
return this.regionId;
}
public ListTagResourcesQuery setResourceType(String resourceType) {
this.resourceType = resourceType;
return this;
}
public String getResourceType() {
return this.resourceType;
}
public ListTagResourcesQuery setNextToken(String nextToken) {
this.nextToken = nextToken;
return this;
}
public String getNextToken() {
return this.nextToken;
}
public ListTagResourcesQuery setResourceIds(String resourceIds) {
this.resourceIds = resourceIds;
return this;
}
public String getResourceIds() {
return this.resourceIds;
}
public ListTagResourcesQuery setTags(String tags) {
this.tags = tags;
return this;
}
public String getTags() {
return this.tags;
}
}
| [
"[email protected]"
] | |
9a14f22794e2b18dea9bc14b33c66806f34e01cd | ffe58d32e5e78cd51934a5e27e76b6442db557f3 | /src/proj/HashMap.java | 1ed732f51ad4f65bce35152e782adcd48e0c6dbe | [] | no_license | Data-Struct-Proj/proj-files | 155ef5843b890711dfe8f85c1b99f2a9bda6eb9c | 549f302e923a334319b6e3c70656832fdd0967ca | refs/heads/master | 2022-10-22T21:29:07.929300 | 2020-06-17T09:33:35 | 2020-06-17T09:33:35 | 264,357,870 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,003 | java | package proj;
public class HashMap {
class Data {
int key;
String value;
public Data(int k,String v){
key=k;
value=v;
}
public boolean equals(Data that) {
return (this.key==that.key);
}
@Override
public int hashCode() {
return key;
}
};
class Node{
Data data;
Node next,prev;
public Node(Data d) {
data = d;
next=prev=null;
}
};
Node[] map;
public HashMap(int size) {
map=new Node[size];
}
public int hash(Data n) {
return n.hashCode() % map.length;
}
public void put(int k ,String v) {
Data d = new Data (k,v);
int h = hash(d);
Node n = new Node(d);
if (map[h]==null)
map[h]=n;
else {
Node ptr = map[h];
for(;ptr.next!=null;ptr=ptr.next);
ptr.next = n;
n.prev=ptr;
}
}
public String get(int k) {
int h = k%map.length;
Node ptr = map[h];
while(ptr!=null && ptr.data.key!=k) {
ptr = ptr.next;
}
return (ptr==null) ? null:ptr.data.value; //else is a colon,? is a then
}
}
| [
"[email protected]"
] | |
a2d6a818acc40e90746c845725a5d982d205af72 | ce0478e1c168424e006c31b502c130b69d447d4a | /RunnerApp/src/org/dicadeveloper/runnerapp/io/gdata/maps/XmlMapsGDataParser.java | 9cb4c611e09f0159791aef70cb1e4411545b8fe2 | [] | no_license | birkhimerjr/RunnerApp | 2deeb3ec98d8281e0ef3b03773b170bce99966ae | f340ef1fb56844c1178aefd9fea3664bb8a52e5a | refs/heads/master | 2021-05-05T00:37:35.053868 | 2015-04-26T07:52:49 | 2015-04-26T07:52:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,056 | java | // Copyright 2009 Google Inc. All Rights Reserved.
package org.dicadeveloper.runnerapp.io.gdata.maps;
import com.google.wireless.gdata.data.Entry;
import com.google.wireless.gdata.data.Feed;
import com.google.wireless.gdata.data.XmlUtils;
import com.google.wireless.gdata.parser.ParseException;
import com.google.wireless.gdata.parser.xml.XmlGDataParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
/**
* Parser for XML gdata maps data.
*/
class XmlMapsGDataParser extends XmlGDataParser {
public XmlMapsGDataParser(InputStream is, XmlPullParser xpp)
throws ParseException {
super(is, xpp);
}
@Override
protected Feed createFeed() {
return new Feed();
}
@Override
protected Entry createEntry() {
return new MapFeatureEntry();
}
@Override
protected void handleExtraElementInFeed(Feed feed) {
// Do nothing
}
@Override
protected void handleExtraLinkInEntry(
String rel, String type, String href, Entry entry)
throws XmlPullParserException, IOException {
if (!(entry instanceof MapFeatureEntry)) {
throw new IllegalArgumentException("Expected MapFeatureEntry!");
}
if (rel.endsWith("#view")) {
return;
}
super.handleExtraLinkInEntry(rel, type, href, entry);
}
/**
* Parses the current entry in the XML document. Assumes that the parser is
* currently pointing just after an <entry>.
*
* @param plainEntry The entry that will be filled.
* @throws XmlPullParserException Thrown if the XML cannot be parsed.
* @throws IOException Thrown if the underlying inputstream cannot be read.
*/
@Override
protected void handleEntry(Entry plainEntry)
throws XmlPullParserException, IOException, ParseException {
XmlPullParser parser = getParser();
if (!(plainEntry instanceof MapFeatureEntry)) {
throw new IllegalArgumentException("Expected MapFeatureEntry!");
}
MapFeatureEntry entry = (MapFeatureEntry) plainEntry;
int eventType = parser.getEventType();
entry.setPrivacy("public");
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
String name = parser.getName();
if ("entry".equals(name)) {
// stop parsing here.
return;
} else if ("id".equals(name)) {
entry.setId(XmlUtils.extractChildText(parser));
} else if ("title".equals(name)) {
entry.setTitle(XmlUtils.extractChildText(parser));
} else if ("link".equals(name)) {
String rel = parser.getAttributeValue(null /* ns */, "rel");
String type = parser.getAttributeValue(null /* ns */, "type");
String href = parser.getAttributeValue(null /* ns */, "href");
if ("edit".equals(rel)) {
entry.setEditUri(href);
} else if ("alternate".equals(rel) && "text/html".equals(type)) {
entry.setHtmlUri(href);
} else {
handleExtraLinkInEntry(rel, type, href, entry);
}
} else if ("summary".equals(name)) {
entry.setSummary(XmlUtils.extractChildText(parser));
} else if ("content".equals(name)) {
StringBuilder contentBuilder = new StringBuilder();
int parentDepth = parser.getDepth();
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
int etype = parser.next();
switch (etype) {
case XmlPullParser.START_TAG:
contentBuilder.append('<');
contentBuilder.append(parser.getName());
contentBuilder.append('>');
break;
case XmlPullParser.TEXT:
contentBuilder.append("<![CDATA[");
contentBuilder.append(parser.getText());
contentBuilder.append("]]>");
break;
case XmlPullParser.END_TAG:
if (parser.getDepth() > parentDepth) {
contentBuilder.append("</");
contentBuilder.append(parser.getName());
contentBuilder.append('>');
}
break;
}
if (etype == XmlPullParser.END_TAG
&& parser.getDepth() == parentDepth) {
break;
}
}
entry.setContent(contentBuilder.toString());
} else if ("category".equals(name)) {
String category = parser.getAttributeValue(null /* ns */, "term");
if (category != null && category.length() > 0) {
entry.setCategory(category);
}
String categoryScheme =
parser.getAttributeValue(null /* ns */, "scheme");
if (categoryScheme != null && category.length() > 0) {
entry.setCategoryScheme(categoryScheme);
}
} else if ("published".equals(name)) {
entry.setPublicationDate(XmlUtils.extractChildText(parser));
} else if ("updated".equals(name)) {
entry.setUpdateDate(XmlUtils.extractChildText(parser));
} else if ("deleted".equals(name)) {
entry.setDeleted(true);
} else if ("draft".equals(name)) {
String draft = XmlUtils.extractChildText(parser);
entry.setPrivacy("yes".equals(draft) ? "unlisted" : "public");
} else if ("customProperty".equals(name)) {
String attrName = parser.getAttributeValue(null, "name");
String attrValue = XmlUtils.extractChildText(parser);
entry.setAttribute(attrName, attrValue);
} else if ("deleted".equals(name)) {
entry.setDeleted(true);
} else {
handleExtraElementInEntry(entry);
}
break;
default:
break;
}
eventType = parser.next();
}
}
}
| [
"[email protected]"
] | |
addf836fffc6161f91a5bd3b83fc154df3edfd67 | 838376338d007faad8ecae04eebd623393139569 | /com.rufang.leetcode/src/com/rufang/leetcode/array/ContainerWithMostWater.java | e2e7004ca4ecc44055e776fc74318faf88563229 | [] | no_license | amyfang/InterviewCode | 35bc3287fa78f8b26e6b41413d5d029251fb68ec | 4ecca02b0689e8a46775ad53f2cadcd2cf29a86c | refs/heads/master | 2021-01-25T05:57:50.929525 | 2019-09-25T19:11:48 | 2019-09-25T19:11:48 | 27,024,267 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,444 | java | package com.rufang.leetcode.array;
public class ContainerWithMostWater {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] input1 = {1,8,6,2,5,4,8,3,7};
int result1 = maxArea(input1);
int result1_1 = maxArea2(input1);
System.out.println(result1);
System.out.println(result1_1);
int[] input2 = {1};
int result2 = maxArea(input2);
System.out.println(result2);
}
//brute force O(n2)
public static int maxArea(int[] height) {
if(null == height)
return 0;
if(height.length == 1)
return 0;
int maxValue = 0;
for(int i=0; i<height.length-1; i++){
for(int j=i+1; j<height.length; j++){
int value = (j-i) * Math.min(height[i], height[j]);
System.out.println("i=" + i + " j=" +j + " value=" + value);
if(value > maxValue){
maxValue = value;
}
}
}
return maxValue;
}
//two pointer solution, O(n)
public static int maxArea2(int[] height) {
if(null == height)
return 0;
if(height.length == 1)
return 0;
int maxValue = 0;
int left = 0, right = height.length - 1;
while(left < right){
int value = (right - left) * Math.min(height[left], height[right]);
System.out.println("left=" + left + " right=" +right + " value=" + value);
maxValue = maxValue < value ? value : maxValue;
if(height[left] < height[right]){
left ++;
} else {
right --;
}
}
return maxValue;
}
}
| [
"[email protected]"
] | |
0b24f54ffd2150c27fcf1e7957c178abf440e8a8 | 3efaa0b164bf250dd29fcec49e522a15d1deaaf8 | /src/noorteck/Demo4.java | 261ce63a9d8ea61ee0fd1d1c0b9e776855b5f759 | [] | no_license | fernanda102017/Coding1 | a1405b0b6355a63e0930c44d24ac277485822ab4 | a0b3b9869129552a2c64f6785ecb97cb899a8b16 | refs/heads/master | 2022-06-28T14:40:09.940466 | 2020-05-15T17:34:48 | 2020-05-15T17:34:48 | 264,258,344 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 126 | java | package noorteck;
public class Demo4 {
public static void main(String[] args) {
System.out.println("Integer");
}
}
| [
"[email protected]"
] | |
f8c354ad89cbe0e10764c553ee1f3b7483e06df3 | 35c23bc154dadf5af29508a285311ad073eec132 | /src/main/java/net/programDemo/service/MembersService.java | d6e773939b47dd65d4b49e59278f0d9f6ef0fb86 | [] | no_license | lifeBoolean/programDemo | 23e1bb167bf7dfdc89c22eed1e8aa847fad63b26 | c8f6e1c88e9fafb6e59cb3a652682e1679a7823b | refs/heads/master | 2022-12-17T14:39:37.470470 | 2020-09-23T11:42:40 | 2020-09-23T11:42:40 | 289,659,258 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 376 | java | package net.programDemo.service;
import net.programDemo.model.MembersVo;
public interface MembersService {
void memberInsert(MembersVo membersVo) throws Exception;
public MembersVo memberLogin(MembersVo membersVo) throws Exception;
public void memberModify(MembersVo membersVo) throws Exception;
public int memberDelete(MembersVo membersVo) throws Exception;
}
| [
"[email protected]"
] | |
d06c7da9afb9fea7f7a92e7b1b988f69de24ccb3 | 0bb711323711c4a9c7ca38638ae691e7a063978c | /Week-08/greenfoxws03/src/main/java/Account.java | f0da524a4dc217ae5a5de06bbcec737724ecce39 | [] | no_license | greenfox-zerda-raptors/vikukzs | 462a592c61f5d4e996c36859117f697980b0ffb4 | b8370b279d79e9b153d70ed37eded709b1d791da | refs/heads/master | 2021-01-12T18:15:21.934253 | 2017-02-17T09:11:28 | 2017-02-17T09:11:28 | 71,352,666 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 858 | java | /**
* Created by Zsuzska on 2016. 12. 14..
*/
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@DatabaseTable(tableName = "accounts")
public class Account {
@DatabaseField(id = true)
private String name;
@DatabaseField
private String password;
@DatabaseField(foreign = true)
public Address address;
public Account() {}
public Account(String name, String password ) {
this.name = name;
this.password = password;
}
public Account(String name, String password, Address address){
this.name = name;
this.password = password;
this.address = address;
}
@Override
public String toString() {
return "Name: " + getName() + "Address: " + address.toString();
}
} | [
"[email protected]"
] | |
66ca41786b18f253861286efce9b42243e3966ab | c6992ce8db7e5aab6fd959c0c448659ab91b16ce | /sdk/security/azure-resourcemanager-security/src/main/java/com/azure/resourcemanager/security/implementation/InformationProtectionPolicyImpl.java | ca0107ed1389d3f148e02c8c7c3a5af67c768a99 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"CC0-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later"
] | permissive | g2vinay/azure-sdk-for-java | ae6d94d583cc2983a5088ec8f6146744ee82cb55 | b88918a2ba0c3b3e88a36c985e6f83fc2bae2af2 | refs/heads/master | 2023-09-01T17:46:08.256214 | 2021-09-23T22:20:20 | 2021-09-23T22:20:20 | 161,234,198 | 3 | 1 | MIT | 2020-01-16T20:22:43 | 2018-12-10T20:44:41 | Java | UTF-8 | Java | false | false | 6,601 | java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.security.implementation;
import com.azure.core.util.Context;
import com.azure.resourcemanager.security.fluent.models.InformationProtectionPolicyInner;
import com.azure.resourcemanager.security.models.InformationProtectionPoliciesInformationProtectionPolicyName;
import com.azure.resourcemanager.security.models.InformationProtectionPolicy;
import com.azure.resourcemanager.security.models.InformationType;
import com.azure.resourcemanager.security.models.SensitivityLabel;
import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.Map;
public final class InformationProtectionPolicyImpl
implements InformationProtectionPolicy, InformationProtectionPolicy.Definition, InformationProtectionPolicy.Update {
private InformationProtectionPolicyInner innerObject;
private final com.azure.resourcemanager.security.SecurityManager serviceManager;
public String id() {
return this.innerModel().id();
}
public String name() {
return this.innerModel().name();
}
public String type() {
return this.innerModel().type();
}
public OffsetDateTime lastModifiedUtc() {
return this.innerModel().lastModifiedUtc();
}
public String version() {
return this.innerModel().version();
}
public Map<String, SensitivityLabel> labels() {
Map<String, SensitivityLabel> inner = this.innerModel().labels();
if (inner != null) {
return Collections.unmodifiableMap(inner);
} else {
return Collections.emptyMap();
}
}
public Map<String, InformationType> informationTypes() {
Map<String, InformationType> inner = this.innerModel().informationTypes();
if (inner != null) {
return Collections.unmodifiableMap(inner);
} else {
return Collections.emptyMap();
}
}
public InformationProtectionPolicyInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.security.SecurityManager manager() {
return this.serviceManager;
}
private String scope;
private InformationProtectionPoliciesInformationProtectionPolicyName informationProtectionPolicyName;
public InformationProtectionPolicyImpl withExistingScope(String scope) {
this.scope = scope;
return this;
}
public InformationProtectionPolicy create() {
this.innerObject =
serviceManager
.serviceClient()
.getInformationProtectionPolicies()
.createOrUpdateWithResponse(scope, informationProtectionPolicyName, this.innerModel(), Context.NONE)
.getValue();
return this;
}
public InformationProtectionPolicy create(Context context) {
this.innerObject =
serviceManager
.serviceClient()
.getInformationProtectionPolicies()
.createOrUpdateWithResponse(scope, informationProtectionPolicyName, this.innerModel(), context)
.getValue();
return this;
}
InformationProtectionPolicyImpl(
InformationProtectionPoliciesInformationProtectionPolicyName name,
com.azure.resourcemanager.security.SecurityManager serviceManager) {
this.innerObject = new InformationProtectionPolicyInner();
this.serviceManager = serviceManager;
this.informationProtectionPolicyName = name;
}
public InformationProtectionPolicyImpl update() {
return this;
}
public InformationProtectionPolicy apply() {
this.innerObject =
serviceManager
.serviceClient()
.getInformationProtectionPolicies()
.createOrUpdateWithResponse(scope, informationProtectionPolicyName, this.innerModel(), Context.NONE)
.getValue();
return this;
}
public InformationProtectionPolicy apply(Context context) {
this.innerObject =
serviceManager
.serviceClient()
.getInformationProtectionPolicies()
.createOrUpdateWithResponse(scope, informationProtectionPolicyName, this.innerModel(), context)
.getValue();
return this;
}
InformationProtectionPolicyImpl(
InformationProtectionPolicyInner innerObject,
com.azure.resourcemanager.security.SecurityManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
this.scope =
Utils
.getValueFromIdByParameterName(
innerObject.id(),
"/{scope}/providers/Microsoft.Security/informationProtectionPolicies"
+ "/{informationProtectionPolicyName}",
"scope");
this.informationProtectionPolicyName =
InformationProtectionPoliciesInformationProtectionPolicyName
.fromString(
Utils
.getValueFromIdByParameterName(
innerObject.id(),
"/{scope}/providers/Microsoft.Security/informationProtectionPolicies"
+ "/{informationProtectionPolicyName}",
"informationProtectionPolicyName"));
}
public InformationProtectionPolicy refresh() {
this.innerObject =
serviceManager
.serviceClient()
.getInformationProtectionPolicies()
.getWithResponse(scope, informationProtectionPolicyName, Context.NONE)
.getValue();
return this;
}
public InformationProtectionPolicy refresh(Context context) {
this.innerObject =
serviceManager
.serviceClient()
.getInformationProtectionPolicies()
.getWithResponse(scope, informationProtectionPolicyName, context)
.getValue();
return this;
}
public InformationProtectionPolicyImpl withLabels(Map<String, SensitivityLabel> labels) {
this.innerModel().withLabels(labels);
return this;
}
public InformationProtectionPolicyImpl withInformationTypes(Map<String, InformationType> informationTypes) {
this.innerModel().withInformationTypes(informationTypes);
return this;
}
}
| [
"[email protected]"
] | |
ef91c8a2509e9c62d65b1a569a5aef75611c6e54 | e53daa94a988135b8b1379c2a1e19e25bb045091 | /new_application/app/src/main/java/com/example/new_application/adapter/ServerInfoAdapter.java | e642872ee88e8e710175d77974b37539f8708a60 | [] | no_license | 2020xiaotu/trunk | f90c9bf15c9000a1bb18c7c0a3c0a96d4daf8e68 | ba19836c64828c2994e1f0db22fb5d26b4a014f5 | refs/heads/master | 2023-08-27T08:10:41.709940 | 2021-10-05T06:27:12 | 2021-10-05T06:27:12 | 413,684,673 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 681 | java | package com.example.new_application.adapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.example.new_application.bean.ServerInfoEntity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class ServerInfoAdapter extends BaseQuickAdapter<ServerInfoEntity, BaseViewHolder> {
public ServerInfoAdapter(int layoutResId, @Nullable List<ServerInfoEntity> data) {
super(layoutResId, data);
}
@Override
protected void convert(@NotNull BaseViewHolder baseViewHolder, ServerInfoEntity serverInfoEntity) {
}
}
| [
"[email protected]"
] | |
e84b47f565686d77e4e451ce00b4ab1504298552 | f065d03dca5b2bb71ac7fef2c476fcbe505a4f9e | /src/main/java/mathModel/manufacturing/Prices.java | 7465644ea2522a537745d50244166c9d97446bd2 | [] | no_license | vladyslav-kramarenko/project_Simulation | 7f5475701c07f5c2338bf1ac633bdd771ba3fd5b | 998776e2c8d7fd28a4bac4682f8633a7f761a97e | refs/heads/master | 2022-12-15T14:01:28.029493 | 2017-06-20T08:53:55 | 2017-06-20T08:53:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,321 | java | package mathModel.manufacturing;
import mathModel.Statistics;
import org.apache.log4j.Logger;
public class Prices {
private static Logger LOG = Logger.getLogger(Prices.class);
static void prices(Statistics coefOutcome, Statistics coefProdPrice, Statistics coefRawPrice,
Statistics prodPrice, Statistics rawPrice, Statistics wc) {
LOG.debug("Calculate prices");
double value;
LOG.debug("coefProdPrice = " + coefProdPrice);
LOG.debug("prodPriceValue=prodPrice(0) * multiply(coefProdPrice, i)");
LOG.debug("coefRawPrice = " + coefRawPrice);
LOG.debug("rawPriceValue = rawPrice(0) * multiply(coefRawPrice, i)");
for (byte i = 1; i < coefOutcome.size(); i++) {
LOG.debug("i = " + i);
value = prodPrice.getValue(0) * Multiply.multiply(coefProdPrice, i);
LOG.debug("prodPriceValue = " + prodPrice.getValue(0) + " * "
+ Multiply.multiply(coefProdPrice, i) + " = " + value);
prodPrice.add(wc.getYear(i), value);
LOG.debug("prodPrice.add(" + wc.getYear(i) + "," + value + ")");
value = rawPrice.getValue(0) * Multiply.multiply(coefRawPrice, i);
LOG.debug("rawPriceValue = " + rawPrice.getValue(0) + " * " + Multiply.multiply(coefRawPrice, i)
+ " = " + value);
rawPrice.add(wc.getYear(i), value);
LOG.debug("rawPrice.add(" + wc.getYear(i) + "," + value + ")");
}
}
}
| [
"[email protected]"
] | |
668053f32acac60691b3810a121474b935504557 | 96209005e1ff0506b5789ab83fdc1277ef20255d | /src/main/java/app/dao/ItemExameDAO.java | 46cc2f2658fe937d4f61c088b4950773dd01a61b | [] | no_license | thiagowenceslau/hygya | 4f2d66749cab3de0ba3b7bf482bf33913be21743 | da419596dbc574f42624d096d7607daa0d812a4d | refs/heads/master | 2020-03-15T14:56:52.292156 | 2018-06-05T19:12:31 | 2018-06-05T19:12:31 | 132,200,855 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,969 | java | package app.dao;
import app.entity.*;
import java.util.*;
import org.springframework.stereotype.*;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.domain.*;
import org.springframework.data.repository.query.*;
import org.springframework.transaction.annotation.*;
/**
* Realiza operação de Create, Read, Update e Delete no banco de dados.
* Os métodos de create, edit, delete e outros estão abstraídos no JpaRepository
*
* @see org.springframework.data.jpa.repository.JpaRepository
*
* @generated
*/
@Repository("ItemExameDAO")
@Transactional(transactionManager="app-TransactionManager")
public interface ItemExameDAO extends JpaRepository<ItemExame, java.lang.String> {
/**
* Obtém a instância de ItemExame utilizando os identificadores
*
* @param id
* Identificador
* @return Instância relacionada com o filtro indicado
* @generated
*/
@Query("SELECT entity FROM ItemExame entity WHERE entity.id = :id")
public ItemExame findOne(@Param(value="id") java.lang.String id);
/**
* Remove a instância de ItemExame utilizando os identificadores
*
* @param id
* Identificador
* @return Quantidade de modificações efetuadas
* @generated
*/
@Modifying
@Query("DELETE FROM ItemExame entity WHERE entity.id = :id")
public void delete(@Param(value="id") java.lang.String id);
/**
* OneToMany Relation
* @generated
*/
@Query("SELECT entity FROM ItemValorExame entity WHERE entity.itemExame.id = :id")
public Page<ItemValorExame> findItemValorExame(@Param(value="id") java.lang.String id, Pageable pageable);
/**
* Foreign Key resultado
* @generated
*/
@Query("SELECT entity FROM ItemExame entity WHERE entity.resultado.id = :id")
public Page<ItemExame> findItemExamesByResultado(@Param(value="id") java.lang.String id, Pageable pageable);
}
| [
"[email protected]"
] | |
d2902f2a85e22ae92dfc5b0a01ea9b3bdbba256f | ff774c9a856a47cd59b94a27c3586260c412751e | /tokenengine-common/src/main/java/com/mchain/tokenengine/service/CoinService.java | f9b8bfd54957f7a5699f20d0e022d3f2a7c42139 | [] | no_license | zhangdongle/token-engine | f9637aca5b5d62dcc929a8abaf58c078a8cf6502 | 95a96d2a274ebfea84b7cf3ff04d8cd4660dccf2 | refs/heads/master | 2023-03-24T09:20:39.793992 | 2021-03-15T08:13:55 | 2021-03-15T08:13:55 | 347,885,656 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 330 | java | package com.mchain.tokenengine.service;
import com.baomidou.mybatisplus.service.IService;
import com.mchain.tokenengine.entity.Coin;
/**
* <p>
* 币种表 服务类
* </p>
*
* @author koc
* @since 2018-09-06
*/
public interface CoinService extends IService<Coin> {
Coin getByCoinName(String name);
}
| [
"[email protected]"
] | |
c47ba0d546384ac5bbb4281d656fa8a1871e0166 | 10cd391ef94399b623e75eafa45a907aaa8602cd | /app/src/main/java/com/demoproject/custom/CTextView.java | 6ccd92963ce645ee8281311c53a1d6d15a2297e5 | [] | no_license | GaneshajDivekar/SynerzipDemoProject | 672943524f7e85466672985869b482d46b083501 | 8c74195499e562d0b90f197ff9323bb7e3f414b7 | refs/heads/master | 2023-01-12T04:28:56.466432 | 2020-11-04T04:52:03 | 2020-11-04T04:52:03 | 302,827,918 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,161 | java | package com.demoproject.custom;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatTextView;
import com.demoproject.R;
public class CTextView extends AppCompatTextView {
public CTextView(Context context) {
super(context);
init(null);
}
public CTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public CTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
public void init(AttributeSet attrs){
if(attrs!=null){
try{
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomTextFont);
String font=typedArray.getString(R.styleable.CustomTextFont_fontName);
setTypeface(FontCache.getTypeface(getContext(), font));
typedArray.recycle();
}catch (Exception e){ e.printStackTrace(); }
}else{ setTypeface(FontCache.getTypeface(getContext())); }
}
}
| [
"[email protected]"
] | |
d168a27f3b64c51e9bc383a9a311aad6e93b7787 | 3eb3438640806ed125c3a29c14885a7ae8269856 | /src/main/java/sk/akademiasovy/tipos/Server/TiposApplication.java | bba8b275589472d19228de0695e75eef5cee2314 | [] | no_license | JakuSel/projektTiposServer | ab9b3732cf03863dd796127fa3a3c9d191ecc616 | 8ae3fa1cca0b4209e55d5cdc427fcaa823d579e8 | refs/heads/master | 2021-04-25T08:30:26.102931 | 2018-05-10T19:18:30 | 2018-05-10T19:18:30 | 122,194,460 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,719 | java | package sk.akademiasovy.tipos.Server;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import sk.akademiasovy.tipos.Server.resources.Bets;
import sk.akademiasovy.tipos.Server.resources.Draws;
import sk.akademiasovy.tipos.Server.resources.Login;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import java.util.EnumSet;
public class TiposApplication extends Application<TiposConfiguration> {
public static void main(final String[] args) throws Exception {
new TiposApplication().run(args);
}
@Override
public String getName() {
return "Tipos";
}
@Override
public void initialize(final Bootstrap<TiposConfiguration> bootstrap) {
// TODO: application initialization
}
@Override
public void run(final TiposConfiguration configuration,
final Environment environment) {
// TODO: implement application
environment.jersey().register( new Login());
environment.jersey().register( new Bets());
environment.jersey().register( new Draws());
final FilterRegistration.Dynamic cors =
environment.servlets().addFilter("CORS", CrossOriginFilter.class);
// Configure CORS parameters
cors.setInitParameter("allowedOrigins", "*");
cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin");
cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
// Add URL mapping
cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
}
| [
"[email protected]"
] | |
c7992f0bad4b44729c5c283a239d68371a7a06f1 | 9200174e3ba816033815d9c54e7b5d44c30f32f6 | /chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java | 9ece0f55f60d76a70011e74009900afeb0ceb6e9 | [
"BSD-3-Clause"
] | permissive | NotBugThisFicha/Unobtainium | f9c059b77af6c85f8612308f56a2b92f32db80cd | 708de84c55b01e0deba1f6f505a7b2cea3f0a38b | refs/heads/master | 2022-04-04T17:05:00.777549 | 2018-06-22T14:09:52 | 2018-06-22T14:09:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 99,628 | java | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.SearchManager;
import android.app.assist.AssistContent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.os.SystemClock;
import android.support.annotation.CallSuper;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener;
import android.view.accessibility.AccessibilityManager.TouchExplorationStateChangeListener;
import org.chromium.base.ActivityState;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.ApplicationStatus;
import org.chromium.base.BaseSwitches;
import org.chromium.base.Callback;
import org.chromium.base.CommandLine;
import org.chromium.base.ContextUtils;
import org.chromium.base.DiscardableReferencePool;
import org.chromium.base.SysUtils;
import org.chromium.base.TraceEvent;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.IntentHandler.IntentHandlerDelegate;
import org.chromium.chrome.browser.IntentHandler.TabOpenType;
import org.chromium.chrome.browser.appmenu.AppMenu;
import org.chromium.chrome.browser.appmenu.AppMenuHandler;
import org.chromium.chrome.browser.appmenu.AppMenuObserver;
import org.chromium.chrome.browser.appmenu.AppMenuPropertiesDelegate;
import org.chromium.chrome.browser.bookmarks.BookmarkModel;
import org.chromium.chrome.browser.bookmarks.BookmarkUtils;
import org.chromium.chrome.browser.compositor.CompositorViewHolder;
import org.chromium.chrome.browser.compositor.bottombar.OverlayPanel.StateChangeReason;
import org.chromium.chrome.browser.compositor.layouts.Layout;
import org.chromium.chrome.browser.compositor.layouts.LayoutManager;
import org.chromium.chrome.browser.compositor.layouts.SceneChangeObserver;
import org.chromium.chrome.browser.compositor.layouts.content.ContentOffsetProvider;
import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager;
import org.chromium.chrome.browser.contextual_suggestions.ContextualSuggestionsCoordinator;
import org.chromium.chrome.browser.contextual_suggestions.PageViewTimer;
import org.chromium.chrome.browser.contextualsearch.ContextualSearchFieldTrial;
import org.chromium.chrome.browser.contextualsearch.ContextualSearchManager;
import org.chromium.chrome.browser.contextualsearch.ContextualSearchManager.ContextualSearchTabPromotionDelegate;
import org.chromium.chrome.browser.datausage.DataUseTabUIManager;
import org.chromium.chrome.browser.device.DeviceClassManager;
import org.chromium.chrome.browser.dom_distiller.DomDistillerUIUtils;
import org.chromium.chrome.browser.dom_distiller.ReaderModeManager;
import org.chromium.chrome.browser.download.DownloadManagerService;
import org.chromium.chrome.browser.download.DownloadUtils;
import org.chromium.chrome.browser.download.items.OfflineContentAggregatorNotificationBridgeUiFactory;
import org.chromium.chrome.browser.firstrun.ForcedSigninProcessor;
import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager;
import org.chromium.chrome.browser.gsa.ContextReporter;
import org.chromium.chrome.browser.gsa.GSAAccountChangeListener;
import org.chromium.chrome.browser.gsa.GSAState;
import org.chromium.chrome.browser.help.HelpAndFeedback;
import org.chromium.chrome.browser.history.HistoryManagerUtils;
import org.chromium.chrome.browser.infobar.InfoBarContainer;
import org.chromium.chrome.browser.init.AsyncInitializationActivity;
import org.chromium.chrome.browser.init.ProcessInitializationHandler;
import org.chromium.chrome.browser.locale.LocaleManager;
import org.chromium.chrome.browser.media.PictureInPicture;
import org.chromium.chrome.browser.media.PictureInPictureController;
import org.chromium.chrome.browser.metrics.LaunchMetrics;
import org.chromium.chrome.browser.metrics.StartupMetrics;
import org.chromium.chrome.browser.metrics.UmaSessionStats;
import org.chromium.chrome.browser.metrics.WebApkUma;
import org.chromium.chrome.browser.modaldialog.AppModalPresenter;
import org.chromium.chrome.browser.modaldialog.ModalDialogManager;
import org.chromium.chrome.browser.multiwindow.MultiWindowUtils;
import org.chromium.chrome.browser.net.spdyproxy.DataReductionProxySettings;
import org.chromium.chrome.browser.nfc.BeamController;
import org.chromium.chrome.browser.ntp.NewTabPage;
import org.chromium.chrome.browser.ntp.NewTabPageUma;
import org.chromium.chrome.browser.offlinepages.OfflinePageUtils;
import org.chromium.chrome.browser.omaha.UpdateMenuItemHelper;
import org.chromium.chrome.browser.page_info.PageInfoPopup;
import org.chromium.chrome.browser.partnercustomizations.PartnerBrowserCustomizations;
import org.chromium.chrome.browser.preferences.ChromePreferenceManager;
import org.chromium.chrome.browser.preferences.PrefServiceBridge;
import org.chromium.chrome.browser.preferences.PreferencesLauncher;
import org.chromium.chrome.browser.printing.TabPrinter;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.share.ShareMenuActionHandler;
import org.chromium.chrome.browser.snackbar.BottomContainer;
import org.chromium.chrome.browser.snackbar.DataUseSnackbarController;
import org.chromium.chrome.browser.snackbar.SnackbarManager;
import org.chromium.chrome.browser.snackbar.SnackbarManager.SnackbarManageable;
import org.chromium.chrome.browser.sync.ProfileSyncService;
import org.chromium.chrome.browser.sync.SyncController;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tabmodel.AsyncTabParamsManager;
import org.chromium.chrome.browser.tabmodel.EmptyTabModel;
import org.chromium.chrome.browser.tabmodel.TabCreatorManager;
import org.chromium.chrome.browser.tabmodel.TabModel;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelSelectorTabObserver;
import org.chromium.chrome.browser.tabmodel.TabModelUtils;
import org.chromium.chrome.browser.tabmodel.TabWindowManager;
import org.chromium.chrome.browser.toolbar.BottomToolbarController;
import org.chromium.chrome.browser.toolbar.Toolbar;
import org.chromium.chrome.browser.toolbar.ToolbarControlContainer;
import org.chromium.chrome.browser.toolbar.ToolbarManager;
import org.chromium.chrome.browser.util.AccessibilityUtil;
import org.chromium.chrome.browser.util.ColorUtils;
import org.chromium.chrome.browser.util.FeatureUtilities;
import org.chromium.chrome.browser.vr_shell.VrIntentUtils;
import org.chromium.chrome.browser.vr_shell.VrShellDelegate;
import org.chromium.chrome.browser.webapps.AddToHomescreenManager;
import org.chromium.chrome.browser.widget.ControlContainer;
import org.chromium.chrome.browser.widget.FadingBackgroundView;
import org.chromium.chrome.browser.widget.bottomsheet.BottomSheet;
import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController;
import org.chromium.chrome.browser.widget.findinpage.FindToolbarManager;
import org.chromium.chrome.browser.widget.textbubble.TextBubble;
import org.chromium.components.bookmarks.BookmarkId;
import org.chromium.content.browser.ContentVideoView;
import org.chromium.content.common.ContentSwitches;
import org.chromium.content_public.browser.ContentViewCore;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.SelectionPopupController;
import org.chromium.content_public.browser.WebContents;
import org.chromium.policy.CombinedPolicyProvider;
import org.chromium.policy.CombinedPolicyProvider.PolicyChangeListener;
import org.chromium.printing.PrintManagerDelegateImpl;
import org.chromium.printing.PrintingController;
import org.chromium.printing.PrintingControllerImpl;
import org.chromium.ui.base.ActivityWindowAndroid;
import org.chromium.ui.base.DeviceFormFactor;
import org.chromium.ui.base.PageTransition;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.display.DisplayAndroid;
import org.chromium.ui.widget.Toast;
import org.chromium.webapk.lib.client.WebApkNavigationClient;
import org.chromium.webapk.lib.client.WebApkValidator;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* A {@link AsyncInitializationActivity} that builds and manages a {@link CompositorViewHolder}
* and associated classes.
*/
public abstract class ChromeActivity extends AsyncInitializationActivity
implements TabCreatorManager, AccessibilityStateChangeListener, PolicyChangeListener,
ContextualSearchTabPromotionDelegate, SnackbarManageable, SceneChangeObserver {
/**
* Factory which creates the AppMenuHandler.
*/
public interface AppMenuHandlerFactory {
/**
* @return AppMenuHandler for the given activity and menu resource id.
*/
public AppMenuHandler get(Activity activity, AppMenuPropertiesDelegate delegate,
int menuResourceId);
}
/**
* No control container to inflate during initialization.
*/
static final int NO_CONTROL_CONTAINER = -1;
/**
* No toolbar layout to inflate during initialization.
*/
static final int NO_TOOLBAR_LAYOUT = -1;
private static final int RECORD_MULTI_WINDOW_SCREEN_WIDTH_DELAY_MS = 5000;
/**
* Timeout in ms for reading PartnerBrowserCustomizations provider.
*/
private static final int PARTNER_BROWSER_CUSTOMIZATIONS_TIMEOUT_MS = 10000;
private static AppMenuHandlerFactory sAppMenuHandlerFactory =
(activity, delegate, menuResourceId) -> new AppMenuHandler(activity, delegate,
menuResourceId);
private TabModelSelector mTabModelSelector;
private TabModelSelectorTabObserver mTabModelSelectorTabObserver;
private TabCreatorManager.TabCreator mRegularTabCreator;
private TabCreatorManager.TabCreator mIncognitoTabCreator;
private TabContentManager mTabContentManager;
private UmaSessionStats mUmaSessionStats;
private ContextReporter mContextReporter;
private boolean mPartnerBrowserRefreshNeeded;
protected IntentHandler mIntentHandler;
/** Set if {@link #postDeferredStartupIfNeeded()} is called before native has loaded. */
private boolean mDeferredStartupQueued;
/** Whether or not {@link #postDeferredStartupIfNeeded()} has already successfully run. */
private boolean mDeferredStartupPosted;
private boolean mTabModelsInitialized;
private boolean mNativeInitialized;
private boolean mRemoveWindowBackgroundDone;
// The class cannot implement TouchExplorationStateChangeListener,
// because it is only available for Build.VERSION_CODES.KITKAT and later.
// We have to instantiate the TouchExplorationStateChangeListner object in the code.
@SuppressLint("NewApi")
private TouchExplorationStateChangeListener mTouchExplorationStateChangeListener;
// Observes when sync becomes ready to create the mContextReporter.
private ProfileSyncService.SyncStateChangedListener mSyncStateChangedListener;
private ChromeFullscreenManager mFullscreenManager;
private boolean mCreatedFullscreenManager;
// The PictureInPictureController is initialized lazily https://crbug.com/729738.
private PictureInPictureController mPictureInPictureController;
private CompositorViewHolder mCompositorViewHolder;
private InsetObserverView mInsetObserverView;
private ContextualSearchManager mContextualSearchManager;
protected ReaderModeManager mReaderModeManager;
private SnackbarManager mSnackbarManager;
private ModalDialogManager mModalDialogManager;
private DataUseSnackbarController mDataUseSnackbarController;
private AppMenuPropertiesDelegate mAppMenuPropertiesDelegate;
private AppMenuHandler mAppMenuHandler;
private ToolbarManager mToolbarManager;
private FindToolbarManager mFindToolbarManager;
private BottomSheetController mBottomSheetController;
private BottomToolbarController mBottomToolbarController;
private BottomSheet mBottomSheet;
private ContextualSuggestionsCoordinator mContextualSuggestionsCoordinator;
private FadingBackgroundView mFadingBackgroundView;
// Time in ms that it took took us to inflate the initial layout
private long mInflateInitialLayoutDurationMs;
private int mUiMode;
private int mDensityDpi;
private int mScreenWidthDp;
private Runnable mRecordMultiWindowModeScreenWidthRunnable;
private final DiscardableReferencePool mReferencePool = new DiscardableReferencePool();
private AssistStatusHandler mAssistStatusHandler;
// A set of views obscuring all tabs. When this set is nonempty,
// all tab content will be hidden from the accessibility tree.
private Set<View> mViewsObscuringAllTabs = new HashSet<>();
// See enableHardwareAcceleration()
private boolean mSetWindowHWA;
/** Whether or not a PolicyChangeListener was added. */
private boolean mDidAddPolicyChangeListener;
/** Adds TabObserver and TabModelObserver to measure page view times. */
private PageViewTimer mPageViewTimer;
/**
* @param factory The {@link AppMenuHandlerFactory} for creating {@link #mAppMenuHandler}
*/
@VisibleForTesting
public static void setAppMenuHandlerFactoryForTesting(AppMenuHandlerFactory factory) {
sAppMenuHandlerFactory = factory;
}
@Override
protected ActivityWindowAndroid createWindowAndroid() {
return new ChromeWindow(this);
}
@Override
public void preInflationStartup() {
super.preInflationStartup();
if (VrShellDelegate.bootsToVr()) {
// TODO(mthiesse): Remove this once b/78108624 is fixed. This is a workaround for a
// platform bug where Chrome crashes on launch for standalone devices if not launched
// onto the primary display (There's a virtual display 2D apps are default launched onto
// with different display properties). Re-launch with the same intent but to the primary
// display.
if (DisplayAndroid.getNonMultiDisplay(this).getDisplayId() != Display.DEFAULT_DISPLAY) {
finish();
startActivity(getIntent(),
ApiCompatibilityUtils.createLaunchDisplayIdActivityOptions(
Display.DEFAULT_DISPLAY));
return;
}
}
// We need to explicitly enable VR mode here so that the system doesn't kick us out of VR,
// or drop us into the 2D-in-VR rendering mode, while we prepare for VR rendering.
if (VrIntentUtils.isVrIntent(getIntent())
|| VrIntentUtils.wouldUse2DInVrRenderingMode(this)) {
VrShellDelegate.setVrModeEnabled(this, true);
}
// Force a partner customizations refresh if it has yet to be initialized. This can happen
// if Chrome is killed and you refocus a previous activity from Android recents, which does
// not go through ChromeLauncherActivity that would have normally triggered this.
mPartnerBrowserRefreshNeeded = !PartnerBrowserCustomizations.isInitialized();
ApplicationInitialization.enableFullscreenFlags(
getResources(), this, getControlContainerHeightResource());
getWindow().setBackgroundDrawable(getBackgroundDrawable());
mFullscreenManager = createFullscreenManager();
mCreatedFullscreenManager = true;
}
@SuppressLint("NewApi")
@Override
public void postInflationStartup() {
super.postInflationStartup();
Intent intent = getIntent();
if (intent != null && getSavedInstanceState() == null) {
VrShellDelegate.maybeHandleVrIntentPreNative(this, intent);
}
mSnackbarManager = new SnackbarManager(this, null);
mDataUseSnackbarController = new DataUseSnackbarController(this, getSnackbarManager());
mAssistStatusHandler = createAssistStatusHandler();
if (mAssistStatusHandler != null) {
if (mTabModelSelector != null) {
mAssistStatusHandler.setTabModelSelector(mTabModelSelector);
}
mAssistStatusHandler.updateAssistState();
}
// This check is only applicable for JB since in KK svelte was supported from the start.
// See https://crbug.com/826460 for context.
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
// If a user had ALLOW_LOW_END_DEVICE_UI explicitly set to false then we manually
// override SysUtils.isLowEndDevice() with a switch so that they continue to see the
// normal UI. This is only the case for grandfathered-in svelte users. We no longer do
// so for newer users.
if (!ChromePreferenceManager.getInstance().getAllowLowEndDeviceUi()) {
CommandLine.getInstance().appendSwitch(BaseSwitches.DISABLE_LOW_END_DEVICE_MODE);
}
}
AccessibilityManager manager = (AccessibilityManager)
getBaseContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
manager.addAccessibilityStateChangeListener(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mTouchExplorationStateChangeListener = enabled -> checkAccessibility();
manager.addTouchExplorationStateChangeListener(mTouchExplorationStateChangeListener);
}
// Make the activity listen to policy change events
CombinedPolicyProvider.get().addPolicyChangeListener(this);
mDidAddPolicyChangeListener = true;
// Set up the animation placeholder to be the SurfaceView. This disables the
// SurfaceView's 'hole' clipping during animations that are notified to the window.
getWindowAndroid().setAnimationPlaceholderView(mCompositorViewHolder.getCompositorView());
// Inform the WindowAndroid of the keyboard accessory view.
getWindowAndroid().setKeyboardAccessoryView(
(ViewGroup) findViewById(R.id.keyboard_accessory));
initializeToolbar();
initializeTabModels();
if (!isFinishing() && getFullscreenManager() != null) {
getFullscreenManager().initialize(
(ControlContainer) findViewById(R.id.control_container),
getTabModelSelector(),
getControlContainerHeightResource());
}
((BottomContainer) findViewById(R.id.bottom_container)).initialize(mFullscreenManager);
mModalDialogManager = createModalDialogManager();
mPageViewTimer = new PageViewTimer(mTabModelSelector);
}
@Override
protected View getViewToBeDrawnBeforeInitializingNative() {
View controlContainer = findViewById(R.id.control_container);
return controlContainer != null ? controlContainer
: super.getViewToBeDrawnBeforeInitializingNative();
}
/**
* This function builds the {@link CompositorViewHolder}. Subclasses *must* call
* super.setContentView() before using {@link #getTabModelSelector()} or
* {@link #getCompositorViewHolder()}.
*/
@Override
protected final void setContentView() {
final long begin = SystemClock.elapsedRealtime();
TraceEvent.begin("onCreate->setContentView()");
SelectionPopupController.setShouldGetReadbackViewFromWindowAndroid();
enableHardwareAcceleration();
setLowEndTheme();
int controlContainerLayoutId = getControlContainerLayoutId();
WarmupManager warmupManager = WarmupManager.getInstance();
if (warmupManager.hasViewHierarchyWithToolbar(controlContainerLayoutId)) {
View placeHolderView = new View(this);
setContentView(placeHolderView);
ViewGroup contentParent = (ViewGroup) placeHolderView.getParent();
warmupManager.transferViewHierarchyTo(contentParent);
contentParent.removeView(placeHolderView);
} else {
warmupManager.clearViewHierarchy();
// Allow disk access for the content view and toolbar container setup.
// On certain android devices this setup sequence results in disk writes outside
// of our control, so we have to disable StrictMode to work. See crbug.com/639352.
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
try {
setContentView(R.layout.main);
if (controlContainerLayoutId != NO_CONTROL_CONTAINER) {
ViewStub toolbarContainerStub =
((ViewStub) findViewById(R.id.control_container_stub));
toolbarContainerStub.setLayoutResource(controlContainerLayoutId);
toolbarContainerStub.inflate();
}
// It cannot be assumed that the result of toolbarContainerStub.inflate() will be
// the control container since it may be wrapped in another view.
ControlContainer controlContainer =
(ControlContainer) findViewById(R.id.control_container);
// Inflate the correct toolbar layout for the device.
int toolbarLayoutId = getToolbarLayoutId();
if (toolbarLayoutId != NO_TOOLBAR_LAYOUT && controlContainer != null) {
controlContainer.initWithToolbar(toolbarLayoutId);
}
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
}
TraceEvent.end("onCreate->setContentView()");
mInflateInitialLayoutDurationMs = SystemClock.elapsedRealtime() - begin;
// Set the status bar color to black by default. This is an optimization for
// Chrome not to draw under status and navigation bars when we use the default
// black status bar
setStatusBarColor(null, Color.BLACK);
ViewGroup rootView = (ViewGroup) getWindow().getDecorView().getRootView();
mCompositorViewHolder = (CompositorViewHolder) findViewById(R.id.compositor_view_holder);
mCompositorViewHolder.setRootView(rootView);
// Setting fitsSystemWindows to false ensures that the root view doesn't consume the insets.
rootView.setFitsSystemWindows(false);
// Add a custom view right after the root view that stores the insets to access later.
// ContentViewCore needs the insets to determine the portion of the screen obscured by
// non-content displaying things such as the OSK.
mInsetObserverView = InsetObserverView.create(this);
rootView.addView(mInsetObserverView, 0);
}
@Override
public boolean shouldStartGpuProcess() {
return true;
}
/**
* Constructs {@link ToolbarManager} and the handler necessary for controlling the menu on the
* {@link Toolbar}. Extending classes can override this call to avoid creating the toolbar.
*/
protected void initializeToolbar() {
final View controlContainer = findViewById(R.id.control_container);
assert controlContainer != null;
ToolbarControlContainer toolbarContainer = (ToolbarControlContainer) controlContainer;
mAppMenuPropertiesDelegate = createAppMenuPropertiesDelegate();
mAppMenuHandler = sAppMenuHandlerFactory.get(this, mAppMenuPropertiesDelegate,
getAppMenuLayoutId());
Callback<Boolean> urlFocusChangedCallback = hasFocus -> onOmniboxFocusChanged(hasFocus);
mToolbarManager = new ToolbarManager(this, toolbarContainer, mAppMenuHandler,
mAppMenuPropertiesDelegate, getCompositorViewHolder().getInvalidator(),
urlFocusChangedCallback);
mFindToolbarManager = new FindToolbarManager(
this, mToolbarManager.getActionModeController().getActionModeCallback());
mAppMenuHandler.addObserver(new AppMenuObserver() {
@Override
public void onMenuVisibilityChanged(boolean isVisible) {
if (isVisible && !isInOverviewMode()) {
// The app menu badge should be removed the first time the menu is opened.
if (mToolbarManager.getToolbar().isShowingAppMenuUpdateBadge()) {
mToolbarManager.getToolbar().removeAppMenuUpdateBadge(true);
mCompositorViewHolder.requestRender();
}
}
if (!isVisible) {
mAppMenuPropertiesDelegate.onMenuDismissed();
MenuItem updateMenuItem = mAppMenuHandler.getAppMenu().getMenu().findItem(
R.id.update_menu_id);
if (updateMenuItem != null && updateMenuItem.isVisible()) {
UpdateMenuItemHelper.getInstance().onMenuDismissed();
}
}
}
@Override
public void onMenuHighlightChanged(boolean highlighting) {}
});
}
/**
* Initialize the {@link TabModelSelector}, {@link TabModel}s, and
* {@link org.chromium.chrome.browser.tabmodel.TabCreatorManager.TabCreator} needed by
* this activity.
*/
protected final void initializeTabModels() {
if (mTabModelsInitialized) return;
mTabModelSelector = createTabModelSelector();
if (mTabModelSelector == null) {
assert isFinishing();
mTabModelsInitialized = true;
return;
}
Pair<? extends TabCreator, ? extends TabCreator> tabCreators = createTabCreators();
mRegularTabCreator = tabCreators.first;
mIncognitoTabCreator = tabCreators.second;
OfflinePageUtils.observeTabModelSelector(this, mTabModelSelector);
NewTabPageUma.monitorNTPCreation(mTabModelSelector);
if (mTabModelSelectorTabObserver != null) mTabModelSelectorTabObserver.destroy();
mTabModelSelectorTabObserver = new TabModelSelectorTabObserver(mTabModelSelector) {
@Override
public void didFirstVisuallyNonEmptyPaint(Tab tab) {
if (DataUseTabUIManager.checkAndResetDataUseTrackingStarted(tab)
&& DataUseTabUIManager.shouldShowDataUseStartedUI()) {
mDataUseSnackbarController.showDataUseTrackingStartedBar();
} else if (DataUseTabUIManager.shouldShowDataUseEndedUI()
&& DataUseTabUIManager.shouldShowDataUseEndedSnackbar(
getApplicationContext())
&& DataUseTabUIManager.checkAndResetDataUseTrackingEnded(tab)) {
mDataUseSnackbarController.showDataUseTrackingEndedBar();
}
/*
// Only alert about data savings once the first paint has happened. It doesn't make
// sense to show a snackbar about savings when nothing has been displayed yet.
if (DataReductionProxySettings.getInstance().isSnackbarPromoAllowed(tab.getUrl())) {
if (mDataReductionPromoSnackbarController == null) {
mDataReductionPromoSnackbarController =
new DataReductionPromoSnackbarController(
getApplicationContext(), getSnackbarManager());
}
mDataReductionPromoSnackbarController.maybeShowDataReductionPromoSnackbar(
DataReductionProxySettings.getInstance()
.getTotalHttpContentLengthSaved());
}*/
}
@Override
public void onShown(Tab tab) {
setStatusBarColor(tab, tab.getThemeColor());
}
@Override
public void onHidden(Tab tab) {
mDataUseSnackbarController.dismissDataUseBar();
}
@Override
public void onDestroyed(Tab tab) {
mDataUseSnackbarController.dismissDataUseBar();
}
@Override
public void onLoadStopped(Tab tab, boolean toDifferentDocument) {
postDeferredStartupIfNeeded();
}
@Override
public void onPageLoadFinished(Tab tab) {
postDeferredStartupIfNeeded();
OfflinePageUtils.showOfflineSnackbarIfNecessary(tab);
}
@Override
public void onCrash(Tab tab, boolean sadTabShown) {
postDeferredStartupIfNeeded();
}
@Override
public void onDidChangeThemeColor(Tab tab, int color) {
if (getActivityTab() != tab) return;
setStatusBarColor(tab, color);
if (getToolbarManager() == null) return;
getToolbarManager().updatePrimaryColor(color, true);
ControlContainer controlContainer =
(ControlContainer) findViewById(R.id.control_container);
controlContainer.getToolbarResourceAdapter().invalidate(null);
}
@Override
public void onContentChanged(Tab tab) {
if (getBottomSheet() != null) setStatusBarColor(tab, tab.getDefaultThemeColor());
}
};
if (mAssistStatusHandler != null) {
mAssistStatusHandler.setTabModelSelector(mTabModelSelector);
}
mTabModelsInitialized = true;
}
/**
* @return The {@link TabModelSelector} owned by this {@link ChromeActivity}.
*/
protected abstract TabModelSelector createTabModelSelector();
/**
* @return The {@link org.chromium.chrome.browser.tabmodel.TabCreatorManager.TabCreator}s owned
* by this {@link ChromeActivity}. The first item in the Pair is the normal model tab
* creator, and the second is the tab creator for incognito tabs.
*/
protected abstract Pair<? extends TabCreator, ? extends TabCreator> createTabCreators();
/**
* @return {@link ToolbarManager} that belongs to this activity.
*/
public ToolbarManager getToolbarManager() {
return mToolbarManager;
}
/**
* @return {@link FindToolbarManager} that belongs to this activity.
*/
public FindToolbarManager getFindToolbarManager() {
return mFindToolbarManager;
}
/**
* @return The resource id for the menu to use in {@link AppMenu}. Default is R.menu.main_menu.
*/
protected int getAppMenuLayoutId() {
return R.menu.main_menu;
}
/**
* Get the Chrome Home bottom sheet if it exists.
* @return The bottom sheet or null.
*/
@Nullable
public BottomSheet getBottomSheet() {
return mBottomSheet;
}
/**
* @return The View used to obscure content and bring focus to a foreground view.
*/
public FadingBackgroundView getFadingBackgroundView() {
return mFadingBackgroundView;
}
/**
* @return {@link AppMenuPropertiesDelegate} instance that the {@link AppMenuHandler}
* should be using in this activity.
*/
protected AppMenuPropertiesDelegate createAppMenuPropertiesDelegate() {
return new AppMenuPropertiesDelegate(this);
}
/**
* @return The assist handler for this activity.
*/
protected AssistStatusHandler getAssistStatusHandler() {
return mAssistStatusHandler;
}
/**
* @return A newly constructed assist handler for this given activity type.
*/
protected AssistStatusHandler createAssistStatusHandler() {
return new AssistStatusHandler(this);
}
/**
* @return The resource id for the layout to use for {@link ControlContainer}. 0 by default.
*/
protected int getControlContainerLayoutId() {
return NO_CONTROL_CONTAINER;
}
/**
* @return The layout ID for the toolbar to use.
*/
protected int getToolbarLayoutId() {
return NO_TOOLBAR_LAYOUT;
}
/**
* @return Whether contextual search is allowed for this activity or not.
*/
protected boolean isContextualSearchAllowed() {
return true;
}
@Override
public void initializeState() {
super.initializeState();
IntentHandler.setTestIntentsEnabled(
CommandLine.getInstance().hasSwitch(ContentSwitches.ENABLE_TEST_INTENTS));
mIntentHandler = new IntentHandler(createIntentHandlerDelegate(), getPackageName());
}
@Override
public void initializeCompositor() {
TraceEvent.begin("ChromeActivity:CompositorInitialization");
super.initializeCompositor();
setTabContentManager(new TabContentManager(this, getContentOffsetProvider(),
DeviceClassManager.enableSnapshots()));
mCompositorViewHolder.onNativeLibraryReady(getWindowAndroid(), getTabContentManager());
if (isContextualSearchAllowed() && ContextualSearchFieldTrial.isEnabled()) {
mContextualSearchManager = new ContextualSearchManager(this, this);
if (mFindToolbarManager != null) {
mContextualSearchManager.setFindToolbarManager(mFindToolbarManager);
}
}
if (ReaderModeManager.isEnabled(this)) {
mReaderModeManager = new ReaderModeManager(getTabModelSelector(), this);
}
TraceEvent.end("ChromeActivity:CompositorInitialization");
}
@Override
public void onStartWithNative() {
assert mNativeInitialized : "onStartWithNative was called before native was initialized.";
super.onStartWithNative();
UpdateMenuItemHelper.getInstance().onStart();
ChromeActivitySessionTracker.getInstance().onStartWithNative();
// postDeferredStartupIfNeeded() is called in TabModelSelectorTabObsever#onLoadStopped(),
// #onPageLoadFinished() and #onCrash(). If we are not actively loading a tab (e.g.
// in Android N multi-instance, which is created by re-parenting an existing tab),
// ensure onDeferredStartup() gets called by calling postDeferredStartupIfNeeded() here.
if (mDeferredStartupQueued || getActivityTab() == null || !getActivityTab().isLoading()) {
postDeferredStartupIfNeeded();
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
maybeRemoveWindowBackground();
Tab tab = getActivityTab();
if (hasFocus) {
if (tab != null) tab.onActivityShown();
VrShellDelegate.onActivityShown(this);
} else {
boolean stopped = ApplicationStatus.getStateForActivity(this) == ActivityState.STOPPED;
if (stopped) {
VrShellDelegate.onActivityHidden(this);
if (tab != null) tab.onActivityHidden();
}
}
}
/**
* Set device status bar to a given color.
* @param tab The tab that is currently showing.
* @param color The color that the status bar should be set to.
*/
protected void setStatusBarColor(@Nullable Tab tab, int color) {
boolean useModernDesign =
supportsModernDesign() && FeatureUtilities.isChromeModernDesignEnabled();
int statusBarColor = color;
boolean supportsDarkStatusIcons = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
View root = getWindow().getDecorView().getRootView();
if (useModernDesign && supportsDarkStatusIcons) {
int systemUiVisibility = root.getSystemUiVisibility();
boolean needsDarkStatusBarIcons =
!ColorUtils.shouldUseLightForegroundOnBackground(statusBarColor);
if (needsDarkStatusBarIcons) {
systemUiVisibility |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
} else if (!needsDarkStatusBarIcons) {
systemUiVisibility &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
}
root.setSystemUiVisibility(systemUiVisibility);
} else {
statusBarColor = (tab != null && tab.isDefaultThemeColor())
? Color.BLACK
: ColorUtils.getDarkenedColorForStatusBar(color);
}
ApiCompatibilityUtils.setStatusBarColor(getWindow(), statusBarColor);
}
private void createContextReporterIfNeeded() {
if (mContextReporter != null || getActivityTab() == null) return;
final SyncController syncController = SyncController.get(this);
final ProfileSyncService syncService = ProfileSyncService.get();
if (syncController != null && syncController.isSyncingUrlsWithKeystorePassphrase()) {
assert syncService != null;
mContextReporter = AppHooks.get().createGsaHelper().getContextReporter(this);
if (mSyncStateChangedListener != null) {
syncService.removeSyncStateChangedListener(mSyncStateChangedListener);
mSyncStateChangedListener = null;
}
return;
} else {
ContextReporter.reportSyncStatus(syncService);
}
if (mSyncStateChangedListener == null && syncService != null) {
mSyncStateChangedListener = () -> createContextReporterIfNeeded();
syncService.addSyncStateChangedListener(mSyncStateChangedListener);
}
}
@Override
public void onResumeWithNative() {
super.onResumeWithNative();
markSessionResume();
RecordUserAction.record("MobileComeToForeground");
if (getActivityTab() != null) {
LaunchMetrics.commitLaunchMetrics(getActivityTab().getWebContents());
}
for (TabModel model : getTabModelSelector().getModels()) {
int count = model.getCount();
for (int i = 0; i < count; ++i) {
ContentViewCore cvc = model.getTabAt(i).getActiveContentViewCore();
if (cvc != null) cvc.onResume();
}
}
FeatureUtilities.setCustomTabVisible(isCustomTab());
FeatureUtilities.setIsInMultiWindowMode(
MultiWindowUtils.getInstance().isInMultiWindowMode(this));
if (getActivityTab() != null) {
getActivityTab().setPictureInPictureEnabled(
PictureInPicture.isEnabled(getApplicationContext()));
}
if (mPictureInPictureController != null) {
mPictureInPictureController.cleanup(this);
}
VrShellDelegate.maybeRegisterVrEntryHook(this);
}
@Override
protected void onUserLeaveHint() {
super.onUserLeaveHint();
if (mPictureInPictureController == null) {
mPictureInPictureController = new PictureInPictureController();
}
mPictureInPictureController.attemptPictureInPicture(this);
}
@Override
public void onPauseWithNative() {
RecordUserAction.record("MobileGoToBackground");
Tab tab = getActivityTab();
if (tab != null) getTabContentManager().cacheTabThumbnail(tab);
for (TabModel model : getTabModelSelector().getModels()) {
int count = model.getCount();
for (int i = 0; i < count; ++i) {
ContentViewCore cvc = model.getTabAt(i).getActiveContentViewCore();
if (cvc != null) cvc.onPause();
}
}
VrShellDelegate.maybeUnregisterVrEntryHook(this);
markSessionEnd();
super.onPauseWithNative();
}
@Override
public void onStopWithNative() {
Tab tab = getActivityTab();
if (!hasWindowFocus()) {
VrShellDelegate.onActivityHidden(this);
if (tab != null) tab.onActivityHidden();
}
if (mAppMenuHandler != null) mAppMenuHandler.hideAppMenu();
if (GSAState.getInstance(this).isGsaAvailable() && !SysUtils.isLowEndDevice()) {
GSAAccountChangeListener.getInstance().disconnect();
if (mSyncStateChangedListener != null) {
ProfileSyncService syncService = ProfileSyncService.get();
if (syncService != null) {
syncService.removeSyncStateChangedListener(mSyncStateChangedListener);
}
mSyncStateChangedListener = null;
}
}
if (mContextReporter != null) mContextReporter.disable();
super.onStopWithNative();
}
@Override
protected void onNewIntent(Intent intent) {
// This should be called before the call to super so that the needed VR flags are set as
// soon as the VR intent is received.
VrShellDelegate.maybeHandleVrIntentPreNative(this, intent);
super.onNewIntent(intent);
}
@Override
public void onNewIntentWithNative(Intent intent) {
if (mPictureInPictureController != null) {
mPictureInPictureController.cleanup(this);
}
super.onNewIntentWithNative(intent);
if (mIntentHandler.shouldIgnoreIntent(intent)) return;
// We send this intent so that we can enter WebVr presentation mode if needed. This
// call doesn't consume the intent because it also has the url that we need to load.
VrShellDelegate.onNewIntentWithNative(this, intent);
mIntentHandler.onNewIntent(intent);
}
/**
* @return Whether the given activity contains a CustomTab.
*/
public boolean isCustomTab() {
return false;
}
/**
* @return Whether the given activity can show the publisher URL from a trusted CDN.
*/
public boolean canShowTrustedCdnPublisherUrl() {
return false;
}
/**
* Actions that may be run at some point after startup. Place tasks that are not critical to the
* startup path here. This method will be called automatically.
*/
private void onDeferredStartup() {
initDeferredStartupForActivity();
ProcessInitializationHandler.getInstance().initializeDeferredStartupTasks();
DeferredStartupHandler.getInstance().queueDeferredTasksOnIdleHandler();
}
/**
* All deferred startup tasks that require the activity rather than the app should go here.
*
* Overriding methods should queue tasks on the DeferredStartupHandler before or after calling
* super depending on whether the tasks should run before or after these ones.
*/
@CallSuper
protected void initDeferredStartupForActivity() {
DeferredStartupHandler.getInstance().addDeferredTask(() -> {
if (isActivityDestroyed()) return;
BeamController.registerForBeam(ChromeActivity.this, () -> {
Tab currentTab = getActivityTab();
if (currentTab == null) return null;
if (!currentTab.isUserInteractable()) return null;
return currentTab.getUrl();
});
UpdateMenuItemHelper.getInstance().checkForUpdateOnBackgroundThread(
ChromeActivity.this);
});
final String simpleName = getClass().getSimpleName();
DeferredStartupHandler.getInstance().addDeferredTask(() -> {
if (isActivityDestroyed()) return;
if (mToolbarManager != null) {
RecordHistogram.recordTimesHistogram(
"MobileStartup.ToolbarInflationTime." + simpleName,
mInflateInitialLayoutDurationMs, TimeUnit.MILLISECONDS);
mToolbarManager.onDeferredStartup(getOnCreateTimestampMs(), simpleName);
}
if (MultiWindowUtils.getInstance().isInMultiWindowMode(ChromeActivity.this)) {
onDeferredStartupForMultiWindowMode();
}
long intentTimestamp = IntentHandler.getTimestampFromIntent(getIntent());
if (intentTimestamp != -1) {
recordIntentToCreationTime(getOnCreateTimestampMs() - intentTimestamp);
}
});
DeferredStartupHandler.getInstance().addDeferredTask(() -> {
if (isActivityDestroyed()) return;
ForcedSigninProcessor.checkCanSignIn(ChromeActivity.this);
});
// GSA connection is not needed on low-end devices because Icing is disabled.
if (!SysUtils.isLowEndDevice()) {
if (isActivityDestroyed()) return;
DeferredStartupHandler.getInstance().addDeferredTask(() -> {
if (!GSAState.getInstance(this).isGsaAvailable()) {
ContextReporter.reportStatus(ContextReporter.STATUS_GSA_NOT_AVAILABLE);
return;
}
GSAAccountChangeListener.getInstance().connect();
createContextReporterIfNeeded();
});
}
}
/**
* Actions that may be run at some point after startup for Android N multi-window mode. Should
* be called from #onDeferredStartup() if the activity is in multi-window mode.
*/
protected void onDeferredStartupForMultiWindowMode() {
// If the Activity was launched in multi-window mode, record a user action and the screen
// width.
recordMultiWindowModeChangedUserAction(true);
recordMultiWindowModeScreenWidth();
}
/**
* Records the time it takes from creating an intent for {@link ChromeActivity} to activity
* creation, including time spent in the framework.
* @param timeMs The time from creating an intent to activity creation.
*/
@CallSuper
protected void recordIntentToCreationTime(long timeMs) {
RecordHistogram.recordTimesHistogram(
"MobileStartup.IntentToCreationTime", timeMs, TimeUnit.MILLISECONDS);
}
@Override
public void onStart() {
if (AsyncTabParamsManager.hasParamsWithTabToReparent()) {
mCompositorViewHolder.prepareForTabReparenting();
}
super.onStart();
if (mPartnerBrowserRefreshNeeded) {
mPartnerBrowserRefreshNeeded = false;
PartnerBrowserCustomizations.initializeAsync(getApplicationContext(),
PARTNER_BROWSER_CUSTOMIZATIONS_TIMEOUT_MS);
PartnerBrowserCustomizations.setOnInitializeAsyncFinished(() -> {
if (PartnerBrowserCustomizations.isIncognitoDisabled()) {
terminateIncognitoSession();
}
});
}
if (mCompositorViewHolder != null) mCompositorViewHolder.onStart();
mSnackbarManager.onStart();
// Explicitly call checkAccessibility() so things are initialized correctly when Chrome has
// been re-started after closing due to the last tab being closed when homepage is enabled.
// See crbug.com/541546.
checkAccessibility();
Configuration config = getResources().getConfiguration();
mUiMode = config.uiMode;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
mDensityDpi = config.densityDpi;
} else {
mDensityDpi = getResources().getDisplayMetrics().densityDpi;
}
mScreenWidthDp = config.screenWidthDp;
}
@Override
public void onStop() {
super.onStop();
// We want to refresh partner browser provider every onStart().
mPartnerBrowserRefreshNeeded = true;
if (mCompositorViewHolder != null) mCompositorViewHolder.onStop();
mSnackbarManager.onStop();
}
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onProvideAssistContent(AssistContent outContent) {
if (getAssistStatusHandler() == null || !getAssistStatusHandler().isAssistSupported()) {
// No information is provided in incognito mode.
return;
}
Tab tab = getActivityTab();
if (tab != null && !isInOverviewMode()) {
outContent.setWebUri(Uri.parse(tab.getUrl()));
}
}
@Override
public long getOnCreateTimestampMs() {
return super.getOnCreateTimestampMs();
}
/**
* This cannot be overridden in order to preserve destruction order. Override
* {@link #onDestroyInternal()} instead to perform clean up tasks.
*/
@SuppressLint("NewApi")
@Override
protected final void onDestroy() {
if (mPageViewTimer != null) {
mPageViewTimer.destroy();
mPageViewTimer = null;
}
if (mReaderModeManager != null) {
mReaderModeManager.destroy();
mReaderModeManager = null;
}
if (mContextualSearchManager != null) {
mContextualSearchManager.destroy();
mContextualSearchManager = null;
}
if (mTabModelSelectorTabObserver != null) {
mTabModelSelectorTabObserver.destroy();
mTabModelSelectorTabObserver = null;
}
if (mCompositorViewHolder != null) {
if (mCompositorViewHolder.getLayoutManager() != null) {
mCompositorViewHolder.getLayoutManager().removeSceneChangeObserver(this);
}
mCompositorViewHolder.shutDown();
mCompositorViewHolder = null;
}
onDestroyInternal();
if (mToolbarManager != null) {
mToolbarManager.destroy();
mToolbarManager = null;
}
if (mBottomSheet != null) {
mBottomSheet.destroy();
mBottomSheet = null;
}
if (mBottomToolbarController != null) {
mBottomToolbarController.destroy();
mBottomToolbarController = null;
}
if (mContextualSuggestionsCoordinator != null) {
mContextualSuggestionsCoordinator.destroy();
mContextualSuggestionsCoordinator = null;
}
if (mTabModelsInitialized) {
TabModelSelector selector = getTabModelSelector();
if (selector != null) selector.destroy();
}
if (mDidAddPolicyChangeListener) {
CombinedPolicyProvider.get().removePolicyChangeListener(this);
mDidAddPolicyChangeListener = false;
}
if (mTabContentManager != null) {
mTabContentManager.destroy();
mTabContentManager = null;
}
AccessibilityManager manager = (AccessibilityManager)
getBaseContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
manager.removeAccessibilityStateChangeListener(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
manager.removeTouchExplorationStateChangeListener(mTouchExplorationStateChangeListener);
}
super.onDestroy();
}
/**
* Override this to perform destruction tasks. Note that by the time this is called, the
* {@link CompositorViewHolder} will be destroyed, but the {@link WindowAndroid} and
* {@link TabModelSelector} will not.
* <p>
* After returning from this, the {@link TabModelSelector} will be destroyed followed
* by the {@link WindowAndroid}.
*/
protected void onDestroyInternal() {
}
/**
* @return The unified manager for all snackbar related operations.
*/
@Override
public SnackbarManager getSnackbarManager() {
return mBottomSheetController != null
&& mBottomSheetController.getBottomSheet().isSheetOpen()
? mBottomSheetController.getSnackbarManager()
: mSnackbarManager;
}
/**
* @return The {@link ModalDialogManager} created for this class.
*/
protected ModalDialogManager createModalDialogManager() {
return new ModalDialogManager(new AppModalPresenter(this), ModalDialogManager.APP_MODAL);
}
/**
* @return The {@link ModalDialogManager} that manages the display of modal dialogs (e.g.
* JavaScript dialogs).
*/
public ModalDialogManager getModalDialogManager() {
return mModalDialogManager;
}
/**
* Sets the modal dialog mangaer.
*/
public void setModalDialogManager(ModalDialogManager modalDialogManager) {
mModalDialogManager = modalDialogManager;
}
protected Drawable getBackgroundDrawable() {
return new ColorDrawable(
ApiCompatibilityUtils.getColor(getResources(), R.color.light_background_color));
}
private void maybeRemoveWindowBackground() {
// Only need to do this logic once.
if (mRemoveWindowBackgroundDone) return;
// Remove the window background only after native init and window getting focus. It's done
// after native init because before native init, a fake background gets shown. The window
// focus dependency is because doing it earlier can cause drawing bugs, e.g. crbug/673831.
if (!mNativeInitialized || !hasWindowFocus()) return;
// The window background color is used as the resizing background color in Android N+
// multi-window mode. See crbug.com/602366.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
getWindow().setBackgroundDrawable(new ColorDrawable(
ApiCompatibilityUtils.getColor(getResources(),
R.color.resizing_background_color)));
} else {
// Post the removeWindowBackground() call as a separate task, as doing it synchronously
// here can cause redrawing glitches. See crbug.com/686662 for an example problem.
Handler handler = new Handler();
handler.post(() -> removeWindowBackground());
}
mRemoveWindowBackgroundDone = true;
}
@Override
public void finishNativeInitialization() {
mNativeInitialized = true;
OfflineContentAggregatorNotificationBridgeUiFactory.instance();
maybeRemoveWindowBackground();
DownloadManagerService.getDownloadManagerService().onActivityLaunched();
if (getSavedInstanceState() == null && getIntent() != null) {
VrShellDelegate.onNewIntentWithNative(this, getIntent());
}
VrShellDelegate.onNativeLibraryAvailable();
super.finishNativeInitialization();
if (FeatureUtilities.isChromeDuplexEnabled()) {
ViewGroup coordinator = findViewById(R.id.coordinator);
mBottomToolbarController = new BottomToolbarController(mFullscreenManager,
mCompositorViewHolder.getResourceManager(),
mCompositorViewHolder.getLayoutManager(), coordinator);
}
if (supportsContextualSuggestionsBottomSheet()
&& FeatureUtilities.isContextualSuggestionsBottomSheetEnabled(isTablet())) {
ViewGroup coordinator = (ViewGroup) findViewById(R.id.coordinator);
getLayoutInflater().inflate(R.layout.bottom_sheet, coordinator);
mBottomSheet = coordinator.findViewById(R.id.bottom_sheet);
mBottomSheet.init(coordinator, this);
((BottomContainer) findViewById(R.id.bottom_container)).setBottomSheet(mBottomSheet);
mFadingBackgroundView = (FadingBackgroundView) findViewById(R.id.fading_focus_target);
mBottomSheetController = new BottomSheetController(this, getTabModelSelector(),
getCompositorViewHolder().getLayoutManager(), mFadingBackgroundView,
getContextualSearchManager(), mBottomSheet);
mContextualSuggestionsCoordinator = new ContextualSuggestionsCoordinator(
this, mBottomSheetController, getTabModelSelector());
}
}
/**
* @return Whether native initialization has been completed for this activity.
*/
public boolean didFinishNativeInitialization() {
return mNativeInitialized;
}
/**
* Called when the accessibility status of this device changes. This might be triggered by
* touch exploration or general accessibility status updates. It is an aggregate of two other
* accessibility update methods.
*
* @see #onAccessibilityStateChanged
* @see #mTouchExplorationStateChangeListener
* @param enabled Whether or not accessibility and touch exploration are currently enabled.
*/
protected void onAccessibilityModeChanged(boolean enabled) {
InfoBarContainer.setIsAllowedToAutoHide(!enabled);
if (mToolbarManager != null) mToolbarManager.onAccessibilityStatusChanged(enabled);
if (mContextualSearchManager != null) {
mContextualSearchManager.onAccessibilityModeChanged(enabled);
}
if (mContextualSuggestionsCoordinator != null) {
mContextualSuggestionsCoordinator.onAccessibilityModeChanged(enabled);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && onMenuOrKeyboardAction(item.getItemId(), true)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Triggered when the share menu item is selected.
* This creates and shows a share intent picker dialog or starts a share intent directly.
* @param shareDirectly Whether it should share directly with the activity that was most
* recently used to share.
* @param isIncognito Whether currentTab is incognito.
*/
@VisibleForTesting
public void onShareMenuItemSelected(final boolean shareDirectly, final boolean isIncognito) {
ShareMenuActionHandler.getInstance().onShareMenuItemSelected(
this, getActivityTab(), shareDirectly, isIncognito);
}
/**
* @return Whether the activity is in overview mode.
*/
public boolean isInOverviewMode() {
return false;
}
/**
* @return Whether the app menu should be shown.
*/
public boolean shouldShowAppMenu() {
// Do not show the menu if Contextual Search panel is opened.
if (mContextualSearchManager != null && mContextualSearchManager.isSearchPanelOpened()) {
return false;
}
// Do not show the menu if we are in find in page view.
if (mFindToolbarManager != null && mFindToolbarManager.isShowing() && !isTablet()) {
return false;
}
return true;
}
/**
* Shows the app menu (if possible) for a key press on the keyboard with the correct anchor view
* chosen depending on device configuration and the visible menu button to the user.
*/
protected void showAppMenuForKeyboardEvent() {
if (getAppMenuHandler() == null) return;
TextBubble.dismissBubbles();
boolean hasPermanentMenuKey = ViewConfiguration.get(this).hasPermanentMenuKey();
getAppMenuHandler().showAppMenu(
hasPermanentMenuKey ? null : getToolbarManager().getMenuButton(), false);
}
/**
* Allows Activities that extend ChromeActivity to do additional hiding/showing of menu items.
* @param menu Menu that is going to be shown when the menu button is pressed.
*/
public void prepareMenu(Menu menu) {
}
protected IntentHandlerDelegate createIntentHandlerDelegate() {
return new IntentHandlerDelegate() {
@Override
public void processWebSearchIntent(String query) {
final Intent searchIntent = new Intent(Intent.ACTION_WEB_SEARCH);
searchIntent.putExtra(SearchManager.QUERY, query);
Callback<Boolean> callback = result -> {
if (result != null && result) startActivity(searchIntent);
};
LocaleManager.getInstance().showSearchEnginePromoIfNeeded(
ChromeActivity.this, callback);
}
@Override
public void processUrlViewIntent(String url, String referer, String headers,
TabOpenType tabOpenType, String externalAppId, int tabIdToBringToFront,
boolean hasUserGesture, Intent intent) {
}
};
}
/**
* @return The resource id that contains how large the browser controls are.
*/
public int getControlContainerHeightResource() {
return R.dimen.control_container_height;
}
@Override
public final void onAccessibilityStateChanged(boolean enabled) {
checkAccessibility();
}
private void checkAccessibility() {
onAccessibilityModeChanged(AccessibilityUtil.isAccessibilityEnabled());
}
/**
* @return A casted version of {@link #getApplication()}.
*/
public ChromeApplication getChromeApplication() {
return (ChromeApplication) getApplication();
}
/**
* Add the specified tab to bookmarks or allows to edit the bookmark if the specified tab is
* already bookmarked. If a new bookmark is added, a snackbar will be shown.
* @param tabToBookmark The tab that needs to be bookmarked.
*/
public void addOrEditBookmark(final Tab tabToBookmark) {
if (tabToBookmark == null || tabToBookmark.isFrozen()) {
return;
}
// Defense in depth against the UI being erroneously enabled.
if (!mToolbarManager.getBookmarkBridge().isEditBookmarksEnabled()) {
assert false;
return;
}
// Note the use of getUserBookmarkId() over getBookmarkId() here: Managed bookmarks can't be
// edited. If the current URL is only bookmarked by managed bookmarks, this will return
// INVALID_BOOKMARK_ID, so the code below will fall back on adding a new bookmark instead.
// TODO(bauerb): This does not take partner bookmarks into account.
final long bookmarkId = tabToBookmark.getUserBookmarkId();
final BookmarkModel bookmarkModel = new BookmarkModel();
bookmarkModel.finishLoadingBookmarkModel(() -> {
// Gives up the bookmarking if the tab is being destroyed.
if (!tabToBookmark.isClosing() && tabToBookmark.isInitialized()) {
// The BookmarkModel will be destroyed by BookmarkUtils#addOrEditBookmark() when
// done.
BookmarkId newBookmarkId = BookmarkUtils.addOrEditBookmark(bookmarkId,
bookmarkModel, tabToBookmark, getSnackbarManager(), ChromeActivity.this,
isCustomTab());
// If a new bookmark was created, try to save an offline page for it.
if (newBookmarkId != null && newBookmarkId.getId() != bookmarkId) {
OfflinePageUtils.saveBookmarkOffline(newBookmarkId, tabToBookmark);
}
} else {
bookmarkModel.destroy();
}
});
}
/**
* @return Whether the tab models have been fully initialized.
*/
public boolean areTabModelsInitialized() {
return mTabModelsInitialized;
}
/**
* {@link TabModelSelector} no longer implements TabModel. Use getTabModelSelector() or
* getCurrentTabModel() depending on your needs.
* @return The {@link TabModelSelector}, possibly null.
*/
public TabModelSelector getTabModelSelector() {
if (!mTabModelsInitialized) {
throw new IllegalStateException(
"Attempting to access TabModelSelector before initialization");
}
return mTabModelSelector;
}
/**
* Returns the {@link InsetObserverView} that has the current system window
* insets information.
* @return The {@link InsetObserverView}, possibly null.
*/
public InsetObserverView getInsetObserverView() {
return mInsetObserverView;
}
@Override
public TabCreatorManager.TabCreator getTabCreator(boolean incognito) {
if (!mTabModelsInitialized) {
throw new IllegalStateException(
"Attempting to access TabCreator before initialization");
}
return incognito ? mIncognitoTabCreator : mRegularTabCreator;
}
/**
* Convenience method that returns a tab creator for the currently selected {@link TabModel}.
* @return A tab creator for the currently selected {@link TabModel}.
*/
public TabCreatorManager.TabCreator getCurrentTabCreator() {
return getTabCreator(getTabModelSelector().isIncognitoSelected());
}
/**
* Gets the {@link TabContentManager} instance which holds snapshots of the tabs in this model.
* @return The thumbnail cache, possibly null.
*/
public TabContentManager getTabContentManager() {
return mTabContentManager;
}
/**
* Sets the {@link TabContentManager} owned by this {@link ChromeActivity}.
* @param tabContentManager A {@link TabContentManager} instance.
*/
protected void setTabContentManager(TabContentManager tabContentManager) {
mTabContentManager = tabContentManager;
}
/**
* Gets the current (inner) TabModel. This is a convenience function for
* getModelSelector().getCurrentModel(). It is *not* equivalent to the former getModel()
* @return Never null, if modelSelector or its field is uninstantiated returns a
* {@link EmptyTabModel} singleton
*/
public TabModel getCurrentTabModel() {
TabModelSelector modelSelector = getTabModelSelector();
if (modelSelector == null) return EmptyTabModel.getInstance();
return modelSelector.getCurrentModel();
}
/**
* Returns the tab being displayed by this ChromeActivity instance. This allows differentiation
* between ChromeActivity subclasses that swap between multiple tabs (e.g. ChromeTabbedActivity)
* and subclasses that only display one Tab (e.g. FullScreenActivity and DocumentActivity).
*
* The default implementation grabs the tab currently selected by the TabModel, which may be
* null if the Tab does not exist or the system is not initialized.
*/
public Tab getActivityTab() {
return TabModelUtils.getCurrentTab(getCurrentTabModel());
}
/**
* @return The current ContentViewCore, or null if the tab does not exist or is not showing a
* ContentViewCore.
*/
public ContentViewCore getCurrentContentViewCore() {
return TabModelUtils.getCurrentContentViewCore(getCurrentTabModel());
}
/**
* @return A {@link CompositorViewHolder} instance.
*/
public CompositorViewHolder getCompositorViewHolder() {
return mCompositorViewHolder;
}
/**
* Gets the full screen manager.
* @return The fullscreen manager, possibly null
*/
public ChromeFullscreenManager getFullscreenManager() {
if (!mCreatedFullscreenManager) {
throw new IllegalStateException(
"Attempting to access FullscreenManager before it has been created.");
}
return mFullscreenManager;
}
/**
* Sets the overlay mode.
* Overlay mode means that we are currently using AndroidOverlays to display video, and
* that the compositor's surface should support alpha and not be marked as opaque.
*/
public void setOverlayMode(boolean useOverlayMode) {
if (mCompositorViewHolder != null) mCompositorViewHolder.setOverlayMode(useOverlayMode);
}
/**
* @return The content offset provider, may be null.
*/
public ContentOffsetProvider getContentOffsetProvider() {
return mCompositorViewHolder;
}
/**
* @return The {@code ContextualSearchManager} or {@code null} if none;
*/
public ContextualSearchManager getContextualSearchManager() {
return mContextualSearchManager;
}
/**
* @return The {@code ReaderModeManager} or {@code null} if none;
*/
@VisibleForTesting
public ReaderModeManager getReaderModeManager() {
return mReaderModeManager;
}
/**
* Create a full-screen manager to be used by this activity.
* Note: This is called during {@link #postInflationStartup}, so native code may not have been
* initialized, but Android Views will have been.
* @return A {@link ChromeFullscreenManager} instance that's been created.
*/
protected ChromeFullscreenManager createFullscreenManager() {
return new ChromeFullscreenManager(this, ChromeFullscreenManager.CONTROLS_POSITION_TOP);
}
/**
* Exits the fullscreen mode, if any. Does nothing if no fullscreen is present.
* @return Whether the fullscreen mode is currently showing.
*/
protected boolean exitFullscreenIfShowing() {
ContentVideoView view = ContentVideoView.getContentVideoView();
if (view != null && view.getContext() == this) {
view.exitFullscreen(false);
return true;
}
if (getFullscreenManager() != null
&& getFullscreenManager().getPersistentFullscreenMode()) {
getFullscreenManager().setPersistentFullscreenMode(false);
return true;
}
return false;
}
/**
* Initializes the {@link CompositorViewHolder} with the relevant content it needs to properly
* show content on the screen.
* @param layoutManager A {@link LayoutManager} instance. This class is
* responsible for driving all high level screen content and
* determines which {@link Layout} is shown when.
* @param urlBar The {@link View} representing the URL bar (must be
* focusable) or {@code null} if none exists.
* @param contentContainer A {@link ViewGroup} that can have content attached by
* {@link Layout}s.
* @param controlContainer A {@link ControlContainer} instance to draw.
*/
protected void initializeCompositorContent(LayoutManager layoutManager, View urlBar,
ViewGroup contentContainer, ControlContainer controlContainer) {
if (mContextualSearchManager != null) {
mContextualSearchManager.initialize(contentContainer);
mContextualSearchManager.setSearchContentViewDelegate(layoutManager);
}
layoutManager.addSceneChangeObserver(this);
mCompositorViewHolder.setLayoutManager(layoutManager);
mCompositorViewHolder.setFocusable(false);
mCompositorViewHolder.setControlContainer(controlContainer);
mCompositorViewHolder.setFullscreenHandler(getFullscreenManager());
mCompositorViewHolder.setUrlBar(urlBar);
mCompositorViewHolder.onFinishNativeInitialization(getTabModelSelector(), this,
getTabContentManager(), contentContainer, mContextualSearchManager);
if (controlContainer != null && DeviceClassManager.enableToolbarSwipe()
&& getCompositorViewHolder().getLayoutManager().getTopSwipeHandler() != null) {
controlContainer.setSwipeHandler(
getCompositorViewHolder().getLayoutManager().getTopSwipeHandler());
}
}
/**
* Called when the back button is pressed.
* @return Whether or not the back button was handled.
*/
protected abstract boolean handleBackPressed();
@Override
public void onOrientationChange(int orientation) {
if (mToolbarManager != null) mToolbarManager.onOrientationChange();
Tab tab = getActivityTab();
if (tab != null) tab.onOrientationChange();
}
/**
* Notified when the focus of the omnibox has changed.
*
* @param hasFocus Whether the omnibox currently has focus.
*/
protected void onOmniboxFocusChanged(boolean hasFocus) {}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (mAppMenuHandler != null) mAppMenuHandler.hideAppMenu();
super.onConfigurationChanged(newConfig);
// We only handle VR UI mode changes. Any other changes should follow the default behavior
// of recreating the activity.
if (didChangeNonVrUiMode(mUiMode, newConfig.uiMode)) {
recreate();
return;
}
mUiMode = newConfig.uiMode;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (newConfig.densityDpi != mDensityDpi) {
if (!VrShellDelegate.onDensityChanged(mDensityDpi, newConfig.densityDpi)) {
recreate();
return;
}
mDensityDpi = newConfig.densityDpi;
}
}
if (newConfig.screenWidthDp != mScreenWidthDp) {
mScreenWidthDp = newConfig.screenWidthDp;
final Activity activity = this;
if (mRecordMultiWindowModeScreenWidthRunnable != null) {
mHandler.removeCallbacks(mRecordMultiWindowModeScreenWidthRunnable);
}
// When exiting Android N multi-window mode, onConfigurationChanged() gets called before
// isInMultiWindowMode() returns false. Delay to avoid recording width when exiting
// multi-window mode. This also ensures that we don't record intermediate widths seen
// only for a brief period of time.
mRecordMultiWindowModeScreenWidthRunnable = () -> {
mRecordMultiWindowModeScreenWidthRunnable = null;
if (MultiWindowUtils.getInstance().isInMultiWindowMode(activity)) {
recordMultiWindowModeScreenWidth();
}
};
mHandler.postDelayed(mRecordMultiWindowModeScreenWidthRunnable,
RECORD_MULTI_WINDOW_SCREEN_WIDTH_DELAY_MS);
}
}
private static boolean didChangeNonVrUiMode(int oldMode, int newMode) {
if (oldMode == newMode) return false;
return isInVrUiMode(oldMode) == isInVrUiMode(newMode);
}
private static boolean isInVrUiMode(int uiMode) {
return (uiMode & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_VR_HEADSET;
}
/**
* Called by the system when the activity changes from fullscreen mode to multi-window mode
* and visa-versa.
* @param isInMultiWindowMode True if the activity is in multi-window mode.
*/
@Override
public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
// If native is not initialized, the multi-window user action will be recorded in
// #onDeferredStartupForMultiWindowMode() and FeatureUtilities#setIsInMultiWindowMode()
// will be called in #onResumeWithNative(). Both of these methods require native to be
// initialized, so do not call here to avoid crashing. See https://crbug.com/797921.
if (mNativeInitialized) {
recordMultiWindowModeChangedUserAction(isInMultiWindowMode);
if (!isInMultiWindowMode
&& ApplicationStatus.getStateForActivity(this) == ActivityState.RESUMED) {
// Start a new UMA session when exiting multi-window mode if the activity is
// currently resumed. When entering multi-window Android recents gains focus, so
// ChromeActivity will get a call to onPauseWithNative(), ending the current UMA
// session. When exiting multi-window, however, if ChromeActivity is resumed it
// stays in that state.
markSessionEnd();
markSessionResume();
FeatureUtilities.setIsInMultiWindowMode(
MultiWindowUtils.getInstance().isInMultiWindowMode(this));
}
}
VrShellDelegate.onMultiWindowModeChanged(isInMultiWindowMode);
super.onMultiWindowModeChanged(isInMultiWindowMode);
}
/**
* Records user actions associated with entering and exiting Android N multi-window mode
* @param isInMultiWindowMode True if the activity is in multi-window mode.
*/
protected void recordMultiWindowModeChangedUserAction(boolean isInMultiWindowMode) {
if (isInMultiWindowMode) {
RecordUserAction.record("Android.MultiWindowMode.Enter");
} else {
RecordUserAction.record("Android.MultiWindowMode.Exit");
}
}
@Override
public final void onBackPressed() {
if (mNativeInitialized) RecordUserAction.record("SystemBack");
TextBubble.dismissBubbles();
if (VrShellDelegate.onBackPressed()) return;
if (mCompositorViewHolder != null) {
LayoutManager layoutManager = mCompositorViewHolder.getLayoutManager();
if (layoutManager != null && layoutManager.onBackPressed()) return;
}
SelectionPopupController controller = getSelectionPopupController();
if (controller != null && controller.isSelectActionBarShowing()) {
controller.clearSelection();
return;
}
if (mContextualSearchManager != null && mContextualSearchManager.onBackPressed()) return;
if (handleBackPressed()) return;
super.onBackPressed();
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
// The conditions are expressed using ranges to capture intermediate levels possibly added
// to the API in the future.
if ((level >= TRIM_MEMORY_RUNNING_LOW && level < TRIM_MEMORY_UI_HIDDEN)
|| level >= TRIM_MEMORY_MODERATE) {
mReferencePool.drain();
clearToolbarResourceCache();
}
}
private ContentViewCore getContentViewCore() {
Tab tab = getActivityTab();
if (tab == null) return null;
return tab.getContentViewCore();
}
private WebContents getWebContents() {
Tab tab = getActivityTab();
if (tab == null) return null;
return tab.getWebContents();
}
private SelectionPopupController getSelectionPopupController() {
WebContents webContents = getWebContents();
return webContents != null ? SelectionPopupController.fromWebContents(webContents) : null;
}
@Override
public void createContextualSearchTab(String searchUrl) {
Tab currentTab = getActivityTab();
if (currentTab == null) return;
TabCreator tabCreator = getTabCreator(currentTab.isIncognito());
if (tabCreator == null) return;
tabCreator.createNewTab(
new LoadUrlParams(searchUrl, PageTransition.LINK),
TabModel.TabLaunchType.FROM_LINK, getActivityTab());
}
/**
* @return The {@link AppMenuHandler} associated with this activity.
*/
@VisibleForTesting
public AppMenuHandler getAppMenuHandler() {
return mAppMenuHandler;
}
/**
* @return The {@link AppMenuPropertiesDelegate} associated with this activity.
*/
@VisibleForTesting
public AppMenuPropertiesDelegate getAppMenuPropertiesDelegate() {
return mAppMenuPropertiesDelegate;
}
/**
* Callback after UpdateMenuItemHelper#checkForUpdateOnBackgroundThread is complete.
* @param updateAvailable Whether an update is available.
*/
public void onCheckForUpdate(boolean updateAvailable) {
if (UpdateMenuItemHelper.getInstance().shouldShowToolbarBadge(this)) {
mToolbarManager.getToolbar().showAppMenuUpdateBadge();
mCompositorViewHolder.requestRender();
} else {
mToolbarManager.getToolbar().removeAppMenuUpdateBadge(false);
}
}
/**
* Handles menu item selection and keyboard shortcuts.
*
* @param id The ID of the selected menu item (defined in main_menu.xml) or
* keyboard shortcut (defined in values.xml).
* @param fromMenu Whether this was triggered from the menu.
* @return Whether the action was handled.
*/
public boolean onMenuOrKeyboardAction(int id, boolean fromMenu) {
if (id == R.id.preferences_id) {
PreferencesLauncher.launchSettingsPage(this, null);
RecordUserAction.record("MobileMenuSettings");
} else if (id == R.id.show_menu) {
showAppMenuForKeyboardEvent();
} else if (id == R.id.find_in_page_id) {
if (mFindToolbarManager == null) return false;
mFindToolbarManager.showToolbar();
if (mContextualSearchManager != null) {
getContextualSearchManager().hideContextualSearch(StateChangeReason.UNKNOWN);
}
if (fromMenu) {
RecordUserAction.record("MobileMenuFindInPage");
} else {
RecordUserAction.record("MobileShortcutFindInPage");
}
return true;
}
if (id == R.id.update_menu_id) {
UpdateMenuItemHelper.getInstance().onMenuItemClicked(this);
return true;
}
final Tab currentTab = getActivityTab();
if (id == R.id.help_id) {
String url = currentTab != null ? currentTab.getUrl() : "";
Profile profile = mTabModelSelector.isIncognitoSelected()
? Profile.getLastUsedProfile().getOffTheRecordProfile()
: Profile.getLastUsedProfile().getOriginalProfile();
startHelpAndFeedback(url, "MobileMenuFeedback", profile);
return true;
}
// All the code below assumes currentTab is not null, so return early if it is null.
if (currentTab == null) {
return false;
} else if (id == R.id.forward_menu_id) {
if (currentTab.canGoForward()) {
currentTab.goForward();
RecordUserAction.record("MobileMenuForward");
}
} else if (id == R.id.bookmark_this_page_id) {
addOrEditBookmark(currentTab);
RecordUserAction.record("MobileMenuAddToBookmarks");
} else if (id == R.id.offline_page_id) {
DownloadUtils.downloadOfflinePage(this, currentTab);
RecordUserAction.record("MobileMenuDownloadPage");
} else if (id == R.id.reload_menu_id) {
if (currentTab.isLoading()) {
currentTab.stopLoading();
RecordUserAction.record("MobileMenuStop");
} else {
currentTab.reload();
RecordUserAction.record("MobileMenuReload");
}
} else if (id == R.id.info_menu_id) {
PageInfoPopup.show(this, currentTab, null, PageInfoPopup.OPENED_FROM_MENU);
} else if (id == R.id.open_history_menu_id) {
if (NewTabPage.isNTPUrl(currentTab.getUrl())) {
NewTabPageUma.recordAction(NewTabPageUma.ACTION_OPENED_HISTORY_MANAGER);
}
RecordUserAction.record("MobileMenuHistory");
HistoryManagerUtils.showHistoryManager(this, currentTab);
StartupMetrics.getInstance().recordOpenedHistory();
} else if (id == R.id.share_menu_id || id == R.id.direct_share_menu_id) {
onShareMenuItemSelected(id == R.id.direct_share_menu_id,
getCurrentTabModel().isIncognito());
} else if (id == R.id.print_id) {
PrintingController printingController = PrintingControllerImpl.getInstance();
if (printingController != null && !printingController.isBusy()
&& PrefServiceBridge.getInstance().isPrintingEnabled()) {
printingController.startPrint(new TabPrinter(currentTab),
new PrintManagerDelegateImpl(this));
RecordUserAction.record("MobileMenuPrint");
}
} else if (id == R.id.add_to_homescreen_id) {
// Record whether or not we have finished installability checks for this page when the
// user clicks the add to homescren menu item. This will let us determine how effective
// an on page-load check will be in speeding up WebAPK installation.
currentTab.getAppBannerManager().recordMenuItemAddToHomescreen();
AddToHomescreenManager addToHomescreenManager =
new AddToHomescreenManager(this, currentTab);
addToHomescreenManager.start();
RecordUserAction.record("MobileMenuAddToHomescreen");
} else if (id == R.id.open_webapk_id) {
Context context = ContextUtils.getApplicationContext();
String packageName = WebApkValidator.queryWebApkPackage(context, currentTab.getUrl());
Intent launchIntent = WebApkNavigationClient.createLaunchWebApkIntent(
packageName, currentTab.getUrl(), false);
try {
context.startActivity(launchIntent);
RecordUserAction.record("MobileMenuOpenWebApk");
WebApkUma.recordWebApkOpenAttempt(WebApkUma.WEBAPK_OPEN_LAUNCH_SUCCESS);
} catch (ActivityNotFoundException e) {
WebApkUma.recordWebApkOpenAttempt(WebApkUma.WEBAPK_OPEN_ACTIVITY_NOT_FOUND);
Toast.makeText(context, R.string.open_webapk_failed, Toast.LENGTH_SHORT).show();
}
} else if (id == R.id.request_desktop_site_id || id == R.id.request_desktop_site_check_id) {
final boolean reloadOnChange = !currentTab.isNativePage();
final boolean usingDesktopUserAgent = currentTab.getUseDesktopUserAgent();
currentTab.setUseDesktopUserAgent(!usingDesktopUserAgent, reloadOnChange);
RecordUserAction.record("MobileMenuRequestDesktopSite");
} else if (id == R.id.reader_mode_prefs_id) {
DomDistillerUIUtils.openSettings(currentTab.getWebContents());
} else {
return false;
}
return true;
}
/**
* Shows HelpAndFeedback and records the user action as well.
* @param url The URL of the tab the user is currently on.
* @param recordAction The user action to record.
* @param profile The current {@link Profile}.
*/
public void startHelpAndFeedback(String url, String recordAction, Profile profile) {
// Since reading back the compositor is asynchronous, we need to do the readback
// before starting the GoogleHelp.
String helpContextId = HelpAndFeedback.getHelpContextIdFromUrl(
this, url, getCurrentTabModel().isIncognito());
HelpAndFeedback.getInstance(this).show(this, helpContextId, profile, url);
RecordUserAction.record(recordAction);
}
/**
* Add a view to the set of views that obscure the content of all tabs for
* accessibility. As long as this set is nonempty, all tabs should be
* hidden from the accessibility tree.
*
* @param view The view that obscures the contents of all tabs.
*/
public void addViewObscuringAllTabs(View view) {
mViewsObscuringAllTabs.add(view);
Tab tab = getActivityTab();
if (tab != null) tab.updateAccessibilityVisibility();
}
/**
* Remove a view that previously obscured the content of all tabs.
*
* @param view The view that no longer obscures the contents of all tabs.
*/
public void removeViewObscuringAllTabs(View view) {
mViewsObscuringAllTabs.remove(view);
Tab tab = getActivityTab();
if (tab != null) tab.updateAccessibilityVisibility();
}
/**
* Returns whether or not any views obscure all tabs.
*/
public boolean isViewObscuringAllTabs() {
return !mViewsObscuringAllTabs.isEmpty();
}
private void markSessionResume() {
// Start new session for UMA.
if (mUmaSessionStats == null) {
mUmaSessionStats = new UmaSessionStats(this);
}
UmaSessionStats.updateMetricsServiceState();
mUmaSessionStats.startNewSession(getTabModelSelector());
}
/**
* Mark that the UMA session has ended.
*/
private void markSessionEnd() {
if (mUmaSessionStats == null) {
// If you hit this assert, please update crbug.com/172653 on how you got there.
assert false;
return;
}
// Record session metrics.
mUmaSessionStats.logMultiWindowStats(windowArea(), displayArea(),
TabWindowManager.getInstance().getNumberOfAssignedTabModelSelectors());
mUmaSessionStats.logAndEndSession();
}
private int windowArea() {
Window window = getWindow();
if (window != null) {
View view = window.getDecorView();
return view.getWidth() * view.getHeight();
}
return -1;
}
private int displayArea() {
if (getResources() != null && getResources().getDisplayMetrics() != null) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
return metrics.heightPixels * metrics.widthPixels;
}
return -1;
}
protected final void postDeferredStartupIfNeeded() {
if (!mNativeInitialized) {
// Native hasn't loaded yet. Queue it up for later.
mDeferredStartupQueued = true;
return;
}
mDeferredStartupQueued = false;
if (!mDeferredStartupPosted) {
mDeferredStartupPosted = true;
onDeferredStartup();
}
}
@Override
public void terminateIncognitoSession() {}
@Override
public void onTabSelectionHinted(int tabId) { }
@Override
public void onSceneChange(Layout layout) { }
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
// See enableHardwareAcceleration()
if (mSetWindowHWA) {
mSetWindowHWA = false;
getWindow().setWindowManager(
getWindow().getWindowManager(),
getWindow().getAttributes().token,
getComponentName().flattenToString(),
true /* hardwareAccelerated */);
}
}
private boolean shouldDisableHardwareAcceleration() {
// Low end devices should disable hardware acceleration for memory gains.
if (SysUtils.isLowEndDevice()) return true;
// Turning off hardware acceleration reduces crash rates. See http://crbug.com/651918
// GT-S7580 on JDQ39 accounts for 42% of crashes in libPowerStretch.so on dev and beta.
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR1
&& Build.MODEL.equals("GT-S7580")) {
return true;
}
// SM-N9005 on JSS15J accounts for 44% of crashes in libPowerStretch.so on stable channel.
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR2
&& Build.MODEL.equals("SM-N9005")) {
return true;
}
return false;
}
private void enableHardwareAcceleration() {
// HW acceleration is disabled in the manifest and may be re-enabled here.
if (!shouldDisableHardwareAcceleration()) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
// When HW acceleration is enabled manually for an activity, child windows (e.g.
// dialogs) don't inherit HW acceleration state. However, when HW acceleration is
// enabled in the manifest, child windows do inherit HW acceleration state. That
// looks like a bug, so I filed b/23036374
//
// In the meanwhile the workaround is to call
// window.setWindowManager(..., hardwareAccelerated=true)
// to let the window know that it's HW accelerated. However, since there is no way
// to know 'appToken' argument until window's view is attached to the window (!!),
// we have to do the workaround in onAttachedToWindow()
mSetWindowHWA = true;
}
}
/** @return the theme ID to use. */
public static int getThemeId() {
boolean useLowEndTheme =
SysUtils.isLowEndDevice() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
return (useLowEndTheme ? R.style.MainTheme_LowEnd : R.style.MainTheme);
}
/**
* Looks up the Chrome activity of the given web contents. This can be null. Should never be
* cached, because web contents can change activities, e.g., when user selects "Open in Chrome"
* menu item.
*
* @param webContents The web contents for which to lookup the Chrome activity.
* @return Possibly null Chrome activity that should never be cached.
*/
@Nullable public static ChromeActivity fromWebContents(@Nullable WebContents webContents) {
if (webContents == null) return null;
if (webContents.isDestroyed()) return null;
WindowAndroid window = webContents.getTopLevelNativeWindow();
if (window == null) return null;
Activity activity = window.getActivity().get();
if (activity == null) return null;
if (!(activity instanceof ChromeActivity)) return null;
return (ChromeActivity) activity;
}
private void setLowEndTheme() {
if (getThemeId() == R.style.MainTheme_LowEnd) setTheme(R.style.MainTheme_LowEnd);
}
/**
* Records UMA histograms for the current screen width. Should only be called when the activity
* is in Android N multi-window mode.
*/
protected void recordMultiWindowModeScreenWidth() {
if (!isTablet()) return;
RecordHistogram.recordBooleanHistogram(
"Android.MultiWindowMode.IsTabletScreenWidthBelow600",
mScreenWidthDp < DeviceFormFactor.MINIMUM_TABLET_WIDTH_DP);
if (mScreenWidthDp < DeviceFormFactor.MINIMUM_TABLET_WIDTH_DP) {
RecordHistogram.recordLinearCountHistogram("Android.MultiWindowMode.TabletScreenWidth",
mScreenWidthDp, 1, DeviceFormFactor.MINIMUM_TABLET_WIDTH_DP, 50);
}
}
@Override
public boolean onActivityResultWithNative(int requestCode, int resultCode, Intent intent) {
if (super.onActivityResultWithNative(requestCode, resultCode, intent)) return true;
if (VrShellDelegate.onActivityResultWithNative(requestCode, resultCode)) return true;
return false;
}
/**
* Called when VR mode is entered using this activity. 2D UI components that steal focus or
* draw over VR contents should be hidden in this call.
*/
public void onEnterVr() {}
/**
* Called when VR mode using this activity is exited. Any state set for VR should be restored
* in this call, including showing 2D UI that was hidden.
*/
public void onExitVr() {}
/**
* Whether this Activity supports moving a {@link Tab} to the {@link FullscreenActivity} when it
* enters fullscreen.
*/
public boolean supportsFullscreenActivity() {
return false;
}
/**
* @return Whether this Activity supports modern design.
*/
public boolean supportsModernDesign() {
return false;
}
/**
* @return Whether this Activity supports showing contextual suggestions in a bottom sheet.
*/
public boolean supportsContextualSuggestionsBottomSheet() {
return false;
}
/**
* @return the reference pool for this activity.
* @deprecated Use {@link ChromeApplication#getReferencePool} instead.
*/
// TODO(bauerb): Migrate clients to ChromeApplication#getReferencePool.
@Deprecated
public DiscardableReferencePool getReferencePool() {
return mReferencePool;
}
private void clearToolbarResourceCache() {
ControlContainer controlContainer = (ControlContainer) findViewById(R.id.control_container);
controlContainer.getToolbarResourceAdapter().dropCachedBitmap();
}
@Override
public void startActivity(Intent intent) {
startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, Bundle options) {
if (VrShellDelegate.canLaunch2DIntents() || VrIntentUtils.isVrIntent(intent)) {
super.startActivity(intent, options);
return;
}
VrShellDelegate.requestToExitVrAndRunOnSuccess(() -> {
if (!VrShellDelegate.canLaunch2DIntents()) {
throw new IllegalStateException("Still in VR after having exited VR.");
}
super.startActivity(intent, options);
});
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
@Override
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
if (VrShellDelegate.canLaunch2DIntents() || VrIntentUtils.isVrIntent(intent)) {
super.startActivityForResult(intent, requestCode, options);
return;
}
VrShellDelegate.requestToExitVrAndRunOnSuccess(() -> {
if (!VrShellDelegate.canLaunch2DIntents()) {
throw new IllegalStateException("Still in VR after having exited VR.");
}
super.startActivityForResult(intent, requestCode, options);
});
}
@Override
public boolean startActivityIfNeeded(Intent intent, int requestCode) {
return startActivityIfNeeded(intent, requestCode, null);
}
@Override
public boolean startActivityIfNeeded(Intent intent, int requestCode, Bundle options) {
// Avoid starting Activities when possible while in VR.
if (VrShellDelegate.isInVr() && !VrIntentUtils.isVrIntent(intent)) return false;
return super.startActivityIfNeeded(intent, requestCode, options);
}
/**
* If the density of the device changes while Chrome is in the background (not resumed), we
* won't have received an onConfigurationChanged yet for this new density. In this case, the
* density this Activity thinks it's in, and the actual display density will differ.
* @return The density this Activity thinks it's in (the density it was in last time it was in
* the resumed state).
*/
public float getLastActiveDensity() {
return mDensityDpi;
}
@VisibleForTesting
public ContextualSuggestionsCoordinator getContextualSuggestionsCoordinatorForTesting() {
return mContextualSuggestionsCoordinator;
}
}
| [
"[email protected]"
] | |
7974a9f2747823433b603d6e5e3fd5fa6df81da9 | ab91bc6461c219a189ea4b90e729e109fef64189 | /app/src/main/java/com/ps/myapplication/AboutUsActivity.java | 52eccd2105c925c2eeeaa1fe452c451593fd559a | [] | no_license | hsshamloo/NEAR_EAST_HOSPITAL_ANDROID_APP | 2af0adf2b87cc21447027eb6a4cc4b1f50804b3b | de4dad9e1bfb93693f4cd6846b9a547dac203858 | refs/heads/master | 2020-04-24T14:38:28.317348 | 2019-02-22T08:57:13 | 2019-02-22T08:57:13 | 172,023,755 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,583 | java | package com.ps.myapplication;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class AboutUsActivity extends ActionBarActivity {
private Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {"About Us", "Events"};
int Numboftabs = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aboutus_activity);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
@Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
@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_aboutus_activity, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| [
"[email protected]"
] | |
509f84bcdea6521d38131796541fc26947a82cc6 | 4ab11aac2a3b4e8d11902dfcfb967d5742d5ecb9 | /knowledge/demo/boot/empty/src/main/java/com/mg/empty/demo/alt/sort/SelectSort.java | a36e050e13da71540134193697893077fbd72e01 | [] | no_license | MT-GMZ/mg | af72d0d71ce1b6a8100cddc84af4bbaa14efb9e8 | 020a6796fafa494a6a875689da202835c680f04e | refs/heads/master | 2023-01-19T23:56:13.961811 | 2020-11-29T06:06:21 | 2020-11-29T06:06:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 875 | java | package com.mg.empty.demo.alt.sort;
import com.mg.empty.demo.alt.util.ShowUtill;
/**
* 算法思路,将最小的放在第一个
* 然后 获取出剩余的最小值 放在第二个位置
* 依次排序成功
*/
public class SelectSort {
public void selectSort(int[] array)
{
for(int i=0;i<array.length-1;i++)
{
int index =i;
for(int j=i+1;j<array.length;j++)
{
if(array[j]<array[index])
{
index = j;
}
}
int tmp = array[i];
array[i] = array[index];
array[index] = tmp;
}
ShowUtill.showArray(array);
}
public static void main(String[] args) {
SelectSort selectSort = new SelectSort();
selectSort.selectSort(new int[]{100,9,3,2,7,15,300,12});
}
}
| [
"[email protected]"
] | |
dcd91a6698983f3e9d16c37728d2a8744971e059 | 9c190f0377d1374d98ccf6866dbd8719aba0be06 | /app/src/main/java/me/lancer/pocket/util/FileTypeRefereeUtil.java | f7548759411fee2c701c140f341e8d512f9a128d | [] | no_license | 1anc3r/Pocket | e7bb03e98947d984ef225971fbfc8610f110766d | 68a49bc2ecabcbf536d7daa12145766aca05c586 | refs/heads/master | 2020-03-28T19:47:22.647719 | 2019-03-02T10:40:54 | 2019-03-02T10:40:54 | 94,602,624 | 11 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,448 | java | package me.lancer.pocket.util;
import java.io.File;
public class FileTypeRefereeUtil {
public static final String[][] FILE_TYPE_TABLE = {
{".3gp", "video/3gpp"},
{".apk", "application/vnd.android.package-archive"},
{".asf", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".class", "application/octet-stream"},
{".conf", "text/plain"},
{".cpp", "text/plain"},
{".doc", "application/msword"},
{".exe", "application/octet-stream"},
{".gif", "image/gif"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".htm", "text/html"},
{".html", "text/html"},
{".jar", "application/java-archive"},
{".java", "text/plain"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".log", "text/plain"},
{".m3u", "audio/x-mpegurl"},
{".m4a", "audio/mp4a-latm"},
{".m4b", "audio/mp4a-latm"},
{".m4p", "audio/mp4a-latm"},
{".m4u", "video/vnd.mpegurl"},
{".m4v", "video/x-m4v"},
{".mov", "video/quicktime"},
{".mp2", "audio/x-mpeg"},
{".mp3", "audio/x-mpeg"},
{".mp4", "video/mp4"},
{".mpc", "application/vnd.mpohun.certificate"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".mpg4", "video/mp4"},
{".mpga", "audio/mpeg"},
{".msg", "application/vnd.ms-outlook"},
{".ogg", "audio/ogg"},
{".pdf", "application/pdf"},
{".png", "image/png"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppt", "application/vnd.ms-powerpoint"},
{".prop", "text/plain"},
{".rar", "application/x-rar-compressed"},
{".rc", "text/plain"},
{".rmvb", "audio/x-pn-realaudio"},
{".rtf", "application/rtf"},
{".sh", "text/plain"},
{".tar", "application/x-tar"},
{".tgz", "application/x-compressed"},
{".txt", "text/plain"},
{".wav", "audio/x-wav"},
{".wma", "audio/x-ms-wma"},
{".wmv", "audio/x-ms-wmv"},
{".wps", "application/vnd.ms-works"},
{".xml", "text/plain"},
{".z", "application/x-compress"},
{".zip", "application/zip"},
{"", "*/*"}
};
File file;
public FileTypeRefereeUtil() {
}
public FileTypeRefereeUtil(File file) {
this.file = file;
}
public String getFileType(File file) {
String type = "*/*";
String name = file.getName();
int dot = name.lastIndexOf(".");
if (dot < 0) {
return type;
}
String suffix = name.substring(dot, name.length()).toLowerCase();
if (suffix == "") {
return type;
}
for (int i = 0; i < FILE_TYPE_TABLE.length; i++) {
if (suffix.equals(FILE_TYPE_TABLE[i][0])) {
type = FILE_TYPE_TABLE[i][1];
}
}
return type;
}
}
| [
"[email protected]"
] | |
c962914e0d6422d188c1a9fcbf5e14b9b98c173c | 65981f65e5d1dd676e4b5f48f3b81e1f55ed39ce | /konig-gae-generator/src/test/java/io/konig/gae/datastore/SimpleDaoNamerTest.java | 747f0722bb8c1fcd1a363ab3081103159313bad9 | [] | no_license | konigio/konig | dd49aa70aa63e6bdeb1161f26cf9fba8020e1bfb | 2c093aa94be40ee6a0fa533020f4ef14cecc6f1d | refs/heads/master | 2023-08-11T12:12:53.634492 | 2019-12-02T17:05:03 | 2019-12-02T17:05:03 | 48,807,429 | 4 | 3 | null | 2022-12-14T20:21:51 | 2015-12-30T15:42:21 | Java | UTF-8 | Java | false | false | 1,436 | java | package io.konig.gae.datastore;
/*
* #%L
* Konig GAE Generator
* %%
* Copyright (C) 2015 - 2017 Gregory McFall
* %%
* 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.
* #L%
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import io.konig.core.NamespaceManager;
import io.konig.core.impl.MemoryNamespaceManager;
import io.konig.core.vocab.Schema;
import io.konig.gae.datastore.SimpleDaoNamer;
public class SimpleDaoNamerTest {
@Test
public void test() {
NamespaceManager nsManager = new MemoryNamespaceManager();
nsManager.add("schema", Schema.NAMESPACE);
String basePackage = "com.example.gae.datastore";
SimpleDaoNamer namer = new SimpleDaoNamer(basePackage, nsManager);
String daoClass = namer.daoName(Schema.Person);
assertEquals("com.example.gae.datastore.schema.PersonDao", daoClass);
}
}
| [
"[email protected]"
] | |
6fe1db6734f488d42721a5392a5dd886ac161bce | aed3740053d41f15ad5cdf57084dd297b0766637 | /quickcoding_pedometer/src/androidTest/java/com/example/quickcoding_pedometer/ExampleInstrumentedTest.java | ad8715890523c5743b9508f48227daa5c48ea87e | [] | no_license | guswo9496ver2/Android_Mobileprogramming | bd3ecbaa96456026459ef531d0c429749fb01c43 | 3454d4b1bd3ab677e9c1ac589fbbca7f75f338fa | refs/heads/master | 2021-01-12T09:57:57.848721 | 2016-12-13T01:31:16 | 2016-12-13T01:31:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 770 | java | package com.example.quickcoding_pedometer;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.quickcoding_pedometer", appContext.getPackageName());
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.