blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2 values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82 values | src_encoding stringclasses 28 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 5.41M | extension stringclasses 11 values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1e174fa8ea2c6ccd784dd46d79495df8a8135cf9 | ccb0da21fd11d0afdbd4190951e20a018c179909 | /src/main/java/com/personal/eternaljourney/utils/PageUtils.java | ebb220ff6a4d336003fe94a662d075d0b1389af4 | [] | no_license | CharmZJH/eternal-journey | c86c9a3f5cff9262bafc256f46b35654421902df | 1f86cca52cf36284f049f714b5eb554bf81f8ce2 | refs/heads/master | 2023-06-02T13:03:30.375064 | 2021-06-25T09:08:02 | 2021-06-25T09:08:02 | 377,775,540 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 955 | java | package com.personal.eternaljourney.utils;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class PageUtils implements Serializable {
private static final long serialVersionUID = -1202716581589799959L;
//总记录数
private int totalCount;
//每页记录数
private int pageSize;
//总页数
private int totalPage;
//当前页数
private int currPage;
//列表数据
private List<?> list;
/**
* 分页
* @param list 列表数据
* @param totalCount 总记录数
* @param pageSize 每页记录数
* @param currPage 当前页数
*/
public PageUtils(List<?> list, int totalCount, int pageSize, int currPage) {
this.list = list;
this.totalCount = totalCount;
this.pageSize = pageSize;
this.currPage = currPage;
this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
}
}
| [
"1925565912@qq.com"
] | 1925565912@qq.com |
e5ddc988803445b5a2e762aa8e4a2472e3c0d32b | c65008e3fb144d009c3c3702dfc8f4c26460a762 | /restful-web-services-github/src/main/java/com/rest/webservices/SwaggerConfig.java | 4d5e3db8c171134ff6338966a29bd794cb8a5b9c | [] | no_license | sameervogeti/currency-converter-microservices | b62749deaeea288438cdc39002d547524789524c | 8b62e0917cc116ebb85d7f347f365ac7f9cfab3f | refs/heads/master | 2020-08-07T21:27:12.136716 | 2019-10-17T15:23:23 | 2019-10-17T15:23:23 | 213,591,168 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 486 | java | package com.rest.webservices;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2);
}
}
| [
"sameervogeti@gmail.com"
] | sameervogeti@gmail.com |
0d9944cad3c8396fd9472e44e06df1c892bf168d | 4fe695b4a62d5d71e57941421b4effd25cbc3f21 | /chapter_2/src/chapter_2/CircleArea.java | 2b7dcafef3b4297e348309c8a18ad93a5f5bbb4b | [] | no_license | EunjiShin/java_study | 99926b8e5e82922f852a8915207741426047ec77 | e0811c1a40a7557166ac04ad5d6f209d2b4ec6e6 | refs/heads/master | 2020-07-30T14:55:05.246210 | 2019-11-17T09:35:48 | 2019-11-17T09:35:48 | 210,269,253 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 472 | java | package chapter_2;
public class CircleArea {
// 원의 면적을 구하는 프로그램
public static void main(String[] args) {
final double PI = 3.14; // 원주율을 상수로 선언한다.
double radius = 10.0; // 원의 반지름을 선언한다.
double circleArea = radius*radius*PI; // 원의 면적 공식을 이용해 면적을 구한다.
System.out.println("원의 면적 = " + circleArea);
// 구한 원의 면적을 출력한다.
}
}
| [
"eunji980310@gmail.com"
] | eunji980310@gmail.com |
83cf4d18b48cfde46c15313459a077661c7ebb42 | 2d43628c269dd1ffe67be0cf5402c98334c8055d | /aigo-android/app/src/main/java/com/cloudpick/yunna/utils/message/MessageCenter.java | 82f57467b1ee446b1908082b351fc2343c5bd32a | [] | no_license | Yunna-AIGO/aigo-ui | 81f27da852b20c3b94c248fedfb370e20c24e9fa | e9c662f2e5d75aee9178067ad7f61e372239b3e2 | refs/heads/master | 2023-02-08T16:51:45.433945 | 2021-04-19T03:04:22 | 2021-04-19T03:04:22 | 98,144,937 | 0 | 0 | null | 2023-01-25T08:18:00 | 2017-07-24T03:19:58 | Java | UTF-8 | Java | false | false | 8,332 | java | package com.cloudpick.yunna.utils.message;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import com.cloudpick.yunna.BuildConfig;
import com.cloudpick.yunna.model.User;
import com.cloudpick.yunna.ui.MainActivity;
import com.cloudpick.yunna.ui.WelcomeActivity;
import com.cloudpick.yunna.utils.AppData;
import com.cloudpick.yunna.utils.Constants;
import com.cloudpick.yunna.utils.NotificationHelper;
import com.cloudpick.yunna.utils.enums.AppActionTypes;
import com.cloudpick.yunna.utils.http.Callback;
import com.cloudpick.yunna.utils.http.Requests;
import com.cloudpick.yunna.utils.http.Response;
import com.cloudpick.yunna.utils.message.push.JPush;
import com.cloudpick.yunna.utils.message.push.PushPlugins;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
/**
* Created by maxwell on 18-1-25.
*/
public class MessageCenter {
private final static String TAG = "CloudPick";
private volatile static MessageCenter instance = null;
public static MessageCenter getInstance(){
if(instance == null){
synchronized(MessageCenter.class){
if(instance == null){
instance = new MessageCenter();
}
}
}
return instance;
}
private Context context;
private PushPlugins pushPlugins = null;
private boolean registed = false;
private MessageCenter(){
}
public void init(Context ctx){
this.context = ctx;
registed = getSubscriberIdRegistStatus();
//初始化推送
pushPlugins = getPushPlugins();
if(pushPlugins != null){
pushPlugins.init();
Log.i(TAG, pushPlugins.toString());
}
}
private PushPlugins getPushPlugins(){
try{
CommonPushPluginsTypes pushType = CommonPushPluginsTypes.valueOf(BuildConfig.PUSH_PLUGINS);
if(pushType == null){
pushType = CommonPushPluginsTypes.AUTO;
}
if(pushType == CommonPushPluginsTypes.AUTO){
//根据设备获取推送插件
return getPushPluginsByDevice();
}else{
return getPushPluginsByName(pushType.getName());
}
}catch (Exception ex){
ex.printStackTrace();
return null;
}
}
private PushPlugins getPushPluginsByDevice(){
//TODO: 根据不同的设备实例化不同的推送插件类,如华为的实例化华为的插件。
//如果设备未存在对应的推送,则根据CommonPushPluginsTypes中的优先级创建推送实例
//暂时统一使用极光推送,
return new JPush(context);
}
private PushPlugins getPushPluginsByName(String pushName){
try{
//根据类名获取Class对象
Class clazz = Class.forName("com.cloudpick.yunna.utils.message.push." + pushName);
Class[] parameterTypes = {android.content.Context.class};
Constructor ctor = clazz.getConstructor(parameterTypes);
Object[] parameters = {context};
return (PushPlugins)ctor.newInstance(parameters);
}catch (Exception ex){
ex.printStackTrace();
return null;
}
}
/**
* 从本地获取向服务器注册SubscriberId的结果
* @return
*/
private boolean getSubscriberIdRegistStatus(){
return AppData.getAppData().getAsBoolean(Constants.KEY_SUBSCRIBER_ID_REGIST_STATUS);
}
private void setSubscriberIdRegistStatus(boolean value){
registed = value;
AppData.getAppData().put(Constants.KEY_SUBSCRIBER_ID_REGIST_STATUS, registed);
}
/**
* 向服务器注册subscriberId
*/
public void registSubscriberId(){
if(registed){
Log.d(TAG, "subscriber id already registed!");
return;
}
try{
String userId = User.getUser().getUserId();
String subscriberId = pushPlugins != null? pushPlugins.SubscriberId():"";
if(!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(subscriberId)){
Log.d(TAG, "regist subscriber id " + subscriberId + " to server");
Map<String, String> data = new HashMap<>();
data.put(Constants.KEY_USER_ID, userId);
data.put(Constants.KEY_SUBSCRIBER_ID, subscriberId);
data.put(Constants.KEY_PUSH_TYPE, pushPlugins.getPushPluginsName().toLowerCase());
Requests.postAsync(Constants.URL_SKD_INFO, data,
new Callback<Response<Object>>(){
@Override
public void error(Exception e){
e.printStackTrace();
}
@Override
public void ok(Response<Object> r){
setSubscriberIdRegistStatus(true);
}
});
}
}catch (Exception ex){
ex.printStackTrace();
}
}
public void unregistSubscriberId(){
setSubscriberIdRegistStatus(false);
if(pushPlugins != null && !TextUtils.isEmpty(pushPlugins.SubscriberId())){
Log.d(TAG, "unregist subscriber id from server");
Map<String, String> data = new HashMap<>();
data.put(Constants.KEY_MOBILE, User.getUser().getMobile());
data.put(Constants.KEY_SUBSCRIBER_ID, pushPlugins.SubscriberId());
data.put(Constants.KEY_PUSH_TYPE, pushPlugins.getPushPluginsName().toLowerCase());
data.put(Constants.KEY_TOKEN, User.getUser().getToken());
Requests.postAsync(Constants.URL_LOGOUT, data,
new Callback<Response<Object>>(){
@Override
public void error(Exception e){
e.printStackTrace();
}
@Override
public void ok(Response<Object> r){ }
});
}
}
//推送相关
/**
* 点击打开通知
* @param action
* @param isAppAlive
*/
public void handleNotificationOpened(String action, boolean isAppAlive){
try{
AppAction appAction = new AppAction(AppActionTypes.valueOf(action.toUpperCase()));
Intent intent = null;
if(isAppAlive){
//MainActivity还存在,直接拉起跳转
Log.d(TAG, "the app process is alive");
intent = MainActivity.newIntent(context, false, appAction);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
}else{
//MainActivity不存在,拉起WelcomeActivity后再跳转
Log.d(TAG, "the app process is dead");
intent = WelcomeActivity.newIntent(context, appAction);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// intent.addCategory(Intent.CATEGORY_LAUNCHER);
}
context.startActivity(intent);
}catch (Exception ex){
ex.printStackTrace();
}
}
public void handleCustomMessage(String title, String content, String action){
NotificationHelper.getInstance().notify(title, content);
}
/**
* 通用推送插件类型枚举
*/
public enum CommonPushPluginsTypes{
JPUSH("JPUSH", "JPush", 1),//极光推送
MOCK_PUSH("MOCK_PUSH", "MockPush", 2),//Mock推送插件
AUTO("AUTO", "Auto", 0);//自动选择推送插件
private final String code;
private final String name;
private final int priority;
CommonPushPluginsTypes(String code, String name, int priority){
this.code = code;
this.name = name;
this.priority = priority;
}
public String getCode() {
return code;
}
public int getPriority() {
return priority;
}
public String getName(){
return name;
}
}
}
| [
"maxwell@localhost.localdomain"
] | maxwell@localhost.localdomain |
e01f0e8602f4bb9753216a3663cf2ad4c83ae3fd | b2cadece3ab85d41e90a06e5b39af2cbe5c01df5 | /subtraction/src/souji/sub.java | 9b22a80504f30e672165a788d3fbdda5edaa07c4 | [] | no_license | soujanyasab/gittestsouji | 450b5dd3d26955ba8bfa32e44b8fadb3f7dc7ab7 | 5a8239e788e937b6816d18698d31a58e08a89ea0 | refs/heads/master | 2021-05-14T06:28:45.006386 | 2019-01-28T07:30:19 | 2019-01-28T07:30:19 | 116,241,590 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 461 | java | package souji;
public class sub {
int arg1=3;
int arg2=2;
public sub(int a, int b)
{
System.out.println("inside constructor");
this.arg1=a;
this.arg2=b;
}
public int sub()
{
System.out.println("sub method");
return arg1+arg2;
//aa
// return arg1*arg2;
}
public static void main(String[] args){
sub obj=new sub(100,50);
System.out.println("output of subtraction" +obj.sub());
}
//abcdefgh
//bb
//cc
}
| [
"670317@PC176398.cts.com"
] | 670317@PC176398.cts.com |
1ae706b32194c36d75c2f05ee278f052e56e5b29 | 7106fc7eb07b2fe7d175db145f7345d73b0a9659 | /tawassol-repository/src/main/java/com/ayouris/tawassol/common/repository/impl/CommonRepositoryImpl.java | addb05f02d9d95d624fa67516f19abec92ccb075 | [] | no_license | mohcine-wannas/test | a6ef0ac763b8a344695cff8e6c01b4f3d064b1b6 | 3403a37df11b824b749d13d9e28e653bb9bfb88d | refs/heads/master | 2020-04-01T13:26:49.560211 | 2018-02-22T09:09:00 | 2018-02-22T09:09:00 | 153,252,834 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,172 | java | package com.ayouris.tawassol.common.repository.impl;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import org.hibernate.annotations.QueryHints;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.QueryDslJpaRepository;
import com.ayouris.tawassol.common.model.entity.generic.BaseEntity;
import com.ayouris.tawassol.common.model.entity.lang.CountryLang;
import com.ayouris.tawassol.common.model.entity.lang.Lang;
import com.ayouris.tawassol.common.model.entity.lang.QLang;
import com.ayouris.tawassol.common.model.entity.lang.RefDataLang;
import com.ayouris.tawassol.common.model.entity.ref.CountryRef;
import com.ayouris.tawassol.common.model.entity.ref.RefData;
import com.ayouris.tawassol.common.repository.CommonRepository;
import com.ayouris.tawassol.common.repository.entitygraph.EntityGraphGenerator;
import com.ayouris.tawassol.common.util.QueryUtils;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.EntityPathBase;
import com.querydsl.core.types.dsl.PathBuilder;
public class CommonRepositoryImpl<T extends BaseEntity> extends QueryDslJpaRepository<T, Long>
implements CommonRepository<T> {
private final EntityManager entityManager;
private final JpaEntityInformation<T, Long> entityInformation;
private final JPAQueryFactory queryFactory;
private final QLang lang = QLang.lang;
public CommonRepositoryImpl(JpaEntityInformation<T, Long> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityManager = entityManager;
this.entityInformation = entityInformation;
this.queryFactory = new JPAQueryFactory(entityManager);
}
@Override
public Long getSequenceNextVal(String sequenceName) {
return ((BigInteger) entityManager.createNativeQuery(sequenceName + ".nextval").getSingleResult()).longValue();
}
@Override
public <O extends Comparable<O>, P extends BaseEntity> Iterable<T> findRefData(Class<T> entityRef,
Class<P> entityLang, Predicate predicate, Integer pageNumber, Integer pageSize, String orderByColumn) {
PathBuilder<T> entityRefPath = new PathBuilder<T>(entityRef, "entityRef");
PathBuilder<P> entityLangPath = new PathBuilder<P>(entityLang, "entityLang");
JPAQuery<T> query = queryFactory.selectFrom(entityRefPath);
query.fetchJoin()
.leftJoin(entityRefPath.getSet(RefData.COLUMNS.LOCALIZED_LABEL.getName(), entityLang), entityLangPath)
.fetchJoin()
.leftJoin(entityLangPath.getSet(RefDataLang.COLUMNS.LANG.getName(), Lang.class), (Path) lang).fetch();
query.where(predicate);
QueryUtils.applyPagination(query, pageNumber, pageSize);
if (orderByColumn != null) {
query.orderBy(new OrderSpecifier<>(Order.ASC, entityRefPath.getString(orderByColumn)));
}
return query.fetch();
}
@Override
public <O extends Comparable<O>, P extends BaseEntity> Iterable<T> findRefDataWithCountry(Class<T> entityRef,
Class<P> entityLang, Predicate predicate, Integer pageNumber, Integer pageSize, String orderByColumn,
String userLang) {
PathBuilder<T> entityRefPath = new PathBuilder<T>(entityRef, "entityRef");
PathBuilder<P> entityLangPath = new PathBuilder<P>(entityLang, "entityLang");
PathBuilder<CountryRef> countryRef = new PathBuilder<>(CountryRef.class, "countryRef");
PathBuilder<CountryLang> countryLang = new PathBuilder<>(CountryLang.class, "countryLang");
QLang langCountry = new QLang("langCountry");
JPAQuery<T> query = queryFactory.selectFrom(entityRefPath);
query.fetchJoin()
.leftJoin(entityRefPath.getSet(RefData.COLUMNS.LOCALIZED_LABEL.getName(), entityLang), entityLangPath)
.fetchJoin()
.leftJoin(entityLangPath.getSet(RefDataLang.COLUMNS.LANG.getName(), Lang.class), (Path) lang)
.fetchJoin().leftJoin(entityRefPath.get("country", CountryRef.class), countryRef).fetchJoin()
.leftJoin(countryRef.get(RefData.COLUMNS.LOCALIZED_LABEL.getName(), CountryLang.class), countryLang)
.fetchJoin()
.leftJoin(countryLang.getSet(RefDataLang.COLUMNS.LANG.getName(), Lang.class), (Path) langCountry)
.fetch();
BooleanExpression predicateAll = langCountry.code.eq(userLang).and(predicate);
query.where(predicateAll);
QueryUtils.applyPagination(query, pageNumber, pageSize);
if (orderByColumn != null) {
query.orderBy(new OrderSpecifier<>(Order.ASC, entityRefPath.getString(orderByColumn)));
}
return query.fetch();
}
@Override
public Iterable<T> searchByEntityGraph(Predicate predicate, EntityPathBase<T> qObject, String... properties) {
return searchOrderedByEntityGraph(predicate, qObject, properties != null ? Arrays.asList(properties) : null,
null, null, null);
}
@Override
public T searchOneByEntityGraph(Predicate pred, EntityPathBase<T> qObject, String... attributeEntities) {
Iterable<T> it = searchByEntityGraph(pred, qObject, attributeEntities);
if (it != null) {
Iterator<T> ite = it.iterator();
if (ite != null && ite.hasNext()) {
return ite.next();
}
}
return null;
}
@Override
public <O extends Comparable<O>> Iterable<T> searchOrderedByEntityGraph(Predicate predicate,
EntityPathBase<T> qObject, List<String> properties, Integer pageNumber, Integer pageSize,
OrderSpecifier<O> orders) {
JPAQuery<T> query = new JPAQuery<T>(entityManager);
if (properties != null && !properties.isEmpty()) {
query = query.setHint(QueryHints.FETCHGRAPH, new EntityGraphGenerator().graphWithRequests(entityManager,
qObject.getType(), properties.toArray(new String[properties.size()])));
}
query = query.from(qObject);
if (predicate != null) {
query = query.where(predicate);
}
if (orders != null) {
query = query.orderBy(orders);
}
QueryUtils.applyPagination(query, pageNumber, pageSize);
return query.fetch();
}
}
| [
"mohcine.wannas@gmail.com"
] | mohcine.wannas@gmail.com |
fd02f9df24f588f4334770d33f3f58c050d378ea | bdefb1f7722cbbd571d3cdf466671f73d4b43680 | /src/main/java/pcehr_override/org/w3/Reference.java | 381aa52ec48d631662d43b3879e7e3409f681d05 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | AuDigitalHealth/pcehr-compiled-wsdl-java | 07975bcdba00af2ddd9933050a1da08a71c712e1 | 098fa9e9b0859e2785dd4ae81a60094898ecf053 | refs/heads/master | 2023-03-08T21:31:59.626392 | 2021-02-23T01:58:03 | 2021-02-23T01:58:03 | 338,191,318 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,038 | java |
package pcehr_override.org.w3;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for ReferenceType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ReferenceType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://www.w3.org/2000/09/xmldsig#}Transforms" minOccurs="0"/>
* <element ref="{http://www.w3.org/2000/09/xmldsig#}DigestMethod"/>
* <element ref="{http://www.w3.org/2000/09/xmldsig#}DigestValue"/>
* </sequence>
* <attribute name="Id" type="{http://www.w3.org/2001/XMLSchema}ID" />
* <attribute name="URI" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* <attribute name="Type" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ReferenceType", propOrder = {
"transforms",
"digestMethod",
"digestValue"
})
@XmlRootElement(name = "Reference")
public class Reference {
@XmlElement(name = "Transforms")
protected Transforms transforms;
@XmlElement(name = "DigestMethod", required = true)
protected DigestMethod digestMethod;
@XmlElement(name = "DigestValue", required = true)
protected byte[] digestValue;
@XmlAttribute(name = "Id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
@XmlAttribute(name = "URI")
@XmlSchemaType(name = "anyURI")
protected String uri;
@XmlAttribute(name = "Type")
@XmlSchemaType(name = "anyURI")
protected String type;
/**
* Gets the value of the transforms property.
*
* @return
* possible object is
* {@link Transforms }
*
*/
public Transforms getTransforms() {
return transforms;
}
/**
* Sets the value of the transforms property.
*
* @param value
* allowed object is
* {@link Transforms }
*
*/
public void setTransforms(Transforms value) {
this.transforms = value;
}
/**
* Gets the value of the digestMethod property.
*
* @return
* possible object is
* {@link DigestMethod }
*
*/
public DigestMethod getDigestMethod() {
return digestMethod;
}
/**
* Sets the value of the digestMethod property.
*
* @param value
* allowed object is
* {@link DigestMethod }
*
*/
public void setDigestMethod(DigestMethod value) {
this.digestMethod = value;
}
/**
* Gets the value of the digestValue property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getDigestValue() {
return digestValue;
}
/**
* Sets the value of the digestValue property.
*
* @param value
* allowed object is
* byte[]
*/
public void setDigestValue(byte[] value) {
this.digestValue = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the uri property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getURI() {
return uri;
}
/**
* Sets the value of the uri property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setURI(String value) {
this.uri = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
}
| [
"peter.ball@digitalhealth.gov.au"
] | peter.ball@digitalhealth.gov.au |
e4fb3f974fe3fa3e9de61694b5eda5f90a635a06 | 0c212ca7fc9394c7f026d235ec1cb27d7a53f6e2 | /src/main/java/com/devroods/cestao_backend/services/GetNFCeService.java | 7d6d67c3068ecc859a7c9724337c495f0131cfcb | [] | no_license | rodolfomedeiros/cestao_backend | 8304eb298d1c20421646eb848b083be3fe3f00c8 | 06381370b1ba274aaa42c2ce0ef7486014033cd6 | refs/heads/master | 2023-03-02T20:33:22.830824 | 2021-02-13T17:47:26 | 2021-02-13T17:47:26 | 249,535,916 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,481 | java | package com.devroods.cestao_backend.services;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Optional;
import com.devroods.cestao_backend.exceptions.NfceServerNotFoundException;
import com.devroods.cestao_backend.models.forms.NfceDTO;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class GetNFCeService {
private final RestTemplate restTemplate;
private final String urlNotaFiscal = "http://nfce-service:3000/nota?nfceKey=";
public GetNFCeService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
public Optional<NfceDTO> getNfceForm(String nfceKey) throws NfceServerNotFoundException {
try {
return Optional.ofNullable(restTemplate.getForObject(urlNotaFiscal + nfceKey, NfceDTO.class));
} catch (Exception e) {
throw new NfceServerNotFoundException();
}
}
public Optional<NfceDTO> getDefaultNfceForm() {
try {
JsonReader reader = new JsonReader(new FileReader("./src/main/resources/defaultNfceForm.json"));
NfceDTO nfceDTO = new Gson().fromJson(reader, NfceDTO.class);
return Optional.ofNullable(nfceDTO);
} catch (FileNotFoundException e) {
e.printStackTrace();
return Optional.ofNullable(null);
}
}
} | [
"sd.rodolfo.medeiros@gmail.com"
] | sd.rodolfo.medeiros@gmail.com |
8e32d647a5dad876f2ca1813337c25f66509bf2b | 7b97b7f8b14cc752deedde00aeeea26bfaa66da9 | /src/main/java/uk/gov/digital/ho/hocs/info/domain/entity/EntityRepository.java | 185f5109091db727827c6e70a5dde0d2fe8383d1 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | nickmcmahon01/hocs-info-service | 80039d050e0d891c52ac10e1aa0bde4cf52cb862 | 70aed25f306d550c1f655dd0ceb2a784e3b3ac3a | refs/heads/master | 2020-06-15T07:13:44.400542 | 2019-06-27T22:43:44 | 2019-06-27T22:43:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,095 | java | package uk.gov.digital.ho.hocs.info.domain.entity;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Set;
@Repository
public interface EntityRepository extends CrudRepository<Entity, Long> {
@Query(value = "select e3.* from entity_list el\n" +
" join entity e on e.entity_list_uuid = el.uuid\n" +
" join entity_relation er on e.uuid = er.parent_entity_uuid\n" +
" join entity e2 on e2.uuid = er.entity_uuid\n" +
" join entity_list el2 on e2.entity_list_uuid = el2.uuid\n" +
" join entity_relation er2 on e2.uuid = er2.parent_entity_uuid\n" +
" join entity e3 on e3.uuid = er2.entity_uuid\n" +
"where el.simple_name = ?1 and e.simple_name = ?2 and el2.simple_name = ?3", nativeQuery = true)
Set<Entity> findBySimpleName(String owner, String ownerType, String list);
} | [
"nick.mcmahon@digital.homeoffice.gov.uk"
] | nick.mcmahon@digital.homeoffice.gov.uk |
baf5fb0ae58ee32b6945270f43be61cfb4e08722 | d613b1235c9b3e2cbf9afb8cad2e6f77e5dd177b | /src/main/java/priv/tangxin/algorithm/problem/towSums.java | c89e931f2b91dd7012d68c13161efc7f56c018bd | [] | no_license | D2mer/algorithm | 912eac60d2b0868eb4a57c0d0ecd5c67d9ab4b09 | 6b9aa9d704e1999d957f03f705c24e41661c26fe | refs/heads/master | 2023-05-08T14:38:22.665631 | 2021-06-01T09:55:58 | 2021-06-01T09:55:58 | 372,665,664 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 801 | java | package priv.tangxin.algorithm.problem;
import java.util.Arrays;
/**
* @Desc
* @Author tangxin
* @Date 2021/5/26
*/
public class towSums {
public static int[] twoSum(int[] nums, int target) {
for(int i = 0;i<nums.length-1;i++){
Arrays.binarySearch(nums,target - nums[i]);
for(int k = i+1 ;k<nums.length; k++ ){
if((nums[i]+nums[k]) == target) return new int[]{i,k};
}
}
return null;
}
public static void main(String[] args) {
int[] nums = {1,2,5,7,10,15,17};
int target = 10;
int[] result =twoSum(nums,target);
if(result!=null) {
System.out.println(result[0]+","+result[1]);
} else {
System.out.println("not find");
}
}
}
| [
"tangxin@cdzgph.com"
] | tangxin@cdzgph.com |
145bcb4075440fac617daf215a1f61ac8d2eb9a8 | f4ab451d4430979491f863b55dc11a2d38569666 | /tablereservation/src/main/java/com/galaxy/springboot/support/PageInfo.java | 1503639d6132ec99e5d432649e6dacfdb3c5301a | [] | no_license | www-jin/- | e99d30b3f9542cab05fb9059fbde7011145d5b3d | c8980d0e150253ceb4ea0489fd204ce161b6228b | refs/heads/master | 2020-11-26T06:53:52.028210 | 2019-12-25T01:45:39 | 2019-12-25T01:45:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,976 | java | package com.galaxy.springboot.support;
import java.util.List;
/**
* �����ҳ����ʹ�õ�����
* @author Lenovo
*�Զ�������ɷ�ҳ����
����ҳ��Ҫ��Щ������
1 ������
2 ÿҳ������
3 ��ǰ��ҳ��
4 ��ҳ��
ҳ����ʾ
5 ��ҳ��ѯ�ݵ�ǰ�˽�����ص�չʾ List<T>
��ѯ����
6 ������� private SalChance salChance; private T entity;
*/
public class PageInfo<T> {
//������
private int totalCount;
//ҳ��������ʼֵ����ָ������5
private int pageSize = 5;
//��ǰ��ҳ������ʼֵ�� 1
private int pageNum = 1;
//��ҳ��
private int totalPage;
//���͵�ʹ�ã���ʵ������ʱ��ָ�����ͣ�
private List<T> lists;
//������ԣ���ѯ����
private T entity;
//��ʼ����
private int start;
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<T> getLists() {
return lists;
}
public void setLists(List<T> lists) {
this.lists = lists;
}
public T getEntity() {
return entity;
}
public void setEntity(T entity) {
this.entity = entity;
}
public int getStart() {
//����ָ����ʼ������
this.start = (pageNum-1)*pageSize;
return start;
}
public void setStart(int start) {
this.start = start;
}
}
| [
"1106315424@qq.com"
] | 1106315424@qq.com |
c4302bcd20733dbdfc49308437635108daca0d0b | 94c055cd58750549275d32b3ee0d2fd64090966d | /other_module/src/androidTest/java/com/hai/jackie/other_module/ExampleInstrumentedTest.java | 164883eaa0aee0206ecd050a248cd7e7943136ea | [] | no_license | ljzyljc/HaiRoute | 419c81987caa48c8e54ba87845ad1dea18dab611 | 80c42fdbae3e2e1b948e0af8e67de5902d215524 | refs/heads/master | 2020-05-24T07:25:48.338471 | 2019-05-17T06:30:47 | 2019-05-17T06:30:47 | 187,159,618 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 743 | java | package com.hai.jackie.other_module;
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.*;
/**
* 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 ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.hai.jackie.other_module.test", appContext.getPackageName());
}
}
| [
"feifei5292190@163.com"
] | feifei5292190@163.com |
4f24838e8f7290ba0536d328520c0dd876fda6ff | d9d04a95675865c5cae30b002aa91afac87c258a | /src/main/java/com/kogni/pontointeligente/api/security/JwtAuthenticationEntryPoint.java | 628f8012a65233690ba5a892f6eadff254abb950 | [
"MIT"
] | permissive | leosilvarj/ponto-inteligente-api | 4ab8490c20b73c8835dbc11da57ca97004c925ac | c85b499aad73d751ffaa584cf3eb1987c9a555c8 | refs/heads/master | 2020-03-14T15:37:05.044088 | 2018-05-04T04:58:22 | 2018-05-04T04:58:22 | 131,680,148 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 758 | java | package com.kogni.pontointeligente.api.security;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Acesso negado. Você deve estar autenticado no sistema para acessar a URL solicitada.");
}
}
| [
"leosilvarj@gmail.com"
] | leosilvarj@gmail.com |
5aa402b381c99384e23cadc081d4f8522a405bb9 | b0820d34ab17dae22cee455d3b37ac00e7a798bc | /solr/solrj/src/java/org/apache/solr/client/solrj/request/beans/ModifyCollectionPayload.java | e2c744e78d5a994971a72e7bb0266cfca39c041d | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown",
"LGPL-2.0-or-later",
"Classpath-exception-2.0",
"CDDL-1.0",
"GPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-unicode",
"CC-BY-SA-3.0",
"CDDL-1.1",
"LicenseRef-scancode-proprietary-license",
"NAIST-2003",
"BSD-3-Clause",
"LicenseRef-... | permissive | makosten/solr | 7265b7d4e28092f3b58e6bffe8b6099b8d994a4d | b532f4dc604d01dbddd8e45ee5cc16d3e3afe0b3 | refs/heads/main | 2023-08-28T20:44:47.471847 | 2021-11-04T13:58:59 | 2021-11-04T19:24:54 | 397,412,744 | 0 | 0 | Apache-2.0 | 2021-08-17T23:07:07 | 2021-08-17T23:07:06 | null | UTF-8 | Java | false | false | 1,291 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.client.solrj.request.beans;
import org.apache.solr.common.annotation.JsonProperty;
import org.apache.solr.common.util.ReflectMapWriter;
import java.util.Map;
public class ModifyCollectionPayload implements ReflectMapWriter {
@JsonProperty
public Integer replicationFactor;
@JsonProperty
public Boolean readOnly;
@JsonProperty
public String config;
@JsonProperty
public Map<String, Object> properties;
@JsonProperty
public String async;
}
| [
"noreply@github.com"
] | noreply@github.com |
292f608f187121c821cff477916d7c2089c1d083 | 37dd44461f3ad8213cecad3898c877b95d6c917b | /imagepickerlib/src/main/java/com/jinu/imagepickerlib/PhotoPagerActivity.java | c8cd6f2bfcc1a040fb866675881ee7f231e787a8 | [] | no_license | j1nu/imagepicker | 5e98da724c2ed137f7252f6bd27ff50158eeec01 | 887bc5820bbb5cc7009d874e53bd1b4bf912bf91 | refs/heads/master | 2022-12-07T11:48:32.059581 | 2020-08-22T15:30:05 | 2020-08-22T15:30:05 | 274,215,680 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,544 | java | package com.jinu.imagepickerlib;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;
import com.jinu.imagepickerlib.fragment.ImagePagerFragment;
import java.io.File;
import java.util.List;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
public class PhotoPagerActivity extends AppCompatActivity {
private ImagePagerFragment pagerFragment;
private static final String FOLDER_NAME = "y_photopicker";
public final static String EXTRA_CURRENT_ITEM = "current_item";
public final static String EXTRA_PHOTOS = "photos";
private ActionBar actionBar;
private TextView tv_count;
private ImageView iv_back_btn;
private int mSaveEditPostion = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.util_activity_photo_pager);
int currentItem = getIntent().getIntExtra(EXTRA_CURRENT_ITEM, 0);
List<String> paths = getIntent().getStringArrayListExtra(EXTRA_PHOTOS);
tv_count = (TextView) findViewById(R.id.tv_count);
iv_back_btn = (ImageView) findViewById(R.id.iv_back_btn);
iv_back_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
pagerFragment = (ImagePagerFragment) getSupportFragmentManager().findFragmentById(R.id.photoPagerFragment);
pagerFragment.setPhotos(paths, currentItem);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
updateActionBarTitle();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
actionBar.setElevation(25);
}
pagerFragment.getViewPager().addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
updateActionBarTitle();
}
@Override
public void onPageSelected(int i) {
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_preview, menu);
return true;
}
@Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS, pagerFragment.getPaths());
setResult(RESULT_OK, intent);
finish();
super.onBackPressed();
}
// @Override
// public void onActivityResult(int requestCode, int resultCode, Intent data) {
//
//// if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
//// final Uri resultUri = UCrop.getOutput(data);
////
//// Toast.makeText(PhotoPagerActivity.this , "Saved Image ["+ resultUri + "]" , Toast.LENGTH_LONG).show();
////
//// } else if (resultCode == UCrop.RESULT_ERROR) {
//// final Throwable cropError = UCrop.getError(data);
//// Toast.makeText(PhotoPagerActivity.this , "[Error]"+cropError , Toast.LENGTH_SHORT).show();
//// }
// }
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
if (item.getItemId() == R.id.delete) {
final int index = pagerFragment.getCurrentItem();
final String deletedPath = pagerFragment.getPaths().get(index);
Snackbar snackbar = Snackbar.make(pagerFragment.getView(), R.string.y_photopicker_deleted_a_photo, Snackbar.LENGTH_LONG);
if (pagerFragment.getPaths().size() <= 1) {
// show confirm dialog
new AlertDialog.Builder(this)
.setTitle(R.string.y_photopicker_confirm_to_delete)
.setPositiveButton(R.string.y_photopicker_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
setResult(RESULT_OK);
finish();
}
})
.setNegativeButton(R.string.y_photopicker_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.show();
} else {
snackbar.show();
pagerFragment.getPaths().remove(index);
pagerFragment.getViewPager().getAdapter().notifyDataSetChanged();
}
snackbar.setAction(R.string.y_photopicker_undo, new View.OnClickListener() {
@Override
public void onClick(View view) {
if (pagerFragment.getPaths().size() > 0) {
pagerFragment.getPaths().add(index, deletedPath);
} else {
pagerFragment.getPaths().add(deletedPath);
}
pagerFragment.getViewPager().getAdapter().notifyDataSetChanged();
pagerFragment.getViewPager().setCurrentItem(index, true);
}
});
return true;
}
return super.onOptionsItemSelected(item);
}
public void updateActionBarTitle() {
tv_count.setText("" + (pagerFragment.getViewPager().getCurrentItem() + 1) + "/" + pagerFragment.getPaths().size());
}
/**
* create Image save Folder
* @return
*/
private File createFolders() {
File baseDir;
if (Build.VERSION.SDK_INT < 8) {
baseDir = Environment.getExternalStorageDirectory();
} else {
baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
}
if (baseDir == null) {
return Environment.getExternalStorageDirectory();
}
File aviaryFolder = new File(baseDir, FOLDER_NAME);
if (aviaryFolder.exists()) {
return aviaryFolder;
}
if (aviaryFolder.mkdirs()) {
return aviaryFolder;
}
return Environment.getExternalStorageDirectory();
}
/**
* get Uri Fimename
* @param context
* @param uri
* @return
*/
public static String getFileNameByUri(Context context, Uri uri)
{
String fileName="unknown";//default fileName
Uri filePathUri = uri;
if (uri.getScheme().toString().compareTo("content")==0)
{
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor.moveToFirst())
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
filePathUri = Uri.parse(cursor.getString(column_index));
fileName = filePathUri.getLastPathSegment().toString();
}
}
else if (uri.getScheme().compareTo("file")==0)
{
fileName = filePathUri.getLastPathSegment().toString();
}
else
{
fileName = fileName+"_"+filePathUri.getLastPathSegment();
}
return fileName;
}
}
| [
"gle00@naver.com"
] | gle00@naver.com |
2f4b88ac3a8a3351f33095a6b2d344f7ba6847d6 | cd15756c7e57947dd98eb3a8e4942b8ad3e694d9 | /google-ads/src/main/java/com/google/ads/googleads/v0/services/MutateOperationOrBuilder.java | 9bc004854f74a0729723dbb4d31e5b5c84eda0eb | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | DalavanCloud/google-ads-java | e4d967d3f36c4c9f0f06b98a74cd12cda90d5a85 | 70d951aa0202833b3e487fb909fd5294e1dda405 | refs/heads/master | 2020-04-21T13:07:19.440871 | 2019-02-06T13:54:21 | 2019-02-06T13:54:21 | 169,587,855 | 1 | 0 | Apache-2.0 | 2019-02-07T14:49:54 | 2019-02-07T14:49:54 | null | UTF-8 | Java | false | true | 11,746 | java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v0/services/google_ads_service.proto
package com.google.ads.googleads.v0.services;
public interface MutateOperationOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v0.services.MutateOperation)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* An ad group ad mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.AdGroupAdOperation ad_group_ad_operation = 1;</code>
*/
boolean hasAdGroupAdOperation();
/**
* <pre>
* An ad group ad mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.AdGroupAdOperation ad_group_ad_operation = 1;</code>
*/
com.google.ads.googleads.v0.services.AdGroupAdOperation getAdGroupAdOperation();
/**
* <pre>
* An ad group ad mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.AdGroupAdOperation ad_group_ad_operation = 1;</code>
*/
com.google.ads.googleads.v0.services.AdGroupAdOperationOrBuilder getAdGroupAdOperationOrBuilder();
/**
* <pre>
* An ad group bid modifier mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.AdGroupBidModifierOperation ad_group_bid_modifier_operation = 2;</code>
*/
boolean hasAdGroupBidModifierOperation();
/**
* <pre>
* An ad group bid modifier mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.AdGroupBidModifierOperation ad_group_bid_modifier_operation = 2;</code>
*/
com.google.ads.googleads.v0.services.AdGroupBidModifierOperation getAdGroupBidModifierOperation();
/**
* <pre>
* An ad group bid modifier mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.AdGroupBidModifierOperation ad_group_bid_modifier_operation = 2;</code>
*/
com.google.ads.googleads.v0.services.AdGroupBidModifierOperationOrBuilder getAdGroupBidModifierOperationOrBuilder();
/**
* <pre>
* An ad group criterion mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.AdGroupCriterionOperation ad_group_criterion_operation = 3;</code>
*/
boolean hasAdGroupCriterionOperation();
/**
* <pre>
* An ad group criterion mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.AdGroupCriterionOperation ad_group_criterion_operation = 3;</code>
*/
com.google.ads.googleads.v0.services.AdGroupCriterionOperation getAdGroupCriterionOperation();
/**
* <pre>
* An ad group criterion mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.AdGroupCriterionOperation ad_group_criterion_operation = 3;</code>
*/
com.google.ads.googleads.v0.services.AdGroupCriterionOperationOrBuilder getAdGroupCriterionOperationOrBuilder();
/**
* <pre>
* An ad group mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.AdGroupOperation ad_group_operation = 5;</code>
*/
boolean hasAdGroupOperation();
/**
* <pre>
* An ad group mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.AdGroupOperation ad_group_operation = 5;</code>
*/
com.google.ads.googleads.v0.services.AdGroupOperation getAdGroupOperation();
/**
* <pre>
* An ad group mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.AdGroupOperation ad_group_operation = 5;</code>
*/
com.google.ads.googleads.v0.services.AdGroupOperationOrBuilder getAdGroupOperationOrBuilder();
/**
* <pre>
* A bidding strategy mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.BiddingStrategyOperation bidding_strategy_operation = 6;</code>
*/
boolean hasBiddingStrategyOperation();
/**
* <pre>
* A bidding strategy mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.BiddingStrategyOperation bidding_strategy_operation = 6;</code>
*/
com.google.ads.googleads.v0.services.BiddingStrategyOperation getBiddingStrategyOperation();
/**
* <pre>
* A bidding strategy mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.BiddingStrategyOperation bidding_strategy_operation = 6;</code>
*/
com.google.ads.googleads.v0.services.BiddingStrategyOperationOrBuilder getBiddingStrategyOperationOrBuilder();
/**
* <pre>
* A campaign bid modifier mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignBidModifierOperation campaign_bid_modifier_operation = 7;</code>
*/
boolean hasCampaignBidModifierOperation();
/**
* <pre>
* A campaign bid modifier mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignBidModifierOperation campaign_bid_modifier_operation = 7;</code>
*/
com.google.ads.googleads.v0.services.CampaignBidModifierOperation getCampaignBidModifierOperation();
/**
* <pre>
* A campaign bid modifier mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignBidModifierOperation campaign_bid_modifier_operation = 7;</code>
*/
com.google.ads.googleads.v0.services.CampaignBidModifierOperationOrBuilder getCampaignBidModifierOperationOrBuilder();
/**
* <pre>
* A campaign budget mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignBudgetOperation campaign_budget_operation = 8;</code>
*/
boolean hasCampaignBudgetOperation();
/**
* <pre>
* A campaign budget mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignBudgetOperation campaign_budget_operation = 8;</code>
*/
com.google.ads.googleads.v0.services.CampaignBudgetOperation getCampaignBudgetOperation();
/**
* <pre>
* A campaign budget mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignBudgetOperation campaign_budget_operation = 8;</code>
*/
com.google.ads.googleads.v0.services.CampaignBudgetOperationOrBuilder getCampaignBudgetOperationOrBuilder();
/**
* <pre>
* A campaign mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignOperation campaign_operation = 10;</code>
*/
boolean hasCampaignOperation();
/**
* <pre>
* A campaign mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignOperation campaign_operation = 10;</code>
*/
com.google.ads.googleads.v0.services.CampaignOperation getCampaignOperation();
/**
* <pre>
* A campaign mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignOperation campaign_operation = 10;</code>
*/
com.google.ads.googleads.v0.services.CampaignOperationOrBuilder getCampaignOperationOrBuilder();
/**
* <pre>
* A campaign shared set mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignSharedSetOperation campaign_shared_set_operation = 11;</code>
*/
boolean hasCampaignSharedSetOperation();
/**
* <pre>
* A campaign shared set mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignSharedSetOperation campaign_shared_set_operation = 11;</code>
*/
com.google.ads.googleads.v0.services.CampaignSharedSetOperation getCampaignSharedSetOperation();
/**
* <pre>
* A campaign shared set mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignSharedSetOperation campaign_shared_set_operation = 11;</code>
*/
com.google.ads.googleads.v0.services.CampaignSharedSetOperationOrBuilder getCampaignSharedSetOperationOrBuilder();
/**
* <pre>
* A conversion action mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.ConversionActionOperation conversion_action_operation = 12;</code>
*/
boolean hasConversionActionOperation();
/**
* <pre>
* A conversion action mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.ConversionActionOperation conversion_action_operation = 12;</code>
*/
com.google.ads.googleads.v0.services.ConversionActionOperation getConversionActionOperation();
/**
* <pre>
* A conversion action mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.ConversionActionOperation conversion_action_operation = 12;</code>
*/
com.google.ads.googleads.v0.services.ConversionActionOperationOrBuilder getConversionActionOperationOrBuilder();
/**
* <pre>
* A campaign criterion mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignCriterionOperation campaign_criterion_operation = 13;</code>
*/
boolean hasCampaignCriterionOperation();
/**
* <pre>
* A campaign criterion mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignCriterionOperation campaign_criterion_operation = 13;</code>
*/
com.google.ads.googleads.v0.services.CampaignCriterionOperation getCampaignCriterionOperation();
/**
* <pre>
* A campaign criterion mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.CampaignCriterionOperation campaign_criterion_operation = 13;</code>
*/
com.google.ads.googleads.v0.services.CampaignCriterionOperationOrBuilder getCampaignCriterionOperationOrBuilder();
/**
* <pre>
* A shared criterion mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.SharedCriterionOperation shared_criterion_operation = 14;</code>
*/
boolean hasSharedCriterionOperation();
/**
* <pre>
* A shared criterion mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.SharedCriterionOperation shared_criterion_operation = 14;</code>
*/
com.google.ads.googleads.v0.services.SharedCriterionOperation getSharedCriterionOperation();
/**
* <pre>
* A shared criterion mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.SharedCriterionOperation shared_criterion_operation = 14;</code>
*/
com.google.ads.googleads.v0.services.SharedCriterionOperationOrBuilder getSharedCriterionOperationOrBuilder();
/**
* <pre>
* A shared set mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.SharedSetOperation shared_set_operation = 15;</code>
*/
boolean hasSharedSetOperation();
/**
* <pre>
* A shared set mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.SharedSetOperation shared_set_operation = 15;</code>
*/
com.google.ads.googleads.v0.services.SharedSetOperation getSharedSetOperation();
/**
* <pre>
* A shared set mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.SharedSetOperation shared_set_operation = 15;</code>
*/
com.google.ads.googleads.v0.services.SharedSetOperationOrBuilder getSharedSetOperationOrBuilder();
/**
* <pre>
* A user list mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.UserListOperation user_list_operation = 16;</code>
*/
boolean hasUserListOperation();
/**
* <pre>
* A user list mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.UserListOperation user_list_operation = 16;</code>
*/
com.google.ads.googleads.v0.services.UserListOperation getUserListOperation();
/**
* <pre>
* A user list mutate operation.
* </pre>
*
* <code>.google.ads.googleads.v0.services.UserListOperation user_list_operation = 16;</code>
*/
com.google.ads.googleads.v0.services.UserListOperationOrBuilder getUserListOperationOrBuilder();
public com.google.ads.googleads.v0.services.MutateOperation.OperationCase getOperationCase();
}
| [
"noreply@github.com"
] | noreply@github.com |
c1bfb370158121ecc5391c392acbeb6b015ac04a | db94dd778079616ab1d193763bdf139cfb83ee9b | /assignments/src/dev/selvam/module2/Qus3_arrayFunctionWithSearch.java | 7b6899b1f808c39309e9e175b9572faf2ef39369 | [] | no_license | selvam-rhce/j2ee_course | 87d93ff5e814462a300cbe24e1e885343b5ac4c1 | 19034284f6cc3e55de99e5e5c6e9b1a5484514d2 | refs/heads/master | 2022-12-23T00:55:32.978396 | 2020-09-11T06:38:57 | 2020-09-11T06:38:57 | 259,819,840 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,886 | java | package dev.selvam.module2;
import java.util.Scanner;
public class Qus3_arrayFunctionWithSearch {
public static void main(String[] args) {
/*
* Qus: Write another function named display() which takes 4 arguments.
* The arguments are namedas String and 3 arrays (Employee id, name and salary).
* Function prototype looks like:display (String name, int regno[], String Empname[], double salary[]).
* This function will search for the name in the Empname array and will display its corresponding
* id and salary in the below given format. For example,
* if Divya is given as the name to search then display () function will display the following record
*
* ID NAME salary
* 00 Divya 10000
*
*/
// declaration part
int numOfEmp=5; // accept 5 emp
int[] empId = new int[numOfEmp]; // empid array
String[] empName = new String[numOfEmp]; // empname array
int[] empSalary = new int[numOfEmp];; // empsalary array
int empCount;
// Opening scanner to read input from user
Scanner myinputs = new Scanner(System.in);
// Reading employee information one by one using for loop
for (int empidx=0; empidx<numOfEmp; empidx++ )
{
empCount = empidx+1;
System.out.println("Enter Employee"+empCount+" ID?");
empId[empidx] = myinputs.nextInt();
System.out.println("Enter Employee"+empCount+" NAME?");
empName[empidx] = myinputs.next();
System.out.println("Enter Employee"+empCount+" SALARY?");
empSalary[empidx] = myinputs.nextInt();
}
display(empId, empName, empSalary); // printing employee informations
display(empId, empName); // function overloading
System.out.println("Enter the employee you want to search?");
String searchName = myinputs.next();
myinputs.close(); // closing scanner
display(searchName, empId, empName, empSalary); // printing employee informations
}
static void display(int[] empId, String[] empName, int[] empSalary) {
System.out.println("ID \t NAME \t\t SALARY\n");
for (int empidx=0; empidx<empId.length;empidx++)
{
System.out.println(empId[empidx]+" \t "+empName[empidx]+" \t "+empSalary[empidx]);
}
System.out.println("\n");
}
static void display(int[] empId, String[] empName) { //function overloading
System.out.println("ID \t NAME\n");
for (int empidx=0; empidx<empId.length;empidx++)
{
System.out.println(empId[empidx]+" \t "+empName[empidx]);
}
System.out.println("\n");
}
static void display(String name, int[] empId, String[] empName, int[] empSalary) {
System.out.println("ID \t NAME \t\t SALARY\n");
for (int empidx=0; empidx<empId.length;empidx++)
{
if (name.equals(empName[empidx])) { // only print the required employee
System.out.println(empId[empidx]+" \t "+empName[empidx]+" \t "+empSalary[empidx]);
}
}
System.out.println("\n");
}
}
| [
"selvam.ayyanar@flytxt.com"
] | selvam.ayyanar@flytxt.com |
9775ae40039824d0a0021a61b51c6775ca972588 | 5c3bb5a03637e966890bcc75eae07a61787ba865 | /learning_udp-master/src/main/java/com/example/demo/init/UdpServer.java | 47ff375e3e9cdce9c2992846dbaf09d6f87993f3 | [] | no_license | wuhlcom/JavaEE | 735751770e5192d55a69538a39ca743734dc8f84 | 2f613dd7f24f5a959ba9e8b0a1649cd21d8448f6 | refs/heads/master | 2021-01-01T04:32:34.453606 | 2017-10-31T03:25:10 | 2017-10-31T03:25:10 | 97,192,364 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,422 | java | package com.example.demo.init;
import com.example.demo.handle.UdpServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* server服务器
* Created by wj on 2017/8/30.
*/
@Component
public class UdpServer {
private static final Logger log= LoggerFactory.getLogger(UdpServer.class);
// private static final int PORT = Integer.parseInt(System.getProperty("port", "7686"));
@Async("myTaskAsyncPool")
public void run(int udpReceivePort) {
EventLoopGroup group = new NioEventLoopGroup();
log.info("Server start! Udp Receive msg Port:" + udpReceivePort );
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new UdpServerHandler());
b.bind(udpReceivePort).sync().channel().closeFuture().await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
}
| [
"378433855@qq.com"
] | 378433855@qq.com |
dfbf4d9b6e5b982c1b61ed1ffa167b3394f3d444 | 890af51efbc9b8237e0fd09903f78fe2bb9caadd | /general/oa/com/hd/agent/oa/dao/OaCustomerFeeMapper.java | f1de44b4979e670dd6865faa7d6c8c3cf31fa69f | [] | no_license | 1045907427/project | 815fb0c5b4b44bf5d8365acfde61b6f68be6e52a | 6eaecf09cd3414295ccf91454f62cf4d619cdbf2 | refs/heads/master | 2020-04-14T19:17:54.310613 | 2019-01-14T10:49:11 | 2019-01-14T10:49:11 | 164,052,678 | 0 | 5 | null | null | null | null | UTF-8 | Java | false | false | 2,137 | java | package com.hd.agent.oa.dao;
import com.hd.agent.common.util.PageMap;
import com.hd.agent.oa.model.OaCustomerFee;
import com.hd.agent.oa.model.OaCustomerFeeDetail;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 客户费用申请单(账扣)Mapper
* @author limin
* @date Mar 23, 2016
*/
public interface OaCustomerFeeMapper {
/**
* 查询客户费用
* @param id
* @return
* @author limin
* @date Mar 23, 2016
*/
public OaCustomerFee selectOaCustomerFee(String id);
/**
* 删除客户费用
* @param id
* @return
* @author limin
* @date Mar 23, 2016
*/
public int deleteOaCustomerFee(String id);
/**
* 客户费用登录
* @param fee
* @return
* @author limin
* @date Mar 23, 2016
*/
public int insertOaCustomerFee(OaCustomerFee fee);
/**
* 客户费用更新
* @param fee
* @return
* @author limin
* @date Mar 23, 2016
*/
public int updateOaCustomerFee(OaCustomerFee fee);
/**
* 客户费用明细登录
* @param detail
* @return
* @author limin
* @date Mar 23, 2016
*/
public int insertOaCustomerFeeDetail(OaCustomerFeeDetail detail);
/**
* 根据billid删除客户费用明细
* @param billid
* @return
* @author limin
* @date Mar 23, 2016
*/
public int deleteOaCustomerFeeDetailByBillid(String billid);
/**
* 查询客户费用明细List
* @return
* @throws Exception
* @author limin
* @date Mar 29, 2016
*/
public List<OaCustomerFeeDetail> getCustomerFeeDetailList(PageMap map);
/**
* 查询客户费用明细List
* @return
* @throws Exception
* @author limin
* @date Mar 29, 2016
*/
public int getCustomerFeeDetailListCount(PageMap map);
/**
* 查询客户费用明细List
* @return
* @throws Exception
* @author limin
* @date Mar 29, 2016
*/
public List<OaCustomerFeeDetail> getCustomerFeeDetailListByBillid(@Param("billid") String billid);
} | [
"1045907427@qq.com"
] | 1045907427@qq.com |
3b8bcf7f0c484caf631dd32f115c4e7432d299fe | 4167fff95d69ce739177a119912c245a1c21b5f1 | /src/main/java/com/kasiyanov/spaceport/template/parameterExtractor/WarriorParameterExtractor.java | 48c7531e9b269d027d09b3bf01a94e5aaba596c8 | [] | no_license | VladimirKasiyanov/polymorphism-with-JSON | d04919dcee50e074af8a918ce82f3c1ce684d898 | 9354e913e870b61cd69bfb07f86648d4b1704981 | refs/heads/master | 2020-04-24T01:09:26.747177 | 2019-03-04T02:46:20 | 2019-03-04T02:46:20 | 171,588,962 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 898 | java | package com.kasiyanov.spaceport.template.parameterExtractor;
import com.kasiyanov.spaceport.dto.InputDto;
import com.kasiyanov.spaceport.shipModel.parametersModel.Damage;
import com.kasiyanov.spaceport.shipModel.parametersModel.Parameter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class WarriorParameterExtractor extends ShipParameterExtractor {
public Integer getDamageOfWarrior(InputDto inputDto) {
Integer damage = null;
List<Parameter> parametersList = new ArrayList<>(inputDto.getParameters());
Iterator<Parameter> iterator = parametersList.iterator();
while (iterator.hasNext()) {
Object element = iterator.next();
if (element instanceof Damage) {
damage = ((Damage) element).getDamage();
break;
}
}
return damage;
}
}
| [
"vladimirqw@gmail.com"
] | vladimirqw@gmail.com |
6503b493957e5b27a80134198e0bbec6926cd87a | a7f3554def3bff08de8e973c0a712883685e1e8d | /EmployeeServiceContract/src/com/tanmoy/employee/dto/Employee.java | 489f979f0f3ec54a95c4ecc33614e26819f5a8e1 | [] | no_license | guoyu07/RESTful_Resource_Spring_App | 0e477650eed0799bc1ec03a7eaf15f0d0f406ad4 | 99d04732406de1c41cbb99827732108aac9fdcb6 | refs/heads/master | 2020-03-07T08:11:55.881547 | 2017-07-02T06:53:40 | 2017-07-02T06:53:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,577 | java | package com.tanmoy.employee.dto;
public class Employee {
public String loginID;
public int businessEntityID;
public String employeeName;
public String nationalIDNumber;
public String jobTitle;
public String birthDate;
public char maritalStatus;
public char gender;
public String hireDate;
public String getLoginID() {
return loginID;
}
public void setLoginID(String loginID) {
this.loginID = loginID;
}
public int getBusinessEntityID() {
return businessEntityID;
}
public void setBusinessEntityID(int businessEntityID) {
this.businessEntityID = businessEntityID;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getNationalIDNumber() {
return nationalIDNumber;
}
public void setNationalIDNumber(String nationalIDNumber) {
this.nationalIDNumber = nationalIDNumber;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public char getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(char maritalStatus) {
this.maritalStatus = maritalStatus;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public String getHireDate() {
return hireDate;
}
public void setHireDate(String hireDate) {
this.hireDate = hireDate;
}
}
| [
"tanmoy.banerjee@outlook.in"
] | tanmoy.banerjee@outlook.in |
970e0595ca08024a34b980a8b9a55033379ec23c | 8307662040711983aa540000216ea69dc1180ae5 | /src/main/java/me/teakivy/eggfix/Main.java | 68762f96d83710a254e4ffd7453bcd0096436294 | [] | no_license | teakivy/EggFix-1.17 | 99c43a88d56bb6e339c4d9f9349a0000083cc744 | a96797b227b0c38420e7906d0e9933a2c7edb1b6 | refs/heads/main | 2023-06-26T23:50:03.669312 | 2021-07-29T12:30:30 | 2021-07-29T12:30:30 | 379,803,606 | 3 | 3 | null | 2021-07-29T12:09:27 | 2021-06-24T04:32:26 | Java | UTF-8 | Java | false | false | 2,738 | java | package me.teakivy.eggfix;
import org.bukkit.*;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.*;
public final class Main extends JavaPlugin implements Listener {
@Override
public void onEnable() {
// Plugin startup logic
getServer().getPluginManager().registerEvents(this, this);
this.saveDefaultConfig();
if (getConfig().getBoolean("check-on-chunk-load")) {
getServer().getPluginManager().registerEvents(new ChunkLoadEvent(), this);
}
}
@EventHandler
public void onEggPickup(EntityPickupItemEvent event) {
Entity entity = event.getEntity();
if (!(entity.getType().equals(EntityType.PLAYER))) {
if(event.getItem().getItemStack().getType().equals(Material.EGG)) {
event.setCancelled(true);
}
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("eggfix")) {
if(sender instanceof Player) {
if(!sender.isOp()) {
sender.sendMessage(ChatColor.RED + "You need to have OP to run this command!");
return true;
}
}
int count = 0;
for(World world : Bukkit.getWorlds()) {
for(LivingEntity entity : world.getLivingEntities()) {
if (entity.getType() != EntityType.PLAYER && Objects.requireNonNull(entity.getEquipment()).getItemInMainHand().getType() == Material.EGG) {
entity.remove();
count++;
}
}
}
if (sender instanceof Player) {
sender.sendMessage(
"\n" + ChatColor.GRAY + "---------------" + "\n" +
ChatColor.YELLOW + "Removed " +
ChatColor.GOLD.toString() + ChatColor.BOLD + count +
ChatColor.RESET.toString() + ChatColor.YELLOW + " Mobs Holding Eggs!" + "\n" +
ChatColor.GRAY + "---------------" + "\n");
return true;
}
sender.sendMessage("Removed " + count + " Mobs Holding Eggs");
return true;
}
return false;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
483a2c05830ab99a65ccd0e4eae53e495624bc46 | 3d5b7238c82e4c1b61e619562ccea73cfed13c9b | /StudentForum/src/java/com/leapfrog/springFramework/Filter/AdminFilter.java | 54d463d836e5827a23fd80a132b7888b82b18642 | [] | no_license | binodG/TicketingSystem | 82abbf53d1bca46dc4178b198ce83dc2ba5a050b | 678f31f403014be814eb18543092883dcfc03384 | refs/heads/master | 2021-01-21T02:52:55.353074 | 2016-09-18T04:19:34 | 2016-09-18T04:19:34 | 68,496,601 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,476 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.leapfrog.springFramework.Filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author BkoNod
*/
public class AdminFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)req;
HttpServletResponse response=(HttpServletResponse)res;
HttpSession session=request.getSession(false);
if(session.getAttribute("USER")==null || !session.getAttribute("ROLE").equals("ADMIN"))
{
response.sendRedirect(request.getContextPath()+"/adminlogin");
}
else{
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
}
| [
"gbnod55@gmail.com"
] | gbnod55@gmail.com |
a482dd38512b32cb1dfee73a3002a01ccef9a1c1 | 6b50497523111b029a9c294c5fd04430e8802d5f | /app/src/androidTest/java/com/p/dreamcelebration/ExampleInstrumentedTest.java | 68ec240e5103d60eb3d704e5e680369ec5ebd10b | [] | no_license | PRATYUSHNAIR1976/DREAMCELEBRATION | 52bb612084202eeaf5b6b4b6434390b21ebf0416 | 1f8a576f07060ac55dbe62056bca90cb9e30ceff | refs/heads/master | 2020-05-01T06:22:01.626907 | 2019-03-28T02:16:47 | 2019-03-28T02:16:47 | 177,328,309 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 728 | java | package com.p.dreamcelebration;
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.*;
/**
* 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 ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.p.dreamcelebration", appContext.getPackageName());
}
}
| [
"pratyushnair1976@gmail.com"
] | pratyushnair1976@gmail.com |
1550ddae19196b45ccf751f895fc9f822f33071e | 3e2cf0ccc59771d7183615becb8f0fe23dcb095e | /SmartBanking_Frontend/android/support/v7/internal/view/SupportMenuInflater.java | 20029bef4de09a6a5d43cc4173e6d36017fe59b2 | [] | no_license | Masebeni/smartBanking_f | de6a138d17ac8370dfd56e591a0d274144f0aa38 | 84128539a93168429020d740e3e897be6eb3b3c2 | refs/heads/master | 2020-04-18T08:47:22.344599 | 2016-09-02T20:53:52 | 2016-09-02T20:53:52 | 67,164,095 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,236 | java | package android.support.v7.internal.view;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.support.v4.app.NotificationCompat.WearableExtender;
import android.support.v4.internal.view.SupportMenu;
import android.support.v4.view.ActionProvider;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.appcompat.C0111R;
import android.support.v7.internal.view.menu.MenuItemImpl;
import android.support.v7.internal.view.menu.MenuItemWrapperICS;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Xml;
import android.view.InflateException;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.SubMenu;
import android.view.View;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
public class SupportMenuInflater extends MenuInflater {
private static final Class<?>[] ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE;
private static final Class<?>[] ACTION_VIEW_CONSTRUCTOR_SIGNATURE;
private static final String LOG_TAG = "SupportMenuInflater";
private static final int NO_ID = 0;
private static final String XML_GROUP = "group";
private static final String XML_ITEM = "item";
private static final String XML_MENU = "menu";
private final Object[] mActionProviderConstructorArguments;
private final Object[] mActionViewConstructorArguments;
private Context mContext;
private Object mRealOwner;
private static class InflatedOnMenuItemClickListener implements OnMenuItemClickListener {
private static final Class<?>[] PARAM_TYPES;
private Method mMethod;
private Object mRealOwner;
static {
PARAM_TYPES = new Class[]{MenuItem.class};
}
public InflatedOnMenuItemClickListener(Object realOwner, String methodName) {
this.mRealOwner = realOwner;
Class<?> c = realOwner.getClass();
try {
this.mMethod = c.getMethod(methodName, PARAM_TYPES);
} catch (Exception e) {
InflateException ex = new InflateException("Couldn't resolve menu item onClick handler " + methodName + " in class " + c.getName());
ex.initCause(e);
throw ex;
}
}
public boolean onMenuItemClick(MenuItem item) {
try {
if (this.mMethod.getReturnType() == Boolean.TYPE) {
return ((Boolean) this.mMethod.invoke(this.mRealOwner, new Object[]{item})).booleanValue();
}
this.mMethod.invoke(this.mRealOwner, new Object[]{item});
return true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private class MenuState {
private static final int defaultGroupId = 0;
private static final int defaultItemCategory = 0;
private static final int defaultItemCheckable = 0;
private static final boolean defaultItemChecked = false;
private static final boolean defaultItemEnabled = true;
private static final int defaultItemId = 0;
private static final int defaultItemOrder = 0;
private static final boolean defaultItemVisible = true;
private int groupCategory;
private int groupCheckable;
private boolean groupEnabled;
private int groupId;
private int groupOrder;
private boolean groupVisible;
private ActionProvider itemActionProvider;
private String itemActionProviderClassName;
private String itemActionViewClassName;
private int itemActionViewLayout;
private boolean itemAdded;
private char itemAlphabeticShortcut;
private int itemCategoryOrder;
private int itemCheckable;
private boolean itemChecked;
private boolean itemEnabled;
private int itemIconResId;
private int itemId;
private String itemListenerMethodName;
private char itemNumericShortcut;
private int itemShowAsAction;
private CharSequence itemTitle;
private CharSequence itemTitleCondensed;
private boolean itemVisible;
private Menu menu;
public MenuState(Menu menu) {
this.menu = menu;
resetGroup();
}
public void resetGroup() {
this.groupId = defaultItemOrder;
this.groupCategory = defaultItemOrder;
this.groupOrder = defaultItemOrder;
this.groupCheckable = defaultItemOrder;
this.groupVisible = defaultItemVisible;
this.groupEnabled = defaultItemVisible;
}
public void readGroup(AttributeSet attrs) {
TypedArray a = SupportMenuInflater.this.mContext.obtainStyledAttributes(attrs, C0111R.styleable.MenuGroup);
this.groupId = a.getResourceId(C0111R.styleable.MenuGroup_android_id, defaultItemOrder);
this.groupCategory = a.getInt(C0111R.styleable.MenuGroup_android_menuCategory, defaultItemOrder);
this.groupOrder = a.getInt(C0111R.styleable.MenuGroup_android_orderInCategory, defaultItemOrder);
this.groupCheckable = a.getInt(C0111R.styleable.MenuGroup_android_checkableBehavior, defaultItemOrder);
this.groupVisible = a.getBoolean(C0111R.styleable.MenuGroup_android_visible, defaultItemVisible);
this.groupEnabled = a.getBoolean(C0111R.styleable.MenuGroup_android_enabled, defaultItemVisible);
a.recycle();
}
public void readItem(AttributeSet attrs) {
TypedArray a = SupportMenuInflater.this.mContext.obtainStyledAttributes(attrs, C0111R.styleable.MenuItem);
this.itemId = a.getResourceId(C0111R.styleable.MenuItem_android_id, defaultItemOrder);
this.itemCategoryOrder = (SupportMenu.CATEGORY_MASK & a.getInt(C0111R.styleable.MenuItem_android_menuCategory, this.groupCategory)) | (SupportMenu.USER_MASK & a.getInt(C0111R.styleable.MenuItem_android_orderInCategory, this.groupOrder));
this.itemTitle = a.getText(C0111R.styleable.MenuItem_android_title);
this.itemTitleCondensed = a.getText(C0111R.styleable.MenuItem_android_titleCondensed);
this.itemIconResId = a.getResourceId(C0111R.styleable.MenuItem_android_icon, defaultItemOrder);
this.itemAlphabeticShortcut = getShortcut(a.getString(C0111R.styleable.MenuItem_android_alphabeticShortcut));
this.itemNumericShortcut = getShortcut(a.getString(C0111R.styleable.MenuItem_android_numericShortcut));
if (a.hasValue(C0111R.styleable.MenuItem_android_checkable)) {
int i;
if (a.getBoolean(C0111R.styleable.MenuItem_android_checkable, defaultItemChecked)) {
i = 1;
} else {
i = defaultItemOrder;
}
this.itemCheckable = i;
} else {
this.itemCheckable = this.groupCheckable;
}
this.itemChecked = a.getBoolean(C0111R.styleable.MenuItem_android_checked, defaultItemChecked);
this.itemVisible = a.getBoolean(C0111R.styleable.MenuItem_android_visible, this.groupVisible);
this.itemEnabled = a.getBoolean(C0111R.styleable.MenuItem_android_enabled, this.groupEnabled);
this.itemShowAsAction = a.getInt(C0111R.styleable.MenuItem_showAsAction, -1);
this.itemListenerMethodName = a.getString(C0111R.styleable.MenuItem_android_onClick);
this.itemActionViewLayout = a.getResourceId(C0111R.styleable.MenuItem_actionLayout, defaultItemOrder);
this.itemActionViewClassName = a.getString(C0111R.styleable.MenuItem_actionViewClass);
this.itemActionProviderClassName = a.getString(C0111R.styleable.MenuItem_actionProviderClass);
boolean hasActionProvider = this.itemActionProviderClassName != null ? defaultItemVisible : defaultItemChecked;
if (hasActionProvider && this.itemActionViewLayout == 0 && this.itemActionViewClassName == null) {
this.itemActionProvider = (ActionProvider) newInstance(this.itemActionProviderClassName, SupportMenuInflater.ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE, SupportMenuInflater.this.mActionProviderConstructorArguments);
} else {
if (hasActionProvider) {
Log.w(SupportMenuInflater.LOG_TAG, "Ignoring attribute 'actionProviderClass'. Action view already specified.");
}
this.itemActionProvider = null;
}
a.recycle();
this.itemAdded = defaultItemChecked;
}
private char getShortcut(String shortcutString) {
if (shortcutString == null) {
return '\u0000';
}
return shortcutString.charAt(defaultItemOrder);
}
private void setItem(MenuItem item) {
item.setChecked(this.itemChecked).setVisible(this.itemVisible).setEnabled(this.itemEnabled).setCheckable(this.itemCheckable >= 1 ? defaultItemVisible : defaultItemChecked).setTitleCondensed(this.itemTitleCondensed).setIcon(this.itemIconResId).setAlphabeticShortcut(this.itemAlphabeticShortcut).setNumericShortcut(this.itemNumericShortcut);
if (this.itemShowAsAction >= 0) {
MenuItemCompat.setShowAsAction(item, this.itemShowAsAction);
}
if (this.itemListenerMethodName != null) {
if (SupportMenuInflater.this.mContext.isRestricted()) {
throw new IllegalStateException("The android:onClick attribute cannot be used within a restricted context");
}
item.setOnMenuItemClickListener(new InflatedOnMenuItemClickListener(SupportMenuInflater.this.getRealOwner(), this.itemListenerMethodName));
}
if (item instanceof MenuItemImpl) {
MenuItemImpl impl = (MenuItemImpl) item;
}
if (this.itemCheckable >= 2) {
if (item instanceof MenuItemImpl) {
((MenuItemImpl) item).setExclusiveCheckable(defaultItemVisible);
} else if (item instanceof MenuItemWrapperICS) {
((MenuItemWrapperICS) item).setExclusiveCheckable(defaultItemVisible);
}
}
boolean actionViewSpecified = defaultItemChecked;
if (this.itemActionViewClassName != null) {
MenuItemCompat.setActionView(item, (View) newInstance(this.itemActionViewClassName, SupportMenuInflater.ACTION_VIEW_CONSTRUCTOR_SIGNATURE, SupportMenuInflater.this.mActionViewConstructorArguments));
actionViewSpecified = defaultItemVisible;
}
if (this.itemActionViewLayout > 0) {
if (actionViewSpecified) {
Log.w(SupportMenuInflater.LOG_TAG, "Ignoring attribute 'itemActionViewLayout'. Action view already specified.");
} else {
MenuItemCompat.setActionView(item, this.itemActionViewLayout);
}
}
if (this.itemActionProvider != null) {
MenuItemCompat.setActionProvider(item, this.itemActionProvider);
}
}
public void addItem() {
this.itemAdded = defaultItemVisible;
setItem(this.menu.add(this.groupId, this.itemId, this.itemCategoryOrder, this.itemTitle));
}
public SubMenu addSubMenuItem() {
this.itemAdded = defaultItemVisible;
SubMenu subMenu = this.menu.addSubMenu(this.groupId, this.itemId, this.itemCategoryOrder, this.itemTitle);
setItem(subMenu.getItem());
return subMenu;
}
public boolean hasAddedItem() {
return this.itemAdded;
}
private <T> T newInstance(String className, Class<?>[] constructorSignature, Object[] arguments) {
try {
Constructor<?> constructor = SupportMenuInflater.this.mContext.getClassLoader().loadClass(className).getConstructor(constructorSignature);
constructor.setAccessible(defaultItemVisible);
return constructor.newInstance(arguments);
} catch (Exception e) {
Log.w(SupportMenuInflater.LOG_TAG, "Cannot instantiate class: " + className, e);
return null;
}
}
}
static {
ACTION_VIEW_CONSTRUCTOR_SIGNATURE = new Class[]{Context.class};
ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE = ACTION_VIEW_CONSTRUCTOR_SIGNATURE;
}
public SupportMenuInflater(Context context) {
super(context);
this.mContext = context;
this.mActionViewConstructorArguments = new Object[]{context};
this.mActionProviderConstructorArguments = this.mActionViewConstructorArguments;
}
public void inflate(int menuRes, Menu menu) {
if (menu instanceof SupportMenu) {
XmlResourceParser parser = null;
try {
parser = this.mContext.getResources().getLayout(menuRes);
parseMenu(parser, Xml.asAttributeSet(parser), menu);
if (parser != null) {
parser.close();
}
} catch (XmlPullParserException e) {
throw new InflateException("Error inflating menu XML", e);
} catch (IOException e2) {
throw new InflateException("Error inflating menu XML", e2);
} catch (Throwable th) {
if (parser != null) {
parser.close();
}
}
} else {
super.inflate(menuRes, menu);
}
}
private void parseMenu(XmlPullParser parser, AttributeSet attrs, Menu menu) throws XmlPullParserException, IOException {
MenuState menuState = new MenuState(menu);
int eventType = parser.getEventType();
boolean lookingForEndOfUnknownTag = false;
String unknownTagName = null;
while (eventType != 2) {
eventType = parser.next();
if (eventType == 1) {
break;
}
}
String tagName = parser.getName();
if (tagName.equals(XML_MENU)) {
eventType = parser.next();
boolean reachedEndOfMenu = false;
while (!reachedEndOfMenu) {
switch (eventType) {
case SwipeRefreshLayout.DEFAULT /*1*/:
throw new RuntimeException("Unexpected end of document");
case DrawerLayout.STATE_SETTLING /*2*/:
if (!lookingForEndOfUnknownTag) {
tagName = parser.getName();
if (!tagName.equals(XML_GROUP)) {
if (!tagName.equals(XML_ITEM)) {
if (!tagName.equals(XML_MENU)) {
lookingForEndOfUnknownTag = true;
unknownTagName = tagName;
break;
}
parseMenu(parser, attrs, menuState.addSubMenuItem());
break;
}
menuState.readItem(attrs);
break;
}
menuState.readGroup(attrs);
break;
}
break;
case WearableExtender.SIZE_MEDIUM /*3*/:
tagName = parser.getName();
if (!lookingForEndOfUnknownTag || !tagName.equals(unknownTagName)) {
if (!tagName.equals(XML_GROUP)) {
if (!tagName.equals(XML_ITEM)) {
if (!tagName.equals(XML_MENU)) {
break;
}
reachedEndOfMenu = true;
break;
} else if (!menuState.hasAddedItem()) {
if (menuState.itemActionProvider != null && menuState.itemActionProvider.hasSubMenu()) {
menuState.addSubMenuItem();
break;
} else {
menuState.addItem();
break;
}
} else {
break;
}
}
menuState.resetGroup();
break;
}
lookingForEndOfUnknownTag = false;
unknownTagName = null;
break;
default:
break;
}
eventType = parser.next();
}
return;
}
throw new RuntimeException("Expecting menu, got " + tagName);
}
private Object getRealOwner() {
if (this.mRealOwner == null) {
this.mRealOwner = findRealOwner(this.mContext);
}
return this.mRealOwner;
}
private Object findRealOwner(Object owner) {
if (!(owner instanceof Activity) && (owner instanceof ContextWrapper)) {
return findRealOwner(((ContextWrapper) owner).getBaseContext());
}
return owner;
}
}
| [
"xmabeni1@gmail.com"
] | xmabeni1@gmail.com |
a68729568587f103a1e95709f16a5edb6906ceef | 7f6eeb1a0c0b4b3effd499cc8b08c7935a508fdb | /src/login/LoginModel.java | faeff8144e3c0dac6c3b1b141a7b7ed338d9a30c | [] | no_license | Mpumelelodube/inventory-managementsystem-Pos | 331a58b8e404e057189295ccf6c8700ee486d16d | c1ecdde0e6d10767fe0614dbd79239e6a5798179 | refs/heads/master | 2022-08-03T03:01:47.542091 | 2020-05-25T16:07:51 | 2020-05-25T16:07:51 | 260,697,896 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,284 | java | package login;
import database.DatabaseConnection;
import javafx.scene.control.Alert;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class LoginModel {
public static boolean isLogin(String useName, String password, String departmentSelection){
String sql = "select * from users where username = ? and password = ? and accesslevel = ?";
try {
Connection connection = DatabaseConnection.connection();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, useName);
statement.setString(2,password);
statement.setString(3, departmentSelection);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()){
connection.close();
return true;
}
} catch (SQLException | NullPointerException e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Login");
alert.setContentText("Error logging in please recheck your credentials");
alert.show();
e.printStackTrace();
return false;
}
return false;
}
}
| [
"dubempumelelo9@gmail.com"
] | dubempumelelo9@gmail.com |
d24f7af0956f709f5fa4e9345a5b31b5f3a0449d | 3426ac29a405b436807cc341a14079bf4466f44e | /next one/src/Count.java | e655d0aaf79ddd7705cd1906e18b58763f3eb12b | [] | no_license | santhoshbollena/nextone | 02d09ff6c0da5a4fadca8fff32c102f386be3fed | b12c4995798c3d93a4dbe52233a8c95fdede6076 | refs/heads/master | 2021-05-14T02:04:35.202886 | 2018-01-07T17:15:24 | 2018-01-07T17:15:24 | 116,583,919 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 889 | java | import java.util.Scanner;
public class Count {
public static void main(String[] args) {
// TODO Auto-generated method stub
int c=1;
boolean f=true;
System.out.println("enter a string");
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
System.out.println(s);
int n=s.length();
String tok[]=new String[n];
for(int i=0;i<n;i++)
{
tok[i]=s.substring(i,i+1);
}
for(int i=0;i<n;i++)
{ c=1;
f=true;
for(int j=0;j<n;j++)
{
if(i==j)
{
j=j+1;
}
if(j>=n)
{
break;
}
if(tok[i].equals(tok[j]))
{
c++;
f=false;
}
}
boolean t=false;
for(int k=i-1;k>=0;k--)
{
if(tok[i].equals(tok[k]))
{
t=true;
}
}
if(!t)
{
System.out.print(tok[i]+"="+c+" ");
}
}
}
}
| [
"bollenasanthosh@gmail.com"
] | bollenasanthosh@gmail.com |
330e0d885fd444f7e72a3c67eccb099e11b098d5 | be73270af6be0a811bca4f1710dc6a038e4a8fd2 | /crash-reproduction-moho/results/XRENDERING-418-1-13-SPEA2-WeightedSum:TestLen:CallDiversity/com/xpn/xwiki/doc/DefaultDocumentAccessBridge_ESTest.java | f147d42e59cfab8bb110c79d7ec86dcebeb013d8 | [] | 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 | 578 | java | /*
* This file was automatically generated by EvoSuite
* Mon Apr 06 10:13:24 UTC 2020
*/
package com.xpn.xwiki.doc;
import org.junit.Test;
import static org.junit.Assert.*;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true)
public class DefaultDocumentAccessBridge_ESTest extends DefaultDocumentAccessBridge_ESTest_scaffolding {
@Test
public void notGeneratedAnyTest() {
// EvoSuite did not generate any tests
}
}
| [
"pouria.derakhshanfar@gmail.com"
] | pouria.derakhshanfar@gmail.com |
8c1303afda85757f397284c8a4bc7db289356a11 | a1029a8e2f152dd9990f2012cac72edfcf898ee8 | /src/main/java/bank/ocr/FileUtil.java | 50ecdc5ab8864a5b1a129694be9c01476ac0685b | [] | no_license | mihailrc/bankOcr | 2271a6055832ee0a3cc8a6e2c8aa7330dd10d91e | ae1b99361bd888f7196d6a0ef6c3b45de95b2e58 | refs/heads/master | 2021-01-21T00:00:52.474034 | 2016-04-13T12:15:22 | 2016-04-13T12:15:22 | 14,602,974 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,162 | java | package bank.ocr;
import java.io.*;
public class FileUtil {
public static final int BUFFER_SIZE = 4096;
public static int copy(Reader in, Writer out) throws IOException {
try {
int byteCount = 0;
char[] buffer = new char[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
return byteCount;
} finally {
try {
in.close();
} catch (IOException ex) {
}
try {
out.close();
} catch (IOException ex) {
}
}
}
public static String readToString(File in) throws IOException {
StringWriter out = new StringWriter();
copy(new FileReader(in), out);
return out.toString();
}
public static void writeToFile(String contents, File out) throws IOException {
FileWriter fw = new FileWriter(out);
StringReader sr = new StringReader(contents);
copy(sr, fw);
}
}
| [
"mihailrc@gmail.com"
] | mihailrc@gmail.com |
222bfa718b2c0c86c196f2604bf5fdaaeb096ada | af2482fde6ea6942726682474d6f196510ab2b78 | /PhotoClient/app/src/main/java/edwin/team/com/photoclient/Classes/ImageAdapterPickPhoto.java | 7571bb06c4cac22e0df27474350c31616ad50e33 | [] | no_license | Algarode/PTS4 | c12eddcb041442fdb836c9cf118b33f0389119b5 | f5805ab3a741668b4b946a6637ee005bd940aae4 | refs/heads/master | 2021-01-17T14:36:13.223243 | 2015-01-20T10:47:06 | 2015-01-20T10:47:06 | 23,931,241 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,664 | java | package edwin.team.com.photoclient.Classes;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.ArrayList;
import edwin.team.com.photoclient.Activities.EditPickPhotoActivity;
import edwin.team.com.photoclient.Activities.PickPhotoActivity;
import edwin.team.com.photoclient.R;
/**
* Created by Edwin on 11-1-2015.
*/
public class ImageAdapterPickPhoto extends BaseAdapter {
private Context context;
private ArrayList<ImageCollection> collection;
private VolleyHelper helper = AppController.getVolleyHelper();
private ImageLoader imageLoader;
private boolean isEditPickPhoto;
public ImageAdapterPickPhoto(Context context, ArrayList<ImageCollection> collection, boolean isEditPickPhoto) {
this.context = context;
this.collection = collection;
this.imageLoader = helper.getImageLoader();
this.isEditPickPhoto = isEditPickPhoto;
}
@Override
public int getCount() {
return collection.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.image_grid_pickphoto, null);
final ImageCollection col = collection.get(position);
final NetworkImageView image = (NetworkImageView )view.findViewById(R.id.grid_item_photo);
image.setImageUrl(collection.get(position).getImageUrl(),imageLoader);
image.setDefaultImageResId(R.drawable.loading);
image.setErrorImageResId(R.drawable.error);
image.setId(position);
final RadioButton rbut = (RadioButton) view.findViewById(R.id.grid_item_radiobutton);
rbut.setTag(position);
if(col.isChecked())
rbut.setChecked(true);
rbut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!isEditPickPhoto)
((PickPhotoActivity)context).onRbImageChecked(col,image);
else
((EditPickPhotoActivity)context).onRbImageChecked(rbut);
}
});
return view;
}
}
| [
"edwin.lambregts0@gmail.com"
] | edwin.lambregts0@gmail.com |
672b65d13be684ce2e0719a6e85b19dde96c462d | bb2d8e294e03370ebc2be07074c0428ca93b6e7d | /Final/HRPS/src/model/RoomServiceItem.java | af0e941c8a90a98e8d374606780fd9cad99114ec | [] | no_license | shantanuj/2002MovieBookingSystem | 85bb153e565f4e2ac62829c3b5a24c32410d0592 | 4708cc8787cdfe5ff9e5d23ce5348585ed4b1144 | refs/heads/master | 2020-04-17T06:56:50.264401 | 2016-09-10T04:33:07 | 2016-09-10T04:33:07 | 67,573,885 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,464 | java | package model;
public class RoomServiceItem {
/**
* The name of this Room Service Item.
*/
private String name;
/**
* The description of this Room Service Item.
*/
private String description;
/**
* The price of this Room Service Item.
*/
private double price;
/**
* Gets the name of this Room Service Item.
* @return this RoomServiceItem's name.
*/
public String getName() {
return name;
}
/**
* Sets the name of this Room Service Item.
* @param name this RoomServiceItem's name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the description of this Room Service Item.
* @return this RoomServiceItem's description.
*/
public String getDescription() {
return description;
}
/**
* Sets the description of this Room Service Item.
* @param description this RoomServiceItem's description.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Gets the price of this Room Service Item.
* @return this RoomServiceItem's price.
*/
public double getPrice() {
return price;
}
/**
* Sets the price of this Room Service Item.
* @param price this RoomServiceItem's price.
*/
public void setPrice(double price) {
this.price = price;
}
}
| [
"shantanu12jswl@gmail.com"
] | shantanu12jswl@gmail.com |
45c51efaa7b3e3f25a3d8ab6b63b2ca83cf4c993 | 72c01f86724d708abf9423145d3c8dc076961c2f | /GangSDK/src/main/java/com/qm/gangsdk/ui/custom/button/XLRecorderButton.java | 48fe9293eec529baea674ba389c1460ff97672c9 | [] | no_license | qq474141627/who | 3fd0fde7603f4f06f549c375dced9cc51fdb3187 | 482c35d07450047c605292a6a1edd9b7748a4e80 | refs/heads/master | 2020-03-08T04:17:49.470844 | 2018-04-03T14:27:42 | 2018-04-03T14:27:42 | 127,917,024 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,310 | java | package com.qm.gangsdk.ui.custom.button;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
import com.qm.gangsdk.ui.custom.dialog.ViewTools;
import com.qm.gangsdk.ui.utils.FileSaveUtil;
import com.qm.gangsdk.ui.utils.XLToastUtil;
import java.io.IOException;
public class XLRecorderButton extends Button {
private static final int STATE_UNRECORD = 1;
private static final int STATE_START_RECORD = 2;
private static final int STATE_RECORDING = 3;
private static final int STATE_WANT_RECORD = 4;
private static final int STATE_WANT_CANCEL = 5;
private static final int STATE_FINISH = 6;
private static final int STATE_CANCEL = 7;
private static final int DISTANCE_Y_CANCEL = 50;
private static final int OVERTIME = 60;
private int mCurrentState = STATE_UNRECORD;
private float mTime = 0;
private XLRecorder recorder;
private boolean canRecord = true;
/**
* 先实现两个参数的构造方法,布局会默认引用这个构造方法, 用一个 构造参数的构造方法来引用这个方法 * @param context
*/
public XLRecorderButton(Context context) {
this(context, null);
// TODO Auto-generated constructor stub
}
public XLRecorderButton(Context context, AttributeSet attrs) {
super(context, attrs);
recorder = new XLRecorder();
}
public void setRecordable(boolean canRecord){
this.canRecord = canRecord;
}
/**
* 录音完成后的回调,回调给activiy,可以获得mtime和文件的路径
*/
public interface OnRecorderStateListener {
void onUnrecord();
void onStartRecord();
void onRecording(float seconds);
void onWantRecord();
void onWantCancel();
void onFinish(boolean success, float seconds);
}
private OnRecorderStateListener onRecorderStateListener;
public void setOnRecorderStateListener(OnRecorderStateListener onRecorderStateListener) {
this.onRecorderStateListener = onRecorderStateListener;
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
int action = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
setState(STATE_START_RECORD);
break;
case MotionEvent.ACTION_MOVE:
if (recorder.isRecording()) {
// 根据x,y来判断用户是否想要取消
if (wantToCancel(x, y)) {
setState(STATE_WANT_CANCEL);
} else {
setState(STATE_WANT_RECORD);
}
}
break;
case MotionEvent.ACTION_UP:
// 如果按的时间太短,还没准备好或者时间录制太短,就离开了,则显示这个dialog
if (!recorder.isRecording() || mTime < 0.6f) {
setState(STATE_CANCEL);
} else if (mCurrentState == STATE_WANT_RECORD) {// 正常录制结束
setState(STATE_FINISH);
} else if (mCurrentState == STATE_WANT_CANCEL) {
setState(STATE_CANCEL);
}
reset();// 恢复标志位
break;
case MotionEvent.ACTION_CANCEL:
reset();
break;
}
return true;
// return super.onTouchEvent(event);
}
/**
* 回复标志位以及状态
*/
private void reset() {
setState(STATE_UNRECORD);
mTime = 0;
}
private boolean wantToCancel(int x, int y) {
// TODO Auto-generated method stub
if (x < 0 || x > getWidth()) {// 判断是否在左边,右边,上边,下边
return true;
}
if (y < -DISTANCE_Y_CANCEL || y > getHeight() + DISTANCE_Y_CANCEL) {
return true;
}
return false;
}
private void setState(int state) {
// TODO Auto-generated method stub
if (mCurrentState != state) {
mCurrentState = state;
switch (mCurrentState) {
case STATE_UNRECORD:
if(onRecorderStateListener != null){
onRecorderStateListener.onUnrecord();
}
break;
case STATE_START_RECORD:
if(onRecorderStateListener != null){
onRecorderStateListener.onStartRecord();
}
if(canRecord){
if(recorder.startRecord()){
new Thread(mGetVoiceLevelRunnable).start();
}else{
XLToastUtil.showToastShort("点击太频繁了");
onRecorderStateListener.onUnrecord();
}
}
break;
case STATE_RECORDING:
break;
case STATE_WANT_RECORD:
if(onRecorderStateListener != null){
onRecorderStateListener.onWantRecord();
}
break;
case STATE_WANT_CANCEL:
if(onRecorderStateListener != null){
onRecorderStateListener.onWantCancel();
}
break;
case STATE_FINISH:
recorder.stopRecord();
if(onRecorderStateListener != null){
// BigDecimal b = new BigDecimal(mTime);
// float f1 = b.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
onRecorderStateListener.onFinish(true, mTime);
}
break;
case STATE_CANCEL:
recorder.stopRecord();
if(onRecorderStateListener != null){
onRecorderStateListener.onFinish(false, 0);
}
break;
}
}
}
public XLRecorder getRecorder(){
if(recorder == null){
recorder = new XLRecorder();
}
return recorder;
}
// 准备三个常量
private static final int MSG_AUDIO_PREPARED = 0X110;
private static final int MSG_VOICE_CHANGE = 0X111;
private static final int MSG_DIALOG_DIMISS = 0X112;
private static final int MSG_OVERTIME_SEND = 0X113;
private Handler mhandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_AUDIO_PREPARED:
break;
case MSG_VOICE_CHANGE:
if(onRecorderStateListener != null){
onRecorderStateListener.onRecording(mTime);
}
break;
case MSG_DIALOG_DIMISS:
break;
case MSG_OVERTIME_SEND:
setState(STATE_FINISH);
break;
}
}
;
};
// 获取音量大小的runnable
private Runnable mGetVoiceLevelRunnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (recorder.isRecording()) {
try {
Thread.sleep(100);
mTime += 0.1f;
mhandler.sendEmptyMessage(MSG_VOICE_CHANGE);
if (mTime >= OVERTIME) {
mTime = OVERTIME;
mhandler.sendEmptyMessage(MSG_OVERTIME_SEND);
break;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
}
| [
"752387519@qq.com"
] | 752387519@qq.com |
29d4fd86bf2e720e1eb8b992a37852d6c66f1bb7 | 85803bf95187b74431e10efee2a2086edb5df81e | /Binary_Tree_Preorder_Traversal/Iterative/Solution.java | 8a23c17252e88a84eb641b0439a0f9873c1ab906 | [] | no_license | congyue/Leetcode | cf2d2a8b2f2c068fbffd99e122ef2a61deacde37 | 8c60189739e78261e5995472c041a065f09a6881 | refs/heads/master | 2021-03-27T10:18:28.282651 | 2015-10-04T22:05:23 | 2015-10-04T22:05:23 | 25,962,526 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,277 | java | import java.util.*;
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new LinkedList<Integer>();
if (root == null)
return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode cur = stack.pop();
if (cur == null)
continue;
result.add(cur.val);
stack.push(cur.right);
stack.push(cur.left);
}
return result;
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; left = null; right = null; }
}
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode root = new TreeNode(1);
root.right = new TreeNode(2);
root.right.left = new TreeNode(3);
System.out.println(solution.preorderTraversal(root));
}
public static List<String> serialized(TreeNode t) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<String> result = new ArrayList<String>();
queue.add(t);
while(!queue.isEmpty()) {
TreeNode newNode = queue.remove();
if (newNode != null)
result.add(Integer.toString(newNode.val));
else {
result.add("#");
continue;
}
queue.add(newNode.left);
queue.add(newNode.right);
}
return result;
}
}
| [
"congyue@Congyues-iMac.local"
] | congyue@Congyues-iMac.local |
89d13e5690077d0c877f479c532ee79fab08db26 | 74d2705d91e9313ac5be48f9d73887f64da52f6a | /src/main/java/designPatterns/behavioural/observer/com/one/impl/StockObserver.java | eaf5da9dda78fe1be4565ddf1ef5df10e854b814 | [] | no_license | prashant146/datastructuresalgorithms | 733b06ee8f33bbea450ef145cdbdd66f1e95c918 | ad5b85867091fc6dfc1b7b31b311519a503346f8 | refs/heads/master | 2021-05-12T11:02:52.444096 | 2020-09-02T15:19:35 | 2020-09-02T15:19:35 | 117,377,419 | 0 | 0 | null | 2020-10-14T00:22:40 | 2018-01-13T20:52:21 | Java | UTF-8 | Java | false | false | 1,060 | java | package designPatterns.behavioural.observer.com.one.impl;
import designPatterns.behavioural.observer.com.one.Observer;
import designPatterns.behavioural.observer.com.one.Subject;
public class StockObserver implements Observer {
private double ibmPrice;
private double aaplPrice;
private double googPrice;
private static int observerIDTracker = 0;
private int observerID;
private Subject stockGrabber;
public StockObserver(Subject stockGrabber){
this.stockGrabber = stockGrabber;
this.observerID = ++observerIDTracker;
System.out.println("New Observer " + this.observerID);
stockGrabber.register(this);
}
@Override
public void update(double ibm, double apple, double yahoo) {
this.ibmPrice = ibm;
this.aaplPrice = apple;
this.googPrice = yahoo;
printThePrices();
}
public void printThePrices(){
System.out.println(observerID + "\nIBM: " + ibmPrice + "\nAAPL: " +
aaplPrice + "\nGOOG: " + googPrice + "\n");
}
}
| [
"prashant146"
] | prashant146 |
bd36303de137877fdaf50a14b00524a4a16de031 | 207a9294c0f6c024ae8d8f989c06e385fe7e5904 | /src/main/java/com/sofang/base/HouseSort.java | 78ba8b975d542566d3606c18eb70770baa3c533c | [] | no_license | GodNoBug/sofang | 4968a3d1e28be6758a6945532583ea27d2b01295 | 65ada51867dff87901a6410b0bd27adc953c823d | refs/heads/master | 2021-07-05T12:49:49.840641 | 2020-09-12T10:56:26 | 2020-09-12T10:56:26 | 173,574,459 | 0 | 0 | null | 2019-03-03T12:52:04 | 2019-03-03T12:52:04 | null | UTF-8 | Java | false | false | 1,042 | java | package com.sofang.base;
import java.util.Set;
import org.springframework.data.domain.Sort;
import com.google.common.collect.Sets;
/**
* 排序生成器
* Created by gegf
*/
public class HouseSort {
public static final String DEFAULT_SORT_KEY = "lastUpdateTime";
public static final String DISTANCE_TO_SUBWAY_KEY = "distanceToSubway";
private static final Set<String> SORT_KEYS = Sets.newHashSet(
DEFAULT_SORT_KEY,
"createTime",
"price",
"area",
DISTANCE_TO_SUBWAY_KEY
);
public static Sort generateSort(String key, String directionKey) {
key = getSortKey(key);
Sort.Direction direction = Sort.Direction.fromStringOrNull(directionKey);
if (direction == null) {
direction = Sort.Direction.DESC;
}
return new Sort(direction, key);
}
public static String getSortKey(String key) {
if (!SORT_KEYS.contains(key)) {
key = DEFAULT_SORT_KEY;
}
return key;
}
}
| [
"849447894@qq.com"
] | 849447894@qq.com |
ea6696b1ce6e5b2cfaf2d4636e513e6f0f8e20de | f6736b669713c08483548527ff11cc5388189da8 | /src/KeywordDriven_Framework/Excution.java | 246ae0c05b9b01f84fdfa40e9284dbc82175217c | [] | no_license | shraddha03salvi/POI | 54817afbdf5043c6cd635c5199d1262bdc779855 | 8aa3534b2af9793a2cb560e228131a03e7ac95d9 | refs/heads/master | 2020-07-17T17:14:13.030503 | 2019-09-03T11:28:11 | 2019-09-03T11:28:11 | 188,956,050 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,165 | java | package KeywordDriven_Framework;
public class Excution {
public static void main(String[] args) throws Exception {
String path ="E:\\ExcelData\\TestCases.xlsx";
ExcelUtility.setExcel(path,1);
for(int i=0;i<=6;i++)
{
String keyword = ExcelUtility.getData(i,6);
if(keyword.equals("OpenBrowser"))
{
ActionKeywords.OpenBrowser();
System.out.println("Open browser successfully");
}
// else if(keyword.equals("navigate"))
// {
// ActionKeywords.navigate();
// System.out.println("Navigate to Url successfully");
//
// }
else if(keyword.equals("Sendkeys_Textfield"))
{
ActionKeywords.Sendkeys_Textfield();
System.out.println("Pass Username successfully");
}
else if(keyword.equals("Sendkeys_Textfield1"))
{
ActionKeywords.Sendkeys_Textfield1();
System.out.println("Pass password successfully");
}
else if(keyword.equals("Click"))
{
ActionKeywords.Click();
System.out.println("Click on Login successfully");
}
else if(keyword.equals("closeBrowser"))
{
ActionKeywords.closeBrowser();
System.out.println("close driver successfully");
}
}
}
} | [
"shraddha12salvi@gmail.com"
] | shraddha12salvi@gmail.com |
88331e20c386479bbb1ae14655c5637367d0885c | e5e048e558af1b5e1d5f925d91bec468c9ae275a | /src/controlFlow_Statements/Student_if_else_if_ladder.java | 9a18ae8bbcb67869e226e1d4bc4fa70406d1dde2 | [] | no_license | JaydeepUniverse/java_core | e1857a041ae8054066f87d7b8384ae722b4eb57b | ab74c920cca88ef315a51f54c52d93f9b37b2818 | refs/heads/master | 2021-10-09T11:32:49.525628 | 2018-12-27T05:52:22 | 2018-12-27T05:52:22 | 153,394,040 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 578 | java | package controlFlow_Statements;
import java.util.Scanner;
public class Student_if_else_if_ladder {
public static void main(String[] args) {
Scanner s1=new Scanner(System.in);
System.out.println("Enter your marks: ");
int m=s1.nextInt();
if (m>40 && m<=50) {
System.out.println("Third Grade");
}
else if (m>50 && m<=60) {
System.out.println("Second Grade");
}
else if (m>60 && m<=70) {
System.out.println("First Grade");
}
else if (m>70){
System.out.println("Distinction");
}
else {
System.out.println("Fail");
}
s1.close();
}
}
| [
"ecjaydeepsoni@gmail.com"
] | ecjaydeepsoni@gmail.com |
24ea8455e6a42f5efc8aad3feb90cd5523ab68b5 | 192f8b6b57e3f8feb0e06f06f1f909b34ae725e0 | /trunk/radio_web/src/main/java/no/radio/web/server/resource/RapporterRadioStartServerResourceHTML.java | 67cc9a21fcc077b18b492c1fac9826c5808731f1 | [] | no_license | olufjen/acemradio | b20bf5dbf33913dd25e11eacb96ae51814011f01 | 0c249516700d8435e8fbac15d8a72d962c4b8727 | refs/heads/master | 2022-09-11T14:24:41.163173 | 2022-08-23T07:36:23 | 2022-08-23T07:36:23 | 48,162,132 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,660 | java | package no.radio.web.server.resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import no.radio.web.model.FileModel;
import org.restlet.Request;
import org.restlet.data.Form;
import org.restlet.data.LocalReference;
import org.restlet.data.MediaType;
import org.restlet.data.Parameter;
import org.restlet.data.Reference;
import org.restlet.ext.freemarker.TemplateRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import freemarker.template.SimpleScalar;
/**
* @author olj
* Denne resursen er knyttet til startsiden for radio applikasjonen
*/
public class RapporterRadioStartServerResourceHTML extends RadioSessionServer {
private String delMelding = "delmelding";
private String meldeTxtId = "melding";
private String passordCheck = "none";
private String displayPassord = "passord";
public String getDisplayPassord() {
return displayPassord;
}
public void setDisplayPassord(String displayPassord) {
this.displayPassord = displayPassord;
}
public String getPassordCheck() {
return passordCheck;
}
public void setPassordCheck(String passordCheck) {
this.passordCheck = passordCheck;
}
public String getDelMelding() {
return delMelding;
}
public void setDelMelding(String delMelding) {
this.delMelding = delMelding;
}
public String getMeldeTxtId() {
return meldeTxtId;
}
public void setMeldeTxtId(String meldeTxtId) {
this.meldeTxtId = meldeTxtId;
}
/**
* getStartpage
* Denne rutinen starter med startside.html
* Denne rutinen henter inn nødvendige session objekter og setter opp nettsiden for Acem radio
* @return
*/
@Get
public Representation getStartpage() {
Reference reference = new Reference(getReference(),"..").getTargetRef();
Request request = getRequest();
FileModel translist = new FileModel();
translist.setFilePath("c:\\ullern\\acem\\radio\\translist.txt");
translist.createLines();
Stream lines = translist.getLines();
String firstLine = "tom";
DateTimeFormatter translistformatter = DateTimeFormatter.ofPattern("uuuu-MM-dd");
List sendeListe = translist.sendeListe();
int len = sendeListe.size();
String sisteLinje = (String)sendeListe.get(len-1);
char sep = '-';
String sisteDato = "20" + translist.extractString(sisteLinje,sep,0);
Map<String, Object> dataModel = new HashMap<String, Object>();
startDato = LocalDate.parse(sisteDato, translistformatter);
String meldingsText = " ";
SimpleScalar simple = new SimpleScalar(meldingsText);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MMM.yyyy");
LocalDate sluttDato = LocalDate.now();
String formEndDate = sluttDato.format(formatter);
String formDate = startDato.format(formatter);
// LocalDate formStartdate = LocalDate.parse(formDate);
dataModel.put(meldeTxtId,simple );
dataModel.put(startDatoId, formDate);
dataModel.put(sluttdatoId, formEndDate);
// SimpleScalar pwd = new SimpleScalar(passordCheck);
// dataModel.put(displayPassord,pwd);
sessionAdmin.setSessionObject(request, formDate, startDatoId);
sessionAdmin.setSessionObject(request, startDato, startdatoDate);
sessionAdmin.setSessionObject(request, translist, fileModelId);
LocalReference pakke = LocalReference.createClapReference(LocalReference.CLAP_CLASS,
"/radio");
LocalReference localUri = new LocalReference(reference);
// Denne client resource forholder seg til src/main/resource katalogen !!!
ClientResource clres2 = new ClientResource(LocalReference.createClapReference(LocalReference.CLAP_CLASS,"/radio/startside.html"));
Representation pasientkomplikasjonFtl = clres2.get();
TemplateRepresentation templatemapRep = new TemplateRepresentation(pasientkomplikasjonFtl,dataModel,
MediaType.TEXT_HTML);
return templatemapRep;
}
/**
* storeHemovigilans
* Denne rutinen rutinen kjøres dersom epost og passord er gitt fra bruker.
* Den tar imot epost og passord og henter frem riktig meldingsinformasjon fra
* databasen basert på melders id
* @param form
* @return
*/
/**
* @param form
* @return
*/
@Post
public Representation storestartPage(Form form) {
Map<String, Object> dataModel = new HashMap<String, Object>();
Request request = getRequest();
FileModel translist = (FileModel)sessionAdmin.getSessionObject(request, fileModelId);
translist.setFilePath("c:\\ullern\\acem\\radio\\translist.txt");
translist.createLines();
Stream lines = translist.getLines();
List sendeListe = translist.sendeListe();
String firstLine = "tom";
/* try {
firstLine = translist.readlines((BufferedReader r) -> r.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(firstLine);*/
/* Map<String,List> alleMeldinger = new HashMap<String,List>();
List<Vigilansmelding> meldinger = null;
// List delMeldinger = null;
List<Vigilansmelding> andreMeldinger = null;
List<Vigilansmelding> pasientMeldinger = null;
List<Vigilansmelding> giverMeldinger = null;*/
if(form == null){
invalidateSessionobjects();
}
/*
* Verdier angitt av bruker
*/
String melderEpost = null;
String melderPassord = null;
String meldingsNokkel = null;
/*
* Verdier fra database
*/
String name ="";
String passord = "";
Long melderid = null;
Parameter nyttPassord = form.getFirst("nyttpassord");
String page = "../hemovigilans/melder_rapport.html";
LocalDate sluttDato = null;
LocalDate startDato = (LocalDate) sessionAdmin.getSessionObject(request, startdatoDate);
DateTimeFormatter endformatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
for (Parameter entry : form) {
if (entry.getValue() != null && !(entry.getValue().equals(""))){
System.out.println(entry.getName() + "=" + entry.getValue());
if (entry.getName().equals("slutt-date")){
// sluttDato.parse(entry.getValue());
sluttDato = LocalDate.parse(entry.getValue(), endformatter);
}
}
}
Parameter formValue = form.getFirst("datohendt"); // Bruker oppgir sluttdato
sendeListe = translist.createNewLines(startDato, sluttDato, sendeListe);
lines = translist.getLines();
Stream newList = sendeListe.stream();
translist.writetoFile(newList);
int size = sendeListe.size();
String endD = (String) sendeListe.get(size-1);
System.out.println("Sendeliste har "+size+" elementer Siste element "+endD);
Reference reference = new Reference(getReference(),"..").getTargetRef();
String meldingsText = " ";
SimpleScalar simple = new SimpleScalar(meldingsText);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MMM.yyyy");
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-dd-MM");
String formDate = startDato.format(formatter);
String formEndDate = sluttDato.format(formatter);
// LocalDate formStartdate = LocalDate.parse(formDate);
dataModel.put(meldeTxtId,simple );
dataModel.put(startDatoId, formDate);
dataModel.put(sluttdatoId, formEndDate);
// SimpleScalar pwd = new SimpleScalar(passordCheck);
// dataModel.put(displayPassord,pwd);
LocalReference pakke = LocalReference.createClapReference(LocalReference.CLAP_CLASS,
"/radio");
LocalReference localUri = new LocalReference(reference);
//Denne client resource forholder seg til src/main/resource katalogen !!!
ClientResource clres2 = new ClientResource(LocalReference.createClapReference(LocalReference.CLAP_CLASS,"/radio/startside.html"));
Representation pasientkomplikasjonFtl = clres2.get();
TemplateRepresentation templatemapRep = new TemplateRepresentation(pasientkomplikasjonFtl,dataModel,
MediaType.TEXT_HTML);
return templatemapRep;
}
}
| [
"olufjen@gmail.com"
] | olufjen@gmail.com |
f9853d22b3f5a6196619e0235d7ace8173924f8b | 41898abc4b9e37589ddaff8b64b581e072fc097f | /services/osm/src/main/java/com/huaweicloud/sdk/osm/v2/model/DeleteAccessoriesRequest.java | 2a4da3d71c876db9a7b9692bd3f16a2bbee55501 | [
"Apache-2.0"
] | permissive | jierui001/huaweicloud-sdk-java-v3 | 55f5ee27973bf38cef2b80d19e6d31547c506e3f | a14a19255d2890784a4e9cea05076d2d76ac3ebd | refs/heads/master | 2022-12-27T04:54:25.594241 | 2020-09-30T02:49:42 | 2020-09-30T02:49:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,187 | java | package com.huaweicloud.sdk.osm.v2.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.function.Consumer;
import java.util.Objects;
/**
* Request Object
*/
public class DeleteAccessoriesRequest {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="accessory_id")
private String accessoryId;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="X-Site")
private Integer xSite;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="X-Language")
private String xLanguage;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="X-Time-Zone")
private String xTimeZone;
public DeleteAccessoriesRequest withAccessoryId(String accessoryId) {
this.accessoryId = accessoryId;
return this;
}
/**
* Get accessoryId
* @return accessoryId
*/
public String getAccessoryId() {
return accessoryId;
}
public void setAccessoryId(String accessoryId) {
this.accessoryId = accessoryId;
}
public DeleteAccessoriesRequest withXSite(Integer xSite) {
this.xSite = xSite;
return this;
}
/**
* Get xSite
* minimum: 0
* maximum: 1
* @return xSite
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="")
public Integer getXSite() {
return xSite;
}
public void setXSite(Integer xSite) {
this.xSite = xSite;
}
public DeleteAccessoriesRequest withXLanguage(String xLanguage) {
this.xLanguage = xLanguage;
return this;
}
/**
* Get xLanguage
* @return xLanguage
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="")
public String getXLanguage() {
return xLanguage;
}
public void setXLanguage(String xLanguage) {
this.xLanguage = xLanguage;
}
public DeleteAccessoriesRequest withXTimeZone(String xTimeZone) {
this.xTimeZone = xTimeZone;
return this;
}
/**
* Get xTimeZone
* @return xTimeZone
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="")
public String getXTimeZone() {
return xTimeZone;
}
public void setXTimeZone(String xTimeZone) {
this.xTimeZone = xTimeZone;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeleteAccessoriesRequest deleteAccessoriesRequest = (DeleteAccessoriesRequest) o;
return Objects.equals(this.accessoryId, deleteAccessoriesRequest.accessoryId) &&
Objects.equals(this.xSite, deleteAccessoriesRequest.xSite) &&
Objects.equals(this.xLanguage, deleteAccessoriesRequest.xLanguage) &&
Objects.equals(this.xTimeZone, deleteAccessoriesRequest.xTimeZone);
}
@Override
public int hashCode() {
return Objects.hash(accessoryId, xSite, xLanguage, xTimeZone);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DeleteAccessoriesRequest {\n");
sb.append(" accessoryId: ").append(toIndentedString(accessoryId)).append("\n");
sb.append(" xSite: ").append(toIndentedString(xSite)).append("\n");
sb.append(" xLanguage: ").append(toIndentedString(xLanguage)).append("\n");
sb.append(" xTimeZone: ").append(toIndentedString(xTimeZone)).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(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
33121128ce3ffb1b29e2939b692e3d7e9e78ebca | 4a4baf8410fefc4326555aa7f8ae74703b000a7f | /Apollo/src/com/apollo/messages/EntityRemovedMessage.java | 19e60158ea8be1599795b221a6bc135352c0b323 | [
"BSD-2-Clause",
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-freemarker"
] | permissive | egyware/fp4g | 6fd84a538df6c88f39b8f627d8d1df45dbe88227 | 60ebb5bde0c52ea60b62bcf3e87aa5e799d7f49b | refs/heads/master | 2021-01-19T18:30:52.415711 | 2015-07-03T15:44:33 | 2015-07-03T15:44:33 | 12,302,601 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 263 | java | package com.apollo.messages;
import com.apollo.Entity;
import com.apollo.Message;
public class EntityRemovedMessage extends Message
{
public Entity entity;
@Override
public Class<? extends Message> getType()
{
return EntityRemovedMessage.class;
}
}
| [
"egyware@gmail.com"
] | egyware@gmail.com |
1a94d327de60adb38e0738cd2987629eefc71599 | d55e5e6ae7bf7b20051d2ecfed8906a38ef24145 | /src/main/java/leon/ssi/test/person.java | c36dc0b83f6ffe99bb4c051f41e8ba4e6cc38446 | [] | no_license | huoex/tssm | b3cfa25f78f317dba60a9673be9697fd19807805 | e6065ede29c3d964b649e124e22821528330844e | refs/heads/master | 2016-09-05T20:17:25.456440 | 2015-07-02T07:08:19 | 2015-07-02T07:08:19 | 29,567,424 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 165 | java | package leon.ssi.test;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
@Service
public class person {
@Resource
friend frd;
}
| [
"huoex0628@gmail.com"
] | huoex0628@gmail.com |
93a7b4823ec29e08a50e23826caa82d69f8e34de | a3a5aeb018ab1c3e92f924e13c7e290eeec6bd06 | /workspace2/NetworkProgramme/src/com/_520it/day01/UDP/Send.java | e06226f01fd028d627fc766c1d8653ae73de59ed | [] | no_license | qyl1006/JavaApps | bc21a25d9a28e98f83227af6b54b6b4859a7ff30 | e47445194677531babcc7a20c8fd334f253682e1 | refs/heads/master | 2021-05-15T07:44:26.776608 | 2018-03-09T14:37:21 | 2018-03-09T14:37:21 | 111,789,114 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 541 | java | package com._520it.day01.UDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
//发送端
public class Send {
public static void main(String[] args) throws Exception {
String str = "我欲成仙,快乐齐天----测试Ing";
//创建发送端对象
DatagramSocket send = new DatagramSocket(10011);
DatagramPacket p = new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getLocalHost(), 10086);
send.send(p);
send.close();
}
}
| [
"yuelinshi@qq.com"
] | yuelinshi@qq.com |
ef189844fef33f3c96b16e30314c20bc18c19402 | e83c2bbed55681f4f6386af2820dff65cd5fa8a6 | /app/src/main/java/com/ubergeek42/WeechatAndroid/Weechat.java | db721ed1c541dae25e3bd188d37df49053120538 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | hlmtre/weechat-android | ccbe1c38a18f0da3051731642a0bdd5bbcbf0612 | 4a8984d133434f111d6ce689122f5335279bb169 | refs/heads/master | 2022-11-10T16:56:02.807280 | 2020-05-06T02:28:23 | 2020-05-06T02:28:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,723 | java | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package com.ubergeek42.WeechatAndroid;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import androidx.annotation.StringRes;
import android.widget.Toast;
import com.ubergeek42.WeechatAndroid.service.Events;
import com.ubergeek42.WeechatAndroid.service.Notificator;
import com.ubergeek42.WeechatAndroid.service.P;
import com.ubergeek42.WeechatAndroid.service.RelayService.STATE;
import com.ubergeek42.cats.Cat;
import com.ubergeek42.cats.Cats;
import org.greenrobot.eventbus.EventBus;
import java.util.EnumSet;
@SuppressWarnings("unused")
public class Weechat extends Application {
static Thread mainThread = Thread.currentThread();
static Handler mainHandler = new Handler();
static Context applicationContext;
@Override public void onCreate() {
super.onCreate();
applicationContext = getApplicationContext();
Cats.setup(applicationContext);
P.init(getApplicationContext());
P.restoreStuff();
Notificator.init(this);
EventBus.builder().logNoSubscriberMessages(false).eventInheritance(false).installDefaultEventBus();
EventBus.getDefault().postSticky(new Events.StateChangedEvent(EnumSet.of(STATE.STOPPED)));
}
////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// main thread
////////////////////////////////////////////////////////////////////////////////////////////////
// like runOnUiThread, but always queue
public static void runOnMainThread(Runnable action) {
mainHandler.post(action);
}
public static void runOnMainThread(Runnable action, long delay) {
mainHandler.postDelayed(action, delay);
}
public static void runOnMainThreadASAP(Runnable action) {
if (Thread.currentThread() == mainThread) action.run();
else mainHandler.post(action);
}
////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// toasts
////////////////////////////////////////////////////////////////////////////////////////////////
@Cat public static void showShortToast(final String message) {
mainHandler.post(() -> Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show());
}
public static void showShortToast(final String message, final Object... args) {
showShortToast(String.format(message, args));
}
public static void showShortToast(final @StringRes int id) {
showShortToast(applicationContext.getResources().getString(id));
}
public static void showShortToast(final @StringRes int id, final Object... args) {
showShortToast(applicationContext.getResources().getString(id, args));
}
@Cat public static void showLongToast(final String message) {
mainHandler.post(() -> Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show());
}
public static void showLongToast(final String message, final Object... args) {
showLongToast(String.format(message, args));
}
public static void showLongToast(final @StringRes int id) {
showLongToast(applicationContext.getResources().getString(id));
}
public static void showLongToast(final @StringRes int id, final Object... args) {
showLongToast(applicationContext.getResources().getString(id, args));
}
}
| [
"oakkitten@users.noreply.github.com"
] | oakkitten@users.noreply.github.com |
6e3904d5371114744ca487ead2ddd87f70962daf | 8e248d45c789e8fc5e2a3be30a6b56f07a72b56d | /app/src/main/java/de/foodora/android/automapper/model/ParentModel.java | 9e31ab587eb2890e6dce0263a89224d97838457b | [
"Apache-2.0"
] | permissive | foodora/android-auto-mapper | d17e35eb64815536dd00a41b581f787825949d75 | 282350483c5a18c7ca7c799b01c52966f60997e4 | refs/heads/master | 2021-01-20T08:41:40.697283 | 2017-05-08T06:57:37 | 2017-05-08T06:57:37 | 90,180,193 | 5 | 1 | null | 2017-05-08T06:51:55 | 2017-05-03T18:22:25 | Java | UTF-8 | Java | false | false | 1,224 | java | package de.foodora.android.automapper.model;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
public class ParentModel implements Parcelable {
public String name;
public String description;
public List<ChildModel> children;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeString(this.description);
dest.writeList(this.children);
}
public ParentModel() {
}
protected ParentModel(Parcel in) {
this.name = in.readString();
this.description = in.readString();
this.children = new ArrayList<ChildModel>();
in.readList(this.children, ChildModel.class.getClassLoader());
}
public static final Parcelable.Creator<ParentModel> CREATOR = new Parcelable.Creator<ParentModel>() {
@Override
public ParentModel createFromParcel(Parcel source) {
return new ParentModel(source);
}
@Override
public ParentModel[] newArray(int size) {
return new ParentModel[size];
}
};
}
| [
"noreply@github.com"
] | noreply@github.com |
9d49916774765bf31c3f0b53b788641791344e0d | 654d23d30767594ef7852476d373a9a533380ab9 | /flexible-adapter-app/src/main/java/eu/davidea/samples/flexibleadapter/animators/FlipInBottomXItemAnimator.java | 1d6a4ed96af43f62a585eacbc68823a93a8be2d2 | [
"Apache-2.0"
] | permissive | ouyangzn/FlexibleAdapter | 08392110c33626036e135bf962774f1cc59d3e63 | 51d31b923315f923f208303bf2b5479449514305 | refs/heads/master | 2021-09-20T09:48:31.234196 | 2018-08-08T06:24:09 | 2018-08-08T06:24:09 | 104,318,254 | 0 | 0 | Apache-2.0 | 2018-08-08T06:25:02 | 2017-09-21T07:53:36 | Java | UTF-8 | Java | false | false | 2,015 | java | /*
* Copyright (C) 2015 Wasabeef
*
* 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 eu.davidea.samples.flexibleadapter.animators;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.view.animation.Interpolator;
import eu.davidea.flexibleadapter.common.FlexibleItemAnimator;
public class FlipInBottomXItemAnimator extends FlexibleItemAnimator {
public FlipInBottomXItemAnimator() {
}
public FlipInBottomXItemAnimator(Interpolator interpolator) {
mInterpolator = interpolator;
}
@Override
protected void animateRemoveImpl(final RecyclerView.ViewHolder holder, final int index) {
ViewCompat.animate(holder.itemView)
.rotationX(-90)
.setDuration(getRemoveDuration())
.setInterpolator(mInterpolator)
.setListener(new DefaultRemoveVpaListener(holder))
.start();
}
@Override
protected boolean preAnimateAddImpl(final RecyclerView.ViewHolder holder) {
holder.itemView.setRotationX(-90);
return true;
}
@Override
protected void animateAddImpl(final RecyclerView.ViewHolder holder, final int index) {
ViewCompat.animate(holder.itemView)
.rotationX(0)
.setDuration(getAddDuration())
.setInterpolator(mInterpolator)
.setListener(new DefaultAddVpaListener(holder))
.start();
}
} | [
"dave.dna@gmail.com"
] | dave.dna@gmail.com |
6fd63b55ef336f78ac2d399483584903689be81e | 2e98d01a0a2a3509298a748a9fdd058e5394446d | /src/com/oauth/services/EmployeeServices.java | 2eaadbb2f96e3e731cf81d798e027d04f043669d | [] | no_license | khpraful/JavaProject-OAuth | db1ac17d65d361952987c0103572ca1b18e1564c | 9284c1538c81fb198d7e12777ce9d9ed20ab8161 | refs/heads/master | 2020-05-01T10:14:50.681162 | 2019-04-06T10:10:24 | 2019-04-06T10:10:24 | 177,416,793 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,615 | java | package com.oauth.services;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.oauth.configuration.AuthServerConfig;
import com.oauth.dao.TokenManager;
import com.oauth.model.Employee;
public class EmployeeServices {
public static void getEmployees(HttpServletRequest request) {
if (serveRequest(request)) {
List<Employee> empList = new ArrayList<>();
Employee emp1 = new Employee(1, "Ralph", "Digital", 1000);
Employee emp2 = new Employee(2, "Fredric", "Digital", 2000);
empList.add(emp1);
empList.add(emp2);
for (int i = 0; i < empList.size(); i++) {
System.out.println(empList.get(i).getId() + " | "
+ empList.get(i).getName() + " | "
+ empList.get(i).getDept() + " | "
+ empList.get(i).getSalary());
}
}
}
public static void getEmployee(HttpServletRequest request) {
if (serveRequest(request)) {
Employee emp = new Employee(10, "Ralph", "Digital", 1000);
System.out.println(emp.getId() + " | " + emp.getName() + " | "
+ emp.getDept() + " | " + emp.getSalary());
}
}
public static boolean createEmployee() {
return true;
}
public static boolean updateEmployee() {
return true;
}
public static boolean deleteEmployee() {
return true;
}
public static boolean serveRequest(HttpServletRequest request) {
String token = request.getParameter("token");
System.out.println("Received Token: " + token);
if (token != null && TokenManager.isValidToken(token)
&& AuthServerConfig.getScope().equals("read")) {
return true;
} else {
return false;
}
}
}
| [
"khpraful@yahoo.co.in"
] | khpraful@yahoo.co.in |
73b9796e6eb23b82fb48ae4c5e2c13f9561601a3 | c85117a4e0474fe1a67d16a303f53a9a51aa5dbb | /libs/support/v4/src/java/android/support/v4/app/FragmentActivity.java | c3209b554103d68a86a7724af91fd84c9c7c6679 | [
"Apache-2.0"
] | permissive | WesleyCharlesBlake/Sensu_API_Android | 48b0cb8862b884b3bc1d69f86f41575f5c37c3c7 | d70d2b6d5329a143d3dd24da75c56e3393965987 | refs/heads/master | 2020-12-26T00:51:37.413483 | 2015-06-28T11:18:23 | 2015-06-28T11:18:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 32,712 | java | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v4.util.SimpleArrayMap;
import android.util.AttributeSet;
import android.util.Log;
import android.view.*;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
/**
* Base class for activities that want to use the support-based
* {@link android.support.v4.app.Fragment} and
* {@link android.support.v4.content.Loader} APIs.
*
* <p>When using this class as opposed to new platform's built-in fragment
* and loader support, you must use the {@link #getSupportFragmentManager()}
* and {@link #getSupportLoaderManager()} methods respectively to access
* those features.
*
* <p class="note"><strong>Note:</strong> If you want to implement an activity that includes
* an <a href="{@docRoot}guide/topics/ui/actionbar.html">action bar</a>, you should instead use
* the {@link android.support.v7.app.ActionBarActivity} class, which is a subclass of this one,
* so allows you to use {@link android.support.v4.app.Fragment} APIs on API level 7 and higher.</p>
*
* <p>Known limitations:</p>
* <ul>
* <li> <p>When using the <code><fragment></code> tag, this implementation can not
* use the parent view's ID as the new fragment's ID. You must explicitly
* specify an ID (or tag) in the <code><fragment></code>.</p>
* <li> <p>Prior to Honeycomb (3.0), an activity's state was saved before pausing.
* Fragments are a significant amount of new state, and dynamic enough that one
* often wants them to change between pausing and stopping. These classes
* throw an exception if you try to change the fragment state after it has been
* saved, to avoid accidental loss of UI state. However this is too restrictive
* prior to Honeycomb, where the state is saved before pausing. To address this,
* when running on platforms prior to Honeycomb an exception will not be thrown
* if you change fragments between the state save and the activity being stopped.
* This means that in some cases if the activity is restored from its last saved
* state, this may be a snapshot slightly before what the user last saw.</p>
* </ul>
*/
public class FragmentActivity extends Activity {
private static final String TAG = "FragmentActivity";
static final String FRAGMENTS_TAG = "android:support:fragments";
// This is the SDK API version of Honeycomb (3.0).
private static final int HONEYCOMB = 11;
static final int MSG_REALLY_STOPPED = 1;
static final int MSG_RESUME_PENDING = 2;
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REALLY_STOPPED:
if (mStopped) {
doReallyStop(false);
}
break;
case MSG_RESUME_PENDING:
onResumeFragments();
mFragments.execPendingActions();
break;
default:
super.handleMessage(msg);
}
}
};
final FragmentManagerImpl mFragments = new FragmentManagerImpl();
final FragmentContainer mContainer = new FragmentContainer() {
@Override
public View findViewById(int id) {
return FragmentActivity.this.findViewById(id);
}
};
boolean mCreated;
boolean mResumed;
boolean mStopped;
boolean mReallyStopped;
boolean mRetaining;
boolean mOptionsMenuInvalidated;
boolean mCheckedForLoaderManager;
boolean mLoadersStarted;
SimpleArrayMap<String, LoaderManagerImpl> mAllLoaderManagers;
LoaderManagerImpl mLoaderManager;
static final class NonConfigurationInstances {
Object activity;
Object custom;
SimpleArrayMap<String, Object> children;
ArrayList<Fragment> fragments;
SimpleArrayMap<String, LoaderManagerImpl> loaders;
}
static class FragmentTag {
public static final int[] Fragment = {
0x01010003, 0x010100d0, 0x010100d1
};
public static final int Fragment_id = 1;
public static final int Fragment_name = 0;
public static final int Fragment_tag = 2;
}
// ------------------------------------------------------------------------
// HOOKS INTO ACTIVITY
// ------------------------------------------------------------------------
/**
* Dispatch incoming result to the correct fragment.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFragments.noteStateNotSaved();
int index = requestCode>>16;
if (index != 0) {
index--;
if (mFragments.mActive == null || index < 0 || index >= mFragments.mActive.size()) {
Log.w(TAG, "Activity result fragment index out of range: 0x"
+ Integer.toHexString(requestCode));
return;
}
Fragment frag = mFragments.mActive.get(index);
if (frag == null) {
Log.w(TAG, "Activity result no fragment exists for index: 0x"
+ Integer.toHexString(requestCode));
} else {
frag.onActivityResult(requestCode&0xffff, resultCode, data);
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}
}
/**
* Dispatch configuration change to all fragments.
*/
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mFragments.dispatchConfigurationChanged(newConfig);
}
/**
* Perform initialization of all fragments and loaders.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
mFragments.attachActivity(this, mContainer, null);
// Old versions of the platform didn't do this!
if (getLayoutInflater().getFactory() == null) {
getLayoutInflater().setFactory(this);
}
super.onCreate(savedInstanceState);
NonConfigurationInstances nc = (NonConfigurationInstances)
getLastNonConfigurationInstance();
if (nc != null) {
mAllLoaderManagers = nc.loaders;
}
if (savedInstanceState != null) {
Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
mFragments.restoreAllState(p, nc != null ? nc.fragments : null);
}
mFragments.dispatchCreate();
}
/**
* Dispatch to Fragment.onCreateOptionsMenu().
*/
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
boolean show = super.onCreatePanelMenu(featureId, menu);
show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
return show;
}
// Prior to Honeycomb, the framework can't invalidate the options
// menu, so we must always say we have one in case the app later
// invalidates it and needs to have it shown.
return true;
}
return super.onCreatePanelMenu(featureId, menu);
}
/**
* Add support for inflating the <fragment> tag.
*/
@Override
public View onCreateView(String name, @NonNull Context context, @NonNull AttributeSet attrs) {
if (!"fragment".equals(name)) {
return super.onCreateView(name, context, attrs);
}
String fname = attrs.getAttributeValue(null, "class");
TypedArray a = context.obtainStyledAttributes(attrs, FragmentTag.Fragment);
if (fname == null) {
fname = a.getString(FragmentTag.Fragment_name);
}
int id = a.getResourceId(FragmentTag.Fragment_id, View.NO_ID);
String tag = a.getString(FragmentTag.Fragment_tag);
a.recycle();
if (!Fragment.isSupportFragmentClass(this, fname)) {
// Invalid support lib fragment; let the device's framework handle it.
// This will allow android.app.Fragments to do the right thing.
return super.onCreateView(name, context, attrs);
}
View parent = null; // NOTE: no way to get parent pre-Honeycomb.
int containerId = parent != null ? parent.getId() : 0;
if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
throw new IllegalArgumentException(attrs.getPositionDescription()
+ ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
}
// If we restored from a previous state, we may already have
// instantiated this fragment from the state and should use
// that instance instead of making a new one.
Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
if (fragment == null && tag != null) {
fragment = mFragments.findFragmentByTag(tag);
}
if (fragment == null && containerId != View.NO_ID) {
fragment = mFragments.findFragmentById(containerId);
}
if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
+ Integer.toHexString(id) + " fname=" + fname
+ " existing=" + fragment);
if (fragment == null) {
fragment = Fragment.instantiate(this, fname);
fragment.mFromLayout = true;
fragment.mFragmentId = id != 0 ? id : containerId;
fragment.mContainerId = containerId;
fragment.mTag = tag;
fragment.mInLayout = true;
fragment.mFragmentManager = mFragments;
fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
mFragments.addFragment(fragment, true);
} else if (fragment.mInLayout) {
// A fragment already exists and it is not one we restored from
// previous state.
throw new IllegalArgumentException(attrs.getPositionDescription()
+ ": Duplicate id 0x" + Integer.toHexString(id)
+ ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
+ " with another fragment for " + fname);
} else {
// This fragment was retained from a previous instance; get it
// going now.
fragment.mInLayout = true;
// If this fragment is newly instantiated (either right now, or
// from last saved state), then give it the attributes to
// initialize itself.
if (!fragment.mRetaining) {
fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
}
mFragments.moveToState(fragment);
}
if (fragment.mView == null) {
throw new IllegalStateException("Fragment " + fname
+ " did not create a view.");
}
if (id != 0) {
fragment.mView.setId(id);
}
if (fragment.mView.getTag() == null) {
fragment.mView.setTag(tag);
}
return fragment.mView;
}
/**
* Destroy all fragments and loaders.
*/
@Override
protected void onDestroy() {
super.onDestroy();
doReallyStop(false);
mFragments.dispatchDestroy();
if (mLoaderManager != null) {
mLoaderManager.doDestroy();
}
}
/**
* Take care of calling onBackPressed() for pre-Eclair platforms.
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (android.os.Build.VERSION.SDK_INT < 5 /* ECLAIR */
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
// Take care of calling this method on earlier versions of
// the platform where it doesn't exist.
onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Dispatch onLowMemory() to all fragments.
*/
@Override
public void onLowMemory() {
super.onLowMemory();
mFragments.dispatchLowMemory();
}
/**
* Dispatch context and options menu to fragments.
*/
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (super.onMenuItemSelected(featureId, item)) {
return true;
}
switch (featureId) {
case Window.FEATURE_OPTIONS_PANEL:
return mFragments.dispatchOptionsItemSelected(item);
case Window.FEATURE_CONTEXT_MENU:
return mFragments.dispatchContextItemSelected(item);
default:
return false;
}
}
/**
* Call onOptionsMenuClosed() on fragments.
*/
@Override
public void onPanelClosed(int featureId, Menu menu) {
switch (featureId) {
case Window.FEATURE_OPTIONS_PANEL:
mFragments.dispatchOptionsMenuClosed(menu);
break;
}
super.onPanelClosed(featureId, menu);
}
/**
* Dispatch onPause() to fragments.
*/
@Override
protected void onPause() {
super.onPause();
mResumed = false;
if (mHandler.hasMessages(MSG_RESUME_PENDING)) {
mHandler.removeMessages(MSG_RESUME_PENDING);
onResumeFragments();
}
mFragments.dispatchPause();
}
/**
* Handle onNewIntent() to inform the fragment manager that the
* state is not saved. If you are handling new intents and may be
* making changes to the fragment state, you want to be sure to call
* through to the super-class here first. Otherwise, if your state
* is saved but the activity is not stopped, you could get an
* onNewIntent() call which happens before onResume() and trying to
* perform fragment operations at that point will throw IllegalStateException
* because the fragment manager thinks the state is still saved.
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
mFragments.noteStateNotSaved();
}
/**
* Dispatch onResume() to fragments. Note that for better inter-operation
* with older versions of the platform, at the point of this call the
* fragments attached to the activity are <em>not</em> resumed. This means
* that in some cases the previous state may still be saved, not allowing
* fragment transactions that modify the state. To correctly interact
* with fragments in their proper state, you should instead override
* {@link #onResumeFragments()}.
*/
@Override
protected void onResume() {
super.onResume();
mHandler.sendEmptyMessage(MSG_RESUME_PENDING);
mResumed = true;
mFragments.execPendingActions();
}
/**
* Dispatch onResume() to fragments.
*/
@Override
protected void onPostResume() {
super.onPostResume();
mHandler.removeMessages(MSG_RESUME_PENDING);
onResumeFragments();
mFragments.execPendingActions();
}
/**
* This is the fragment-orientated version of {@link #onResume()} that you
* can override to perform operations in the Activity at the same point
* where its fragments are resumed. Be sure to always call through to
* the super-class.
*/
protected void onResumeFragments() {
mFragments.dispatchResume();
}
/**
* Dispatch onPrepareOptionsMenu() to fragments.
*/
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
if (mOptionsMenuInvalidated) {
mOptionsMenuInvalidated = false;
menu.clear();
onCreatePanelMenu(featureId, menu);
}
boolean goforit = onPrepareOptionsPanel(view, menu);
goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
return goforit;
}
return super.onPreparePanel(featureId, view, menu);
}
/**
* @hide
*/
protected boolean onPrepareOptionsPanel(View view, Menu menu) {
return super.onPreparePanel(Window.FEATURE_OPTIONS_PANEL, view, menu);
}
/**
* Retain all appropriate fragment and loader state. You can NOT
* override this yourself! Use {@link #onRetainCustomNonConfigurationInstance()}
* if you want to retain your own state.
*/
@Override
public final Object onRetainNonConfigurationInstance() {
if (mStopped) {
doReallyStop(true);
}
Object custom = onRetainCustomNonConfigurationInstance();
ArrayList<Fragment> fragments = mFragments.retainNonConfig();
boolean retainLoaders = false;
if (mAllLoaderManagers != null) {
// prune out any loader managers that were already stopped and so
// have nothing useful to retain.
final int N = mAllLoaderManagers.size();
LoaderManagerImpl loaders[] = new LoaderManagerImpl[N];
for (int i=N-1; i>=0; i--) {
loaders[i] = mAllLoaderManagers.valueAt(i);
}
for (int i=0; i<N; i++) {
LoaderManagerImpl lm = loaders[i];
if (lm.mRetaining) {
retainLoaders = true;
} else {
lm.doDestroy();
mAllLoaderManagers.remove(lm.mWho);
}
}
}
if (fragments == null && !retainLoaders && custom == null) {
return null;
}
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.activity = null;
nci.custom = custom;
nci.children = null;
nci.fragments = fragments;
nci.loaders = mAllLoaderManagers;
return nci;
}
/**
* Save all appropriate fragment state.
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Parcelable p = mFragments.saveAllState();
if (p != null) {
outState.putParcelable(FRAGMENTS_TAG, p);
}
}
/**
* Dispatch onStart() to all fragments. Ensure any created loaders are
* now started.
*/
@Override
protected void onStart() {
super.onStart();
mStopped = false;
mReallyStopped = false;
mHandler.removeMessages(MSG_REALLY_STOPPED);
if (!mCreated) {
mCreated = true;
mFragments.dispatchActivityCreated();
}
mFragments.noteStateNotSaved();
mFragments.execPendingActions();
if (!mLoadersStarted) {
mLoadersStarted = true;
if (mLoaderManager != null) {
mLoaderManager.doStart();
} else if (!mCheckedForLoaderManager) {
mLoaderManager = getLoaderManager("(root)", mLoadersStarted, false);
// the returned loader manager may be a new one, so we have to start it
if ((mLoaderManager != null) && (!mLoaderManager.mStarted)) {
mLoaderManager.doStart();
}
}
mCheckedForLoaderManager = true;
}
// NOTE: HC onStart goes here.
mFragments.dispatchStart();
if (mAllLoaderManagers != null) {
final int N = mAllLoaderManagers.size();
LoaderManagerImpl loaders[] = new LoaderManagerImpl[N];
for (int i=N-1; i>=0; i--) {
loaders[i] = mAllLoaderManagers.valueAt(i);
}
for (int i=0; i<N; i++) {
LoaderManagerImpl lm = loaders[i];
lm.finishRetain();
lm.doReportStart();
}
}
}
/**
* Dispatch onStop() to all fragments. Ensure all loaders are stopped.
*/
@Override
protected void onStop() {
super.onStop();
mStopped = true;
mHandler.sendEmptyMessage(MSG_REALLY_STOPPED);
mFragments.dispatchStop();
}
// ------------------------------------------------------------------------
// NEW METHODS
// ------------------------------------------------------------------------
/**
* Use this instead of {@link #onRetainNonConfigurationInstance()}.
* Retrieve later with {@link #getLastCustomNonConfigurationInstance()}.
*/
public Object onRetainCustomNonConfigurationInstance() {
return null;
}
/**
* Return the value previously returned from
* {@link #onRetainCustomNonConfigurationInstance()}.
*/
public Object getLastCustomNonConfigurationInstance() {
NonConfigurationInstances nc = (NonConfigurationInstances)
getLastNonConfigurationInstance();
return nc != null ? nc.custom : null;
}
/**
* Support library version of {@link Activity#invalidateOptionsMenu}.
*
* <p>Invalidate the activity's options menu. This will cause relevant presentations
* of the menu to fully update via calls to onCreateOptionsMenu and
* onPrepareOptionsMenu the next time the menu is requested.
*/
public void supportInvalidateOptionsMenu() {
if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
// If we are running on HC or greater, we can use the framework
// API to invalidate the options menu.
ActivityCompatHoneycomb.invalidateOptionsMenu(this);
return;
}
// Whoops, older platform... we'll use a hack, to manually rebuild
// the options menu the next time it is prepared.
mOptionsMenuInvalidated = true;
}
/**
* Print the Activity's state into the given stream. This gets invoked if
* you run "adb shell dumpsys activity <activity_component_name>".
*
* @param prefix Desired prefix to prepend at each line of output.
* @param fd The raw file descriptor that the dump is being sent to.
* @param writer The PrintWriter to which you should dump your state. This will be
* closed for you after you return.
* @param args additional arguments to the dump request.
*/
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
// XXX This can only work if we can call the super-class impl. :/
//ActivityCompatHoneycomb.dump(this, prefix, fd, writer, args);
}
writer.print(prefix); writer.print("Local FragmentActivity ");
writer.print(Integer.toHexString(System.identityHashCode(this)));
writer.println(" State:");
String innerPrefix = prefix + " ";
writer.print(innerPrefix); writer.print("mCreated=");
writer.print(mCreated); writer.print("mResumed=");
writer.print(mResumed); writer.print(" mStopped=");
writer.print(mStopped); writer.print(" mReallyStopped=");
writer.println(mReallyStopped);
writer.print(innerPrefix); writer.print("mLoadersStarted=");
writer.println(mLoadersStarted);
if (mLoaderManager != null) {
writer.print(prefix); writer.print("Loader Manager ");
writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
writer.println(":");
mLoaderManager.dump(prefix + " ", fd, writer, args);
}
mFragments.dump(prefix, fd, writer, args);
writer.print(prefix); writer.println("View Hierarchy:");
dumpViewHierarchy(prefix + " ", writer, getWindow().getDecorView());
}
private static String viewToString(View view) {
StringBuilder out = new StringBuilder(128);
out.append(view.getClass().getName());
out.append('{');
out.append(Integer.toHexString(System.identityHashCode(view)));
out.append(' ');
switch (view.getVisibility()) {
case View.VISIBLE: out.append('V'); break;
case View.INVISIBLE: out.append('I'); break;
case View.GONE: out.append('G'); break;
default: out.append('.'); break;
}
out.append(view.isFocusable() ? 'F' : '.');
out.append(view.isEnabled() ? 'E' : '.');
out.append(view.willNotDraw() ? '.' : 'D');
out.append(view.isHorizontalScrollBarEnabled()? 'H' : '.');
out.append(view.isVerticalScrollBarEnabled() ? 'V' : '.');
out.append(view.isClickable() ? 'C' : '.');
out.append(view.isLongClickable() ? 'L' : '.');
out.append(' ');
out.append(view.isFocused() ? 'F' : '.');
out.append(view.isSelected() ? 'S' : '.');
out.append(view.isPressed() ? 'P' : '.');
out.append(' ');
out.append(view.getLeft());
out.append(',');
out.append(view.getTop());
out.append('-');
out.append(view.getRight());
out.append(',');
out.append(view.getBottom());
final int id = view.getId();
if (id != View.NO_ID) {
out.append(" #");
out.append(Integer.toHexString(id));
final Resources r = view.getResources();
if (id != 0 && r != null) {
try {
String pkgname;
switch (id&0xff000000) {
case 0x7f000000:
pkgname="app";
break;
case 0x01000000:
pkgname="android";
break;
default:
pkgname = r.getResourcePackageName(id);
break;
}
String typename = r.getResourceTypeName(id);
String entryname = r.getResourceEntryName(id);
out.append(" ");
out.append(pkgname);
out.append(":");
out.append(typename);
out.append("/");
out.append(entryname);
} catch (Resources.NotFoundException e) {
}
}
}
out.append("}");
return out.toString();
}
private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
writer.print(prefix);
if (view == null) {
writer.println("null");
return;
}
writer.println(viewToString(view));
if (!(view instanceof ViewGroup)) {
return;
}
ViewGroup grp = (ViewGroup)view;
final int N = grp.getChildCount();
if (N <= 0) {
return;
}
prefix = prefix + " ";
for (int i=0; i<N; i++) {
dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
}
}
void doReallyStop(boolean retaining) {
if (!mReallyStopped) {
mReallyStopped = true;
mRetaining = retaining;
mHandler.removeMessages(MSG_REALLY_STOPPED);
onReallyStop();
}
}
/**
* Pre-HC, we didn't have a way to determine whether an activity was
* being stopped for a config change or not until we saw
* onRetainNonConfigurationInstance() called after onStop(). However
* we need to know this, to know whether to retain fragments. This will
* tell us what we need to know.
*/
void onReallyStop() {
if (mLoadersStarted) {
mLoadersStarted = false;
if (mLoaderManager != null) {
if (!mRetaining) {
mLoaderManager.doStop();
} else {
mLoaderManager.doRetain();
}
}
}
mFragments.dispatchReallyStop();
}
// ------------------------------------------------------------------------
// FRAGMENT SUPPORT
// ------------------------------------------------------------------------
/**
* Called when a fragment is attached to the activity.
*/
public void onAttachFragment(Fragment fragment) {
}
/**
* Return the FragmentManager for interacting with fragments associated
* with this activity.
*/
public FragmentManager getSupportFragmentManager() {
return mFragments;
}
/**
* Modifies the standard behavior to allow results to be delivered to fragments.
* This imposes a restriction that requestCode be <= 0xffff.
*/
@Override
public void startActivityForResult(Intent intent, int requestCode) {
if (requestCode != -1 && (requestCode&0xffff0000) != 0) {
throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
}
super.startActivityForResult(intent, requestCode);
}
/**
* Called by Fragment.startActivityForResult() to implement its behavior.
*/
public void startActivityFromFragment(Fragment fragment, Intent intent,
int requestCode) {
if (requestCode == -1) {
super.startActivityForResult(intent, -1);
return;
}
if ((requestCode&0xffff0000) != 0) {
throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
}
super.startActivityForResult(intent, ((fragment.mIndex+1)<<16) + (requestCode&0xffff));
}
void invalidateSupportFragment(String who) {
//Log.v(TAG, "invalidateSupportFragment: who=" + who);
if (mAllLoaderManagers != null) {
LoaderManagerImpl lm = mAllLoaderManagers.get(who);
if (lm != null && !lm.mRetaining) {
lm.doDestroy();
mAllLoaderManagers.remove(who);
}
}
}
// ------------------------------------------------------------------------
// LOADER SUPPORT
// ------------------------------------------------------------------------
/**
* Return the LoaderManager for this fragment, creating it if needed.
*/
public LoaderManager getSupportLoaderManager() {
if (mLoaderManager != null) {
return mLoaderManager;
}
mCheckedForLoaderManager = true;
mLoaderManager = getLoaderManager("(root)", mLoadersStarted, true);
return mLoaderManager;
}
LoaderManagerImpl getLoaderManager(String who, boolean started, boolean create) {
if (mAllLoaderManagers == null) {
mAllLoaderManagers = new SimpleArrayMap<String, LoaderManagerImpl>();
}
LoaderManagerImpl lm = mAllLoaderManagers.get(who);
if (lm == null) {
if (create) {
lm = new LoaderManagerImpl(who, this, started);
mAllLoaderManagers.put(who, lm);
}
} else {
lm.updateActivity(this);
}
return lm;
}
}
| [
"golan@Golanss-MacBook-Pro.local"
] | golan@Golanss-MacBook-Pro.local |
d0b89531a3578b20c78c67d916a59e6c1281b5f2 | 751cb15d444df73ceb5a5ac28964d9d25334be9f | /src/com/chapter03/scripting/ICoconut.java | 23e5a208d48640f285e4b48838ecb495a5eaeac9 | [] | no_license | ruicaihua/springInActionS | 8ed5b4a1e6e5643dbb64ee88082f4bb89de9f417 | a9f351351fac236f6d6b8d4f1d138d1a95e7ba18 | refs/heads/master | 2016-09-06T21:43:14.932842 | 2013-05-07T09:57:30 | 2013-05-07T09:57:30 | 9,595,116 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 91 | java | package com.chapter03.scripting;
public interface ICoconut {
void drinkThemBothUp();
}
| [
"ruicaihua_3@126.com"
] | ruicaihua_3@126.com |
b78f19efac8ba77112f5a285ce4bfdca07397bd2 | f56664cde6a2b7c56a0a7ade669de493608ca831 | /src/testThread/mySuspend/Run.java | 063399b9064cc704cb1483af0273265629dc4476 | [] | no_license | NewerForGitHub/multiThreadProject | e2625be055f010f5731e62364a5a5d5f88934f92 | 2e10a3fb7ef8f7d0f035121619daf889b16949dd | refs/heads/master | 2021-07-02T03:11:13.499148 | 2017-09-21T07:31:07 | 2017-09-21T07:31:08 | 103,330,465 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 844 | java | package testThread.mySuspend;
/**
* 该方法的缺点:<br>
* 1.独占公共对象,其他线程无法访问<br>
* 2.数据不同步,有点类似于数据库的数据完整性<br>
*
*/
public class Run {
public static void main(String[] args) throws InterruptedException {
MyThread mt = new MyThread();
mt.start();
Thread.sleep(5000);
//A段
mt.suspend();
System.out.println("A=" + System.currentTimeMillis() + " i=" + mt.getI());
Thread.sleep(5000);
System.out.println("A=" + System.currentTimeMillis() + " i=" + mt.getI());
//B段
mt.resume();
Thread.sleep(5000);
//C段
mt.suspend();
System.out.println("A=" + System.currentTimeMillis() + " i=" + mt.getI());
Thread.sleep(5000);
System.out.println("A=" + System.currentTimeMillis() + " i=" + mt.getI());
}
}
| [
"Administrator@GASHGY1HZK3IK4U"
] | Administrator@GASHGY1HZK3IK4U |
8385354aa3022358bdf412ed554fadc3d1df60b5 | 87d929cdeca9be361055e06b4c4b32a65134cbc4 | /spring-boot-jms/src/main/java/com/devglan/Order.java | 81bf06a7f773c2b1816101e70fa6b751f55efa8e | [] | no_license | pshahapur/Kiosk_Projects | 63a0410b9dff9d966b510bce15f0843a22ee8bc4 | 317a7462b924097936112217601413dbb8d803cf | refs/heads/master | 2020-04-06T08:50:12.720516 | 2018-11-13T08:33:41 | 2018-11-13T08:33:41 | 157,318,376 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 675 | java | package com.devglan;
public class Order {
private String orderId;
private String customerId;
private float orderAmount;
private String status;
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public float getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(float orderAmount) {
this.orderAmount = orderAmount;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| [
"prashant.shahapur@gmail.com"
] | prashant.shahapur@gmail.com |
67e8f783f396658f54442c704cf8c231363d7945 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/5/5_87c2b864e73f02c82deb42adafbaf45e1921aa6e/FaceList/5_87c2b864e73f02c82deb42adafbaf45e1921aa6e_FaceList_t.java | 8f9b790501f04ce98fad89d96ebe6f5ea129e2d5 | [] | 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 | 22,536 | java | /*
Copyright 2012 Olaf Delgado-Friedrichs
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.gavrog.joss.tilings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.gavrog.box.collections.Pair;
import org.gavrog.jane.compounds.Matrix;
import org.gavrog.jane.numbers.Real;
import org.gavrog.joss.dsyms.basic.DSymbol;
import org.gavrog.joss.dsyms.basic.DelaneySymbol;
import org.gavrog.joss.dsyms.basic.DynamicDSymbol;
import org.gavrog.joss.dsyms.basic.IndexList;
import org.gavrog.joss.dsyms.derived.DSCover;
import org.gavrog.joss.geometry.Point;
import org.gavrog.joss.geometry.Vector;
import org.gavrog.joss.pgraphs.basic.INode;
import org.gavrog.joss.pgraphs.io.GenericParser;
import org.gavrog.joss.pgraphs.io.NetParser;
import org.gavrog.joss.pgraphs.io.NetParser.Face;
/**
* Implements a periodic face set meant to define a tiling.
*
* TODO Remove ? and Object as type parameters.
*/
public class FaceList {
final private static boolean DEBUG = false;
/**
* Hashable class for edges in the tiling to be constructed.
*/
private static class Edge implements Comparable<Edge> {
final public int source;
final public int target;
final public Vector shift;
public Edge(final int source, final int target, final Vector shift) {
if (source < target || (source == target && shift.isNonNegative())) {
this.source = source;
this.target = target;
this.shift = shift;
} else {
this.source = target;
this.target = source;
this.shift = (Vector) shift.negative();
}
}
public int hashCode() {
return ((source * 37) + target * 127) + shift.hashCode();
}
public boolean equals(final Object other) {
final Edge e = (Edge) other;
return source == e.source && target == e.target
&& shift.equals(e.shift);
}
public int compareTo(final Edge other) {
if (this.source != other.source) {
return this.source - other.source;
}
if (this.target != other.target) {
return this.target - other.target;
}
return this.shift.compareTo(other.shift);
}
public String toString() {
return "(" + source + "," + target + "," + shift + ")";
}
}
private static class Incidence implements Comparable<Incidence> {
final public int faceIndex;
final public int edgeIndex;
final public boolean reverse;
final public double angle;
public Incidence(
final int faceIndex, final int edgeIndex, final boolean rev,
final double angle) {
this.faceIndex = faceIndex;
this.edgeIndex = edgeIndex;
this.reverse = rev;
this.angle = angle;
}
public Incidence(
final int faceIndex, final int edgeIndex, final boolean rev) {
this(faceIndex, edgeIndex, rev, 0.0);
}
public Incidence(final Incidence source, final double angle) {
this(source.faceIndex, source.edgeIndex, source.reverse, angle);
}
public int compareTo(final Incidence other) {
if (this.angle < other.angle) {
return -1;
} else if (this.angle > other.angle) {
return 1;
}
if (this.faceIndex != other.faceIndex) {
return this.faceIndex - other.faceIndex;
}
if (this.edgeIndex != other.edgeIndex) {
return this.edgeIndex - other.edgeIndex;
}
if (!this.reverse && other.reverse) {
return -1;
} else if (this.reverse && !other.reverse) {
return 1;
} else {
return 0;
}
}
public String toString() {
return "(" + faceIndex + "," + edgeIndex + "," + reverse + ","
+ angle + ")";
}
}
final private List<Face> faces;
final private List<List<Pair<Face, Vector>>> tiles;
final private Map<Face, List<Pair<Integer, Vector>>> tilesAtFace;
final private Map<Integer, Point> indexToPos;
final private int dim;
final private DSymbol ds;
final private DSCover<Integer> cover;
final private Map<Integer, Point> positions;
public FaceList(
final List<Object> input,
final Map<Integer, Point> indexToPosition)
{
if (DEBUG) {
System.err.println("\nStarting FaceList constructor");
}
if (input == null || input.size() < 1) {
throw new IllegalArgumentException("no data given");
}
if (input.get(0) instanceof List) {
this.tiles = new ArrayList<List<Pair<Face, Vector>>>();
this.tilesAtFace = new HashMap<Face, List<Pair<Integer, Vector>>>();
for (int i = 0; i < input.size(); ++i) {
@SuppressWarnings("unchecked")
final List<Pair<Face, Vector>> tile =
(List<Pair<Face, Vector>>) input.get(i);
final List<Pair<Face, Vector>> newTile =
new ArrayList<Pair<Face, Vector>>();
for (final Pair<Face, Vector> entry: tile) {
final Face face = entry.getFirst();
final Pair<Face, Vector> normal =
NetParser.normalizedFace(face);
final Vector shift =
(Vector) entry.getSecond().plus(normal.getSecond());
if (!this.tilesAtFace.containsKey(face)) {
this.tilesAtFace.put(face,
new ArrayList<Pair<Integer, Vector>>());
}
this.tilesAtFace.get(face).add(
new Pair<Integer, Vector>(i, shift));
newTile.add(new Pair<Face, Vector>(face, shift));
}
this.tiles.add(newTile);
}
// --- make sure each face is in exactly two tiles
for (final List<Pair<Integer, Vector>> tlist:
this.tilesAtFace.values())
{
final int n = tlist.size();
if (n != 2) {
throw new IllegalArgumentException("Face incident to " + n
+ " tile" + (n == 1 ? "" : "s") + ".");
}
}
this.faces = new ArrayList<Face>();
this.faces.addAll(this.tilesAtFace.keySet());
} else {
this.tiles = null;
this.tilesAtFace = null;
this.faces = new ArrayList<Face>();
for (final Object x: input)
this.faces.add((Face) x);
}
final Face f0 = this.faces.get(0);
if (f0.size() < 3) {
throw new IllegalArgumentException("minimal face-size is 3");
}
this.dim = f0.shift(0).getDimension();
if (this.dim != 3) {
throw new UnsupportedOperationException("dimension must be 3");
}
this.indexToPos = indexToPosition;
// --- initialize the intermediate symbol
final Map<Face, List<Integer>> faceElements =
new HashMap<Face, List<Integer>>();
final DynamicDSymbol ds = new DynamicDSymbol(this.dim);
for (final Face f: this.faces) {
final int n = f.size();
final int _2n = 2 * n;
final List<Integer> elms = ds.grow(4 * n);
faceElements.put(f, elms);
for (int i = 0; i < 4 * n; i += 2) {
ds.redefineOp(0, elms.get(i), elms.get(i + 1));
}
for (int i = 1; i < _2n; i += 2) {
final int i1 = (i + 1) % _2n;
ds.redefineOp(1, elms.get(i), elms.get(i1));
ds.redefineOp(1, elms.get(i + _2n), elms.get(i1 + _2n));
}
for (int i = 0; i < _2n; ++i) {
ds.redefineOp(3, elms.get(i), elms.get(i + _2n));
}
}
if (DEBUG) {
System.err.println("Symbol without 2-ops: " + new DSymbol(ds));
}
if (this.tiles == null) {
set2opPlainMode(ds, faceElements);
} else {
set2opTileMode(ds, faceElements);
}
if (DEBUG) {
System.err.println("Symbol with 2-ops: " + new DSymbol(ds));
}
// --- set all v values to 1
for (int i = 0; i < dim; ++i) {
for (final int D: ds.elements()) {
if (!ds.definesV(i, i + 1, D)) {
ds.redefineV(i, i + 1, D, 1);
}
}
}
if (DEBUG) {
System.err.println("Completed symbol: " + new DSymbol(ds));
}
// --- do some checks
assertCompleteness(ds);
if (!ds.isConnected()) {
throw new RuntimeException("Built non-connected symbol.");
} else if (!ds.isLocallyEuclidean3D()) {
throw new RuntimeException("Built non-manifold symbol.");
} else if (!ds.isLocallyEuclidean3D()) {
throw new RuntimeException("Built non-manifold symbol.");
}
// --- freeze the symbol, make a tiling object, and extract the cover
this.ds = new DSymbol(ds);
final Tiling tiling = new Tiling(this.ds);
this.cover = tiling.getCover();
// --- map skeleton nodes for the tiling to appropriate positions
final Tiling.Skeleton skel = tiling.getSkeleton();
this.positions = new HashMap<Integer, Point>();
for (final Face f: this.faces)
{
final int n = f.size();
final List<Integer> chambers = faceElements.get(f);
for (int i = 0; i < 4 * n; ++i)
{
final int k = (i % (2 * n) + 1) / 2 % n;
final int D = chambers.get(i);
assert(this.cover.image(D) == D);
final INode v = skel.nodeForChamber(D);
if (D == skel.chamberAtNode(v))
{
final Point p = indexToPosition.get(f.vertex(k));
final Vector s = f.shift(k);
final Vector t = tiling.cornerShift(0, D);
this.positions.put(D, (Point) p.plus(s).minus(t));
}
}
}
}
private FaceList(final Pair<List<Object>, Map<Integer, Point>> p) {
this(p.getFirst(), p.getSecond());
}
public FaceList(final GenericParser.Block data) {
this(NetParser.parseFaceList(data));
}
/**
* Computes normals for the sectors of a face.
*
* @param f the input face.
* @param indexToPos maps symbolic corners to positions.
* @return the array of sector normals.
*/
private static Vector[] sectorNormals(
final Face f,
final Map<Integer, Point> indexToPos)
{
final int n = f.size();
if (DEBUG) {
System.err.println("Computing normals for face " + f);
}
// --- compute corners and center of this face
Matrix sum = null;
final Point corners[] = new Point[n];
for (int i = 0; i < n; ++i) {
final int v = f.vertex(i);
final Vector s = f.shift(i);
final Point p = (Point) s.plus(indexToPos.get(v));
corners[i] = p;
if (sum == null) {
sum = p.getCoordinates();
} else {
sum = (Matrix) sum.plus(p.getCoordinates());
}
}
final Point center = new Point((Matrix) sum.dividedBy(n));
// --- use that to compute the normals
final Vector normals[] = new Vector[n];
for (int i = 0; i < n; ++i) {
final int i1 = (i + 1) % n;
final Vector a = (Vector) corners[i].minus(center);
final Vector b = (Vector) corners[i1].minus(corners[i]);
normals[i] = Vector.unit(Vector.crossProduct3D(a, b));
if (DEBUG) {
System.err.println(" " + normals[i]);
}
}
return normals;
}
private static Map<?, List<Incidence>> collectEdges(
final List<?> faces,
final boolean useShifts)
{
final Map<Object, List<Incidence>> facesAtEdge =
new HashMap<Object, List<Incidence>>();
for (int i = 0; i < faces.size(); ++i) {
final Face f;
final Vector fShift;
if (useShifts) {
@SuppressWarnings("unchecked")
final Pair<Face, Vector> entry =
(Pair<Face, Vector>) faces.get(i);
f = entry.getFirst();
fShift = entry.getSecond();
} else {
f = (Face) faces.get(i);
fShift = null;
}
final int n = f.size();
for (int j = 0; j < n; ++j) {
final int j1 = (j + 1) % n;
final int v = f.vertex(j);
final int w = f.vertex(j1);
final Vector s = (Vector) f.shift(j1).minus(f.shift(j));
final Edge e = new Edge(v, w, s);
final boolean rev = (e.source != v || !e.shift.equals(s));
final Object key;
if (useShifts) {
final Vector vShift = rev ? f.shift(j1) : f.shift(j);
key = new Pair<Edge, Vector>(e,
(Vector) fShift.plus(vShift));
} else {
key = e;
}
if (!facesAtEdge.containsKey(key)) {
facesAtEdge.put(key, new ArrayList<Incidence>());
}
facesAtEdge.get(key).add(new Incidence(i, j, rev));
}
}
if (DEBUG) {
System.err.println("Edge to incident faces mapping:");
final List<Object> edges = new ArrayList<Object>();
edges.addAll(facesAtEdge.keySet());
Collections.sort(edges, new Comparator<Object>() {
public int compare(final Object arg0, final Object arg1) {
if (useShifts) {
@SuppressWarnings("unchecked")
final Pair<Edge, Vector> p0 = (Pair<Edge, Vector>) arg0;
@SuppressWarnings("unchecked")
final Pair<Edge, Vector> p1 = (Pair<Edge, Vector>) arg1;
if (p0.getFirst().equals(p1.getFirst()))
return p0.getSecond().compareTo(p1.getSecond());
else
return p0.getFirst().compareTo(p1.getFirst());
} else
return ((Edge) arg0).compareTo((Edge) arg1);
}});
for (final Object e: edges) {
final List<Incidence> inc = facesAtEdge.get(e);
System.err.println(" " + inc.size() + " at edge " + e + ":");
for (int i = 0; i < inc.size(); ++i) {
System.err.println(" " + inc.get(i));
}
}
}
return facesAtEdge;
}
private void set2opPlainMode(
final DynamicDSymbol ds,
final Map<Face, List<Integer>> faceElms)
{
// --- determine sector normals for each face
final Map<Face, Vector[]> normals = new HashMap<Face, Vector[]>();
for (final Face f: this.faces) {
normals.put(f, sectorNormals(f, this.indexToPos));
}
// --- set 2 operator according to cyclic orders of faces around edges
final Map<?, List<Incidence>> facesAtEdge =
collectEdges(this.faces, false);
for (final Object obj: facesAtEdge.keySet()) {
final Edge e = (Edge) obj;
final Point p = this.indexToPos.get(e.source);
final Point q = this.indexToPos.get(e.target);
final Vector a = Vector.unit((Vector) q.plus(e.shift).minus(p));
// --- augment all incidences at this edge with their angles
final List<Incidence> incidences = facesAtEdge.get(e);
Vector n0 = null;
for (int i = 0; i < incidences.size(); ++i) {
final Incidence inc = incidences.get(i);
Vector normal =
(normals.get(faces.get(inc.faceIndex)))[inc.edgeIndex];
if (inc.reverse) {
normal = (Vector) normal.negative();
}
double angle;
if (i == 0) {
n0 = normal;
angle = 0.0;
} else {
double x = ((Real) Vector.dot(n0, normal)).doubleValue();
x = Math.max(Math.min(x, 1.0), -1.0);
angle = Math.acos(x);
if (Vector.volume3D(a, n0, normal).isNegative()) {
angle = 2 * Math.PI - angle;
}
}
incidences.set(i, new Incidence(inc, angle));
}
if (DEBUG) {
System.err.println("Augmented incidences at edge " + e + ":");
for (int i = 0; i < incidences.size(); ++i) {
System.err.println(" " + incidences.get(i));
}
}
// --- sort by angle
Collections.sort(incidences);
// --- top off with a copy of the first incidences
final Incidence inc = incidences.get(0);
incidences.add(new Incidence(inc, inc.angle + 2 * Math.PI));
if (DEBUG) {
System.err.println("Sorted incidences at edge " + e + ":");
for (int i = 0; i < incidences.size(); ++i) {
System.err.println(" " + incidences.get(i));
}
}
// --- now set all the connections around this edge
for (int i = 0; i < incidences.size() - 1; ++i) {
final Incidence inc1 = incidences.get(i);
final Incidence inc2 = incidences.get(i + 1);
if (inc2.angle - inc1.angle < 1e-3) {
throw new RuntimeException("tiny dihedral angle");
}
final List<Integer> elms1 =
faceElms.get(faces.get(inc1.faceIndex));
final List<Integer> elms2 =
faceElms.get(faces.get(inc2.faceIndex));
final int A, B, C, D;
if (inc1.reverse) {
final int k =
2 * (inc1.edgeIndex + faces.get(inc1.faceIndex).size());
A = elms1.get(k + 1);
B = elms1.get(k);
} else {
final int k = 2 * inc1.edgeIndex;
A = elms1.get(k);
B = elms1.get(k + 1);
}
if (inc2.reverse) {
final int k = 2 * inc2.edgeIndex;
C = elms2.get(k + 1);
D = elms2.get(k);
} else {
final int k =
2 * (inc2.edgeIndex + faces.get(inc2.faceIndex).size());
C = elms2.get(k);
D = elms2.get(k + 1);
}
ds.redefineOp(2, A, C);
ds.redefineOp(2, B, D);
}
}
}
private void set2opTileMode(
final DynamicDSymbol ds,
final Map<Face, List<Integer>> faceElms)
{
for (int i = 0; i < this.tiles.size(); ++i) {
final List<Pair<Face, Vector>> tile = this.tiles.get(i);
final Map<?, List<Incidence>> facesAtEdge =
collectEdges(tile, true);
for (final List<Incidence> flist: facesAtEdge.values()) {
if (flist.size() != 2) {
final String msg = flist.size() + " faces at an edge";
throw new UnsupportedOperationException(msg);
}
final int D[] = new int[2];
final int E[] = new int[2];
boolean reverse = false;
for (int k = 0; k <= 1; ++k) {
final Incidence inc = flist.get(k);
final Pair<Face, Vector> p = tile.get(inc.faceIndex);
final Face face = p.getFirst();
final Vector shift = p.getSecond();
final List<Pair<Integer, Vector>> taf =
this.tilesAtFace.get(face);
final int t =
taf.indexOf(new Pair<Integer, Vector>(i, shift));
final int x = 2 * (t * face.size() + inc.edgeIndex);
D[k] = faceElms.get(face).get(x);
E[k] = faceElms.get(face).get(x + 1);
if (inc.reverse) {
reverse = !reverse;
}
}
if (reverse) {
ds.redefineOp(2, D[0], E[1]);
ds.redefineOp(2, D[1], E[0]);
} else {
ds.redefineOp(2, D[0], D[1]);
ds.redefineOp(2, E[0], E[1]);
}
}
}
}
private void assertCompleteness(final DelaneySymbol<Integer> ds)
{
final IndexList idcs = new IndexList(ds);
for (final int D: ds.elements()) {
for (int i = 0; i < idcs.size()-1; ++i) {
final int ii = idcs.get(i);
if (!ds.definesOp(ii, D)) {
throw new AssertionError(
"op(" + ii + ", " + D + ") undefined");
}
for (int j = i+1; j < idcs.size(); ++j) {
final int jj = idcs.get(j);
if (!ds.definesV(ii, jj, D)) {
throw new AssertionError(
"v(" + ii + ", " + jj + ", " + D +
") undefined");
}
}
}
}
}
public DSymbol getSymbol() {
return ds;
}
public DSCover<Integer> getCover() {
return cover;
}
public Map<Integer, Point> getPositions() {
return positions;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
f70b3b55b1d48023e1571286045353f451a69a03 | 8627dcb979f1611c6896db180cf2c9f2cb6b7e08 | /JSON/src/net/ukr/ruslana/Address.java | cf68fdb46af59b9db53b20a32cfd362260afb397 | [] | no_license | RuslanaN/JavaPro | f3fad3aa6edb229168a8abdb1c8f1d365abce907 | f8121a51ed41d28774d962883b75a837cb90d7c9 | refs/heads/master | 2016-08-12T13:50:30.512238 | 2016-04-28T11:15:19 | 2016-04-28T11:15:19 | 55,510,551 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 572 | java | package net.ukr.ruslana;
/**
* Created by ruslana on 12.04.16.
*/
public class Address {
private String country;
private String city;
private String street;
public Address(String country, String city, String street) {
this.country = country;
this.city = city;
this.street = street;
}
@Override
public String toString() {
return "Address{" +
"country='" + country + '\'' +
", city='" + city + '\'' +
", street='" + street + '\'' +
'}';
}
}
| [
"ryslananesheret@ukr.net"
] | ryslananesheret@ukr.net |
751d8b090c17ec32b373e61b8ecb9f506f652d04 | a6630866c873395f188bc2860f4e7c9dbdf892de | /contratacao/src/main/java/com/contratacao/service/VagaService.java | 2d5614127f77543d4bfef678b01de5f7e228f584 | [
"MIT"
] | permissive | uervitonsantos/Contratacao | 5fd76e987cc524ba3e870a48aca907532198901e | 82b634bee3fe0ab7a186f2bf26a26b58de9e234a | refs/heads/main | 2023-09-06T03:17:26.600707 | 2021-11-01T21:54:45 | 2021-11-01T21:54:45 | 409,222,593 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,776 | java | /**
CLASE QUE TEM COMO RESPONSABILIDADE GERENCIA AS REGRAS DE NEGOCIOS
*/
package com.contratacao.service;
import java.time.LocalDate;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import com.contratacao.model.Vaga;
import com.contratacao.repository.VagaRepository;
/**
* @author uerviton-santos
*
*/
@Service
public class VagaService {
@Autowired
VagaRepository vagaRepository;
// Metodo utilizado para realizar a persistencia dos dados na tabela Vaga
public String salva(@Valid Vaga vaga) {
vaga.setData(LocalDate.now());
vagaRepository.save(vaga);
return "redirect:/api/vagas";
}
// Metodo utilizado para realizar a busca por ID
public Vaga buscaPorId(@PathVariable Long id) {
return vagaRepository.findById(id).get();
}
// Metodo para realizar a listagem dos dados da tabela Vaga
public List<Vaga> listaTodos() {
return vagaRepository.findAll();
}
// Metodo utilizado para atualizar os dados na tabela Vaga
public Vaga atualiza(@RequestBody Vaga newvaga, @PathVariable Long id) {
return vagaRepository.findById(id).map(vaga -> {
vaga.setId_vaga(newvaga.getId_vaga());
vaga.setTitulo(newvaga.getTitulo());
vaga.setDescricao(newvaga.getDescricao());
vaga.setData_validade(newvaga.getData_validade());
return vagaRepository.save(vaga);
}).orElseGet(() -> {
newvaga.setId_vaga(id);
return vagaRepository.save(newvaga);
});
}
// Metodo utilizado para excluir os dados da tabela Vaga
public void exclui(@PathVariable Long id) {
vagaRepository.deleteById(id);
}
}
| [
"uerviton@gmail.com"
] | uerviton@gmail.com |
a36d0fedcb4a31d3120dffecd5af717206232b65 | 1196a70f9b77837a0ed6189851af5c7832faab45 | /src/main/java/itisx/TicketSeller/Model/IPerson.java | 62e1fda6480a31977ac156d31814ce7c737ce9a1 | [] | no_license | DicuRazvanGabiel/TicketSeller | dba8ec79edf5a96037d29167e1e56f3bf440b819 | fe267aeb75d25c704137f11ceedff6559470af2f | refs/heads/master | 2021-01-24T10:16:18.927099 | 2016-09-28T09:31:03 | 2016-09-28T09:31:03 | 68,895,619 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 410 | java | package itisx.TicketSeller.Model;
import java.io.Serializable;
public interface IPerson extends Serializable{
void setFirstName(String firstName);
void setLastName(String lastName);
void setSocialSecurityNumber(String socialSecurityNumber);
void setIdentityCard(String identityCard);
void setNationality(String nationality);
void setCountry(String country);
void setAddress(String address);
}
| [
"dicu.razvan.gabriel@gmail.com"
] | dicu.razvan.gabriel@gmail.com |
aeee97a9a1c9516dca33efcb2eb1e697ec93915b | 11b26e42f4a95ad20f98d801c438029c3b546724 | /plugin-caches/src/main/java/cn/newcapec/framework/plugins/cache/utils/ObjectUtils.java | 72cfb2d7bff09f488e3e52bdc81d082f9ea92061 | [
"MIT"
] | permissive | 3203317/ppp | 48a81592feddc102c279affe7ed212b494bcada9 | 3d60ca71ac3ab4ccd3210fef42f535220cd79447 | refs/heads/master | 2021-01-17T10:42:47.761033 | 2016-03-25T14:57:07 | 2016-03-25T14:57:07 | 26,523,690 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 6,299 | java | package cn.newcapec.framework.plugins.cache.utils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
public class ObjectUtils {
private final static Log log = LogFactory.getLog(ObjectUtils.class);
public static final String EMPTY_STRING = StringUtils.Symbol.EMPTY;
public static final int DEFAULT_INT_VALUE = Integer.MIN_VALUE;
public static final long DEFAULT_LONG_VALUE = Long.MIN_VALUE;
public static void main(String[] args) {
// log.debug(toLong("1231,233"));
// log.debug(toInteger("1111,161"));
// log.debug(arg0);
// log.debug(arg0);
// log.debug(arg0);
// log.debug(arg0);
// log.debug(arg0);
}
private static Map<Class,Object> INSTANCES = new HashMap<Class,Object>();
public static <T> T newInstance(Class<T> type){
Assert.notNull(type);
try {
return type.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
throw new RuntimeException("实例�? [" + type +" 错误] !");
}
/**
* 转换 Bean �? Field 编码
* Field 的类型为 String �? String[]
* */
public static void convertStringFieldCoding(Object theObject){
PropertyDescriptor[] propDescs = PropertyUtils.getPropertyDescriptors(theObject);
for (int i = 0, n = propDescs.length; i < n; i++) {
String name = propDescs[i].getName();
if (!PropertyUtils.isReadable(theObject, name)) {continue;}
Object value = null;
try {
value = PropertyUtils.getProperty(theObject, name);
} catch (Exception e) {
throw new RuntimeException(e);
}
//log.debug("1111 name ==" + name +", value == " + ObjectUtils.nullSafeToString(value));
if(!PropertyUtils.isWriteable(theObject, name)){continue;}
if(value instanceof String){
value = StringUtils.convertStrByCoding((String)value, "ISO-8859-1");
}
else if(value != null && value.getClass().equals(String[].class)){
String[] strs = (String[])(value);
if(strs.length <= 0){continue;}
String[] values = new String[strs.length];
for(int index=0;index<strs.length;index++){
// log.debug(objs[index]);
values[index] = StringUtils.convertStrByCoding((String)strs[index], "ISO-8859-1");
}
value = values;
}
else{
continue;
}
//log.debug("2222 name ==" + name +", value == " + ObjectUtils.nullSafeToString(value));
try {
PropertyUtils.setProperty(theObject, name, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
// public static <T> T newInstance(Class<T> clazz){
// if(clazz == null){ return null;}
// try {
// return clazz.newInstance();
// } catch (Exception e) {
// throw new RuntimeException("["+clazz+"] 实例化错�?,请检查是否有默认构�?�方�?!");
// }
//
// }
/**
* @see #toString()
* �?个�?�用的toString方法
* 将一个POJO类的 getXXX 的�?�全部输�?
* */
public static String toStringMethod(Object theObject){
try {
StringBuffer sb = new StringBuffer(500);
PropertyDescriptor[] propDescs = PropertyUtils.getPropertyDescriptors(theObject);
for (int i = 0, n = propDescs.length; i < n; i++) {
String name = propDescs[i].getName();
if (!PropertyUtils.isReadable(
theObject, name)) {
continue;
}
Object obj;
try {
obj = PropertyUtils.getProperty(theObject, name);
} catch (UnsupportedOperationException e) {
obj = "Unsupported!";
}
if (obj instanceof Collection || obj instanceof Map) {
sb.append(name).append("=[more...]");
}else {
sb.append(name).append("=[").append(obj).append("]");
}
}
return sb.toString();
} catch (Exception e) {
log.error(theObject.getClass().getCanonicalName()+" toString() Error!",e);
return "";
}
}
public static boolean nullSafeEquals(Object o1, Object o2) {
return org.springframework.util.ObjectUtils.nullSafeEquals(o1, o2);
}
public static int nullSafeHashCode(Object obj) {
return org.springframework.util.ObjectUtils.nullSafeHashCode((Object)obj);
}
public static String nullSafeClassName(Object obj) {
return org.springframework.util.ObjectUtils.nullSafeClassName(obj);
}
public static String nullSafeToString(Object obj) {
return org.springframework.util.ObjectUtils.nullSafeToString(obj);
}
/**
* 如果�? NULL 就返回空�?
* */
public static String nullSafeToEmptyString(Object obj){
if (obj == null) {
return EMPTY_STRING;
}else{
return nullSafeToString(obj);
}
}
public static boolean isFieldInClass(Class<?> clazz, String fieldName) {
if(clazz == null || fieldName == null)
throw new NullPointerException();
Field[] fields = clazz.getDeclaredFields();
//log.debug("fields.length " + fields.length);
for(Field field:fields){
//log.debug(field.getName());
if(field.getName().equals(fieldName)){
return true;
}
}
return false;
}
public static String getFieldName(Class<?> clazz, Class<?> fieldType){
if(clazz == null || fieldType == null)
throw new NullPointerException();
Field[] fields = clazz.getDeclaredFields();
for(Field field:fields){
if(field.getType().equals(fieldType)){
return field.getName();
}
}
throw new IllegalArgumentException("The Field [" + fieldType.getCanonicalName() + "] is not in Object [" + clazz.getCanonicalName() + "] ");
}
public static String format(Object obj){
String result;
if(obj instanceof Collection || obj instanceof Map){
throw new IllegalArgumentException();
}
if(obj == null){
result = null;
}
else if(obj instanceof Date){
result = DateUtils.format((Date)obj,"yyyy-MM-dd");
}
else if(obj instanceof Double){
result = NumberUtils.defaultFormat((Double)obj);
}
else if(obj instanceof Integer){
result = NumberUtils.defaultFormat((Integer)obj);
}
else{
result = obj.toString();
}
return result;
}
}
| [
"3203317@qq.com"
] | 3203317@qq.com |
a515c1211bf2f593631cab9b51f3fff6a7abd0f5 | 74fc4a40288db8189538dbb93dc19db691f540bf | /app/src/main/java/net/londatiga/android/bluetooth/DeviceListActivity.java | 4663dd25deac2e34842db9025c82f3e6837e0a5e | [] | no_license | AjoCes/AndroBluetooth-master | 925ae00cb1ea086127e9390acc054c26b85990b6 | 6ba2334c01e5cd77d8fea2455f61f2a2e61f220d | refs/heads/master | 2021-01-13T00:45:48.352934 | 2015-11-10T15:10:29 | 2015-11-10T15:10:29 | 45,919,742 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,318 | java | package net.londatiga.android.bluetooth;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class DeviceListActivity extends Activity {
private ListView mListView;
private DeviceListAdapter mAdapter;
private ArrayList<BluetoothDevice> mDeviceList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paired_devices);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapter = new DeviceListAdapter(this);
mAdapter.setData(mDeviceList);
mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {
@Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
showToast("Pairing...");
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapter);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
@Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
showToast("Paired");
//new line
Intent intent1 = new Intent(DeviceListActivity.this, JoyStickActivity.class);
startActivity(intent1);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
showToast("Unpaired");
}
mAdapter.notifyDataSetChanged();
}
}
};
} | [
"ajshecesko@gmail.com"
] | ajshecesko@gmail.com |
e2d27de339582c5487609c560c5b8628cdfa94cb | a133545f4e2eb4682a00b1f71c26d790b4e90c5a | /OPEN-LMS/src/main/java/kr/co/soyuni/controller/package-info.java | d37aac233db4d61fecdd40d9043bab274d75851c | [] | no_license | SOYUNI/OPEN-LMS | 928f9e91a7e99f45406029bfc1c8751f4b056738 | 2b7a2bfa5f9daf6abecfccbfcad6e8e473aeede8 | refs/heads/master | 2020-12-24T10:32:40.596651 | 2016-08-16T00:44:02 | 2016-08-16T00:44:02 | 65,773,273 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 32 | java | package kr.co.soyuni.controller; | [
"psy1214@debec.co.kr"
] | psy1214@debec.co.kr |
ee1896cd9c0aa7d128cd9df977e6b0ab86977578 | 4d46ec3b1bf9a12c74cbbc384f0a04f47de4ca49 | /cash-back/src/main/java/com/info/back/utils/JsonFormatUtil.java | ff8184a68514256668f3af1363bb5c0fb0841781 | [] | no_license | lovelimanyi/liquan_cuishou_back | 80e4438c7de6e96b3236ed0c4605607e8de85f62 | 7edf0312e974b84afd7c339548fbbf34e757257f | refs/heads/master | 2022-12-23T16:45:36.449496 | 2020-03-19T09:42:39 | 2020-03-19T09:44:48 | 190,881,567 | 0 | 1 | null | 2022-12-16T05:46:04 | 2019-06-08T11:46:07 | JavaScript | UTF-8 | Java | false | false | 739 | java | package com.info.back.utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.util.StringUtils;
/**
* @author Administrator
* @Description: 格式化json输出
* @CreateTime 2018-05-28 上午 9:52
**/
public class JsonFormatUtil {
/**
* 格式化输出json
*
* @param src 需要格式化的json字符串
* @return
*/
public static String formatJson(Object src) {
if (src == null || StringUtils.isEmpty(src)) {
return null;
}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();//设置出漂亮的格式
Gson gson = gsonBuilder.create();
return gson.toJson(src);
}
}
| [
"hxj@xianjinxia.com"
] | hxj@xianjinxia.com |
11fe73788af336872f6a92db935e9389e739e743 | 400e7b5ccdd6edbdbec2696593119b1a6a6c5a73 | /SwipePullListDemo/SwipeMenuPullLibrary/src/com/handmark/pulltorefresh/library/PullToRefreshBase.java | 72911d7fa48d80a2bf466608806074901449e28c | [
"Apache-2.0"
] | permissive | wbsguo/library | aed80d59e6446ac526fb6854a7807007dc040fa6 | 9f1fc9dbefd6d6c734a5ff056b688a8893438e74 | refs/heads/master | 2021-01-17T16:02:14.874634 | 2016-08-04T08:59:48 | 2016-08-04T08:59:48 | 58,438,700 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 47,449 | java | /*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.handmark.pulltorefresh.library;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.handmark.pulltorefresh.library.internal.FlipLoadingLayout;
import com.handmark.pulltorefresh.library.internal.LoadingLayout;
import com.handmark.pulltorefresh.library.internal.Utils;
import com.handmark.pulltorefresh.library.internal.ViewCompat;
import com.jeremyfeinstein.slidingmenu.lib.R;
public abstract class PullToRefreshBase<T extends View> extends LinearLayout implements IPullToRefresh<T> {
// ===========================================================
// Constants
// ===========================================================
static final boolean DEBUG = true;
static final boolean USE_HW_LAYERS = false;
static final String LOG_TAG = "PullToRefresh";
static final float FRICTION = 2.0f;
public static final int SMOOTH_SCROLL_DURATION_MS = 200;
public static final int SMOOTH_SCROLL_LONG_DURATION_MS = 325;
static final int DEMO_SCROLL_INTERVAL = 225;
static final String STATE_STATE = "ptr_state";
static final String STATE_MODE = "ptr_mode";
static final String STATE_CURRENT_MODE = "ptr_current_mode";
static final String STATE_SCROLLING_REFRESHING_ENABLED = "ptr_disable_scrolling";
static final String STATE_SHOW_REFRESHING_VIEW = "ptr_show_refreshing_view";
static final String STATE_SUPER = "ptr_super";
// ===========================================================
// Fields
// ===========================================================
private int mTouchSlop;
private float mLastMotionX, mLastMotionY;
private float mInitialMotionX, mInitialMotionY;
private boolean mIsBeingDragged = false;
private State mState = State.RESET;
private Mode mMode = Mode.getDefault();
private Mode mCurrentMode;
T mRefreshableView;
private FrameLayout mRefreshableViewWrapper;
private boolean mShowViewWhileRefreshing = true;
private boolean mScrollingWhileRefreshingEnabled = false;
private boolean mFilterTouchEvents = true;
private boolean mOverScrollEnabled = true;
private boolean mLayoutVisibilityChangesEnabled = true;
private Interpolator mScrollAnimationInterpolator;
private AnimationStyle mLoadingAnimationStyle = AnimationStyle.getDefault();
private LoadingLayout mHeaderLayout;
private LoadingLayout mFooterLayout;
private OnRefreshListener<T> mOnRefreshListener;
private OnRefreshListener2<T> mOnRefreshListener2;
private OnPullEventListener<T> mOnPullEventListener;
private SmoothScrollRunnable mCurrentSmoothScrollRunnable;
// ===========================================================
// Constructors
// ===========================================================
public PullToRefreshBase(Context context) {
super(context);
init(context, null);
}
public PullToRefreshBase(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public PullToRefreshBase(Context context, Mode mode) {
super(context);
mMode = mode;
init(context, null);
}
public PullToRefreshBase(Context context, Mode mode, AnimationStyle animStyle) {
super(context);
mMode = mode;
mLoadingAnimationStyle = animStyle;
init(context, null);
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (DEBUG) {
Log.d(LOG_TAG, "addView: " + child.getClass().getSimpleName());
}
final T refreshableView = getRefreshableView();
if (refreshableView instanceof ViewGroup) {
((ViewGroup) refreshableView).addView(child, index, params);
} else {
throw new UnsupportedOperationException("Refreshable View is not a ViewGroup so can't addView");
}
}
@Override
public final boolean demo() {
if (mMode.showHeaderLoadingLayout() && isReadyForPullStart()) {
smoothScrollToAndBack(-getHeaderSize() * 2);
return true;
} else if (mMode.showFooterLoadingLayout() && isReadyForPullEnd()) {
smoothScrollToAndBack(getFooterSize() * 2);
return true;
}
return false;
}
@Override
public final Mode getCurrentMode() {
return mCurrentMode;
}
@Override
public final boolean getFilterTouchEvents() {
return mFilterTouchEvents;
}
@Override
public final ILoadingLayout getLoadingLayoutProxy() {
return getLoadingLayoutProxy(true, true);
}
@Override
public final ILoadingLayout getLoadingLayoutProxy(boolean includeStart, boolean includeEnd) {
return createLoadingLayoutProxy(includeStart, includeEnd);
}
@Override
public final Mode getMode() {
return mMode;
}
@Override
public final T getRefreshableView() {
return mRefreshableView;
}
@Override
public final boolean getShowViewWhileRefreshing() {
return mShowViewWhileRefreshing;
}
@Override
public final State getState() {
return mState;
}
/**
* @deprecated See {@link #isScrollingWhileRefreshingEnabled()}.
*/
public final boolean isDisableScrollingWhileRefreshing() {
return !isScrollingWhileRefreshingEnabled();
}
@Override
public final boolean isPullToRefreshEnabled() {
return mMode.permitsPullToRefresh();
}
@Override
public final boolean isPullToRefreshOverScrollEnabled() {
return VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD && mOverScrollEnabled && OverscrollHelper.isAndroidOverScrollEnabled(mRefreshableView);
}
@Override
public final boolean isRefreshing() {
return mState == State.REFRESHING || mState == State.MANUAL_REFRESHING;
}
@Override
public final boolean isScrollingWhileRefreshingEnabled() {
return mScrollingWhileRefreshingEnabled;
}
/**
* 检测到向上或者向下滑动时候拦截事件
*/
@Override
public final boolean onInterceptTouchEvent(MotionEvent event) {
if (!isPullToRefreshEnabled()) {
return false;
}
final int action = event.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
mIsBeingDragged = false;
return false;
}
if (action != MotionEvent.ACTION_DOWN && mIsBeingDragged) {
return true;
}
switch (action) {
case MotionEvent.ACTION_MOVE: {
// If we're refreshing, and the flag is set. Eat all MOVE events
if (!mScrollingWhileRefreshingEnabled && isRefreshing()) {
return true;
}
if (isReadyForPull()) {
final float y = event.getY(), x = event.getX();
final float diff, oppositeDiff, absDiff;
// We need to use the correct values, based on scroll
// direction
switch (getPullToRefreshScrollDirection()) {
case HORIZONTAL:
diff = x - mLastMotionX;
oppositeDiff = y - mLastMotionY;
break;
case VERTICAL:
default:
diff = y - mLastMotionY;
oppositeDiff = x - mLastMotionX;
break;
}
absDiff = Math.abs(diff);
// 有滑动,y方向上偏移大于x方向上偏移
if (absDiff > mTouchSlop && (!mFilterTouchEvents || absDiff > Math.abs(oppositeDiff))) {
if (mMode.showHeaderLoadingLayout() && diff >= 1f && isReadyForPullStart()) {
// 向下滑动,isReadyForPullStart()表示headView马上要显示出来了
mLastMotionY = y;
mLastMotionX = x;
mIsBeingDragged = true;
if (mMode == Mode.BOTH) {
mCurrentMode = Mode.PULL_FROM_START;
}
} else if (mMode.showFooterLoadingLayout() && diff <= -1f && isReadyForPullEnd()) {
// 向上滑动,isReadyForPullEnd()表示hootView马上要显示出来了
mLastMotionY = y;
mLastMotionX = x;
mIsBeingDragged = true;
if (mMode == Mode.BOTH) {
mCurrentMode = Mode.PULL_FROM_END;
}
}
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
if (isReadyForPull()) {
mLastMotionY = mInitialMotionY = event.getY();
mLastMotionX = mInitialMotionX = event.getX();
mIsBeingDragged = false;
}
break;
}
}
return mIsBeingDragged;
}
@Override
public final void onRefreshComplete() {
if (isRefreshing()) {
setState(State.RESET);
}
}
@Override
public final boolean onTouchEvent(MotionEvent event) {
if (!isPullToRefreshEnabled()) {
return false;
}
// If we're refreshing, and the flag is set. Eat the event
if (!mScrollingWhileRefreshingEnabled && isRefreshing()) {
return true;
}
if (event.getAction() == MotionEvent.ACTION_DOWN && event.getEdgeFlags() != 0) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE: {
if (mIsBeingDragged) {
mLastMotionY = event.getY();
mLastMotionX = event.getX();
pullEvent();
return true;
}
break;
}
case MotionEvent.ACTION_DOWN: {
if (isReadyForPull()) {
mLastMotionY = mInitialMotionY = event.getY();
mLastMotionX = mInitialMotionX = event.getX();
return true;
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
if (mIsBeingDragged) {
mIsBeingDragged = false;
if (mState == State.RELEASE_TO_REFRESH && (null != mOnRefreshListener || null != mOnRefreshListener2)) {
setState(State.REFRESHING, true);
return true;
}
// If we're already refreshing, just scroll back to the top
if (isRefreshing()) {
smoothScrollTo(0);
return true;
}
// If we haven't returned by here, then we're not in a state
// to pull, so just reset
setState(State.RESET);
return true;
}
break;
}
}
return false;
}
public final void setScrollingWhileRefreshingEnabled(boolean allowScrollingWhileRefreshing) {
mScrollingWhileRefreshingEnabled = allowScrollingWhileRefreshing;
}
/**
* @deprecated See {@link #setScrollingWhileRefreshingEnabled(boolean)}
*/
public void setDisableScrollingWhileRefreshing(boolean disableScrollingWhileRefreshing) {
setScrollingWhileRefreshingEnabled(!disableScrollingWhileRefreshing);
}
@Override
public final void setFilterTouchEvents(boolean filterEvents) {
mFilterTouchEvents = filterEvents;
}
/**
* @deprecated You should now call this method on the result of
* {@link #getLoadingLayoutProxy()}.
*/
public void setLastUpdatedLabel(CharSequence label) {
getLoadingLayoutProxy().setLastUpdatedLabel(label);
}
/**
* @deprecated You should now call this method on the result of
* {@link #getLoadingLayoutProxy()}.
*/
public void setLoadingDrawable(Drawable drawable) {
getLoadingLayoutProxy().setLoadingDrawable(drawable);
}
/**
* @deprecated You should now call this method on the result of
* {@link #getLoadingLayoutProxy(boolean, boolean)}.
*/
public void setLoadingDrawable(Drawable drawable, Mode mode) {
getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setLoadingDrawable(drawable);
}
@Override
public void setLongClickable(boolean longClickable) {
getRefreshableView().setLongClickable(longClickable);
}
@Override
public final void setMode(Mode mode) {
if (mode != mMode) {
if (DEBUG) {
Log.d(LOG_TAG, "Setting mode to: " + mode);
}
mMode = mode;
updateUIForMode();
}
}
public void setOnPullEventListener(OnPullEventListener<T> listener) {
mOnPullEventListener = listener;
}
@Override
public final void setOnRefreshListener(OnRefreshListener<T> listener) {
mOnRefreshListener = listener;
mOnRefreshListener2 = null;
}
@Override
public final void setOnRefreshListener(OnRefreshListener2<T> listener) {
mOnRefreshListener2 = listener;
mOnRefreshListener = null;
}
/**
* @deprecated You should now call this method on the result of
* {@link #getLoadingLayoutProxy()}.
*/
public void setPullLabel(CharSequence pullLabel) {
getLoadingLayoutProxy().setPullLabel(pullLabel);
}
/**
* @deprecated You should now call this method on the result of
* {@link #getLoadingLayoutProxy(boolean, boolean)}.
*/
public void setPullLabel(CharSequence pullLabel, Mode mode) {
getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setPullLabel(pullLabel);
}
/**
* @param enable
* Whether Pull-To-Refresh should be used
* @deprecated This simple calls setMode with an appropriate mode based on
* the passed value.
*/
public final void setPullToRefreshEnabled(boolean enable) {
setMode(enable ? Mode.getDefault() : Mode.DISABLED);
}
@Override
public final void setPullToRefreshOverScrollEnabled(boolean enabled) {
mOverScrollEnabled = enabled;
}
@Override
public final void setRefreshing() {
setRefreshing(true);
}
@Override
public final void setRefreshing(boolean doScroll) {
if (!isRefreshing()) {
setState(State.MANUAL_REFRESHING, doScroll);
}
}
/**
* @deprecated You should now call this method on the result of
* {@link #getLoadingLayoutProxy()}.
*/
public void setRefreshingLabel(CharSequence refreshingLabel) {
getLoadingLayoutProxy().setRefreshingLabel(refreshingLabel);
}
/**
* @deprecated You should now call this method on the result of
* {@link #getLoadingLayoutProxy(boolean, boolean)}.
*/
public void setRefreshingLabel(CharSequence refreshingLabel, Mode mode) {
getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setRefreshingLabel(refreshingLabel);
}
/**
* @deprecated You should now call this method on the result of
* {@link #getLoadingLayoutProxy()}.
*/
public void setReleaseLabel(CharSequence releaseLabel) {
setReleaseLabel(releaseLabel, Mode.BOTH);
}
/**
* @deprecated You should now call this method on the result of
* {@link #getLoadingLayoutProxy(boolean, boolean)}.
*/
public void setReleaseLabel(CharSequence releaseLabel, Mode mode) {
getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setReleaseLabel(releaseLabel);
}
public void setScrollAnimationInterpolator(Interpolator interpolator) {
mScrollAnimationInterpolator = interpolator;
}
@Override
public final void setShowViewWhileRefreshing(boolean showView) {
mShowViewWhileRefreshing = showView;
}
/**
* @return Either {@link Orientation#VERTICAL} or
* {@link Orientation#HORIZONTAL} depending on the scroll direction.
*/
public abstract Orientation getPullToRefreshScrollDirection();
final void setState(State state, final boolean... params) {
mState = state;
if (DEBUG) {
Log.d(LOG_TAG, "State: " + mState.name());
}
switch (mState) {
case RESET:
onReset();
break;
case PULL_TO_REFRESH:
onPullToRefresh();
break;
case RELEASE_TO_REFRESH:
onReleaseToRefresh();
break;
case REFRESHING:
case MANUAL_REFRESHING:
onRefreshing(params[0]);
break;
case OVERSCROLLING:
// NO-OP
break;
}
// Call OnPullEventListener
if (null != mOnPullEventListener) {
mOnPullEventListener.onPullEvent(this, mState, mCurrentMode);
}
}
/**
* Used internally for adding view. Need because we override addView to
* pass-through to the Refreshable View
*/
protected final void addViewInternal(View child, int index, ViewGroup.LayoutParams params) {
super.addView(child, index, params);
}
/**
* Used internally for adding view. Need because we override addView to
* pass-through to the Refreshable View
*/
protected final void addViewInternal(View child, ViewGroup.LayoutParams params) {
super.addView(child, -1, params);
}
protected LoadingLayout createLoadingLayout(Context context, Mode mode, TypedArray attrs) {
LoadingLayout layout = mLoadingAnimationStyle.createLoadingLayout(context, mode, getPullToRefreshScrollDirection(), attrs);
layout.setVisibility(View.INVISIBLE);
return layout;
}
/**
* Used internally for {@link #getLoadingLayoutProxy(boolean, boolean)}.
* Allows derivative classes to include any extra LoadingLayouts.
*/
protected LoadingLayoutProxy createLoadingLayoutProxy(final boolean includeStart, final boolean includeEnd) {
LoadingLayoutProxy proxy = new LoadingLayoutProxy();
if (includeStart && mMode.showHeaderLoadingLayout()) {
proxy.addLayout(mHeaderLayout);
}
if (includeEnd && mMode.showFooterLoadingLayout()) {
proxy.addLayout(mFooterLayout);
}
return proxy;
}
/**
* This is implemented by derived classes to return the created View. If you
* need to use a custom View (such as a custom ListView), override this
* method and return an instance of your custom class.
* <p/>
* Be sure to set the ID of the view in this method, especially if you're
* using a ListActivity or ListFragment.
*
* @param context
* Context to create view with
* @param attrs
* AttributeSet from wrapped class. Means that anything you
* include in the XML layout declaration will be routed to the
* created View
* @return New instance of the Refreshable View
*/
protected abstract T createRefreshableView(Context context, AttributeSet attrs);
protected final void disableLoadingLayoutVisibilityChanges() {
mLayoutVisibilityChangesEnabled = false;
}
protected final LoadingLayout getFooterLayout() {
return mFooterLayout;
}
protected final int getFooterSize() {
return mFooterLayout.getContentSize();
}
protected final LoadingLayout getHeaderLayout() {
return mHeaderLayout;
}
protected final int getHeaderSize() {
return mHeaderLayout.getContentSize();
}
protected int getPullToRefreshScrollDuration() {
return SMOOTH_SCROLL_DURATION_MS;
}
protected int getPullToRefreshScrollDurationLonger() {
return SMOOTH_SCROLL_LONG_DURATION_MS;
}
protected FrameLayout getRefreshableViewWrapper() {
return mRefreshableViewWrapper;
}
/**
* Allows Derivative classes to handle the XML Attrs without creating a
* TypedArray themsevles
*
* @param a
* - TypedArray of PullToRefresh Attributes
*/
protected void handleStyledAttributes(TypedArray a) {
}
/**
* Implemented by derived class to return whether the View is in a state
* where the user can Pull to Refresh by scrolling from the end.
*
* @return true if the View is currently in the correct state (for example,
* bottom of a ListView)
*/
protected abstract boolean isReadyForPullEnd();
/**
* Implemented by derived class to return whether the View is in a state
* where the user can Pull to Refresh by scrolling from the start.
*
* @return true if the View is currently the correct state (for example, top
* of a ListView)
*/
protected abstract boolean isReadyForPullStart();
/**
* Called by {@link #onRestoreInstanceState(Parcelable)} so that derivative
* classes can handle their saved instance state.
*
* @param savedInstanceState
* - Bundle which contains saved instance state.
*/
protected void onPtrRestoreInstanceState(Bundle savedInstanceState) {
}
/**
* Called by {@link #onSaveInstanceState()} so that derivative classes can
* save their instance state.
*
* @param saveState
* - Bundle to be updated with saved state.
*/
protected void onPtrSaveInstanceState(Bundle saveState) {
}
/**
* Called when the UI has been to be updated to be in the
* {@link State#PULL_TO_REFRESH} state.
*/
protected void onPullToRefresh() {
switch (mCurrentMode) {
case PULL_FROM_END:
mFooterLayout.pullToRefresh();
break;
case PULL_FROM_START:
mHeaderLayout.pullToRefresh();
break;
default:
// NO-OP
break;
}
}
/**
* Called when the UI has been to be updated to be in the
* {@link State#REFRESHING} or {@link State#MANUAL_REFRESHING} state.
*
* @param doScroll
* - Whether the UI should scroll for this event.
*/
protected void onRefreshing(final boolean doScroll) {
if (mMode.showHeaderLoadingLayout()) {
mHeaderLayout.refreshing();
}
if (mMode.showFooterLoadingLayout()) {
mFooterLayout.refreshing();
}
if (doScroll) {
if (mShowViewWhileRefreshing) {
// Call Refresh Listener when the Scroll has finished
OnSmoothScrollFinishedListener listener = new OnSmoothScrollFinishedListener() {
@Override
public void onSmoothScrollFinished() {
callRefreshListener();
}
};
switch (mCurrentMode) {
case MANUAL_REFRESH_ONLY:
case PULL_FROM_END:
smoothScrollTo(getFooterSize(), listener);
break;
default:
case PULL_FROM_START:
smoothScrollTo(-getHeaderSize(), listener);
break;
}
} else {
smoothScrollTo(0);
}
} else {
// We're not scrolling, so just call Refresh Listener now
callRefreshListener();
}
}
/**
* Called when the UI has been to be updated to be in the
* {@link State#RELEASE_TO_REFRESH} state.
*/
protected void onReleaseToRefresh() {
switch (mCurrentMode) {
case PULL_FROM_END:
mFooterLayout.releaseToRefresh();
break;
case PULL_FROM_START:
mHeaderLayout.releaseToRefresh();
break;
default:
// NO-OP
break;
}
}
/**
* Called when the UI has been to be updated to be in the
* {@link State#RESET} state.
*/
protected void onReset() {
mIsBeingDragged = false;
mLayoutVisibilityChangesEnabled = true;
// Always reset both layouts, just in case...
mHeaderLayout.reset();
mFooterLayout.reset();
smoothScrollTo(0);
}
@Override
protected final void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
setMode(Mode.mapIntToValue(bundle.getInt(STATE_MODE, 0)));
mCurrentMode = Mode.mapIntToValue(bundle.getInt(STATE_CURRENT_MODE, 0));
mScrollingWhileRefreshingEnabled = bundle.getBoolean(STATE_SCROLLING_REFRESHING_ENABLED, false);
mShowViewWhileRefreshing = bundle.getBoolean(STATE_SHOW_REFRESHING_VIEW, true);
// Let super Restore Itself
super.onRestoreInstanceState(bundle.getParcelable(STATE_SUPER));
State viewState = State.mapIntToValue(bundle.getInt(STATE_STATE, 0));
if (viewState == State.REFRESHING || viewState == State.MANUAL_REFRESHING) {
setState(viewState, true);
}
// Now let derivative classes restore their state
onPtrRestoreInstanceState(bundle);
return;
}
super.onRestoreInstanceState(state);
}
@Override
protected final Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
// Let derivative classes get a chance to save state first, that way we
// can make sure they don't overrite any of our values
onPtrSaveInstanceState(bundle);
bundle.putInt(STATE_STATE, mState.getIntValue());
bundle.putInt(STATE_MODE, mMode.getIntValue());
bundle.putInt(STATE_CURRENT_MODE, mCurrentMode.getIntValue());
bundle.putBoolean(STATE_SCROLLING_REFRESHING_ENABLED, mScrollingWhileRefreshingEnabled);
bundle.putBoolean(STATE_SHOW_REFRESHING_VIEW, mShowViewWhileRefreshing);
bundle.putParcelable(STATE_SUPER, super.onSaveInstanceState());
return bundle;
}
@Override
protected final void onSizeChanged(int w, int h, int oldw, int oldh) {
if (DEBUG) {
Log.d(LOG_TAG, String.format("onSizeChanged. W: %d, H: %d", w, h));
}
super.onSizeChanged(w, h, oldw, oldh);
// We need to update the header/footer when our size changes
refreshLoadingViewsSize();
// Update the Refreshable View layout
refreshRefreshableViewSize(w, h);
/**
* As we're currently in a Layout Pass, we need to schedule another one
* to layout any changes we've made here
*/
post(new Runnable() {
@Override
public void run() {
requestLayout();
}
});
}
/**
* Re-measure the Loading Views height, and adjust internal padding as
* necessary
*/
protected final void refreshLoadingViewsSize() {
final int maximumPullScroll = (int) (getMaximumPullScroll() * 1.2f);
int pLeft = getPaddingLeft();
int pTop = getPaddingTop();
int pRight = getPaddingRight();
int pBottom = getPaddingBottom();
switch (getPullToRefreshScrollDirection()) {
case HORIZONTAL:
if (mMode.showHeaderLoadingLayout()) {
mHeaderLayout.setWidth(maximumPullScroll);
pLeft = -maximumPullScroll;
} else {
pLeft = 0;
}
if (mMode.showFooterLoadingLayout()) {
mFooterLayout.setWidth(maximumPullScroll);
pRight = -maximumPullScroll;
} else {
pRight = 0;
}
break;
case VERTICAL:
if (mMode.showHeaderLoadingLayout()) {
mHeaderLayout.setHeight(maximumPullScroll);
pTop = -maximumPullScroll;
} else {
pTop = 0;
}
if (mMode.showFooterLoadingLayout()) {
mFooterLayout.setHeight(maximumPullScroll);
pBottom = -maximumPullScroll;
} else {
pBottom = 0;
}
break;
}
if (DEBUG) {
Log.d(LOG_TAG, String.format("Setting Padding. L: %d, T: %d, R: %d, B: %d", pLeft, pTop, pRight, pBottom));
}
setPadding(pLeft, pTop, pRight, pBottom);
}
protected final void refreshRefreshableViewSize(int width, int height) {
// We need to set the Height of the Refreshable View to the same as
// this layout
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mRefreshableViewWrapper.getLayoutParams();
switch (getPullToRefreshScrollDirection()) {
case HORIZONTAL:
if (lp.width != width) {
lp.width = width;
mRefreshableViewWrapper.requestLayout();
}
break;
case VERTICAL:
if (lp.height != height) {
lp.height = height;
mRefreshableViewWrapper.requestLayout();
}
break;
}
}
/**
* Helper method which just calls scrollTo() in the correct scrolling
* direction.
*
* @param value
* - New Scroll value
*/
protected final void setHeaderScroll(int value) {
if (DEBUG) {
Log.d(LOG_TAG, "setHeaderScroll: " + value);
}
// Clamp value to with pull scroll range
final int maximumPullScroll = getMaximumPullScroll();
value = Math.min(maximumPullScroll, Math.max(-maximumPullScroll, value));
if (mLayoutVisibilityChangesEnabled) {
if (value < 0) {
//向下滑动,可以用value设置动画
mHeaderLayout.setVisibility(View.VISIBLE);
} else if (value > 0) {
//向上滑动,可以用value设置动画
mFooterLayout.setVisibility(View.VISIBLE);
} else {
mHeaderLayout.setVisibility(View.INVISIBLE);
mFooterLayout.setVisibility(View.INVISIBLE);
}
}
if (USE_HW_LAYERS) {
/**
* Use a Hardware Layer on the Refreshable View if we've scrolled at
* all. We don't use them on the Header/Footer Views as they change
* often, which would negate any HW layer performance boost.
*/
ViewCompat.setLayerType(mRefreshableViewWrapper, value != 0 ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE);
}
switch (getPullToRefreshScrollDirection()) {
case VERTICAL:
scrollTo(0, value);
break;
case HORIZONTAL:
scrollTo(value, 0);
break;
}
}
/**
* Smooth Scroll to position using the default duration of
* {@value #SMOOTH_SCROLL_DURATION_MS} ms.
*
* @param scrollValue
* - Position to scroll to
*/
protected final void smoothScrollTo(int scrollValue) {
smoothScrollTo(scrollValue, getPullToRefreshScrollDuration());
}
/**
* Smooth Scroll to position using the default duration of
* {@value #SMOOTH_SCROLL_DURATION_MS} ms.
*
* @param scrollValue
* - Position to scroll to
* @param listener
* - Listener for scroll
*/
protected final void smoothScrollTo(int scrollValue, OnSmoothScrollFinishedListener listener) {
smoothScrollTo(scrollValue, getPullToRefreshScrollDuration(), 0, listener);
}
/**
* Smooth Scroll to position using the longer default duration of
* {@value #SMOOTH_SCROLL_LONG_DURATION_MS} ms.
*
* @param scrollValue
* - Position to scroll to
*/
protected final void smoothScrollToLonger(int scrollValue) {
smoothScrollTo(scrollValue, getPullToRefreshScrollDurationLonger());
}
/**
* Updates the View State when the mode has been set. This does not do any
* checking that the mode is different to current state so always updates.
*/
protected void updateUIForMode() {
// We need to use the correct LayoutParam values, based on scroll
// direction
final LinearLayout.LayoutParams lp = getLoadingLayoutLayoutParams();
// Remove Header, and then add Header Loading View again if needed
if (this == mHeaderLayout.getParent()) {
removeView(mHeaderLayout);
}
if (mMode.showHeaderLoadingLayout()) {
addViewInternal(mHeaderLayout, 0, lp);
}
// Remove Footer, and then add Footer Loading View again if needed
if (this == mFooterLayout.getParent()) {
removeView(mFooterLayout);
}
if (mMode.showFooterLoadingLayout()) {
addViewInternal(mFooterLayout, lp);
}
// Hide Loading Views
refreshLoadingViewsSize();
// If we're not using Mode.BOTH, set mCurrentMode to mMode, otherwise
// set it to pull down
resetCurrentMode();
}
public void resetCurrentMode() {
if (!isRefreshing()) {
mCurrentMode = (mMode != Mode.BOTH) ? mMode : Mode.PULL_FROM_START;
}
}
private void addRefreshableView(Context context, T refreshableView) {
mRefreshableViewWrapper = new FrameLayout(context);
mRefreshableViewWrapper.addView(refreshableView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
addViewInternal(mRefreshableViewWrapper, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
private void callRefreshListener() {
if (null != mOnRefreshListener) {
mOnRefreshListener.onRefresh(this);
} else if (null != mOnRefreshListener2) {
if (mCurrentMode == Mode.PULL_FROM_START) {
mOnRefreshListener2.onPullDownToRefresh(this);
} else if (mCurrentMode == Mode.PULL_FROM_END) {
mOnRefreshListener2.onPullUpToRefresh(this);
}
}
}
@SuppressWarnings("deprecation")
private void init(Context context, AttributeSet attrs) {
switch (getPullToRefreshScrollDirection()) {
case HORIZONTAL:
setOrientation(LinearLayout.HORIZONTAL);
break;
case VERTICAL:
default:
setOrientation(LinearLayout.VERTICAL);
break;
}
setGravity(Gravity.CENTER);
ViewConfiguration config = ViewConfiguration.get(context);
mTouchSlop = config.getScaledTouchSlop();
// Styleables from XML
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PullToRefresh);
if (a.hasValue(R.styleable.PullToRefresh_ptrMode)) {
mMode = Mode.mapIntToValue(a.getInteger(R.styleable.PullToRefresh_ptrMode, 0));
}
if (a.hasValue(R.styleable.PullToRefresh_ptrAnimationStyle)) {
mLoadingAnimationStyle = AnimationStyle.mapIntToValue(a.getInteger(R.styleable.PullToRefresh_ptrAnimationStyle, 0));
}
// Refreshable View
// By passing the attrs, we can add ListView/GridView params via XML
mRefreshableView = createRefreshableView(context, attrs);
addRefreshableView(context, mRefreshableView);
// We need to create now layouts now
mHeaderLayout = createLoadingLayout(context, Mode.PULL_FROM_START, a);
mFooterLayout = createLoadingLayout(context, Mode.PULL_FROM_END, a);
/**
* Styleables from XML
*/
if (a.hasValue(R.styleable.PullToRefresh_ptrRefreshableViewBackground)) {
Drawable background = a.getDrawable(R.styleable.PullToRefresh_ptrRefreshableViewBackground);
if (null != background) {
mRefreshableView.setBackgroundDrawable(background);
}
} else if (a.hasValue(R.styleable.PullToRefresh_ptrAdapterViewBackground)) {
Utils.warnDeprecation("ptrAdapterViewBackground", "ptrRefreshableViewBackground");
Drawable background = a.getDrawable(R.styleable.PullToRefresh_ptrAdapterViewBackground);
if (null != background) {
mRefreshableView.setBackgroundDrawable(background);
}
}
if (a.hasValue(R.styleable.PullToRefresh_ptrOverScroll)) {
mOverScrollEnabled = a.getBoolean(R.styleable.PullToRefresh_ptrOverScroll, true);
}
if (a.hasValue(R.styleable.PullToRefresh_ptrScrollingWhileRefreshingEnabled)) {
mScrollingWhileRefreshingEnabled = a.getBoolean(R.styleable.PullToRefresh_ptrScrollingWhileRefreshingEnabled, false);
}
// Let the derivative classes have a go at handling attributes, then
// recycle them...
handleStyledAttributes(a);
a.recycle();
// Finally update the UI for the modes
updateUIForMode();
}
/**
* PULL_FROM_START模式下,第一个条目可见返回true PULL_FROM_END模式下,最后一个条目可见返回true
* BOTH模式下,第一个条目可见或者最后一个条目可见返回true
*
* @return
*/
private boolean isReadyForPull() {
switch (mMode) {
case PULL_FROM_START:
return isReadyForPullStart();
case PULL_FROM_END:
return isReadyForPullEnd();
case BOTH:
return isReadyForPullEnd() || isReadyForPullStart();
default:
return false;
}
}
/**
* Actions a Pull Event
*
* @return true if the Event has been handled, false if there has been no
* change
*/
private void pullEvent() {
final int newScrollValue;
final int itemDimension;
final float initialMotionValue, lastMotionValue;
switch (getPullToRefreshScrollDirection()) {
case HORIZONTAL:
initialMotionValue = mInitialMotionX;
lastMotionValue = mLastMotionX;
break;
case VERTICAL:
default:
initialMotionValue = mInitialMotionY;// down的时候初始化
lastMotionValue = mLastMotionY;// 移动的时候就会被赋值
break;
}
// footView和headView出现时候调用
switch (mCurrentMode) {
case PULL_FROM_END:
newScrollValue = Math.round(Math.max(initialMotionValue - lastMotionValue, 0) / FRICTION);// 向上滑动时,newScrollValue会越来越大
itemDimension = getFooterSize();
break;
case PULL_FROM_START:
default:
newScrollValue = Math.round(Math.min(initialMotionValue - lastMotionValue, 0) / FRICTION);// 向下滑动时,newScrollValue会越来越小(0-->-80)
itemDimension = getHeaderSize();
break;
}
setHeaderScroll(newScrollValue);
if (newScrollValue != 0 && !isRefreshing()) {
float scale = Math.abs(newScrollValue) / (float) itemDimension;
//滑动的距离newScrollValue和headView/footView高度的比例,从0-->0.1-->1.0-->3.0
switch (mCurrentMode) {
case PULL_FROM_END:
mFooterLayout.onPull(scale);
break;
case PULL_FROM_START:
default:
mHeaderLayout.onPull(scale);
break;
}
if (mState != State.PULL_TO_REFRESH && itemDimension >= Math.abs(newScrollValue)) {
setState(State.PULL_TO_REFRESH);
} else if (mState == State.PULL_TO_REFRESH && itemDimension < Math.abs(newScrollValue)) {
setState(State.RELEASE_TO_REFRESH);
}
}
}
private LinearLayout.LayoutParams getLoadingLayoutLayoutParams() {
switch (getPullToRefreshScrollDirection()) {
case HORIZONTAL:
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
case VERTICAL:
default:
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
}
private int getMaximumPullScroll() {
switch (getPullToRefreshScrollDirection()) {
case HORIZONTAL:
return Math.round(getWidth() / FRICTION);
case VERTICAL:
default:
return Math.round(getHeight() / FRICTION);
}
}
/**
* Smooth Scroll to position using the specific duration
*
* @param scrollValue
* - Position to scroll to
* @param duration
* - Duration of animation in milliseconds
*/
private final void smoothScrollTo(int scrollValue, long duration) {
smoothScrollTo(scrollValue, duration, 0, null);
}
private final void smoothScrollTo(int newScrollValue, long duration, long delayMillis, OnSmoothScrollFinishedListener listener) {
if (null != mCurrentSmoothScrollRunnable) {
mCurrentSmoothScrollRunnable.stop();
}
final int oldScrollValue;
switch (getPullToRefreshScrollDirection()) {
case HORIZONTAL:
oldScrollValue = getScrollX();
break;
case VERTICAL:
default:
oldScrollValue = getScrollY();
break;
}
if (oldScrollValue != newScrollValue) {
if (null == mScrollAnimationInterpolator) {
// Default interpolator is a Decelerate Interpolator
mScrollAnimationInterpolator = new DecelerateInterpolator();
}
mCurrentSmoothScrollRunnable = new SmoothScrollRunnable(oldScrollValue, newScrollValue, duration, listener);
if (delayMillis > 0) {
postDelayed(mCurrentSmoothScrollRunnable, delayMillis);
} else {
post(mCurrentSmoothScrollRunnable);
}
}
}
private final void smoothScrollToAndBack(int y) {
smoothScrollTo(y, SMOOTH_SCROLL_DURATION_MS, 0, new OnSmoothScrollFinishedListener() {
@Override
public void onSmoothScrollFinished() {
smoothScrollTo(0, SMOOTH_SCROLL_DURATION_MS, DEMO_SCROLL_INTERVAL, null);
}
});
}
public static enum AnimationStyle {
/**
* This is the default for Android-PullToRefresh. Allows you to use any
* drawable, which is automatically rotated and used as a Progress Bar.
*/
ROTATE,
/**
* This is the old default, and what is commonly used on iOS. Uses an
* arrow image which flips depending on where the user has scrolled.
*/
FLIP;
static AnimationStyle getDefault() {
return ROTATE;
}
/**
* Maps an int to a specific mode. This is needed when saving state, or
* inflating the view from XML where the mode is given through a attr
* int.
*
* @param modeInt
* - int to map a Mode to
* @return Mode that modeInt maps to, or ROTATE by default.
*/
static AnimationStyle mapIntToValue(int modeInt) {
switch (modeInt) {
case 0x0:
default:
return ROTATE;
case 0x1:
return FLIP;
}
}
LoadingLayout createLoadingLayout(Context context, Mode mode, Orientation scrollDirection, TypedArray attrs) {
switch (this) {
case ROTATE:
default:
// return new RotateLoadingLayout(context, mode,
// scrollDirection, attrs);
return new FlipLoadingLayout(context, mode, scrollDirection, attrs);
case FLIP:
return new FlipLoadingLayout(context, mode, scrollDirection, attrs);
}
}
}
public static enum Mode {
/**
* Disable all Pull-to-Refresh gesture and Refreshing handling
*/
DISABLED(0x0),
/**
* Only allow the user to Pull from the start of the Refreshable View to
* refresh. The start is either the Top or Left, depending on the
* scrolling direction.
*/
PULL_FROM_START(0x1),
/**
* Only allow the user to Pull from the end of the Refreshable View to
* refresh. The start is either the Bottom or Right, depending on the
* scrolling direction.
*/
PULL_FROM_END(0x2),
/**
* Allow the user to both Pull from the start, from the end to refresh.
*/
BOTH(0x3),
/**
* Disables Pull-to-Refresh gesture handling, but allows manually
* setting the Refresh state via
* {@link PullToRefreshBase#setRefreshing() setRefreshing()}.
*/
MANUAL_REFRESH_ONLY(0x4);
/**
* @deprecated Use {@link #PULL_FROM_START} from now on.
*/
public static Mode PULL_DOWN_TO_REFRESH = Mode.PULL_FROM_START;
/**
* @deprecated Use {@link #PULL_FROM_END} from now on.
*/
public static Mode PULL_UP_TO_REFRESH = Mode.PULL_FROM_END;
/**
* Maps an int to a specific mode. This is needed when saving state, or
* inflating the view from XML where the mode is given through a attr
* int.
*
* @param modeInt
* - int to map a Mode to
* @return Mode that modeInt maps to, or PULL_FROM_START by default.
*/
static Mode mapIntToValue(final int modeInt) {
for (Mode value : Mode.values()) {
if (modeInt == value.getIntValue()) {
return value;
}
}
// If not, return default
return getDefault();
}
static Mode getDefault() {
return PULL_FROM_START;
}
private int mIntValue;
// The modeInt values need to match those from attrs.xml
Mode(int modeInt) {
mIntValue = modeInt;
}
/**
* @return true if the mode permits Pull-to-Refresh
*/
boolean permitsPullToRefresh() {
return !(this == DISABLED || this == MANUAL_REFRESH_ONLY);
}
/**
* @return true if this mode wants the Loading Layout Header to be shown
*/
public boolean showHeaderLoadingLayout() {
return this == PULL_FROM_START || this == BOTH;
}
/**
* @return true if this mode wants the Loading Layout Footer to be shown
*/
public boolean showFooterLoadingLayout() {
return this == PULL_FROM_END || this == BOTH || this == MANUAL_REFRESH_ONLY;
}
int getIntValue() {
return mIntValue;
}
}
// ===========================================================
// Inner, Anonymous Classes, and Enumerations
// ===========================================================
/**
* Simple Listener that allows you to be notified when the user has scrolled
* to the end of the AdapterView. See (
* {@link PullToRefreshAdapterViewBase#setOnLastItemVisibleListener}.
*
* @author Chris Banes
*/
public static interface OnLastItemVisibleListener {
/**
* Called when the user has scrolled to the end of the list
*/
public void onLastItemVisible();
}
/**
* Listener that allows you to be notified when the user has started or
* finished a touch event. Useful when you want to append extra UI events
* (such as sounds). See (
* {@link PullToRefreshAdapterViewBase#setOnPullEventListener}.
*
* @author Chris Banes
*/
public static interface OnPullEventListener<V extends View> {
/**
* Called when the internal state has been changed, usually by the user
* pulling.
*
* @param refreshView
* - View which has had it's state change.
* @param state
* - The new state of View.
* @param direction
* - One of {@link Mode#PULL_FROM_START} or
* {@link Mode#PULL_FROM_END} depending on which direction
* the user is pulling. Only useful when <var>state</var> is
* {@link State#PULL_TO_REFRESH} or
* {@link State#RELEASE_TO_REFRESH}.
*/
public void onPullEvent(final PullToRefreshBase<V> refreshView, State state, Mode direction);
}
/**
* Simple Listener to listen for any callbacks to Refresh.
*
* @author Chris Banes
*/
public static interface OnRefreshListener<V extends View> {
/**
* onRefresh will be called for both a Pull from start, and Pull from
* end
*/
public void onRefresh(final PullToRefreshBase<V> refreshView);
}
/**
* An advanced version of the Listener to listen for callbacks to Refresh.
* This listener is different as it allows you to differentiate between Pull
* Ups, and Pull Downs.
*
* @author Chris Banes
*/
public static interface OnRefreshListener2<V extends View> {
// TODO These methods need renaming to START/END rather than DOWN/UP
/**
* onPullDownToRefresh will be called only when the user has Pulled from
* the start, and released.
*/
public void onPullDownToRefresh(final PullToRefreshBase<V> refreshView);
/**
* onPullUpToRefresh will be called only when the user has Pulled from
* the end, and released.
*/
public void onPullUpToRefresh(final PullToRefreshBase<V> refreshView);
}
public static enum Orientation {
VERTICAL, HORIZONTAL;
}
public static enum State {
/**
* When the UI is in a state which means that user is not interacting
* with the Pull-to-Refresh function.
*/
RESET(0x0),
/**
* When the UI is being pulled by the user, but has not been pulled far
* enough so that it refreshes when released.
*/
PULL_TO_REFRESH(0x1),
/**
* When the UI is being pulled by the user, and <strong>has</strong>
* been pulled far enough so that it will refresh when released.
*/
RELEASE_TO_REFRESH(0x2),
/**
* When the UI is currently refreshing, caused by a pull gesture.
*/
REFRESHING(0x8),
/**
* When the UI is currently refreshing, caused by a call to
* {@link PullToRefreshBase#setRefreshing() setRefreshing()}.
*/
MANUAL_REFRESHING(0x9),
/**
* When the UI is currently overscrolling, caused by a fling on the
* Refreshable View.
*/
OVERSCROLLING(0x10);
/**
* Maps an int to a specific state. This is needed when saving state.
*
* @param stateInt
* - int to map a State to
* @return State that stateInt maps to
*/
static State mapIntToValue(final int stateInt) {
for (State value : State.values()) {
if (stateInt == value.getIntValue()) {
return value;
}
}
// If not, return default
return RESET;
}
private int mIntValue;
State(int intValue) {
mIntValue = intValue;
}
int getIntValue() {
return mIntValue;
}
}
final class SmoothScrollRunnable implements Runnable {
private final Interpolator mInterpolator;
private final int mScrollToY;
private final int mScrollFromY;
private final long mDuration;
private OnSmoothScrollFinishedListener mListener;
private boolean mContinueRunning = true;
private long mStartTime = -1;
private int mCurrentY = -1;
public SmoothScrollRunnable(int fromY, int toY, long duration, OnSmoothScrollFinishedListener listener) {
mScrollFromY = fromY;
mScrollToY = toY;
mInterpolator = mScrollAnimationInterpolator;
mDuration = duration;
mListener = listener;
}
@Override
public void run() {
/**
* Only set mStartTime if this is the first time we're starting,
* else actually calculate the Y delta
*/
if (mStartTime == -1) {
mStartTime = System.currentTimeMillis();
} else {
/**
* We do do all calculations in long to reduce software float
* calculations. We use 1000 as it gives us good accuracy and
* small rounding errors
*/
long normalizedTime = (1000 * (System.currentTimeMillis() - mStartTime)) / mDuration;
normalizedTime = Math.max(Math.min(normalizedTime, 1000), 0);
final int deltaY = Math.round((mScrollFromY - mScrollToY) * mInterpolator.getInterpolation(normalizedTime / 1000f));
mCurrentY = mScrollFromY - deltaY;
setHeaderScroll(mCurrentY);
}
// If we're not at the target Y, keep going...
if (mContinueRunning && mScrollToY != mCurrentY) {
ViewCompat.postOnAnimation(PullToRefreshBase.this, this);
} else {
if (null != mListener) {
mListener.onSmoothScrollFinished();
}
}
}
public void stop() {
mContinueRunning = false;
removeCallbacks(this);
}
}
static interface OnSmoothScrollFinishedListener {
void onSmoothScrollFinished();
}
}
| [
"563492052@qq.com"
] | 563492052@qq.com |
294176937994ad2e0458524878528c7aae45f009 | 8919c918fd27b09931f7bb4af3054aff3f97a3db | /src/main/java/com/pmrodrigues/gnsnet/models/Operadora.java | e2d1ef03de0dd1a9ba413333010ac784086e05a9 | [] | no_license | marcelosrodrigues/gpsnet | 25618eb6dcba65192a98befce0687128beaefcfc | fe00df82d1a55f2de7bd6d8e8c2db5b497ca1605 | refs/heads/master | 2021-01-19T08:20:27.262507 | 2015-01-22T00:53:59 | 2015-01-22T00:53:59 | 29,502,708 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 578 | java | package com.pmrodrigues.gnsnet.models;
import javax.persistence.*;
import java.io.Serializable;
/**
* Created by Marceloo on 21/01/2015.
*/
@Entity
@Table
public class Operadora implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String nome;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
| [
"marcelosrodrigues@globo.com"
] | marcelosrodrigues@globo.com |
ce2948a2618bfbbd8f2d6f0d395e021cd5374619 | d5853cf56b8d97228d9ee389e699ff01899fd79a | /PokerBot/src/strategy/strategyPokerChallenge/interfacesToPokerChallenge/StrategyTwo.java | a6342b90a9fd42ff75a1cb137a0a771afb5b3490 | [] | no_license | joschkabraun/pokerbot | 292b5222966d65c9dfd821d96e1f05c9187922b1 | 26b9c554010e2d9a75625fb9b0adc72f9a477f82 | refs/heads/master | 2020-07-09T02:45:07.145878 | 2019-11-10T19:57:35 | 2019-11-10T19:57:35 | 203,852,925 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,063 | java | package strategy.strategyPokerChallenge.interfacesToPokerChallenge;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import parser.ParserCreatorWinnerPoker4Tables;
import strategy.strategyPokerChallenge.ringclient.ClientRingDynamics;
import strategy.strategyPokerChallenge.simulation.real.RealSimulator;
import gameBasics.Action;
import gameBasics.GameState;
import gameBasics.PlayerYou;
import handHistory.HandHistory;
import handHistory.IPostFlop;
import handHistory.PreFlop;
/**
* This class implements an interface for using the strategy of the TU Darmstadt's AKI-RealBot.
*/
public class StrategyTwo {
/**
* For using this method the following datastructures/classes have to be initialized:
* strategy.strategyPokerChallenge.CONSTANT
* strategy.strategyPokerChallenge.History and strategy.strategyPokerChallenge.GlobalRoundData
* strategy.strategyPokerChallenge.ClientRingDynamics
*
* A sample code for doing that:
* strategy.strategyPokerChallenge.interfacesToPokerChallenge.HHToTUDBotHistory.createPrivateHands( new File("c://pokerBot//bot_v1_1_0//hhTableLeftDown.txt"),
* bots.Bot_v1_1_0Tables.LEFT_DOWN, "Hold'Em", "Fixed Limit", 9, "walk10er", new BufferedImage[1], new Rectangle[1] );
* HandHistory hh = parser.ParserCreatorWinnerPoker4Tables.parserMainCWP(new File("c://pokerBot//bot_v1_1_0//hhTableLeftDown.txt"),
* new File("c://pokerBot//bot_v1_2_0//parserTableLeftDown.txt"), "Hold'Em", "Fixed Limit", 9,
* "walk10er", new BufferedImage[1], new Rectangle[1]);
* strategy.strategyPokerChallenge.interfacesToPokerChallenge.HHToTUDBotHistory.createCONSTANT(hh);
* ClientRingDynamics crd = strategy.strategyPokerChallenge.interfacesToPokerChallenge.HHToTUDBotHistory.createRingDynamics(hh, hh.getPlayerYou("walk10er"));
* strategy.strategyPokerChallenge.interfacesToPokerChallenge.HHToTUDBotHistory.createHistory(hh, hh.getPlayerYou("walk10er"));
*
* @param hh the actual hand history
* @param py the player you are
* @param sesFile a file with the people who enter and leave the table
* @param pictureSeats pictures of the seats if there are not any players
* @param spaceSeats the rectangles where the seats are
* @param crd the ClientRingDynamics
* @param tableWasRemoved whether the table was removed or not. This information is important for other.Tools.compare(...)-methods.
* @return The action determined by the strategy of the TU Darmstadt poker agent AKI-RealBot
* @throws AWTException
*/
public static synchronized Action actionFor( HandHistory hh, PlayerYou py, File sesFile, BufferedImage[] pictureSeats, Rectangle[] spaceSeats, ClientRingDynamics crd,
boolean tableWasRemoved) throws AWTException {
if ( hh.bettingRounds.get(hh.bettingRounds.size()-1).getPokerChallengeGameState().equals(strategy.strategyPokerChallenge.data.GameState.PRE_FLOP) )
if ( hh.allPlayers.size() != ParserCreatorWinnerPoker4Tables.howManyPlayersAtTableByFile(sesFile))
return strategy.strategyPokerStrategy.StrategyOne.actionFor(hh, py);
long time;
double random = Math.random();
if (random <= 0.25)
time = 3000L;
else if (random <= 0.5)
time = 3500L;
else if (random <= 0.75)
time = 4000L;
else if (random <= 1.0)
time = 4500L;
else
time = 6000L;
RealSimulator rs = new RealSimulator();
TimeManager tm = new TimeManager(rs);
rs.startSimulation(crd);
Action ret = tm.getDecision(time);
if ( hh.state == GameState.PRE_FLOP ) {
if ( (ret.actionName.equals("fold") || ret.actionName.equals("call")) && PreFlop.actionMin(hh, py).actionName.equals("check") )
ret.set("check");
} else {
IPostFlop postflop = (IPostFlop) hh.bettingRounds.get(hh.bettingRounds.size()-1);
if ( (ret.actionName.equals("fold") || ret.actionName.equals("call")) && postflop.actionMin().actionName.equals("check") )
ret.set("check");
}
return ret;
// return actionFor(hh, py, sesFile, crd);
}
/**
* For using this method the following datastructures/classes have to be initialized:
* strategy.strategyPokerChallenge.CONSTANT
* strategy.strategyPokerChallenge.History and strategy.strategyPokerChallenge.GlobalRoundData
* strategy.strategyPokerChallenge.ClientRingDynamics
*
* A sample code for doing that:
* strategy.strategyPokerChallenge.interfacesToPokerChallenge.HHToTUDBotHistory.createPrivateHands( new File("c://pokerBot//bot_v1_1_0//hhTableLeftDown.txt"),
* bots.Bot_v1_1_0Tables.LEFT_DOWN, "Hold'Em", "Fixed Limit", 9, "walk10er", new BufferedImage[1], new Rectangle[1] );
* HandHistory hh = parser.ParserCreatorWinnerPoker4Tables.parserMainCWP(new File("c://pokerBot//bot_v1_1_0//hhTableLeftDown.txt"),
* new File("c://pokerBot//bot_v1_2_0//parserTableLeftDown.txt"), "Hold'Em", "Fixed Limit", 9,
* "walk10er", new BufferedImage[1], new Rectangle[1]);
* strategy.strategyPokerChallenge.interfacesToPokerChallenge.HHToTUDBotHistory.createCONSTANT(hh);
* ClientRingDynamics crd = strategy.strategyPokerChallenge.interfacesToPokerChallenge.HHToTUDBotHistory.createRingDynamics(hh, hh.getPlayerYou("walk10er"));
* strategy.strategyPokerChallenge.interfacesToPokerChallenge.HHToTUDBotHistory.createHistory(hh, hh.getPlayerYou("walk10er"));
*
* @param hh the actual hand history
* @param py the player you are
* @param sesFile a file with the people who enter and leave the table
* @param crd the ClientRingDynamics
* @return The action determined by the strategy of the TU Darmstadt poker agent AKI-RealBot
* @throws AWTException
*/
public static synchronized Action actionFor( HandHistory hh, PlayerYou py, File sesFile, ClientRingDynamics crd) throws AWTException {
if ( hh.bettingRounds.get(hh.bettingRounds.size()-1).getPokerChallengeGameState().equals(strategy.strategyPokerChallenge.data.GameState.PRE_FLOP) )
if ( hh.allPlayers.size() != ParserCreatorWinnerPoker4Tables.howManyPlayersAtTableByFile(sesFile))
return strategy.strategyPokerStrategy.StrategyOne.actionFor(hh, py);
long time;
double random = Math.random();
if (random <= 0.25)
time = 3000L;
else if (random <= 0.5)
time = 3500L;
else if (random <= 0.75)
time = 4000L;
else if (random <= 1.0)
time = 4500L;
else
time = 6000L;
RealSimulator rs = new RealSimulator();
TimeManager tm = new TimeManager(rs);
rs.startSimulation(crd);
Action ret = tm.getDecision(time);
if ( hh.state == GameState.PRE_FLOP ) {
if ( (ret.actionName.equals("fold") || ret.actionName.equals("call")) && PreFlop.actionMin(hh, py).actionName.equals("check") )
ret.set("check");
} else {
IPostFlop postflop = (IPostFlop) hh.bettingRounds.get(hh.bettingRounds.size()-1);
if ( (ret.actionName.equals("fold") || ret.actionName.equals("call")) && postflop.actionMin().actionName.equals("check") )
ret.set("check");
}
return ret;
}
}
| [
"joschka.braun@gmail.de"
] | joschka.braun@gmail.de |
1f14a94713e479279172bc9399639f77b668a5d1 | 2edbc7267d9a2431ee3b58fc19c4ec4eef900655 | /AL-Game/data/scripts/system/handlers/quest/fatebound_abbey/_29661Protect_Beluslan.java | 7f33b19a14fb714ed947482936b1f88569b079b0 | [] | no_license | EmuZONE/Aion-Lightning-5.1 | 3c93b8bc5e63fd9205446c52be9b324193695089 | f4cfc45f6aa66dfbfdaa6c0f140b1861bdcd13c5 | refs/heads/master | 2020-03-08T14:38:42.579437 | 2018-04-06T04:18:19 | 2018-04-06T04:18:19 | 128,191,634 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,899 | java | /*
* This file is part of Encom. **ENCOM FUCK OTHER SVN**
*
* Encom is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Encom is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Encom. If not, see <http://www.gnu.org/licenses/>.
*/
package quest.fatebound_abbey;
import com.aionemu.gameserver.model.*;
import com.aionemu.gameserver.model.gameobjects.*;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.*;
import com.aionemu.gameserver.questEngine.handlers.*;
import com.aionemu.gameserver.questEngine.model.*;
import com.aionemu.gameserver.utils.*;
/****/
/** Author Rinzler (Encom)
/****/
public class _29661Protect_Beluslan extends QuestHandler
{
private final static int questId = 29661;
private final static int[] mobs = {213009, 213010, 213017, 213018};
public _29661Protect_Beluslan() {
super(questId);
}
@Override
public void register() {
qe.registerQuestNpc(804662).addOnQuestStart(questId);
qe.registerQuestNpc(804662).addOnTalkEvent(questId);
qe.registerQuestNpc(804662).addOnTalkEvent(questId);
for (int mob: mobs) {
qe.registerQuestNpc(mob).addOnKillEvent(questId);
}
}
@Override
public boolean onDialogEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
QuestDialog dialog = env.getDialog();
int targetId = env.getTargetId();
if (env.getVisibleObject() instanceof Npc) {
targetId = ((Npc) env.getVisibleObject()).getNpcId();
} if (qs == null || qs.getStatus() == QuestStatus.NONE || qs.canRepeat()) {
if (targetId == 804662) {
switch (dialog) {
case START_DIALOG: {
if (player.getInventory().getItemCountByItemId(164000336) >= 1) { //Abbey Return Stone.
return sendQuestDialog(env, 4762);
} else {
PacketSendUtility.broadcastPacket(player, new SM_MESSAGE(player,
"You must have <Abbey Return Stone>", ChatType.BRIGHT_YELLOW_CENTER), true);
return true;
}
}
case ACCEPT_QUEST:
case ACCEPT_QUEST_SIMPLE:
return sendQuestStartDialog(env);
case REFUSE_QUEST_SIMPLE:
return closeDialogWindow(env);
}
}
} else if (qs.getStatus() == QuestStatus.START) {
switch (targetId) {
case 804662: {
switch (dialog) {
case START_DIALOG: {
return sendQuestDialog(env, 10002);
} case SELECT_REWARD: {
return sendQuestEndDialog(env);
} default:
return sendQuestEndDialog(env);
}
}
}
} else if (qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 804662) {
switch (dialog) {
case SELECT_REWARD: {
return sendQuestDialog(env, 5);
} default:
return sendQuestEndDialog(env);
}
}
}
return false;
}
@Override
public boolean onKillEvent(QuestEnv env) {
Player player = env.getPlayer();
int targetId = env.getTargetId();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs == null || qs.getStatus() != QuestStatus.START) {
return false;
} switch (targetId) {
case 213009:
case 213010:
case 213017:
case 213018:
if (qs.getQuestVarById(1) < 10) {
qs.setQuestVarById(1, qs.getQuestVarById(1) + 1);
updateQuestStatus(env);
} if (qs.getQuestVarById(1) >= 10) {
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
}
break;
}
return false;
}
} | [
"naxdevil@gmail.com"
] | naxdevil@gmail.com |
10ace3e60473d2f35b5c7603154eef98f680d25f | a4287b09e211e410cedf194c3b1f7dddc7785d83 | /src/com/abid/atm/bank/Account.java | 9e6b1b35b07d2c895696433c6c4c9d5c21dd20a8 | [] | no_license | rahmanabidchy/Java-CashMachine-with-MySQL | 0c9529e256a3f3072582a4cd5817e6de9ac6ba1e | d3542780dce6b30bf2237bb813c7393471beea27 | refs/heads/master | 2023-04-22T22:27:39.874862 | 2021-04-30T09:10:04 | 2021-04-30T09:10:04 | 359,405,819 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,243 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.abid.atm.bank;
import java.util.ArrayList;
public class Account {
private String UUID;
private String holderUUID;
private String acctType;
private double balance;
private ArrayList<Transaction> transactions;
/**
* Creates an object of Account
* @param UUID the UUID of the account
* @param holderUUID the UUID of the user of this account
* @param acctType the type of the account
* @param balance the amount present in the account
*/
public Account(String UUID, String holderUUID,String acctType){
this.UUID = UUID;
this.holderUUID = holderUUID;
this.acctType = acctType;
}
/**
* Get the type of the account
* @return the type of the account
*/
public String getAcctType(){
return this.acctType;
}
/**
* Updates the balance of this account
*/
public void updateBalance(){
double tempBal = 0;
for(Transaction tr: transactions){
tempBal+=tr.getAmount();
}
balance = tempBal;
}
/**
* Get the balance of the account
* @return the amount
*/
public double getBalance(){
return this.balance;
}
/**
* Get the UUID of the Account
* @return the UUID of the Accounts
*/
public String getUUID(){
return this.UUID;
}
/**
* Set the lists of transactions associated with the account
* @param transactions the list of the transaction
*/
public void setTransList(ArrayList<Transaction> transactions){
this.transactions = transactions;
}
/**
* Get summary line for the account
* @return the string summary
*/
public String getSummaryLine(){
// get the account's balance
double balance = this.getBalance();
// format the summary line depending on
// whether tha balance is negative.
if(balance >= 0){
return String.format("%s : $%.02f : %s", this.UUID, balance, this.acctType);
} else {
return String.format("%s : $(%.02f) : %s", this.UUID, balance, this.acctType);
}
}
/**
* Print transaction history of a particular account
*/
public void printAccTransHistory(){
System.out.printf("\nTransaction history for account %s\n", this.UUID);
for(int t=this.transactions.size()-1; t>=0; t--){
System.out.println(this.transactions.get(t).getSmryTransaction());
}
System.out.println();
}
/**
* Add a new transaction in this account
* @param trans The transaction object to be added
*/
public void addTransaction(Transaction trans){
// add the new transation to the current array list
this.transactions.add(trans);
// update the balance
updateBalance();
}
}
| [
"rahmanabidkafoo@gmail.com"
] | rahmanabidkafoo@gmail.com |
61508bf5debeebccc030d801cd83c9b709ec6c6c | a2a2d5286fa1a2e39fc864c2431bb32932e39c44 | /cdm/src/main/java/ucar/nc2/dataset/conv/AWIPSsatConvention.java | 852143db8d61afa9b036fe3a8df06a120c6646d6 | [
"BSD-3-Clause"
] | permissive | gknauth/netcdf-java | 7902c1466dc21134f67dd046b4d1a62979fb35bf | e979e6bc206ab291e057dec2885a6c75cef837ec | refs/heads/master | 2020-07-19T01:15:43.589986 | 2019-09-03T21:49:14 | 2019-09-03T22:32:16 | 206,348,469 | 0 | 1 | BSD-3-Clause | 2019-09-04T15:11:56 | 2019-09-04T15:11:56 | null | UTF-8 | Java | false | false | 11,236 | java | /*
* Copyright (c) 1998-2018 John Caron and University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
package ucar.nc2.dataset.conv;
import ucar.nc2.*;
import ucar.nc2.constants.CDM;
import ucar.nc2.constants._Coordinate;
import ucar.nc2.constants.AxisType;
import ucar.nc2.util.CancelTask;
import ucar.nc2.dataset.*;
import ucar.nc2.units.SimpleUnit;
import ucar.unidata.geoloc.*;
import ucar.unidata.geoloc.projection.*;
import ucar.ma2.ArrayByte;
import ucar.ma2.DataType;
import java.util.*;
/**
* AWIPS netcdf output.
*
* @author caron
*
* @see <a href=
* "http://www-md.fsl.noaa.gov/eft/AWIPS/16c/onlinehelp/ifpServerSatelliteNETCDF.html">http://www-md.fsl.noaa.gov/eft/AWIPS/16c/onlinehelp/ifpServerSatelliteNETCDF.html</a>
* @see <a href=
* "http://www.nws.noaa.gov/mdl/awips/aifmdocs/sec_4_e.htm">http://www.nws.noaa.gov/mdl/awips/aifmdocs/sec_4_e.htm</a>
*/
public class AWIPSsatConvention extends CoordSysBuilder {
/**
* @param ncfile the NetcdfFile to test
* @return true if we think this is a AWIPSsatConvention file.
*/
public static boolean isMine(NetcdfFile ncfile) {
return (null != ncfile.findGlobalAttribute("projName")) && (null != ncfile.findGlobalAttribute("lon00"))
&& (null != ncfile.findGlobalAttribute("lat00")) && (null != ncfile.findGlobalAttribute("lonNxNy"))
&& (null != ncfile.findGlobalAttribute("latNxNy")) && (null != ncfile.findGlobalAttribute("centralLon"))
&& (null != ncfile.findGlobalAttribute("centralLat")) && (null != ncfile.findDimension("x"))
&& (null != ncfile.findDimension("y")) && (null != ncfile.findVariable("image"));
}
private static final boolean debugProj = false;
private ProjectionCT projCT;
private double startx, starty, dx, dy;
public AWIPSsatConvention() {
this.conventionName = "AWIPS-Sat";
}
public void augmentDataset(NetcdfDataset ds, CancelTask cancelTask) {
if (null != ds.findVariable("x"))
return; // check if its already been done - aggregating enhanced datasets.
Dimension dimx = ds.findDimension("x");
int nx = dimx.getLength();
Dimension dimy = ds.findDimension("y");
int ny = dimy.getLength();
String projName = ds.findAttValueIgnoreCase(null, "projName", "none");
if (projName.equalsIgnoreCase("CYLINDRICAL_EQUIDISTANT")) {
makeLatLonProjection(ds, projName, nx, ny);
ds.addCoordinateAxis(makeLonCoordAxis(ds, nx, "x"));
ds.addCoordinateAxis(makeLatCoordAxis(ds, ny, "y"));
} else {
if (projName.equalsIgnoreCase("LAMBERT_CONFORMAL"))
projCT = makeLCProjection(ds, projName, nx, ny);
if (projName.equalsIgnoreCase("MERCATOR"))
projCT = makeMercatorProjection(ds, projName, nx, ny);
ds.addCoordinateAxis(makeXCoordAxis(ds, nx, "x"));
ds.addCoordinateAxis(makeYCoordAxis(ds, ny, "y"));
}
// long_name; LOOK: not sure of units
Variable datav = ds.findVariable("image");
String long_name = ds.findAttValueIgnoreCase(null, "channel", null);
if (null != long_name)
datav.addAttribute(new Attribute(CDM.LONG_NAME, long_name));
datav.setDataType(DataType.UBYTE);
// missing values
ArrayByte.D1 missing_values = new ArrayByte.D1(2, true);
missing_values.set(0, (byte) 0);
missing_values.set(1, (byte) -127);
datav.addAttribute(new Attribute(CDM.MISSING_VALUE, missing_values));
if (projCT != null) {
VariableDS v = makeCoordinateTransformVariable(ds, projCT);
v.addAttribute(new Attribute(_Coordinate.Axes, "x y"));
ds.addVariable(null, v);
}
ds.finish();
}
/////////////////////////////////////////////////////////////////////////
protected AxisType getAxisType(NetcdfDataset ds, VariableEnhanced ve) {
Variable v = (Variable) ve;
String vname = v.getShortName();
String units = v.getUnitsString();
if (units.equalsIgnoreCase(CDM.LON_UNITS))
return AxisType.Lon;
if (units.equalsIgnoreCase(CDM.LAT_UNITS))
return AxisType.Lat;
if (vname.equalsIgnoreCase("x"))
return AxisType.GeoX;
if (vname.equalsIgnoreCase("lon"))
return AxisType.Lon;
if (vname.equalsIgnoreCase("y"))
return AxisType.GeoY;
if (vname.equalsIgnoreCase("lat"))
return AxisType.Lat;
if (vname.equalsIgnoreCase("record"))
return AxisType.Time;
Dimension dim = v.getDimension(0);
if ((dim != null) && dim.getShortName().equalsIgnoreCase("record"))
return AxisType.Time;
String unit = ve.getUnitsString();
if (unit != null) {
if (SimpleUnit.isCompatible("millibar", unit))
return AxisType.Pressure;
if (SimpleUnit.isCompatible("m", unit))
return AxisType.Height;
}
return AxisType.GeoZ;
}
protected void makeCoordinateTransforms(NetcdfDataset ds) {
if (projCT != null) {
VarProcess vp = findVarProcess(projCT.getName(), null);
vp.isCoordinateTransform = true;
vp.ct = projCT;
}
super.makeCoordinateTransforms(ds);
}
private void makeLatLonProjection(NetcdfDataset ds, String name, int nx, int ny) throws NoSuchElementException {
double lat0 = findAttributeDouble(ds, "lat00");
double lon0 = findAttributeDouble(ds, "lon00");
double latEnd = findAttributeDouble(ds, "latNxNy");
double lonEnd = findAttributeDouble(ds, "lonNxNy");
if (lonEnd < lon0)
lonEnd += 360;
startx = lon0;
starty = lat0;
dx = (lonEnd - lon0) / nx;
dy = (latEnd - lat0) / ny;
}
private ProjectionCT makeLCProjection(NetcdfDataset ds, String name, int nx, int ny) throws NoSuchElementException {
double centralLat = findAttributeDouble(ds, "centralLat");
double centralLon = findAttributeDouble(ds, "centralLon");
double rotation = findAttributeDouble(ds, "rotation");
// lat0, lon0, par1, par2
LambertConformal proj = new LambertConformal(rotation, centralLon, centralLat, centralLat);
// we have to project in order to find the origin
double lat0 = findAttributeDouble(ds, "lat00");
double lon0 = findAttributeDouble(ds, "lon00");
ProjectionPointImpl start = (ProjectionPointImpl) proj.latLonToProj(new LatLonPointImpl(lat0, lon0));
if (debugProj)
parseInfo.format("getLCProjection start at proj coord %s%n", start);
startx = start.getX();
starty = start.getY();
// we will use the end to compute grid size LOOK may be wrong
double latN = findAttributeDouble(ds, "latNxNy");
double lonN = findAttributeDouble(ds, "lonNxNy");
ProjectionPointImpl end = (ProjectionPointImpl) proj.latLonToProj(new LatLonPointImpl(latN, lonN));
dx = (end.getX() - startx) / nx;
dy = (end.getY() - starty) / ny;
if (debugProj) {
parseInfo.format(" makeProjectionLC start at proj coord %f %f%n", startx, starty);
parseInfo.format(" makeProjectionLC end at proj coord %f %f%n", end.getX(), end.getY());
double fdx = findAttributeDouble(ds, "dxKm");
double fdy = findAttributeDouble(ds, "dyKm");
parseInfo.format(" makeProjectionLC calc dx= %f file dx= %f%n", dx, fdx);
parseInfo.format(" makeProjectionLC calc dy= %f file dy= %f%n", dy, fdy);
}
return new ProjectionCT(name, "FGDC", proj);
}
private ProjectionCT makeMercatorProjection(NetcdfDataset ds, String name, int nx, int ny)
throws NoSuchElementException {
// double centralLat = findAttributeDouble( ds, "centralLat");
// Center longitude for the mercator projection, where the mercator projection is parallel to the Earth's surface.
// from this, i guess is actually transverse mercator
// double centralLon = findAttributeDouble( ds, "centralLon");
// lat0, central meridian, scale factor
// TransverseMercator proj = new TransverseMercator(centralLat, centralLon, 1.0);
double latDxDy = findAttributeDouble(ds, "latDxDy");
double lonDxDy = findAttributeDouble(ds, "lonDxDy");
// lat0, lon0, par
Mercator proj = new Mercator(lonDxDy, latDxDy);
// we have to project in order to find the start LOOK may be wrong
double lat0 = findAttributeDouble(ds, "lat00");
double lon0 = findAttributeDouble(ds, "lon00");
ProjectionPointImpl start = (ProjectionPointImpl) proj.latLonToProj(new LatLonPointImpl(lat0, lon0));
startx = start.getX();
starty = start.getY();
// we will use the end to compute grid size
double latN = findAttributeDouble(ds, "latNxNy");
double lonN = findAttributeDouble(ds, "lonNxNy");
ProjectionPointImpl end = (ProjectionPointImpl) proj.latLonToProj(new LatLonPointImpl(latN, lonN));
dx = (end.getX() - startx) / nx;
dy = (end.getY() - starty) / ny;
if (debugProj) {
parseInfo.format(" makeProjectionMercator start at proj coord %f %f%n", startx, starty);
parseInfo.format(" makeProjectionMercator end at proj coord %f %f%n", end.getX(), end.getY());
double fdx = findAttributeDouble(ds, "dxKm");
double fdy = findAttributeDouble(ds, "dyKm");
parseInfo.format(" makeProjectionMercator calc dx= %f file dx= %f%n", dx, fdx);
parseInfo.format(" makeProjectionMercator calc dy= %f file dy= %f%n", dy, fdy);
}
return new ProjectionCT(name, "FGDC", proj);
}
private CoordinateAxis makeXCoordAxis(NetcdfDataset ds, int nx, String xname) {
CoordinateAxis v = new CoordinateAxis1D(ds, null, xname, DataType.DOUBLE, xname, "km", "x on projection");
v.setValues(nx, startx, dx);
parseInfo.format("Created X Coordinate Axis = ");
v.getNameAndDimensions(parseInfo, true, false);
parseInfo.format("%n");
if (debugProj)
parseInfo.format(" makeXCoordAxis ending x %f nx= %d dx= %f%n", startx + nx * dx, nx, dx);
return v;
}
private CoordinateAxis makeYCoordAxis(NetcdfDataset ds, int ny, String yname) {
CoordinateAxis v = new CoordinateAxis1D(ds, null, yname, DataType.DOUBLE, yname, "km", "y on projection");
v.setValues(ny, starty, dy);
parseInfo.format("Created Y Coordinate Axis = ");
v.getNameAndDimensions(parseInfo, true, false);
parseInfo.format("%n");
if (debugProj)
parseInfo.format(" makeYCoordAxis ending y %f ny= %d dy= %f%n", starty + ny * dy, ny, dy);
return v;
}
private CoordinateAxis makeLonCoordAxis(NetcdfDataset ds, int nx, String xname) {
CoordinateAxis v = new CoordinateAxis1D(ds, null, xname, DataType.DOUBLE, xname, CDM.LON_UNITS, "longitude");
v.setValues(nx, startx, dx);
parseInfo.format("Created X Coordinate Axis = ");
v.getNameAndDimensions(parseInfo, true, false);
parseInfo.format("%n");
return v;
}
private CoordinateAxis makeLatCoordAxis(NetcdfDataset ds, int ny, String yname) {
CoordinateAxis v = new CoordinateAxis1D(ds, null, yname, DataType.DOUBLE, yname, CDM.LAT_UNITS, "latitude");
v.setValues(ny, starty, dy);
parseInfo.format("Created Lat Coordinate Axis = ");
v.getNameAndDimensions(parseInfo, true, false);
parseInfo.format("%n");
return v;
}
private double findAttributeDouble(NetcdfDataset ds, String attname) {
Attribute att = ds.findGlobalAttributeIgnoreCase(attname);
return att.getNumericValue().doubleValue();
}
}
| [
"67096+lesserwhirls@users.noreply.github.com"
] | 67096+lesserwhirls@users.noreply.github.com |
f58befd4b5d17631d08a8d555789e0e8eeb9c03d | 379353571e5c0335e9f3b70b585e42e169dcb75e | /app/src/main/java/com/mwm/loyal/activity/ListFeedBackActivity.java | 6bf42dddd4a35ff1b2648ab618fdd78952b643b6 | [] | no_license | l6yang/MwMApp | 3f8f82607dca110247582055899d67054887576e | 945066eff455e47da223edadd0b8980027e9ad23 | refs/heads/master | 2021-01-18T13:09:46.843238 | 2019-12-08T15:19:14 | 2019-12-08T15:19:14 | 80,723,477 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,456 | java | package com.mwm.loyal.activity;
import android.graphics.Color;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import com.loyal.kit.GsonUtil;
import com.loyal.rx.RxUtil;
import com.loyal.rx.impl.RxSubscriberListener;
import com.mwm.loyal.R;
import com.mwm.loyal.adapter.FeedBackAdapter;
import com.mwm.loyal.base.BaseSwipeActivity;
import com.mwm.loyal.beans.FeedBackBean;
import com.mwm.loyal.beans.ResultBean;
import com.mwm.loyal.databinding.ActivityListFeedbackBinding;
import com.mwm.loyal.libs.rxjava.RxProgressSubscriber;
import com.mwm.loyal.utils.DividerItemDecoration;
import com.mwm.loyal.utils.ImageUtil;
import com.yanzhenjie.recyclerview.swipe.Closeable;
import com.yanzhenjie.recyclerview.swipe.OnSwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
public class ListFeedBackActivity extends BaseSwipeActivity<ActivityListFeedbackBinding> implements RxSubscriberListener<String>, SwipeMenuCreator, OnSwipeMenuItemClickListener {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.listFeedBack)
SwipeMenuRecyclerView recyclerView;
private List<FeedBackBean> beanList = new ArrayList<>();
private FeedBackAdapter feedBackAdapter;
@Override
protected int actLayoutRes() {
return R.layout.activity_list_feedback;
}
@Override
public void afterOnCreate() {
toolbar.setTitle("反馈历史");
setSupportActionBar(toolbar);
binding.setDrawable(ImageUtil.getBackground(this));
queryHistory();
initViews();
}
@Override
public int setEdgePosition() {
return LEFT;
}
private void queryHistory() {
String account = getIntent().getStringExtra("account");
RxProgressSubscriber<String> subscriber = new RxProgressSubscriber<>(this, "192.168.0.110");
subscriber.setSubscribeListener(this);
RxUtil.rxExecute(subscriber.getFeedback(account), subscriber);
}
private void initViews() {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this));// 添加分割线。
recyclerView.setSwipeMenuCreator(this);
recyclerView.setSwipeMenuItemClickListener(this);// 监听拖拽,更新UI。
recyclerView.setAdapter(feedBackAdapter = new FeedBackAdapter(this, beanList));
}
@Override
public boolean isFullScreen() {
return false;
}
@Override
public void onResult(int what, Object tag, String result) {
try {
ResultBean resultBean = GsonUtil.json2Bean(result, ResultBean.class);
if (TextUtils.equals("1", resultBean.getCode())) {
this.beanList = GsonUtil.json2List(resultBean.getMessage(), FeedBackBean.class);
if (null != feedBackAdapter) {
feedBackAdapter.refreshList(this.beanList);
}
}
} catch (Exception e) {
showDialog("解析历史反馈数据异常\n" + e.toString(), false);
}
}
@Override
public void onError(int what, Object tag, Throwable e) {
showErrorDialog(e.toString(), false);
}
@Override
public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
int width = getResources().getDimensionPixelSize(R.dimen.item_height);
// MATCH_PARENT 自适应高度,保持和内容一样高;也可以指定菜单具体高度,也可以用WRAP_CONTENT。
int height = ViewGroup.LayoutParams.MATCH_PARENT;
SwipeMenuItem deleteItem = new SwipeMenuItem(this)
.setBackgroundDrawable(android.R.color.holo_red_light)
.setText("删除") // 文字,还可以设置文字颜色,大小等。。
.setTextColor(Color.WHITE)
.setWidth(width)
.setHeight(height);
swipeRightMenu.addMenuItem(deleteItem);
}
@Override
public void onItemClick(Closeable closeable, final int adapterPosition, int menuPosition, int direction) {
closeable.smoothCloseMenu();// 关闭被点击的菜单。
// 如果是删除:推荐调用Adapter.notifyItemRemoved(position),不推荐Adapter.notifyDataSetChanged();
if (menuPosition == 0) {// 删除按钮被点击。
RxProgressSubscriber<String> subscriber = new RxProgressSubscriber<>(this, "192.168.0.110");
subscriber.setSubscribeListener(new RxSubscriberListener<String>() {
@Override
public void onResult(int what, Object tag, String result) {
ResultBean resultBean = GsonUtil.json2Bean(result, ResultBean.class);
if (null != resultBean) {
if (TextUtils.equals("1", resultBean.getCode())) {
showToast("删除成功");
beanList.remove(adapterPosition);
feedBackAdapter.notifyItemRemoved(adapterPosition);
} else showDialog(resultBean.getMessage(), false);
} else showDialog("解析删除反馈数据失败", false);
}
@Override
public void onError(int what, Object tag, Throwable e) {
showDialog(e.toString(), false);
}
});
RxUtil.rxExecute(subscriber.deleteFeedback(beanList.get(adapterPosition).toString()), subscriber);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sync, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_sync:
beanList.clear();
feedBackAdapter.refreshList(beanList);
queryHistory();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| [
"zhangluyang112@163.com"
] | zhangluyang112@163.com |
1d118d97b889ae23b81678a22194042e99871dfe | 6daccefd410f0f92dcb0451fc8500439a7cca942 | /src/CeilingFan/CeilingFanTest.java | d35b96fdedb86f73635e6771e7c8e0c6705012b7 | [] | no_license | suraj1938/CGICeilingFan | 1cb3527324d2c641279371b53905bfd5dc5f8ebb | 972d283fd73f89e64052ea218f394fcdae75ef19 | refs/heads/master | 2023-03-27T23:36:10.367299 | 2021-03-31T02:44:49 | 2021-03-31T02:44:49 | 353,203,232 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 779 | java | package CeilingFan;
import java.util.Scanner;
public class CeilingFanTest {
public static void main(String[] args) {
CeilingFan fan =new CeilingFan();
while (true) {
System.out.print("Press 'S' to Change Speed and 'D' to change Direction");
char input=readLine();
if(input == 'S'){
fan.changeSpeed();
}
else if (input == 'D'){
fan.changeDirection();
}else{
System.out.println("Please Enter either 'S' or 'D'");
}
}
}
public static char readLine(){
Scanner sc = new Scanner(System.in);
System.out.print("Input a character: ");
char c = sc.next().charAt(0);
return c;
}
}
| [
"ss544867@dal.ca"
] | ss544867@dal.ca |
25f57df9db9730bab9afffccc2dc62695ebd9c68 | 8f315ffa7883b386c6f921e9f8d3a56edd245ad6 | /src/com/coolweather/app/activity/MainActivity.java | c080fdeeda8fbc0b99ff799c660c0f72773e9260 | [
"Apache-2.0"
] | permissive | kyxiaobai724/coolweathre | 80a0bed8ce5f6245557efeb56f91eab49f901f1f | e43fb649028ce2a5dfb5faeae3065c1c20b64cd0 | refs/heads/master | 2021-01-23T03:59:55.115167 | 2015-08-30T09:41:21 | 2015-08-30T09:41:21 | 41,417,218 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 415 | java | package com.coolweather.app.activity;
import com.coolweather.app.R;
import com.coolweather.app.R.layout;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| [
"yaohua@hua.(none)"
] | yaohua@hua.(none) |
ea88e687fc9d495a5bd123abc0e490619466e849 | 20eb62855cb3962c2d36fda4377dfd47d82eb777 | /newEvaluatedBugs/Jsoup_59_buggy/mutated/1288/Element.java | fe6f5bd6da88a24516b19accd521571dcd1316f3 | [] | no_license | ozzydong/CapGen | 356746618848065cce4e253e5d3c381baa85044a | 0ba0321b6b1191443276021f1997833342f02515 | refs/heads/master | 2023-03-18T20:12:02.923428 | 2020-08-21T03:08:28 | 2020-08-21T03:08:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 36,614 | java | package org.jsoup.nodes;
import org.jsoup.helper.StringUtil;
import org.jsoup.helper.Validate;
import org.jsoup.parser.Parser;
import org.jsoup.parser.Tag;
import org.jsoup.select.Collector;
import org.jsoup.select.Elements;
import org.jsoup.select.Selector;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* A HTML element consists of a tag name, attributes, and child nodes (including text nodes and
* other elements).
*
* From an Element, you can extract data, traverse the node graph, and manipulate the HTML.
*
* @author Jonathan Hedley, jonathan@hedley.net
*/
public class Element extends Node {
private final Tag tag;
private Set<String> classNames;
/**
* Create a new, standalone Element. (Standalone in that is has no parent.)
*
* @param tag tag of this element
* @param baseUri the base URI
* @param attributes initial attributes
* @see #appendChild(Node)
* @see #appendElement(String)
*/
public Element(Tag tag, String baseUri, Attributes attributes) {
super(baseUri, attributes);
Validate.notNull(tag);
this.tag = tag;
}
/**
* Create a new Element from a tag and a base URI.
*
* @param tag element tag
* @param baseUri the base URI of this element. It is acceptable for the base URI to be an empty
* string, but not null.
* @see Tag#valueOf(String)
*/
public Element(Tag tag, String baseUri) {
this(tag, baseUri, new Attributes());
}
@Override
public String nodeName() {
return tag.getName();
}
/**
* Get the name of the tag for this element. E.g. {@code div}
*
* @return the tag name
*/
public String tagName() {
return tag.getName();
}
/**
* Get the Tag for this element.
*
* @return the tag object
*/
public Tag tag() {
return tag;
}
/**
* Test if this element is a block-level element. (E.g. {@code <div> == true} or an inline element
* {@code <p> == false}).
*
* @return true if block, false if not (and thus inline)
*/
public boolean isBlock() {
return tag.isBlock();
}
/**
* Get the {@code id} attribute of this element.
*
* @return The id attribute, if present, or an empty string if not.
*/
public String id() {
String id = attr("id");
return id == null ? "" : id;
}
/**
* Set an attribute value on this element. If this element already has an attribute with the
* key, its value is updated; otherwise, a new attribute is added.
*
* @return this element
*/
public Element attr(String attributeKey, String attributeValue) {
super.attr(attributeKey, attributeValue);
return this;
}
/**
* Get this element's HTML5 custom data attributes. Each attribute in the element that has a key
* starting with "data-" is included the dataset.
* <p>
* E.g., the element {@code <div data-package="jsoup" data-language="Java" class="group">...} has the dataset
* {@code package=jsoup, language=java}.
* <p>
* This map is a filtered view of the element's attribute map. Changes to one map (add, remove, update) are reflected
* in the other map.
* <p>
* You can find elements that have data attributes using the {@code [^data-]} attribute key prefix selector.
* @return a map of {@code key=value} custom data attributes.
*/
public Map<String, String> dataset() {
return attributes.dataset();
}
@Override
public final Element parent() {
return (Element) parentNode;
}
/**
* Get this element's parent and ancestors, up to the document root.
* @return this element's stack of parents, closest first.
*/
public Elements parents() {
Elements parents = new Elements();
accumulateParents(this, parents);
return parents;
}
private static void accumulateParents(Element el, Elements parents) {
Element parent = el.parent();
if (parent != null && !parent.tagName().equals("#root")) {
parents.add(parent);
accumulateParents(parent, parents);
}
}
/**
* Get a child element of this element, by its 0-based index number.
* <p/>
* Note that an element can have both mixed Nodes and Elements as children. This method inspects
* a filtered list of children that are elements, and the index is based on that filtered list.
*
* @param index the index number of the element to retrieve
* @return the child element, if it exists, or {@code null} if absent.
* @see #childNode(int)
*/
public Element child(int index) {
return children().get(index);
}
/**
* Get this element's child elements.
* <p/>
* This is effectively a filter on {@link #childNodes()} to get Element nodes.
* @return child elements. If this element has no children, returns an
* empty list.
* @see #childNodes()
*/
public Elements children() {
// create on the fly rather than maintaining two lists. if gets slow, memoize, and mark dirty on change
List<Element> elements = new ArrayList<Element>();
for (Node node : childNodes) {
if (node instanceof Element)
elements.add((Element) node);
}
return new Elements(elements);
}
/**
* Find elements that match the selector query, with this element as the starting context. Matched elements
* may include this element, or any of its children.
* <p/>
* This method is generally more powerful to use than the DOM-type {@code getElementBy*} methods, because
* multiple filters can be combined, e.g.:
* <ul>
* <li>{@code el.select("a[href]")} - finds links ({@code a} tags with {@code href} attributes)
* <li>{@code el.select("a[href*=example.com]")} - finds links pointing to example.com (loosely)
* </ul>
* <p/>
* See the query syntax documentation in {@link org.jsoup.select.Selector}.
*
* @param query a {@link Selector} query
* @return elements that match the query (empty if none match)
* @see org.jsoup.select.Selector
*/
public Elements select(String query) {
return Selector.select(query, this);
}
/**
* Add a node to the last child of this element.
*
* @param child node to add. Must not already have a parent.
* @return this element, so that you can add more child nodes or elements.
*/
public Element appendChild(Node child) {
Validate.notNull(child);
addChildren(child);
return this;
}
/**
* Add a node to the start of this element's children.
*
* @param child node to add. Must not already have a parent.
* @return this element, so that you can add more child nodes or elements.
*/
public Element prependChild(Node child) {
Validate.notNull(child);
addChildren(0, child);
return this;
}
/**
* Create a new element by tag name, and add it as the last child.
*
* @param tagName the name of the tag (e.g. {@code div}).
* @return the new element, to allow you to add content to it, e.g.:
* {@code parent.appendElement("h1").attr("id", "header").text("Welcome");}
*/
public Element appendElement(String tagName) {
Element child = new Element(Tag.valueOf(tagName), baseUri());
appendChild(child);
return child;
}
/**
* Create a new element by tag name, and add it as the first child.
*
* @param tagName the name of the tag (e.g. {@code div}).
* @return the new element, to allow you to add content to it, e.g.:
* {@code parent.prependElement("h1").attr("id", "header").text("Welcome");}
*/
public Element prependElement(String tagName) {
Element child = new Element(Tag.valueOf(tagName), baseUri());
prependChild(child);
return child;
}
/**
* Create and append a new TextNode to this element.
*
* @param text the unencoded text to add
* @return this element
*/
public Element appendText(String text) {
TextNode node = new TextNode(text, baseUri());
appendChild(node);
return this;
}
/**
* Create and prepend a new TextNode to this element.
*
* @param text the unencoded text to add
* @return this element
*/
public Element prependText(String text) {
TextNode node = new TextNode(text, baseUri());
prependChild(node);
return this;
}
/**
* Add inner HTML to this element. The supplied HTML will be parsed, and each node appended to the end of the children.
* @param html HTML to add inside this element, after the existing HTML
* @return this element
* @see #html(String)
*/
public Element append(String html) {
Validate.notNull(html);
Element fragment = Parser.parseBodyFragmentRelaxed(html, baseUri()).body();
addChildren(fragment.childNodesAsArray());
return this;
}
/**
* Add inner HTML into this element. The supplied HTML will be parsed, and each node prepended to the start of the element's children.
* @param html HTML to add inside this element, before the existing HTML
* @return this element
* @see #html(String)
*/
public Element prepend(String html) {
Validate.notNull(html);
Element fragment = Parser.parseBodyFragmentRelaxed(html, baseUri()).body();
addChildren(0, fragment.childNodesAsArray());
return this;
}
/**
* Insert the specified HTML into the DOM before this element (i.e. as a preceeding sibling).
* @param html HTML to add before this element
* @return this element, for chaining
* @see #after(String)
*/
public Element before(String html) {
addSiblingHtml(siblingIndex(), html);
return this;
}
/**
* Insert the specified HTML into the DOM after this element (i.e. as a following sibling).
* @param html HTML to add after this element
* @return this element, for chaining
* @see #before(String)
*/
public Element after(String html) {
addSiblingHtml(siblingIndex()+1, html);
return this;
}
private void addSiblingHtml(int index, String html) {
Validate.notNull(html);
Validate.notNull(parentNode);
Element fragment = Parser.parseBodyFragmentRelaxed(html, baseUri()).body();
parentNode.addChildren(index, fragment.childNodesAsArray());
}
/**
* Remove all of the element's child nodes. Any attributes are left as-is.
* @return this element
*/
public Element empty() {
childNodes.clear();
return this;
}
/**
Wrap the supplied HTML around this element.
@param html HTML to wrap around this element, e.g. {@code <div class="head"></div>}. Can be arbitralily deep.
@return this element, for chaining.
*/
public Element wrap(String html) {
Validate.notEmpty(html);
Element wrapBody = Parser.parseBodyFragmentRelaxed(html, baseUri).body();
Elements wrapChildren = wrapBody.children();
Element wrap = wrapChildren.first();
if (wrap == null) // nothing to wrap with; noop
return null;
Element deepest = getDeepChild(wrap);
parentNode.replaceChild(this, wrap);
deepest.addChildren(this);
// remainder (unbalananced wrap, like <div></div><p></p> -- The <p> is remainder
if (wrapChildren.size() > 1) {
for (int i = 1; i < wrapChildren.size(); i++) { // skip first
Element remainder = wrapChildren.get(i);
remainder.parentNode.removeChild(remainder);
wrap.appendChild(remainder);
}
}
return this;
}
private Element getDeepChild(Element el) {
List<Element> children = el.children();
if (children.size() > 0)
return getDeepChild(children.get(0));
else
return el;
}
/**
* Get sibling elements.
* @return sibling elements
*/
public Elements siblingElements() {
return parent().children();
}
/**
* Gets the next sibling element of this element. E.g., if a {@code div} contains two {@code p}s,
* the {@code nextElementSibling} of the first {@code p} is the second {@code p}.
* <p/>
* This is similar to {@link #nextSibling()}, but specifically finds only Elements
* @return the next element, or null if there is no next element
* @see #previousElementSibling()
*/
public Element nextElementSibling() {
List<Element> siblings = parent().children();
Integer index = indexInList(this, siblings);
Validate.notNull(index);
if (siblings.size() > index+1)
return siblings.get(index+1);
else
return null;
}
/**
* Gets the previous element sibling of this element.
* @return the previous element, or null if there is no previous element
* @see #nextElementSibling()
*/
public Element previousElementSibling() {
List<Element> siblings = parent().children();
Integer index = indexInList(this, siblings);
Validate.notNull(index);
if (index > 0)
return siblings.get(index-1);
else
return null;
}
/**
* Gets the first element sibling of this element.
* @return the first sibling that is an element (aka the parent's first element child)
*/
public Element firstElementSibling() {
// todo: should firstSibling() exclude this?
List<Element> siblings = parent().children();
return siblings.size() > 1 ? siblings.get(0) : null;
}
/**
* Get the list index of this element in its element sibling list. I.e. if this is the first element
* sibling, returns 0.
* @return position in element sibling list
*/
public Integer elementSiblingIndex() {
if (parent() == null) return 0;
return indexInList(this, parent().children());
}
/**
* Gets the last element sibling of this element
* @return the last sibling that is an element (aka the parent's last element child)
*/
public Element lastElementSibling() {
List<Element> siblings = parent().children();
return siblings.size() > 1 ? siblings.get(siblings.size() - 1) : null;
}
private static <E extends Element> Integer indexInList(Element search, List<E> elements) {
Validate.notNull(search);
Validate.notNull(elements);
for (int i = 0; i < elements.size(); i++) {
E element = elements.get(i);
if (element.equals(search))
return i;
}
return null;
}
// DOM type methods
/**
* Finds elements, including and recursively under this element, with the specified tag name.
* @param tagName The tag name to search for (case insensitively).
* @return a matching unmodifiable list of elements. Will be empty if this element and none of its children match.
*/
public Elements getElementsByTag(String tagName) {
Validate.notEmpty(tagName);
tagName = tagName.toLowerCase().trim();
return Collector.collect(new Evaluator.Tag(tagName), this);
}
/**
* Find an element by ID, including or under this element.
* <p>
* Note that this finds the first matching ID, starting with this element. If you search down from a different
* starting point, it is possible to find a different element by ID. For unique element by ID within a Document,
* use {@link Document#getElementById(String)}
* @param id The ID to search for.
* @return The first matching element by ID, starting with this element, or null if none found.
*/
public Element getElementById(String id) {
Validate.notEmpty(id);
Elements elements = Collector.collect(new Evaluator.Id(id), this);
if (elements.size() > 0)
return elements.get(0);
else
return null;
}
/**
* Find elements that have this class, including or under this element. Case insensitive.
* <p>
* Elements can have multiple classes (e.g. {@code <div class="header round first">}. This method
* checks each class, so you can find the above with {@code el.getElementsByClass("header");}.
*
* @param className the name of the class to search for.
* @return elements with the supplied class name, empty if none
* @see #hasClass(String)
* @see #classNames()
*/
public Elements getElementsByClass(String className) {
Validate.notEmpty(className);
return Collector.collect(new Evaluator.Class(className), this);
}
/**
* Find elements that have a named attribute set. Case insensitive.
*
* @param key name of the attribute, e.g. {@code href}
* @return elements that have this attribute, empty if none
*/
public Elements getElementsByAttribute(String key) {
Validate.notEmpty(key);
key = key.trim().toLowerCase();
return Collector.collect(new Evaluator.Attribute(key), this);
}
/**
* Find elements that have an attribute name starting with the supplied prefix. Use {@code data-} to find elements
* that have HTML5 datasets.
* @param keyPrefix name prefix of the attribute e.g. {@code data-}
* @return elements that have attribute names that start with with the prefix, empty if none.
*/
public Elements getElementsByAttributeStarting(String keyPrefix) {
Validate.notEmpty(keyPrefix);
keyPrefix = keyPrefix.trim().toLowerCase();
return Collector.collect(new Evaluator.AttributeStarting(keyPrefix), this);
}
/**
* Find elements that have an attribute with the specific value. Case insensitive.
*
* @param key name of the attribute
* @param value value of the attribute
* @return elements that have this attribute with this value, empty if none
*/
public Elements getElementsByAttributeValue(String key, String value) {
return Collector.collect(new Evaluator.AttributeWithValue(key, value), this);
}
/**
* Find elements that either do not have this attribute, or have it with a different value. Case insensitive.
*
* @param key name of the attribute
* @param value value of the attribute
* @return elements that do not have a matching attribute
*/
public Elements getElementsByAttributeValueNot(String key, String value) {
return Collector.collect(new Evaluator.AttributeWithValueNot(key, value), this);
}
/**
* Find elements that have attributes that start with the value prefix. Case insensitive.
*
* @param key name of the attribute
* @param valuePrefix start of attribute value
* @return elements that have attributes that start with the value prefix
*/
public Elements getElementsByAttributeValueStarting(String key, String valuePrefix) {
return Collector.collect(new Evaluator.AttributeWithValueStarting(key, valuePrefix), this);
}
/**
* Find elements that have attributes that end with the value suffix. Case insensitive.
*
* @param key name of the attribute
* @param valueSuffix end of the attribute value
* @return elements that have attributes that end with the value suffix
*/
public Elements getElementsByAttributeValueEnding(String key, String valueSuffix) {
return Collector.collect(new Evaluator.AttributeWithValueEnding(key, valueSuffix), this);
}
/**
* Find elements that have attributes whose value contains the match string. Case insensitive.
*
* @param key name of the attribute
* @param match substring of value to search for
* @return elements that have attributes containing this text
*/
public Elements getElementsByAttributeValueContaining(String key, String match) {
return Collector.collect(new Evaluator.AttributeWithValueContaining(key, match), this);
}
/**
* Find elements that have attributes whose values match the supplied regular expression.
* @param key name of the attribute
* @param pattern compiled regular expression to match against attribute values
* @return elements that have attributes matching this regular expression
*/
public Elements getElementsByAttributeValueMatching(String key, Pattern pattern) {
return Collector.collect(new Evaluator.AttributeWithValueMatching(key, pattern), this);
}
/**
* Find elements that have attributes whose values match the supplied regular expression.
* @param key name of the attribute
* @param regex regular expression to match agaisnt attribute values. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements that have attributes matching this regular expression
*/
public Elements getElementsByAttributeValueMatching(String key, String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsByAttributeValueMatching(key, pattern);
}
/**
* Find elements whose sibling index is less than the supplied index.
* @param index 0-based index
* @return elements less than index
*/
public Elements getElementsByIndexLessThan(int index) {
return Collector.collect(new Evaluator.IndexLessThan(index), this);
}
/**
* Find elements whose sibling index is greater than the supplied index.
* @param index 0-based index
* @return elements greater than index
*/
public Elements getElementsByIndexGreaterThan(int index) {
return Collector.collect(new Evaluator.IndexGreaterThan(index), this);
}
/**
* Find elements whose sibling index is equal to the supplied index.
* @param index 0-based index
* @return elements equal to index
*/
public Elements getElementsByIndexEquals(int index) {
return Collector.collect(new Evaluator.IndexEquals(index), this);
}
/**
* Find elements that contain the specified string. The search is case insensitive. The text may appear directly
* in the element, or in any of its descendants.
* @param searchText to look for in the element's text
* @return elements that contain the string, case insensitive.
* @see Element#text()
*/
public Elements getElementsContainingText(String searchText) {
return Collector.collect(new Evaluator.ContainsText(searchText), this);
}
/**
* Find elements that directly contain the specified string. The search is case insensitive. The text must appear directly
* in the element, not in any of its descendants.
* @param searchText to look for in the element's own text
* @return elements that contain the string, case insensitive.
* @see Element#ownText()
*/
public Elements getElementsContainingOwnText(String searchText) {
return Collector.collect(new Evaluator.ContainsOwnText(searchText), this);
}
/**
* Find elements whose text matches the supplied regular expression.
* @param pattern regular expression to match text against
* @return elements matching the supplied regular expression.
* @see Element#text()
*/
public Elements getElementsMatchingText(Pattern pattern) {
return Collector.collect(new Evaluator.Matches(pattern), this);
}
/**
* Find elements whose text matches the supplied regular expression.
* @param regex regular expression to match text against. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements matching the supplied regular expression.
* @see Element#text()
*/
public Elements getElementsMatchingText(String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsMatchingText(pattern);
}
/**
* Find elements whose own text matches the supplied regular expression.
* @param pattern regular expression to match text against
* @return elements matching the supplied regular expression.
* @see Element#ownText()
*/
public Elements getElementsMatchingOwnText(Pattern pattern) {
return Collector.collect(new Evaluator.MatchesOwn(pattern), this);
}
/**
* Find elements whose text matches the supplied regular expression.
* @param regex regular expression to match text against. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements matching the supplied regular expression.
* @see Element#ownText()
*/
public Elements getElementsMatchingOwnText(String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsMatchingOwnText(pattern);
}
/**
* Find all elements under this element (including self, and children of children).
*
* @return all elements
*/
public Elements getAllElements() {
return Collector.collect(new Evaluator.AllElements(), this);
}
/**
* Gets the combined text of this element and all its children.
* <p>
* For example, given HTML {@code <p>Hello <b>there</b> now!</p>}, {@code p.text()} returns {@code "Hello there now!"}
*
* @return unencoded text, or empty string if none.
* @see #ownText()
*/
public String text() {
StringBuilder sb = new StringBuilder();
text(sb);
return sb.toString().trim();
}
private void text(StringBuilder accum) {
for (Node child : childNodes) {
if (child instanceof TextNode) {
TextNode textNode = (TextNode) child;
appendNormalisedText(accum, textNode);
} else if (child instanceof Element) {
Element element = (Element) child;
if (accum.length() > 0 && element.isBlock() && !TextNode.lastCharIsWhitespace(accum))
accum.append(" ");
element.text(accum);
}
}
}
/**
* Gets the text owned by this element only; does not get the combined text of all children.
* <p>
* For example, given HTML {@code <p>Hello <b>there</b> now!</p>}, {@code p.ownText()} returns {@code "Hello now!"},
* whereas {@code p.text()} returns {@code "Hello there now!"}.
* Note that the text within the {@code b} element is not returned, as it is not a direct child of the {@code p} element.
*
* @return unencoded text, or empty string if none.
* @see #text()
*/
public String ownText() {
StringBuilder sb = new StringBuilder();
ownText(sb);
return sb.toString().trim();
}
private void ownText(StringBuilder accum) {
for (Node child : childNodes) {
if (child instanceof TextNode) {
TextNode textNode = (TextNode) child;
appendNormalisedText(accum, textNode);
}
}
}
private void appendNormalisedText(StringBuilder accum, TextNode textNode) {
String text = textNode.getWholeText();
if (!preserveWhitespace()) {
text = TextNode.normaliseWhitespace(text);
if (TextNode.lastCharIsWhitespace(accum))
text = TextNode.stripLeadingWhitespace(text);
}
accum.append(text);
}
boolean preserveWhitespace() {
return tag.preserveWhitespace() || parent() != null && parent().preserveWhitespace();
}
/**
* Set the text of this element. Any existing contents (text or elements) will be cleared
* @param text unencoded text
* @return this element
*/
public Element text(String text) {
Validate.notNull(text);
empty();
TextNode textNode = new TextNode(text, baseUri);
appendChild(textNode);
return this;
}
/**
Test if this element has any text content (that is not just whitespace).
@return true if element has non-blank text content.
*/
public boolean hasText() {
for (Node child: childNodes) {
if (child instanceof TextNode) {
TextNode textNode = (TextNode) child;
if (!textNode.isBlank())
return true;
} else if (child instanceof Element) {
Element el = (Element) child;
if (el.hasText())
return true;
}
}
return false;
}
/**
* Get the combined data of this element. Data is e.g. the inside of a {@code script} tag.
* @return the data, or empty string if none
*/
public String data() {
StringBuilder sb = new StringBuilder();
for (Node childNode : childNodes) {
if (childNode instanceof DataNode) {
DataNode data = (DataNode) childNode;
sb.append(data.getWholeData());
} else if (childNode instanceof Element) {
Element element = (Element) childNode;
String elementData = element.data();
sb.append(elementData);
}
}
return sb.toString();
}
/**
* Gets the literal value of this element's "class" attribute, which may include multiple class names, space
* separated. (E.g. on <code><div class="header gray"></code> returns, "<code>header gray</code>")
* @return The literal class attribute, or <b>empty string</b> if no class attribute set.
*/
public String className() {
return attributes.hasKey("class") ? attributes.get("class") : "";
}
/**
* Get all of the element's class names. E.g. on element {@code <div class="header gray"}>},
* returns a set of two elements {@code "header", "gray"}. Note that modifications to this set are not pushed to
* the backing {@code class} attribute; use the {@link #classNames(java.util.Set)} method to persist them.
* @return set of classnames, empty if no class attribute
*/
public Set<String> classNames() {
if (classNames == null) {
String[] names = className().split("\\s+");
classNames = new LinkedHashSet<String>(Arrays.asList(names));
}
return classNames;
}
/**
Set the element's {@code class} attribute to the supplied class names.
@param classNames set of classes
@return this element, for chaining
*/
public Element classNames(Set<String> classNames) {
Validate.notNull(classNames);
attributes.put("class", StringUtil.join(classNames, " "));
return this;
}
/**
* Tests if this element has a class.
* @param className name of class to check for
* @return true if it does, false if not
*/
public boolean hasClass(String className) {
return classNames().contains(className);
}
/**
Add a class name to this element's {@code class} attribute.
@param className class name to add
@return this element
*/
public Element addClass(String className) {
Validate.notNull(className);
Set<String> classes = classNames();
classes.add(className);
classNames(classes);
return this;
}
/**
Remove a class name from this element's {@code class} attribute.
@param className class name to remove
@return this element
*/
public Element removeClass(String className) {
Validate.notNull(className);
Set<String> classes = classNames();
classes.remove(className);
classNames(classes);
return this;
}
/**
Toggle a class name on this element's {@code class} attribute: if present, remove it; otherwise add it.
@param className class name to toggle
@return this element
*/
public Element toggleClass(String className) {
Validate.notNull(className);
Set<String> classes = classNames();
if (classes.contains(className))
classes.remove(className);
else
classes.add(className);
classNames(classes);
return this;
}
/**
* Get the value of a form element (input, textarea, etc).
* @return the value of the form element, or empty string if not set.
*/
public String val() {
if (tagName().equals("textarea"))
return text();
else
return attr("value");
}
/**
* Set the value of a form element (input, textarea, etc).
* @param value value to set
* @return this element (for chaining)
*/
public Element val(String value) {
if (tagName().equals("textarea"))
text(value);
else
attr("value", value);
return this;
}
void outerHtmlHead(StringBuilder accum, int depth, Document.OutputSettings out) {
if (out.prettyPrint() && (isBlock() || (preserveWhitespace() != null && parent().tag().canContainBlock() && siblingIndex() == 0)))
indent(accum, depth, out);
accum
.append("<")
.append(tagName());
attributes.html(accum, out);
if (childNodes.isEmpty() && tag.isSelfClosing())
accum.append(" />");
else
accum.append(">");
}
void outerHtmlTail(StringBuilder accum, int depth, Document.OutputSettings out) {
if (!(childNodes.isEmpty() && tag.isSelfClosing())) {
if (out.prettyPrint() && !childNodes.isEmpty() && tag.canContainBlock())
indent(accum, depth, out);
accum.append("</").append(tagName()).append(">");
}
}
/**
* Retrieves the element's inner HTML. E.g. on a {@code <div>} with one empty {@code <p>}, would return
* {@code <p></p>}. (Whereas {@link #outerHtml()} would return {@code <div><p></p></div>}.)
*
* @return String of HTML.
* @see #outerHtml()
*/
public String html() {
StringBuilder accum = new StringBuilder();
html(accum);
return accum.toString().trim();
}
private void html(StringBuilder accum) {
for (Node node : childNodes)
node.outerHtml(accum);
}
/**
* Set this element's inner HTML. Clears the existing HTML first.
* @param html HTML to parse and set into this element
* @return this element
* @see #append(String)
*/
public Element html(String html) {
empty();
append(html);
return this;
}
public String toString() {
return outerHtml();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Element)) return false;
if (!super.equals(o)) return false;
Element element = (Element) o;
if (tag != null ? !tag.equals(element.tag) : element.tag != null) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (tag != null ? tag.hashCode() : 0);
return result;
}
}
| [
"justinwm@163.com"
] | justinwm@163.com |
a85d5b9430e683571f17c5f0f6b212c1d7abd054 | 61962bcb57f33ea7bfdc6a66a18a471bcccafd89 | /app/src/main/java/com/tudorluca/lantern/utils/Base64DecoderException.java | 9c82b2558fdcceb8151997e02c431129aeffa11a | [
"Apache-2.0"
] | permissive | suanweijiang/lantern | 98ad62d90d2265914f19524fbc320c36ec14e5da | cdd44e930e4ba585aa4813d8e444aacc3fe97056 | refs/heads/master | 2021-01-22T02:17:36.306385 | 2016-02-19T21:43:06 | 2016-02-19T21:43:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 975 | java | // Copyright 2002, Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.tudorluca.lantern.utils;
/**
* Exception thrown when encountering an invalid Base64 input character.
*
* @author nelson
*/
public class Base64DecoderException extends Exception {
public Base64DecoderException() {
super();
}
public Base64DecoderException(String s) {
super(s);
}
private static final long serialVersionUID = 1L;
}
| [
"luca.mtudor@gmail.com"
] | luca.mtudor@gmail.com |
f8a3ed6b6c29f9a9791a4b5a6f7b4790cb9b41f5 | 7c60a93a41da7d6a5b174373283519997b8cb0cd | /app/src/main/java/bayern/mimo/masterarbeit/util/Constants.java | 132ada915d2b873d21fee535b4474c32328e8a3f | [] | no_license | gitarreiro/Masterarbeit | a7200e7cf2e3e33a4b69db88cd8e5f49a7c47b46 | c7812d09a869e67b99aa51ad7a814b304b39c934 | refs/heads/master | 2021-01-18T17:58:59.588144 | 2018-02-07T13:22:51 | 2018-02-07T13:22:51 | 86,830,596 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 180 | java | package bayern.mimo.masterarbeit.util;
/**
* Created by MiMo
*/
public class Constants {
public static final int REQUEST_BLUETOOTH = 1;
private Constants(){}
}
| [
"m.moosbauer@fupa.net"
] | m.moosbauer@fupa.net |
e4cdc18a4a1da36dbd653553774a983ca28e5ac3 | ebf8a3b2737b31d11cc20b7906014cd857b841fc | /src/main/java/SeliniumSessions/TotalLinks.java | 3a91f665f2a0d0fc4d918892ad7b51841e325e43 | [] | no_license | UshaAthota/SeleniumCode | 2efe8f589f7bb7c4d3673b02869f9b20d5c2a336 | aed64248e9ee04ef7de8713d57b5eaec0ba2b0e8 | refs/heads/master | 2022-07-16T14:35:31.831977 | 2020-05-07T21:37:03 | 2020-05-07T21:37:03 | 262,163,286 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 940 | java | package SeliniumSessions;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class TotalLinks {
public static void main(String[] args) {
//to get total number of link
WebDriverManager.chromedriver().setup();
WebDriver driver=new ChromeDriver();
driver.get("http://www.amazon.in/");
List<WebElement> linksList=driver.findElements(By.tagName("a"));
int totalLinks=linksList.size();
System.out.println("Total links on the page is "+ totalLinks);
//to print text of each link
for(int i=0;i<totalLinks;i++) {
String linksText=linksList.get(i).getText();
if(!linksText.isEmpty()) {
System.out.print(i+"--->"+linksText+"---->");
System.out.println(linksList.get(i).getAttribute("href"));
}
}
}
}
| [
"usha.grpt@gmail.com"
] | usha.grpt@gmail.com |
0108c5c350688e919f9157bef7c29e97726ca8ca | 3cc63f4af091d264f9987463ca60c79e6c7dd25d | /spring/hzq-spring-v2/src/main/java/com/hzqing/user/UserController.java | 35c88f90b9acca3ab097b34014c5dc5e6c162d7a | [] | no_license | mmd0308/study | 0db4d4aa9d77ec015c4e1c2a5db9378430be0b9f | 5489bf43569ef121354adf80cce34e10713ff9dd | refs/heads/master | 2022-12-25T09:24:01.176086 | 2020-01-09T08:55:08 | 2020-01-09T08:55:08 | 193,449,889 | 2 | 0 | null | 2022-12-16T05:00:21 | 2019-06-24T06:47:43 | Java | UTF-8 | Java | false | false | 889 | java | package com.hzqing.user;
import com.hzqing.annoation.HZQAutowired;
import com.hzqing.annoation.HZQController;
import com.hzqing.annoation.HZQRequestMapping;
import com.hzqing.annoation.HZQRequestParam;
import com.hzqing.user.service.IUserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author hzqing
* @date 2020-01-04 14:26
*/
@HZQController
@HZQRequestMapping("/user")
public class UserController {
@HZQAutowired
private IUserService userService;
@HZQRequestMapping("/get")
public void get(HttpServletRequest request, HttpServletResponse response, @HZQRequestParam("name")String name){
String res = userService.get(name);
try {
response.getWriter().write(res);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| [
"hengzhaoqing@163.com"
] | hengzhaoqing@163.com |
62790c22eb19e7a2a70d53ee3b69dc8ba38df99a | 64ac9d4821ee0faea73ebc4d5e1b97d08cb5bf57 | /app/src/main/java/com/example/lenovo/sqliteimage/MainActivity.java | 709e9ce3229053a23ad99b1285ecdf716376a4b1 | [] | no_license | nurafiqahamnan/SQLiteImage | c2a19753504c8334a0893621b1fbbc1d10477268 | 4f679cb643c1ca4fd420a6f8f2ef40bd56a81e22 | refs/heads/master | 2021-07-20T05:16:31.976112 | 2017-10-28T17:47:46 | 2017-10-28T17:47:46 | 108,670,951 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,533 | java | package com.example.lenovo.sqliteimage;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import static android.support.v7.appcompat.R.id.image;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
EditText edtName, edtPrice;
Button btnChoose, btnAdd, btnList;
ImageView imageView;
final int REQUEST_CODE_GALLERY = 999;
public static SQLiteHelper sqLiteHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
sqLiteHelper = new SQLiteHelper(this, "FoodDB.sqlite", null, 1);
sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, price VARCHAR, image BLOB)");
btnChoose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(
MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_GALLERY
);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
sqLiteHelper.insertData(
edtName.getText().toString().trim(),
edtPrice.getText().toString().trim(),
imageViewToByte(imageView)
);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
edtName.setText("");
edtPrice.setText("");
imageView.setImageResource(R.mipmap.ic_launcher);
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, FoodList.class);
startActivity(intent);
}
});
}
public static byte[] imageViewToByte(ImageView image) {
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_GALLERY) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_GALLERY);
} else {
Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void init() {
edtName = (EditText) findViewById(R.id.edtName);
edtPrice = (EditText) findViewById(R.id.edtPrice);
btnChoose = (Button) findViewById(R.id.btnChoose);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnList = (Button) findViewById(R.id.btnList);
imageView = (ImageView) findViewById(R.id.imageView);
}
} | [
"nurafiqahamnan@yahoo.com"
] | nurafiqahamnan@yahoo.com |
6ae643cf6eb8c04a8faee08fe10d7a75079a5645 | a67b443bab042c3ca69b42932b25c5279ae7c679 | /app/src/main/java/cn/njthl/cleaner/util/VideoThumbLoader.java | 14a12bba1692d8ffcf120b7df8ae44f18f4bbf0c | [] | no_license | chenzongguo/Cleaner | fad32fab48bb4d014f8eb9f6e6c4dcf69e7c0e6f | 0672efee721206ece1ba8a1989adb7296cc2972d | refs/heads/master | 2020-08-08T18:59:46.797013 | 2019-11-04T00:32:08 | 2019-11-04T00:32:08 | 213,894,543 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,517 | java | package cn.njthl.cleaner.util;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.widget.ImageView;
import androidx.collection.LruCache;
/**
* @创建者 CSDN_LQR
* @描述 视频缩略图加载工具
*/
public class VideoThumbLoader {
private ImageView imgView;
private String path;
static VideoThumbLoader instance;
public static VideoThumbLoader getInstance() {
if (instance == null) {
synchronized (VideoThumbLoader.class) {
if (instance == null) {
instance = new VideoThumbLoader();
}
}
}
return instance;
}
// 创建cache
private LruCache<String, Bitmap> lruCache;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (imgView.getTag().equals(path)) {
Bitmap btp = (Bitmap) msg.obj;
imgView.setImageBitmap(btp);
}
}
};
// @SuppressLint("NewApi")
private VideoThumbLoader() {
int maxMemory = (int) Runtime.getRuntime().maxMemory();// 获取最大的运行内存
int maxSize = maxMemory / 8;
lruCache = new LruCache<String, Bitmap>(maxSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
// 这个方法会在每次存入缓存的时候调用
// return value.getByteCount();
return value.getRowBytes() * value.getHeight();
}
};
}
private void addVideoThumbToCache(String path, Bitmap bitmap) {
if (getVideoThumbToCache(path) == null && bitmap != null) {
// 当前地址没有缓存时,就添加
lruCache.put(path, bitmap);
}
}
private Bitmap getVideoThumbToCache(String path) {
return lruCache.get(path);
}
public void showThumb(String path, ImageView imgview, int width, int height) {
if (getVideoThumbToCache(path) == null) {
// 异步加载
imgview.setTag(path);
new MyBobAsynctack(imgview, path, width, height).execute(path);
} else {
imgview.setImageBitmap(getVideoThumbToCache(path));
}
}
class MyBobAsynctack extends AsyncTask<String, Void, Bitmap> {
private ImageView imgView;
private String path;
private int width;
private int height;
public MyBobAsynctack(ImageView imageView, String path, int width,
int height) {
this.imgView = imageView;
this.path = path;
this.width = width;
this.height = height;
}
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = createVideoThumbnail(params[0], width, height,
MediaStore.Video.Thumbnails.MICRO_KIND);
// 加入缓存中
if (getVideoThumbToCache(params[0]) == null && bitmap != null) {
addVideoThumbToCache(path, bitmap);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imgView.getTag() != null && imgView.getTag().equals(path)) {
imgView.setImageBitmap(bitmap);
}
}
}
private void showDateByThread(ImageView imageview, final String path,
final int width, final int height) {
imgView = imageview;
this.path = path;
new Thread(new Runnable() {
@Override
public void run() {
Bitmap bitmap = createVideoThumbnail(path, width, height,
MediaStore.Video.Thumbnails.MICRO_KIND);
Message msg = new Message();
msg.obj = bitmap;
msg.what = 1001;
mHandler.sendMessage(msg);
}
}).start();
}
private static Bitmap createVideoThumbnail(String vidioPath, int width,
int height, int kind) {
Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(vidioPath, kind);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}
}
| [
"1196437229@qq.com"
] | 1196437229@qq.com |
3e6fa61dd49ef6121a176ee6ec0d04038a029e62 | 5af6ff1f12441aed3a5e371588e0a22b3facbfeb | /SlaveBot.java | 7203a454c8177e4affe347dac4f8bcb2fd5897fd | [] | no_license | Divyasam/DDOS | a6ce2716c4793cdc7de726c6f0c60fe1d99f036b | c1afd561f97e27afe80069642481c11b34b607f1 | refs/heads/master | 2021-09-05T21:39:38.770856 | 2018-01-31T06:25:38 | 2018-01-31T06:25:38 | 119,644,505 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,377 | java | //package com.divya.serverclient.program;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SlaveBot
{
public static ArrayList<Client_connections> Target_List;
// public static ArrayList IpAddressList = new ArrayList();
// public static ArrayList TargetPortList = new ArrayList();
static String Target_name;
static int Target_port;
static int Number_ofconn;
static Socket host_comm;
static String command5;
static String[] command ;
public static void main(String[] args) throws Exception
{
String Local_host = null;
int Port_number=0;
Socket server_comm = null;
String Client_input = null;
if(args.length>4 || args.length<3)
{
System.out.println("Incorrect Slave Command");
}
else if (args.length==4)
{
if(args[0].equals("-h") && args[2].equals("-p"))
{
Local_host=args[1];
Port_number=Integer.parseInt(args[3]);
}
else
{
System.out.println("Input is invalid use -h and -p option for the command");
System.exit(0);
}
try
{
server_comm = new Socket(Local_host,Port_number);
}
catch(Exception e)
{
System.out.println(e.getStackTrace().toString());
}
while(true)
{
Scanner sc=new Scanner(server_comm.getInputStream());
Client_input = sc.nextLine();
command = Client_input.split(" ");
if(command[0].equals("connect"))
{
if (command.length < 4)
{
System.out.println("Incorrect connect command");
}
else
{
Target_name=command[1];
Target_port=Integer.parseInt(command[2]);
Number_ofconn=Integer.parseInt(command[3]);
command5=command[4];
Target_List=new ArrayList<Client_connections>();
for(int i=0; i<Number_ofconn; i++)
{
try
{
Client_connections cli_conn = new Client_connections();
host_comm=new Socket(Target_name,Target_port);
if(command.length==5)
{
if(command5.equalsIgnoreCase("keepalive"))
{
System.out.println("I am at keepalive");
host_comm.setKeepAlive(true);
}
else if (command5.matches("^url=[^ ]+$"))
{
String URL = command5.substring(4);
String randomCode = createRandomCode(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
String Final_URL = URL + randomCode ;
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(host_comm.getOutputStream(), "UTF8"));
writer.write("GET " + Final_URL + "\r\n");
writer.write("\r\n");
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(host_comm.getInputStream()));
String responseLine;
if((responseLine = reader.readLine()) != null)
{
System.out.println("I got the response and here is the first line: " + responseLine);
}
System.out.println("Connected Via: " + host_comm.getInetAddress().getLocalHost()+ ":" + host_comm.getLocalPort());
}
}
cli_conn.Host_socket = host_comm;
cli_conn.Host_address=host_comm.getInetAddress().getHostAddress();
cli_conn.Host_name=host_comm.getInetAddress().getHostName();
cli_conn.Host_port = Target_port;
Target_List.add(cli_conn);
}
catch(IOException e)
{
System.out.println(e.getStackTrace().toString());
}
}
}
}
if(command[0].equals("disconnect"))
{
if (command.length < 3)
{
System.out.println("Incorrect disconnect command");
}
else
{
Iterator<Client_connections> iterate = Target_List.iterator();
int targetport=0;
targetport = Integer.parseInt(command[2]);
if (command[1].matches("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$") == true)
{
int found = 0;
if(targetport==0)
{
for(int i=0; i<Target_List.size();i++ )
{
if(Target_List.get(i).Host_address.equals(command[1]))
{
Target_List.get(i).Host_socket.close();
Target_List.remove(i);
found=1;
}
}
}
else
{
for(int i=0; i<Target_List.size();i++ )
{
if(Target_List.get(i).Host_address.equals(command[1])&&Target_List.get(i).Host_port==targetport)
{
Target_List.get(i).Host_socket.close();
Target_List.remove(i);
found=1;
}
}
}
if(found == 0)
{
System.out.println("Incorrect host address or port in disconnect!!");
}
}
else
{
int found = 0;
if(targetport==0)
{
for(int i=0; i<Target_List.size();i++ )
{
if(Target_List.get(i).Host_name.equals(command[1]))
{
Target_List.get(i).Host_socket.close();
Target_List.remove(i);
found=1;
}
}
}
else
{
for(int i=0; i<Target_List.size();i++ )
{
if(Target_List.get(i).Host_name.equals(command[1]) && Target_List.get(i).Host_port==targetport)
{
Target_List.get(i).Host_socket.close();
Target_List.remove(i);
found=1;
}
}
}
if(found == 0)
{
System.out.println("Incorrect host address or port in disconnect!!");
}
}
}
}
if(command[0].equals("ipscan"))
{
ArrayList IpAddressList = new ArrayList();
String IpAddressRange=command[1];
String[] parts = IpAddressRange.split("-");
String start = parts[0];
String end = parts[1];
String[] startParts = start.split("(?<=\\.)(?!.*\\.)");
String[] endParts = end.split("(?<=\\.)(?!.*\\.)");
int first = Integer.parseInt(startParts[1]);
int last = Integer.parseInt(endParts[1]);
String ListOfIpAddresses ="";
for (int i = first; i <= last; i++)
{
String IpAddress = startParts[0] + i ;
boolean result = isReachable(1, 5000, IpAddress);
//boolean result = InetAddress.getByName(IpAddress).isReachable(5000);
//System.out.println("output : " + result);
if(result)
{
IpAddressList.add(IpAddress);
}
}
for(int j=0, length=IpAddressList.size(); j<length; j++)
ListOfIpAddresses+=(j==0?"":", ") + IpAddressList.get(j);
PrintStream p = new PrintStream(server_comm.getOutputStream());
p.println(ListOfIpAddresses);
p.flush();
}
if(command[0].equals("tcpportscan"))
{
ArrayList TargetPortList = new ArrayList();
String TargetPortNumberRange = command[2];
String[] parts = TargetPortNumberRange.split("-");
int part1 = Integer.parseInt(parts[0]);
int part2 = Integer.parseInt(parts[1]);
for (int i = part1; i <= part2; i++)
{
int TargetPort=i;
boolean result = isPortInUse(command[1],TargetPort);
//System.out.println("output : " + result);
if(result)
{
TargetPortList.add(TargetPort);
}
}
String ListOfTargetPorts ="";
for(int j=0, length=TargetPortList.size(); j<length; j++)
ListOfTargetPorts+=(j==0?"":", ") + TargetPortList.get(j);
//System.out.println(ListOfTargetPorts);
PrintStream p = new PrintStream(server_comm.getOutputStream());
p.println(ListOfTargetPorts);
p.flush();
}
if(command[0].equals("geoipscan"))
{
ArrayList IpAddressList = new ArrayList();
String IpAddressRange=command[1];
String[] parts = IpAddressRange.split("-");
String start = parts[0];
String end = parts[1];
String[] startParts = start.split("(?<=\\.)(?!.*\\.)");
String[] endParts = end.split("(?<=\\.)(?!.*\\.)");
int first = Integer.parseInt(startParts[1]);
int last = Integer.parseInt(endParts[1]);
StringBuilder builder = new StringBuilder();
for (int i = first; i <= last; i++)
{
String IpAddress = startParts[0] + i ;
boolean result = isReachable(1, 5000, IpAddress);
if(result)
{
//Using api to get the geolocation of the particular IpAddress.
String text = callURL("http://ip-api.com/csv/" + IpAddress) ;
//The response will contain success in the beginning.
//If its success, geolocation of that IpAddress can be obtained.
char a_char = text.charAt(0);
ArrayList TextList = new ArrayList();
if(a_char == 's')
{
//To remove success from the response
String response=text.substring(8);
//Server response will contain the IpAddress. But its not needed.
//To remove the IpAddress from the server returned(response) string.
//Splitting the response by comma and comparing it with IpAddress.
String[] TextSeperatedArray = response.split(",");
for(int j=0 ; j<TextSeperatedArray.length ; j++)
{
String SingleValue=TextSeperatedArray[j];
//If the value matches IpAddress, replace it with blankspace.
if(SingleValue.equalsIgnoreCase(IpAddress))
{
SingleValue = " ";
}
TextList.add(SingleValue);
}
String TextLine="";
for(int k=0, length=TextList.size(); k<length; k++)
TextLine+=(k==0?"":", ") + TextList.get(k);
//To remove comma(the last character) from the IpAddress removed line.
Pattern p = Pattern.compile("[, ]+$");
Matcher m = p.matcher(TextLine);
String clean = m.replaceFirst("");
builder.append( IpAddress + " " + clean + "\n" );
}
else
{
System.out.println("Check the geoipscan command");
}
}
}
PrintStream p = new PrintStream(server_comm.getOutputStream());
p.println(builder.toString());
p.flush();
}
}
}
}
private static boolean isReachable(int nping, int wping, String ipping) throws Exception
{
String strCommand = "";
if(System.getProperty("os.name").startsWith("Windows"))
{
// construct command for Windows Operating system
strCommand = "ping -n " + nping + " -w " + wping + " " + ipping;
}
else
{
// construct command for Linux and OSX
strCommand = "ping -c 1 " + ipping;
}
Runtime runtime = Runtime.getRuntime();
Process process1 = runtime.exec(strCommand);
Scanner sc3 = new Scanner(process1.getInputStream());
process1.waitFor();
ArrayList<String> list = new ArrayList<>();
String data = "";
while (sc3.hasNextLine()) {
String string1 = sc3.nextLine();
data = data + string1 + "\n";
list.add(string1);
}
if (data.contains("IP address must be specified.")
|| (data.contains("Ping request could not find host " + ipping + ".")
|| data.contains("Please check the name and try again."))) {
throw new Exception(data);
} else if (nping > list.size()) {
throw new Exception(data);
}
int connections_made = 0;
int connections_lost = 0;
int index = 2;
for (int i = index; i < nping + index; i++) {
String string2 = list.get(i);
if (string2.contains("Destination host unreachable.")) {
connections_lost++;
} else if (string2.contains("Request timed out.")) {
connections_lost++;
} else if (string2.contains("bytes") && string2.contains("time") && string2.contains("TTL")) {
connections_made++;
} else {
}
}
return connections_made > 0;
}
private static boolean isPortInUse(String hostName, int portNumber)
{
boolean result;
try {
Socket s = new Socket(hostName, portNumber);
s.close();
result = true;
}
catch(Exception e) {
result = false;
}
return(result);
}
public static String createRandomCode(int codeLength, String id){
char[] chars = id.toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new SecureRandom();
for (int i = 0; i < codeLength; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
return output ;
}
public static String callURL(String myURL) {
//System.out.println("Requeted URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
urlConn.setReadTimeout(5 * 1000);
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:"+ myURL, e);
}
return sb.toString();
}
}
| [
"noreply@github.com"
] | noreply@github.com |
a9ebb2567ae88e02e3690fe16fc9eec88a2777ff | 4ff9c60bcd39e04f84d7208f72387aa2cc48aec8 | /Btvn_Buoi2/src/Bai29.java | 94d33b8cfe6525528ed4e79b5a5cb14dce17edd0 | [] | no_license | buitam/ANDROID | 583281c7d13a8aab0ecdc9f64e81597ab5a6dc5d | 45d3107253d5aeda617837317f2a7a6bf1cb1660 | refs/heads/master | 2020-06-27T15:32:03.293355 | 2019-10-01T17:03:16 | 2019-10-01T17:03:16 | 199,987,945 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 665 | java | public class Bai29 {
int h;
void nhap( int gtn) {
h = gtn;
}
void in() {
for (int i = 1; i <= h; i++) {
for (int k = i; k < h ; k++){
System.out.print(" ");
}
for (int j = 1; j <= i; j++){
if(i == h || j == i || j == 1) {
System.out.print(" *");
}
else {
System.out.print(" ");
}
}
System.out.println(" ");
}
}
public static void main(String[] args) {
Bai29 b29 = new Bai29();
b29.nhap(8);
b29.in();
}
}
| [
"buitam2708@gmail.com"
] | buitam2708@gmail.com |
0cce90f307223f02d158d998902c67824c200439 | 7155009652b45a45ab04a278b7a843eb5b8209ce | /demo_05/src/main/java/com/lss/myapplication/Main2Activity.java | ccdf872d89202227cbd2aced7e462ac88586ad6c | [] | no_license | liss133/AndroidOne | 1bf8a919c24950e68d1aca4929a11090b1ac03f4 | 67176a6b050e73dad216427aeb105dd198f379da | refs/heads/master | 2020-03-23T17:27:42.593596 | 2018-12-17T14:59:36 | 2018-12-17T14:59:36 | 141,861,048 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,835 | java | package com.lss.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class Main2Activity extends AppCompatActivity {
private ListView listView;
private ArrayAdapter <String> arrayAdapter;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
listView= (ListView) findViewById(R.id.listView);
button= (Button) findViewById(R.id.to3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Main2Activity.this,Main3Activity.class);
startActivity(intent);
//动态跳出第三个界面
overridePendingTransition(R.anim.tip_right,R.anim.tip_left);
}
});
arrayAdapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,getList());
listView.setAdapter(arrayAdapter);
//讲菜单注册到长点击事件上
registerForContextMenu(listView);
}
public List<String> getList(){
List<String> list = new ArrayList<String>();
list.add("数据1");
list.add("数据2");
list.add("数据3");
list.add("数据4");
list.add("数据5");
return list;
}
//注册和激活
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
//菜单填充器
MenuInflater menuInflater = getMenuInflater();
//把one填充进去
menuInflater.inflate(R.menu.one,menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
//菜单选择器
@Override
public boolean onContextItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id){
case R.id.save:
Toast.makeText(Main2Activity.this, "保存", Toast.LENGTH_SHORT).show();
break;
case R.id.delete:
Toast.makeText(Main2Activity.this, "删除", Toast.LENGTH_SHORT).show();
break;
case R.id.sao:
Toast.makeText(Main2Activity.this, "扫一扫", Toast.LENGTH_SHORT).show();
break;
}
return super.onContextItemSelected(item);
}
}
| [
"18843109253@163.com"
] | 18843109253@163.com |
ac41304c6e460fcaa723a61d6a7c38da9ed53ba5 | 8d88d9d1663baef19da866a5008b92a27aedf1d4 | /providers/cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/compute/CloudServersUSTemplateBuilderLiveTest.java | c58e96e2377c7be1b6aeb797ef8b032f66bf2e9a | [
"Apache-2.0"
] | permissive | maxrak/jclouds | 54ca1de8d23f1e23c82dacd5d00667bf018cbc3d | ab7b19d6bd819e69e0071b74c2a1db7b9fb78b59 | refs/heads/master | 2021-01-16T20:57:24.242224 | 2011-01-25T02:09:50 | 2011-01-25T02:09:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,812 | java | /**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rackspace.cloudservers.compute;
import static org.jclouds.compute.util.ComputeServiceUtils.getCores;
import static org.testng.Assert.assertEquals;
import org.jclouds.compute.BaseTemplateBuilderLiveTest;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.os.OsFamilyVersion64Bit;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
/**
*
* @author Adrian Cole
*/
@Test(groups = "live")
public class CloudServersUSTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {
public CloudServersUSTemplateBuilderLiveTest() {
provider = "cloudservers-us";
}
@Override
protected Predicate<OsFamilyVersion64Bit> defineUnsupportedOperatingSystems() {
return new Predicate<OsFamilyVersion64Bit>() {
@Override
public boolean apply(OsFamilyVersion64Bit input) {
return (input.family != OsFamily.WINDOWS && !input.is64Bit) || //
input.family == OsFamily.RHEL || //
(input.family == OsFamily.UBUNTU && input.version.equals("11.04")) || //
(input.family == OsFamily.CENTOS && input.version.matches("5.[23]")) || //
(input.family == OsFamily.WINDOWS && input.version.equals("2008")) || //
(input.family == OsFamily.WINDOWS && input.version.equals("2008 R2") && !input.is64Bit);
}
};
}
@Test
public void testTemplateBuilder() {
Template defaultTemplate = this.context.getComputeService().templateBuilder().build();
assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "10.04");
assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(defaultTemplate.getLocation().getId(), "US");
assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);
}
}
| [
"adrian@jclouds.org"
] | adrian@jclouds.org |
68d7310f478294f2d70625250abc5c4191224575 | b62e073c733922ca8a36997e84805b4dfbd4d215 | /mssqserverJPARepoMultipleDB/src/main/java/com/example/jpa/mssqserver/mssqserver/controller/CertifiedCellPhoneController.java | 8d1e1d821a5db389f099dd5dd0c3a553e2ae151d | [] | no_license | Angel1216/SpringDataJPAMultipleDB | df5a76980b77ccf2118484297cf684f05c64d8ca | 0f385bab4aaa18c2ac1cece0790a92e289c3ffe2 | refs/heads/master | 2022-12-24T06:46:27.337024 | 2020-09-28T19:31:44 | 2020-09-28T19:31:44 | 299,406,857 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,534 | java | package com.example.jpa.mssqserver.mssqserver.controller;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.jpa.mssqserver.mssqserver.entity.clients.Clients;
import com.example.jpa.mssqserver.mssqserver.service.CertifiedCellPhoneService;
import com.example.jpa.mssqserver.mssqserver.service.ClientService;
@RestController
//@RequestMapping(value = "/retrieve-db")
public class CertifiedCellPhoneController {
@Autowired
private CertifiedCellPhoneService certifiedCellPhoneService;
@Autowired
private ClientService clientService;
@PostMapping(value = "/certifiedCellPhone", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, String>> getCertifiedCellPhone() {
Map<String, String> responseSP = certifiedCellPhoneService.certifiedCellPhoneValidation("254656");
return new ResponseEntity<>(responseSP, HttpStatus.OK);
}
@PostMapping(value = "/client", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Optional<Clients>> getClient() {
Optional<Clients> client = clientService.clientValidation(254656);
return new ResponseEntity<>(client, HttpStatus.OK);
}
}
| [
"amartinez@novasolutionsystems.com"
] | amartinez@novasolutionsystems.com |
2dda94b71060616fe63b50a6775f7a15879e6ffc | 3ba0d14ed08848788c7c7880d0e4b2a157ad8ac0 | /src/main/java/com/hcl/onlinefood/OnlineFoodHibernate/beans/Owner.java | 67b372a98ef4d9faf0a6d7b37eb50046a1d12337 | [] | no_license | vaddadipranathi/SpringBoot-App | 7203479f90c0fe57e60b8cc0894fd72744769467 | bf95f73b75b25371118eab18de2c9c529e5f1b4b | refs/heads/master | 2023-05-27T02:19:47.736852 | 2021-06-01T06:30:53 | 2021-06-01T06:30:53 | 372,397,937 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 408 | java | package com.hcl.onlinefood.OnlineFoodHibernate.beans;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@NoArgsConstructor
@Entity
@Table(name = "owner2")
public class Owner {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "oid")
private int oid;
@Column(name = "ownerName", nullable = false)
private String ownerName;
}
| [
"vaddadipranathi0@gmail.com"
] | vaddadipranathi0@gmail.com |
357dbb5efcc6b984f950b789b60f0ed85e26adef | c40efb977101232d91e99af0b78778bad3e0950a | /game_server/src/com/hifun/soul/gameserver/shop/template/ShopTemplateVO.java | 99c19cc72ad01c1706fb8e0dd0519f178a55857e | [] | no_license | cietwwl/server | 2bca79a17be6d5e6fee65e57d0df1fc753fb35e3 | d18804f8c182eaa2509666aec10a2212ababc13c | refs/heads/master | 2020-06-14T15:12:16.679591 | 2014-11-19T14:48:04 | 2014-11-19T14:48:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,496 | java | package com.hifun.soul.gameserver.shop.template;
import com.hifun.soul.core.annotation.ExcelRowBinding;
import com.hifun.soul.common.exception.TemplateConfigException;
import com.hifun.soul.core.annotation.ExcelCellBinding;
import com.hifun.soul.core.template.TemplateObject;
/**
* 商店模版
*
* @author SevenSoul
*/
@ExcelRowBinding
public abstract class ShopTemplateVO extends TemplateObject {
/** 道具ID */
@ExcelCellBinding(offset = 1)
protected int itemId;
/** 购买货币类型 */
@ExcelCellBinding(offset = 2)
protected short currencyType;
/** 购买货币数量 */
@ExcelCellBinding(offset = 3)
protected int num;
/** 等级限制 */
@ExcelCellBinding(offset = 4)
protected int levelLimit;
/** 职业限制 */
@ExcelCellBinding(offset = 5)
protected int occupationLimit;
public int getItemId() {
return this.itemId;
}
public void setItemId(int itemId) {
if (itemId == 0) {
throw new TemplateConfigException(this.getSheetName(), this.getId(),
2, "[ 道具ID]itemId不可以为0");
}
this.itemId = itemId;
}
public short getCurrencyType() {
return this.currencyType;
}
public void setCurrencyType(short currencyType) {
if (currencyType == 0) {
throw new TemplateConfigException(this.getSheetName(), this.getId(),
3, "[ 购买货币类型]currencyType不可以为0");
}
this.currencyType = currencyType;
}
public int getNum() {
return this.num;
}
public void setNum(int num) {
if (num == 0) {
throw new TemplateConfigException(this.getSheetName(), this.getId(),
4, "[ 购买货币数量]num不可以为0");
}
this.num = num;
}
public int getLevelLimit() {
return this.levelLimit;
}
public void setLevelLimit(int levelLimit) {
if (levelLimit < 0) {
throw new TemplateConfigException(this.getSheetName(), this.getId(),
5, "[ 等级限制]levelLimit的值不得小于0");
}
this.levelLimit = levelLimit;
}
public int getOccupationLimit() {
return this.occupationLimit;
}
public void setOccupationLimit(int occupationLimit) {
if (occupationLimit < 0) {
throw new TemplateConfigException(this.getSheetName(), this.getId(),
6, "[ 职业限制]occupationLimit的值不得小于0");
}
this.occupationLimit = occupationLimit;
}
@Override
public String toString() {
return "ShopTemplateVO[itemId=" + itemId + ",currencyType=" + currencyType + ",num=" + num + ",levelLimit=" + levelLimit + ",occupationLimit=" + occupationLimit + ",]";
}
} | [
"magicstoneljg@163.com"
] | magicstoneljg@163.com |
6acb91e0315d728a295e70635bd54ad2506f0b1d | cacec52e5653ab773d35d7f1b4f4f660580d7826 | /web-admin/src/main/java/com/alipay/api/response/AlipayMobilePublicLabelUpdateResponse.java | 254ed551927b1531c6ecc69b4376028f98c24916 | [] | no_license | liuyuhua1984/GameAdminWeb | 6d830e7ad1551ac1803abd12e9359c6bfd5965ec | c590fd88d768c8231e2160bf7415996b0027ac98 | refs/heads/master | 2021-08-28T13:40:50.540862 | 2017-12-12T10:20:06 | 2017-12-12T10:20:06 | 106,268,614 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 910 | java | package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.mobile.public.label.update response.
*
* @author auto create
* @since 1.0, 2016-07-29 19:58:24
*/
public class AlipayMobilePublicLabelUpdateResponse extends AlipayResponse {
private static final long serialVersionUID = 6874464923242368379L;
/**
* 结果码
*/
@ApiField("code")
private String code;
/**
* 标签编号
*/
@ApiField("id")
private Long id;
/**
* 结果信息
*/
@ApiField("msg")
private String msg;
public void setCode(String code) {
this.code = code;
}
public String getCode( ) {
return this.code;
}
public void setId(Long id) {
this.id = id;
}
public Long getId( ) {
return this.id;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getMsg( ) {
return this.msg;
}
}
| [
"lyh@163.com"
] | lyh@163.com |
d891ec64006fe96c19958129a662bb2df91c64d8 | e26f7491d21ac0c8623e921e61d502d2160cde8f | /src/main/java/tony/verlaan/hu/lingo/Game/Repository/ScoreRepository.java | a9a36b3028bcef3d4721fef6bde3ff0a986edbc1 | [] | no_license | tony0200/lingo2.0 | 9358dcf6f32d5a38a852762d336c626e50fb683f | a6681666d5c220e0eede2585f15b130579733687 | refs/heads/main | 2023-02-12T03:37:41.877830 | 2021-01-08T13:21:06 | 2021-01-08T13:21:06 | 323,901,742 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 256 | java | package tony.verlaan.hu.lingo.Game.Repository;
import org.springframework.data.repository.CrudRepository;
import tony.verlaan.hu.lingo.Game.Domain.Score;
import java.util.List;
public interface ScoreRepository<S> extends CrudRepository<Score, Long> {
}
| [
"tony.verlaan@student.hu.nl"
] | tony.verlaan@student.hu.nl |
997d146db98809d8bf663a498542dbe9ed3b7a94 | e4d20db8e12f6c0682f32fa80f55da59f155a602 | /mysql-demo/src/main/java/com/example/mysql/mappers/BookMapper.java | 42fbe74d8cdb78a2f0ddc39b90054c1958c13327 | [] | no_license | Ar11rA/Learning-Spring | 051c1731ec70f06ac532d59f83b9ac2d5a248776 | 5c2f482c8e4e42311132628e581d65a524aaa82c | refs/heads/master | 2020-03-11T19:35:48.419119 | 2018-07-08T14:59:16 | 2018-07-08T14:59:16 | 130,212,285 | 1 | 0 | null | 2018-05-03T10:26:39 | 2018-04-19T12:29:09 | Java | UTF-8 | Java | false | false | 551 | java | package com.example.mysql.mappers;
import com.example.mysql.domains.Book;
import com.example.mysql.models.BookBaseDTO;
import com.example.mysql.models.BookDTO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import org.springframework.stereotype.Component;
@Component
@Mapper(componentModel = "spring")
public interface BookMapper {
BookMapper INSTANCE = Mappers.getMapper(BookMapper.class);
BookDTO bookToBookDTO(Book book);
BookBaseDTO bookToBookBaseDTO(Book book);
Book bookDtoToBook(BookBaseDTO bookDTO);
}
| [
"noreply@github.com"
] | noreply@github.com |
1a231de1ed1c1f97e551a5b757163b4e08fa1450 | e2ee76aeaf8049cb7a9b230c8869d3e5ea1056ed | /app/src/test/java/com/example/notesappwithmvvm/ExampleUnitTest.java | 30a7386484d8de4b3ed4a76f90384f5291b50deb | [] | no_license | devr22/NotesApp_MVVM_architecture | d18b4a39ae450d05a96bbf2738fd3d6d2428d179 | 9fffcd984001a9755e76dcccecefc59b3ac12d3d | refs/heads/master | 2020-12-29T13:22:47.895817 | 2020-07-10T05:07:48 | 2020-07-10T05:07:48 | 238,621,174 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 389 | java | package com.example.notesappwithmvvm;
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);
}
} | [
"devr52222@gmail.com"
] | devr52222@gmail.com |
dc3b1ef41fdc98ad1718e90e9523d48db8a332fd | fdcf6b088e125b6093a6cfc1d1ce76973a7ad3ce | /CompleteJavaTutorialTelusko/src/com/assegd/demos/java/releases/java8/LambdaDemo.java | 84f4031212f9273bbdd8e04cc690dac8094774ca | [] | no_license | assetozen/CompleteJavaTutorialTelusko | 8c71c5b609ffe85fcffc4034675d2a0df3e36f70 | a84e866ca0ab5a0dd2cf51187f46a044c2e4e202 | refs/heads/master | 2023-06-13T03:07:06.100323 | 2021-07-09T07:06:51 | 2021-07-09T07:06:51 | 269,629,612 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,522 | java | package com.assegd.demos.java.releases.java8;
//import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput; // commented when changing jdk from 1.8 to 11
import javax.crypto.spec.PSource;
/** ------------- Lambda Expression ------------------------------------
* Example
* when implementing an interface with single method declaration
* - we can use lambda expr. to simply implement the method in a class with out creating an other class
* - this will not create an inner class at compile time
*/
interface A{
void show();
}
class Xyz implements A{
public void show() {
System.out.println("Hello");
}
}
public class LambdaDemo {
public static void main(String[] args) {
System.out.println("Different ways of implementing show() method of an interface A");
System.out.println("1 -- By Simply creating instance of interface A and calling show() mmethod");
A obj = new Xyz();
obj.show();
System.out.println("\n2 -- If the class is creating only to implement interface's method, use anonymous class instead");
A obj2 = new A() {
public void show() {
System.out.println("Using Anonymous class - Hello");
}
};
obj2.show();
System.out.println("\n3 -- simplifying step 2, removing boiler code blocks and using LAMBDA Expr");
A obj3 = () -> {
System.out.println("Using Lambda Expr - Hello");
};
obj3.show();
}
}
| [
"assetozen@gmail.com"
] | assetozen@gmail.com |
4e5a3411b3159e424b5cb83249112538e6b30702 | 1eb5a884ea15cba0c19537092759c6c2b0f6ca87 | /javastudy/src/main/java/JUC/锁/StampedSample.java | 74f7f816f8ef97e3c5b32a18aefafc61ff60ffa6 | [
"MIT"
] | permissive | gaoweigithub/aboutJava | b6d63096c2730334098725555eed89a478e45183 | 48bc69d21a90e9712244ea6bf4b8ed5be6d3ecaf | refs/heads/master | 2021-07-16T00:26:12.698821 | 2019-02-11T06:40:07 | 2019-02-11T06:40:07 | 129,116,318 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,186 | java | package JUC.锁;
import java.util.concurrent.locks.StampedLock;
/**
* 所以,JDK 在后期引入了 StampedLock,在提供类似读写锁的同时,
* 还支持优化读模式。优化读基于假设,大多数情况下读操作并不会和写操作冲突,
* 其逻辑是先试着修改,然后通过 validate 方法确认是否进入了写模式,如果没有进入,
* 就成功避免了开销;如果进入,则尝试获取读锁。请参考我下面的样例代码。
*/
public class StampedSample {
private final StampedLock s1 = new StampedLock();
void mutate() {
long stamp = s1.writeLock();
try {
write();
} finally {
s1.unlockWrite(stamp);
}
}
String access() {
long stamp = s1.tryOptimisticRead();
String data = read();
if (!s1.validate(stamp)) {
stamp = s1.readLock();
try {
data = read();
} finally {
s1.unlockRead(stamp);
}
}
return data;
}
void write() {
System.out.println("write");
}
String read() {
return "read";
}
}
| [
"gw33973@ly.com"
] | gw33973@ly.com |
e2cdbd9877a6741917b8c94ef0a22a2fc5605982 | 79f5bb1444a02c0d639c5a4deb1cf0c69131fee4 | /src/com/sourceit/java/basic/Popazovdk/HT7/MyArrays.java | 189a6a68fb5f1f7cf855dead6735b2a9fb5a4dfc | [] | no_license | saiferdima/sourceIt | 0375b419aa03d5fe0c0ee03ff1a975db64660575 | d56632d157043039fbb461bf3f8612435269b0b4 | refs/heads/master | 2016-09-06T01:52:47.529754 | 2015-06-12T23:02:13 | 2015-06-12T23:02:13 | 33,277,300 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 725 | java | package com.sourceit.java.basic.Popazovdk.HT7;
import com.sourceit.exercise.IntArrays;
public class MyArrays implements IntArrays {
int [] array;
public MyArrays(){
this(0);
}
public MyArrays (int i){
array = new int[i];
}
@Override
public void add(int arg0) {
int newLength = array.length+1;
int[] temp = new int[newLength];
for(int i =0;i<array.length;i++){
temp[i]=array[i];
}
temp[newLength-1]=arg0;
array = new int[newLength];
for(int i =0;i<newLength;i++){
array[i]=temp[i];
}
}
@Override
public int get(int arg0) {
return array[arg0];
}
@Override
public int size() {
return array.length;
}
}
| [
"Saiferdima@gmail.com"
] | Saiferdima@gmail.com |
adc2b1eeab326eb6a4b102024bf1bbd5864ee7b3 | 547d720d6d50b0819921d2003d469f200426d7d2 | /src/examples/Parse_OCR_8_Mitae_Schwarz_2008.java | 6cc89a503d90a0d5ab34483f47f7ec8fed6865e9 | [] | no_license | biosemantics/textProcessing | e7b0e29a8bc185cef04252b39e63ac9c110f4f83 | ad30508886249ac71008bf78e1aff78aea372897 | refs/heads/master | 2020-05-22T13:18:02.524907 | 2014-01-03T07:38:00 | 2014-01-03T07:38:00 | 12,469,019 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 20,029 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package examples;
import common.utils.StringUtil;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import paragraph.bean.Document;
import paragraph.bean.Paragraph;
import xml.taxonomy.Hierarchy;
import xml.taxonomy.HierarchyEntry;
import xml.taxonomy.Rank;
import xml.taxonomy.RankRelation;
import xml.taxonomy.TaxonXMLCommon;
import xml.taxonomy.Taxonomy;
import xml.taxonomy.beans.key.Key;
import xml.taxonomy.beans.treatment.Treatment;
/**
*
* @author iychoi
*/
public class Parse_OCR_8_Mitae_Schwarz_2008 {
private int documentID;
private Document document;
private List<Paragraph> paragraphs;
private String processor_name;
public Parse_OCR_8_Mitae_Schwarz_2008(String processor_name) {
this.processor_name = processor_name;
}
private String getTaxonName(String nameInfo) {
String newTaxon = nameInfo;
int idxBrace = newTaxon.indexOf("[");
if (idxBrace > 0) {
newTaxon = newTaxon.substring(0, idxBrace).trim();
}
/*
int idxDot = nameInfo.indexOf(".");
if(idxDot > 0) {
newTaxon = newTaxon.substring(idxDot + 1).trim();
}
*/
int idxNewSp = newTaxon.indexOf(" NEW SPECIES");
if (idxNewSp > 0) {
newTaxon = newTaxon.substring(0, idxNewSp).trim();
}
int idxNewSubg = newTaxon.indexOf(" NEW SUBGENUS");
if (idxNewSubg > 0) {
newTaxon = newTaxon.substring(0, idxNewSubg).trim();
}
int idxNewCb = newTaxon.indexOf(" NEW COMBINATION");
if (idxNewCb > 0) {
newTaxon = newTaxon.substring(0, idxNewCb).trim();
}
Pattern p1 = Pattern.compile("^(.+)?, \\d+$");
Matcher mt1 = p1.matcher(newTaxon);
if (mt1.find()) {
return mt1.group(1);
}
return newTaxon;
}
private String getPureName(String name) {
String authority = getAuthority(name);
if (authority == null) {
return name;
}
int idx = name.indexOf(authority);
if (idx >= 0) {
return name.substring(0, idx).trim();
}
System.out.println("No purename found - " + name);
return null;
}
private String getAuthority(String name) {
String name2 = name;
if (name2.endsWith(", sp. nov.")) {
int lastIdx = name2.indexOf(", sp. nov.");
if (lastIdx >= 0) {
name2 = name2.substring(0, lastIdx);
}
} else if (name2.endsWith(" n. sp.")) {
System.out.println("n. sp. found");
int lastIdx = name2.indexOf(" n. sp.");
if (lastIdx >= 0) {
name2 = name2.substring(0, lastIdx);
}
} else if (name.endsWith(" n. subsp.")) {
System.out.println("n. subsp. found");
int lastIdx = name2.indexOf(" n. subsp.");
if (lastIdx >= 0) {
name2 = name2.substring(0, lastIdx);
}
} else if (name.endsWith(" var.")) {
System.out.println("var. found");
int lastIdx = name2.indexOf(" var.");
if (lastIdx >= 0) {
name2 = name2.substring(0, lastIdx);
}
}
int startPos = name2.length() - 1;
int commaIdx = name2.indexOf(",");
if (commaIdx >= 0) {
startPos = Math.min(startPos, commaIdx - 1);
}
int etIdx = name2.indexOf(" et ");
if (etIdx >= 0) {
startPos = Math.min(startPos, etIdx - 1);
}
int spacePos = 0;
for (int i = startPos; i >= 0; i--) {
if (name2.charAt(i) == ' ') {
if (i >= 1 && name2.charAt(i - 1) != '.') {
spacePos = i;
break;
}
}
}
String authority = name2.substring(spacePos + 1).trim();
if ((authority.charAt(0) >= 'A' && authority.charAt(0) <= 'Z')
|| authority.charAt(0) == '(') {
return authority;
} else {
System.out.println("No authority found - " + name2);
return null;
}
}
private String removeBrace(String name) {
if (name.startsWith("(") && name.endsWith(")")) {
return name.substring(1, name.length() - 1);
}
return name;
}
private HierarchyEntry getHierarchyEntry(String name, String rank) throws IOException {
List<String> new_name_parts = new ArrayList<String>();
List<String> new_rank_parts = new ArrayList<String>();
List<String> new_auth_parts = new ArrayList<String>();
List<RankRelation> rank_relations = new ArrayList<RankRelation>();
System.out.println(name);
rank_relations.add(new RankRelation("Family", "Subfamily"));
rank_relations.add(new RankRelation("Subfamily", "Genus"));
rank_relations.add(new RankRelation("Genus", "Species"));
rank_relations.add(new RankRelation("Species", "Subspecies"));
rank_relations.add(new RankRelation("Subgenus", "Variety"));
String firstPart = null;
boolean hasSecondPart = false;
if (name.indexOf(" ssp. ") >= 0 || name.indexOf(" var. ") >= 0) {
// split into two
int idx = 0;
int len = 0;
String rnk = null;
if (name.indexOf(" ssp. ") >= 0) {
idx = name.indexOf(" ssp. ");
len = 6;
rnk = "Subspecies";
} else if (name.indexOf(" var. ") >= 0) {
idx = name.indexOf(" var. ");
len = 6;
rnk = "Variety";
}
firstPart = name.substring(0, idx).trim();
String secondPart = name.substring(idx + 6).trim();
String secondAuth = getAuthority(secondPart);
String secondName = getPureName(secondPart);
System.out.println("secondName : " + secondName);
if (secondName.split("\\s").length > 1) {
throw new IOException("second part has more than 2 parts : " + secondName);
}
new_name_parts.add(0, secondName);
new_rank_parts.add(0, rnk);
new_auth_parts.add(0, secondAuth);
hasSecondPart = true;
} else if (name.indexOf(" n. sp.") >= 0 || name.indexOf(" n. subsp.") >= 0 || name.indexOf(" var.") >= 0) {
int idx = 0;
if (name.indexOf(" n. sp.") >= 0) {
idx = name.indexOf(" n. sp.");
} else if (name.indexOf(" n. subsp.") >= 0) {
idx = name.indexOf(" n. subsp.");
} else if (name.indexOf(" var.") >= 0) {
idx = name.indexOf(" var.");
}
firstPart = name.substring(0, idx).trim();
} else {
firstPart = name;
}
if (firstPart.indexOf(" ") < 0) {
// not found
String pure_name = removeBrace(firstPart);
new_name_parts.add(0, pure_name);
new_rank_parts.add(0, rank);
new_auth_parts.add(0, null);
} else {
String firstAuth = getAuthority(firstPart);
String firstName = getPureName(firstPart);
String[] name_parts = firstName.split("\\s");
for (int i = name_parts.length - 1; i >= 0; i--) {
String pure_name = removeBrace(name_parts[i]);
new_name_parts.add(0, pure_name);
if (i == name_parts.length - 1) {
new_auth_parts.add(0, firstAuth);
} else {
new_auth_parts.add(0, null);
}
}
String prevRank = rank;
for (int i = 0; i < name_parts.length; i++) {
int me = name_parts.length - 1 - i;
if (hasSecondPart) {
String newRank = Rank.findParentRank(prevRank, rank_relations);
new_rank_parts.add(0, newRank);
prevRank = newRank;
} else {
if (me == name_parts.length - 1) {
new_rank_parts.add(0, prevRank);
} else {
String newRank = Rank.findParentRank(prevRank, rank_relations);
new_rank_parts.add(0, newRank);
prevRank = newRank;
}
}
}
}
String[] entryNames = new String[new_name_parts.size()];
String[] entryRanks = new String[new_rank_parts.size()];
String[] entryAuths = new String[new_auth_parts.size()];
entryNames = new_name_parts.toArray(entryNames);
entryRanks = new_rank_parts.toArray(entryRanks);
entryAuths = new_auth_parts.toArray(entryAuths);
HierarchyEntry entry = new HierarchyEntry(entryNames, entryRanks, entryAuths);
return entry;
}
private HierarchyEntry genHierarchyEntry(String taxonNameInfo) throws IOException {
System.out.println("taxonNameInfo : " + taxonNameInfo);
String taxonName = getTaxonName(taxonNameInfo);
String rankRemoved = TaxonXMLCommon.removeAllRank(taxonName);
System.out.println("full name : " + rankRemoved);
String rank = TaxonXMLCommon.getFirstRank(taxonName);
if (rank == null) {
rank = "Species";
if (rankRemoved.endsWith(" n. sp.")) {
rank = "Species";
} else if (rankRemoved.endsWith(" n. subsp.")) {
rank = "Subspecies";
} else if (rankRemoved.endsWith(" var.")) {
rank = "Variety";
} else if (rankRemoved.split("\\s").length == 3) {
rank = "Species";
} else if (rankRemoved.split("\\s").length == 2) {
rank = "Subgenus";
} else if (rankRemoved.split("\\s").length == 5) {
rank = "Subspecies";
}
}
HierarchyEntry entry = getHierarchyEntry(rankRemoved, rank);
return entry;
}
public void start(int documentID) throws IOException, Exception {
this.documentID = documentID;
this.document = TaxonXMLCommon.loadDocument(this.documentID);
this.paragraphs = TaxonXMLCommon.loadParagraphs(document);
List<Taxonomy> taxonomies = new ArrayList<Taxonomy>();
List<Key> keys = new ArrayList<Key>();
Hierarchy hierarchy = new Hierarchy();
Taxonomy taxonomy = null;
Key key = null;
String prevTitle = null;
for (Paragraph paragraph : paragraphs) {
switch (paragraph.getType()) {
case PARAGRAPH_TITLE: {
HierarchyEntry hierarchy_entry = getHierarchyEntry("Nomada", "Genus");
hierarchy.addEntry(hierarchy_entry);
break;
}
case PARAGRAPH_TAXONNAME: {
taxonomy = TaxonXMLCommon.createNewTaxonomy();
TaxonXMLCommon.addNewMeta(taxonomy, this.processor_name, document.getFilename());
// set metadata
String rankRemovedName = TaxonXMLCommon.removeAllRank(getTaxonName(paragraph.getContent()));
taxonomy.setTaxonName(rankRemovedName);
HierarchyEntry hierarchy_entry = genHierarchyEntry(paragraph.getContent());
TaxonXMLCommon.addNewIdentification(taxonomy, hierarchy, hierarchy_entry, paragraph.getContent());
// add to list
taxonomies.add(taxonomy);
break;
}
case PARAGRAPH_OTHERINFO: {
TaxonXMLCommon.addNewOtherInfoOnName(taxonomy, paragraph.getContent());
break;
}
case PARAGRAPH_SYNONYM: {
TaxonXMLCommon.addNewSynonym(taxonomy, paragraph.getContent());
break;
}
case PARAGRAPH_DISCUSSION_NON_TITLED_BODY: {
TaxonXMLCommon.addNewDiscussion(taxonomy, paragraph.getContent());
break;
}
case PARAGRAPH_REMARKS:
case PARAGRAPH_DISCUSSION: {
prevTitle = paragraph.getContent();
break;
}
case PARAGRAPH_REMARKS_BODY:
case PARAGRAPH_DISCUSSION_BODY: {
TaxonXMLCommon.addNewDiscussion(taxonomy, prevTitle, paragraph.getContent());
break;
}
case PARAGRAPH_REMARKS_WITH_BODY:
case PARAGRAPH_DISCUSSION_WITH_BODY: {
String[] split = TaxonXMLCommon.splitTitleBody(paragraph.getContent());
TaxonXMLCommon.addNewDiscussion(taxonomy, split[0], split[1]);
break;
}
case PARAGRAPH_DESCRIPTION: {
prevTitle = paragraph.getContent();
break;
}
case PARAGRAPH_DESCRIPTION_BODY: {
TaxonXMLCommon.addNewDescription(taxonomy, prevTitle, paragraph.getContent());
break;
}
case PARAGRAPH_DESCRIPTION_WITH_BODY: {
String[] split = TaxonXMLCommon.splitTitleBody(paragraph.getContent());
TaxonXMLCommon.addNewDescription(taxonomy, split[0], split[1]);
break;
}
case PARAGRAPH_TYPE_WITH_BODY: {
String[] split = TaxonXMLCommon.splitTitleBody(paragraph.getContent());
TaxonXMLCommon.addNewType(taxonomy, split[0], split[1]);
break;
}
case PARAGRAPH_MATERIAL: {
prevTitle = paragraph.getContent();
break;
}
case PARAGRAPH_MATERIAL_BODY: {
TaxonXMLCommon.addNewMaterial(taxonomy, prevTitle, paragraph.getContent());
break;
}
case PARAGRAPH_MATERIAL_WITH_BODY: {
String[] split = TaxonXMLCommon.splitTitleBody(paragraph.getContent());
TaxonXMLCommon.addNewMaterial(taxonomy, split[0], split[1]);
break;
}
case PARAGRAPH_ARTICULATION: {
prevTitle = paragraph.getContent();
break;
}
case PARAGRAPH_ARTICULATION_BODY: {
TaxonXMLCommon.addNewArticulation(taxonomy, prevTitle, paragraph.getContent());
break;
}
case PARAGRAPH_HABITAT:
case PARAGRAPH_ELEVATION:
case PARAGRAPH_ECOLOGY:
case PARAGRAPH_DISTRIBUTION: {
prevTitle = paragraph.getContent();
break;
}
case PARAGRAPH_HABITAT_BODY:
case PARAGRAPH_ELEVATION_BODY:
case PARAGRAPH_ECOLOGY_BODY:
case PARAGRAPH_DISTRIBUTION_BODY: {
TaxonXMLCommon.addNewHabitatElevationDistribution(taxonomy, prevTitle, paragraph.getContent());
break;
}
case PARAGRAPH_HABITAT_WITH_BODY:
case PARAGRAPH_ELEVATION_WITH_BODY:
case PARAGRAPH_ECOLOGY_WITH_BODY:
case PARAGRAPH_DISTRIBUTION_WITH_BODY: {
String[] split = TaxonXMLCommon.splitTitleBody(paragraph.getContent());
TaxonXMLCommon.addNewHabitatElevationDistribution(taxonomy, split[0], split[1]);
break;
}
case PARAGRAPH_KEY: {
if (paragraph.getContent().startsWith("Key to")) {
prevTitle = paragraph.getContent();
} else {
taxonomy.increaseKeyToTable();
if (prevTitle == null) {
key = TaxonXMLCommon.createNewKey(paragraph.getContent());
} else {
key = TaxonXMLCommon.createNewKey(prevTitle + " - " + paragraph.getContent());
}
keys.add(key);
}
break;
}
case PARAGRAPH_KEY_DISCUSSION: {
TaxonXMLCommon.addNewDiscussion(key, paragraph.getContent());
break;
}
case PARAGRAPH_KEY_BODY: {
String[] statement = TaxonXMLCommon.splitKeyStatement(paragraph.getContent());
TaxonXMLCommon.addKeyStatement(key, statement[0], statement[1], statement[2]);
break;
}
case PARAGRAPH_IGNORE:
break;
default: {
System.err.println("Skipped - " + paragraph.getTypeString());
System.err.println(paragraph.getContent());
break;
}
}
}
File taxonOutDir = new File("taxonomy");
taxonOutDir.mkdir();
File keyOutDir = new File("key");
keyOutDir.mkdir();
int keyfileIndex = 1;
int allocKeyToTableNum = 0;
for (Key k : keys) {
File outKeyFile = new File(keyOutDir, StringUtil.getSafeFileName(keyfileIndex + ". " + k.getKeyHeading() + ".xml"));
createXML(k, outKeyFile);
keyfileIndex++;
int sumKeyTo = 0;
for (Taxonomy taxon : taxonomies) {
int keyToNum = taxon.getKeyToTable();
sumKeyTo += keyToNum;
if (allocKeyToTableNum < sumKeyTo) {
TaxonXMLCommon.addKeyFile(taxon, outKeyFile.getName());
allocKeyToTableNum++;
break;
}
}
}
// taxon file
int taxonfileIndex = 1;
for (Taxonomy taxon : taxonomies) {
if (!taxon.getTreatment().getTaxonIdentification().isEmpty()) {
String taxonName = taxon.getTaxonName();
File outTaxonFile = new File(taxonOutDir, StringUtil.getSafeFileName(taxonfileIndex + ". " + taxonName + ".xml"));
createXML(taxon, outTaxonFile);
taxonfileIndex++;
}
}
}
private void createXML(Taxonomy taxonomy, File outFile) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Treatment.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(taxonomy.getTreatment(), outFile);
}
private void createXML(Key key, File outFile) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Key.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(key, outFile);
}
public static void main(String[] args) throws Exception {
Parse_OCR_8_Mitae_Schwarz_2008 obj = new Parse_OCR_8_Mitae_Schwarz_2008("Illyoung Choi");
obj.start(19);
}
}
| [
"iychoi@email.arizona.edu"
] | iychoi@email.arizona.edu |
e2c74c42ff0295af78b2b86c17b16b0c021823c2 | 7d17963e4b8ba8298c63bcd14adeaf2883edc581 | /RechargeApp_152626/src/com/capg/service/RechargeService.java | 9962f658c521a0509c8bc49da6ffb32ca2239b79 | [] | no_license | akhilnarendrula123/Dummy | 1c06561192141257369fbac98c1f983e45624680 | 5b6b8d09122c2bdbf72562d8d6e64f6619363ab7 | refs/heads/master | 2020-03-22T17:09:32.113636 | 2018-08-14T12:37:43 | 2018-08-14T12:37:43 | 140,376,932 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 548 | java | package com.capg.service;
import com.capg.bean.RechargeDetails;
import com.capg.dao.RechargeDAO;
public class RechargeService implements IRechargeService{
RechargeDAO dao=new RechargeDAO();
public boolean addRechargeDetails(RechargeDetails recharge) {
return dao.addRechargeDetails(recharge);
}
public void displayDetails(int tid) {
dao.displayDetails(tid);
}
public boolean updateDetails(int tid) {
return dao.updateDetails(tid);
}
public boolean removeDetails(int tid) {
return dao.removeDetails(tid);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
1a1650d4a03cd14733cc8c37b818a10d496b4f8b | 57d9f39a8485639d026f3040c3baccdd02620550 | /src/main/java/com/castro/libraryapi/model/repository/BookRepository.java | 2dfca7fd84ee026f6f22626f2dcd370b696623a5 | [] | no_license | wevertoncastro/library-api | e8f4fd60cfea5f6b6ee249ff1e14aca0b4b085c3 | 5d1c5d73b3df6f403e75235e8959ee9969061654 | refs/heads/master | 2021-05-17T17:42:38.393581 | 2020-03-28T22:03:29 | 2020-03-28T22:03:29 | 250,901,757 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 273 | java | package com.castro.libraryapi.model.repository;
import com.castro.libraryapi.api.model.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
boolean existsByIsbn(String isbn);
}
| [
"weverton.castro@ilinksolutions.com.br"
] | weverton.castro@ilinksolutions.com.br |
0598cc8dd0daa799b41242c0ecd74cc10bf176f0 | b83910d792f01bc6aa459c2a719ba852a3b84f24 | /LevelCode/Program01/day02/src/basecode/_02Collection概述/Demo021.java | 3fe704d642ff5e5990cd4b45501c8c5d9faf89b9 | [] | no_license | lanrenke/Java | 8ed83cc76bb1076cbcf3172a029a9e8fd95fd9c6 | f5263b7a6ca9d91f1c2780b8cefa28463a9ec744 | refs/heads/master | 2020-05-02T13:04:56.698438 | 2019-04-20T13:40:07 | 2019-04-20T13:40:07 | 177,974,947 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 703 | java | package basecode._02Collection概述;
/**
目标:能够阐述单列集合的继承体系
Collection 接口(父类) 单列集合中的根接口
List 子接口
ArrayList 实现类
LinkedList 实现类
Set 子接口
HashSet 实现类
LinkedHashSet 实现类
小结
Collection集合体系
List 子接口
ArrayList 实现类
LinkedList 实现类
Set 子接口
HashSet 实现类
LinkedHashSet 实现类
*/
public class Demo021 {
}
| [
"noreply@github.com"
] | noreply@github.com |
51ae9e28b1cbeeca7ceb02fc6b4cedcfcf67195b | 3266f48fee9878d6cfe399cdf900234ca987dda4 | /wolips/core/plugins/org.objectstyle.wolips.preferences/java/org/objectstyle/wolips/preferences/PreferencesPlugin.java | 3d6a6d0d8eb9ce668507785b3088d6a699a0b4ff | [] | no_license | wocommunity/wolips | b9d2eeb0db5f5e3e0635da468167013ed3bdf983 | 462107e10646f969856e9385c7d3adae8632a113 | refs/heads/master | 2023-08-03T18:50:52.000212 | 2023-01-08T22:31:42 | 2023-01-08T22:31:42 | 1,585,278 | 13 | 22 | null | 2023-07-25T17:21:48 | 2011-04-08T01:04:53 | Java | UTF-8 | Java | false | false | 3,465 | java | /*
* ====================================================================
*
* The ObjectStyle Group Software License, Version 1.0
*
* Copyright (c) 2002 - 2004 The ObjectStyle Group and individual authors of the
* software. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowlegement: "This product includes software
* developed by the ObjectStyle Group (http://objectstyle.org/)." Alternately,
* this acknowlegement may appear in the software itself, if and wherever such
* third-party acknowlegements normally appear.
*
* 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse or
* promote products derived from this software without prior written permission.
* For written permission, please contact andrus@objectstyle.org.
*
* 5. Products derived from this software may not be called "ObjectStyle" nor
* may "ObjectStyle" appear in their names without prior written permission of
* the ObjectStyle Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* OBJECTSTYLE GROUP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many individuals on
* behalf of the ObjectStyle Group. For more information on the ObjectStyle
* Group, please see <http://objectstyle.org/>.
*
*/
package org.objectstyle.wolips.preferences;
import org.objectstyle.wolips.baseforuiplugins.AbstractBaseUIActivator;
import org.osgi.framework.BundleContext;
/**
* The main plugin class to be used in the desktop.
*
* @author uli
* @author markus
*/
public class PreferencesPlugin extends AbstractBaseUIActivator {
// The plugin.
private static PreferencesPlugin plugin;
/**
* The constructor.
*/
// The constructur is very sensitive. Make sure that your stuff works.
// If this cunstructor fails, the whole plugin will be disabled.
public PreferencesPlugin() {
super();
plugin = this;
}
/**
* @return the shared instance
*/
public static PreferencesPlugin getDefault() {
return plugin;
}
public void start(BundleContext context) throws Exception {
super.start(context);
// set up missing preferences
Preferences.setDefaults();
}
} | [
"uli@930f2ab1-3212-0410-a8ea-d1eb4cc50a93"
] | uli@930f2ab1-3212-0410-a8ea-d1eb4cc50a93 |
b1842826e4b943df6097db2013608292b76a1ab9 | 2a9801932fa75112b85d9ae517c9acc4a8d4204d | /Components/src/main/java/com/service/customer/components/http/request/ProgressRequestBody.java | fc540cc03b07c745bf463f3e72da15607c88a055 | [] | no_license | Tyeeee/LifeServicePlatform | e5ec3d4c1ce140dd10a1caf074515a04ab222c0a | 9d1a9c24aebaeabb04d1bc8edf32ef27f51ec131 | refs/heads/master | 2021-09-11T21:00:29.721110 | 2018-04-12T10:10:36 | 2018-04-12T10:10:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,285 | java | package com.service.customer.components.http.request;
import com.service.customer.components.http.listener.OnUpdateProgressListener;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
public class ProgressRequestBody extends RequestBody {
private long time;
private RequestBody requestBody;
private OnUpdateProgressListener onUpdateProgressListener;
public ProgressRequestBody(RequestBody body, OnUpdateProgressListener listener) {
this.requestBody = body;
this.onUpdateProgressListener = listener;
}
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() {
try {
return requestBody.contentLength();
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
time = System.currentTimeMillis();
BufferedSink newSink = Okio.buffer(new CountingSink(sink));
requestBody.writeTo(newSink);
newSink.flush();
}
private final class CountingSink extends ForwardingSink {
private long writtenBytes;
private long dataLength;
public CountingSink(Sink delegate) {
super(delegate);
}
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
if (dataLength == 0) {
dataLength = contentLength();
}
writtenBytes += byteCount;
if (onUpdateProgressListener != null) {
long totalTime = (System.currentTimeMillis() - time) / 1000;
if (totalTime == 0) {
totalTime += 1;
}
long networkSpeed = writtenBytes / totalTime;
int progress = (int) (writtenBytes * 100 / dataLength);
boolean done = writtenBytes == dataLength;
onUpdateProgressListener.updateProgress(progress, networkSpeed, done);
}
}
}
}
| [
"yuanjintye@163.com"
] | yuanjintye@163.com |
545d8a027d59e25db2cd84eb24a77311fa748b5d | 87a1c80600c50e29ef30a9837d46b4c0cfec71d0 | /MQ_Sample/src/main/java/cn/timlin/rabbitmq/rpc/RPCClient.java | d5050f58b8aa8c8a444e2a76b62da8611338b09c | [] | no_license | TimLin0007/MQ_Samples | 8fb1bb0f4e8febf5631b21940be19cf9b87626e1 | e32a2568c48633075520512695e3c8f14fc3f36c | refs/heads/master | 2020-07-26T15:15:20.540031 | 2016-11-16T09:12:35 | 2016-11-16T09:12:35 | 73,719,995 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,252 | java | package cn.timlin.rabbitmq.rpc;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.AMQP.BasicProperties;
import java.util.UUID;
public class RPCClient {
private Connection connection;
private Channel channel;
private String requestQueueName = "rpc_queue";
private String replyQueueName;
private QueueingConsumer consumer;
public RPCClient() throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
connection = factory.newConnection();
channel = connection.createChannel();
replyQueueName = channel.queueDeclare().getQueue();
consumer = new QueueingConsumer(channel);
channel.basicConsume(replyQueueName, true, consumer);
}
public String call(String message) throws Exception {
String response = null;
String corrId = UUID.randomUUID().toString();
BasicProperties props = new BasicProperties
.Builder()
.correlationId(corrId)
.replyTo(replyQueueName)
.build();
channel.basicPublish("", requestQueueName, props, message.getBytes("UTF-8"));
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
if (delivery.getProperties().getCorrelationId().equals(corrId)) {
response = new String(delivery.getBody(),"UTF-8");
break;
}
}
return response;
}
public void close() throws Exception {
connection.close();
}
public static void main(String[] argv) {
RPCClient fibonacciRpc = null;
String response = null;
try {
fibonacciRpc = new RPCClient();
System.out.println(" [x] Requesting fib(30)");
response = fibonacciRpc.call("30");
System.out.println(" [.] Got '" + response + "'");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (fibonacciRpc!= null) {
try {
fibonacciRpc.close();
}
catch (Exception ignore) {}
}
}
}
}
| [
"TimLin0007@gmail.com"
] | TimLin0007@gmail.com |
2e2bda60409ae60db81e86293fb8ea91c3241893 | 5133569fb5579b61d3920fb154da164842a05659 | /src/main/java/warrior/framework/filter/package-info.java | bcff935fdc8f48caf01ce5810448d16eda63b8dc | [] | no_license | yaobj/warrior | 77bd75d28b3528dcc7b5c5fd9c635b21f8226a5d | d5f1ac7675d9e83c0373400b719ae88d857522ff | refs/heads/master | 2023-03-21T09:42:52.995316 | 2021-03-09T08:35:54 | 2021-03-09T08:35:54 | 290,694,170 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 33 | java | package warrior.framework.filter; | [
"yaobj@wjs.com"
] | yaobj@wjs.com |
4e92d923ce6e0012c39f573c74d73c126e038294 | 8fa58e97da81643f0f16d305126d540f18f36d97 | /src/Controller/Schedule.java | 7ecd3dc9f96370a5bae03724eecb08376d910b65 | [] | no_license | awfast/Seat-Allocating-System | fb436bd9a4cff502b8edb8f42b3d6501c58727d6 | 06c284ca12d6b56ef88cff557b94f7cce795307e | refs/heads/master | 2021-01-18T16:05:18.031935 | 2016-04-28T16:36:41 | 2016-04-28T16:36:41 | 46,301,123 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 24,030 | java | package Controller;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import Model.Building;
import Model.Capacity;
import Model.Room;
/*
* @author Damyan Rusinov
* @This class covers the functionality of the system, dealing with a new schedule
*/
public class Schedule {
//connection
protected Connection conn = null;
//statements to query the database
private Statement stmt = null;
private Statement stmt2 = null;
//reader for the files to be imported
@SuppressWarnings("unused")
private DataReader dataReader = null;
/*the following 12 variables represent what each schedule consists of
* a schedule has a:
* module code
*/
private String moduleCode = null;
//a module title
private String moduleTitle = null;
//an accessible seat inside a room specified
@SuppressWarnings("unused")
private String accessible;
//location, made out of a building room, room number and seat number
private String location;
//day of the exam
private String day;
//date of the exam
private String date;
//every schedule has a session, representing whether the exam is in the morning or afternoon(i.e. am, pm)
private String session;
//a student ID
private int studentID;
//a session ID
private int sessionID;
//a building number
private int buildingNumber;
//a room number
private int roomNumber;
//this variable is used when the calculation of the most optimal location for a certain schedule is to be found
private int closestAccessibleSeats;
//alphabet list used for seat allocation
private ArrayList<String> alphabet = new ArrayList<String>();
//counter used for allocating a seat with a different letter per a certain number of students
private int seatCounter10 = 0;
private String tempModule = null;
private boolean goalReached = false;
//list of all modules
private List<String> modules = new ArrayList<String>();
//a linked hashmap keeping the building number and room number
private Map<Building, Room> locations_buildingRoom = new LinkedHashMap<Building, Room>();
//a linked hashmap keeping the room number and its capacity
private Map<Room, Integer> locations_roomCapacity = new LinkedHashMap<Room, Integer>();
// all modules, and students registered for them.s
private HashMap<String, ArrayList<Integer>> moduleVstudents = new HashMap<String, ArrayList<Integer>>();
// all modules and their sessions assigned
private HashMap<String, Integer> moduleVsession = new HashMap<String, Integer>();
// all available sessions
private List<Integer> sessions = new ArrayList<Integer>();
// the already assigned students
private ArrayList<Integer> assignedStudents;
/* the already assigned students are assigned based on the modules they are registered on
* once a module is assigned to all students, it is marked as an 'assignedModule'
*/
private List<String> assignedModules = new ArrayList<String>();
//modules to be assigned
private List<String> modulesToCheck = new ArrayList<String>();
//a hashmap storing a module code against all the students assigned to it
private Map<String, ArrayList<Schedule>> schedules = new HashMap<String, ArrayList<Schedule>>();
// a list containing the capacity of all buildings
private List<Capacity> list_Capacity_Buildings = new ArrayList<Capacity>();
// once a building is occupied, it is marked as unavailable
private Map<String, Building> unavailableBuildings = new HashMap<String, Building>();
// a schedule, containing all of the aforementioned 7 variables is kept in the following list
private ArrayList<Schedule> finalizedSchedules = new ArrayList<Schedule>();
public Schedule(int studentID, String moduleCode, int sessionID, String date, String accessible, int buildingNumber,
int roomNumber) {
this.studentID = studentID;
this.moduleCode = moduleCode;
this.sessionID = sessionID;
this.accessible = accessible;
this.buildingNumber = buildingNumber;
this.roomNumber = roomNumber;
this.date = date;
}
public Schedule(int studentID, String moduleCode, String moduleTitle, String day, String date, String session,
String location) {
this.studentID = studentID;
this.moduleCode = moduleCode;
this.moduleTitle = moduleTitle;
this.day = day;
this.date = date;
this.session = session;
this.location = location;
}
public int getStudentID() {
return studentID;
}
public String getModuleCode() {
return moduleCode;
}
public String getModuleTitle() {
return moduleTitle;
}
public int getSessionID() {
return sessionID;
}
public String getSessionString() {
return session;
}
public int getBuildingNumber() {
return buildingNumber;
}
public int getRoomNumber() {
return roomNumber;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public void setSessionID(int sessionID) {
this.sessionID = sessionID;
}
public boolean getGoalReached() {
return goalReached;
}
public void setGoalReached(boolean goalReached) {
this.goalReached = goalReached;
}
public void setBuildingNumber(int buildingNumber) {
this.buildingNumber = buildingNumber;
}
public void setRoomNumber(int roomNumber) {
this.roomNumber = roomNumber;
}
public String getDay() {
return this.day;
}
public String getLocation() {
return this.location;
}
//method, being called from the main method
//triggers the whole system's functionality
public void generateInformation(Connection conn, DataReader dataReader) throws SQLException {
this.dataReader = dataReader;
this.conn = conn;
getAllSessions();
}
// get all schedules
private void getSchedules() throws SQLException {
for (String module : moduleVsession.keySet()) {
String query = "SELECT * FROM RegisteredStudents WHERE ModuleCode='" + module + "' ";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ArrayList<Schedule> arr = new ArrayList<Schedule>();
while (rs.next()) {
int studentID = rs.getInt(1);
String accessible = rs.getString("AccessibleSeat");
Schedule schedule = new Schedule(studentID, module, moduleVsession.get(module),
getDatePerSessionID(moduleVsession.get(module)), accessible, 0, 0);
arr.add(schedule);
}
this.schedules.put(module, arr);
}
}
// get the list of all the finalized schedules
public ArrayList<Schedule> getFinalSchedules(Connection conn) {
this.conn = conn;
return finalizedSchedules;
}
// insert into our 'Schedule' table the finalized schedules
// and add them to our list of finalized schedules
public Map<String, ArrayList<Schedule>> insertSchedulesIntoTable(Map<String, ArrayList<Schedule>> s)
throws SQLException {
for (String moduleCode : s.keySet()) {
for (int i = 0; i < s.get(moduleCode).size(); i++) {
//do the insertion
insertIntoTableSchedule(schedules.get(moduleCode).get(i).getStudentID(), moduleCode,
schedules.get(moduleCode).get(i).getSessionID(), schedules.get(moduleCode).get(i).getDate(),
schedules.get(moduleCode).get(i).getBuildingNumber(),
schedules.get(moduleCode).get(i).getRoomNumber());
String location = "Building: " + schedules.get(moduleCode).get(i).getBuildingNumber() + ", Room: "
+ schedules.get(moduleCode).get(i).getRoomNumber() + ", Seat: " + checkSeat(moduleCode);
Schedule finalSchedule = new Schedule(schedules.get(moduleCode).get(i).getStudentID(), moduleCode,
getModuleTitle(moduleCode, conn), getDayOfTheWeek(schedules.get(moduleCode).get(i).getDate()),
schedules.get(moduleCode).get(i).getDate(),
schedules.get(moduleCode).get(i).getSessionID() + " ("
+ schedules.get(moduleCode).get(i).getSessionName(sessionID, conn).toUpperCase() + ")",
location);
//add them to the list of finalized schedules
finalizedSchedules.add(finalSchedule);
}
}
return s;
}
//if a student has no location, assign them with one
public Map<String, ArrayList<Schedule>> assign(Map<String, ArrayList<Schedule>> schedules) throws SQLException {
for (String moduleCode : schedules.keySet()) {
for (int i = 0; i < schedules.get(moduleCode).size(); i++) {
if (schedules.get(moduleCode).get(i).getBuildingNumber() == 0
|| schedules.get(moduleCode).get(i).getRoomNumber() == 0) {
//find the building and room
findBuildingAndRoom(schedules.get(moduleCode).get(i));
for (int j = 0; j < schedules.get(moduleCode).size(); j++) {
if (schedules.get(moduleCode).get(j).getModuleCode().equals(moduleCode)) {
//and set it
schedules.get(moduleCode).get(j)
.setBuildingNumber(schedules.get(moduleCode).get(i).getBuildingNumber());
schedules.get(moduleCode).get(j)
.setRoomNumber(schedules.get(moduleCode).get(i).getRoomNumber());
}
}
break;
}
}
}
return schedules;
}
//a goal state must cover all of the constraints specified below
public boolean goal(List<Schedule> schedules) throws SQLException {
boolean isWrong = false;
for (int i = 0; i < schedules.size(); i++) {
if (schedules.get(i).getBuildingNumber() == 0 || schedules.get(i).getRoomNumber() == 0
|| schedules.get(i).getModuleCode() == null || schedules.get(i).getStudentID() == 0
|| schedules.get(i).getSessionID() == 0 || schedules.get(i).getDay() == null
|| schedules.get(i).getDate() == null) {
isWrong = true;
} else {
isWrong = false;
}
}
if (isWrong == true) {
return false;
} else {
return true;
}
}
// find an available building and room
private void findBuildingAndRoom(Schedule s) throws SQLException {
int room = 0;
int building = 0;
locations_buildingRoom.clear();
locations_roomCapacity.clear();
list_Capacity_Buildings.clear();
getLocations();
while (!list_Capacity_Buildings.isEmpty()) {
//get the capacity of the most optimal location, based on the number of students registered on a module code
int capacity = closest(getStudentsForThisModuleCode(s.getModuleCode()));
//find the room based on the capacity provided
room = findRoomNumber(capacity, closestAccessibleSeats);
//and its corresponding building
building = findBuildingNumber(room);
//if the building and room are available for the session given
if (checkIfAvailable(s.getModuleCode(), building, room, s.getSessionID())) {
//set as a location
s.setBuildingNumber(building);
s.setRoomNumber(room);
return;
} else {
for (int x = 0; x < list_Capacity_Buildings.size();) {
for (Room key : locations_roomCapacity.keySet()) {
//otherwise, remove the room from the list of available rooms.
if (key.getRoomNumber() == room) {
locations_roomCapacity.remove(key);
list_Capacity_Buildings.remove(list_Capacity_Buildings.get(x));
break;
}
}
break;
}
}
}
}
//check if a building is available for a given sesion
private boolean checkIfAvailable(String moduleCode, int buildingNumber, int room, int sessionID) {
if (unavailableBuildings.isEmpty()) {
Building b = new Building(buildingNumber, room, sessionID, moduleCode);
unavailableBuildings.put(moduleCode, b);
return true;
} else {
if (unavailableBuildings.containsKey(moduleCode)) {
return true;
} else {
for (String module : unavailableBuildings.keySet()) {
if (unavailableBuildings.get(module).getBuildingNumber() == buildingNumber
&& unavailableBuildings.get(module).getRoomNumber() == room
&& getSessionID() == sessionID) {
return false;
}
}
}
}
return true;
}
// allocate students with a session
private void findSessions() throws SQLException {
//for all the modules having students registered on
for (int i = 0; i < modulesToCheck.size(); i++) {
//get all the students for the first module
ArrayList<Integer> module = moduleVstudents.get(modulesToCheck.get(i));
//loop through every session
modulesToCheckLoop: for (int j = 0; j < sessions.size(); j++) {
//base case if no modules have been assigned a session already
sessionLoop: if (assignedModules.isEmpty()) {
assignedModules.add(modulesToCheck.get(i));
moduleVsession.put(modulesToCheck.get(i), sessions.get(j));
break modulesToCheckLoop;
} else {
//inductive case for all the assigned modules
for (int x = 0; x < assignedModules.size(); x++) {
//get all students already assigned a session and store them in the following list
ArrayList<Integer> assignedModule = moduleVstudents.get(assignedModules.get(x));
//for all the students for the first module
for (int y = 0; y < module.size(); y++) {
//get their session
int currentSession = moduleVsession.get(assignedModules.get(x));
//if it is the same as the session being passed, that breaks a constraint
//so we get the next session(no student must be allocated two exams for the same session)
if (assignedModule.contains(module.get(y)) && getDatePerSessionID(currentSession)
.equals(getDatePerSessionID(sessions.get(j)))) {
break sessionLoop;
}
}
//get the next module if all the assigned students have been processed.
if (x == assignedModules.size() - 1) {
assignedModules.add(modulesToCheck.get(i));
moduleVsession.put(modulesToCheck.get(i), sessions.get(j));
break modulesToCheckLoop;
} else {
continue;
}
}
}
}
}
//shuffle in the attempt to find a better allocation(could be extended in future)
if (assignedModules.size() != modulesToCheck.size()) {
Collections.shuffle(modulesToCheck);
}
}
//insert data into table schedule
private void insertIntoTableSchedule(int studentID, String moduleCode, int sessionID, String date,
int buildingNumber, int roomNumber) throws SQLException {
String query = "INSERT INTO Schedule(StudentID, ModuleCode, SessionID, Date, BuildingNumber, RoomNumber) VALUES ('"
+ studentID + "', + '" + moduleCode + "', + '" + sessionID + "', + '" + date + "', + '" + buildingNumber
+ "', + '" + roomNumber + "')";
stmt = conn.createStatement();
stmt.executeUpdate(query);
}
//find the most optimal location, given a number of students registered on a moduleCode
public int closest(int of) throws SQLException {
int min = Integer.MAX_VALUE;
int closesetCapacity = 0;
int secondClosestCapacity = of;
closestAccessibleSeats = 0;
//for all the buildings and their capacities
for (int i = 0; i < list_Capacity_Buildings.size(); i++) {
//get the difference between the capacity of the building and the number 'of' students registered for a given module code
final int diff = Math.abs(list_Capacity_Buildings.get(i).getCapacity() - of);
//if the location has more seats than number of students
if (diff < min) {
//get its capacity
secondClosestCapacity = list_Capacity_Buildings.get(i).getCapacity();
// if it is exactly equal to the number of students and there are enough accessible seats available
if (secondClosestCapacity == of && list_Capacity_Buildings.get(i)
.getNumberOfAccessibleSeats() >= findNumberOfAccessibleSeatsNeeded(moduleCode)) {
closesetCapacity = secondClosestCapacity;
closestAccessibleSeats = list_Capacity_Buildings.get(i).getNumberOfAccessibleSeats();
//return this location as most optimal
return closesetCapacity;
//otherwise, if the location has more seats than the number of students
} else if (secondClosestCapacity > of & list_Capacity_Buildings.get(i)
.getNumberOfAccessibleSeats() >= findNumberOfAccessibleSeatsNeeded(moduleCode)) {
if (closesetCapacity == 0) {
closesetCapacity = secondClosestCapacity;
min = secondClosestCapacity;
closestAccessibleSeats = list_Capacity_Buildings.get(i).getNumberOfAccessibleSeats();
} else {
if (secondClosestCapacity < closesetCapacity) {
closesetCapacity = secondClosestCapacity;
closestAccessibleSeats = list_Capacity_Buildings.get(i).getNumberOfAccessibleSeats();
}
}
}
}
}
return closesetCapacity;
}
// fill the list with the letters of the English alphabet
private void fillAlphabet() {
alphabet.add("a");
alphabet.add("b");
alphabet.add("c");
alphabet.add("d");
alphabet.add("e");
alphabet.add("f");
alphabet.add("g");
alphabet.add("h");
alphabet.add("i");
alphabet.add("j");
alphabet.add("k");
alphabet.add("l");
alphabet.add("m");
alphabet.add("n");
alphabet.add("o");
alphabet.add("p");
alphabet.add("q");
alphabet.add("r");
alphabet.add("s");
alphabet.add("t");
alphabet.add("u");
alphabet.add("v");
alphabet.add("w");
alphabet.add("x");
alphabet.add("y");
alphabet.add("z");
}
// for every 35th student, change the seat letter to the next one of the alphabet
private String checkSeat(String moduleCode) {
fillAlphabet();
if (tempModule == null) {
tempModule = moduleCode;
String str = alphabet.get(0).toUpperCase();
return str + seatCounter10;
} else if (!tempModule.equals(moduleCode)) {
alphabet.clear();
fillAlphabet();
tempModule = moduleCode;
seatCounter10 = 0;
String str = alphabet.get(0).toUpperCase();
seatCounter10++;
return str + 0;
} else {
seatCounter10++;
if (seatCounter10 == 35) {
alphabet.remove(0);
String str = alphabet.get(0).toUpperCase();
seatCounter10 = 0;
return str + seatCounter10;
} else {
String str = alphabet.get(0).toUpperCase();
return str + seatCounter10;
}
}
}
//get the day of the week given the date
public String getDayOfTheWeek(String date) {
String x = date.substring(0, 2);
String y = date.substring(3, 5);
String z = date.substring(6, 10);
int day = Integer.parseInt(x);
int month = Integer.parseInt(y);
int year = Integer.parseInt(z);
LocalDate a = LocalDate.of(year, month, day);
return a.getDayOfWeek().name();
}
//query the database for the date, according to the session provided
public String getDatePerSessionID(int sessionID) throws SQLException {
String query = "SELECT * FROM Session WHERE ID=" + sessionID;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
String date = null;
while (rs.next()) {
date = rs.getString("date");
return date;
}
return date;
}
//get the id of the session
public String getSessionName(int sessionID, Connection conn) throws SQLException {
String query = "SELECT * FROM Session WHERE ID=" + sessionID;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
String session = null;
while (rs.next()) {
session = rs.getString("MorningAfternoon");
return session;
}
return date;
}
//get the title of the module provided
public String getModuleTitle(String moduleCode, Connection conn) throws SQLException {
String query2 = "SELECT * FROM RegisteredStudents WHERE ModuleCode ='" + moduleCode + "'";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query2);
while (rs.next()) {
String title = rs.getString("ModuleTitle");
return title;
}
return null;
}
//given a date, get its session id
public int getSessionIDPerDate(String date) throws SQLException {
String query = "SELECT * FROM Session WHERE date='" + date + "'";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int sessionID = rs.getInt(1);
return sessionID;
}
return 0;
}
// find all the students per the module code passed
private int getStudentsForThisModuleCode(String moduleCode) throws SQLException {
String query = "SELECT * FROM RegisteredStudents WHERE ModuleCode='" + moduleCode + "'";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
int count = 0;
while (rs.next()) {
count++;
}
return count;
}
// find the number of the room, provided the capacity and the number of accessible seats it has
public int findRoomNumber(int capacity, int accessibleSeats) throws SQLException {
String query = "SELECT * FROM Location WHERE SeatNumber='" + capacity + "' AND AccessibleSeatsNumber='"
+ accessibleSeats + "'";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int room = rs.getInt(2);
return room;
}
return 0;
}
// find the total number of accessible seats needed
public int findNumberOfAccessibleSeatsNeeded(String moduleCode) throws SQLException {
String query2 = "SELECT * FROM RegisteredStudents WHERE ModuleCode='" + moduleCode + "'";
stmt2 = conn.createStatement();
ResultSet rs2 = stmt2.executeQuery(query2);
int seatsNeeded = 0;
while (rs2.next()) {
String accessibleFlag = rs2.getString("AccessibleSeat");
if (accessibleFlag.equals("YES")) {
seatsNeeded++;
}
}
return seatsNeeded;
}
// find the total number of accessible seats available
public int findNumberOfAccessibleSeatsAvailable(int buildingNumber, int roomNumber) throws SQLException {
String query2 = "SELECT * FROM Location WHERE BuildingNumber='" + buildingNumber + "' AND RoomNumber='"
+ roomNumber + "'";
stmt2 = conn.createStatement();
ResultSet rs2 = stmt2.executeQuery(query2);
int availableSeats = 0;
while (rs2.next()) {
availableSeats = rs2.getInt(4);
}
return availableSeats;
}
// find the building number, given the room
public int findBuildingNumber(int roomNumber) throws SQLException {
String query = "SELECT * FROM Location WHERE RoomNumber='" + roomNumber + "'";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int building = rs.getInt(1);
return building;
}
return 0;
}
// get all the sessions
private void getAllSessions() throws SQLException {
String query = "SELECT * FROM Session";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int sessionID = rs.getInt(1);
sessions.add(sessionID);
}
// then populate the modules with students
populateModules();
//after they are populated and the allocation has taken place
getSchedules();
//insert the finalized schedules into the given table
insertSchedulesIntoTable(assign(schedules));
}
private void populateModules() throws SQLException {
String query = "SELECT * FROM Exam";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String moduleCode = rs.getString("ModuleCode");
modules.add(moduleCode);
}
getAllStudentsPerModules();
}
// get all students registered to all modules
private void getAllStudentsPerModules() throws SQLException {
for (int i = 0; i < modules.size(); i++) {
String query2 = "SELECT * FROM RegisteredStudents WHERE ModuleCode ='" + modules.get(i) + "'";
stmt2 = conn.createStatement();
ResultSet rs2 = stmt2.executeQuery(query2);
assignedStudents = new ArrayList<Integer>();
while (rs2.next()) {
int studentID = rs2.getInt(1);
assignedStudents.add(studentID);
}
modulesToCheck.add(modules.get(i));
moduleVstudents.put(modules.get(i), assignedStudents);
}
findSessions();
}
// populate the lists with locations
private void getLocations() throws SQLException {
String query2 = "SELECT * FROM Location";
stmt2 = conn.createStatement();
ResultSet rs2 = stmt2.executeQuery(query2);
while (rs2.next()) {
int building = rs2.getInt(1);
int room = rs2.getInt(2);
int capacity = rs2.getInt(3);
int accSeats = rs2.getInt(4);
Building b = new Building(building);
Room r = new Room(room);
Capacity c = new Capacity(capacity, accSeats);
locations_buildingRoom.put(b, r);
locations_roomCapacity.put(r, capacity);
list_Capacity_Buildings.add(c);
}
}
} | [
"damqnrusinov@gmail.com"
] | damqnrusinov@gmail.com |
31b2b3df04d394c1c27a8e33519279f9be41e8bf | df8a7ef35ff28506053e4729b029c8d7a80587cd | /src/main/java/com/joymain/ng/webapp/controller/FidFundbookJournalController.java | da9f3e5e962e8230a27398c56d234204afaf39a6 | [] | no_license | lshowbiz/agnt_qt | 101a5b3cabd0e1ff9135155ac87a602997a9eff5 | 789c2439308adaa5371d5bbb8a0f71a295395006 | refs/heads/master | 2022-12-11T10:13:18.791876 | 2019-10-02T01:01:57 | 2019-10-02T01:01:57 | 212,161,344 | 0 | 1 | null | 2022-12-05T23:28:41 | 2019-10-01T17:46:56 | Java | UTF-8 | Java | false | false | 3,966 | java | package com.joymain.ng.webapp.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.joymain.ng.dao.SearchException;
import com.joymain.ng.service.FiFundbookBalanceManager;
import com.joymain.ng.service.FiFundbookJournalManager;
import com.joymain.ng.util.GroupPage;
import com.joymain.ng.util.StringUtil;
import com.joymain.ng.model.FiFundbookBalance;
import com.joymain.ng.model.FiFundbookJournal;
import com.joymain.ng.model.JsysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* 定向基金查询控制器
* @author Administrator
*
*/
@Controller
@RequestMapping("/fidFundbookJournals*")
public class FidFundbookJournalController {
private FiFundbookJournalManager fiFundbookJournalManager;
private FiFundbookBalanceManager fiFundbookBalanceManager;
@Autowired
public void setFiFundbookBalanceManager(FiFundbookBalanceManager fiFundbookBalanceManager) {
this.fiFundbookBalanceManager = fiFundbookBalanceManager;
}
@Autowired
public void setFiFundbookJournalManager(FiFundbookJournalManager fiFundbookJournalManager) {
this.fiFundbookJournalManager = fiFundbookJournalManager;
}
@RequestMapping(method = RequestMethod.GET)
public Model handleRequest(@RequestParam(value="dealStartTime", required=false) String dealStartTime,@RequestParam(value="dealEndTime", required=false) String dealEndTime,
HttpServletRequest request)
throws Exception {
Model model = new ExtendedModelMap();
try {
//当前用户
JsysUser jsysUser = (JsysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//基金类型:1,分红基金;2,定向基金
String bankbookType ="2";
//List fiFundbookJournalList=fiFundbookJournalManager.search(query, FiFundbookJournal.class);
if("null".equals(dealStartTime)){
dealStartTime = "";
}
if("null".equals(dealEndTime)){
dealEndTime = "";
}
//----------------------Modify By WuCF 添加分页展示功能
//分页单位:固定写法
Integer pageSize = StringUtil.dealPageSize(request);
//创建分页数据对象,传递URL和分页单位:一级目录(如果没有则传空字符串)、 二级目录、分页单位
GroupPage page = new GroupPage("","fidFundbookJournals?dealStartTime="+dealStartTime+"&dealEndTime="+dealEndTime+"&pageSize="+pageSize,pageSize,request);
// List<FiFundbookJournal> fiFundbookJournalList=fiFundbookJournalManager.getFiFundbookJournalListByUser(jsysUser.getUserCode(), dealStartTime, dealEndTime);
List<FiFundbookJournal> fiFundbookJournalList=fiFundbookJournalManager.getFiFundbookJournalListByUserPage(page,jsysUser.getUserCode(), bankbookType, dealStartTime, dealEndTime);
request.setAttribute("page", page);//将分页信息加入到request作用域中
model.addAttribute("fiFundbookJournalList",fiFundbookJournalList);
//查询存折余额对象
FiFundbookBalance fiFundbookBalance = fiFundbookBalanceManager.getFiFundbookBalance(jsysUser.getUserCode(), bankbookType);
model.addAttribute("fiFundbookBalance",fiFundbookBalance);
} catch (SearchException se) {
model.addAttribute("searchError", se.getMessage());
//model.addAttribute(fiFundbookJournalManager.getAll());
}
return model;
}
}
| [
"727736571@qq.com"
] | 727736571@qq.com |
8a60acdafab00baa23945f7b8d84f08f01f1586e | 8df0553905ff0503e705c29e37a7fe588e7e332d | /hlj_android_merchant/src/main/java/com/hunliji/marrybiz/view/ChoosePhotoPageActivity.java | 51af8df7be316f4e4554a318ae217bcb0dc1821a | [] | no_license | Catfeeds/myWorkspace | 9cd0af10597af9d28f8d8189ca0245894d270feb | 3c0932e626e72301613334fd19c5432494f198d2 | refs/heads/master | 2020-04-11T12:19:27.141598 | 2018-04-04T08:14:31 | 2018-04-04T08:14:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,686 | java | package com.hunliji.marrybiz.view;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.hunliji.marrybiz.R;
import com.hunliji.marrybiz.model.Photo;
import com.hunliji.marrybiz.task.AsyncBitmapDrawable;
import com.hunliji.marrybiz.task.ImageLoadTask;
import com.hunliji.marrybiz.task.OnHttpRequestListener;
import com.hunliji.marrybiz.util.JSONUtil;
import com.hunliji.marrybiz.util.ScaleMode;
import com.hunliji.marrybiz.widget.CheckableLinearLayout2;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import uk.co.senab.photoview.PhotoView;
/**
* Created by Suncloud on 2016/3/8.
*/
public class ChoosePhotoPageActivity extends Activity {
@BindView(R.id.pager)
ViewPager mViewPager;
@BindView(R.id.selected_view)
CheckableLinearLayout2 selectedView;
@BindView(R.id.choose_ok)
Button chooseOk;
private ArrayList<Photo> list;
private ArrayList<String> selectedPaths;
private Point point;
private int width;
private int limit;
private Toast toast;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
point = JSONUtil.getDeviceSize(this);
width = point.x;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_photo_page);
ButterKnife.bind(this);
limit = getIntent().getIntExtra("limit", 0);
list = (ArrayList<Photo>) getIntent().getSerializableExtra("images");
selectedPaths = getIntent().getStringArrayListExtra("selectedPaths");
if (selectedPaths == null) {
selectedPaths = new ArrayList<>();
}
if (selectedPaths.size() < 1) {
chooseOk.setEnabled(false);
chooseOk.setText(R.string.label_choose_ok);
} else {
chooseOk.setEnabled(true);
chooseOk.setText(getString(R.string.label_choose_ok2, selectedPaths.size()));
}
int position = getIntent().getIntExtra("position", 0);
if (list != null && !list.isEmpty() && JSONUtil.isEmpty(list.get(0)
.getImagePath())) {
list.remove(0);
position--;
}
mViewPager.setAdapter(new SamplePagerAdapter(this));
mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
Photo image = list.get(position);
selectedView.setChecked(selectedPaths.contains(image.getImagePath()));
}
});
if (list != null && !list.isEmpty()) {
selectedView.setChecked(selectedPaths.contains(list.get(0)
.getImagePath()));
}
mViewPager.setCurrentItem(position);
selectedView.setOnCheckedChangeListener(new CheckableLinearLayout2.OnCheckedChangeListener() {
@Override
public void onCheckedChange(View view, boolean checked) {
Photo image = list.get(mViewPager.getCurrentItem());
if (!checked) {
selectedPaths.remove(image.getImagePath());
} else if (!selectedPaths.contains(image.getImagePath())) {
if (limit > 0 && selectedPaths.size() >= limit) {
if (toast == null) {
toast = Toast.makeText(ChoosePhotoPageActivity.this,
R.string.hint_choose_photo_limit_out,
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
}
toast.show();
selectedView.setChecked(false);
return;
}
selectedPaths.add(image.getImagePath());
}
Intent intent = getIntent();
intent.putExtra("selectedPaths", selectedPaths);
setResult(RESULT_OK, intent);
if (selectedPaths.size() < 1) {
chooseOk.setEnabled(false);
chooseOk.setText(R.string.label_choose_ok);
} else {
chooseOk.setEnabled(true);
chooseOk.setText(getString(R.string.label_choose_ok2, selectedPaths.size()));
}
}
});
}
public void onBackPressed(View view) {
onBackPressed();
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(0, R.anim.activity_anim_out);
}
public void onChooseOk(View view) {
Intent intent = getIntent();
intent.putExtra("done", true);
setResult(RESULT_OK, intent);
onBackPressed();
}
public class SamplePagerAdapter extends PagerAdapter {
private Context mContext;
public SamplePagerAdapter(Context context) {
mContext = context;
}
@Override
public int getCount() {
return list == null ? 0 : list.size();
}
@Override
public View instantiateItem(ViewGroup container, int position) {
final View view = LayoutInflater.from(mContext)
.inflate(R.layout.thread_photos_view, null, false);
view.findViewById(R.id.progressBar)
.setVisibility(View.VISIBLE);
Photo image = list.get(position);
final PhotoView photoView = (PhotoView) view.findViewById(R.id.image);
ImageLoadTask task = new ImageLoadTask(photoView, new OnHttpRequestListener() {
@Override
public void onRequestCompleted(Object obj) {
view.findViewById(R.id.progressBar)
.setVisibility(View.GONE);
Bitmap bitmap = (Bitmap) obj;
float rate = (float) point.x / bitmap.getWidth();
int w = point.x;
int h = Math.round(bitmap.getHeight() * rate);
if (h > point.y || (h * point.x > w * point.y)) {
photoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
photoView.setScaleType(ImageView.ScaleType.FIT_CENTER);
}
}
@Override
public void onRequestFailed(Object obj) {
}
});
photoView.setTag(image.getImagePath());
AsyncBitmapDrawable asyncDrawable = new AsyncBitmapDrawable(mContext.getResources(),
R.mipmap.icon_empty_image,
task);
task.loadImage(image.getImagePath(), width, ScaleMode.WIDTH, asyncDrawable);
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
| [
"hdwhhc@sina.cn"
] | hdwhhc@sina.cn |
84be6e29d8e7cdb9650b3e796a64e4db333677c9 | 60b638d37ff6bd8a5a0ef452436423c7c57ee7b0 | /src/Exercicio_Extra_03.java | 4b10417a80aed021906aa957644d5742c6c4a161 | [] | no_license | thiagokalu/Exercicios_bonus_Fiap_modulo01 | 38704fb643e3baac4dbd908817ac193d9627afa2 | dcbf5ad9138c14238f6ee803a0fa3da480972e09 | refs/heads/master | 2023-06-09T23:46:20.650830 | 2021-06-19T12:05:37 | 2021-06-19T12:05:37 | 376,859,917 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,250 | java | import java.util.Scanner;
public class Exercicio_Extra_03 {
public static void main(String[] args) {
/*Criar um programa que calcule a média de salários de uma empresa,
pedindo ao usuário a grade de funcionários e os salários, e devolvendo a média salarial.*/
Scanner leitor = new Scanner(System.in);
double salario, mediaSalarial, totalSalarios=0;
int numeroDeFuncionarios;
System.out.println("Olá, este programa irá receber um número informado pelo usuário de funcionários e os salários. A partir do numero de salários e o número de funcionários o programa irá informar a média salarial.");
System.out.println("Por favor, informe quantos salários serão cadastrados");
numeroDeFuncionarios = leitor.nextInt();
for (int i = 0;
i < numeroDeFuncionarios;
i++){
System.out.println("Por favor, informe o salário");
salario = leitor.nextDouble();
totalSalarios = totalSalarios + salario;
}
mediaSalarial = totalSalarios / numeroDeFuncionarios ;
System.out.println("A média salarial dos " + numeroDeFuncionarios + " é de R$ " + mediaSalarial);
leitor.close();
}
}
| [
"thiagokalu@gmail.com"
] | thiagokalu@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.