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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c3ab17fdd8ab4a2e490fd7f42c0016a4bbacf3df
|
8eea06842621061bbc47e53c57fce0a54340f542
|
/renren-fast/src/main/java/io/renren/modules/job/utils/ScheduleUtils.java
|
b37ff1da7b2ed494b39b850759edb00e0fcca3ee
|
[
"Apache-2.0"
] |
permissive
|
JinTaoZh/cloudmall
|
42c70ff0fcc3455ba657fc85c6c2c623aaa6ae06
|
cacd2e4cad816f8d223b3dbad5d22bcd4a331a96
|
refs/heads/master
| 2023-06-14T05:47:22.157854
| 2021-04-19T03:41:24
| 2021-04-19T03:41:24
| 353,542,868
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,113
|
java
|
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.job.utils;
import io.renren.common.exception.BusinessException;
import io.renren.common.utils.Constant;
import io.renren.modules.job.entity.ScheduleJobEntity;
import org.quartz.*;
/**
* 定时任务工具类
*
* @author Mark sunlightcs@gmail.com
*/
public class ScheduleUtils {
private final static String JOB_NAME = "TASK_";
/**
* 获取触发器key
*/
public static TriggerKey getTriggerKey(Long jobId) {
return TriggerKey.triggerKey(JOB_NAME + jobId);
}
/**
* 获取jobKey
*/
public static JobKey getJobKey(Long jobId) {
return JobKey.jobKey(JOB_NAME + jobId);
}
/**
* 获取表达式触发器
*/
public static CronTrigger getCronTrigger(Scheduler scheduler, Long jobId) {
try {
return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
} catch (SchedulerException e) {
throw new BusinessException("获取定时任务CronTrigger出现异常", e);
}
}
/**
* 创建定时任务
*/
public static void createScheduleJob(Scheduler scheduler, ScheduleJobEntity scheduleJob) {
try {
//构建job信息
JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(scheduleJob.getJobId())).build();
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
.withMisfireHandlingInstructionDoNothing();
//按新的cronExpression表达式构建一个新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getJobId())).withSchedule(scheduleBuilder).build();
//放入参数,运行时的方法可以获取
jobDetail.getJobDataMap().put(ScheduleJobEntity.JOB_PARAM_KEY, scheduleJob);
scheduler.scheduleJob(jobDetail, trigger);
//暂停任务
if(scheduleJob.getStatus() == Constant.ScheduleStatus.PAUSE.getValue()){
pauseJob(scheduler, scheduleJob.getJobId());
}
} catch (SchedulerException e) {
throw new BusinessException("创建定时任务失败", e);
}
}
/**
* 更新定时任务
*/
public static void updateScheduleJob(Scheduler scheduler, ScheduleJobEntity scheduleJob) {
try {
TriggerKey triggerKey = getTriggerKey(scheduleJob.getJobId());
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
.withMisfireHandlingInstructionDoNothing();
CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getJobId());
//按新的cronExpression表达式重新构建trigger
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
//参数
trigger.getJobDataMap().put(ScheduleJobEntity.JOB_PARAM_KEY, scheduleJob);
scheduler.rescheduleJob(triggerKey, trigger);
//暂停任务
if(scheduleJob.getStatus() == Constant.ScheduleStatus.PAUSE.getValue()){
pauseJob(scheduler, scheduleJob.getJobId());
}
} catch (SchedulerException e) {
throw new BusinessException("更新定时任务失败", e);
}
}
/**
* 立即执行任务
*/
public static void run(Scheduler scheduler, ScheduleJobEntity scheduleJob) {
try {
//参数
JobDataMap dataMap = new JobDataMap();
dataMap.put(ScheduleJobEntity.JOB_PARAM_KEY, scheduleJob);
scheduler.triggerJob(getJobKey(scheduleJob.getJobId()), dataMap);
} catch (SchedulerException e) {
throw new BusinessException("立即执行定时任务失败", e);
}
}
/**
* 暂停任务
*/
public static void pauseJob(Scheduler scheduler, Long jobId) {
try {
scheduler.pauseJob(getJobKey(jobId));
} catch (SchedulerException e) {
throw new BusinessException("暂停定时任务失败", e);
}
}
/**
* 恢复任务
*/
public static void resumeJob(Scheduler scheduler, Long jobId) {
try {
scheduler.resumeJob(getJobKey(jobId));
} catch (SchedulerException e) {
throw new BusinessException("暂停定时任务失败", e);
}
}
/**
* 删除定时任务
*/
public static void deleteScheduleJob(Scheduler scheduler, Long jobId) {
try {
scheduler.deleteJob(getJobKey(jobId));
} catch (SchedulerException e) {
throw new BusinessException("删除定时任务失败", e);
}
}
}
|
[
"jtz"
] |
jtz
|
dc63ab1756c98108e9c2faa94a2ee8398f4b59d9
|
9a7fd2a60f4ea6150e0103162bff65853782c021
|
/app/src/main/java/com/student/john/taskmanagerclient/models/taskFields/dueDate/dueDateTextOptions/Within2Weeks.java
|
44d5b3ac5adfc489c872c5a89dadf6f7bcca85c2
|
[] |
no_license
|
jlund24/TaskManagerClient
|
46558b3383a84e576f62107232a0cfd720f06a7b
|
b0536834a7f9414db3f72cd2f5c451341d5b5caa
|
refs/heads/master
| 2021-03-24T13:56:32.813081
| 2017-09-19T22:55:33
| 2017-09-19T22:55:33
| 89,713,554
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 362
|
java
|
package com.student.john.taskmanagerclient.models.taskFields.dueDate.dueDateTextOptions;
import com.student.john.taskmanagerclient.models.Model;
import com.student.john.taskmanagerclient.models.taskFields.dueDate.DueDateText;
public class Within2Weeks extends DueDateText {
public Within2Weeks() {
setDescription(Model.DD_WITHIN_2_WEEKS);
}
}
|
[
"johnrlund@byu.studentbody.edu"
] |
johnrlund@byu.studentbody.edu
|
856ac64be85aa2acbe70c980f54e10f8c6a04de7
|
23ee7b0379db15f33201b692c8c337b7ebcca057
|
/src/main/java/com/hiteamtech/uws/dao/ModuleDao.java
|
6add17405ef1c59595805cf5917f96685bb263c4
|
[] |
no_license
|
swwboom/myweb
|
e87fe613c4ae8b8f08462d1025d7a4c36b62c4a0
|
b10709ec067c4146e67ad291f29941e01763a31a
|
refs/heads/master
| 2021-08-19T17:14:10.171448
| 2017-11-27T01:54:29
| 2017-11-27T01:54:29
| 111,972,363
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,771
|
java
|
package com.hiteamtech.uws.dao;
import com.hiteamtech.uws.resultmapping.tpl.Modules;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Mapper
public interface ModuleDao {
/**
* Update by on 2017/9/29.
* 增加模块
*/
@Results({
@Result(property = "id",column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "appId" , column = "app_id"),
@Result(property = "type", column = "type"),
@Result(property = "describe",column = "modules_describe"),
@Result(property = "status",column = "status")
})
@Insert("INSERT INTO modules (name,app_id,type,modules_describe,status) VALUES (#{modules.name},#{modules.appId},#{modules.type},#{modules.describe},#{modules.status})")
@Options(useGeneratedKeys = true, keyProperty = "modules.id")
int addModules(@Param("modules") Modules modules);
/**
* Update by on 2017/9/29.
* 删除模块
*/
@Results({
@Result(property = "id",column = "id"),
@Result(property = "status",column = "status")
})
@Update("UPDATE modules SET status = 0 WHERE id =#{id}")
void deleteModule(@Param("id") int id);
/**
* Update by on 2017/9/29.
* 根据模块id查询模块详情
*/
@Select({"SELECT * from modules where id = #{id} and status = 1"})
List<Map<String, Object>> findModuleById(@Param("id") int id);
/**
* Update by on 2017/9/29.
* 查询app模块列表
*/
@Select({"SELECT id,name,modules_describe as modulesDescribe,type from modules where app_id = #{appId} and status = 1 order by id limit #{page},#{pageCount}"})
List<Map<String,Object>> findModuleByAppId(@Param("appId") int appId , @Param("page") int page1, @Param("pageCount") int pageCount);
@Select("SELECT count(*) from modules where app_id=#{appId} and status=1")
long findModuleCount(@Param("appId") int appId);
@Select("SELECT bn.id,bn.img_url imgUrl,bn.jump_url jumpUrl,bn.banner_id bannerId,bn.sort_num sortNum\n" +
"FROM module_banner mb\n" +
"LEFT JOIN banner_node bn ON mb.banner_id=bn.banner_id\n" +
"WHERE mb.modules_id=#{moduleId} AND bn.status=1 limit #{page},#{pageCount}")
List<Map> findBannersByModuleId(@Param("moduleId") int moduleId,@Param("page")int page, @Param("pageCount")int pageCount);
@Select("SELECT count(bn.id)\n" +
"FROM module_banner mb\n" +
"LEFT JOIN banner_node bn ON mb.banner_id=bn.banner_id\n" +
"WHERE mb.modules_id=#{moduleId} AND bn.status=1")
int findBannerNumByModuleId(@Param("moduleId") int moduleId);
}
|
[
"563482166@qq.com"
] |
563482166@qq.com
|
9c8142145eb939f468d188f3feb7df732efe37b5
|
b71e450856267c0d86f94fdcac17d9b445ff7ff0
|
/src/demo/Spring/src/com/demo/hello/MainApp.java
|
534f210a85cf1048aa34ff9d701e5200f99e6056
|
[] |
no_license
|
abingagl/JavaCourse
|
6a3462b52b1724cd5576042449410daec7b06fae
|
f2d8a4452c84ad5fa861b3fcc6cb9a092da5c7a3
|
refs/heads/main
| 2023-07-01T07:07:23.806958
| 2021-08-08T15:43:14
| 2021-08-08T15:43:14
| 380,771,146
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 514
|
java
|
package com.demo.hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author :zhang
* @title :TODO
* @date :created in 2021/07/25
*/
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld2");
System.out.println(obj.getMessage());
}
}
|
[
"bxzhang2@163.com"
] |
bxzhang2@163.com
|
28323dd13a8ea16e071700d480aac327318c88fa
|
901c5c4e7bb5273550daf468c638af23e7dabdd6
|
/exLicenta/Business/src/main/java/ro/uvt/fmi/itro/ejb/autor/AutorRemote.java
|
ec034a9d34433fc826d05d45a9bf5d34e3b72f43
|
[] |
no_license
|
zflavia/ITRO
|
fa3d1442d44b17866079238a15db6e9e8d5cfe74
|
c165b69c3d194d4c29387ab425f2745db2a0bb68
|
refs/heads/master
| 2021-06-28T10:52:08.278959
| 2020-09-10T10:22:15
| 2020-09-10T10:22:15
| 141,394,295
| 0
| 2
| null | 2020-09-10T10:30:09
| 2018-07-18T06:58:21
|
Java
|
UTF-8
|
Java
| false
| false
| 401
|
java
|
package ro.uvt.fmi.itro.ejb.autor;
import java.util.List;
import javax.ejb.EJBException;
import javax.ejb.Remote;
import ro.uvt.fmi.persistenta.autor.Autor;
@Remote
public interface AutorRemote {
public List<Autor> getAll();
public Autor getById(Long id);
public Autor insert(Autor t) throws EJBException;
public Autor update(Autor t) throws EJBException;
public void delete(Long id);
}
|
[
"flavia.micota@e-uvt.ro"
] |
flavia.micota@e-uvt.ro
|
e125671f23f709385eb9317603ca15df8dac8b64
|
b9eee567eadecd509fd47d05f37e1bcf5e7878ac
|
/druid-spring-boot-3-starter/src/test/java/com/alibaba/druid/spring/boot3/demo/service/UserServiceImpl.java
|
18c8bccb14229161eff5e46deb07bd9ee542a159
|
[
"Apache-2.0"
] |
permissive
|
vanlin/druid
|
de101e95ab5235b128dbdeb8300824781871bc13
|
602342ec895c0252dd3104021814768d9dba66cd
|
refs/heads/master
| 2023-09-01T15:39:26.897225
| 2023-08-28T03:09:23
| 2023-08-28T03:09:23
| 683,897,864
| 0
| 0
|
Apache-2.0
| 2023-08-28T02:39:27
| 2023-08-28T02:39:21
| null |
UTF-8
|
Java
| false
| false
| 626
|
java
|
package com.alibaba.druid.spring.boot3.demo.service;
import com.alibaba.druid.spring.boot3.demo.dao.UserDao;
import com.alibaba.druid.spring.boot3.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User findById(Long id) {
Optional<User> result = userDao.findById(id);
if (!result.isPresent()) {
return null;
}
return result.get();
}
}
|
[
"shaojin.wensj@alibaba-inc.com"
] |
shaojin.wensj@alibaba-inc.com
|
ecb2b78d88ff41dd09ea6ec480bd40ea7a5d19ae
|
5ff3bbbb7a450e723e096cefc1edd2ce1c304e24
|
/app/src/main/java/com/mindclarity/checkmaid/data/remote/models/user_registration/response/UserRegistrationResponseModel.java
|
40ecc7c58848944e1cc626ddc738362ef96b0602
|
[] |
no_license
|
umairmunir-95/CheckMaid-Android
|
8e85c302ec51339c9da776fdd63a0c1a9201a472
|
3c43cd9ea3dd2f3d1b21cca25425f4a0b4159ce5
|
refs/heads/master
| 2020-04-29T08:21:46.845647
| 2019-03-16T15:15:24
| 2019-03-16T15:15:24
| 175,984,352
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 659
|
java
|
package com.mindclarity.checkmaid.data.remote.models.user_registration.response;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class UserRegistrationResponseModel {
@SerializedName("status")
@Expose
private Boolean status;
@SerializedName("message")
@Expose
private String message;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
[
"umairmunir.95@gmail.com"
] |
umairmunir.95@gmail.com
|
5eca275816b6f9555dc53aad4f2856836ed5a26e
|
7fa47be1b7e870b33251241c657db9b00b7b27fa
|
/app/src/main/java/com/capstone/sarangbang/triplejong/MatchingView.java
|
118262f62807ee5a63914310ecf0a55b341f127d
|
[] |
no_license
|
jjony553/triple-jong
|
1bf1245a26bbcf14dc7353c0f3f2225989d4c6fe
|
00fab49249c3aeec0f9d49f5f2376b870394447b
|
refs/heads/master
| 2020-08-06T09:39:35.211881
| 2019-12-26T15:18:59
| 2019-12-26T15:18:59
| 212,927,184
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 4,505
|
java
|
package com.capstone.sarangbang.triplejong;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MatchingView extends AppCompatActivity {
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
MatchingAdapter matchingAdapter;
private FirebaseAuth authentication;
private FirebaseUser currentFbUser;
private DatabaseReference dbref;
private DatabaseReference usersRef;
private DatabaseReference contactsRef;
private static List<User> users = Collections.emptyList();
private User currentUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.matching_recycler);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView = findViewById(R.id.matchingRecyclerView);
recyclerView.addItemDecoration(
new DividerItemDecoration(this,linearLayoutManager.getOrientation()));
recyclerView.setLayoutManager(linearLayoutManager);
initFirebase();
final List<MatchingContact> userList = new ArrayList<>();
final int aa[] = {0};
usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
initUsers(dataSnapshot);
initCurrentUser();
for(int i=0; i<users.size(); i++) {
if(currentUser.getRank().equals(users.get(i).getRank())){
if(currentUser.getEmail().equals(users.get(i).getEmail())) {
continue;
} else {
userList.add(new MatchingContact(users.get(i).getEmail(), users.get(i).getFname(), users.get(i).getLname(), users.get(i).getUID()));
aa[0]++;
}
}
}
if (aa[0] == 0) {
Toast.makeText(getApplicationContext(), "추천 사용자가 없습니다.", Toast.LENGTH_LONG).show();
}
matchingAdapter = new MatchingAdapter(userList);
recyclerView.setAdapter(matchingAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w("FIREBASE", "usersRef:onCancelled", databaseError.toException());
}
});
}
public void onBackPressed() {
finish();
super.onBackPressed();
}
private void initFirebase () {
authentication = FirebaseAuth.getInstance();
currentFbUser = authentication.getCurrentUser();
dbref = FirebaseDatabase.getInstance().getReference();
usersRef = dbref.child("users");
contactsRef = dbref.child("contacts/" + currentFbUser.getUid());
}
private void initUsers (DataSnapshot dataSnapshot){
users = new ArrayList<User>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
users.add(user);
}
}
private void initCurrentUser() {
currentUser = new User();
currentUser.setUID(currentFbUser.getUid());
Log.d("UID", currentUser.getUID());
for (int i = 0; i < users.size(); i++) {
if (currentUser.getUID().equals(users.get(i).getUID())) {
currentUser.setFname(users.get(i).getFname());
currentUser.setLname(users.get(i).getLname());
currentUser.setEmail(users.get(i).getEmail());
currentUser.setRank(users.get(i).getRank());
}
}
}
}
|
[
"ds3jpi3@naver.com"
] |
ds3jpi3@naver.com
|
ad1324ec07c3dd9e30057d156ce12b25ef5714b1
|
3465ff0abebaccf093d9f2603921aee62bc9fe52
|
/src/main/java/org/vngx/jsch/kex/KexAlgorithm.java
|
3a4af1bd9036ae2fdea638024915715890d1d18e
|
[
"BSD-3-Clause"
] |
permissive
|
joval/vngx-jsch
|
772404c517878e300721f2bb34cafdd57a969da5
|
70aa70c4172b8a6ff5371fcd2469b7f9e1928911
|
refs/heads/master
| 2020-04-05T02:11:34.731272
| 2016-11-10T22:08:07
| 2016-11-10T22:08:07
| 2,734,254
| 1
| 2
| null | 2016-08-01T13:16:46
| 2011-11-08T14:26:37
|
Java
|
UTF-8
|
Java
| false
| false
| 7,414
|
java
|
/*
* Copyright (c) 2010-2011 Michael Laudati, N1 Concepts LLC.
*
* 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 names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* 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 N1
* CONCEPTS LLC OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.vngx.jsch.kex;
import java.io.IOException;
import org.vngx.jsch.Buffer;
import org.vngx.jsch.Packet;
import org.vngx.jsch.Session;
import org.vngx.jsch.Util;
import org.vngx.jsch.algorithm.Algorithm;
import org.vngx.jsch.exception.JSchException;
import org.vngx.jsch.hash.Hash;
import org.vngx.jsch.util.KeyType;
/**
* <p>Abstract class for defining key exchange algorithm implementations. After
* the SSH_MSG_KEXINIT message exchange, the key exchange algorithm is run. It
* may involve several packet exchanges, as specified by the key exchange
* method.</p>
*
* <p>The key exchange produces two values: a shared secret K, and an exchange
* hash H. Encryption and authentication keys are derived from these. The
* exchange hash H from the first key exchange is additionally used as the
* session identifier, which is a unique identifier for this connection. It is
* used by authentication methods as a part of the data that is signed as a
* proof of possession of a private key. Once computed, the session identifier
* is not changed, even if keys are later re-exchanged.</p>
*
* <p>Each key exchange method specifies a hash function that is used in the key
* exchange. The same hash algorithm MUST be used in key derivation. Here,
* we'll call it HASH.</p>
*
* <p><a href="http://tools.ietf.org/html/rfc4253#section-7">RFC 4253 - The
* Secure Shell (SSH) Transport Layer Protocol: Key Exchange</a></p>
*
* @see org.vngx.jsch.kex.KeyExchange
*
* @author Michael Laudati
*/
public abstract class KexAlgorithm implements Algorithm {
/** Constant state code for when key exchange is completed. */
public final static int STATE_END = 0;
/** Buffer for sending and receiving SSH packets. */
protected final Buffer _buffer = new Buffer();
/** SSH packet for sending and receiving requests to SSH server for kex. */
protected final Packet _packet = new Packet(_buffer);
/** Session the key exchange is for. */
protected Session _session;
/** Client version String sent to remote SSH server (CR and LF excluded). */
protected byte[] V_C;
/** Server version String read from SSH server response (CR and LF excluded). */
protected byte[] V_S;
/** Client's SSH_MSG_KEXINIT payload sent to server. */
protected byte[] I_C;
/** Server's SSH_MSG_KEXINIT payload received from server. */
protected byte[] I_S;
/** K_S is the server's public host key. */
protected byte[] K_S;
/** Host key type. */
protected KeyType _hostKeyType;
/** State code for current state of key exchange. */
protected int _state = -1;
/**
* {@code Hash} instance used to hash values in key exchange. This hash must
* be used in key derivation.
*/
protected final Hash _hash;
/**
* K is the shared secret created by both the server and the client used
* in key derivation.
*/
protected byte[] _K;
/**
* The exchange hash H used to derive the encryption and authentication
* keys. The first kex exchange hash is also used as the session identifier.
*/
protected byte[] _H;
/**
* Creates a new instance of {@code KexAlgorithm} which uses the specified
* {@code hash} implementation for key exchange. Every kex algorithm must
* have a {@code Hash} which is used in key derivation for {@code Cipher}s
* and {@code MAC}s used in the transport layer for the session.
*
* @param hash implementation
* @throws IllegalArgumentException if hash is null
*/
protected KexAlgorithm(final Hash hash) {
if( hash == null ) {
throw new IllegalArgumentException("Hash cannot be null for kex algorithm");
}
_hash = hash;
}
/**
* Initializes the key exchange algorithm for the specified {@code session},
* {@code I_C} client kex init and {@code I_S} server kex init payloads.
* Implementations should override the {@code init} method and start the
* specific key exchange algorithm process with the appropriate SSH message
* code.
*
* @param session instance
* @param I_C client's KEXINIT payload
* @param I_S server's KEXINIT payload
* @throws JSchException if any errors occur
* @throws IOException if any IO related errors occur
*/
protected void init(Session session, byte[] I_C, byte[] I_S) throws JSchException, IOException {
_session = session;
this.V_C = Util.str2byte(_session.getClientVersion());
this.V_S = Util.str2byte(_session.getServerVersion());
this.I_C = I_C; // Consider making a safe copy of the client's and
this.I_S = I_S; // server's kex init payloers
}
/**
* Processes the next key exchange response from the server.
*
* @param buffer containing server response
* @return true if response processed successfully
* @throws JSchException if any errors occur
* @throws IOException if any IO errors occur
*/
protected abstract boolean next(final Buffer buffer) throws JSchException, IOException;
/**
* Returns the current state of the key exchange. Since the key exchange
* may take several requests back and forth between server and client, the
* state helps to track the process and ensure both sides are in the same
* state.
*
* @return state of key exchange process
*/
protected int getState() {
return _state;
}
/**
* Returns the {@code Hash} instance used for the key exchange and key
* derivation for encryption.
*
* @return hash used for key exchange
*/
public Hash getHash() {
return _hash;
}
/**
* Returns the exchange hash H generated in the key exchange. The exchange
* hash H is a sensitive piece of data and should be carefully protected and
* cleared after use.
*
* @return exchange hash H
*/
public byte[] getH() {
return _H;
}
/**
* Returns the shared secret key K generated during the key exchange. The
* shared secret is a sensitive piece of data and should be carefully
* protected and cleared after use.
*
* @return shared secret K
*/
public byte[] getK() {
return _K;
}
}
|
[
"michael.laudati@gmail.com"
] |
michael.laudati@gmail.com
|
f7f5bbc34eae043df27601760acdb4c6bc8a3e75
|
48b8c22f5cb2dca5b48832a86cb836b944e73c3b
|
/FLAPPYBD.java
|
5d57a528fa4e4316e2f6bfaa95885ce53f1cdc96
|
[] |
no_license
|
kamalharsh14/Codechef
|
f15eb46f3713c28b9523f6110dc5265af98e0b36
|
b20ae061786824463a924596f166388684d2de27
|
refs/heads/master
| 2023-07-05T14:49:42.014217
| 2021-08-28T18:02:38
| 2021-08-28T18:02:38
| 397,483,205
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,087
|
java
|
package Codechef;
import java.util.*;
public class FLAPPYBD {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int i = 0 ; i < t ; i ++){
int N = in.nextInt();
int H = in.nextInt();
int x[] = new int[N];
int h[] = new int[N];
for(int j = 0 ; j < N ; j ++){
x[i] = in.nextInt();
}
for(int j = 0 ; j < N ; j ++){
h[i] = in.nextInt();
}
int click = 0;
for(int j = 0 ; j < N ; j ++){
if(h[j] > H && x[j] == j){
click = click + h[i] - H ;
H = H+click;
}
H--;
if(H < 1){
click++;
H++;
}
if(h[j] == H){
System.out.println(-1);
break;
}
}
System.out.println(click);
}
in.close();
}
}
|
[
"singhharsh998@gmail.com"
] |
singhharsh998@gmail.com
|
dff0f9bdfcc0cbbad521b97b0efcb61c24e957d4
|
34f8d4ba30242a7045c689768c3472b7af80909c
|
/jdk-12/src/jdk.internal.vm.compiler/org.graalvm.compiler.hotspot.amd64/src/org/graalvm/compiler/hotspot/amd64/AMD64HotSpotSafepointOp.java
|
f30148a91feba3307e18c93806010480744afc5b
|
[
"Apache-2.0"
] |
permissive
|
lovelycheng/JDK
|
5b4cc07546f0dbfad15c46d427cae06ef282ef79
|
19a6c71e52f3ecd74e4a66be5d0d552ce7175531
|
refs/heads/master
| 2023-04-08T11:36:22.073953
| 2022-09-04T01:53:09
| 2022-09-04T01:53:09
| 227,544,567
| 0
| 0
| null | 2019-12-12T07:18:30
| 2019-12-12T07:18:29
| null |
UTF-8
|
Java
| false
| false
| 6,470
|
java
|
/*
* Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.graalvm.compiler.hotspot.amd64;
import static org.graalvm.compiler.core.common.NumUtil.isInt;
import static org.graalvm.compiler.core.common.GraalOptions.GeneratePIC;
import static org.graalvm.compiler.core.common.GraalOptions.ImmutableCode;
import static jdk.vm.ci.amd64.AMD64.rax;
import static jdk.vm.ci.amd64.AMD64.rip;
import org.graalvm.compiler.asm.amd64.AMD64Address;
import org.graalvm.compiler.asm.amd64.AMD64MacroAssembler;
import org.graalvm.compiler.core.common.LIRKind;
import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig;
import org.graalvm.compiler.lir.LIRFrameState;
import org.graalvm.compiler.lir.LIRInstructionClass;
import org.graalvm.compiler.lir.Opcode;
import org.graalvm.compiler.lir.amd64.AMD64LIRInstruction;
import org.graalvm.compiler.lir.asm.CompilationResultBuilder;
import org.graalvm.compiler.nodes.spi.NodeLIRBuilderTool;
import jdk.vm.ci.code.Register;
import jdk.vm.ci.code.RegisterValue;
import jdk.vm.ci.code.site.InfopointReason;
import jdk.vm.ci.meta.AllocatableValue;
import jdk.vm.ci.meta.JavaConstant;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.Value;
/**
* Emits a safepoint poll.
*/
@Opcode("SAFEPOINT")
public final class AMD64HotSpotSafepointOp extends AMD64LIRInstruction {
public static final LIRInstructionClass<AMD64HotSpotSafepointOp> TYPE = LIRInstructionClass.create(AMD64HotSpotSafepointOp.class);
@State protected LIRFrameState state;
@Temp({OperandFlag.REG, OperandFlag.ILLEGAL}) private AllocatableValue temp;
private final GraalHotSpotVMConfig config;
private final Register thread;
public AMD64HotSpotSafepointOp(LIRFrameState state, GraalHotSpotVMConfig config, NodeLIRBuilderTool tool, Register thread) {
super(TYPE);
this.state = state;
this.config = config;
this.thread = thread;
if (config.threadLocalHandshakes || isPollingPageFar(config) || ImmutableCode.getValue(tool.getOptions())) {
temp = tool.getLIRGeneratorTool().newVariable(LIRKind.value(tool.getLIRGeneratorTool().target().arch.getWordKind()));
} else {
// Don't waste a register if it's unneeded
temp = Value.ILLEGAL;
}
}
@Override
public void emitCode(CompilationResultBuilder crb, AMD64MacroAssembler asm) {
emitCode(crb, asm, config, false, state, thread, temp instanceof RegisterValue ? ((RegisterValue) temp).getRegister() : null);
}
public static void emitCode(CompilationResultBuilder crb, AMD64MacroAssembler asm, GraalHotSpotVMConfig config, boolean atReturn, LIRFrameState state, Register thread, Register scratch) {
if (config.threadLocalHandshakes) {
emitThreadLocalPoll(crb, asm, config, atReturn, state, thread, scratch);
} else {
emitGlobalPoll(crb, asm, config, atReturn, state, scratch);
}
}
/**
* Tests if the polling page address can be reached from the code cache with 32-bit
* displacements.
*/
private static boolean isPollingPageFar(GraalHotSpotVMConfig config) {
final long pollingPageAddress = config.safepointPollingAddress;
return config.forceUnreachable || !isInt(pollingPageAddress - config.codeCacheLowBound) || !isInt(pollingPageAddress - config.codeCacheHighBound);
}
private static void emitGlobalPoll(CompilationResultBuilder crb, AMD64MacroAssembler asm, GraalHotSpotVMConfig config, boolean atReturn, LIRFrameState state, Register scratch) {
assert !atReturn || state == null : "state is unneeded at return";
if (ImmutableCode.getValue(crb.getOptions())) {
JavaKind hostWordKind = JavaKind.Long;
int alignment = hostWordKind.getBitCount() / Byte.SIZE;
JavaConstant pollingPageAddress = JavaConstant.forIntegerKind(hostWordKind, config.safepointPollingAddress);
// This move will be patched to load the safepoint page from a data segment
// co-located with the immutable code.
if (GeneratePIC.getValue(crb.getOptions())) {
asm.movq(scratch, asm.getPlaceholder(-1));
} else {
asm.movq(scratch, (AMD64Address) crb.recordDataReferenceInCode(pollingPageAddress, alignment));
}
final int pos = asm.position();
crb.recordMark(atReturn ? config.MARKID_POLL_RETURN_FAR : config.MARKID_POLL_FAR);
if (state != null) {
crb.recordInfopoint(pos, state, InfopointReason.SAFEPOINT);
}
asm.testl(rax, new AMD64Address(scratch));
} else if (isPollingPageFar(config)) {
asm.movq(scratch, config.safepointPollingAddress);
crb.recordMark(atReturn ? config.MARKID_POLL_RETURN_FAR : config.MARKID_POLL_FAR);
final int pos = asm.position();
if (state != null) {
crb.recordInfopoint(pos, state, InfopointReason.SAFEPOINT);
}
asm.testl(rax, new AMD64Address(scratch));
} else {
crb.recordMark(atReturn ? config.MARKID_POLL_RETURN_NEAR : config.MARKID_POLL_NEAR);
final int pos = asm.position();
if (state != null) {
crb.recordInfopoint(pos, state, InfopointReason.SAFEPOINT);
}
// The C++ code transforms the polling page offset into an RIP displacement
// to the real address at that offset in the polling page.
asm.testl(rax, new AMD64Address(rip, 0));
}
}
private static void emitThreadLocalPoll(CompilationResultBuilder crb, AMD64MacroAssembler asm, GraalHotSpotVMConfig config, boolean atReturn, LIRFrameState state, Register thread,
Register scratch) {
assert !atReturn || state == null : "state is unneeded at return";
assert config.threadPollingPageOffset >= 0;
asm.movptr(scratch, new AMD64Address(thread, config.threadPollingPageOffset));
crb.recordMark(atReturn ? config.MARKID_POLL_RETURN_FAR : config.MARKID_POLL_FAR);
final int pos = asm.position();
if (state != null) {
crb.recordInfopoint(pos, state, InfopointReason.SAFEPOINT);
}
asm.testl(rax, new AMD64Address(scratch));
}
}
|
[
"zeng255@163.com"
] |
zeng255@163.com
|
b3d818ef3f829d48cff0ec7e847f9551cc9215c0
|
8dcd6fac592760c5bff55349ffb2d7ce39d485cc
|
/com/google/android/gms/common/stats/WakeLockEvent.java
|
3c641cc9d89b9556c87984d4f8adad5678ea513c
|
[] |
no_license
|
andrepcg/hikam-android
|
9e3a02e0ba9a58cf8a17c5e76e2f3435969e4b3a
|
bf39e345a827c6498052d9df88ca58d8823178d9
|
refs/heads/master
| 2021-09-01T11:41:10.726066
| 2017-12-26T19:04:42
| 2017-12-26T19:04:42
| 115,447,829
| 2
| 2
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,985
|
java
|
package com.google.android.gms.common.stats;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import android.text.TextUtils;
import java.util.List;
public final class WakeLockEvent extends StatsEvent {
public static final Creator<WakeLockEvent> CREATOR = new zzg();
private final long DM;
private int DN;
private final long DU;
private long DW;
private final String EA;
private final int EB;
private final List<String> EC;
private final String ED;
private int EE;
private final String EF;
private final float EG;
private final String Ey;
private final String Ez;
private final long mTimeout;
final int mVersionCode;
WakeLockEvent(int i, long j, int i2, String str, int i3, List<String> list, String str2, long j2, int i4, String str3, String str4, float f, long j3, String str5) {
this.mVersionCode = i;
this.DM = j;
this.DN = i2;
this.Ey = str;
this.Ez = str3;
this.EA = str5;
this.EB = i3;
this.DW = -1;
this.EC = list;
this.ED = str2;
this.DU = j2;
this.EE = i4;
this.EF = str4;
this.EG = f;
this.mTimeout = j3;
}
public WakeLockEvent(long j, int i, String str, int i2, List<String> list, String str2, long j2, int i3, String str3, String str4, float f, long j3, String str5) {
this(2, j, i, str, i2, list, str2, j2, i3, str3, str4, f, j3, str5);
}
public int getEventType() {
return this.DN;
}
public long getTimeMillis() {
return this.DM;
}
public void writeToParcel(Parcel parcel, int i) {
zzg.zza(this, parcel, i);
}
public String zzawp() {
return this.ED;
}
public long zzawq() {
return this.DW;
}
public long zzaws() {
return this.DU;
}
public String zzawt() {
String valueOf = String.valueOf("\t");
String valueOf2 = String.valueOf(zzaww());
String valueOf3 = String.valueOf("\t");
int zzawz = zzawz();
String valueOf4 = String.valueOf("\t");
String join = zzaxa() == null ? "" : TextUtils.join(",", zzaxa());
String valueOf5 = String.valueOf("\t");
int zzaxb = zzaxb();
String valueOf6 = String.valueOf("\t");
String zzawx = zzawx() == null ? "" : zzawx();
String valueOf7 = String.valueOf("\t");
String zzaxc = zzaxc() == null ? "" : zzaxc();
String valueOf8 = String.valueOf("\t");
float zzaxd = zzaxd();
String valueOf9 = String.valueOf("\t");
String zzawy = zzawy() == null ? "" : zzawy();
return new StringBuilder(((((((((((((String.valueOf(valueOf).length() + 37) + String.valueOf(valueOf2).length()) + String.valueOf(valueOf3).length()) + String.valueOf(valueOf4).length()) + String.valueOf(join).length()) + String.valueOf(valueOf5).length()) + String.valueOf(valueOf6).length()) + String.valueOf(zzawx).length()) + String.valueOf(valueOf7).length()) + String.valueOf(zzaxc).length()) + String.valueOf(valueOf8).length()) + String.valueOf(valueOf9).length()) + String.valueOf(zzawy).length()).append(valueOf).append(valueOf2).append(valueOf3).append(zzawz).append(valueOf4).append(join).append(valueOf5).append(zzaxb).append(valueOf6).append(zzawx).append(valueOf7).append(zzaxc).append(valueOf8).append(zzaxd).append(valueOf9).append(zzawy).toString();
}
public String zzaww() {
return this.Ey;
}
public String zzawx() {
return this.Ez;
}
public String zzawy() {
return this.EA;
}
public int zzawz() {
return this.EB;
}
public List<String> zzaxa() {
return this.EC;
}
public int zzaxb() {
return this.EE;
}
public String zzaxc() {
return this.EF;
}
public float zzaxd() {
return this.EG;
}
public long zzaxe() {
return this.mTimeout;
}
}
|
[
"andrepcg@gmail.com"
] |
andrepcg@gmail.com
|
67cd1800dcd159f7258da0bdeab4633b43d41f73
|
8c144196627df83471da9e5b6530623643ed3733
|
/mybatis_demo/src/main/java/com/mb/demo/mapper/DeptMapper.java
|
da4b2bca2552b61700d35325c40cd7dea56d44e3
|
[] |
no_license
|
jazzlly/java-example
|
9879d3dd8718f8d5ceebd569a698ef735f7fca7a
|
b97c892ccbf31ad58bcc3a090f0dfdc50ed785ef
|
refs/heads/master
| 2023-03-19T04:08:11.610597
| 2023-03-08T07:43:03
| 2023-03-08T07:43:03
| 96,027,321
| 0
| 0
| null | 2023-03-03T10:56:23
| 2017-07-02T14:07:10
|
Java
|
UTF-8
|
Java
| false
| false
| 544
|
java
|
package com.mb.demo.mapper;
import com.mb.demo.model.Dept;
import com.mb.demo.model.Emp;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* EmpMapper接口绑定到EmpMapper.xml文件, 通过xml描述sql
*
* 参数映射: 优先使用 注解 @Param > [param1, param2, ] >>> [arg0, arg1, ...]
*/
public interface DeptMapper {
Dept selectDept(Long deptId);
/** 获取部门和部门中所有员工 */
Dept selectDeptAndEmps(Long deptId);
Integer insertDept(@Param("deptName") String deptName);
}
|
[
"rui.jiang@pekall.com"
] |
rui.jiang@pekall.com
|
d04415ba152834846b0af6542785975e825dc572
|
736d2151a0729f7db1073961ffc4ba0e63efff68
|
/app/src/main/java/com/justeat/architectures/react/ViewModel.java
|
73e7a9b38cd22b45a8f8f13abf890c7a066fe0a6
|
[] |
no_license
|
MichalZwierzyk/Architectures
|
676bfdfa5a94d94ef9c044b8653cc363a55aeeef
|
36e6c716ce3a855e4ec3a7257e5ac974caa4e9ac
|
refs/heads/master
| 2021-01-25T10:50:16.904430
| 2017-06-12T23:30:08
| 2017-06-12T23:30:08
| 93,882,118
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,574
|
java
|
package com.justeat.architectures.react;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
class ViewModel {
private UserRepo userRepo;
private UserUiModel userUiModel;
ViewModel(UserRepo userRepo, UserUiModel userUiModel) {
this.userRepo = userRepo;
this.userUiModel = userUiModel;
}
void onGetUserButtonClicked(GetUserUiEvent getUserUiEvent) {
// Transform Ui Event into Action
GetUserAction getUserAction = new GetUserAction(getUserUiEvent.getName());
userRepo.getUser(getUserAction)
.onErrorReturn(throwable -> new UserResult("Unknown", "", UserRole.NONE, "", 0.0))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(userResult -> {
// Transform Result into UiModel (Presentation Logic in View Model)
String userFullName = userResult.getName() + userResult.getSurname();
int userColor;
if (userResult.getRole() == UserRole.ADMIN) {
userColor = 0xFFFF0000;
} else if(userResult.getRole() == UserRole.GUEST) {
userColor = 0xFF0000FF;
} else {
userColor = 0xFF000000;
}
// Consume UiModel
userUiModel.fullname.set(userFullName);
userUiModel.color.set(userColor);
});
}
}
|
[
"michal.zwierzyk@just-eat.com"
] |
michal.zwierzyk@just-eat.com
|
c8914dca685fdd21a4c8702881f818cb7cbe2f55
|
5e9ca46357a11938745a50a6779975907fc12925
|
/app/src/main/java/com/example/enchanterswapna/chanakyaniti/Chapterfftn.java
|
f052972f12023747d8cfdb5da685d035814afd6e
|
[] |
no_license
|
GuruSwapna/ChanakyaNiti
|
f5465b9bf84b21075ee1ad5fb742e80ae4f6774c
|
8e368fff32336d3a5f6a058068025c8cffc61cb4
|
refs/heads/master
| 2021-01-01T06:37:18.064609
| 2017-07-17T12:13:04
| 2017-07-17T12:13:04
| 97,472,071
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,464
|
java
|
package com.example.enchanterswapna.chanakyaniti;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class Chapterfftn extends AppCompatActivity {
TextView txt1;
ImageButton imbtn1,imleft,imrght;
ClipData myClip;
ClipboardManager myClipboard;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapterfftn);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imbtn1=(ImageButton)findViewById(R.id.imageButton1);
txt1=(TextView)findViewById(R.id.textone);
imleft=(ImageButton)findViewById(R.id.but1);
imrght=(ImageButton)findViewById(R.id.but2);
imleft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Toast.makeText(getApplicationContext(),"First Chapter",Toast.LENGTH_SHORT).show();
Intent int2=new Intent(Chapterfftn.this,Chapterfrtn.class);
startActivity(int2);
}
});
imrght.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"Last Chapter",Toast.LENGTH_SHORT).show();
}
});
// txt1.setMovementMethod(new ScrollingMovementMethod());
myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
imbtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String text = txt1.getText().toString();
myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);
Toast.makeText(getApplicationContext(), "Text Copied",
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(Chapterfftn.this, MainActivity.class));
finish();
}
}
|
[
"swapna.d250@gmail.com"
] |
swapna.d250@gmail.com
|
ec08b7320854ee07d0571341c690ec54a1dd2538
|
cea25bcd2cb6972c088452d6b91ef96c7ddf3f98
|
/Selenium-Automation-Elearning-Framework-TestNG/tests/com/training/sanity/tests/RTTC_011Test.java
|
a912df3633d0ea32555ef233fbef5285132ad579
|
[] |
no_license
|
RahilaNoor/Sampletestcases
|
bb197414c390f7f1a2509aaac772db13a7510144
|
382e83bb39d46900f6a90cebb65d2c34d234217f
|
refs/heads/master
| 2020-04-28T11:44:03.478290
| 2019-04-05T06:45:20
| 2019-04-05T06:45:20
| 175,252,419
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,907
|
java
|
package com.training.sanity.tests;
import static org.testng.Assert.assertEquals;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.training.generics.ScreenShot;
import com.training.pom.RTTC_011POM;
import com.training.utility.DriverFactory;
import com.training.utility.DriverNames;
public class RTTC_011Test {
private WebDriver driver;
private String baseUrl;
private RTTC_011POM loginPOM;
private static Properties properties;
private ScreenShot screenShot;
@BeforeClass
public static void setUpBeforeClass() throws IOException {
properties = new Properties();
FileInputStream inStream = new FileInputStream("./resources/others.properties");
properties.load(inStream);
}
@BeforeMethod
public void setUp() throws Exception {
driver = DriverFactory.getDriver(DriverNames.CHROME);
loginPOM = new RTTC_011POM(driver);
baseUrl = properties.getProperty("baseURL");
screenShot = new ScreenShot(driver);
// open the browser
driver.get(baseUrl);
}
@AfterMethod
public void tearDown() throws Exception {
Thread.sleep(1000);
driver.quit();
}
@Test
public void validLoginTest() {
String expected;
String Actual;
//Calling sendUserName method & sending admin Username
loginPOM.sendUserName("admin");
//Calling sendPasswod method & sending admin password
loginPOM.sendPassword("admin@123");
//Calling ClickLoginBtn method
loginPOM.clickLoginBtn();
//capturing screenshot
screenShot.captureScreenShot("First");
System.out.println("Admin logged in successfully");
//AssetEquals
expected="Dashboard";
Actual=driver.getTitle();
assertEquals(Actual, expected);
}
}
|
[
"RahilaRahila@192.168.0.3"
] |
RahilaRahila@192.168.0.3
|
87aa89b02052b951c1192a2c3c5e848e108a1230
|
e4e2cfe448703fd820150a6bf69fa66f90f3d916
|
/src/main/java/br/com/utily/ecommerce/entity/domain/shop/trade/ETradeType.java
|
acae096840a0813852ad0d321cfa1478cf2879b9
|
[] |
no_license
|
hanseld28/utily-ecommerce
|
91b1f11837c3a2d1cdbf0e99a4015fb863d004bc
|
d8e0e9ac2c09234e923747840d4db4cfd98055d5
|
refs/heads/master
| 2023-02-04T16:52:42.496805
| 2020-12-12T21:59:24
| 2020-12-12T21:59:24
| 314,137,567
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 289
|
java
|
package br.com.utily.ecommerce.entity.domain.shop.trade;
import lombok.Getter;
@Getter
public enum ETradeType {
EXCHANGE("Troca"),
REFUND("Devolução");
private final String displayName;
ETradeType(String displayName) {
this.displayName = displayName;
}
}
|
[
"hansel.donizete@gmail.com"
] |
hansel.donizete@gmail.com
|
2c7129fc68a6025e9dfeaedd0b1dd10c62d40334
|
0c1bfadbe115b0a1bf85e9788760289d63de4946
|
/designpatterns/src/com/practice/designpatterns/strategy/KnifeBehaviour.java
|
8c2cfad37787177d86085327e2a1633231a31866
|
[] |
no_license
|
sudamini/java-source-files
|
364917c0d823434c653d59644ed5c3d3e0d685fc
|
e8a8221bc85273815d356fc374fd7d4e5f5ed47c
|
refs/heads/master
| 2021-10-19T06:24:19.421438
| 2019-02-18T16:44:05
| 2019-02-18T16:44:05
| 167,198,754
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 197
|
java
|
package com.practice.designpatterns.strategy;
public class KnifeBehaviour implements WeaponBehaviour {
@Override
public void useWeapon() {
System.out.println( "I cut with a knife" ) ;
}
}
|
[
"sudamini.js@gmail.com"
] |
sudamini.js@gmail.com
|
861ad08e6bb5e1c4436794171feb5e695902fbf5
|
9b814ca7bb6ad2aceb03295338e3c74b58760179
|
/app/src/main/java/com/example/crazynet/student_library/webService/requests/Product_mostViewrequest.java
|
9caba50984087cf3bd73e76596d7de2b34d0f544
|
[] |
no_license
|
ahmedmed7t/student_Library
|
311bf962af86342905425f02036fa5b32bd42b7d
|
0912e864a27cc5f7901c2276bbd74e5023e2a6ec
|
refs/heads/master
| 2020-04-09T22:36:42.580762
| 2018-12-06T07:04:01
| 2018-12-06T07:04:01
| 160,633,316
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 200
|
java
|
package com.example.crazynet.student_library.webService.requests;
/**
* Created by CrazyNet on 16/08/2018.
*/
public class Product_mostViewrequest {
public Product_mostViewrequest() {
}
}
|
[
"medhatahmed19.am9@gmail.com"
] |
medhatahmed19.am9@gmail.com
|
4b74238b52b1300efa399985b3d791eb061d8b85
|
bb3677c1212a273926688596e898595f22772cea
|
/src/test/java/dev/patika/fifthhomework/FifthHomeworkAvemphractApplicationTests.java
|
c9e2853f0574ccb3e4c187b53ba9349a20921c59
|
[
"MIT"
] |
permissive
|
avemphract/fifth-homework-avemphract
|
d7ce4c17ac2a899a906f5f8f72692d40b9930e69
|
36064a649aeedd6d192265389632fb3dc3d6b6cc
|
refs/heads/main
| 2023-08-26T20:38:14.012691
| 2021-09-14T19:55:36
| 2021-09-14T19:55:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 242
|
java
|
package dev.patika.fifthhomework;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class FifthHomeworkAvemphractApplicationTests {
@Test
void contextLoads() {
}
}
|
[
"emrexatalkaya11051997@gmail.com"
] |
emrexatalkaya11051997@gmail.com
|
bc5960afd0d27a26843a387ffa059357157dc170
|
6bed1e7d53396ea5e474250fcb689ac0035e8f89
|
/src/main/java/com/loic/projectfacebook/leetcode/medium/SingleElementSortedArray.java
|
bd27303b69262b0d396e7bfcecfb9adef6bafbfc
|
[] |
no_license
|
ambamanyloic/facebookexercises
|
0b02b8430a1c8dcc7b5648184e763ad92821d140
|
5922edac43d4a01dc1bb2f6e3aaff99cc8e95100
|
refs/heads/master
| 2023-06-11T05:40:51.221738
| 2021-07-05T19:51:40
| 2021-07-05T19:51:40
| 319,823,199
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,306
|
java
|
package com.loic.projectfacebook.leetcode.medium;
import java.util.HashMap;
import java.util.Map;
public class SingleElementSortedArray {
public int singleNonDuplicate(int[] nums) {
int ans = -1;
int n = nums.length;
for (int i = 0; i < n; i += 2) {
if (nums[i] != nums[i + 1]) {
ans = nums[i];
break;
}
}
return ans;
/* Map<Integer,Integer> map = new HashMap<>();
int value = 0;
for(int i=0;i<nums.length;i++) {
if(map.containsKey(nums[i])){
map.put(nums[i],map.get(nums[i]+1));
} else {
map.put(nums[i],1);
}
for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
while( entry.getValue() != null) {
if(entry.getValue() == 1) {
value = entry.getKey();
break;
}
}
}
}
return value;*/
}
public static void main(String [] args) {
SingleElementSortedArray single = new SingleElementSortedArray();
int[] single_arr = {3,3,7,7,10,11,11};
System.out.println(single.singleNonDuplicate(single_arr));
}
}
|
[
"ambamanyloic@gmail.com"
] |
ambamanyloic@gmail.com
|
5236758cae3a448ee5652fb408b8c5c04460a4b2
|
4118a1cfb1aedd93901564cec12d0b38ba2876a9
|
/src/main/java/com/app/recipe/models/Preparation.java
|
0733e9f6a0005ae0b69ef280da28d65fc96fbe95
|
[] |
no_license
|
Godsownchild/Recipe
|
97eba21df7ceec1b394b5754b39fa4b023e25561
|
861a684c60333e1a5f5ac5430f4f3a86a15b40fd
|
refs/heads/master
| 2022-06-26T15:19:08.200639
| 2020-08-07T10:27:03
| 2020-08-07T10:27:03
| 246,008,620
| 0
| 0
| null | 2020-08-07T10:27:05
| 2020-03-09T10:41:51
|
CSS
|
UTF-8
|
Java
| false
| false
| 1,304
|
java
|
package com.app.recipe.models;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "cooking_preparation")
public class Preparation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Lob
@Column(name = "preparation_steps")
List<String> prepSteps;
public Preparation(List<String> prepSteps) {
this.prepSteps = prepSteps;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<String> getPrepSteps() {
return prepSteps;
}
public void setPrepSteps(List<String> prepSteps) {
this.prepSteps = prepSteps;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Preparation that = (Preparation) o;
return Objects.equals(id, that.id) &&
Objects.equals(prepSteps, that.prepSteps);
}
@Override
public int hashCode() {
return Objects.hash(id, prepSteps);
}
@Override
public String toString() {
return "Preparation{" +
"id=" + id +
", prepSteps=" + prepSteps +
'}';
}
}
|
[
"godsownchild08@gmail.com"
] |
godsownchild08@gmail.com
|
da358ea0c08b0cde7eacdcf2b034205263ea081e
|
04d67248e1a7a9c0a70b0c39c11f888c2d2ff6fa
|
/src/ua/nure/sokolov/practice4/part2/Part2.java
|
077c0fbaeb606223e222a3977af80e0f12ea9024
|
[] |
no_license
|
Anton1234567789/practice4
|
fbedfc5a1a4f403028103455a8b2699ecbcdce83
|
cedc9fdf3e2df9eb358ecfb9819b68089e560e6e
|
refs/heads/master
| 2021-08-23T10:24:05.512860
| 2017-12-04T14:36:05
| 2017-12-04T14:36:05
| 111,465,923
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,127
|
java
|
package ua.nure.sokolov.practice4.part2;
import ua.nure.sokolov.practice4.GetInputFile;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
public class Part2 {
private GetInputFile classGetIput = new GetInputFile();
private int[] array = new int[10];
private final String NAME_CREATE_FILE = "part2.txt";
private final String NAME_READ_CREATED_FILES = "part2(1).txt";
public static void main(String[] args) {
Part2 part2 = new Part2();
part2.createFile();
}
public void createFile(){
for (int i = 0; i < array.length; ++i)
array[i] = (int) (Math.random()*50);
System.out.print("input ==> ");
createFilePart2(NAME_CREATE_FILE, array);
int[] arr1 = readFile(NAME_CREATE_FILE);
bubbleSort(arr1);
System.out.print("output ==> ");
createFilePart2(NAME_READ_CREATED_FILES, arr1);
readFile(NAME_READ_CREATED_FILES);
}
public void createFilePart2(String nameTxt, int[] fileArray){
try(PrintWriter out = new PrintWriter(new FileOutputStream(nameTxt))) {
for (int i = 0; i < fileArray.length; ++i)
{
final String s = Integer.toString(fileArray[i]);
out.write(s);
out.write(" ");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public int[] readFile(String nameFile){
String textOfPart2 = classGetIput.getInput(nameFile);
System.out.println(textOfPart2);
String[] str = textOfPart2.split(" ");
int[] arr = new int[10];
for (int j = 0; j < str.length; j++){
arr[j] = Integer.parseInt(str[j]);
}
return arr;
}
public void bubbleSort(int[] arr){
for(int i = arr.length-1 ; i > 0 ; i--){
for(int j = 0 ; j < i ; j++){
if( arr[j] > arr[j+1] ){
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
}
}
|
[
"toshiksokil@mail.ru"
] |
toshiksokil@mail.ru
|
4d3d6afa4c4a390c2f4d9a523a9d5dcc3401671e
|
839d835efbd0e4e21b9bb1becabf9171218d1775
|
/trunk/thesis/de/axelwernicke/mypod/Backend.java
|
6cfb3b0485099ec5a7ebca3ff36465e932206286
|
[] |
no_license
|
BackupTheBerlios/mdnsm-svn
|
1be8b2e8a60b7ff2c95de379dc4b03fa1f07a591
|
27d7665708015ca44d5467614cc9fbe66a6b5f36
|
refs/heads/master
| 2021-01-19T13:26:32.752393
| 2006-04-13T12:03:54
| 2006-04-13T12:03:54
| 40,818,933
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 57,278
|
java
|
// 2.15.05: Hacked up for Get It Together by Greg Jordan
//
// Backend
// $Id: Backend.java,v 1.7 2005/02/23 06:32:06 gjuggler Exp $
//
// Copyright (C) 2002-2003 Axel Wernicke <axel.wernicke@gmx.de>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package de.axelwernicke.mypod;
import de.axelwernicke.mypod.util.ClipsTableUtils;
import de.axelwernicke.mypod.gui.GuiUtils;
import de.axelwernicke.mypod.gui.ProgressDialog;
import de.axelwernicke.mypod.ipod.IPod;
import de.axelwernicke.mypod.util.FileUtils;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JFileChooser;
/**
* Contains all the application logic for myPod
*
* @author axel wernicke
*/
public class Backend
{
/** jdk1.4 logger */
private static Logger logger = Logger.getLogger("de.axelwernicke.mypod");
/** name of the file all playlists are serialized to */
private static final String PLAYLISTS_GZ_FILENAME = "data" + File.separator + "playlists.xml.gz";
/** name of the file to backup the playlistfile to */
private static final String PLAYLISTS_GZ_BACKUP_FILENAME = "data" + File.separator + "playlists.xml.gz.bak";
/** name of the file all playlists are serialized to */
private static final String PLAYLISTS_FILENAME = "data" + File.separator + "playlists.xml";
/** name of myPods preferences file */
private static final String PREFERENCES_GZ_FILENAME = "data" + File.separator + "preferences.xml.gz";
/** name of the file the playlist file is backed up to */
private static final String PREFERENCES_GZ_BACKUP_FILENAME = "data" + File.separator + "preferences.xml.bak.gz";
/** name of the file all playlists are serialized to */
private static final String PREFERENCES_FILENAME = "data" + File.separator + "preferences.xml";
/** iPod mapper filename */
private static final String IPOD_MAPPER_FILENAME = "data/ipodmapper.xml";
/** data pool */
private DataPool dataPool = null;
/** model for the list of all playlists */
private DefaultListModel playlistListModel;
/** model for the spreader - a list of all artists / albums / genres of a playlist */
private DefaultListModel spreaderListModel;
/** table model for list view */
private ClipsTableModel clipsListTableModel;
/** myPod preferences */
private Preferences preferences = null;
/** iPod object */
IPod iPod = null;
// ------------------------------------- BACKEND STARTUP AND SHUTDOWN HELPERS --------------------------------------
/** Creates a new instance of Backend
* <BR>- deserialize preferences
* <BR>- initialize datapool & ipod
* <BR>- deserialize playlists
* <BR>- validate playlists
* <BR>- initialize list view table model
*/
public Backend()
{
logger.entering("Backend", "Backend");
// try to deserialize preferences
boolean success = deserializePreferences();
if(success != true)
{
logger.severe("Creating new preferences!!!");
preferences = new Preferences();
}
// try to deserialize playlists
success = deserializePlaylists();
if(success != true)
{
logger.info("New Playlist List objects created.");
this.playlistListModel = new DefaultListModel();
// add autoplaylist
createAutoPlaylist(GuiUtils.getStringLocalized("allMyMusic"));
}
// initialize spreader list model
this.spreaderListModel = new DefaultListModel();
// initialize data pool
dataPool = new DataPool();
// deserialize data
success = dataPool.deserializeData();
if( success != true )
{
logger.info("New data object created.");
dataPool.setData( new Hashtable() );
}
// create filename cache
dataPool.rebuildFilenameCache();
// validate playlists
validatePlaylists();
// initialize iPod object
iPod = new IPod();
// init list view model from first playlist (which always exist...)
clipsListTableModel = new ClipsTableModel( (Playlist)this.playlistListModel.getElementAt(0) );
logger.exiting("Backend", "Backend");
}
/** shuts the backend down.
* <BR>- serialzie myPod preferences
* <BR>- serialize playlists
* <BR>- shut down the data pool
*/
public void shutdown()
{
serializePreferences();
serializePlaylists();
dataPool.shutdown();
}
/** Gets the data pool.
*
* @return current data pool
*/
protected DataPool getDataPool()
{
return dataPool;
}
/** get list of playlists
*
* @return list of playlists
*/
protected DefaultListModel getPlaylistList()
{
return this.playlistListModel;
}
/** get spreader list model
*
* @param columnCode for the column to get a model for
* @param playlistIdx index of playlist to collect list items from
* @return list model containing a distinct selection of the specified column, ordered
*/
protected DefaultListModel getSpreaderListModel( int columnCode, int playlistIdx )
{
// get the content for the selected column
Vector content;
switch( columnCode )
{
case ClipsTableUtils.ARTIST_INDEX:
content = this.getDataPool().getAllArtistValues( this.getPlaylist(playlistIdx).getAllClips(), true );
break;
case ClipsTableUtils.ALBUM_INDEX:
content = this.getDataPool().getAllAlbumValues( this.getPlaylist(playlistIdx).getAllClips(), true );
break;
case ClipsTableUtils.GENRE_INDEX:
content = this.getDataPool().getAllGenreValues( this.getPlaylist(playlistIdx).getAllClips(), true );
break;
default:
content = new Vector(1);
}
// initialize model for the column
this.spreaderListModel.removeAllElements();
this.spreaderListModel.ensureCapacity( content.size() );
Iterator contentIter = content.iterator();
while( contentIter.hasNext() )
{
this.spreaderListModel.addElement( contentIter.next() );
}
return this.spreaderListModel;
}
// axelwe: unused method
// /** Gets the spreader list model
// * @return spreander list model
// */
// private DefaultListModel getSpreaderListModel()
// {
// return spreaderListModel;
// }
// /** get the TableModel
// * @return table model for the playlist
// */
// private ClipsTableModel getClipsListTableModel()
// {
// return clipsListTableModel;
// }
/** get the TableModel with data for a specific playlist
*
* @param index index of the playlist in the list of playlists
* @return table model for the playlist
*/
private ClipsTableModel getClipsListTableModel(int index)
{
// determine playlist
Playlist playlist = (Playlist)this.playlistListModel.get(index);
return getClipsListTableModel( playlist );
}
/** get the TableModel with data for a specific playlist
*
* @param playlist to get the model for
* @return table model for the playlist
*/
protected ClipsTableModel getClipsListTableModel(Playlist playlist)
{
// determine playlist
if( clipsListTableModel.getPlaylist() == null
|| !clipsListTableModel.getPlaylist().equals( playlist ) )
{
// set playlist
clipsListTableModel.setPlaylist( playlist );
}
return clipsListTableModel;
}
// ---------------------------------------------------- PLAYLIST HELPERS -------------------------------------------
/** Adds a playlist to the list of playlists
* @param playlist to add
*/
public void addPlaylist(Playlist playlist)
{
if( playlist != null )
{
this.getPlaylistList().addElement(playlist);
}
}
/** creates a new playlist.
*
* @param name name of the new playlist
* @return new created playlist
*/
public Playlist createPlaylist( String name )
{
// create new playlist
Playlist playlist = new Playlist(name);
this.playlistListModel.addElement(playlist);
return playlist;
}
/** creates a new auto playlist
*
* @param name name of the new autoplaylist
* @return index of the new autoplaylist in the list of playlists
*/
public Playlist createAutoPlaylist( String name )
{
// create new autoplaylist
Playlist playlist = new AutoPlaylist(name);
this.playlistListModel.addElement(playlist);
return playlist;
}
/** deletes a playlist
* @param index index of the playlist to delete in the list of playlists
*/
public void removePlaylist( int index )
{
this.playlistListModel.remove(index);
clipsListTableModel.setPlaylist(null);
}
/** Removes a playlist
* @param playlist to remove
*/
public void removePlaylist( Playlist playlist )
{
this.playlistListModel.removeElement(playlist);
clipsListTableModel.setPlaylist(null);
}
/** Gets a playlist by its index
* @return the playlist
* @param index index of the playlist in the list of playlists
*/
protected Playlist getPlaylist(int index)
{
return (Playlist)this.playlistListModel.get(index);
}
/** Gets a playlist by its name, or null if it not exists...
* @param name of the playlist to get
* @return first playlist found for the name given as argument
*/
public Playlist getPlaylist( String name )
{
Playlist foundList = null;
// iterate over all playlists
Playlist currList;
boolean found = false;
for( Enumeration playlistIter = this.getPlaylistList().elements(); !found && playlistIter.hasMoreElements(); )
{
currList = (Playlist)playlistIter.nextElement();
if( currList.getName().equals(name) )
{
foundList = currList;
found = true;
}
}
return foundList;
}
/** Applies the filters to an autoplaylist
* <BR>- get the playlist
* <BR>- check if we have an autoplaylist
* <BR>- get all enabled filters
* <BR>- remove clips from the playlist if they not apply to the filter (anymore)
* <BR>- find all clips that apply to the filter
* <BR>- add found clips, if they are not in the playlist yet
* <BR>- update playtime for the playlist
*
* @param index index of the playlist in the list of playlists
*/
public void updateAutoplaylist(int index)
{
Playlist playlist = this.getPlaylist(index);
if( playlist.isAutoplaylist() )
{
((AutoPlaylist)playlist).update( null, this.dataPool );
}
}
/** Applies the filters to an autoplaylist
* <BR>- get the playlist
* <BR>- check if we have an autoplaylist
* <BR>- get all enabled filters
* <BR>- remove clips from the playlist if they not apply to the filter (anymore)
* <BR>- find all clips that apply to the filter
* <BR>- add found clips, if they are not in the playlist yet
* <BR>- update playtime for the playlist
*
* @param playlist to update
* @param oids to update the playlist to
*/
public void updateAutoplaylist( Playlist playlist, List oids )
{
if( playlist.isAutoplaylist() )
{
((AutoPlaylist)playlist).update( oids, this.dataPool );
}
}
/** Update all autoplaylists
* <BR>- iterate over all playlists and update the autoplaylists
* <BR>- additionally total time and total filesize are validated
*/
public void updateAllAutoplaylists()
{
Playlist playlist;
int size = this.playlistListModel.size();
for( int i = 0; i < size; i++ )
{
playlist = this.getPlaylist(i);
if( playlist.isAutoplaylist() )
{
((AutoPlaylist)playlist).update( null, this.dataPool );
}
}
}
/** Validates all playlists.
* Each entry in each playlists is checked.
* If the entry (oid) is not contained in the data pool, its removed from the playlist.
* Attention: This is pretty time consuming!
*/
public void validatePlaylists()
{
logger.entering("Backend", "validatePlaylists");
// do it for all playlists
Playlist playlist;
Vector oids;
Long oid;
// check each playlist
int playlistCnt = this.playlistListModel.size();
for( int i = 0; i < playlistCnt; i++ )
{
// get playlist
playlist = (Playlist)this.playlistListModel.get(i);
oids = playlist.getList();
long validCnt = 0;
long invalidCnt = 0;
if( playlist != null )
{
// check that there is no key ( oid ) without meta data object...
for( int idx = oids.size()-1; idx >= 0; idx--)
{
oid = (Long)oids.get(idx);
if( oid == null || getDataPool().getMeta(oid) == null )
{
logger.warning("oid " + oid + " was invalid, removing entry");
oids.removeElementAt(idx);
invalidCnt++;
}
else
{
validCnt++;
}
} // for all clips of the playlist
}
// log if there was something to correct
if( invalidCnt > 0 )
{
logger.info("checking playlist " + playlist.getName()
+ " resulted in " + validCnt + " , but " + invalidCnt + " invalid clips." );
}
} // for all playlists
logger.exiting("Backend", "validatePlaylists");
} // validate playlists
/** Gets the total time of a couple of clips
*
* @param oids of the clips to summarize duration for
* @return summarized duration of the clips in oids
*/
public int getTotalTime( Vector oids )
{
int totalTime = 0;
// iterate over all oids to summarize clip duration
Iterator oidIter = oids.iterator();
while( oidIter.hasNext() )
{
totalTime += dataPool.getMeta( (Long)oidIter.next() ).getDuration();
}
return totalTime;
}
/** Gets the total filesize of a couple clips.
*
* @param oids to summarize filesize
* @return summarized filesize
*/
public long getTotalFilesize( Vector oids )
{
long totalFileSize = 0;
// iterate over all oids to summarize clip duration
Iterator oidIter = oids.iterator();
while( oidIter.hasNext() )
{
totalFileSize += dataPool.getMeta( (Long)oidIter.next() ).getFilesize();
}
return totalFileSize;
}
// ---------------------------------------------------- ACTION HELPERS -------------------------------------------
/** serializes all playlists
*/
private void serializePlaylists()
{
logger.entering("Backend", "serializePlaylists()");
// create backup file
File playlistFile = new File(PLAYLISTS_GZ_FILENAME);
if( playlistFile.exists() )
{
FileUtils.copy( playlistFile, new File(PLAYLISTS_GZ_BACKUP_FILENAME) );
}
// since jdk 1.4 has a problem to serialize javax.swing.DefaultListModel to xml, lets copy the content in
// a simple Vector
Vector playlists = new Vector( this.playlistListModel.size() );
int modelSize = this.playlistListModel.size();
for( int i = 0; i < modelSize; i++)
{
playlists.addElement( this.playlistListModel.get(i) );
}
try
{
XMLEncoder xe = new XMLEncoder( new GZIPOutputStream( new FileOutputStream(playlistFile), 65535));
xe.writeObject(playlists);
xe.close();
}
catch(Exception e)
{
logger.warning("Exception raised: " + e.getMessage() );
e.printStackTrace();
}
logger.exiting("Backend", "serializePlaylists()");
}
/** deserializes all playlists
* <BR>- check if file exists
* <BR>- heck if file is writable, if not wait and retry
* <BR>- deserialize vector of playlists
* <BR>- copy playlists into a default list model
* @return success
*/
private boolean deserializePlaylists()
{
logger.entering("Backend", "deserializePlaylists()");
logger.info("deserializing playlists");
boolean success = false;
File playlistFile = null;
Vector playlists = null;
// try original playlist file
try
{
playlistFile = new File( PLAYLISTS_GZ_FILENAME );
if( FileUtils.isWritable( playlistFile, 100000 ) )
{
// deserialize vector of playlists
XMLDecoder xd = new XMLDecoder( new GZIPInputStream( new FileInputStream(playlistFile), 65535));
playlists = (Vector)xd.readObject();
xd.close();
success = true;
}
}
catch( Exception e ) { logger.warning("Exception raised: " + e.getMessage() ); }
// try backup playlist file
if( !success )
{
logger.warning("Deserializing Playlists from backup file");
try
{
playlistFile = new File( PLAYLISTS_GZ_BACKUP_FILENAME );
if( FileUtils.isWritable( playlistFile, 100000 ) )
{
// deserialize vector of playlists
XMLDecoder xd = new XMLDecoder( new GZIPInputStream( new FileInputStream(playlistFile), 65535));
playlists = (Vector)xd.readObject();
xd.close();
success = true;
}
}
catch( Exception e ) { logger.warning("Exception raised: " + e.getMessage() ); }
}
// try old unzipped playlist file
if( !success )
{
logger.warning("Deserializing Playlists from old unzipped file");
try
{
playlistFile = new File( PLAYLISTS_FILENAME );
if( FileUtils.isWritable( playlistFile, 100000 ) )
{
// deserialize vector of playlists
XMLDecoder xd = new XMLDecoder( new BufferedInputStream( new FileInputStream(playlistFile), 65535));
playlists = (Vector)xd.readObject();
xd.close();
success = true;
}
}
catch( Exception e ) { logger.warning("Exception raised: " + e.getMessage() ); }
}
if( success )
{
// copy playlists into a default list model
this.playlistListModel = new DefaultListModel();
int size = playlists.size();
for( int i = 0; i<size; i++)
{
this.playlistListModel.addElement( playlists.get(i) );
}
}
logger.exiting("Backend", "deserializePlaylists()");
return success;
}
/** Gets the myPod preferences
* @return myPod preferences
*/
public Preferences getPreferences()
{
return preferences;
}
/** Sets myPod preferences
* @param prefs to set
*/
public void setPreferences( Preferences prefs )
{
preferences = prefs;
}
/** serializes all preferences
* <BR>- encode and save prefs to file
*
* @return success
*/
private boolean serializePreferences()
{
logger.entering("Backend", "serializePreferences()");
boolean result = false;
File preferencesFile = new File( Backend.PREFERENCES_GZ_FILENAME );
if( preferencesFile.exists() )
{
FileUtils.copy( preferencesFile, new File(PREFERENCES_GZ_BACKUP_FILENAME) );
}
try
{
XMLEncoder xe = new XMLEncoder( new GZIPOutputStream( new FileOutputStream(preferencesFile),65535 ) );
xe.writeObject(this.preferences);
xe.close();
result = true;
}
catch(Exception e)
{
logger.warning("Exception raised: " + e.getMessage() );
e.printStackTrace();
}
logger.exiting("Backend", "serializePreferences()");
return result;
}
/** Deserializes myPods preferences
* <BR>- check if the file exists
* <BR>- check if the file is writable
* <BR>- load and decode preferences file
*
* @return success
*/
private boolean deserializePreferences()
{
logger.entering("Backend", "deserializePreferences()");
logger.info("deserializing preferences");
boolean success = false;
File prefsFile = null;
// try original preferences file
try
{
prefsFile = new File( PREFERENCES_GZ_FILENAME );
if( FileUtils.isWritable( prefsFile, 100000 ) )
{
// load and decode prefs file
XMLDecoder xd = new XMLDecoder( new GZIPInputStream( new FileInputStream(prefsFile), 65535));
this.preferences = (Preferences)xd.readObject();
xd.close();
success = true;
}
}
catch( Exception e ) { logger.warning("Exception raised: " + e.getMessage() ); }
// try backup preferences file
if( !success )
{
logger.warning("Deserializing preferences from backup file");
try
{
prefsFile = new File( PREFERENCES_GZ_BACKUP_FILENAME );
if( FileUtils.isWritable( prefsFile, 100000 ) )
{
// load and decode prefs file
XMLDecoder xd = new XMLDecoder( new GZIPInputStream( new FileInputStream(prefsFile), 65535));
this.preferences = (Preferences)xd.readObject();
xd.close();
success = true;
}
}
catch( Exception e ) { logger.warning("Exception raised: " + e.getMessage() ); }
}
// try old, unzipped preferences file
if( !success )
{
logger.warning("Deserializing preferences from old unzipped file");
try
{
prefsFile = new File( PREFERENCES_FILENAME );
if( FileUtils.isWritable( prefsFile, 100000 ) )
{
// load and decode prefs file
XMLDecoder xd = new XMLDecoder( new BufferedInputStream( new FileInputStream(prefsFile), 65535));
this.preferences = (Preferences)xd.readObject();
xd.close();
success = true;
}
}
catch( Exception e ) { logger.warning("Exception raised: " + e.getMessage() ); }
}
logger.exiting("Backend", "deserializePreferences()");
return success;
}
/** creates a new playlist from an m3u file.
* <BR>- determine name of the playlist from filename
*
* @param file m3u playlist
* @return playlist loaded from file
*/
public Playlist loadPlaylistM3U( File file )
{
logger.entering("Backend", "loadPlaylistM3U");
Playlist playlist = null;
try
{
// determine name of the playlist from filename
String name = file.getName();
if( name.toLowerCase().endsWith(".m3u" ) )
{
name = name.substring( 0, name.length()-4 );
}
// open file and get a buffered reader
BufferedReader br = new BufferedReader( new java.io.InputStreamReader( new FileInputStream( file ) ) );
Vector oids = new Vector();
Long oid = null;
Vector artistFilter = new Vector();
Vector genreFilter = new Vector();
Vector yearFilter = new Vector();
// read the file line by line and parse m3u playlist
String line = br.readLine();
while(line != null)
{
try
{
line.trim();
// check if we have a line with path and filename
if( !line.startsWith("#") )
{
// try to find file in the data pool
oid = getDataPool().getOid(line);
// add clip to playlist
if(oid != null)
{
oids.add(oid);
}
else
{
logger.info("unable to find clip " + line + " in the data pool.");
}
}
else
{
// check for filter definition
if( line.startsWith("#mypod artist") )
{
artistFilter.add( line.substring(13).trim() );
}
else if( line.startsWith("#mypod genre") )
{
genreFilter.add( line.substring(12).trim() );
}
else if( line.startsWith("#mypod year") )
{
yearFilter.add( Integer.valueOf( line.substring(11).trim() ));
}
}
// read next line
line = br.readLine();
}
catch( Exception e ) { ; }
}
// close file
br.close();
// create a new playlist object
if( artistFilter.size() > 0 || genreFilter.size() > 0 || yearFilter.size() > 0 )
{
// create autoplaylist and add filter
playlist = new AutoPlaylist(name);
if( artistFilter.size() > 0 )
{
((AutoPlaylist)playlist).setArtistFilter( artistFilter );
((AutoPlaylist)playlist).setArtistFilterEnabled(true);
}
if( genreFilter.size() > 0 )
{
((AutoPlaylist)playlist).setGenreFilter( genreFilter );
((AutoPlaylist)playlist).setGenreFilterEnabled(true);
}
if( yearFilter.size() > 0 )
{
((AutoPlaylist)playlist).setYearFilter( yearFilter );
((AutoPlaylist)playlist).setYearFilterEnabled(true);
}
}
else
{
// create playlist
playlist = new Playlist(name);
}
// add clips
playlist.addClips(oids);
}
catch(Exception e)
{
logger.warning("exception raised: " + e.getMessage());
e.printStackTrace();
}
logger.exiting("Backend", "loadPlaylistM3U");
return playlist;
} // import playlist
/** Saves a playlist as m3u file.
* <br>- make sure, that the filename ends to .m3u
* <br>- create file
* <br>- write file header
* <br>- write filter information for autoplaylists
* <br>-
*
* @param filename of the playlist
* @param playlist to save
*/
public void savePlaylistM3U( String filename, Playlist playlist )
{
try
{
// make sure, that the filename ends to .m3u
if( !filename.endsWith(".m3u") && !filename.endsWith(".M3U")
&& !filename.endsWith(".M3u") && !filename.endsWith(".m3U") )
{
filename += ".m3u";
}
// open file
BufferedOutputStream fos = new BufferedOutputStream( new FileOutputStream( new File(filename) ) );
// write file header
fos.write(("#EXTM3U" + "\n").getBytes());
// write filter infos
if( playlist.isAutoplaylist() )
{
Iterator filterIter;
Vector filter = ((AutoPlaylist)playlist).getArtistFilter();
if( filter != null )
{
filterIter = filter.iterator();
while( filterIter.hasNext() )
{
fos.write(("#mypod artist " + filterIter.next() + "\n").getBytes());
}
}
filter = ((AutoPlaylist)playlist).getGenreFilter();
if( filter != null )
{
filterIter = filter.iterator();
while( filterIter.hasNext() )
{
fos.write(("#mypod genre " + filterIter.next() + "\n").getBytes());
}
}
filter = ((AutoPlaylist)playlist).getYearFilter();
if( filter != null )
{
filterIter = filter.iterator();
while( filterIter.hasNext() )
{
fos.write(("#mypod year " + filterIter.next() + "\n").getBytes());
}
}
}
// append all tracks
MP3Meta meta;
Vector oids = playlist.getList();
Iterator oidIter = oids.iterator();
while( oidIter.hasNext() )
{
meta = getDataPool().getMeta( (Long)oidIter.next() );
fos.write( new StringBuffer("#EXTINF:").append(meta.getDuration()).append(",")
.append(meta.getArtist()).append(" - ").append(meta.getTitle())
.append("\n").toString().getBytes()
);
fos.write( new StringBuffer(meta.getFilePath()).append("\n").toString().getBytes() );
}
// close file
fos.close();
}
catch( java.io.FileNotFoundException e)
{
JOptionPane.showMessageDialog( null,
GuiUtils.getStringLocalized( "resource/language","couldNotWritePlaylistTo")
+ ": \n" + filename + "\n"
+ GuiUtils.getStringLocalized("makeSureAllDirsExistAndYouAreAllowedToWriteInto")
+ ".",
GuiUtils.getStringLocalized("anErrorOccured"),
JOptionPane.ERROR_MESSAGE
);
}
catch(Exception e)
{
logger.warning("Exception raised: " + e.getMessage() );
e.printStackTrace();
}
} // export playlist
/** Removes clips from myPod
* First the clip is removed from all playlist, the from data pool.
*
* @param oids of the clips to delete
*/
public void removeClipsFromMyPod(Vector oids)
{
logger.entering("Backend", "removeClipsFromMyPod");
// do it for all clips
Iterator iter = oids.iterator();
while(iter.hasNext())
{
// remove clip from myPod
this.removeClipFromMyPod( (Long)iter.next() );
}
logger.exiting("Backend", "removeClipsFromMyPod");
}
/** Removes a clip from myPod
* First the clip is removed from all playlist, the from data pool.
*
* @param oid of the clip to remove
*/
private void removeClipFromMyPod(Long oid)
{
logger.entering("Backend", "removeClipFromMyPod");
logger.fine("deleting oid:" + oid);
// remove clip from all playlists - DO THIS BEFORE REMOVING THE CLIP FROM DATA POOL
int listCnt = this.playlistListModel.size();
for( int i = 0; i < listCnt; i++ )
{
getPlaylist(i).remove(oid);
if( logger.isLoggable( Level.FINE ) )
{
logger.fine("removed oid: " + oid + " from playlist at " + i);
}
}
// if we are in an spreader view, the playlist displayed must be handled here ...
if( !this.playlistListModel.contains( this.clipsListTableModel.getPlaylist() )
&& this.clipsListTableModel.getPlaylist().containsClip(oid) )
{
this.clipsListTableModel.getPlaylist().remove(oid);
}
// remove clip from data pool
dataPool.removeClip(oid);
logger.exiting("Backend", "removeClipFromMyPod");
}
/** Deletes clips from myPod and filesystem.
*
* @param oids to delete media files for
*/
public void deleteClips(Vector oids)
{
logger.entering("Backend", "deleteClips");
// do it for all clips
Iterator iter = oids.iterator();
Long oid = null;
boolean deleted = false;
while(iter.hasNext())
{
oid = (Long)iter.next();
logger.fine("deleting oid:" + oid);
// remove clips media file
deleted = FileUtils.delete( new File( this.dataPool.getMeta(oid).getFilePath() ) );
// remove clip from all myPod
if( deleted ) { this.removeClipFromMyPod(oid); }
}
logger.exiting("Backend", "deleteClips");
}
/** Removes a list of clips vom a playlist
* @param playlist to remove clips from
* @param oids of the clips to remove
*/
public void removeClipsFromPlaylist( Playlist playlist, Vector oids )
{
Long oid = null;
// remove clips from playlist
playlist.remove( oids );
// if we are in an spreader view, the playlist displayed must be handled here ...
if( !this.playlistListModel.contains( this.clipsListTableModel.getPlaylist() ) )
{
for( Iterator clipIter = oids.iterator(); clipIter.hasNext(); )
{
oid = (Long)clipIter.next();
if( this.clipsListTableModel.getPlaylist().containsClip(oid) )
{
this.clipsListTableModel.getPlaylist().remove(oid);
}
}
}
}
/** Gets all clips that are missing.
* all clips in the data pool are checked for their files.
* If the file can not be opended, the oid is added to the
* vector of missing clips
*
* @return vector containing oids of missing clips or null, if action was canceled
* @param dialog to show the progress of the action
*/
public Vector scanForMissingMediaFiles(ProgressDialog dialog)
{
logger.entering("Backend", "scanForMissingMediaFiles");
Vector missingClips = new Vector();
Set oids = getDataPool().getAllOid();
Long oid = null;
String path = null;
DataPool dp = this.getDataPool();
// do some gui stuff
dialog.setStatusText(GuiUtils.getStringLocalized("searchingForMissingMediaFiles"));
dialog.setProgressMax(oids.size());
// iterate over all clips in the data pool
for( Iterator iter = oids.iterator(); iter.hasNext(); )
{
oid = (Long)iter.next();
path = dp.getMeta(oid).getFilePath();
// do some gui stuff
dialog.setProgressValue( dialog.getProgressValue() + 1 );
dialog.setClipText(dp.getMeta(oid).getFilename());
// check if the file exists
if( !new File(path).exists() )
{
missingClips.addElement(oid);
}
// check if user aborted reorganizing
if( Thread.interrupted() )
{
return null;
}
}
logger.fine( missingClips.size() + " missing clips found");
logger.exiting("Backend", "scanForMissingMediaFiles");
return missingClips;
}
/** serializes iPod mapper.
*
* @param mapper to serialize
*/
public void serializeIPodMapper(Hashtable mapper)
{
logger.entering("Backend", "serializeIPodMapper()");
try
{
XMLEncoder xe = new XMLEncoder( new BufferedOutputStream( new FileOutputStream(Backend.IPOD_MAPPER_FILENAME)));
xe.writeObject(mapper);
xe.close();
}
catch(Exception e)
{
logger.warning("Exception raised: " + e.getMessage() );
e.printStackTrace();
}
logger.exiting("Backend", "serializeIPodMapper()");
}
/** deserializes iPod mapper.
*
* @return mapper object
*/
private Hashtable deserializeIPodMapper()
{
logger.entering("Backend", "deserializeIPodMapper()");
Hashtable mapper = null;
try
{
XMLDecoder xd = new XMLDecoder( new BufferedInputStream( new FileInputStream(Backend.IPOD_MAPPER_FILENAME)));
mapper = (Hashtable)xd.readObject();
xd.close();
}
catch(Exception e)
{
logger.info("impapper not found");
}
logger.exiting("Backend", "deserializeIPodMapper()");
if( mapper == null )
{
mapper = new Hashtable();
logger.info("new iPod Mapper object created.");
}
return mapper;
} // deserialize iMapper
/** Synchronizes myPod playlists with iPod.
* <BR>- load iTunes database from iPod
* <BR>- load iMapper
* <BR>- determine all clips to synchronize
* <BR>- determine clips to remove from iPod
* <BR>- determine clips to move to iPod
* <BR>- check space left on iPod
* <BR>- remove clips from iPod
* <BR>- remove empty playlists from iPod
* <BR>- copy clips to iPod
* <BR>- create playlists on iPod
* <BR>- save iTunes database to iPod
* <BR>- serialize iMapper
*
* @param dialog to show progress
* @return space left on iPod after sync in bytes
*/
public long synchronizeIPod(de.axelwernicke.mypod.gui.IPodSyncDialog dialog)
{
// get iTunes DB
dialog.totalProgressBar.setIndeterminate(true);
dialog.statusContentLabel.setText(GuiUtils.getStringLocalized("loadingDababase"));
iPod.getITunesDB();
dialog.totalProgressBar.setIndeterminate(false);
// deserialize iPod Mapper, this hashmap contains oids as key and iPod fileindizes as content.
Hashtable iMapper = deserializeIPodMapper();
// set dialog
dialog.statusContentLabel.setText(GuiUtils.getStringLocalized("determiningFilesToSync"));
dialog.totalProgressBar.setValue(5);
// get a list of all oids to synchronize to the iPod
Vector syncOids = getClipsToSync();
// check clips to remove from iPod, clipsToRemove contains oids
Vector clipsToRemove = getClipsToRemoveFromIPod( syncOids, iMapper );
long removeSize = iPod.getClipsSize(clipsToRemove, iMapper);
// check clips to move to iPod
Vector clipsToMove = getClipsToMoveToIPod( syncOids, iMapper );
long moveSize = getClipsTotalSize(clipsToMove);
// check free space on iPod
long spaceLeft = iPod.getDiscSpaceFree() - moveSize + removeSize;
if( spaceLeft > 0 )
{
// update dialog
dialog.statusContentLabel.setText(GuiUtils.getStringLocalized("removingClips"));
dialog.totalProgressBar.setValue(10);
// remove clips from iPod
iPod.removeClips( clipsToRemove, iMapper, dialog );
// remove empty playlists
iPod.removeEmptyPlaylists();
// copy clips to iPod
dialog.statusContentLabel.setText( GuiUtils.getStringLocalized("copyingFiles") );
dialog.totalProgressBar.setValue(15);
dialog.totalSizeContent.setText( GuiUtils.formatFilesize(moveSize) );
iPod.addClips( dataPool, clipsToMove, iMapper, dialog );
// create playlists
dialog.statusContentLabel.setText(GuiUtils.getStringLocalized("creatingPlaylists"));
dialog.totalProgressBar.setValue(90);
iPod.createPlaylists( this.playlistListModel, iMapper, dialog );
// update dialog
dialog.statusContentLabel.setText(GuiUtils.getStringLocalized("savingDatabase"));
dialog.totalProgressBar.setValue(95);
// save iTunes DB
dialog.totalProgressBar.setIndeterminate(true);
iPod.saveITunesDB();
dialog.totalProgressBar.setIndeterminate(false);
// update dialog
dialog.totalProgressBar.setValue(100);
// serialize iMapper
serializeIPodMapper(iMapper);
}
return spaceLeft;
}
/** Gets all clips to synchronize with iPod
*
* @return vector of all clips to synchronize
*/
private Vector getClipsToSync()
{
Vector syncOids = new Vector();
Playlist playlist = null;
Long clip = null;
// iterate over all playlists
int size = this.playlistListModel.getSize();
for( int i = 0; i < size; i++)
{
// get playlist
playlist = getPlaylist(i);
// check if playlist is synchronized to iPod
if( playlist.isIPodSync() )
{
// iterate over all clips in the playist
int listSize = playlist.getTotalClips();
for(int y = 0; y < listSize; y++)
{
// get current clip
clip = playlist.getClipAt(y);
// check if clip is in result set already
if( !syncOids.contains( clip ) )
{
syncOids.addElement( clip );
}
} // for all clips
} // if playlist is ipod sync
} // for all playlists
return syncOids;
}
/** check clips to remove from iPod
* ->clips are to be removed if clip is on the iPod but not on a playlist to synchronize
*
* @param clipsToSync vector of oids - clips to synchronize
* @param iMapper mapping from oids to iPod song id
* @return fileIndex of the clips to remove
*/
private Vector getClipsToRemoveFromIPod( Vector clipsToSync, Hashtable iMapper )
{
Vector clips2Remove = new Vector();
Long oid = null;
// iterate over all oids on the iPod
for( Iterator iter = iMapper.keySet().iterator(); iter.hasNext(); )
{
oid = (Long)iter.next();
// clip must be removed, if it isn't in a playlist to sync
if( !clipsToSync.contains(oid) )
{
clips2Remove.addElement( oid );
}
}
logger.fine("found " + clips2Remove.size() + " clips to remove from iPod");
return clips2Remove;
} // getClipsToRemoveFromIPod
/** Gets clips to move to iPod
* ->clips are moved if clip is on a playlist, but not on the iPod
*
* @param syncOids oids of the clips to synchronize
* @param iMapper hashtable that defines which songs are synchronized yet
* @return vector of oids to move to iPod
*/
private Vector getClipsToMoveToIPod( Vector syncOids, Hashtable iMapper )
{
Vector clips2move = new Vector(syncOids.size());
Long oid = null;
// iterate over the playlist
for( Iterator iter = syncOids.iterator(); iter.hasNext(); )
{
oid = (Long)iter.next();
if( !iMapper.containsKey(oid) )
{
clips2move.addElement(oid);
}
}
logger.fine("found " + clips2move.size() + " clips to move to iPod");
return clips2move;
}
/** Gets the total count of clips known by myPods data pool
* - get the size of a list of oids for all clips
*
* @return total count of clips known managed by myPod
*/
public long getClipsTotalCount()
{
long result = -1;
try
{
result = getDataPool().getAllOid().size();
}
catch( Exception e )
{
logger.warning("Exception raised: " + e.getMessage() );
e.printStackTrace();
}
return result;
}
/** Gets the total size of all clips known by myPods data pool
* - get a list of oids for all clips
* <BR>- summarize the size of each clip
*
* @return total size of clips known managed by myPod in bytes
*/
public long getClipsTotalSize()
{
long result = 0;
try
{
Set oids = getDataPool().getAllOid();
for( Iterator oidIter = oids.iterator(); oidIter.hasNext(); )
{
result += dataPool.getMeta((Long)oidIter.next()).getFilesize();
}
}
catch( Exception e )
{
logger.warning("Exception raised: " + e.getMessage() );
e.printStackTrace();
result = -1;
}
return result;
}
/** Gets the total duration of all clips known by myPods data pool
* - get a list of oids for all clips
* <BR>- summarize the duration of each clip
*
* @return total duration of clips known managed by myPod
*/
public long getClipsTotalTime()
{
long result = 0;
try
{
Set oids = getDataPool().getAllOid();
for( Iterator oidIter = oids.iterator(); oidIter.hasNext(); )
{
result += dataPool.getMeta((Long)oidIter.next()).getDuration();
}
}
catch( Exception e )
{
logger.warning("Exception raised: " + e.getMessage() );
e.printStackTrace();
result = -1;
}
return result;
}
/** Gets the summarized filesize for all clips.
* It tries to determine clip size from local db via oid. The oid _must_ be known by myPod!
*
* @param oids vector of oids to summarize filesizes
* @return filesize of all specified oids
*/
public long getClipsTotalSize( Vector oids )
{
long size = 0;
MP3Meta meta;
DataPool dp = this.getDataPool();
for( Iterator iter = oids.iterator(); iter.hasNext(); )
{
meta = dp.getMeta((Long)iter.next());
if( meta != null )
{
size += meta.getFilesize();
}
}
logger.fine("summarized size of " + oids.size() + " clips was " + size);
return size;
}
/** Sends a playlist to an external player
* <BR>- determine parameter (add or append)
* <BR>- check that tmp directory exists to store playlist in
* <BR>- check that configured player can be found
* <BR>- store playlist
* <BR>- call player
*
* @param playlist to play
* @param append if true, playlist is appended to the clips on the player
*/
public void playExtern( Playlist playlist, boolean append )
{
if( playlist != null )
{
try
{
String parameter = (append) ? preferences.getAppendParameter() : preferences.getAddParameter();
String fs = File.separator;
// check external player
String playerPath = preferences.getPlayerPath();
if( !new File(playerPath).exists() )
{
JOptionPane.showMessageDialog( null, GuiUtils.getStringLocalized("couldNotFindExternalPlayer") + ": \n" + playerPath,
GuiUtils.getStringLocalized("checkConfiguration"), JOptionPane.ERROR_MESSAGE );
return;
}
// create tmp playlist
String playlistName = System.getProperty("user.dir") + fs + "tmp" + fs + "play.m3u";
savePlaylistM3U( playlistName, playlist );
// create and execute command
String command = "\"" + playerPath + "\" " + parameter + " \"" + playlistName + "\"";
java.lang.Runtime.getRuntime().exec(command);
}
catch(Exception e)
{
logger.warning("Exception occured while trying to start external player :" + e.getMessage() );
e.printStackTrace();
}
}
}
/** Getter for property iPod.
*
* @return Value of property iPod.
*/
public IPod getIPod()
{
return iPod;
}
/** Setter for property iPod.
*
* @param iPod New value of property iPod.
*/
public void setIPod(IPod iPod)
{
this.iPod = iPod;
}
/** Gets a Vector containing all clips that are below a given directory
* @param baseDirectory to determine clips below
* @return vector of oids
*/
private Vector getClipsBelowDirectory( String baseDirectory )
{
Vector oids = new Vector();
Long oid;
for( Iterator oidIter = this.getDataPool().getAllOid().iterator(); oidIter.hasNext(); )
{
oid = (Long)oidIter.next();
if( getDataPool().getMeta(oid).getFilePath().startsWith(baseDirectory + File.separator) )
{
oids.add(oid);
}
}
return oids;
}
/** Reorganizes filestructure and renames files based on id3 tags
*
* <BR>determine clips that are below base directory
* <BR>for all clips to reorganize: determine new pathname
* <BR>for all clips to reorganize: determine new filename
* <BR>for all clips to reorganize: create new file
* <BR>
*
* @param dialog reorganizing progress dialog
* @param removeEmptyDirectories flag, if true - empty directories are removed
* @param baseDirectory all files below are reorganized
* @param dirStructureIndex index that determines how the filestructure is reorganized
* @param filenameStructureIndex index that determines how the files are renamed
*/
public void reorganizeClips( de.axelwernicke.mypod.gui.ReorganizeClipsProgressDialog dialog,
String baseDirectory,
int dirStructureIndex,
int filenameStructureIndex,
boolean removeEmptyDirectories
)
{
logger.entering( "de.axelwernicke.mypod.Backend", "reorganizeClips" );
// statistics for gui
int filesMoved = 0;
int filesRenamed = 0;
boolean dirChanged, filenameChanged;
// do some gui stuff
dialog.statusContentLabel.setText(GuiUtils.getStringLocalized("determiningClipsToReorganize"));
dialog.totalProgressBar.setIndeterminate(true);
// determine clips that are below base directory
logger.fine("determining clips");
Long oid = null;
Vector oids = null;
if( dirStructureIndex != 0 || filenameStructureIndex != 0 )
{
oids = getClipsBelowDirectory( baseDirectory );
}
// check if user aborted reorganizing
if( Thread.interrupted() ) { return; }
// do some gui stuff
dialog.totalProgressBar.setIndeterminate(false);
dialog.totalProgressBar.setMaximum(oids.size());
MP3Meta meta = null;
String album, artist, genre, title, track = null;
String oldDirectoryName, newDirectoryName, newFilename = null;
File newFile, newDir = null;
// iterate over clips to reorganize
int size = oids.size();
for( int i = 0; i < size; i++ )
{
newFilename = null;
newFile = null;
newDir = null;
// get meta data for the current clip
oid = (Long)oids.get(i);
meta = getDataPool().getMeta(oid);
// get valid meta data values to create new directory and filenames from
album = FileUtils.validateDirectoryName(meta.getAlbum());
if( album == null || album.equals("") ) { album = GuiUtils.getStringLocalized("unknown"); }
artist = FileUtils.validateDirectoryName(meta.getArtist());
if( artist == null || artist.equals("") ) { artist = GuiUtils.getStringLocalized("unknown"); }
genre = FileUtils.validateDirectoryName(meta.getGenre());
if( genre == null || genre.equals("") ) { genre = GuiUtils.getStringLocalized("unknown"); }
title = FileUtils.validateDirectoryName(meta.getTitle());
if( title == null || title.equals("") ) { title = GuiUtils.getStringLocalized("unknown"); }
int tmpTrack = meta.getTrack();
if( tmpTrack >= 10 ) { track = String.valueOf(tmpTrack); }
else if( tmpTrack < 0 ) { track = "00"; }
else { track = "0" + String.valueOf(tmpTrack); }
// do some gui stuff
dialog.statusContentLabel.setText( GuiUtils.getStringLocalized("reorganizingClips") + " (" + i + "/" + oids.size() + ")" );
dialog.totalProgressBar.setValue(i);
dialog.clipContentLabel.setText( artist + " - " + title );
dialog.clipsMovedContentLabel.setText( String.valueOf(filesMoved) );
dialog.clipsRenamedContentLabel.setText(String.valueOf(filesRenamed) );
dialog.directoriesRemovedContentLabel.setText( String.valueOf(0) );
try
{
// determine new directory name
oldDirectoryName = meta.getFilePath().substring( 0, meta.getFilePath().lastIndexOf(File.separator));
switch( dirStructureIndex )
{
case 1: newDirectoryName = baseDirectory + File.separator + artist;
break;
case 2: newDirectoryName = baseDirectory + File.separator + artist + File.separator + album;
break;
case 3: newDirectoryName = baseDirectory + File.separator + genre;
break;
case 4: newDirectoryName = baseDirectory + File.separator + genre + File.separator + album;
break;
default: newDirectoryName = oldDirectoryName;
break;
}
// determine file name
switch( filenameStructureIndex )
{
case 1: newFilename = track + " - " + title + ".mp3" ;
break;
default: newFilename = meta.getFilename();
break;
}
// create new file
newFile = new File( newDirectoryName + File.separator + newFilename );
// check if directory change
dirChanged = !( new File(newDirectoryName).equals(new File(oldDirectoryName)) );
if( dirChanged )
{
filesMoved++;
logger.finer("dir changed from " + oldDirectoryName + " to " + newDirectoryName);
// check if the directory exists, create if not
newDir = new File( newDirectoryName );
if( !newDir.exists() ) { newDir.mkdirs(); }
if( !newDir.exists() || !newDir.canWrite() )
{
// if the dir is not there or not readable yet, we are in serious trouble...
throw new Exception("could not get directory " + newDir + " writable");
}
}
// check if filename changed
filenameChanged = !( new File(newFilename).equals(new File(meta.getFilename())) );
if(filenameChanged)
{
filesRenamed++;
logger.finer("filename changed from " + meta.getFilename() + " to " + newFilename);
// check if the file exists, change filename if so
if( newFile.exists() )
{
String tmpFileName = newFilename.substring(0, newFilename.lastIndexOf(".") );
int cnt = 0;
do
{
// check file exteded by counter
newFile = new File( newDirectoryName + File.separator + tmpFileName + " (" + cnt + ").mp3" );
cnt++;
}
while( newFile.exists() && cnt < 100000 );
}
if( newFile.exists() ) // if the dir is not there or not readable yet, we are in serious trouble...
{
throw new Exception("could not get new filename last try was: " + newFile );
}
}
// move file to new location
if( dirChanged || filenameChanged )
{
boolean success = FileUtils.move( new File( meta.getFilePath() ), newFile);
// change meta data
if(success)
{
dataPool.updateFilePath( oid, newFile.getPath() );
}
else
{
logger.info("moving from " + new File( meta.getFilePath() ) + " to " + newFile + " failed");
}
}
}
catch( Exception e)
{
logger.warning("exception raised: " + e.getMessage() );
}
// check if user aborted reorganizing
if( Thread.interrupted() ) { return; }
} // for all files to reorganize
// delete empty directories
if( removeEmptyDirectories )
{
int totalDirsDeleted = 0;
int dirsDeleted = 0;
// do some gui stuff
dialog.statusContentLabel.setText(GuiUtils.getStringLocalized("determiningDirectoriesToRemove"));
dialog.totalProgressBar.setIndeterminate(true);
// get all directories recursively
Vector dirs = FileUtils.getAllDirectories(new File(baseDirectory));
// while empty directories found
int cnt = 0;
do
{
dirsDeleted = FileUtils.deleteEmptyDirectories(dirs);
totalDirsDeleted += dirsDeleted;
cnt++;
// update gui
dialog.directoriesRemovedContentLabel.setText(String.valueOf(totalDirsDeleted));
// check if user aborted reorganizing
if( Thread.interrupted() ) { return; }
}
while( dirsDeleted != 0 && cnt < 50 );
logger.info( "" + totalDirsDeleted + " directories deleted in " + cnt + " loops" );
}
logger.exiting( "de.axelwernicke.mypod.Backend", "reorganizeClips" );
} // reorganizeClips
/** Relocates clips if their media files where moved.
*
* e.g: a:\bbb\ccc\ddd\fool.mp3 --> k:\lll\mmm\nnn\ddd\fool.mp3
* - baseSrc - | -- file -- -- baseDest -- | -- file --
*
* @param dialog to show progress
* @param missingClips clips where media file is missing
*/
public void relocateClips( ProgressDialog dialog, Collection missingClips )
{
Long oid;
MP3Meta meta;
Hashtable moves = new Hashtable();
Enumeration movesIter;
boolean found;
String oldLocation;
String newLocation;
String recentMoveSrc;
File recentPath = new File( this.getPreferences().getRecentScanPath() );
// prepare dialog
dialog.setStatusText( GuiUtils.getStringLocalized("relocateMediaFiles") );
dialog.setProgressBounds( 0, missingClips.size() );
dialog.setProgressValue(0);
// do it for all clips with missing media files
Iterator clipsIter = missingClips.iterator();
while( clipsIter.hasNext() )
{
try
{
//do some preparations for the clip
oid = (Long)clipsIter.next();
meta = this.getDataPool().getMeta(oid);
oldLocation = meta.getFilePath();
newLocation = "";
found = false;
// update dialog
dialog.setProgressValue( dialog.getProgressValue()+1 );
dialog.setClipText(oldLocation);
// check if a known move matches
movesIter = moves.keys();
while( !found && movesIter.hasMoreElements() )
{
recentMoveSrc = (String)movesIter.nextElement();
if( meta.getFilePath().startsWith(recentMoveSrc) )
{
// build potential new location and check if the new location exists
newLocation = moves.get(recentMoveSrc) + oldLocation.substring(recentMoveSrc.length() );
if( (new File( newLocation )).exists() )
{
found = true;
}
logger.fine("Tried " + newLocation + " as new location (recent move), result : " + found );
}
} // for all recent moves
if( !found )
{
// ask the user
JFileChooser fc = new JFileChooser();
fc.setDialogTitle( GuiUtils.getStringLocalized("findNewLocationFor") + " " + oldLocation );
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setMultiSelectionEnabled(false);
fc.setCurrentDirectory( recentPath );
int res = fc.showOpenDialog(dialog);
if( res == JFileChooser.APPROVE_OPTION)
{
if( fc.getSelectedFile().exists() )
{
newLocation = fc.getSelectedFile().toString();
recentPath = fc.getSelectedFile();
found = true;
}
logger.fine("Tried " + newLocation + " as new location (user selection), result : " + found );
}
}
if( !found )
{
// if still not found the user gave us nonsense ... ask for skip or abort
int result = JOptionPane.showInternalConfirmDialog( null,
GuiUtils.getStringLocalized("doYouWantToCancelTheAction"),
GuiUtils.getStringLocalized("pleaseConfirm"),
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE
);
if( result == JOptionPane.YES_OPTION )
{
dialog.interrupt();
}
}
else
{
// split base and extension to remember move
// first we need to know how far meta.getFilename and newLocation equal _from the end_ (!!)
int oldLength = oldLocation.length();
int newLength = newLocation.length();
int minLen = (oldLength < newLength) ? oldLength : newLength;
int equalChars = 0;
boolean equal;
do
{
equal = ( oldLocation.charAt( oldLength-1 - equalChars ) == newLocation.charAt( newLength-1 - equalChars ) );
}
while( equal && equalChars++ < minLen );
// extract and store base path
moves.put( oldLocation.substring(0, oldLength-equalChars), newLocation.substring(0, newLength-equalChars) );
logger.fine( "put new move: " + oldLocation.substring(0, oldLength-equalChars)
+ " : " + newLocation.substring(0, newLength-equalChars) );
// propagate changes to the data pool
dataPool.updateFilePath( oid, newLocation );
}
}
catch(Exception ex)
{
logger.warning("Exception raised: " + ex.getMessage() );
ex.printStackTrace();
}
// return if user cancelled the action
if( Thread.interrupted() ) { return; }
} // do for all clips with missing media files
}
}
|
[
"sloefke@238a1e63-2308-0410-860f-9c3f58a98e0c"
] |
sloefke@238a1e63-2308-0410-860f-9c3f58a98e0c
|
8470c2df98df6b9d8ad4fa8cc591a3d5e3001532
|
cad7bc29389fbf5d5b722ee5327ba8154e7cc952
|
/submissions/available/CPC/CPC-what-property/data/source/apacheDB-trunk/api/src/main/java/javax/jdo/query/CharacterExpression.java
|
c9b5b4b5d8f9cef21c903a2e019c9c966e849d8b
|
[
"Unlicense",
"Apache-2.0"
] |
permissive
|
XZ-X/CPC-artifact-release
|
f9f9f0cde79b111f47622faba02f08b85a8a5ee9
|
5710dc0e39509f79e42535e0b5ca5e41cbd90fc2
|
refs/heads/master
| 2022-12-20T12:30:22.787707
| 2020-01-27T21:45:33
| 2020-01-27T21:45:33
| 236,601,424
| 1
| 0
|
Unlicense
| 2022-12-16T04:24:27
| 2020-01-27T21:41:38
|
Java
|
UTF-8
|
Java
| false
| false
| 1,699
|
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 javax.jdo.query;
/**
* Representation of a character expression.
*/
public interface CharacterExpression extends ComparableExpression<Character>
{
/**
* Method to return a CharacterExpression representing this CharacterExpression in lower case.
* @return The lower case expression
*/
CharacterExpression toLowerCase();
/**
* Method to return a CharacterExpression representing this CharacterExpression in upper case.
* @return The upper case expression
*/
CharacterExpression toUpperCase();
/**
* Method to return an expression that is the current expression negated.
* @return The negated expression
*/
CharacterExpression neg();
/**
* Method to return an expression that is the complement of the current expression.
* @return The complement expression
*/
CharacterExpression com();
}
|
[
"161250170@smail.nju.edu.cn"
] |
161250170@smail.nju.edu.cn
|
e35f8934215376eab7ebbf601cbfbed67189ffa6
|
f46a177f35dc9587ba64b17d159e5a1c519b253f
|
/src/main/java/ml/socshared/gateway/service/impl/TextAnalyzerServiceImpl.java
|
966d36079f159df9dece2fe951f7f494374acfc1
|
[] |
no_license
|
SocShared/gateway-service
|
2d7dafb64bee7191944f331f8cf2f469c92c66dd
|
dec100103eac22acc6ab18a290e730d309167287
|
refs/heads/master
| 2022-11-14T19:08:34.651132
| 2020-06-26T07:33:50
| 2020-06-26T07:33:50
| 260,530,144
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,014
|
java
|
package ml.socshared.gateway.service.impl;
import lombok.RequiredArgsConstructor;
import ml.socshared.gateway.client.TextAnalyzerClient;
import ml.socshared.gateway.domain.text_analyzer.request.TextRequest;
import ml.socshared.gateway.domain.text_analyzer.response.KeyWordResponse;
import ml.socshared.gateway.security.model.TokenObject;
import ml.socshared.gateway.service.TextAnalyzerService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class TextAnalyzerServiceImpl implements TextAnalyzerService {
private final TextAnalyzerClient client;
@Value("#{tokenGetter.tokenTextService}")
private TokenObject textAnalyzerToken;
@Override
public List<KeyWordResponse> getKeyWords(String text, Integer minLength, Integer maxLength) {
return client.extractKeyWords(new TextRequest(text), minLength, maxLength, "Bearer " + textAnalyzerToken.getToken());
}
}
|
[
"vladovchinnikov950@gmail.com"
] |
vladovchinnikov950@gmail.com
|
a6f4fa1c96113aeaeac7d46b37401f6e5e762197
|
27f3ddc8ff6f5994fa1c0377dfbb0b7559f6aa90
|
/course1/paradigms/DoubleEquation/src/expression/exceptions/CheckedSqrt.java
|
209c9f456b7473f36a2aa2e8dddbf74012a82193
|
[] |
no_license
|
vlad-mk/ifmo-kt
|
8240d6e9be6aeffc2eb5287198a367c6e23d4f4c
|
7481e2977dc986339920fd0cc69b360bcfa3d072
|
refs/heads/master
| 2023-07-03T21:01:43.823212
| 2019-01-12T06:11:10
| 2019-01-12T06:11:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 694
|
java
|
package expression.exceptions;
public class CheckedSqrt extends CheckedUnaryOperation {
private static final int MAX = 46341;
public CheckedSqrt(TripleExpression expr) {
super(expr);
}
@Override
protected int count(int r) throws CountException {
if (r < 0) {
throw new CountException("sqrt " + r);
}
if(r < 2){
return r;
}
int min = 0, max = (r < MAX ? r : MAX), mid;
while (max - min > 1) {
mid = (max + min) >>> 1;
if (mid * mid > r) {
max = mid;
} else {
min = mid;
}
}
return min;
}
}
|
[
"egormkn@yandex.ru"
] |
egormkn@yandex.ru
|
715553e507d316d6ce7aeaaad682e3c3ac1bbe80
|
70b5ebd9fb015d793a30ed026bcc4417f3376b1a
|
/java/TeacherSignUp.java
|
ee5b1e211fdc8e3fb32d13f736f0a8c938e83134
|
[] |
no_license
|
vedantsawant/ClassManagementApp
|
00fcec50eab761472dd28b2000b6d717fff4e59f
|
1e1f0b5595ed22929637918643b8e9e123b12f1f
|
refs/heads/master
| 2022-12-22T11:40:45.440112
| 2020-09-30T05:30:34
| 2020-09-30T05:30:34
| 299,815,329
| 2
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 8,856
|
java
|
package in.autodice.classmanagementsystem;
import android.app.AlertDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import in.autodice.classmanagementsystem.R;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Pattern;
public class TeacherSignUp extends AppCompatActivity {
EditText etname,etcontact,etemail,etpassword;
Button btsubmit;
String email,name,password,contact,ADMINID,ct="";
ArrayAdapter adapter;
Spinner sp1;
String selectedSubject="",validate;
HttpServicesHelper helper;
TextView textView,checktext;
URL url;
HttpURLConnection connection;
OutputStream outputStream;
OutputStreamWriter outputStreamWriter;
BufferedWriter bufferedWriter;
InputStream inputStream;
InputStreamReader inputStreamReader;
BufferedReader bufferedReader;
String passkey="ydcYkdJhhArwijdoPslK";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teacher_sign_up);
getSupportActionBar().setTitle("Teacher Sign Up");
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //show back button
Bundle extras = getIntent().getExtras();
ADMINID= extras.getString("classid");
etname=findViewById(R.id.etname);
etcontact=findViewById(R.id.etcontact);
etemail=findViewById(R.id.etemail);
etpassword=findViewById(R.id.etpassword);
textView=findViewById(R.id.tvspsubject);
textView.setVisibility(View.INVISIBLE);
checktext=findViewById(R.id.checktext);
checktext.setVisibility(View.INVISIBLE);
btsubmit=findViewById(R.id.btsubmit);
sp1=findViewById(R.id.spinnerSubjectlist);
helper=new HttpServicesHelper(this);
helper.execute("getsubjectlist",ADMINID);
btsubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedSubject= (String) textView.getText();
validate=(String) checktext.getText();
Pattern emailpattern= Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$");
email = String.valueOf(etemail.getText()).trim();
if(etname.getText().length()==0 || etcontact.getText().length()==0 || etemail.getText().length()==0 || etpassword.getText().length()==0){
Toast.makeText(getBaseContext(),"Enter Complete Data",Toast.LENGTH_SHORT).show();
}
else if(etpassword.getText().length()<6) {
Toast.makeText(getBaseContext(),"Password Length is Too Short",Toast.LENGTH_SHORT).show();
}
else if (!emailpattern.matcher(email).matches()){
Toast.makeText(getBaseContext(),"Enter Vaild Email ID",Toast.LENGTH_SHORT).show();
}else if(selectedSubject.equals("")) {
Toast.makeText(getBaseContext(),"Select Subject",Toast.LENGTH_SHORT).show();
} else {
email = String.valueOf(etemail.getText()).trim();
name= String.valueOf(etname.getText()).trim();
password= String.valueOf(etpassword.getText()).trim();
contact= String.valueOf(etcontact.getText()).trim();
etname.setText("");
etpassword.setText("");
etemail.setText("");
etcontact.setText("");
Log.i("checkmsg", "Button clicked");
new TSignupHttp().execute("validcheck","teacher",name,selectedSubject,ADMINID);
/* if (ct.equals("success")){
HttpServicesHelper helper1=new HttpServicesHelper(getBaseContext());
helper1.execute("insertteacher",name,contact,email,selectedSubject,password,ADMINID);
Log.i("Checkmsg", "inside success");
}else if (ct.equals("fail")){
Log.i("Checkmsg", "inside failure");
AlertDialog.Builder builder=new AlertDialog.Builder(TeacherSignUp.this);
builder.setTitle("Alert").setMessage("Teacher having same name already added for selected subject.");
AlertDialog alert=builder.create();
alert.show();
}*/
}
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
@Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
public class TSignupHttp extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... strings) {
String baseURL = "https://autodice.in/projects/classmanagement/";
try {
String checktype = strings[1];
String name = strings[2];
String itsdata = strings[3];
String adm = strings[4];
Log.i("Checkmsg", "msg1");
url = new URL(baseURL + "checkteacher.php");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
outputStream = connection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
bufferedWriter = new BufferedWriter(outputStreamWriter);
String postdata = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8");
postdata += "&" + URLEncoder.encode("itsdata", "UTF-8") + "=" + URLEncoder.encode(itsdata, "UTF-8");
postdata += "&" + URLEncoder.encode("adminid", "UTF-8") + "=" + URLEncoder.encode(adm, "UTF-8");
postdata += "&" + URLEncoder.encode("passkey", "UTF-8") + "=" + URLEncoder.encode(passkey, "UTF-8");
Log.i("Checkmsg", postdata);
bufferedWriter.write(postdata);
bufferedWriter.flush();
bufferedWriter.close();
outputStreamWriter.close();
outputStream.close();
inputStream = connection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
connection.disconnect();
Log.i("Checkmsg", result);
return result;
} catch (MalformedURLException e) {
Log.i("ecx", String.valueOf(e));
e.printStackTrace();
} catch (IOException e) {
Log.i("ecx1", String.valueOf(e));
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String st = "";
Log.i("Checkmsg", s);
if (s.equals("failure")) {
ct="fail";
AlertDialog.Builder builder=new AlertDialog.Builder(TeacherSignUp.this);
builder.setTitle("Alert").setMessage("Teacher having same name already added for selected subject.");
AlertDialog alert=builder.create();
alert.show();
} else if (s.equals("success")){
ct="success";
Log.i("checkmsg:valid", s);
HttpServicesHelper helper1=new HttpServicesHelper(TeacherSignUp.this);
helper1.execute("insertteacher",name,contact,email,selectedSubject,password,ADMINID);
}
Log.i("Checkmsg", ct);
}
}
}
|
[
"vedant.sawant.2604@gmail.com"
] |
vedant.sawant.2604@gmail.com
|
02e08f7118b5fb971cc68bed7b5ead358c541d41
|
647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4
|
/com.tencent.mm/classes.jar/com/tencent/mm/plugin/account/ui/r$a.java
|
dd4b35c5da92d222129a35d036317c0ed188543b
|
[] |
no_license
|
tsuzcx/qq_apk
|
0d5e792c3c7351ab781957bac465c55c505caf61
|
afe46ef5640d0ba6850cdefd3c11badbd725a3f6
|
refs/heads/main
| 2022-07-02T10:32:11.651957
| 2022-02-01T12:41:38
| 2022-02-01T12:41:38
| 453,860,108
| 36
| 9
| null | 2022-01-31T09:46:26
| 2022-01-31T02:43:22
|
Java
|
UTF-8
|
Java
| false
| false
| 547
|
java
|
package com.tencent.mm.plugin.account.ui;
public final class r$a
{
public static final int anim_not_change = 2130771992;
public static final int anim_shake_horizontal = 2130772001;
public static final int push_down_in = 2130772139;
public static final int slide_left_out = 2130772170;
public static final int slide_right_in = 2130772175;
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes4.jar
* Qualified Name: com.tencent.mm.plugin.account.ui.r.a
* JD-Core Version: 0.7.0.1
*/
|
[
"98632993+tsuzcx@users.noreply.github.com"
] |
98632993+tsuzcx@users.noreply.github.com
|
945c727c922d51c19153332739c7da5c82a90e90
|
13bfac130c43d87377675c668755e529312bfa16
|
/20200422/src/TestDemo.java
|
37446565fc857507218d4e22a1fe9f5b555d5342
|
[] |
no_license
|
Coder-MinYi/Java-Code
|
684f8ac7c078cc24bde46959a8e089e973565fae
|
ac07b1a9f1afe193c69ed3783508181006b79d3c
|
refs/heads/master
| 2021-05-24T18:49:17.350809
| 2021-04-12T07:29:43
| 2021-04-12T07:29:43
| 253,704,614
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,272
|
java
|
/**
* Created with InteIIiJ IDEA.
* Description:
* User:MINYI
* Date:
* Time:
*/
class Person{
//实例成员变量
// public String name;
// public int age;
// public char ch;
// public boolean b;
// public double n;
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
//静态成员变量
public static int size = 10;//只有一份
//方法
public void eat(String eat){
System.out.println("eat");
}
public void sleep(int num){
System.out.println("num");
}
}
public class TestDemo {
public static void main(String[] args) {
Person per = new Person();
// System.out.println(per.name);
// System.out.println(per.age);
// System.out.println(per.ch);
// System.out.println(per.n);
// System.out.println(per.b);
per.setName("minyi");
per.setAge(18);
System.out.println(per.getAge());
System.out.println(per.getName());
}
}
|
[
"2376108021@qq.com"
] |
2376108021@qq.com
|
8cc872b6b60a5d48aecc27ff68e25a05b3b3651b
|
40dde9f15f3b3d0f997a667723f5142b164e7b7f
|
/LibraryManagerSystem/src/main/java/com/mengying/service/impl/AdminServiceImpl.java
|
e77a0b639fe18d4dcad86479c089176a279d0536
|
[] |
no_license
|
gxmandppx/Java-study
|
5ba2ded966740e93b90b1dd8d872359a83d61d0e
|
188fcc034abf702c7113dffcd1e594f069b58da2
|
refs/heads/master
| 2023-08-26T11:37:48.314992
| 2021-10-20T02:39:07
| 2021-10-20T02:39:07
| 404,263,900
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,826
|
java
|
package com.zbw.service.impl;
import com.zbw.domain.*;
import com.zbw.mapper.AdminMapper;
import com.zbw.mapper.BookCategoryMapper;
import com.zbw.mapper.BookMapper;
import com.zbw.service.IAdminService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Service
public class AdminServiceImpl implements IAdminService {
@Resource
private AdminMapper adminMapper;
@Resource
private BookMapper bookMapper;
@Resource
private BookCategoryMapper bookCategoryMapper;
@Override
public boolean adminIsExist(String name) {
AdminExample adminExample = new AdminExample();
AdminExample.Criteria criteria = adminExample.createCriteria();
criteria.andAdminNameEqualTo(name);
List<Admin> admin = adminMapper.selectByExample(adminExample);
if (null == admin)
return false;
if (admin.size() < 1) {
return false;
}
return true;
}
@Override
public Admin adminLogin(String name, String password) {
AdminExample adminExample = new AdminExample();
AdminExample.Criteria criteria = adminExample.createCriteria();
criteria.andAdminNameEqualTo(name);
List<Admin> admin = adminMapper.selectByExample(adminExample);
if (null == admin) {
return null;
}
for (Admin a : admin) {
if (a.getAdminPwd().equals(password)) {
return a;
}
}
return null;
}
@Override
public boolean addBook(Book book) {
int n = bookMapper.insert(book);
if (n > 0) {
return true;
}
return false;
}
@Override
public List<BookCategory> getBookCategories() {
BookCategoryExample bookCategoryExample = new BookCategoryExample();
return bookCategoryMapper.selectByExample(bookCategoryExample);
}
@Override
public boolean addBookCategory(BookCategory bookCategory) {
int n = bookCategoryMapper.insert(bookCategory);
if (n > 0) {
return true;
}
return false;
}
@Override
public boolean updateAdmin(Admin admin, HttpServletRequest request) {
//获取session对象中admin对象
Admin sessionAdmin = (Admin) request.getSession().getAttribute("admin");
admin.setAdminId(sessionAdmin.getAdminId());
int n = adminMapper.updateByPrimaryKey(admin);
if (n > 0) {
//修改成功,更新session对象
Admin newAdmin = adminMapper.selectByPrimaryKey(admin.getAdminId());
request.getSession().setAttribute("admin", newAdmin);
return true;
}
return false;
}
}
|
[
"2016330070@qq.com"
] |
2016330070@qq.com
|
efafa175897c281dfd91899be478e842b39392ae
|
f8c73d40b11c8329f7a7d1d2dae896576434938b
|
/tronsdk/src/main/java/com/centerprime/tronsdk/abi/Utils.java
|
f79cb76c2a368662cd6a486c0c75aab1f4cf3b6d
|
[
"MIT"
] |
permissive
|
centerprime/Tron-Android-SDK
|
e8559e6f44bee06c07df1a4a8313000f8f74acf7
|
6faaa72a31e9ccf9e8e31c49a5dfef70d9e74edb
|
refs/heads/master
| 2023-03-14T14:58:58.467863
| 2021-03-09T02:37:55
| 2021-03-09T02:37:55
| 322,264,623
| 7
| 1
| null | 2021-03-09T02:37:55
| 2020-12-17T10:49:25
|
Java
|
UTF-8
|
Java
| false
| false
| 5,189
|
java
|
package com.centerprime.tronsdk.abi;
import com.centerprime.tronsdk.abi.datatypes.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Utility functions.
*/
public class Utils {
private Utils() {}
static <T extends Type> String getTypeName(TypeReference<T> typeReference) {
try {
java.lang.reflect.Type reflectedType = typeReference.getType();
Class<?> type;
if (reflectedType instanceof ParameterizedType) {
type = (Class<?>) ((ParameterizedType) reflectedType).getRawType();
return getParameterizedTypeName(typeReference, type);
} else {
type = Class.forName(reflectedType.getTypeName());
return getSimpleTypeName(type);
}
} catch (ClassNotFoundException e) {
throw new UnsupportedOperationException("Invalid class reference provided", e);
}
}
static String getSimpleTypeName(Class<?> type) {
String simpleName = type.getSimpleName().toLowerCase();
if (type.equals(Uint.class) || type.equals(Int.class)
|| type.equals(Ufixed.class) || type.equals(Fixed.class)) {
return simpleName + "256";
} else if (type.equals(Utf8String.class)) {
return "string";
} else if (type.equals(DynamicBytes.class)) {
return "bytes";
} else {
return simpleName;
}
}
static <T extends Type, U extends Type> String getParameterizedTypeName(
TypeReference<T> typeReference, Class<?> type) {
try {
if (type.equals(DynamicArray.class)) {
Class<U> parameterizedType = getParameterizedTypeFromArray(typeReference);
String parameterizedTypeName = getSimpleTypeName(parameterizedType);
return parameterizedTypeName + "[]";
} else if (type.equals(StaticArray.class)) {
Class<U> parameterizedType = getParameterizedTypeFromArray(typeReference);
String parameterizedTypeName = getSimpleTypeName(parameterizedType);
return parameterizedTypeName
+ "["
+ ((TypeReference.StaticArrayTypeReference) typeReference).getSize()
+ "]";
} else {
throw new UnsupportedOperationException("Invalid type provided " + type.getName());
}
} catch (ClassNotFoundException e) {
throw new UnsupportedOperationException("Invalid class reference provided", e);
}
}
@SuppressWarnings("unchecked")
static <T extends Type> Class<T> getParameterizedTypeFromArray(
TypeReference typeReference) throws ClassNotFoundException {
java.lang.reflect.Type type = typeReference.getType();
java.lang.reflect.Type[] typeArguments =
((ParameterizedType) type).getActualTypeArguments();
String parameterizedTypeName = typeArguments[0].getTypeName();
return (Class<T>) Class.forName(parameterizedTypeName);
}
@SuppressWarnings("unchecked")
public static List<TypeReference<Type>> convert(List<TypeReference<?>> input) {
List<TypeReference<Type>> result = new ArrayList<>(input.size());
result.addAll(input.stream()
.map(typeReference -> (TypeReference<Type>) typeReference)
.collect(Collectors.toList()));
return result;
}
public static <T, R extends Type<T>, E extends Type<T>> List<E> typeMap(
List<List<T>> input,
Class<E> outerDestType,
Class<R> innerType) {
List<E> result = new ArrayList<>();
try {
Constructor<E> constructor = outerDestType.getDeclaredConstructor(List.class);
for (List<T> ts : input) {
E e = constructor.newInstance(typeMap(ts, innerType));
result.add(e);
}
} catch (NoSuchMethodException
| IllegalAccessException
| InstantiationException
| InvocationTargetException e) {
throw new TypeMappingException(e);
}
return result;
}
public static <T, R extends Type<T>> List<R> typeMap(List<T> input, Class<R> destType)
throws TypeMappingException {
List<R> result = new ArrayList<R>(input.size());
if (!input.isEmpty()) {
try {
Constructor<R> constructor = destType.getDeclaredConstructor(
input.get(0).getClass());
for (T value : input) {
result.add(constructor.newInstance(value));
}
} catch (NoSuchMethodException
| IllegalAccessException
| InvocationTargetException
| InstantiationException e) {
throw new TypeMappingException(e);
}
}
return result;
}
}
|
[
"support@centerprime.technology"
] |
support@centerprime.technology
|
c4b2086e69544d91508547f8c26969afc33310ee
|
81b0bb3cfb2e9501f53451e7f03ec072ee2b0e13
|
/src/me/lyft/android/ui/business/onboard/PaymentSelectionController.java
|
76e914efcfdca65a2e2fbf6714f0aa8036558f2a
|
[] |
no_license
|
reverseengineeringer/me.lyft.android
|
48bb85e8693ce4dab50185424d2ec51debf5c243
|
8c26caeeb54ffbde0711d3ce8b187480d84968ef
|
refs/heads/master
| 2021-01-19T02:32:03.752176
| 2016-07-19T16:30:00
| 2016-07-19T16:30:00
| 63,710,356
| 3
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,462
|
java
|
package me.lyft.android.ui.business.onboard;
import android.content.Context;
import android.content.res.Resources;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.lyft.scoop.Scoop;
import java.util.Iterator;
import java.util.List;
import javax.inject.Inject;
import me.lyft.android.application.IUserProvider;
import me.lyft.android.application.business.BusinessOnboardingAnalytics;
import me.lyft.android.application.payment.IPaymentService;
import me.lyft.android.common.AppFlow;
import me.lyft.android.common.DialogFlow;
import me.lyft.android.common.RxViewController;
import me.lyft.android.controls.Toolbar;
import me.lyft.android.domain.payment.ChargeAccount;
import me.lyft.android.persistence.payment.IChargeAccountsProvider;
import me.lyft.android.rx.RxUIBinder;
import me.lyft.android.ui.Dialogs.AlertDialog;
import me.lyft.android.ui.IProgressController;
import me.lyft.android.ui.payment.AddCreditCardPaymentItemView;
import me.lyft.android.ui.payment.AddPayPalPaymentItemView;
import me.lyft.android.ui.payment.AddWalletCardPaymentItemView;
import me.lyft.android.ui.payment.IChargeAccountSelectionListener;
import me.lyft.android.ui.payment.PaymentListItemView;
public class PaymentSelectionController
extends RxViewController
{
LinearLayout addCard;
LinearLayout addPaymentLayout;
private View addWalletView;
private final AppFlow appFlow;
private final BusinessOnboardingAnalytics businessOnboardingAnalytics;
private IChargeAccountSelectionListener chargeAccountDefaultSelectionListener = new PaymentSelectionController.3(this);
private final IChargeAccountsProvider chargeAccountsProvider;
private final DialogFlow dialogFlow;
ViewGroup paymentCardListWidgetView;
private final IPaymentService paymentService;
private final IProgressController progressController;
Toolbar toolbar;
private final IUserProvider userProvider;
@Inject
public PaymentSelectionController(IChargeAccountsProvider paramIChargeAccountsProvider, IPaymentService paramIPaymentService, IProgressController paramIProgressController, IUserProvider paramIUserProvider, AppFlow paramAppFlow, DialogFlow paramDialogFlow, BusinessOnboardingAnalytics paramBusinessOnboardingAnalytics)
{
chargeAccountsProvider = paramIChargeAccountsProvider;
paymentService = paramIPaymentService;
progressController = paramIProgressController;
userProvider = paramIUserProvider;
appFlow = paramAppFlow;
dialogFlow = paramDialogFlow;
businessOnboardingAnalytics = paramBusinessOnboardingAnalytics;
}
private void insertAddWalletPaymentItem()
{
if (addWalletView == null) {
addWalletView = new AddWalletCardPaymentItemView(getView().getContext());
}
binder.bindAction(paymentService.observeWalletReadyToPay(), new PaymentSelectionController.4(this));
}
private void refreshChargeAccounts(List<ChargeAccount> paramList)
{
paymentCardListWidgetView.removeAllViews();
if (!chargeAccountsProvider.hasWalletCard()) {
insertAddWalletPaymentItem();
}
if (!chargeAccountsProvider.hasPayPalChargeAccount()) {
paymentCardListWidgetView.addView(new AddPayPalPaymentItemView(getView().getContext(), true, true));
}
paramList = paramList.iterator();
while (paramList.hasNext())
{
ChargeAccount localChargeAccount = (ChargeAccount)paramList.next();
PaymentListItemView localPaymentListItemView = PaymentListItemView.createSelectableChargeAccountListItem(getScoop().createContext(getView().getContext()), localChargeAccount, chargeAccountDefaultSelectionListener);
if (localPaymentListItemView != null)
{
if (localChargeAccount.isDefaultBusiness().booleanValue())
{
toolbar.enableItem(2131558445);
localPaymentListItemView.select();
}
paymentCardListWidgetView.addView(localPaymentListItemView);
}
}
}
protected int layoutId()
{
return 2130903071;
}
public void onAttach()
{
super.onAttach();
Object localObject = getView().getContext();
toolbar.showTitle().setTitle(((Context)localObject).getString(2131166093));
toolbar.addItem(2131558445, ((Context)localObject).getString(2131165934).toUpperCase());
toolbar.disableItem(2131558445);
LinearLayout localLinearLayout = addPaymentLayout;
if (chargeAccountsProvider.hasMaximumCreditCardsAmount()) {}
for (int i = 8;; i = 0)
{
localLinearLayout.setVisibility(i);
if (!chargeAccountsProvider.hasMaximumCreditCardsAmount())
{
localObject = new AddCreditCardPaymentItemView((Context)localObject, true, true);
addCard.addView((View)localObject);
}
binder.bindAction(toolbar.observeItemClick(), new PaymentSelectionController.1(this));
binder.bindAction(chargeAccountsProvider.observeChargeAccounts(), new PaymentSelectionController.2(this));
return;
}
}
public void showInvalidChargeAccountDialog()
{
Dialogs.AlertDialog localAlertDialog = new Dialogs.AlertDialog("invalid_card_dialog").setTitle(getResources().getString(2131166055)).setMessage(getResources().getString(2131166054)).addPositiveButton(getResources().getString(2131165939));
dialogFlow.show(localAlertDialog);
}
}
/* Location:
* Qualified Name: me.lyft.android.ui.business.onboard.PaymentSelectionController
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
[
"reverseengineeringer@hackeradmin.com"
] |
reverseengineeringer@hackeradmin.com
|
9ec0be508cf6cc553dd99a5670aa95c05d45926c
|
d2d2822b1f9932f292ec5b6903768486fb4bcd0c
|
/app/src/main/java/com/davis/mall/interfac/IFenLeiFragment.java
|
e6299d12619ff4ec47433a26ae31603d0ce9c3ec
|
[] |
no_license
|
DavisStorm/noteDemo
|
d93e4ba4a3b7f123d430b6d1e9656a242c48c877
|
5438bae23d7854b1bad88e8e3a7f177270fc46c9
|
refs/heads/master
| 2023-02-04T02:40:38.135606
| 2020-12-22T07:03:25
| 2020-12-22T07:03:25
| 256,745,036
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 457
|
java
|
package com.davis.mall.interfac;
import com.davis.mall.bean.CategoryBannerBean;
import com.davis.mall.bean.CategoryBean;
import com.davis.mall.bean.CategoryMuluBean;
/**
* @author 王阳
* @time 2019/11/13 21:10
* @desc
*/
public interface IFenLeiFragment extends IMVP {
void requestSuccess1(CategoryMuluBean categoryBean);
void requestSuccess2(CategoryBannerBean categoryBannerBean);
void requestSuccess3(CategoryBean categoryBean);
}
|
[
"wangyang@uweidao.cn"
] |
wangyang@uweidao.cn
|
098b0228c1af25080ef081b31335d67759c782c0
|
2d57d9e9b97cac5de6b2b69a482cbd3379a7c7bb
|
/Program List/src/patternprogram/SpaceStarPattern2.java
|
eb7efd8fab73d249eebede2f26599d4888fbb5da
|
[] |
no_license
|
ashishgupta930/ProgramsHandsOn
|
7838ed719108603aa3c7b097c2d95bb55f25387e
|
880e75d3a37f6bd22c076ef0ed000d069d1ed3f2
|
refs/heads/master
| 2020-03-15T12:10:22.640763
| 2018-05-08T06:14:12
| 2018-05-08T06:14:12
| 132,138,088
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 372
|
java
|
package patternprogram;
public class SpaceStarPattern2 extends BaseClass {
public static void main(String[] args) {
for(int i=1;i<=n;i++) {
for(int j=1;j<i;j++) {
System.out.print(" "); // first print 0 zero space first check 0<1,1<2
}
for(int j=1;j<=n-i+1;j++) {
System.out.print("*");
}
System.out.println();
}
}
}
|
[
"ashish.gupta930@gmail.com"
] |
ashish.gupta930@gmail.com
|
fcf6a575532c159bcda81f4fbb207ca73870c8e4
|
e0d4987e8ce4a82974733be70f90c184127900b3
|
/src/isoquant/plugins/db/ProjectDBInfoViewer.java
|
32fcac9b883c66b9b24f1b10e9d80d6456d8ecca
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
jkuharev/ISOQuant
|
44a5620c708ec4b122958c4c4a10fcae16fb6ef5
|
6f7f063a7f4270c5e2cb9c6f171663daf5237ff2
|
refs/heads/master
| 2018-11-01T10:21:26.913560
| 2018-09-14T12:04:54
| 2018-09-14T12:04:54
| 116,664,166
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 4,065
|
java
|
/** ISOQuant, isoquant.plugins.db, 10.10.2011*/
package isoquant.plugins.db;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.util.*;
import javax.swing.*;
import de.mz.jk.jsix.ui.FormBuilder;
import de.mz.jk.jsix.ui.TableFactory;
import de.mz.jk.plgs.data.Workflow;
import isoquant.interfaces.iMainApp;
import isoquant.interfaces.log.iLogEntry;
import isoquant.kernel.db.DBProject;
import isoquant.kernel.db.IQDBUtils;
import isoquant.kernel.plugin.SingleActionPlugin4DB;
/**
* <h3>{@link ProjectDBInfoViewer}</h3>
* @author kuharev
* @version 10.10.2011 11:01:59
*/
public class ProjectDBInfoViewer extends SingleActionPlugin4DB
{
static UIDefaults defs = UIManager.getDefaults();
public ProjectDBInfoViewer(iMainApp app){ super(app); }
@Override public void runPluginAction(DBProject p) throws Exception
{
showAbout(Collections.singletonList(p));
}
@Override public void actionPerformed(ActionEvent e)
{
showAbout( app.getSelectedDBProjects() );
}
private void showAbout(List<DBProject> ps)
{
JDialog win = new JDialog((Frame) app.getGUI());
win.setTitle("DBProject attributes");
win.setModal(true);
JTabbedPane tabPane = new JTabbedPane();
for(DBProject p : ps)
{
JComponent pnl = getAboutProjectPane(p);
tabPane.addTab( p.data.title, pnl );
}
win.setContentPane( tabPane );
win.setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
win.pack();
win.setSize( win.getHeight(), win.getWidth() + 50 );
win.setLocationRelativeTo( app.getGUI() );
win.setVisible( true );
}
private JComponent getAboutProjectPane(DBProject p)
{
FormBuilder fb = new FormBuilder();
fb.setBoldCaptions( true );
fb.add( "title:", field( p.data.title ) );
fb.add( "description:", field( p.data.info ) );
fb.add( "additional info:", field( p.data.titleSuffix ) );
fb.add( "project id:", field( p.data.id ) );
fb.add( "database schema:", field( p.data.db ) );
fb.add( "root folder:", field( p.data.root ) );
fb.add( "parameters:", new JScrollPane( getParamTable( p.log.get() ) ) );
fb.add( "workflows:", new JScrollPane( getRunTable( p ) ) );
return fb.getFormContainer();
}
private JTextField field(String content)
{
JTextField f = new JTextField(content);
f.setEditable(false);
f.setBackground(defs.getColor("Label.background"));
f.setForeground(defs.getColor("Label.foreground"));
f.setBorder(BorderFactory.createLoweredBevelBorder());
return f;
}
private JTable getParamTable(List<iLogEntry> logs)
{
Map<String, String> pars = new HashMap<String, String>();
for(iLogEntry e : logs)
{
if( e.getType().equals( iLogEntry.Type.parameter ) )
{
pars.put( e.getValue(), e.getNote() );
}
}
String[][] p = new String[pars.size()][2];
Object[] parNames = pars.keySet().toArray();
Arrays.sort(parNames);
for(int i=0; i<parNames.length; i++)
{
p[i][0] = (String) parNames[i];
p[i][1] = pars.get( parNames[i] );
}
TableFactory tf = new TableFactory( p, new String[]{"parameter", "value"}, new Boolean[]{false, false});
return tf.getTable(true);
}
private JTable getRunTable(DBProject p)
{
String[] captions = {"index", "title", "replicate name", "sample description", "input file", "acquired name"};
List<Workflow> ws = IQDBUtils.getWorkflows(p);
int nRows = ws.size();
String[][] td = new String[nRows][captions.length];
for(int row = 0; row<nRows; row++)
{
Workflow w = ws.get(row);
int col = 0;
td[row][col++] = ""+w.index;
td[row][col++] = ""+w.title;
td[row][col++] = ""+w.replicate_name;
td[row][col++] = ""+w.sample_description;
td[row][col++] = ""+w.input_file;
td[row][col++] = ""+w.acquired_name;
}
TableFactory tf = new TableFactory( td, captions);
return tf.getTable(true);
}
@Override public String getPluginName(){return "DBProject Database Info Viewer";}
@Override public int getExecutionOrder(){return 0;}
@Override public String getMenuItemText(){return "show info";}
@Override public String getMenuItemIconName(){return "info";}
}
|
[
"jkuharev@1041-mac-joerg.local"
] |
jkuharev@1041-mac-joerg.local
|
562efd234f13ef31efacc68e75c087e55dff7679
|
ea8cba523fe3f2be232431aa6282e91acd1829b7
|
/ecp-starter-data-service/src/main/java/id/org/test/data/service/impl/ProductMobileServiceImpl.java
|
9d40bced1167c1cd860dc07c81ef266e4a72caee
|
[] |
no_license
|
adinunu/eCommercePlatform
|
3c4867ba2e927045a82540b8962a903187dc52c6
|
a28ea464e3a0f64394de82d492ffa6b64fb93b96
|
refs/heads/master
| 2022-12-17T04:23:33.215265
| 2020-09-23T19:09:27
| 2020-09-23T19:09:27
| 296,675,074
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 6,300
|
java
|
package id.org.test.data.service.impl;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import id.org.test.common.constant.GeneralStatus;
import id.org.test.common.web.DataTableObject;
import id.org.test.data.model.Product;
import id.org.test.data.repository.MemberRepository;
import id.org.test.data.repository.CategoryRepository;
import id.org.test.data.repository.ProductRepository;
import id.org.test.data.service.ProductMobileService;
import id.org.test.data.service.wrapper.ProductMobileWrapper;
@Service
@Transactional
public class ProductMobileServiceImpl implements ProductMobileService {
private static final Logger logger = LoggerFactory.getLogger(ProductMobileServiceImpl.class);
@Value("${aliyun.oss.cdn-url:http://static.whee.tech}")
private String cdnUrl;
@Value("${aliyun.oss.product-bucket-path:images/product}")
private String productBucketPath;
@Value("${aliyun.oss.bucket-name:whee-tech}")
private String bucketName;
private final ProductRepository productRepository;
private final CategoryRepository categoryRepository;
private final MemberRepository memberRepository;
@Autowired
public ProductMobileServiceImpl(ProductRepository productRepository, CategoryRepository categoryRepository,
MemberRepository memberRepository) {
this.productRepository = productRepository;
this.categoryRepository = categoryRepository;
this.memberRepository = memberRepository;
}
private ProductMobileWrapper toWrapper(Product model) throws Exception {
ProductMobileWrapper wrapper = new ProductMobileWrapper();
wrapper.setId(model.getId());
if (model.getProductCategory() != null) {
wrapper.setCategoryId(model.getProductCategory().getId());
wrapper.setCategoryName(model.getProductCategory().getCategoryName());
}
wrapper.setProductName(model.getProductName());
wrapper.setProductCode(model.getProductCode());
wrapper.setProductDescription(model.getDescription());
wrapper.setProductPrice(model.getProductPrice());
wrapper.setStoreName(model.getStoreName());
wrapper.setBrandName(model.getBrandName());
wrapper.setStatus(String.valueOf(model.getGeneralStatus()));
wrapper.setMemberId(model.getMember().getId());
return wrapper;
}
private List<ProductMobileWrapper> toWrapperList(List<Product> entityList) throws Exception {
List<ProductMobileWrapper> wrapperList = new ArrayList<>();
if (entityList != null && entityList.size() > 0) {
// wrapperList = new ArrayList<>();
for (Product temp : entityList) {
wrapperList.add(toWrapper(temp));
}
}
return wrapperList;
}
@Override
public List<ProductMobileWrapper> getListByMember(Long memberId) throws Exception {
return toWrapperList(productRepository.getActiveListByMember(memberId));
}
@Override
public List<ProductMobileWrapper> getPageableListByMember(Long memberId, Long categoryId, String status,
String param, int startPage, int pageSize, Sort sort) throws Exception {
logger.info("Member Id : " + memberId);
Page<Product> productPage = null;
int page = DataTableObject.getPageFromStartAndLength(startPage, pageSize);
if (memberId != null) {
if (categoryId != null) {
productPage = productRepository.getPageableListByMemberAndCategory(memberId, categoryId, param,
new PageRequest(page, pageSize, sort));
} else {
productPage = productRepository.getPageableListByMemberMob(memberId, param,
new PageRequest(page, pageSize, sort));
}
} else {
if (param != null && !param.equalsIgnoreCase("")) {
productPage = productRepository.getPageable(param, new PageRequest(page, pageSize, sort));
} else {
productPage = productRepository.getPageableNoSearch(new PageRequest(page, pageSize, sort));
}
}
List<ProductMobileWrapper> wrapperList = toWrapperList(productPage.getContent());
return wrapperList;
}
private Product toEntity(ProductMobileWrapper wrapper) throws Exception {
Product entity = new Product();
if (wrapper.getId() != null) {
entity = productRepository.findOne(wrapper.getId());
entity.setVersion(entity.getVersion() + 1L);
} else {
entity.setVersion(1L);
entity.setDeleted(0);
}
if (wrapper.getCategoryId() != null) {
entity.setProductCategory(categoryRepository.findOne(wrapper.getCategoryId()));
}
entity.setProductName(wrapper.getProductName());
entity.setProductCode(wrapper.getProductCode());
entity.setProductPrice(wrapper.getProductPrice());
entity.setDescription(wrapper.getProductDescription());
entity.setGeneralStatus(GeneralStatus.valueOf(wrapper.getStatus()));
entity.setBrandName(wrapper.getBrandName());
entity.setStoreName(wrapper.getStoreName());
entity.setMember(memberRepository.findOne(wrapper.getMemberId()));
return entity;
}
@Override
public Long getNum() {
return productRepository.count();
}
@Override
public ProductMobileWrapper save(ProductMobileWrapper wrapper) throws Exception {
ProductMobileWrapper savedProduct = toWrapper(productRepository.save(toEntity(wrapper)));
return savedProduct;
}
@Override
public ProductMobileWrapper getById(Long id) throws Exception {
return toWrapper(productRepository.findOne(id));
}
@Override
public Boolean delete(Long id) throws Exception {
try {
// customerRepository.delete(aLong); //should be soft-delete
Product model = productRepository.findOne(id);
model.setVersion(model.getVersion() + 1);
model.setDeleted(1);
productRepository.save(model);
return true;
} catch (Exception e) {
throw new Exception(e);
}
}
@Override
public List<ProductMobileWrapper> getAll() throws Exception {
return toWrapperList((List<Product>) productRepository.findAll());
}
@Override
public List<ProductMobileWrapper> findAll() {
try {
return toWrapperList(productRepository.findAll());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
|
[
"adinunu.persada@gmail.com"
] |
adinunu.persada@gmail.com
|
1ef2b005b7e0dbcc4e07fbacba3e740f07cee4c0
|
ff369a5c02c265505b0efc6b80d83f98d4e427a5
|
/src/main/java/com/revature/data/ProjectCommentDAO.java
|
a3eee52e4b7c1962be578805e097a4eb6c9675eb
|
[] |
no_license
|
TeamWorkflow/WorkPipe
|
d0a70f95557ca84c17b12c854914b4d082261f8d
|
558b785838ddb4af2f093efbb7b1667ce1fd8bd9
|
refs/heads/master
| 2023-01-09T01:28:23.442330
| 2020-03-16T19:00:01
| 2020-03-16T19:00:01
| 245,436,826
| 0
| 0
| null | 2023-01-07T15:44:53
| 2020-03-06T14:13:03
|
Java
|
UTF-8
|
Java
| false
| false
| 684
|
java
|
package com.revature.data;
import java.util.Set;
import com.revature.hibernate.beans.Employee;
import com.revature.hibernate.beans.Project;
import com.revature.hibernate.beans.ProjectComment;
public interface ProjectCommentDAO {
// create
public ProjectComment addProjectComment(ProjectComment pc);
// read
public ProjectComment getProjectComment(int i);
public Set<ProjectComment> getProjectComments();
public Set<ProjectComment> getProjectCommentsByProject(Project p);
public Set<ProjectComment> getProjectCommentsByEmployee(Employee emp);
// update
public void updateProjectComment(ProjectComment pc);
// delete
public void deleteProjectComment(ProjectComment pc);
}
|
[
"stephen.wingbermuehle@yahoo.com"
] |
stephen.wingbermuehle@yahoo.com
|
bf90977fe76a966c8c21d718347d3d3f33ec9736
|
b91ef37b5a9bf60eaadea502906d1774369f0159
|
/SiteProjetALD/src/action/action/Recherche.java
|
0395b26fa9612691b38f08f95de53cdf998ad940
|
[] |
no_license
|
nicolasrn/pjtmgghnr
|
18bb5d29444edcb68d8c291f7501655e4d20c0e9
|
6afe42c1283cf5c3225a34e24846d6a3c4b0c63e
|
refs/heads/master
| 2021-01-19T20:22:18.324126
| 2011-05-02T11:10:42
| 2011-05-02T11:10:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,860
|
java
|
package action.action;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import metier.Offre;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import action.form.ActionFormFormuRecherche;
import dao.DAOOffre;
public class Recherche extends Action {
private DAOOffre daoOffre;
/**
* @return the daoOffre
*/
public DAOOffre getDaoOffre() {
return daoOffre;
}
/**
* @param daoOffre the daoOffre to set
*/
public void setDaoOffre(DAOOffre daoOffre) {
this.daoOffre = daoOffre;
}
/* (non-Javadoc)
* @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionFormFormuRecherche f = (ActionFormFormuRecherche)form;
String motClef = f.getMotclef();
int categ = f.getCategorie().trim().isEmpty() ? -1 : Integer.parseInt(f.getCategorie()),
dep = f.getDepartementSelect().trim().isEmpty() ? -1 : Integer.parseInt(f.getDepartementSelect());
double prixMin = f.getMin().trim().isEmpty() ? -1 : Double.parseDouble(f.getMin()),
prixMax = f.getMax().trim().isEmpty() ? -1 : Double.parseDouble(f.getMax());
ArrayList<Offre> offre = daoOffre.findThem(motClef, categ, dep, prixMin, prixMax);
request.getSession().setAttribute("listRecherche", offre);
request.getSession().setAttribute("lastPath", mapping.findForward("resultatRecherche"));
return mapping.findForward("resultatRecherche");
}
}
|
[
"nicolasrnp@gmail.com@52663d97-6de6-0ad8-d9db-d725467354bf"
] |
nicolasrnp@gmail.com@52663d97-6de6-0ad8-d9db-d725467354bf
|
514cec2a0044c322d275ed53d7ea974a559539bb
|
d4ae1861b3b723ef5f5cb362a9e9dd808aab5e11
|
/strings/duplicate/bettersoln.java
|
196dfb72e96e14e42c5b4cf92caf14bb32f5e2bd
|
[] |
no_license
|
Siddanth-pai/my_solutions_gfg
|
3272adce273fba2ac90e4f86fabe827f84fb63e1
|
8fd74925cb486c77e9f7fb95ddf4f63e3bf8c2c2
|
refs/heads/master
| 2021-07-04T13:32:27.429217
| 2019-07-08T20:03:58
| 2019-07-08T20:03:58
| 195,878,317
| 0
| 0
| null | 2020-10-31T18:22:41
| 2019-07-08T20:01:56
|
Java
|
UTF-8
|
Java
| false
| false
| 694
|
java
|
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args)
{
Scanner s=new Scanner(System.in);
int t=s.nextInt();
s.nextLine();
while(t-->0){
String str=s.nextLine();
int n=str.length();
HashMap<Character,Integer> map=new HashMap<>();
for(int i=0;i<n;i++){
char c=str.charAt(i);
map.put(c,1);
}
for(int i=0;i<n;i++){
char c=str.charAt(i);
if(map.containsKey(c)){
System.out.print(c);
map.remove(c);
}
}
System.out.println();
}
}
}
|
[
"siddanthofficial@gmail.com"
] |
siddanthofficial@gmail.com
|
fbc3837d5aeb36b1c4a281fd45a5c0594522ccae
|
c0d01dc606acf576284d5faced2056ecd72512d5
|
/springboot-web/src/main/java/com/springboot/vincent/config/Swagger2Config.java
|
8f41912bad009105ad59ba85e4c556647e9e5320
|
[] |
no_license
|
91xinwei/springboot-project-build
|
f16e2fb531943e58ec5db66bf7b3b6579fd0556a
|
acb701587d7c85c1a26f26292c4e9e86bfe141da
|
refs/heads/master
| 2021-01-24T04:20:19.901592
| 2018-03-06T03:36:38
| 2018-03-06T03:36:38
| 122,933,850
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,323
|
java
|
package com.springboot.vincent.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Created by weix on 2018/3/5.
*/
@Configuration
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.springboot.vincent"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("aouth vincent")
.termsOfServiceUrl("http://blog.didispace.com/")
.contact("Vincent")
.version("1.0")
.build();
}
}
|
[
"wei13593372625@yahoo.com"
] |
wei13593372625@yahoo.com
|
0fec91acd0a4b099fa02efa1f95998b0e8823031
|
aabb25a90702433d92d0fac8d15b7719199c7c45
|
/src/test/java/stepDefinition/Flipkart.java
|
63ed1fb9ea65d1c7235659a1bb053c0173738e78
|
[] |
no_license
|
kskanagu/CucumberFrameWork
|
a84811fe0028578256117346acdacbbf5701b8ea
|
982785bd36e26d234915e796e5e366377ecc66dd
|
refs/heads/master
| 2020-03-22T09:01:34.887532
| 2018-07-05T07:19:35
| 2018-07-05T07:19:35
| 139,801,689
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 661
|
java
|
package stepDefinition;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import main.test.FlipkartScripts;
public class Flipkart{
FlipkartScripts run = new FlipkartScripts();
@Given("^Launch the browser$")
public void launch_the_browser() throws Throwable {
run.launch_the_browser();
}
@When("^Navigate to a website$")
public void navigate_to_a_website() throws Throwable {
run.navigate_to_a_website();
}
@Then("^validate the website$")
public void validate_the_website() throws Throwable {
run.validate_the_website();
}
public static void main(String[] args) {
}
}
|
[
"40464437+ManiYok@users.noreply.github.com"
] |
40464437+ManiYok@users.noreply.github.com
|
4cd307d1addeb04ba64256fab28a6b36e675c97a
|
80243a26e5db1071f4fe9348672eef59a82e4b12
|
/app/src/test/java/edu/upc/eseiaat/pma/shoppinglist2/ExampleUnitTest.java
|
58ca7914755204d5470fca29510f6d5fe906e8ad
|
[] |
no_license
|
marcmmr/ShoppingList2_final
|
e011604547937e943ea44f115fb32f7dbcc9bc3c
|
ef1f796b9ade7da7387b5f963df563e7b0a4671f
|
refs/heads/master
| 2021-05-15T07:55:19.971955
| 2017-10-27T12:06:24
| 2017-10-27T12:06:24
| 108,541,291
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 411
|
java
|
package edu.upc.eseiaat.pma.shoppinglist2;
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() throws Exception {
assertEquals(4, 2 + 2);
}
}
|
[
"marcmontserrrat@gmail.com"
] |
marcmontserrrat@gmail.com
|
0f112bdaf372f3f63bf1cbff6fadbb4d1520fcef
|
30b1ccf0e6405e8097d1a740ffec003f2ecab00a
|
/imcontainer/src/main/java/com/dobybros/gateway/channels/websocket/netty/handler/IMWebSocketHandler.java
|
5217704e37b091a67fb3395b433812da3bc529dd
|
[] |
no_license
|
dobybros/GroovyCloud
|
2e816bbf3469d1e5d157b9313125ff51eb1caa5f
|
cbbd9b30554d95c8e70aa03ed15df9b41bc75bcd
|
refs/heads/master
| 2022-12-10T04:37:50.935960
| 2022-08-09T10:04:43
| 2022-08-09T10:04:43
| 188,410,065
| 4
| 1
| null | 2022-12-06T00:43:04
| 2019-05-24T11:27:09
|
Java
|
UTF-8
|
Java
| false
| false
| 7,501
|
java
|
package com.dobybros.gateway.channels.websocket.netty.handler;
import chat.errors.CoreException;
import chat.logs.LoggerEx;
import com.dobybros.chat.binary.data.Data;
import com.dobybros.chat.channels.Channel;
import com.dobybros.gateway.channels.msgs.MessageReceivedListener;
import com.dobybros.gateway.channels.tcp.UpStreamAnnotationHandler;
import com.dobybros.gateway.channels.websocket.data.NettyChannelContext;
import com.dobybros.gateway.channels.websocket.netty.codec.WebSocketFrameCodec;
import com.dobybros.gateway.errors.GatewayErrorCodes;
import com.dobybros.gateway.onlineusers.OnlineServiceUser;
import com.dobybros.gateway.onlineusers.OnlineUser;
import com.dobybros.gateway.onlineusers.OnlineUserManager;
import com.dobybros.gateway.pack.Pack;
import com.docker.utils.SpringContextUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import script.groovy.object.GroovyObjectEx;
/**
* Created by hzj on 2021/9/28 下午3:49
*/
public class IMWebSocketHandler extends AbstractWebSocketServerHandler {
private static final String TAG = IMWebSocketHandler.class.getSimpleName();
public static final String ATTRIBUTE_VERSION = "VERSION";
private OnlineUserManager onlineUserManager = (OnlineUserManager)SpringContextUtil.getBean("onlineUserManager");
private UpStreamAnnotationHandler upStreamAnnotationHandler = (UpStreamAnnotationHandler)SpringContextUtil.getBean("upStreamAnnotationHandler");
public IMWebSocketHandler(boolean ssl) {
super(ssl);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
closeUserChannel(ctx, Channel.ChannelListener.CLOSE, null);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
NettyChannelContext nettyChannelContext = closeContext(ctx);
LoggerEx.info(TAG, "user event triggered, nettyChannelContext" + nettyChannelContext + ", evt: " + evt);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
try {
closeUserChannel(ctx, Channel.ChannelListener.CLOSE_ERROR, cause);
} finally {
closeContext(ctx);
}
}
@Override
protected void messageReceived(ChannelHandlerContext ctx, BinaryWebSocketFrame webSocketFrame) throws Exception {
NettyChannelContext context = NettyChannelContext.getNettyChannelContextByCtx(ctx);
Data data = null;
try {
data = WebSocketFrameCodec.decode(webSocketFrame, context);
if (data != null) {
Byte type = data.getType();
if (type != Pack.TYPE_IN_IDENTITY && !context.getReadIdentity().get())
throw new CoreException(GatewayErrorCodes.ERROR_TCPCHANNEL_MISSING_ONLINEUSER, "Online user is missing for receiving message");
GroovyObjectEx<MessageReceivedListener> listener = upStreamAnnotationHandler.getMessageReceivedMap().get(type);
if(listener == null)
listener = upStreamAnnotationHandler.getMessageReceivedMap().get(type);
if(listener != null) {
Class<? extends Data> dataClass = listener.getObject().getDataClass();
if(dataClass != null) {
listener.getObject().messageReceived(data, context);
}
}
}
} catch (Throwable t) {
LoggerEx.error(TAG, "Message " + data + " received failed, " + t + " eMsg: " + t.getMessage());
CoreException coreException = null;
if(t instanceof CoreException)
coreException = (CoreException) t;
if(coreException == null)
coreException = new CoreException(GatewayErrorCodes.ERROR_TCPCHANNEL_UNKNOWN, "Unknown error occured while receiving message from tcp channel, channel context " + context + " message " + data + " error " + t.getMessage());
if(coreException.getCode() <= GatewayErrorCodes.TCPCHANNEL_CLOSE_START && coreException.getCode() > GatewayErrorCodes.TCPCHANNEL_CLOSE_END){
boolean closeSuccess = closeUserChannel(ctx, Channel.ChannelListener.CLOSE_ERROR, null);
if(!closeSuccess){
context.close();
}
} else if(coreException.getCode() <= GatewayErrorCodes.TCPCHANNEL_CLOSE_IMMEDIATELY_START && coreException.getCode() > GatewayErrorCodes.TCPCHANNEL_CLOSE_IMMEDIATELY_END){
boolean closeSuccess = closeUserChannel(ctx, Channel.ChannelListener.CLOSE_ERROR, null);
if(!closeSuccess){
context.close();
}
} else {
context.close();
}
}
}
@Override
protected void messageReceived(ChannelHandlerContext ctx, TextWebSocketFrame webSocketFrame) throws Exception {
NettyChannelContext context = NettyChannelContext.getNettyChannelContextByCtx(ctx);
WebSocketFrameCodec.decode(webSocketFrame, context);
}
private NettyChannelContext closeContext(ChannelHandlerContext ctx) {
if (ctx != null) {
NettyChannelContext nettyChannelContext = NettyChannelContext.getNettyChannelContextByCtx(ctx);
if (nettyChannelContext != null)
nettyChannelContext.close();
return nettyChannelContext;
}
return null;
}
private Boolean closeUserChannel(ChannelHandlerContext ctx, int closeError, Throwable exceptionCause) throws CoreException {
if (ctx != null) {
NettyChannelContext nettyChannelContext = NettyChannelContext.getNettyChannelContextByCtx(ctx);
if (nettyChannelContext != null) {
OnlineUser onlineUser = onlineUserManager.getOnlineUser(nettyChannelContext.getUserId());
if (onlineUser != null) {
OnlineServiceUser onlineServiceUser = onlineUser.getOnlineServiceUser(nettyChannelContext.getService());
if(onlineServiceUser != null){
Channel channel = onlineServiceUser.getChannel(nettyChannelContext.getTerminal());
if(channel != null) {
if (exceptionCause != null) {
Channel.ChannelListener listener = channel.getChannelListener();
if(listener != null)
try {
listener.exceptionCaught(exceptionCause);
} catch (Throwable e) {
e.printStackTrace();
LoggerEx.error(TAG, "TcpChannel exceptionCaught " + exceptionCause + "|" + exceptionCause.getMessage() + " occur error " + e.getMessage() + " channel " + channel);
}
}
onlineUser.removeChannel(channel, closeError);
return true;
}
}
}
}
}
return false;
}
}
|
[
"372581643@qq.com"
] |
372581643@qq.com
|
01d46f9f8cd2b4c4db336d1e79b41a5a14555485
|
fcba28abf98a91cbced7080d455fb273a4efefb6
|
/src/main/java/com/bdxh/kmsale/bean/system/Menu.java
|
a641e06eb5ffbfd86da06749a621645eb5fdb910
|
[] |
no_license
|
liuxinhongg/javaweb
|
171d05280a64382f96532ea8931ddebbcdad0c74
|
7b6eb0427b5e87f2bad210eec1319ad1dcf13662
|
refs/heads/master
| 2020-04-06T17:05:53.189878
| 2018-11-15T02:35:32
| 2018-11-15T02:35:32
| 157,646,572
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,571
|
java
|
package com.bdxh.kmsale.bean.system;
import java.io.Serializable;
import java.util.List;
/**
*
* @author 莫夏欣
* @date 创建时间:2018年10月25日,上午10:35:18
* @Description 菜单
*/
public class Menu implements Serializable{
private static final long serialVersionUID = -9162374351617705044L;
private String moduleId;
private String moduleName;
private String moduleType;
private String parentId;
private String url;
private long ord;
private String toggle;
public String getModuleId() {
return moduleId;
}
public void setModuleId(String moduleId) {
this.moduleId = moduleId;
}
public String getModuleName() {
return moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public String getModuleType() {
return moduleType;
}
public void setModuleType(String moduleType) {
this.moduleType = moduleType;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public long getOrd() {
return ord;
}
public void setOrd(long ord) {
this.ord = ord;
}
public String getToggle() {
return toggle;
}
public void setToggle(String toggle) {
this.toggle = toggle;
}
@Override
public String toString() {
return "Menu [moduleId=" + moduleId + ", moduleName=" + moduleName + ", moduleType=" + moduleType
+ ", parentId=" + parentId + ", url=" + url + ", ord=" + ord + ", toggle=" + toggle + "]";
}
}
|
[
"tzrgaga@gmail.com"
] |
tzrgaga@gmail.com
|
b82bfbf68e18c6b510d11755e4757362ad65f3ff
|
c17726013c820d7ba4785a24954d3a14ac99d991
|
/Lab 5/src/Model/Print.java
|
8a7e254a39aa97933bf0bf8801d783e582f7339e
|
[] |
no_license
|
navi07/Rozproszona-sztuczna-inteligencja
|
ba88173edcaf2ebbfde4a2deae4a842155e249fa
|
44d4d7de5242e81d681cd497c75306556511334a
|
refs/heads/master
| 2021-01-25T09:44:10.380877
| 2018-05-28T15:05:38
| 2018-05-28T15:05:38
| 123,314,253
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 61
|
java
|
package Model;
public interface Print {
void print();
}
|
[
"kurzeja.patryk@gmail.com"
] |
kurzeja.patryk@gmail.com
|
1c476f4fb3d443ce4b11699fee0ef3502bed2ff6
|
ee3cfce9655603116b3062b87f09f6a2024adbb9
|
/app/src/main/java/com/example/yoga/DatePickerFragmnet.java
|
afe7f98747d9f2511bc83037242f375fe7354522
|
[] |
no_license
|
Amrit27k/MeditateApp
|
f57057e902a27cb49cbcbd2e87443f2b2d9c6ad2
|
416e92065569f16c9e08f66a42bef18f653c7176
|
refs/heads/master
| 2023-01-28T21:19:06.935341
| 2020-11-29T13:45:33
| 2020-11-29T13:45:33
| 292,666,429
| 0
| 7
| null | 2020-11-28T07:14:01
| 2020-09-03T19:52:59
|
Java
|
UTF-8
|
Java
| false
| false
| 619
|
java
|
package com.example.yoga;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import androidx.fragment.app.DialogFragment;
import java.util.Calendar;
public class DatePickerFragmnet extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day);
}
}
|
[
"jeevanchhajed08@gmail.com"
] |
jeevanchhajed08@gmail.com
|
a4ee3d815453ee660548157131f3eeedc46859ee
|
44f8731792ad2553b3760119d2d68541f229c4da
|
/src/main/java/tomasz/lukawski/cybergenesis/infrastructure/RandomGenerator.java
|
8c42c8f303722d70fe8071ea70fc54908005eb78
|
[] |
no_license
|
tlukawski/cybergenesis2
|
f4490c8963ac09e911bcae67405efef9dd697229
|
097f9cf6f973cf437da578a698333ad1c5424dd0
|
refs/heads/master
| 2020-05-28T09:38:31.627985
| 2019-05-28T05:23:36
| 2019-05-28T05:23:36
| 188,958,514
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 409
|
java
|
package tomasz.lukawski.cybergenesis.infrastructure;
import java.util.Random;
public class RandomGenerator {
private static final Random RANDOM = new Random();
private static final int LOW = 1;
private static final int HIGH = 100;
public int randomTo100() {
return randomTo(HIGH);
}
public int randomTo(int high) {
return RANDOM.nextInt(high - LOW) + LOW;
}
}
|
[
"tomasz.lukawski@hotmail.com"
] |
tomasz.lukawski@hotmail.com
|
911f88a574732fb1d82531116ac18ccae489d0bc
|
c733a55d06bfc8ec7b382e837493c9c12867a825
|
/src/tp2_18_nov/IHM.java
|
2af4c1d9f116dd259003c5737744597713bff944
|
[] |
no_license
|
rocsan10/testGitHub
|
6a170bf7d3c668225f331e944db9e7f27d8dbfc5
|
6690f3aa676cc321d86b39f5227616ae464229cf
|
refs/heads/master
| 2023-01-20T15:46:48.585161
| 2020-11-22T16:13:12
| 2020-11-22T16:13:12
| 315,073,178
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 4,600
|
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 tp2_18_nov;
/**
*
* @author rocsan
*/
public class IHM extends javax.swing.JFrame {
/**
* Creates new form IHM
*/
public IHM() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton1.setText("VOIR TOUS LES PRODUITS");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(36, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 502, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(70, 70, 70))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(86, 86, 86))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(72, 72, 72)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(118, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(IHM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(IHM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(IHM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(IHM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new IHM().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration//GEN-END:variables
}
|
[
"jcrocquet@gmail.com"
] |
jcrocquet@gmail.com
|
7edf854fc6313d555c76136b579579807f88ff3c
|
e27ef5643accc101f18e399bd5696a9321c19bd1
|
/blockbreaker/core/src/com/dfour/blockbreaker/entity/LightBall.java
|
d4cdf5126ba797d20e4f3df699fa1a15baa5cf32
|
[
"MIT"
] |
permissive
|
dfour/BlockBreaker
|
2d5691539d87a636c316b4acada3a339f7b707f6
|
d208ae43c7b5990f433f5edbaefc3a428185dfa5
|
refs/heads/master
| 2021-01-24T18:38:34.203230
| 2018-04-30T15:03:39
| 2018-04-30T15:03:39
| 84,461,828
| 4
| 2
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 804
|
java
|
package com.dfour.blockbreaker.entity;
import box2dLight.PointLight;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.physics.box2d.Body;
public class LightBall extends Entity{
public PointLight light;
public LightBall(Body bod, AtlasRegion tex) {
super(bod,tex);
float r = (float) Math.random() * 0.5f+ 0.5f;
float g = (float) Math.random() * 0.5f+ 0.5f;
float b = (float) Math.random() * 0.5f+ 0.5f;
sprite.setColor(r, g, b, 1f);
sprite.setScale(0.8f);
}
public LightBall(Body bod, AtlasRegion tex, Color col) {
super(bod,tex);
col.add(0.5f,0.5f,0.5f,1);
sprite.setColor(col);
sprite.setScale(0.8f);
}
@Override
public void update(){
super.update();
}
}
|
[
"darkd@DESKTOP-TEVMLPG"
] |
darkd@DESKTOP-TEVMLPG
|
9b4bb2362f0a2f6ebee6c4280f78153442e9f122
|
4f346c5cfd1e652c138a16f32b55a1cdadc3d203
|
/fjs-search/fjs-search-service/src/main/java/cn/fiaojiashu/search/mapper/ItemMapper.java
|
79d41bc9c08b9e0a93caeda07527f8da07df7205
|
[] |
no_license
|
crazy402/fiaojiashu
|
a78f5f038c5c60285b75a6d0d5fb69e5b4b15e5c
|
b1d966e8d2a1cfba4585c0114bcac9f4c28401ba
|
refs/heads/master
| 2022-04-14T16:07:12.529692
| 2020-03-31T09:59:18
| 2020-03-31T09:59:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 392
|
java
|
package cn.fiaojiashu.search.mapper;
import cn.fiaojiashu.common.pojo.SearchItem;
import java.util.List;
/**
* @ClassName: ItemMapper
* @Date: 2020/3/19 14:01
* @Description:商品Mapper,用于查询商品导入索引
*/
public interface ItemMapper {
//获取商品列表
List<SearchItem> getItemList();
//通过id查询商品
SearchItem getItemById(long itemId);
}
|
[
"1441470436@qq.com"
] |
1441470436@qq.com
|
1a25e42cba1677a7c1d182c30bdcad408766c9c6
|
63fbb5d298a889900be9d72b53ed85a3a058e227
|
/src/il/technion/ewolf/server/handlers/JarResourceHandler.java
|
4a84289254415627cf44ec71790e3aa1351f1505
|
[] |
no_license
|
236371/ewolf-webgui
|
e4c5b82723c7ffd7ca3bfbdb3573df5cfb083870
|
bf77d1f5811666bf738466ed8c88e19e4a601e3b
|
refs/heads/master
| 2021-01-10T20:33:51.906589
| 2012-11-07T07:10:42
| 2012-11-07T07:10:42
| 4,605,984
| 1
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,856
|
java
|
package il.technion.ewolf.server.handlers;
import il.technion.ewolf.server.EwolfServer;
import il.technion.ewolf.server.ServerResources;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.httpclient.util.DateParseException;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
public class JarResourceHandler implements HttpRequestHandler {
private static final String PAGE_404 = "/404.html";
private EwolfServer ewolfServer;
public JarResourceHandler(EwolfServer ewolfServer) {
this.ewolfServer = ewolfServer;
}
@Override
public void handle(HttpRequest req, HttpResponse res,
HttpContext context) throws IOException {
String reqUri = req.getRequestLine().getUri();
System.out.println("\t[JarResourceHandler] requesting: " + reqUri);
try {
if (req.containsHeader(HttpHeaders.IF_MODIFIED_SINCE)) {
String dateString = req.getLastHeader(HttpHeaders.IF_MODIFIED_SINCE).getValue();
Date d = DateUtil.parseDate(dateString);
if (d.after(ewolfServer.beforeStartTime)) {
res.setStatusCode(HttpStatus.SC_NOT_MODIFIED);
return;
}
}
} catch (DateParseException e) {
System.err.println("Received date in \"If-Modified-Since\" header is of unknown format.");
e.printStackTrace();
}
if (reqUri.contains("..")) {
res.setStatusCode(HttpStatus.SC_FORBIDDEN);
return;
}
if(reqUri.equals("/")) {
reqUri = "/home.html";
}
String path = "/www" + reqUri;
InputStream is = getResourceAsStream(path);
if (is == null) {
res.setStatusCode(HttpStatus.SC_NOT_FOUND);
path = "/www" + PAGE_404;
is = getResourceAsStream(path);
if (is == null) return;
}
if (reqUri.startsWith("/static_files")) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, 1);
res.setHeader(HttpHeaders.EXPIRES, DateUtil.formatDate(cal.getTime()));
}
setResponseEntity(res, is, path);
}
InputStream getResourceAsStream(String path) {
return getClass().getResourceAsStream(path);
}
void setResponseEntity(HttpResponse response, InputStream is, String path)
throws IOException {
ByteArrayEntity bae = new ByteArrayEntity(IOUtils.toByteArray(is));
response.setEntity(bae);
response.addHeader(HttpHeaders.CONTENT_TYPE,
ServerResources.getFileTypeMap().getContentType(path));
response.setHeader(HttpHeaders.LAST_MODIFIED,
DateUtil.formatDate(ewolfServer.startTime()));
response.setHeader(HttpHeaders.CACHE_CONTROL, "public, must-revalidate");
}
}
|
[
"send2ann@t2.technion.ac.il"
] |
send2ann@t2.technion.ac.il
|
97e4a77fb4973f2568ec9ac9de9f826203fb6f4a
|
5bb4814424c9916607acb3eeb4d9e3845628408e
|
/src/main/java/com/user/arb/RoomBookingApplication.java
|
53c02f7b789db8a2dd42c817461e1a3baf6781e7
|
[] |
no_license
|
exec4life/assessment_room_booking
|
c0c812486b5b18e3a176ce4db7c7d92510f377e2
|
9821e7630165b19d01f24455f39b4e37b01eddc4
|
refs/heads/master
| 2023-06-26T17:04:27.490049
| 2021-07-12T09:38:05
| 2021-07-12T09:38:05
| 382,541,175
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,203
|
java
|
package com.user.arb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
@SpringBootApplication
@ComponentScan(basePackages = "com.user.arb")
@EnableConfigurationProperties
public class RoomBookingApplication {
public static void main(String[] args) {
SpringApplication.run(RoomBookingApplication.class, args);
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localResolver = new SessionLocaleResolver();
return localResolver;
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:i18n/messages");
messageSource.setDefaultEncoding("UTF-8");
messageSource.setAlwaysUseMessageFormat(Boolean.TRUE);
messageSource.setCacheSeconds(3600);
return messageSource;
}
@Bean
public LocalValidatorFactoryBean getValidator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("Access-Control-Allow-Headers", "*")
.allowedHeaders("Access-Control-Allow-Origin", "*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedOrigins("*");
}
};
}
}
|
[
"exec4life@gmail.com"
] |
exec4life@gmail.com
|
f0c8710aab6685e58509a141a9f5531b2a435ccd
|
dec6bd85db1d028edbbd3bd18fe0ca628eda012e
|
/netbeans-projects/TrabEngSoftware/src/Control/auxCalculoFPA.java
|
217b2cd8467604aafe35b78bff3ba1ba7ee78a32
|
[] |
no_license
|
MatheusGrenfell/java-projects
|
21b961697e2c0c6a79389c96b588e142c3f70634
|
93c7bfa2e4f73a232ffde2d38f30a27f2a816061
|
refs/heads/master
| 2022-12-29T12:55:00.014296
| 2020-10-16T00:54:30
| 2020-10-16T00:54:30
| null | 0
| 0
| null | null | null | null |
ISO-8859-2
|
Java
| false
| false
| 6,987
|
java
|
package Control;
public class auxCalculoFPA {
public int ALIeAIE(int tipoDado, int tipoReg) {
switch (tipoReg) {
case 1:
if (tipoDado <= 50) {
return 1;
} else {
return 2;
}
case 2:
case 3:
case 4:
case 5:
if (tipoDado < 20) {
return 1;
} else {
if (tipoDado >= 20 && tipoDado <= 50) {
return 2;
} else {
return 3;
}
}
default:
if (tipoDado < 20) {
return 2;
} else {
return 3;
}
}
}
public int getAliInt(int tipoDado, int tipoReg) {
int valorTab = ALIeAIE(tipoDado, tipoReg);
switch (valorTab) {
case 1:
return 7;
case 2:
return 10;
default:
return 15;
}
}
public String getAliString(int tipoDado, int tipoReg) {
int valorTab = ALIeAIE(tipoDado, tipoReg);
switch (valorTab) {
case 1:
return "Baixa";
case 2:
return "Média";
default:
return "Alta";
}
}
public int getAieInt(int tipoDado, int tipoReg) {
int valorTab = ALIeAIE(tipoDado, tipoReg);
switch (valorTab) {
case 1:
return 5;
case 2:
return 7;
default:
return 10;
}
}
public String getAieString(int tipoDado, int tipoReg) {
int valorTab = ALIeAIE(tipoDado, tipoReg);
switch (valorTab) {
case 1:
return "Baixa";
case 2:
return "Média";
default:
return "Alta";
}
}
public int SEeCE(int tipoDado, int arqRef) {
switch (arqRef) {
case 1:
if (tipoDado < 19) {
return 1;
} else {
return 2;
}
case 2:
case 3:
if (tipoDado < 6) {
return 1;
} else {
if (tipoDado > 19) {
return 3;
} else {
return 2;
}
}
default:
if (tipoDado < 6) {
return 2;
} else {
return 3;
}
}
}
public int getSeInt(int tipoDado, int arqRef) {
int valorTab = SEeCE(tipoDado, arqRef);
switch (valorTab) {
case 1:
return 4;
case 2:
return 5;
default:
return 7;
}
}
public String getSeString(int tipoDado, int arqRef) {
int valorTab = SEeCE(tipoDado, arqRef);
switch (valorTab) {
case 1:
return "Baixa";
case 2:
return "Média";
default:
return "Alta";
}
}
public int getCeInt(int tipoDado, int arqRef) {
int valorTab = SEeCE(tipoDado, arqRef);
switch (valorTab) {
case 1:
return 3;
case 2:
return 4;
default:
return 6;
}
}
public String getCeString(int tipoDado, int arqRef) {
int valorTab = SEeCE(tipoDado, arqRef);
switch (valorTab) {
case 1:
return "Baixa";
case 2:
return "Média";
default:
return "Alta";
}
}
public int EE(int tipoDado, int arqRef) {
switch (arqRef) {
case 1:
if (tipoDado <= 15) {
return 1;
} else {
return 2;
}
case 2:
if (tipoDado < 5) {
return 1;
} else {
if (tipoDado > 15) {
return 3;
} else {
return 2;
}
}
default:
if (tipoDado < 5) {
return 2;
} else {
return 3;
}
}
}
public int getEeInt(int tipoDado, int arqRef) {
int valorTab = EE(tipoDado, arqRef);
switch (valorTab) {
case 1:
return 3;
case 2:
return 4;
default:
return 6;
}
}
public String getEeString(int tipoDado, int arqRef) {
int valorTab = EE(tipoDado, arqRef);
switch (valorTab) {
case 1:
return "Baixa";
case 2:
return "Média";
default:
return "Alta";
}
}
public void NI(int[] caracteristicas) {
int total = 0;
for (int i = 0; i < caracteristicas.length; i++) {
total += caracteristicas[i];
}
}
public int getValorComplexidade(String tipo, int complexidade) {
switch (complexidade) {
case 1:
if (tipo.equals("ALI")) {
return 7;
}
if (tipo.equals("AIE")) {
return 5;
}
if (tipo.equals("EE")) {
return 3;
}
if (tipo.equals("SE")) {
return 4;
}
if (tipo.equals("CE")) {
return 3;
}
case 2:
if (tipo.equals("ALI")) {
return 10;
}
if (tipo.equals("AIE")) {
return 7;
}
if (tipo.equals("EE")) {
return 4;
}
if (tipo.equals("SE")) {
return 5;
}
if (tipo.equals("CE")) {
return 4;
}
case 3:
if (tipo.equals("ALI")) {
return 15;
}
if (tipo.equals("AIE")) {
return 10;
}
if (tipo.equals("EE")) {
return 6;
}
if (tipo.equals("SE")) {
return 7;
}
if (tipo.equals("CE")) {
return 6;
}
default:
return -1;
}
}
}
|
[
"caiohobus@gmail.com"
] |
caiohobus@gmail.com
|
ffe7d8f1eb3b93b32d6448a46303d05ec014dcf4
|
f297b804308dc565bf17e65e87ebfe2e2f92b187
|
/src/com/jnvc/scoremanager/ui/Register.java
|
6e835b9561cdae5f5469a13d6ee67536160cc792
|
[] |
no_license
|
chengyu2333/student-score-manager
|
d6ef4565a2a7d4246bfe4e4ffe26d3fbf3a91c7c
|
64322734ac3f53a19932e8c8fa9e101a006fddbe
|
refs/heads/master
| 2021-08-24T00:16:34.621175
| 2017-12-07T07:09:48
| 2017-12-07T07:09:48
| 113,415,281
| 4
| 0
| null | null | null | null |
GB18030
|
Java
| false
| false
| 4,829
|
java
|
package com.jnvc.scoremanager.ui;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.border.EmptyBorder;
import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI;
import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI.NormalColor;
import com.jnvc.scoremanager.dao.PersonDao;
import com.jnvc.scoremanager.model.Person;
import com.jnvc.scoremanager.other.Factory;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
public class Register extends JFrame {
private JPanel panel;
private JTextField textFieldUsername;
private JPasswordField passwordFieldPassword;
private JPasswordField passwordFieldConfirmPassword;
private JTextField textFieldEmail;
private JTextField textFieldNumber;
private JButton buttonRegister;
private Image image = new ImageIcon("res\\bgreg.jpg").getImage();
public Register() {
initialize();
buttonRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if("".equals(textFieldUsername.getText())&&"".equals(passwordFieldConfirmPassword.getText())&&"".equals(passwordFieldPassword.getText())){
JOptionPane.showMessageDialog(Register.this.panel, "请把信息填写完整");
}else if(!passwordFieldPassword.getText().equals(passwordFieldConfirmPassword.getText())){
JOptionPane.showMessageDialog(panel, "密码不一致");
}else{
try {
PersonDao perdao = Factory.getPersonDao();
Person per = new Person(textFieldNumber.getText(),textFieldUsername.getText(),passwordFieldConfirmPassword.getText(),textFieldEmail.getText());
if(perdao.register(per)){
JOptionPane.showMessageDialog(panel, "注册成功");
Register.this.setVisible(false);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(panel, "系统错误");
e1.printStackTrace();
}
}
}
});
}
private void initialize() {
setTitle("注册");
setIconImage(Toolkit.getDefaultToolkit().getImage("res\\icon.png"));
this.setAlwaysOnTop(true);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setResizable(false);
setBounds(0, 0, 292, 313);
setBounds(Tools.getScreenWidth()/2-getWidth()/2, Tools.getScreenHeight()/2-getHeight()/2, 292, 313);
this.setVisible(true);
panel = new JPanel(){
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);
}
};
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(panel);
panel.setLayout(null);
JLabel label = new JLabel("姓名");
label.setHorizontalAlignment(SwingConstants.RIGHT);
label.setBounds(10, 64, 54, 15);
panel.add(label);
JLabel label_1 = new JLabel("密码");
label_1.setHorizontalAlignment(SwingConstants.RIGHT);
label_1.setBounds(10, 102, 54, 15);
panel.add(label_1);
JLabel label_2 = new JLabel("邮箱");
label_2.setHorizontalAlignment(SwingConstants.RIGHT);
label_2.setBounds(10, 172, 54, 15);
panel.add(label_2);
JLabel lblNewLabel = new JLabel("确认密码");
lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
lblNewLabel.setBounds(10, 137, 54, 15);
panel.add(lblNewLabel);
textFieldUsername = new JTextField();
textFieldUsername.setBounds(74, 61, 171, 25);
panel.add(textFieldUsername);
textFieldUsername.setColumns(10);
passwordFieldPassword = new JPasswordField();
passwordFieldPassword.setBounds(74, 99, 171, 25);
panel.add(passwordFieldPassword);
passwordFieldPassword.setColumns(10);
passwordFieldConfirmPassword = new JPasswordField();
passwordFieldConfirmPassword.setBounds(74, 134, 171, 25);
panel.add(passwordFieldConfirmPassword);
passwordFieldConfirmPassword.setColumns(10);
textFieldEmail = new JTextField();
textFieldEmail.setBounds(74, 169, 171, 25);
panel.add(textFieldEmail);
textFieldEmail.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("工号");
lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT);
lblNewLabel_1.setBounds(10, 26, 54, 15);
panel.add(lblNewLabel_1);
textFieldNumber = new JTextField();
textFieldNumber.setBounds(74, 23, 171, 25);
panel.add(textFieldNumber);
textFieldNumber.setColumns(10);
buttonRegister = new JButton("注册");
buttonRegister.setFont(new Font("YaHei Consolas Hybrid", Font.PLAIN, 16));
buttonRegister.setUI(new BEButtonUI().setNormalColor(NormalColor.green));
buttonRegister.setBounds(74, 219, 136, 36);
panel.add(buttonRegister);
}
}
|
[
"858134843@qq.com"
] |
858134843@qq.com
|
89162d57ac760419579e9d5e90be73a3d7d6ae80
|
a43a5329ca28e4c92982a965876f59348a3dc6f2
|
/src/com/example/mobilesafe/Setup3Activity.java
|
e053e067ebf6eee0f79b11e2c2fd9607b2476d8f
|
[] |
no_license
|
Leezhijiang/MobileSafe
|
e32f04e0d8f3844b406223488a80f60928b2b891
|
125b904c2a8691baed099c3fa8e64ba61c9b5440
|
refs/heads/master
| 2020-12-24T21:01:31.917109
| 2016-05-15T04:15:49
| 2016-05-15T04:15:49
| 58,839,538
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 635
|
java
|
package com.example.mobilesafe;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class Setup3Activity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup1);
}
public void next(View v){
Intent intent = new Intent(Setup3Activity.this,Setup4Activity.class);
startActivity(intent);
}
public void pre(View v){
Intent intent = new Intent(Setup3Activity.this,Setup2Activity.class);
startActivity(intent);
}
}
|
[
"450726723@qq.com"
] |
450726723@qq.com
|
15699b1e49fd6202cc4c906d1053cb24bea0cffc
|
203a12d8c2004851e601c5d825a2d090888c6bee
|
/src/main/java/com/info5059/casestudy/PurchaseOrder/POPDFGenerator.java
|
29ef3aee0077d96d5ac084ad3aedd93d0949b5fb
|
[] |
no_license
|
492443886/JavaEE_Client_caseStudy_6
|
83898aaa10f545fe8a941000294ab4b368982a98
|
cd8958bb6731bb6c5d7a33c7edd937ebd19a3fd6
|
refs/heads/main
| 2023-02-26T18:18:47.315300
| 2021-01-15T02:01:47
| 2021-01-15T02:01:47
| 329,782,294
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 9,756
|
java
|
package com.info5059.casestudy.PurchaseOrder;
import com.info5059.casestudy.vendor.Vendor;
import com.info5059.casestudy.vendor.VendorRepository;
import com.info5059.casestudy.product.Product;
import com.info5059.casestudy.product.ProductRepository;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.web.servlet.view.document.AbstractPdfView;
/**
* ExamplePDFGenerator - a class for testing how to create dynamic output in PDF
* format using the iText 5 library
*
* @author Evan
*/
public abstract class POPDFGenerator extends AbstractPdfView {
public static ByteArrayInputStream generateReport(String repid,
PurchaseOrderDAO repDAO,
VendorRepository employeeRepository,
ProductRepository expenseRepository) {
URL imageUrl = com.info5059.casestudy.PurchaseOrder.POPDFGenerator.class.getResource("/public/images/logo.png");
Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Font catFont = new Font(Font.FontFamily.HELVETICA, 24, Font.BOLD);
Font subFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
Font smallBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
Locale locale = new Locale("en", "US");
NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
try {
PurchaseOrder report = repDAO.findOne(Long.parseLong(repid));
PdfWriter.getInstance(document, baos);
document.open();
Paragraph preface = new Paragraph();
// add the logo here
Image image1 = Image.getInstance(imageUrl);
image1.setAbsolutePosition(55f, 750f);
preface.add(image1);
preface.setAlignment(Element.ALIGN_RIGHT);
// Lets write a big header
Paragraph mainHead = new Paragraph(String.format("%55s", "Purchase Order"), catFont);
preface.add(mainHead);
preface.add(new Paragraph(String.format("%90s", "PO#:" + repid), subFont));
addEmptyLine(preface, 3);
// add the employee info for the order here
PdfPTable employeeTable = new PdfPTable(2);
employeeTable.setWidthPercentage(35);
employeeTable.setHorizontalAlignment(Element.ALIGN_LEFT);
Vendor employee = employeeRepository.getOne(report.getVendor().getId());
PdfPCell c1 = new PdfPCell(new Paragraph("Vendor:", smallBold));
c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
c1.setBorder(0);
employeeTable.addCell(c1);
c1 = new PdfPCell(new Phrase(employee.getName()));
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
c1.setBorder(0);
employeeTable.addCell(c1);
c1 = new PdfPCell(new Phrase(""));
c1.setBorder(0);
employeeTable.addCell(c1);
c1 = new PdfPCell(new Phrase(employee.getAddress1()));
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
c1.setBorder(0);
employeeTable.addCell(c1);
c1 = new PdfPCell(new Phrase(""));
c1.setBorder(0);
employeeTable.addCell(c1);
c1 = new PdfPCell(new Phrase(employee.getProvince()));
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
c1.setBorder(0);
employeeTable.addCell(c1);
c1 = new PdfPCell(new Phrase(""));
c1.setBorder(0);
employeeTable.addCell(c1);
c1 = new PdfPCell(new Phrase(employee.getCity()));
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
c1.setBorder(0);
employeeTable.addCell(c1);
c1 = new PdfPCell(new Phrase(""));
c1.setBorder(0);
employeeTable.addCell(c1);
c1 = new PdfPCell(new Phrase(employee.getPostalcode()));
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
c1.setBorder(0);
employeeTable.addCell(c1);
// c1 = new PdfPCell(new Phrase(""));
// c1.setBorder(0);
// employeeTable.addCell(c1);
//
// c1 = new PdfPCell(new Phrase(employee.getEmail()));
// c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
// c1.setBorder(0);
// employeeTable.addCell(c1);
preface.add(employeeTable);
addEmptyLine(preface, 1);
// set up the order details in a table
PdfPTable table = new PdfPTable(5);
c1 = new PdfPCell(new Phrase("Product Code"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Product Description"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Quantity Sold"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);
c1 = new PdfPCell(new Phrase("Price"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Exit Price"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);
table.setHeaderRows(1);
double tot = 0.0;
// dump out the line items
for (PurchaseOrderLineitem line : report.getItems()) {
Product expense = expenseRepository.getOne(line.getProduct().getId());
c1 = new PdfPCell(new Phrase((expense.getId())));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase(expense.getName()));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase(line.getQty() + ""));
c1.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(c1);
c1 = new PdfPCell(new Phrase(formatter.format(line.getPrice())));
c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(c1);
BigDecimal tem = new BigDecimal(line.getQty()) ;
c1 = new PdfPCell(new Phrase(formatter.format(line.getPrice().multiply(tem))));
c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(c1);
}
tot = report.getAmount().doubleValue();
// report total
//line one
c1 = new PdfPCell(new Phrase(""));
c1.setBorder(0);
c1.setColspan(3);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Total:"));
c1.setBorder(0);
c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(c1);
c1 = new PdfPCell(new Phrase(formatter.format(tot)));
c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
c1.setBackgroundColor(BaseColor.YELLOW);
table.addCell(c1);
//line 2
c1 = new PdfPCell(new Phrase(""));
c1.setBorder(0);
c1.setColspan(3);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Tax:"));
c1.setBorder(0);
c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(c1);
c1 = new PdfPCell(new Phrase(formatter.format(tot* 0.13)));
c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
c1.setBackgroundColor(BaseColor.YELLOW);
table.addCell(c1);
//line 3
c1 = new PdfPCell(new Phrase(""));
c1.setBorder(0);
c1.setColspan(3);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Order Total:"));
c1.setBorder(0);
c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(c1);
c1 = new PdfPCell(new Phrase(formatter.format(tot * 1.13)));
c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
c1.setBackgroundColor(BaseColor.YELLOW);
table.addCell(c1);
///add
preface.add(table);
addEmptyLine(preface, 3);
// footer for date
preface.setAlignment(Element.ALIGN_CENTER);
Date date = report.getPodate();
String tem = (date+"").substring(0,10);
preface.add(new Paragraph(String.format("%85s", "PO Generated on: " + tem, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
smallBold)));
document.add(preface);
document.close();
} catch (Exception ex) {
Logger.getLogger(POPDFGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
return new ByteArrayInputStream(baos.toByteArray());
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
}
|
[
"machunhui492443886@gmail.com"
] |
machunhui492443886@gmail.com
|
3cfe1c771fe3b86885b68e8c5dd26a6e399de7b9
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/27/27_82ba0405553bf15d8243ec06e73bd75072f83170/BookingAction/27_82ba0405553bf15d8243ec06e73bd75072f83170_BookingAction_t.java
|
c67d63dce59d70d1ebe9bf9f44dcc956cb7e2dd9
|
[] |
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
| 30,280
|
java
|
/*******************************************************************************
*
* Copyright 2011 - Sardegna Ricerche, Distretto ICT, Pula, Italy
*
* Licensed under the EUPL, Version 1.1.
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* http://www.osor.eu/eupl
*
* Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and limitations under the Licence.
* In case of controversy the competent court is the Court of Cagliari (Italy).
*******************************************************************************/
package action;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.time.DateUtils;
import model.Adjustment;
import model.ExtraItem;
import model.Booking;
import model.Extra;
import model.Guest;
import model.Payment;
import model.Room;
import model.RoomType;
import model.UserAware;
import model.internal.Message;
import model.listini.Convention;
import model.listini.Season;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;
import service.BookingService;
import service.ConventionService;
import service.ExtraService;
import service.GuestService;
import service.RoomService;
import service.SeasonService;
import service.StructureService;
import com.opensymphony.xwork2.ActionSupport;
@ParentPackage( value="default")
@InterceptorRefs({
@InterceptorRef("userAwareStack")
})
@Result(name="notLogged", location="/WEB-INF/jsp/homeNotLogged.jsp")
public class BookingAction extends ActionSupport implements SessionAware,UserAware{
private Map<String, Object> session = null;
private List<Booking> bookings = null;
private Booking booking = null;
private String dateIn = null;
private Integer id;
private Integer numNights;
private List<Room> rooms = null;
private Message message = new Message();
private String dateOut = null;
private List<Extra> extras = null;
private List<Convention> conventions = null;
private List<Integer> bookingExtraIds = new ArrayList();
private Double adjustmentsSubtotal = 0.0;
private Double paymentsSubtotal = 0.0;
private Integer idStructure;
private List<Integer> listNumGuests = null;
@Autowired
private ExtraService extraService = null;
@Autowired
private GuestService guestService = null;
@Autowired
private StructureService structureService = null;
@Autowired
private BookingService bookingService = null;
@Autowired
private RoomService roomService = null;
@Autowired
private ConventionService conventionService = null;
@Autowired
private SeasonService seasonService = null;
@Actions({
@Action(
value="/updateBookingDates",results = {
@Result(type ="json",name="success", params={
"excludeProperties","session,extraService,guestService,structureService,bookingService,roomService,conventionService,seasonService"
}),
@Result(type ="json",name="error", params={
"excludeProperties","session,extraService,guestService,structureService,bookingService,roomService,conventionService,seasonService"
}),
@Result(name="input", location = "/WEB-INF/jsp/validationError.jsp")
})
})
public String updateBookingDates() {
Integer numNights;
Booking booking = null;
if(!this.checkBookingDates(this.getIdStructure())){
return ERROR;
}
booking = (Booking) this.getSession().get("booking");
booking.setDateIn(this.getBooking().getDateIn());
booking.setDateOut(this.getBooking().getDateOut());
this.updateRoomSubtotal(booking);
this.updateUnitaryPriceInBookedExtraItems(booking);
this.updateMaxQuantityInBookedExtraItems(booking);
this.updateQuantityInBookedExtraItems(booking);
booking.updateExtraSubtotal();
this.setBooking(booking);
numNights = booking.calculateNumNights();
this.setNumNights(numNights);
this.getMessage().setResult(Message.SUCCESS);
this.getMessage().setDescription(getText("calculatedPriceAction"));
return "success";
}
@Actions({
@Action(value="/updateRoom",results = {
@Result(type ="json",name="success", params={
"excludeProperties","session,extraService,guestService,structureService,bookingService,roomService,conventionService,seasonService"
}),
@Result(type ="json",name="error", params={
"excludeProperties","session,extraService,guestService,structureService,bookingService,roomService,conventionService,seasonService"
}),
@Result(name="input", location = "/WEB-INF/jsp/validationError.jsp")
})
})
public String updateRoom() {
Integer numGuests;
Booking booking = null;
RoomType newRoomType = null;
RoomType oldRoomType = null;
if(!this.checkBookingDates(this.getIdStructure())){
return ERROR;
}
booking = (Booking) this.getSession().get("booking");
if(booking.getRoom()!=null){
oldRoomType = booking.getRoom().getRoomType();
}
this.updateRoom(booking);
if(booking.getRoom()!=null){
newRoomType = booking.getRoom().getRoomType();
}
//If the Room Type changes, prices must be updated
if((oldRoomType!= null) && (newRoomType!= null) && !(oldRoomType.equals(newRoomType) )){
numGuests = booking.getNrGuests();
if (numGuests > newRoomType.getMaxGuests()) { //when changing a room which has pre-selected the nrGuests attribute greater than the maxGuests attribute
numGuests = newRoomType.getMaxGuests();
booking.setNrGuests(numGuests);
//If nrGuests changes, extra items' max quantity must be updated
this.updateMaxQuantityInBookedExtraItems(booking);
}
this.updateRoomSubtotal(booking);
this.updateUnitaryPriceInBookedExtraItems(booking);
booking.updateExtraSubtotal();
}
this.setBooking(booking);
this.updateListNumGuests(booking);
this.getMessage().setResult(Message.SUCCESS);
this.getMessage().setDescription(getText("calculatedPriceAction"));
return "success";
}
private void updateRoom(Booking booking){
Room newRoom = null;
newRoom = this.getRoomService().findRoomById(this.getBooking().getRoom().getId());
booking.setRoom(newRoom);
}
@Actions({
@Action(value="/updateNrGuests",results = {
@Result(type ="json",name="success", params={
"excludeProperties","session,extraService,guestService,structureService,bookingService,roomService,conventionService,seasonService"
}),
@Result(type ="json",name="error", params={
"excludeProperties","session,extraService,guestService,structureService,bookingService,roomService,conventionService,seasonService"
}),
@Result(name="input", location = "/WEB-INF/jsp/validationError.jsp")
})
})
public String updateNrGuests() {
Booking booking = null;
if(!this.checkBookingDates(this.getIdStructure())){
return ERROR;
}
booking = (Booking) this.getSession().get("booking");
booking.setNrGuests(this.getBooking().getNrGuests());
this.updateRoomSubtotal(booking);
this.updateMaxQuantityInBookedExtraItems(booking);
this.updateQuantityInBookedExtraItems(booking);
booking.updateExtraSubtotal();
this.setBooking(booking);
this.getMessage().setResult(Message.SUCCESS);
this.getMessage().setDescription(getText("calculatedPriceAction"));
return "success";
}
@Actions({
@Action(value="/updateExtras",results = {
@Result(type ="json",name="success", params={
"excludeProperties","session,extraService,guestService,structureService,bookingService,roomService,conventionService,seasonService"
}),
@Result(type ="json",name="error", params={
"excludeProperties","session,extraService,guestService,structureService,bookingService,roomService,conventionService,seasonService"
}),
@Result(name="input", location = "/WEB-INF/jsp/validationError.jsp")
})
})
public String updateExtras() {
Booking booking = null;
List<Extra> checkedExtras = null;
List<Integer> filteredBookingExtraIds = null;
Integer anInt;
if(!this.checkBookingDatesNotNull(this.getIdStructure())){
return ERROR;
}
booking = (Booking) this.getSession().get("booking");
filteredBookingExtraIds = new ArrayList<Integer>();
for(Object each: this.getBookingExtraIds()){
try{
anInt = Integer.parseInt((String)each);
filteredBookingExtraIds.add(anInt);
}catch (Exception e) {
}
}
checkedExtras = this.getExtraService().findExtrasByIds(filteredBookingExtraIds);
this.updateExtraItems(booking,checkedExtras);
booking.updateExtraSubtotal();
this.setBooking(booking);
this.getMessage().setResult(Message.SUCCESS);
this.getMessage().setDescription(getText("calculatedPriceAction"));
return "success";
}
@Actions({
@Action(value="/updateConvention",results = {
@Result(type ="json",name="success", params={
"excludeProperties","session,extraService,guestService,structureService,bookingService,roomService,conventionService,seasonService"
}),
@Result(type ="json",name="error", params={
"excludeProperties","session,extraService,guestService,structureService,bookingService,roomService,conventionService,seasonService"
}),
@Result(name="input", location = "/WEB-INF/jsp/validationError.jsp")
})
})
public String updateConvention() {
Booking booking = null;
if(!this.checkBookingDates(this.getIdStructure())){
return ERROR;
}
booking = (Booking) this.getSession().get("booking");
booking.setConvention(this.getBooking().getConvention());
//If the convention changes, then room and extra prices must be updated
this.updateRoomSubtotal(booking);
this.updateUnitaryPriceInBookedExtraItems(booking);
booking.updateExtraSubtotal();
this.setBooking(booking);
this.getMessage().setResult(Message.SUCCESS);
this.getMessage().setDescription(getText("calculatedPriceAction"));
return "success";
}
private void updateExtraItems(Booking booking,List<Extra> checkedExtras){
ExtraItem extraItem = null;
List<ExtraItem> extraItems = null;
extraItems = new ArrayList<ExtraItem>();
for(Extra each: checkedExtras){
extraItem = null;
for(ExtraItem bookedExtraItem: this.getBooking().getExtraItems()){
//each already exists and I have to update just the quantity reading it from the request
if(bookedExtraItem.getExtra().equals(each)){
extraItem = bookedExtraItem;
extraItem.setExtra(each);//in some cases extraItem.extra had only the id and not all the other attributes
extraItem.setMaxQuantity(booking.calculateExtraItemMaxQuantity(each));
}
}
if(extraItem == null){
//each is a new extra, so a new extra item must be created
extraItem = new ExtraItem();
extraItem.setExtra(each);
extraItem.setQuantity(booking.calculateExtraItemMaxQuantity(each));
extraItem.setMaxQuantity(booking.calculateExtraItemMaxQuantity(each));
extraItem.setUnitaryPrice(
this.getStructureService().calculateExtraItemUnitaryPrice(this.getIdStructure(), booking.getDateIn(), booking.getDateOut(), booking.getRoom().getRoomType(), booking.getConvention(), each));
}
extraItems.add(extraItem);
}
booking.setExtraItems(extraItems);
}
private void updateRoomSubtotal(Booking booking){
Double roomSubtotal = 0.0;
roomSubtotal = this.getBookingService().calculateRoomSubtotalForBooking(this.getIdStructure(),booking);
booking.setRoomSubtotal(roomSubtotal);
}
private void updateMaxQuantityInBookedExtraItems(Booking booking){
Integer maxQuantity;
for(ExtraItem each: booking.getExtraItems()){
maxQuantity = booking.calculateExtraItemMaxQuantity(each.getExtra());
each.setMaxQuantity(maxQuantity);
}
}
private void updateQuantityInBookedExtraItems(Booking booking){
Integer maxQuantity;
for(ExtraItem each: booking.getExtraItems()){
maxQuantity = booking.calculateExtraItemMaxQuantity(each.getExtra());
each.setQuantity(maxQuantity);
}
}
private void updateUnitaryPriceInBookedExtraItems(Booking booking){
Double unitaryPrice;
if((booking.getDateIn()!=null) && (booking.getDateOut()!=null)){
for(ExtraItem each: booking.getExtraItems()){
unitaryPrice = this.getStructureService().calculateExtraItemUnitaryPrice(this.getIdStructure(), booking.getDateIn(), booking.getDateOut(), booking.getRoom().getRoomType(), booking.getConvention(), each.getExtra());
each.setUnitaryPrice(unitaryPrice);
}
}
}
@Actions({
@Action(value="/displayQuantitySelect",results = {
@Result(name="success",location="/WEB-INF/jsp/contents/extraQuantity_select.jsp")
})
})
public String displayQuantitySelect() {
this.setExtras(this.getExtraService().findExtrasByIdStructure(this.getIdStructure()));
this.setBooking((Booking) this.getSession().get("booking"));
return SUCCESS;
}
@Actions({
@Action(value="/saveUpdateBooking",results = {
@Result(type ="json",name="success", params={"root","message"}),
@Result(name="input", location="/WEB-INF/jsp/validationError.jsp"),
@Result(type ="json",name="error", params={
"root","message"
})
})
})
public String saveUpdateBooking(){
Guest booker = null;
Booking booking = null;
Convention convention = null;
if(!this.checkBookingDates(this.getIdStructure())){
return ERROR;
}
if(!this.checkBookingChecking()){
return ERROR;
}
booking = (Booking) this.getSession().get("booking");
//Adjustments
this.filterAdjustments();
booking.setAdjustments(this.getBooking().getAdjustments());
//Payments
this.filterPayments();
booking.setPayments(this.getBooking().getPayments());
//ExtraItems: no need to filter them, because they're not updated at every updateExtras() call
//Guests: da inserire quando ci saranno i guests
/*
this.filterGuests();
booking.setGuests(this.getBooking().getGuests());
*/
booker = this.getBooking().getBooker();
booker.setId_structure(this.getIdStructure());
booking.setBooker(booker);
booking.setId_room(this.getBooking().getRoom().getId());
convention = booking.getConvention();
booking.setId_convention(convention.getId());
booking.setStatus(this.getBooking().getStatus());
booking.setId_structure(this.getIdStructure());
this.getBookingService().saveUpdateBooking(booking);
this.getSession().put("booking", booking);
this.getMessage().setResult(Message.SUCCESS);
this.getMessage().setDescription(getText("bookingAddUpdateSuccessAction"));
return SUCCESS;
}
@Actions({
@Action(value="/goAddBookingFromPlanner",results = {
@Result(name="success",location="/WEB-INF/jsp/contents/booking_form.jsp"),
@Result(name="input", location="/WEB-INF/jsp/validationError.jsp")
})
})
public String goAddNewBookingFromPlanner() {
Room theBookedRoom = null;
Convention defaultConvention = null;
Integer numNights = 0;
Double roomSubtotal = 0.0;
Booking booking = null;
booking = new Booking();
this.getSession().put("booking", booking);
booking.setDateIn(this.getBooking().getDateIn());
booking.setDateOut(this.getBooking().getDateOut());
theBookedRoom = this.getRoomService().findRoomById(this.getBooking().getRoom().getId());
booking.setRoom(theBookedRoom);
this.updateListNumGuests(booking);
defaultConvention = this.getConventionService().findConventionsByIdStructure(this.getIdStructure()).get(0);
booking.setConvention(defaultConvention);
roomSubtotal = this.getBookingService().calculateRoomSubtotalForBooking(this.getIdStructure(),booking);
booking.setRoomSubtotal(roomSubtotal);
this.setBooking(booking);
this.setRooms(this.getRoomService().findRoomsByIdStructure(this.getIdStructure()));
this.setExtras(this.getExtraService().findExtrasByIdStructure(this.getIdStructure()));
this.setConventions(this.getConventionService().findConventionsByIdStructure(this.getIdStructure()));
numNights = booking.calculateNumNights();
this.setNumNights(numNights);
return SUCCESS;
}
@Actions({
@Action(value="/goAddNewBooking",results = {
@Result(name="success",location="/WEB-INF/jsp/booking.jsp")
})
})
public String goAddNewBooking() {
Convention defaultConvention = null;
Booking booking = null;
booking = new Booking();
this.getSession().put("booking", booking);
defaultConvention = this.getConventionService().findConventionsByIdStructure(this.getIdStructure()).get(0);
booking.setConvention(defaultConvention);
this.setBooking(booking);
this.setRooms(this.getRoomService().findRoomsByIdStructure(this.getIdStructure()));
this.setExtras(this.getExtraService().findExtrasByIdStructure(this.getIdStructure()));
this.setConventions(this.getConventionService().findConventionsByIdStructure(this.getIdStructure()));
this.setListNumGuests(new ArrayList<Integer>());
return SUCCESS;
}
@Actions({
@Action(value="/goAddNewBookingFromGuest",results = {
@Result(name="success",location="/WEB-INF/jsp/booking.jsp")
})
})
public String goAddNewBookingFromGuest() {
Convention defaultConvention = null;
Booking booking = null;
Guest booker = null;
booking = new Booking();
this.getSession().put("booking", booking);
defaultConvention = this.getConventionService().findConventionsByIdStructure(this.getIdStructure()).get(0);
booking.setConvention(defaultConvention);
//booker settings..
booker = this.getGuestService().findGuestById(this.getId());
booking.setBooker(booker);
this.setBooking(booking);
this.setRooms(this.getRoomService().findRoomsByIdStructure(this.getIdStructure()));
this.setExtras(this.getExtraService().findExtrasByIdStructure(this.getIdStructure()));
this.setConventions(this.getConventionService().findConventionsByIdStructure(this.getIdStructure()));
this.setListNumGuests(new ArrayList<Integer>());
return SUCCESS;
}
@Actions({
@Action(value="/goUpdateBooking",results = {
@Result(name="success",location="/WEB-INF/jsp/booking.jsp")
}),
@Action(value="/goUpdateBookingFromPlanner",results = {
@Result(name="success",location="/WEB-INF/jsp/contents/booking_form.jsp")
})
})
public String goUpdateBooking() {
Booking booking = null;
Integer numNights = 0;
Double adjustmentsSubtotal = 0.0;
Double paymentsSubtotal = 0.0;
booking = this.getBookingService().findBookingById(this.getId());
this.getSession().put("booking", booking);
this.setBooking(booking);
this.setRooms(this.getRoomService().findRoomsByIdStructure(this.getIdStructure()));
this.setExtras(this.getExtraService().findExtrasByIdStructure(this.getIdStructure()));
this.setBookingExtraIds(booking.calculateExtraIds());
this.setConventions(this.getConventionService().findConventionsByIdStructure(this.getIdStructure()));
numNights = this.getBooking().calculateNumNights();
this.setNumNights(numNights);
adjustmentsSubtotal = this.getBooking().calculateAdjustmentsSubtotal();
this.setAdjustmentsSubtotal(adjustmentsSubtotal);
paymentsSubtotal = this.getBooking().calculatePaymentsSubtotal();
this.setPaymentsSubtotal(paymentsSubtotal);
this.updateListNumGuests(booking);
return SUCCESS;
}
@Actions({
@Action(value="/findAllBookingsJson",results = {
@Result(type ="json",name="success", params={"root","bookings"})
})
})
public String findAllBookings(){
this.setBookings(this.getBookingService().findBookingsByIdStructure(this.getIdStructure()));
return SUCCESS;
}
@Actions({
@Action(value="/checkBookingDates",results = {
@Result(type ="json",name="success", params={"root","message"}),
@Result(name="input", location="/WEB-INF/jsp/validationError.jsp"),
@Result(type ="json",name="error", params={"root","message"})
})
})
public String checkBookingDates(){
if(!this.checkBookingDates(this.getIdStructure())){
return ERROR;
}
return SUCCESS;
}
@Actions({
@Action(value="/checkBookingDatesNotNull",results = {
@Result(type ="json",name="success", params={"root","message"}),
@Result(name="input", location="/WEB-INF/jsp/validationError.jsp"),
@Result(type ="json",name="error", params={"root","message"})
})
})
public String checkBookingDatesNotNull(){
if(!this.checkBookingDatesNotNull(this.getIdStructure())){
return ERROR;
}
return SUCCESS;
}
private Boolean checkBookingDates(Integer id_structure) {
List<Date> bookingDates = null;
Season season = null;
if(this.getBooking().getDateIn()!=null && this.getBooking().getDateOut()!=null){
if(!this.getBooking().checkDates()){
this.getMessage().setResult(Message.ERROR);
this.getMessage().setDescription(getText("dateOutMoreDateInAction"));
return false;
}
if ((this.getBooking().getRoom().getId()!=null) && (!this.getStructureService().hasRoomFreeForBooking(id_structure,this.getBooking()))) {
this.getMessage().setResult(Message.ERROR);
this.getMessage().setDescription(getText("bookingOverlappedAction"));
return false;
}
bookingDates = this.getBooking().calculateBookingDates();
for(Date aBookingDate: bookingDates){
season = this.getSeasonService().findSeasonByDate(id_structure,aBookingDate );
if(season == null){
this.getMessage().setResult(Message.ERROR);
this.getMessage().setDescription(getText("periodSeasonError"));
return false;
}
}
}
this.getMessage().setDescription(getText("bookingDatesOK"));
this.getMessage().setResult(Message.SUCCESS);
return true;
}
private Boolean checkBookingDatesNotNull(Integer id_structure) {
List<Date> bookingDates = null;
Season season = null;
if(this.getBooking().getDateIn()!=null && this.getBooking().getDateOut()!=null){
if(!this.getBooking().checkDates()){
this.getMessage().setResult(Message.ERROR);
this.getMessage().setDescription(getText("dateOutMoreDateInAction"));
return false;
}
if ((this.getBooking().getRoom().getId()!=null) && (!this.getStructureService().hasRoomFreeForBooking(id_structure,this.getBooking()))) {
this.getMessage().setResult(Message.ERROR);
this.getMessage().setDescription(getText("bookingOverlappedAction"));
return false;
}
bookingDates = this.getBooking().calculateBookingDates();
for(Date aBookingDate: bookingDates){
season = this.getSeasonService().findSeasonByDate(id_structure,aBookingDate );
if(season == null){
this.getMessage().setResult(Message.ERROR);
this.getMessage().setDescription(getText("periodSeasonError"));
return false;
}
}
}
else{
this.getMessage().setResult(Message.ERROR);
this.getMessage().setDescription(getText("bookingNotChosenDates"));
return false;
}
this.getMessage().setDescription(getText("bookingDatesOK"));
this.getMessage().setResult(Message.SUCCESS);
return true;
}
private Boolean checkBookingChecking(){
Date dateOut = this.getBooking().getDateOut();
String status = this.getBooking().getStatus();
if(status!=null && status.equals("checkedout") && dateOut!=null){
if (DateUtils.truncatedCompareTo(Calendar.getInstance().getTime(), dateOut,Calendar.DAY_OF_MONTH) < 0)
{
this.getMessage().setResult(Message.ERROR);
this.getMessage().setDescription(getText("bookingCheckOutDateError"));
return false;
}
}
return true;
}
private void filterAdjustments(){
List<Adjustment> adjustmentsWithoutNulls = null;
adjustmentsWithoutNulls = new ArrayList<Adjustment>();
for(Adjustment each: this.getBooking().getAdjustments()){
if(each!=null){
adjustmentsWithoutNulls.add(each);
}
}
this.getBooking().setAdjustments(adjustmentsWithoutNulls);
}
private void filterPayments(){
List<Payment> paymentsWithoutNulls = null;
paymentsWithoutNulls = new ArrayList<Payment>();
for(Payment each: this.getBooking().getPayments()){
if(each!=null){
paymentsWithoutNulls.add(each);
}
}
this.getBooking().setPayments(paymentsWithoutNulls);
}
@Actions({
@Action(value="/deleteBooking",results = {
@Result(type ="json",name="success", params={"root","message"}),
@Result(type ="json",name="error", params={"root","message"})
})
})
public String deleteBooking() {
Integer count = 0;
count = this.getBookingService().deleteBooking(this.getBooking().getId());
if(count > 0 ){
this.getMessage().setResult(Message.SUCCESS);
this.getMessage().setDescription(getText("bookingDeleteSuccessAction"));
return "success";
}else{
this.getMessage().setResult(Message.ERROR);
this.getMessage().setDescription(getText("bookingDeleteErrorAction"));
return "error";
}
}
@Actions({
@Action(value="/goOnlineBookings",results = {
@Result(name="success",location="/WEB-INF/jsp/onlineBookings.jsp")
})
})
public String goOnlineBookings(){
return SUCCESS;
}
private void updateListNumGuests(Booking booking){
List<Integer> listNumGuests = null;
Integer maxGuests = 0;
listNumGuests = new ArrayList<Integer>();
maxGuests = booking.getRoom().getRoomType().getMaxGuests();
for (Integer i= 1; i<= maxGuests; i++) {
listNumGuests.add(i);
}
this.setListNumGuests(listNumGuests);
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Map<String, Object> getSession() {
return session;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
public Booking getBooking() {
return booking;
}
public void setBooking(Booking booking) {
this.booking = booking;
}
public List<Booking> getBookings() {
return bookings;
}
public void setBookings(List<Booking> bookings) {
this.bookings = bookings;
}
public String getDateIn() {
return dateIn;
}
public void setDateIn(String dateIn) {
this.dateIn = dateIn;
}
public Integer getNumNights() {
return numNights;
}
public void setNumNights(Integer numNights) {
this.numNights = numNights;
}
public List<Room> getRooms() {
return rooms;
}
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
}
public String getDateOut() {
return dateOut;
}
public void setDateOut(String dateOut) {
this.dateOut = dateOut;
}
public List<Extra> getExtras() {
return extras;
}
public void setExtras(List<Extra> extras) {
this.extras = extras;
}
public List<Integer> getBookingExtraIds() {
return bookingExtraIds;
}
public void setBookingExtraIds(List<Integer> bookingExtraIds) {
this.bookingExtraIds = bookingExtraIds;
}
public Double getAdjustmentsSubtotal() {
return adjustmentsSubtotal;
}
public void setAdjustmentsSubtotal(Double adjustmentsSubtotal) {
this.adjustmentsSubtotal = adjustmentsSubtotal;
}
public Double getPaymentsSubtotal() {
return paymentsSubtotal;
}
public void setPaymentsSubtotal(Double paymentsSubtotal) {
this.paymentsSubtotal = paymentsSubtotal;
}
public List<Convention> getConventions() {
return conventions;
}
public void setConventions(List<Convention> conventions) {
this.conventions = conventions;
}
public Integer getIdStructure() {
return idStructure;
}
public void setIdStructure(Integer idStructure) {
this.idStructure = idStructure;
}
public List<Integer> getListNumGuests() {
return listNumGuests;
}
public void setListNumGuests(List<Integer> listNumGuests) {
this.listNumGuests = listNumGuests;
}
public ExtraService getExtraService() {
return extraService;
}
public void setExtraService(ExtraService extraService) {
this.extraService = extraService;
}
public GuestService getGuestService() {
return guestService;
}
public void setGuestService(GuestService guestService) {
this.guestService = guestService;
}
public StructureService getStructureService() {
return structureService;
}
public void setStructureService(StructureService structureService) {
this.structureService = structureService;
}
public BookingService getBookingService() {
return bookingService;
}
public void setBookingService(BookingService bookingService) {
this.bookingService = bookingService;
}
public RoomService getRoomService() {
return roomService;
}
public void setRoomService(RoomService roomService) {
this.roomService = roomService;
}
public ConventionService getConventionService() {
return conventionService;
}
public void setConventionService(ConventionService conventionService) {
this.conventionService = conventionService;
}
public SeasonService getSeasonService() {
return seasonService;
}
public void setSeasonService(SeasonService seasonService) {
this.seasonService = seasonService;
}
}
|
[
"yuzhongxing88@gmail.com"
] |
yuzhongxing88@gmail.com
|
981e692a885f2a3a3d4fa43a41e061e460d9c2f9
|
1f4f0867fafe5b3cbe165061b98b341fc5d0fe0c
|
/app/src/main/java/me/nickcruz/jsonpokemon/api/GetPokemonEndpoint.java
|
0719bc4956f21847349f1551ecb210e9b6ddce18
|
[] |
no_license
|
nickcruz/json-pokemon-list
|
891e114962b366ef3bc86d48c9065a09f91ca3b8
|
6194122e9157fbee5b7d3381ab42e97bcf522047
|
refs/heads/master
| 2020-07-26T03:26:15.505306
| 2019-09-15T19:27:56
| 2019-09-15T19:27:56
| 208,519,265
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,242
|
java
|
package me.nickcruz.jsonpokemon.api;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import me.nickcruz.jsonpokemon.PokemonModel;
import me.nickcruz.jsonpokemon.repository.ErrorHandler;
public class GetPokemonEndpoint {
private static final String TAG = GetPokemonEndpoint.class.getSimpleName();
private static final String PATH = "pokemon/";
public Request<String> getPokemon(final GetPokemonResponseHandler getPokemonResponseHandler) {
return new StringRequest(Request.Method.GET, getURL(), new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
getPokemonResponseHandler.onGetPokemonResponse(parseResponse(response));
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
getPokemonResponseHandler.onError(e.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
getPokemonResponseHandler.onError(error.getMessage());
}
});
}
public List<PokemonModel> parseResponse(String response) throws JSONException {
List<PokemonModel> pokemon = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
JSONArray results = jsonObject.getJSONArray("results");
for (int i = 0; i < results.length(); ++i) {
JSONObject result = (JSONObject) results.get(i);
String name = result.getString("name");
String url = result.getString("url");
pokemon.add(new PokemonModel(name, url));
}
return pokemon;
}
private String getURL() {
return PokemonAPI.API_BASE + PATH;
}
public interface GetPokemonResponseHandler extends ErrorHandler {
void onGetPokemonResponse(List<PokemonModel> pokemon);
}
}
|
[
"ncruz@umich.edu"
] |
ncruz@umich.edu
|
e31b4f6ac7a38a2f7c017a38697a8bbcad1ee267
|
e3c93cbfebdccbdcc9a0195cfa4bac089f09b885
|
/SchoolReserve-base/src/main/java/xiumu/SchoolReserve/base/web/spring/controller/GenericTreeController.java
|
e6993f2e0656306b81e579c225567d207a2765d1
|
[] |
no_license
|
SiuMu/Study
|
d3d1f7e817371bb10679cfdfe6fd5d7366b81b97
|
a13f2f9577b1400ddfd3869cd810d88af19172e9
|
refs/heads/master
| 2021-06-03T04:20:48.276481
| 2018-06-20T07:07:59
| 2018-06-20T07:07:59
| 124,475,763
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,556
|
java
|
package xiumu.SchoolReserve.base.web.spring.controller;
import xiumu.SchoolReserve.base.domain.BaseTreeEntity;
import xiumu.SchoolReserve.base.service.GenericTreeManager;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.Serializable;
import java.util.List;
@NoRepositoryBean
public abstract class GenericTreeController<T extends BaseTreeEntity<T>, PK extends Serializable, M extends GenericTreeManager<T, PK>>
extends GenericController<T, PK, M> {
protected M treeManager;
/**
* 得到树结构;
*
* @param request
* @param response
* @return
*/
@ResponseBody
@RequestMapping(value = "/getChildren/{id}", method = RequestMethod.GET, produces = "application/json")
public List<T> getChildren(@PathVariable PK id) {
List<T> result = this.treeManager.getChildren(id);
logger.info(result);
return result;
}
/**
* 得到树结构;
*
* @param request
* @param response
* @return
*/
@ResponseBody
@RequestMapping(value = "/getTree/{id}", method = RequestMethod.GET, produces = "application/json")
public List<T> getTree(@PathVariable PK id) {
List<T> result = null;
if (id == null) {
result = this.treeManager.getRoot();
} else {
T node = this.treeManager.findById(id);
result = node.getChildren();
}
return result;
}
}
|
[
"37199920+SiuMu@users.noreply.github.com"
] |
37199920+SiuMu@users.noreply.github.com
|
f32844b731641633ef35d40c160629a7b31809de
|
784a1e3b8cdf37d00c65244f1fb57cc8a1046f10
|
/Doctor/app/src/main/java/com/xina/doctor/Models/ProfileDetail.java
|
5f07a6662a4b155f740a2acf10ea3d8dd845f52e
|
[] |
no_license
|
mubarakgauri01/Doctor
|
9c6ad18b232c2195cec6d9b1200f511588392d7d
|
ce85f23a07782c0de7727d11ff9ee90bbe6ab55a
|
refs/heads/master
| 2020-04-01T16:52:03.121206
| 2018-10-17T05:46:29
| 2018-10-17T05:46:29
| 153,401,834
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,334
|
java
|
package com.xina.doctor.Models;
import com.google.gson.annotations.SerializedName;
public class ProfileDetail {
@SerializedName("image")
private String image;
@SerializedName("last_login")
private String lastLogin;
@SerializedName("degree")
private String degree;
@SerializedName("mobile")
private String mobile;
@SerializedName("userid")
private String userid;
@SerializedName("speciality")
private String speciality;
@SerializedName("password")
private String password;
@SerializedName("token_id")
private String tokenId;
@SerializedName("name")
private String name;
@SerializedName("id")
private String id;
@SerializedName("create_at")
private String createAt;
@SerializedName("email")
private String email;
@SerializedName("status")
private String status;
public void setImage(String image){
this.image = image;
}
public String getImage(){
return image;
}
public void setLastLogin(String lastLogin){
this.lastLogin = lastLogin;
}
public String getLastLogin(){
return lastLogin;
}
public void setDegree(String degree){
this.degree = degree;
}
public String getDegree(){
return degree;
}
public void setMobile(String mobile){
this.mobile = mobile;
}
public String getMobile(){
return mobile;
}
public void setUserid(String userid){
this.userid = userid;
}
public String getUserid(){
return userid;
}
public void setSpeciality(String speciality){
this.speciality = speciality;
}
public String getSpeciality(){
return speciality;
}
public void setPassword(String password){
this.password = password;
}
public String getPassword(){
return password;
}
public void setTokenId(String tokenId){
this.tokenId = tokenId;
}
public String getTokenId(){
return tokenId;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setId(String id){
this.id = id;
}
public String getId(){
return id;
}
public void setCreateAt(String createAt){
this.createAt = createAt;
}
public String getCreateAt(){
return createAt;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return email;
}
public void setStatus(String status){
this.status = status;
}
public String getStatus(){
return status;
}
}
|
[
"mubarak.mohd@xinatechnologies.com"
] |
mubarak.mohd@xinatechnologies.com
|
c4c1d55929ced1c7eeb2972d6069025e8c286fe7
|
c7a55c776732af8172eae39666711af3df5b6be2
|
/src/com/android/launcher/NumberPickerButton.java
|
8aad19a0ba05e712d3a4b55cb554f8b35e3dc9d3
|
[
"Apache-2.0"
] |
permissive
|
voku/android_packages_apps_ADWLauncher
|
e241276d308ada41e2ab33e80e8bd4aa6ab60b26
|
4401ac9bf5a0b39b89b6e6f659978c56f9d36b38
|
refs/heads/gingerbread
| 2021-01-18T07:30:36.705277
| 2011-05-02T18:59:08
| 2012-03-24T13:21:43
| 2,904,879
| 0
| 0
|
NOASSERTION
| 2020-12-16T16:52:10
| 2011-12-03T13:09:52
|
Java
|
UTF-8
|
Java
| false
| false
| 2,502
|
java
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.ImageButton;
/**
* This class exists purely to cancel long click events.
*/
public class NumberPickerButton extends ImageButton {
private NumberPicker mNumberPicker;
public NumberPickerButton(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public NumberPickerButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NumberPickerButton(Context context) {
super(context);
}
public void setNumberPicker(NumberPicker picker) {
mNumberPicker = picker;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
cancelLongpressIfRequired(event);
return super.onTouchEvent(event);
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
cancelLongpressIfRequired(event);
return super.onTrackballEvent(event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
|| (keyCode == KeyEvent.KEYCODE_ENTER)) {
cancelLongpress();
}
return super.onKeyUp(keyCode, event);
}
private void cancelLongpressIfRequired(MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_CANCEL)
|| (event.getAction() == MotionEvent.ACTION_UP)) {
cancelLongpress();
}
}
private void cancelLongpress() {
if (R.id.increment == getId()) {
mNumberPicker.cancelIncrement();
} else if (R.id.decrement == getId()) {
mNumberPicker.cancelDecrement();
}
}
}
|
[
"anderweb@gmail.com"
] |
anderweb@gmail.com
|
24c71d979c3787eae354bfa7bded742e1357238f
|
10b0c5e46d25a802a4722fa0e5cc1f78da5ed101
|
/BabyMonitor/src/com/sher/babymonitor/MJpegHttpStreamer.java
|
5f1c95e432061a348b828ee9a227d2b44aebbe05
|
[] |
no_license
|
oaky87/BabyMonitor
|
c42416625c60a248477ff013fc841d01ad6e9d64
|
23aface733dbaa2ba9f8298e177c99a8e39b7595
|
refs/heads/master
| 2020-12-29T18:52:21.113275
| 2015-08-31T03:40:53
| 2015-08-31T03:40:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 7,179
|
java
|
package com.sher.babymonitor;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
/* package */ final class MJpegHttpStreamer
{
private static final String TAG = MJpegHttpStreamer.class.getSimpleName();
private static final String BOUNDARY = "--gc0p4Jq0M2Yt08jU534c0p--";
private static final String BOUNDARY_LINES = "\r\n" + BOUNDARY + "\r\n";
private static final String HTTP_HEADER =
"HTTP/1.0 200 OK\r\n"
+ "Server: Peepers\r\n"
+ "Connection: close\r\n"
+ "Max-Age: 0\r\n"
+ "Expires: 0\r\n"
+ "Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, "
+ "post-check=0, max-age=0\r\n"
+ "Pragma: no-cache\r\n"
+ "Access-Control-Allow-Origin:*\r\n"
+ "Content-Type: multipart/x-mixed-replace; "
+ "boundary=" + BOUNDARY + "\r\n"
+ BOUNDARY_LINES;
private final int mPort;
private boolean mNewJpeg = false;
private boolean mStreamingBufferA = true;
private final byte[] mBufferA;
private final byte[] mBufferB;
private int mLengthA = Integer.MIN_VALUE;
private int mLengthB = Integer.MIN_VALUE;
private long mTimestampA = Long.MIN_VALUE;
private long mTimestampB = Long.MIN_VALUE;
private final Object mBufferLock = new Object();
private Thread mWorker = null;
private volatile boolean mRunning = false;
/* package */ MJpegHttpStreamer(final int port, final int bufferSize)
{
super();
mPort = port;
mBufferA = new byte[bufferSize];
mBufferB = new byte[bufferSize];
} // constructor(int, int)
/* package */ void start()
{
if (mRunning)
{
throw new IllegalStateException("MJpegHttpStreamer is already running");
} // if
mRunning = true;
mWorker = new Thread(new Runnable()
{
@Override
public void run()
{
workerRun();
} // run()
});
mWorker.start();
} // start()
/* package */ void stop()
{
if (!mRunning)
{
throw new IllegalStateException("MJpegHttpStreamer is already stopped");
} // if
mRunning = false;
mWorker.interrupt();
} // stop()
/* package */ void streamJpeg(final byte[] jpeg, final int length, final long timestamp)
{
synchronized (mBufferLock)
{
final byte[] buffer;
if (mStreamingBufferA)
{
buffer = mBufferB;
mLengthB = length;
mTimestampB = timestamp;
} // if
else
{
buffer = mBufferA;
mLengthA = length;
mTimestampA = timestamp;
} // else
System.arraycopy(jpeg, 0 /* srcPos */, buffer, 0 /* dstPos */, length);
mNewJpeg = true;
mBufferLock.notify();
} // synchronized
} // streamJpeg(byte[], int, long)
private void workerRun()
{
while (mRunning)
{
try
{
acceptAndStream();
} // try
catch (final IOException exceptionWhileStreaming)
{
System.err.println(exceptionWhileStreaming);
} // catch
} // while
} // mainLoop()
private void acceptAndStream() throws IOException
{
ServerSocket serverSocket = null;
Socket socket = null;
DataOutputStream stream = null;
try
{
serverSocket = new ServerSocket(mPort);
serverSocket.setSoTimeout(1000 /* milliseconds */);
do
{
try
{
socket = serverSocket.accept();
} // try
catch (final SocketTimeoutException e)
{
if (!mRunning)
{
return;
} // if
} // catch
} while (socket == null);
serverSocket.close();
serverSocket = null;
stream = new DataOutputStream(socket.getOutputStream());
stream.writeBytes(HTTP_HEADER);
stream.flush();
while (mRunning)
{
final byte[] buffer;
final int length;
final long timestamp;
synchronized (mBufferLock)
{
while (!mNewJpeg)
{
try
{
mBufferLock.wait();
} // try
catch (final InterruptedException stopMayHaveBeenCalled)
{
// stop() may have been called
return;
} // catch
} // while
mStreamingBufferA = !mStreamingBufferA;
if (mStreamingBufferA)
{
buffer = mBufferA;
length = mLengthA;
timestamp = mTimestampA;
} // if
else
{
buffer = mBufferB;
length = mLengthB;
timestamp = mTimestampB;
} // else
mNewJpeg = false;
} // synchronized
stream.writeBytes(
"Content-type: image/jpeg\r\n"
+ "Content-Length: " + length + "\r\n"
+ "X-Timestamp:" + timestamp + "\r\n"
+ "\r\n"
);
stream.write(buffer, 0 /* offset */, length);
stream.writeBytes(BOUNDARY_LINES);
stream.flush();
} // while
} // try
finally
{
if (stream != null)
{
try
{
stream.close();
} // try
catch (final IOException closingStream)
{
System.err.println(closingStream);
} // catch
} //
if (socket != null)
{
try
{
socket.close();
} // try
catch (final IOException closingSocket)
{
System.err.println(closingSocket);
} // catch
} // socket
if (serverSocket != null)
{
try
{
serverSocket.close();
} // try
catch (final IOException closingServerSocket)
{
System.err.println(closingServerSocket);
} // catch
} // if
} // finally
} // accept()
} // class MJpegHttpStreamer
|
[
"shaomuhan@outlook.com"
] |
shaomuhan@outlook.com
|
1facd13ac5b4e1dcfdd3212ab0111f37845e9275
|
2e1912a68b0409c81d0dc28371154a707903d529
|
/src/main/java/com/nonce/restsecurity/util/HttpClientUtil.java
|
f63bb2564a26bfc42410e7bca6f0cb8684fd62b4
|
[] |
no_license
|
jinweizou/SpringBoot_SpringSecurity
|
e9a9c76366a647d6bb4461491bf79a22dd9fb76b
|
2a983a91019efffd79304b3f619627dfda9170fc
|
refs/heads/master
| 2020-05-07T17:47:00.630020
| 2019-04-03T11:18:25
| 2019-04-03T11:18:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 7,611
|
java
|
package com.nonce.restsecurity.util;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.ObjectUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Andon
* @date 2019/4/3
*/
@SuppressWarnings("Duplicates")
public class HttpClientUtil {
// 编码格式,发送编码格式统一用UTF-8
private static final String ENCODING = "UTF-8";
// 设置连接超时时间,单位毫秒
private static final int CONNECT_TIMEOUT = 10 * 1000;
// 请求响应超时时间,单位毫秒
private static final int SOCKET_TIMEOUT = 10 * 1000;
/**
* 发送get请求;带请求头和请求参数
*/
public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建访问地址
URIBuilder uriBuilder = new URIBuilder(url);
if (!ObjectUtils.isEmpty(params)) {
params.forEach(uriBuilder::setParameter);
}
// 创建http对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
// 设置请求超时时间及响应超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpGet.setConfig(requestConfig);
// 设置请求头
packageHeader(headers, httpGet);
// 执行请求获取响应体并释放资源
return getHttpClientResult(httpClient, httpGet);
}
/**
* 发送get请求;带请求参数
*/
public static String doGet(String url, Map<String, String> params) throws Exception {
return doGet(url, null, params);
}
/**
* 发送get请求;不带请求头和请求参数
*/
public static String doGet(String url) throws Exception {
return doGet(url, null, null);
}
/**
* 发送post请求;带请求头和请求参数
*/
public static String doPost(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建http对象
HttpPost httpPost = new HttpPost(url);
// 设置请求超时时间及响应超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 设置请求头
/*httpPost.setHeader("Cookie", "");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
packageHeader(headers, httpPost);
// 封装请求参数
packageParam(params, httpPost);
// 执行请求获取响应体并释放资源
return getHttpClientResult(httpClient, httpPost);
}
/**
* 发送post请求;带请求参数
*/
public static String doPost(String url, Map<String, String> params) throws IOException {
return doPost(url, null, params);
}
/**
* 发送post请求;不带请求头和请求参数
*/
public static String doPost(String url) throws IOException {
return doPost(url, null, null);
}
/**
* 发送put请求;带请求头和请求参数
*/
public static String doPut(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPut.setConfig(requestConfig);
packageHeader(headers, httpPut);
packageParam(params, httpPut);
return getHttpClientResult(httpClient, httpPut);
}
/**
* 发送put请求;带请求参数
*/
public static String doPut(String url, Map<String, String> params) throws IOException {
return doPut(url, null, params);
}
/**
* 发送put请求;不带请求头和请求参数
*/
public static String doPut(String url) throws IOException {
return doPut(url, null, null);
}
/**
* 发送delete请求;带请求头和请求参数
*/
public static String doDelete(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
if (ObjectUtils.isEmpty(params)) {
params = new HashMap<>();
}
params.put("_method", "delete");
return doPost(url, headers, params);
}
/**
* 发送delete请求;带请求参数
*/
public static String doDelete(String url, Map<String, String> params) throws IOException {
return doDelete(url, null, params);
}
/**
* 发送delete请求;不带请求头和请求参数
*/
public static String doDelete(String url) throws IOException {
return doDelete(url, null, null);
}
/**
* 封装请求头
*/
private static void packageHeader(Map<String, String> headers, HttpRequestBase httpMethod) {
if (!ObjectUtils.isEmpty(headers)) {
headers.forEach(httpMethod::setHeader);
}
}
/**
* 封装请求参数
*/
private static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod) throws UnsupportedEncodingException {
if (!ObjectUtils.isEmpty(params)) {
List<NameValuePair> nameValuePairs = new ArrayList<>();
params.forEach((key, value) -> nameValuePairs.add(new BasicNameValuePair(key, value)));
httpMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, ENCODING));
}
}
/**
* 执行请求获取响应体并释放资源
*/
private static String getHttpClientResult(CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws IOException {
// 执行请求
CloseableHttpResponse httpResponse = null;
try {
// 获取响应体
httpResponse = httpClient.execute(httpMethod);
String content = "";
if (!ObjectUtils.isEmpty(httpResponse) && !ObjectUtils.isEmpty(httpResponse.getEntity())) {
content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
}
return content;
} finally {
// 释放资源
if (!ObjectUtils.isEmpty(httpResponse)) {
httpResponse.close();
}
if (!ObjectUtils.isEmpty(httpClient)) {
httpClient.close();
}
}
}
}
|
[
"17742023270@163.com"
] |
17742023270@163.com
|
0cbba77b4e73dd7d46ee665b273b3e527e90bb57
|
ace607f491ac96b2f31b2243e032574aac64e2b2
|
/巴适居后端20190116/bashiju-housing/bashiju-housing-service/src/main/java/com/bashiju/housing/service/impl/PrintTemplateService.java
|
97f5abadb04eadec64beb9e82e662eb0cb19c409
|
[] |
no_license
|
lxsgdsgg/test
|
07a3a3e10cd276947ddcfe278dd989da4e55775b
|
dc6899bf4421e4ff9efb1e76d37dba5c930fe63c
|
refs/heads/master
| 2020-04-25T21:56:59.010931
| 2019-02-27T10:40:35
| 2019-02-27T10:40:35
| 173,096,004
| 1
| 0
| null | 2019-02-28T11:00:17
| 2019-02-28T11:00:16
| null |
UTF-8
|
Java
| false
| false
| 13,317
|
java
|
package com.bashiju.housing.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.alibaba.fastjson.JSON;
import com.bashiju.cert.interceptors.DataAuthHelper;
import com.bashiju.enums.FtpFileTypeEnum;
import com.bashiju.enums.FtpSourceTypeEnum;
import com.bashiju.enums.MenuEnum;
import com.bashiju.housing.mapper.PrintTemplateMapper;
import com.bashiju.housing.service.IPrintTemplateService;
import com.bashiju.utils.log.ExecutionResult;
import com.bashiju.utils.log.SystemServiceLog;
import com.bashiju.utils.service.CommonSqlServie;
import com.bashiju.utils.threadlocal.UserThreadLocal;
import com.bashiju.utils.util.FtpUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
@SystemServiceLog(sourceType="房源打印模板设置")
@Service
public class PrintTemplateService implements IPrintTemplateService {
@Autowired
private CommonSqlServie commonSqlServie;
@Autowired
private PrintTemplateMapper printTemplateMapper;
@Autowired
DataAuthHelper dataAuthHelper;
@SystemServiceLog(operationType="查询房源打印模板列表")
@Override
public Page<Map<String, Object>> queryTemplateList(int page, int limit) {
String companyId=UserThreadLocal.get().get("companyId").toString();
PageHelper.startPage(page, limit);
dataAuthHelper.auth(MenuEnum.MENU_74.getCode(),UserThreadLocal.get().get("id").toString());
Page<Map<String, Object>> result=printTemplateMapper.queryTemplateList(companyId);
ExecutionResult.descFormat(companyId, "查询房源打印模板列表");
return result;
}
@SystemServiceLog(operationType="查询房源打印模板详细")
@Override
public Map<String, Object> queryDetailed(Integer id) {
List<Map<String, Object>> list=printTemplateMapper.queryDetailed(id);
Map<String, Object> result=new HashMap<>();
List<Map<String, Object>> spanArry=new ArrayList<>();
List<Map<String, Object>> picArry=new ArrayList<>();
if (list!=null) {
result.put("templateName", list.get(0).get("templateName"));
result.put("typeValue", list.get(0).get("typeId"));
for (Map<String, Object> item : list) {
if (item.get("tag").toString().equals("pic")) {
picArry.add(item);
}
if (item.get("tag").toString().equals("text")||item.get("tag").toString().equals("customer")) {
spanArry.add(item);
}
if (item.get("tag").toString().equals("back")) {
result.put("backgroundUrl", item.get("url"));
}
}
}
result.put("spanArry", spanArry);
result.put("picArry", picArry);
ExecutionResult.descFormat(id.toString(), "查询房源打印模板详细");
return result;
}
@SystemServiceLog(operationType="新增房源打印模板")
@Override
public int addPrintTemplate(String baseInfo,String spanArry,String picArry,String backUrl) {
Map param=JSON.parseObject(baseInfo, Map.class);
Map user=UserThreadLocal.get();
Map<String,Object> template=new HashMap<>();
template.put("templateName", param.get("templateName"));
template.put("typeId", Integer.parseInt(param.get("typeId").toString()));
template.put("typeName", param.get("typeName"));
template.put("companyId", user.get("companyId"));
template.put("companyName", user.get("comName"));
template.put("permissionArea", user.get("deptId"));
template.put("operatorId", user.get("id"));
Long id=commonSqlServie.commonOperationDatabase(template, "hs_house_printTemplate", false);
saveDetailed(spanArry, picArry, backUrl,id);
ExecutionResult.descFormat(id.toString(), "新增房源打印模板");
return id.intValue();
}
private void saveDetailed(String spanArry, String picArry, String backUrl,Long id) {
Map user=UserThreadLocal.get();
String columns="templateId,css,dataColumn,text,tag,width,height,strong,fontstyle,underline,linethrough,color,fontfamily,fontsize,x,y,url,permissionArea,operatorId";
List<String> values=new ArrayList<>();
if (StringUtils.isNotEmpty(spanArry)) {
List<Map> items= JSON.parseArray(spanArry, Map.class);
for (Map item : items) {
StringBuffer sql=new StringBuffer();
sql.append(id);
sql.append(",'");
sql.append(item.get("css").toString().replaceAll("selected", ""));
sql.append("','");
if (item.get("dataColumn")!=null) {
sql.append(item.get("dataColumn"));
}
sql.append("','");
sql.append(item.get("text"));
sql.append("','");
if (item.get("tag")!=null) {
sql.append(item.get("tag"));
}
sql.append("',");
if (item.get("width")!=null) {
sql.append(item.get("width"));
}else {
sql.append(0);
}
sql.append(",");
if (item.get("height")!=null) {
sql.append(item.get("height"));
}else {
sql.append(0);
}
sql.append(",");
if (item.get("strong")!=null) {
sql.append(item.get("strong"));
}else {
sql.append(0);
}
sql.append(",");
if (item.get("fontstyle")!=null) {
sql.append(item.get("fontstyle"));
}else {
sql.append(0);
}
sql.append(",");
if (item.get("underline")!=null) {
sql.append(item.get("underline"));
}else {
sql.append(0);
}
sql.append(",");
if (item.get("linethrough")!=null) {
sql.append(item.get("linethrough"));
}else {
sql.append(0);
}
sql.append(",'");
if (item.get("color")!=null) {
sql.append(item.get("color"));
}
sql.append("','");
if (item.get("fontfamily")!=null) {
sql.append(item.get("fontfamily"));
}
sql.append("',");
if (item.get("fontsize")!=null) {
sql.append(item.get("fontsize"));
}else {
sql.append(16);
}
sql.append(",");
sql.append(item.get("x"));
sql.append(",");
sql.append(item.get("y"));
sql.append(",'','");
sql.append(user.get("deptId"));
sql.append("',");
sql.append(user.get("id"));
values.add(sql.toString());
}
}
if (StringUtils.isNotEmpty(picArry)) {
List<Map> items= JSON.parseArray(picArry, Map.class);
for (Map item : items) {
StringBuffer sql=new StringBuffer();
sql.append(id);
sql.append(",'");
sql.append(item.get("css").toString().replaceAll("selected", ""));
sql.append("','");
if (item.get("dataColumn")!=null) {
sql.append(item.get("dataColumn"));
}
sql.append("','','");
if (item.get("tag")!=null) {
sql.append(item.get("tag"));
}
sql.append("',");
if (item.get("width")!=null) {
sql.append(item.get("width"));
}else {
sql.append(300);
}
sql.append(",");
if (item.get("height")!=null) {
sql.append(item.get("height"));
}else {
sql.append(300);
}
sql.append(",");
sql.append(0);
sql.append(",");
sql.append(0);
sql.append(",");
sql.append(0);
sql.append(",");
sql.append(0);
sql.append(",'");
sql.append("','");
sql.append("',");
sql.append(0);
sql.append(",");
sql.append(item.get("x"));
sql.append(",");
sql.append(item.get("y"));
sql.append(",'");
sql.append(item.get("url"));
sql.append("','");
sql.append(user.get("deptId"));
sql.append("',");
sql.append(user.get("id"));
values.add(sql.toString());
}
}
if (StringUtils.isNotEmpty(backUrl)) {
String back=id+",'','','','back',0,0,0,0,0,0,'','',0,0,0,'"+backUrl+"','"+user.get("deptId")+"',"+user.get("id");
values.add(back);
}
if (values.size()>0) {
commonSqlServie.batchAdd(columns, "hs_house_printtemplateitem", values, false);
}
}
@SystemServiceLog(operationType="修改房源打印模板")
@Override
public int updatePrintTemplate(String baseInfo,String spanArry,String picArry,String backUrl) {
Map param=JSON.parseObject(baseInfo, Map.class);
Map<String,Object> template=new HashMap<>();
template.put("templateName", param.get("templateName"));
template.put("typeId", Integer.parseInt(param.get("typeId").toString()));
template.put("typeName", param.get("typeName"));
template.put("id", param.get("id"));
commonSqlServie.commonOperationDatabase(template, "hs_house_printTemplate","id", false);
Long id=Long.parseLong(param.get("id").toString());
printTemplateMapper.deleteTemplateItem(id.intValue());
saveDetailed(spanArry, picArry, backUrl,id);
ExecutionResult.descFormat(id.toString(), "修改房源打印模板");
return 1;
}
@SystemServiceLog(operationType="删除房源打印模板")
@Override
public int deletePrintTemplate(Integer id) {
commonSqlServie.delData("hs_house_printTemplate", "id", id.toString(), false);
ExecutionResult.descFormat(id.toString(), "删除房源打印模板");
return 1;
}
@SystemServiceLog(operationType="查询房源打印模板背景图片列表")
@Override
public List<Map<String, Object>> queryBackground() {
String companyId=UserThreadLocal.get().get("companyId").toString();
List<Map<String, Object>> list=printTemplateMapper.queryBackground(companyId);
ExecutionResult.descFormat(companyId, "查询房源打印模板背景图片列表");
return list;
}
@SystemServiceLog(operationType="上传打印模板背景图片")
@Override
public int uploadBackgroundPic(HttpServletRequest request) {
// 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 检查form中是否有enctype="multipart/form-data"
if (multipartResolver.isMultipart(request)) {
// 将request变成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 获取multiRequest 中所有的文件名
Iterator iter = multiRequest.getFileNames();
if (iter.hasNext()) {
// 一次遍历所有文件
// List<MultipartFile> files = multiRequest.getFiles(iter.next().toString());
Map<String,Object> user = UserThreadLocal.get();
MultipartFile file = multiRequest.getFile(iter.next().toString());
if (file != null) {
String filepath =FtpUtil.uploadFile(file,user.get("companyId").toString(),FtpSourceTypeEnum.FTP_SOURCE_FY.getCode(),FtpFileTypeEnum.FTP_FILE_TP.getCode(),true);;
Long userid = Long.parseLong(user.get("id").toString());// 操作人id
String username = user.get("realName").toString();// 操作人
String deptid = user.get("deptId").toString();
// 保存小区附件表
Map<String,Object> mm = new HashMap<>();
mm.put("companyId", user.get("companyId"));
mm.put("companyName", user.get("companyName"));
mm.put("url", filepath);
mm.put("operatorId", userid);
mm.put("operator", username);
mm.put("permissionArea", deptid);
Long id = commonSqlServie.commonOperationDatabase(mm, "hs_house_templatePicture", false);
ExecutionResult.descFormat(id.toString(), "上传打印背景图");
return id.intValue();
}
}
}
return 0;
}
@SystemServiceLog(operationType="删除房源打印模板背景图片")
@Override
public boolean deletePrintTemplateBackGroundPic(Integer id) {
boolean result=commonSqlServie.delData("hs_house_templatePicture", "id", id.toString(), false);
ExecutionResult.descFormat(id.toString(), "删除房源打印模板背景图片");
return result;
}
@Override
public Map<String, Object> queryHousePrintDetailed(Long houseId, Integer templateId) {
Map<String, Object> template= queryDetailed(templateId);
List<Map<String, Object>> spanArry= (List<Map<String, Object>>) template.get("spanArry");
List<Map<String, Object>> picArry=(List<Map<String, Object>>) template.get("picArry");
Map<String, Object> houseInfo=printTemplateMapper.queryHousePrintInfo(houseId);
if (spanArry!=null) {
for (Map<String, Object> item : spanArry) {
Integer left=Integer.parseInt(item.get("x").toString());
left-=200;
item.put("x", left);
Integer top=Integer.parseInt(item.get("y").toString());
top-=242;
item.put("y", top);
Object value="";
if (houseInfo!=null) {
value =houseInfo.get(item.get("dataColumn").toString());
if (value==null) {
value="";
}
}
item.put("text", value);
}
}
if (picArry!=null) {
for (Map<String, Object> item : picArry) {
Integer left=Integer.parseInt(item.get("x").toString());
left-=200;
item.put("x", left);
Integer top=Integer.parseInt(item.get("y").toString());
top-=242;
item.put("y", top);
Object value="";
if (houseInfo!=null) {
value =houseInfo.get(item.get("dataColumn").toString());
if (value==null) {
value="";
}
}
item.put("url", value);
}
}
return template;
}
@Override
public List<Map<String, Object>> queryTemplateSelectData() {
String companyId=UserThreadLocal.get().get("companyId").toString();
List<Map<String, Object>> results=printTemplateMapper.queryTemplateSelectData(companyId);
return results;
}
}
|
[
"563667426@qq.com"
] |
563667426@qq.com
|
3002913cf6ccafebdc1c999d932e9644bc7de4d8
|
2d7c28312f8fa96523e28ebcbacedcb3ad4c7506
|
/Experiment_2_Dealz4All_Application/Code/src/main/java/com/online/dealz/deal/services/decorator/DealPriceDecorator/PlatinumMemberPrice.java
|
f556df68ce5ec7de5d9be4db868072bf9535f4d3
|
[] |
no_license
|
shenoygowrish/Testing_with_ALEX
|
c48af9005379a70ff8da3b55728ca11cd66ad7d7
|
c35706ed9021add50ab9dcd9670e688e4d962e09
|
refs/heads/master
| 2022-12-01T21:54:11.335826
| 2020-08-14T05:23:57
| 2020-08-14T05:23:57
| 287,414,051
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 334
|
java
|
package com.online.dealz.deal.services.decorator.DealPriceDecorator;
public class PlatinumMemberPrice implements IDealPrice {
double basePrice;
@Override
public double getPrice() {
return basePrice;
}
@Override
public void setPrice(double price) {
basePrice = price - (price *0.15); //15% off for Platinum Members
}
}
|
[
"34574855+shenoygowrish@users.noreply.github.com"
] |
34574855+shenoygowrish@users.noreply.github.com
|
8d6bb907265669080c2e7864e562a4a3915824c1
|
452190483e4c29fcebe7fce2d8a6e176fcf74d65
|
/app/src/main/java/com/me/gc/scratcher1/ScratchImageView.java
|
72c491a2fe7d466112fd349c92d61b4b86dc9f7a
|
[] |
no_license
|
gilbertchoy/scratcher1
|
56ec3a25b024f7be9112e783d836aa9bb50de458
|
11776845988cf9d9d7e437a40a67f6021fd6208c
|
refs/heads/master
| 2021-09-26T03:03:50.124352
| 2018-10-27T00:48:35
| 2018-10-27T00:48:35
| 137,509,926
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 12,224
|
java
|
/**
*
* Copyright 2016 Harish Sridharan
* 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.me.gc.scratcher1;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
/**
* Created by Harish on 25/03/16.
*/
public class ScratchImageView extends ImageView {
public interface IRevealListener {
public void onRevealed(ScratchImageView iv);
public void onRevealPercentChangedListener(ScratchImageView siv, float percent);
}
public static final float STROKE_WIDTH = 20f;
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
/**
* Bitmap holding the scratch region.
*/
private Bitmap mScratchBitmap;
/**
* Drawable canvas area through which the scratchable area is drawn.
*/
private Canvas mCanvas;
/**
* Path holding the erasing path done by the user.
*/
private Path mErasePath;
/**
* Path to indicate where the user have touched.
*/
private Path mTouchPath;
/**
* Paint properties for drawing the scratch area.
*/
private Paint mBitmapPaint;
/**
* Paint properties for erasing the scratch region.
*/
private Paint mErasePaint;
/**
* Gradient paint properties that lies as a background for scratch region.
*/
private Paint mGradientBgPaint;
/**
* Sample Drawable bitmap having the scratch pattern.
*/
private BitmapDrawable mDrawable;
/**
* Listener object callback reference to send back the callback when the image has been revealed.
*/
private IRevealListener mRevealListener;
/**
* Reveal percent value.
*/
private float mRevealPercent;
/**
* Thread Count
*/
private int mThreadCount = 0;
public ScratchImageView(Context context) {
super(context);
init();
}
public ScratchImageView(Context context, AttributeSet set) {
super(context, set);
init();
}
public ScratchImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
/**
* Set the strokes width based on the parameter multiplier.
* @param multiplier can be 1,2,3 and so on to set the stroke width of the paint.
*/
public void setStrokeWidth(int multiplier) {
mErasePaint.setStrokeWidth(multiplier * STROKE_WIDTH);
}
/**
* Initialises the paint drawing elements.
*/
private void init() {
mTouchPath = new Path();
mErasePaint = new Paint();
mErasePaint.setAntiAlias(true);
mErasePaint.setDither(true);
//mErasePaint.setColor(0xFFFF0000);
mErasePaint.setColor(0xff0000ff);
mErasePaint.setStyle(Paint.Style.STROKE);
mErasePaint.setStrokeJoin(Paint.Join.BEVEL);
mErasePaint.setStrokeCap(Paint.Cap.ROUND);
setStrokeWidth(6);
mGradientBgPaint = new Paint();
mErasePath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
//Bitmap scratchBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_scratch_pattern);
//bert change overlay image here
Bitmap scratchBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.greypattern);
mDrawable = new BitmapDrawable(getResources(), scratchBitmap);
mDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
setEraserMode();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mScratchBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mScratchBitmap);
Rect rect = new Rect(0, 0, mScratchBitmap.getWidth(), mScratchBitmap.getHeight());
mDrawable.setBounds(rect);
int startGradientColor = ContextCompat.getColor(getContext(), R.color.scratch_start_gradient);
int endGradientColor = ContextCompat.getColor(getContext(), R.color.scratch_end_gradient);
mGradientBgPaint.setShader(new LinearGradient(0, 0, 0, getHeight(), startGradientColor, endGradientColor, Shader.TileMode.MIRROR));
mCanvas.drawRect(rect, mGradientBgPaint);
mDrawable.draw(mCanvas);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mScratchBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mErasePath, mErasePaint);
}
private void touch_start(float x, float y) {
mErasePath.reset();
mErasePath.moveTo(x, y);
mX = x;
mY = y;
}
/**
* clears the scratch area to reveal the hidden image.
*/
public void clear() {
int[] bounds = getImageBounds();
int left = bounds[0];
int top = bounds[1];
int right = bounds[2];
int bottom = bounds[3];
int width = right - left;
int height = bottom - top;
int centerX = left + width / 2;
int centerY = top + height / 2;
left = centerX - width / 2;
top = centerY - height / 2;
right = left + width;
bottom = top + height;
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(
PorterDuff.Mode.CLEAR));
mCanvas.drawRect(left, top, right, bottom, paint);
checkRevealed();
invalidate();
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mErasePath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
drawPath();
}
mTouchPath.reset();
mTouchPath.addCircle(mX, mY, 30, Path.Direction.CW);
}
private void drawPath() {
mErasePath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mErasePath, mErasePaint);
// kill this so we don't double draw
mTouchPath.reset();
mErasePath.reset();
mErasePath.moveTo(mX, mY);
checkRevealed();
}
public void reveal() {
clear();
}
private void touch_up() {
drawPath();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
default:
break;
}
return true;
}
public int getColor() {
return mErasePaint.getColor();
}
public Paint getErasePaint() {
return mErasePaint;
}
public void setEraserMode() {
getErasePaint().setXfermode(new PorterDuffXfermode(
PorterDuff.Mode.CLEAR));
}
public void setRevealListener(IRevealListener listener) {
this.mRevealListener = listener;
}
public boolean isRevealed() {
return mRevealPercent == 1;
}
private void checkRevealed() {
if(! isRevealed() && mRevealListener != null) {
int[] bounds = getImageBounds();
int left = bounds[0];
int top = bounds[1];
int width = bounds[2] - left;
int height = bounds[3] - top;
// Do not create multiple calls to compare.
if(mThreadCount > 1) {
Log.d("Captcha", "Count greater than 1");
return;
}
mThreadCount++;
new AsyncTask<Integer, Void, Float>() {
@Override
protected Float doInBackground(Integer... params) {
try {
int left = params[0];
int top = params[1];
int width = params[2];
int height = params[3];
Bitmap croppedBitmap = Bitmap.createBitmap(mScratchBitmap, left, top, width, height);
return BitmapUtils.getTransparentPixelPercent(croppedBitmap);
} finally {
mThreadCount--;
}
}
public void onPostExecute(Float percentRevealed) {
// check if not revealed before.
if( ! isRevealed()) {
float oldValue = mRevealPercent;
mRevealPercent = percentRevealed;
if(oldValue != percentRevealed) {
mRevealListener.onRevealPercentChangedListener(ScratchImageView.this, percentRevealed);
}
// if now revealed.
if( isRevealed()) {
mRevealListener.onRevealed(ScratchImageView.this);
}
}
}
}.execute(left, top, width, height);
}
}
public int[] getImageBounds() {
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int paddingRight = getPaddingRight();
int paddingBottom = getPaddingBottom();
int vwidth = getWidth() - paddingLeft - paddingRight;
int vheight = getHeight() - paddingBottom - paddingTop;
int centerX = vwidth/2;
int centerY = vheight/2;
Drawable drawable = getDrawable();
Rect bounds = drawable.getBounds();
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
if(width <= 0) {
width = bounds.right - bounds.left;
}
if(height <= 0) {
height = bounds.bottom - bounds.top;
}
int left;
int top;
if(height > vheight) {
height = vheight;
}
if(width > vwidth) {
width = vwidth;
}
ScaleType scaleType = getScaleType();
switch (scaleType) {
case FIT_START:
left = paddingLeft;
top = centerY - height / 2;
break;
case FIT_END:
left = vwidth - paddingRight - width;
top = centerY - height / 2;
break;
case CENTER:
left = centerX - width / 2;
top = centerY - height / 2;
break;
default:
left = paddingLeft;
top = paddingTop;
width = vwidth;
height = vheight;
break;
}
return new int[] {left, top, left + width, top + height};
}
}
|
[
"gilbertchoy@gmail.com"
] |
gilbertchoy@gmail.com
|
f527203df2a007ec52a3e341bc243a7a5315b41f
|
c6d931a0b96addf006061f4f1e8bc78e53e35263
|
/core/src/main/java/org/openstack4j/model/common/payloads/InputStreamPayload.java
|
f61c1811ec41910a1249d498700bd618ba97c387
|
[
"Apache-2.0"
] |
permissive
|
17862953931/openstack4j
|
a8ea441009d14afa839cf6f42d128652687751e1
|
9d5f1a0c91b6db8942019fddd2997e6b2a33ef57
|
refs/heads/master
| 2020-09-04T09:29:26.354230
| 2020-02-19T02:52:06
| 2020-02-19T02:52:06
| 219,702,460
| 2
| 1
|
NOASSERTION
| 2020-02-19T02:52:07
| 2019-11-05T09:09:05
|
Java
|
UTF-8
|
Java
| false
| false
| 795
|
java
|
package org.openstack4j.model.common.payloads;
import java.io.IOException;
import java.io.InputStream;
import org.openstack4j.model.common.Payload;
/**
* Input Stream Payload
*
* @author Jeremy Unruh
*/
public class InputStreamPayload implements Payload<InputStream>{
private InputStream is;
public InputStreamPayload(InputStream is) {
this.is = is;
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws IOException {
if (is != null)
is.close();
}
/**
* {@inheritDoc}
*/
@Override
public InputStream open() {
return is;
}
/**
* {@inheritDoc}
*/
@Override
public void closeQuietly() {
try {
close();
}
catch (IOException e) {
}
}
/**
* {@inheritDoc}
*/
@Override
public InputStream getRaw() {
return is;
}
}
|
[
"jeremyunruh@sbcglobal.net"
] |
jeremyunruh@sbcglobal.net
|
82c4efb97432ed734a1ce0080107f0c1a68436b0
|
2496262efc374af6e22d604dd61b50bfadf64b26
|
/app/src/main/java/com/uphealth/cn/ui/login/HealthInfoSetting.java
|
b88452b88eaf489971c23dc24992c721412acd83
|
[] |
no_license
|
gitdahai/apu
|
1044e45ee540ca347ebd2cc3439bc3f61abd7553
|
29fc78df3c6d971fba09e12dbd3ba98daa8fef2d
|
refs/heads/master
| 2021-01-15T15:32:36.862724
| 2016-08-19T00:54:57
| 2016-08-19T00:54:57
| 65,005,827
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 9,175
|
java
|
package com.uphealth.cn.ui.login;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.uphealth.cn.R;
import com.uphealth.cn.adapter.HealthLabelAdapter;
import com.uphealth.cn.data.Contants;
import com.uphealth.cn.data.GlobalData;
import com.uphealth.cn.dialog.SinglePicker;
import com.uphealth.cn.model.CommonModel;
import com.uphealth.cn.network.ErrorMsg;
import com.uphealth.cn.ui.login.home.MainActivity;
import com.uphealth.cn.utils.Utils;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
/**
* @description 健康信息设置
* @data 2016年5月14日
* @author jun.wang
*/
public class HealthInfoSetting extends BaseActivity implements OnClickListener {
private GridView gridView ;
HealthLabelAdapter adapter ;
private TextView edit_height ;
private TextView edit_weight ;
private TextView edit_goal_weight ;
private String heightStr , weightStr = "" ;
private Handler handler = new Handler(){
@SuppressWarnings("unchecked")
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1001:
List<CommonModel> lists = (List<CommonModel>)msg.obj ;
adapter = new HealthLabelAdapter(HealthInfoSetting.this , lists , false) ;
gridView.setAdapter(adapter);
break;
default:
break;
}
};
} ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_healthinfo_setting);
init() ;
}
private void init(){
((TextView)findViewById(R.id.title)).setText("健康信息设置");
findViewById(R.id.back).setOnClickListener(this);
((Button)findViewById(R.id.next)).setText("下一步");
findViewById(R.id.next).setOnClickListener(this);
findViewById(R.id.text_test).setOnClickListener(this);
findViewById(R.id.text_look).setOnClickListener(this);
gridView = (GridView)this.findViewById(R.id.gridView) ;
edit_height = (TextView)this.findViewById(R.id.edit_height) ;
edit_height.setOnClickListener(this);
edit_weight = (TextView)this.findViewById(R.id.edit_weight) ;
edit_weight.setOnClickListener(this);
edit_goal_weight = (TextView)this.findViewById(R.id.edit_goal_weight) ;
edit_goal_weight.setOnClickListener(this);
// adapter = new HealthLabelAdapter(this) ;
// gridView.setAdapter(adapter);
requestData() ;
// 先清空缓存数据
GlobalData.healthLebalList.clear();
}
@Override
public void onClick(View v) {
Intent intent = null ;
switch (v.getId()) {
case R.id.back:
finish();
break;
case R.id.next:
// requestPersonInfo() ;
next() ;
break ;
case R.id.text_test:
intent = new Intent(HealthInfoSetting.this , TestBodyActivity.class) ;
startActivity(intent);
break ;
case R.id.text_look:
intent = new Intent(HealthInfoSetting.this , MainActivity.class) ;
startActivity(intent);
break ;
// 请选择身高
case R.id.edit_height:
SinglePicker singlePicker = new SinglePicker(this , GlobalData.getPersonHeight());
singlePicker.setOnClickOkListener(new SinglePicker.OnClickOkListener() {
@Override
public void onClickOk(String date) {
if(date.equals("请选择身高")){
edit_height.setText("");
}else {
edit_height.setText(date+"厘米");
heightStr = date ;
}
}
});
singlePicker.show(edit_height);
break ;
// // 目标体重
// case R.id.edit_goal_weight:
// SinglePicker weightGoalPicker = new SinglePicker(this , GlobalData.getPersonGoalWeight());
// weightGoalPicker.setOnClickOkListener(new SinglePicker.OnClickOkListener() {
// @Override
// public void onClickOk(String date) {
// if(date.equals("目标体重")){
// edit_goal_weight.setText("");
// }else {
// edit_goal_weight.setText(date);
//
// }
// }
// });
// weightGoalPicker.show(edit_goal_weight);
// break ;
// 当前体重
case R.id.edit_weight:
SinglePicker weightPicker = new SinglePicker(this , GlobalData.getPersonWeight());
weightPicker.setOnClickOkListener(new SinglePicker.OnClickOkListener() {
@Override
public void onClickOk(String date) {
if(date.equals("当前体重")){
edit_weight.setText("");
}else {
edit_weight.setText(date+"公斤");
weightStr = date ;
// 计算目标体重 BMI= 0.00173 为最佳体重
edit_goal_weight.setText(Utils.getBMIWeight(Integer.parseInt(heightStr))+"公斤");
}
}
});
weightPicker.show(edit_weight);
break ;
default:
break;
}
}
private void requestData(){
showDialog();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
Contants.getDemandTagList, new Response.Listener<String>() {
@Override
public void onResponse(String arg0) {
closeDialog() ;
System.out.println("arg0" + arg0);
try {
JSONObject json = new JSONObject(arg0) ;
int result = json.getInt("result") ;
if(result == 1){
String data = json.getString("data") ;
List<CommonModel> lists = new Gson().fromJson(data,
new TypeToken<List<CommonModel>>() {
}.getType());
Message msg = new Message() ;
msg.what = 1001 ;
msg.obj = lists ;
handler.sendMessage(msg) ;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
closeDialog() ;
showToast(ErrorMsg.net_error) ;
}
});
//为此get请求设置一个Tag属性
stringRequest.setTag("GET_TAG");
//将此get请求加入
requestQueue.add(stringRequest);
}
private void next(){
if(TextUtils.isEmpty(edit_height.getText())){
showToast("身高不能为空!");
return ;
}
if(TextUtils.isEmpty(edit_weight.getText())){
showToast("当前体重不能为空!");
return ;
}
if(TextUtils.isEmpty(edit_goal_weight.getText())){
showToast("目标体重不能为空!");
return ;
}
if(GlobalData.healthLebalList.size() == 0){
showToast("您还没有选择健康标签!");
return ;
}
System.out.println("healthLebalList==" + GlobalData.healthLebalList);
requestPersonInfo() ;
}
private void requestPersonInfo(){
showDialog();
StringBuilder tagsBuilder = new StringBuilder() ;
for(int i = 0 ; i < GlobalData.healthLebalList.size() ; i ++){
tagsBuilder.append(GlobalData.healthLebalList.get(i).getId()).append(",") ;
}
StringBuilder builder = new StringBuilder() ;
builder.append(Contants.updatePersonInfo) ;
builder.append("?accountId=").append(GlobalData.getUserId(this)) ;
builder.append("&height=").append(heightStr) ;
builder.append("&weight=").append(weightStr) ;
builder.append("&healthTags=").append(tagsBuilder.toString()) ;
System.out.println("api" + builder.toString());
StringRequest stringRequest = new StringRequest(Request.Method.GET,
builder.toString(), new Response.Listener<String>() {
@Override
public void onResponse(String arg0) {
closeDialog() ;
System.out.println("arg0" + arg0);
try {
JSONObject json = new JSONObject(arg0) ;
int result = json.getInt("result") ;
if(result == 1){
Intent intent = new Intent(HealthInfoSetting.this , HealthInfoTwoActivity.class) ;
startActivity(intent);
showToast("设置成功!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
closeDialog() ;
showToast(ErrorMsg.net_error) ;
}
});
//为此get请求设置一个Tag属性
stringRequest.setTag("GET_TAG");
//将此get请求加入
requestQueue.add(stringRequest);
}
}
|
[
"yangdahai@hollo.cn"
] |
yangdahai@hollo.cn
|
73c68545505c731d6df8c25ec96b511ede6240fa
|
abde7263e2bf8b1a64b6a16a34daf2811b7a4e7f
|
/src/main/java/net/kunmc/lab/gravitymod_dga/ServerUtils.java
|
4396c7cb41f3944d049e6f447a10f5fc838f6498
|
[
"MIT"
] |
permissive
|
TeamKun/Up_And_Down_And_All_Around_And_Death
|
6c213249bb9127805ed055c7936515ed0c90a0b0
|
f47825099577b7694f050a9711d58071f7e551d8
|
refs/heads/master
| 2023-06-19T22:18:34.591729
| 2021-07-21T16:18:30
| 2021-07-21T16:18:30
| 387,070,253
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 712
|
java
|
package net.kunmc.lab.gravitymod_dga;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.fml.common.FMLCommonHandler;
import java.util.List;
import java.util.UUID;
public class ServerUtils {
public static MinecraftServer getServer() {
return FMLCommonHandler.instance().getMinecraftServerInstance();
}
public static List<EntityPlayerMP> getPlayers() {
return getServer().getPlayerList().getPlayers();
}
public static boolean isOnlinePlayer(UUID uuid) {
List<EntityPlayerMP> playes = getPlayers();
return playes.stream().anyMatch(n -> n.getGameProfile().getId().equals(uuid));
}
}
|
[
"morimori.0317@outlook.jp"
] |
morimori.0317@outlook.jp
|
f9915c01cf3187edf870be1faa1ec1196a889005
|
6dd73c6d74061573729fd2e7c411f210dcd1d87b
|
/src/com/flatironschool/javacs/JedisIndex.java
|
853de4784cb171d2245ab620084a7066d16e8778
|
[] |
no_license
|
bwchang/SwaggySearch
|
3d672bcb51476d1f0883e0369da64593368bafcd
|
74b3779f0a489f63117a59b38895c07adf615f08
|
refs/heads/master
| 2021-01-20T18:02:14.419107
| 2016-08-09T14:17:43
| 2016-08-09T14:17:43
| 63,815,263
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 7,823
|
java
|
package com.flatironschool.javacs;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import org.jsoup.select.Elements;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
/**
* Represents a Redis-backed web search index.
*
*/
public class JedisIndex {
private Jedis jedis;
/**
* Constructor.
*
* @param jedis
*/
public JedisIndex(Jedis jedis) {
this.jedis = jedis;
}
/**
* Returns the Redis key for a given search term.
*
* @return Redis key.
*/
private String urlSetKey(String term) {
return "URLSet:" + term;
}
/**
* Returns the Redis key for a URL's TermCounter.
*
* @return Redis key.
*/
private String termCounterKey(String url) {
return "TermCounter:" + url;
}
private String sizeKey() {
return "Size";
}
/**
* Checks whether we have a TermCounter for a given URL.
*
* @param url
* @return
*/
public boolean isIndexed(String url) {
String redisKey = termCounterKey(url);
return jedis.exists(redisKey);
}
/** Returns the number of pages indexed. */
public int size() {
return Integer.parseInt(jedis.get(sizeKey()));
}
/**
* Adds a URL to the set associated with `term`.
*
* @param term
* @param tc
*/
public void add(String term, TermCounter tc) {
jedis.sadd(urlSetKey(term), tc.getLabel());
}
/**
* Looks up a search term and returns a set of URLs.
*
* @param term
* @return Set of URLs.
*/
public Set<String> getURLs(String term) {
Set<String> set = jedis.smembers(urlSetKey(term));
return set;
}
/**
* Looks up a term and returns a map from URL to count.
*
* @param term
* @return Map from URL to count.
*/
public Map<String, Integer> getCounts(String term) {
Map<String, Integer> map = new HashMap<String, Integer>();
Set<String> urls = getURLs(term);
for (String url: urls) {
Integer count = getCount(url, term);
map.put(url, count);
}
return map;
}
/**
* Looks up a term and returns a map from URL to count.
*
* @param term
* @return Map from URL to count.
*/
public Map<String, Integer> getCountsFaster(String term) {
// convert the set of strings to a list so we get the
// same traversal order every time
List<String> urls = new ArrayList<String>();
urls.addAll(getURLs(term));
// construct a transaction to perform all lookups
Transaction t = jedis.multi();
for (String url: urls) {
String redisKey = termCounterKey(url);
t.hget(redisKey, term);
}
List<Object> res = t.exec();
// iterate the results and make the map
Map<String, Integer> map = new HashMap<String, Integer>();
int i = 0;
for (String url: urls) {
Integer count = new Integer((String) res.get(i++));
map.put(url, count);
}
return map;
}
/**
* Returns the number of times the given term appears at the given URL.
*
* @param url
* @param term
* @return
*/
public Integer getCount(String url, String term) {
String redisKey = termCounterKey(url);
String count = jedis.hget(redisKey, term);
return new Integer(count);
}
/**
* Add a page to the index.
*
* @param url URL of the page.
* @param paragraphs Collection of elements that should be indexed.
*/
public void indexPage(String url, Elements paragraphs) {
System.out.println("Indexing " + url);
if (!isIndexed(url)) {
if (jedis.get(sizeKey()) == null) {
jedis.set(sizeKey(), "0");
} else {
jedis.incr(sizeKey());
}
}
// make a TermCounter and count the terms in the paragraphs
TermCounter tc = new TermCounter(url);
tc.processElements(paragraphs);
// push the contents of the TermCounter to Redis
pushTermCounterToRedis(tc);
}
/**
* Pushes the contents of the TermCounter to Redis.
*
* @param tc
* @return List of return values from Redis.
*/
public List<Object> pushTermCounterToRedis(TermCounter tc) {
Transaction t = jedis.multi();
String url = tc.getLabel();
String hashname = termCounterKey(url);
// if this page has already been indexed; delete the old hash
t.del(hashname);
// for each term, add an entry in the termcounter and a new
// member of the index
for (String term: tc.keySet()) {
Integer count = tc.get(term);
t.hset(hashname, term, count.toString());
t.sadd(urlSetKey(term), url);
}
List<Object> res = t.exec();
return res;
}
/**
* Prints the contents of the index.
*
* Should be used for development and testing, not production.
*/
public void printIndex() {
// loop through the search terms
for (String term: termSet()) {
System.out.println(term);
// for each term, print the pages where it appears
Set<String> urls = getURLs(term);
for (String url: urls) {
Integer count = getCount(url, term);
System.out.println(" " + url + " " + count);
}
}
}
/**
* Returns the set of terms that have been indexed.
*
* Should be used for development and testing, not production.
*
* @return
*/
public Set<String> termSet() {
Set<String> keys = urlSetKeys();
Set<String> terms = new HashSet<String>();
for (String key: keys) {
String[] array = key.split(":");
if (array.length < 2) {
terms.add("");
} else {
terms.add(array[1]);
}
}
return terms;
}
/**
* Returns URLSet keys for the terms that have been indexed.
*
* Should be used for development and testing, not production.
*
* @return
*/
public Set<String> urlSetKeys() {
return jedis.keys("URLSet:*");
}
/**
* Returns TermCounter keys for the URLS that have been indexed.
*
* Should be used for development and testing, not production.
*
* @return
*/
public Set<String> termCounterKeys() {
return jedis.keys("TermCounter:*");
}
/**
* Deletes all URLSet objects from the database.
*
* Should be used for development and testing, not production.
*
* @return
*/
public void deleteURLSets() {
Set<String> keys = urlSetKeys();
Transaction t = jedis.multi();
for (String key: keys) {
t.del(key);
}
t.exec();
}
/**
* Deletes all URLSet objects from the database.
*
* Should be used for development and testing, not production.
*
* @return
*/
public void deleteTermCounters() {
Set<String> keys = termCounterKeys();
Transaction t = jedis.multi();
for (String key: keys) {
t.del(key);
}
t.exec();
}
/**
* Deletes all keys from the database.
*
* Should be used for development and testing, not production.
*
* @return
*/
public void deleteAllKeys() {
Set<String> keys = jedis.keys("*");
Transaction t = jedis.multi();
for (String key: keys) {
t.del(key);
}
t.exec();
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Jedis jedis = JedisMaker.make();
JedisIndex index = new JedisIndex(jedis);
//index.deleteTermCounters();
//index.deleteURLSets();
//index.deleteAllKeys();
//loadIndex(index);
System.out.println(index.size());
Map<String, Integer> map = index.getCountsFaster("the");
for (Entry<String, Integer> entry: map.entrySet()) {
System.out.println(entry);
}
}
/**
* Stores two pages in the index for testing purposes.
*
* @return
* @throws IOException
*/
private static void loadIndex(JedisIndex index) throws IOException {
WikiFetcher wf = new WikiFetcher();
String url = "https://en.wikipedia.org/wiki/Java_(programming_language)";
Elements paragraphs = wf.fetchWikipedia(url);
index.indexPage(url, paragraphs);
url = "https://en.wikipedia.org/wiki/Programming_language";
paragraphs = wf.fetchWikipedia(url);
index.indexPage(url, paragraphs);
}
}
|
[
"bwchang@berkeley.edu"
] |
bwchang@berkeley.edu
|
ad5ed80e8a54caa24e0819d2a4cefcba8b62f771
|
587e805e0064b57c49eea48008284a769d7ad0c6
|
/MyJava/src/leetcode/Prob313.java
|
b447acff67bfd9bd3db72e36bcc97134e40ed9c8
|
[] |
no_license
|
NuRrda/MyJava
|
6c77d42ab2174d0e972d016a8a72de90a31d54fd
|
a562e2ae139b15d3d50a851dcb9e54fba7fd49fe
|
refs/heads/master
| 2021-08-24T15:36:14.936873
| 2017-12-10T08:11:20
| 2017-12-10T08:11:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 835
|
java
|
package leetcode;
import java.util.PriorityQueue;
public class Prob313 {
public static void main(String[] args) {
final int i = new Prob313().nthSuperUglyNumber(2, new int[]{2, 3, 5});
System.out.println("i = " + i);
}
public int nthSuperUglyNumber(int n, int[] primes) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
heap.add(1);
int fetchCount = 0;
int min = -1;
while (fetchCount < n) {
min = heap.poll();
while (!heap.isEmpty() && heap.peek() == min) {
heap.poll();
}
for (int prime : primes) {
if (min < Integer.MAX_VALUE / prime) {
heap.add(prime * min);
}
}
fetchCount++;
}
return min;
}
}
|
[
"mdev@gracenote.com"
] |
mdev@gracenote.com
|
07378a684ff508086810e84d15b981a682e644b3
|
b78d8cea7c0abe2ce2637a487ed1978b171d9534
|
/src/it/imtlucca/lecture4/RendezvousPattern.java
|
9ad5204ac3b90fec9e60aa745ad25c144b8ac296
|
[] |
no_license
|
lillo/ppdp-course
|
2fe546e54b265a5d581dfcb9fc7b090f12ecf56e
|
f5b5eb8a86c4ae74866c73d4012a41f0799a42fe
|
refs/heads/master
| 2021-06-20T03:50:34.924504
| 2021-01-16T09:31:16
| 2021-01-16T09:31:16
| 166,976,075
| 0
| 2
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,316
|
java
|
package it.imtlucca.lecture4;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.BiFunction;
import java.util.stream.IntStream;
public class RendezvousPattern {
private Integer max1 = null;
private Integer max2 = null;
private Object commonObject1 = new Object();
private Object commonObject2 = new Object();
private Random rand = new Random();
// Exercise: Write in a better way without code duplication
private Runnable task1 = () -> {
synchronized (commonObject1) {
max1 = IntStream.range(0, 10)
.map(i -> rand.nextInt(100))
.max()
.orElse(Integer.MIN_VALUE);
System.out.printf("Task1 produces %d\n", max1);
commonObject1.notify();
}
synchronized (commonObject2){
try {
System.out.printf("Task1 start waiting\n");
while(max2 == null)
commonObject2.wait();
System.out.printf("Task1 consumes %d\n", max2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
private Runnable task2 = () -> {
synchronized (commonObject2) {
max2 = IntStream.range(0, 10)
.map(i -> rand.nextInt(100))
.max()
.orElse(Integer.MIN_VALUE);
System.out.printf("Task2 produces %d\n", max2);
commonObject2.notify();
}
synchronized (commonObject1){
try {
System.out.printf("Task2 start waiting\n");
while(max1 == null)
commonObject1.wait();
System.out.printf("Task1 consumes %d\n", max1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
public void run (){
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(task1);
executorService.submit(task2);
executorService.shutdown();
}
public static void main(String[] args){
RendezvousPattern pattern = new RendezvousPattern();
pattern.run();
}
}
|
[
"lillocpp@gmail.com"
] |
lillocpp@gmail.com
|
d1c6ac31672a1a6c8cf697ddc2953348a040847a
|
c43c8158179c982606c142565fe10cdbe051e9f3
|
/src/kr/ac/kookmin/cs/bigdata/pkh/WordCountForAsin.java
|
a5f7eccee90f26e9d0595064f00a45988cf5b6dd
|
[] |
no_license
|
kmucs-web-client-2017-01/kmucs-bigdata-project-bus-team
|
a4089b846ad2629ef0503cb014759e8ca01eae19
|
433ef729a934a6adc9f3566a38e10201f48b03c8
|
refs/heads/master
| 2021-03-19T10:52:13.941320
| 2017-06-05T14:50:21
| 2017-06-05T14:50:21
| 91,996,078
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,228
|
java
|
package kr.ac.kookmin.cs.bigdata.pkh;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import kr.ac.kookmin.cs.bigdata.pkh.WordCount.WordCountMapper;
import kr.ac.kookmin.cs.bigdata.pkh.WordCount.WordCountReducer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Reducer.Context;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.json.JSONException;
import org.json.JSONObject;
public class WordCountForAsin extends Configured implements Tool {
public static class WordCountForAsinMapper extends
Mapper<LongWritable, Text, Text, Text> {
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
try {
String[] wordAndAsinCounter = value.toString().split("\t");
String[] wordAndAsin = wordAndAsinCounter[0].split("@");
context.write(new Text(wordAndAsin[1]), new Text(wordAndAsin[0]
+ "=" + wordAndAsinCounter[1]));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static class WordCountForAsinReducer extends
Reducer<Text, Text, Text, Text> {
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
int sumofWordsInAsin = 0;
Map<String, Integer> tempCounter = new HashMap<String, Integer>();
for (Text val : values) {
String[] wordCounter = val.toString().split("=");
tempCounter
.put(wordCounter[0], Integer.valueOf(wordCounter[1]));
sumofWordsInAsin += Integer
.parseInt(val.toString().split("=")[1]);
}
for (String wordKey : tempCounter.keySet()) {
context.write(new Text(wordKey + "@" + key.toString()),
new Text(tempCounter.get(wordKey) + "/"
+ sumofWordsInAsin));
}
}
}
public int run(String[] args) throws Exception {
Configuration conf = new Configuration(true);
conf.set("fs.default.name", "hdfs://" + "master" + ":9000");
Job wordCountForAsin = new Job(conf, "WordCountForAsin");
wordCountForAsin.setJarByClass(WordCountForAsinMapper.class);
wordCountForAsin.setOutputKeyClass(Text.class);
wordCountForAsin.setOutputValueClass(Text.class);
wordCountForAsin.setMapperClass(WordCountForAsinMapper.class);
wordCountForAsin.setReducerClass(WordCountForAsinReducer.class);
wordCountForAsin.setInputFormatClass(TextInputFormat.class);
wordCountForAsin.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.addInputPath(wordCountForAsin, new Path(
Tfidf.INPUTPATH2));
FileOutputFormat.setOutputPath(wordCountForAsin, new Path(
Tfidf.OUTPUTPATH2));
wordCountForAsin.waitForCompletion(true);
return 0;
}
}
|
[
"eaia@naver.com"
] |
eaia@naver.com
|
8a459df7ad0c78300a64bdf36ce4c9a542584200
|
26dd138a7ac5ff7b607905c778f831e2cc33e9cd
|
/src/org/tsinghua/omedia/form/ShowFriendCcnFileForm.java
|
105ce02fa617e24338da214cec0399c470c160d4
|
[] |
no_license
|
xuhongfeng/OmediaAndroid
|
fc550b59b1521e9a14a959c11fa91f369d732664
|
58cf0dec8bda1aae1bc087a7b4f5a83f91ec953f
|
refs/heads/master
| 2016-09-03T07:17:27.463946
| 2014-01-09T00:50:27
| 2014-01-09T00:50:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 392
|
java
|
package org.tsinghua.omedia.form;
import org.tsinghua.omedia.annotation.form.HttpParam;
/**
*
* @author xuhongfeng
*
*/
public class ShowFriendCcnFileForm extends BaseForm {
@HttpParam(name="friendId")
private long friendId;
public long getFriendId() {
return friendId;
}
public void setFriendId(long friendId) {
this.friendId = friendId;
}
}
|
[
"xuhongfeng@wandoujia.com"
] |
xuhongfeng@wandoujia.com
|
e21f2dd5d98492b5826a354ebeaf6e26d54ecca5
|
acdcbd5efe554791742c5226334b3b87a8ef54ca
|
/java-code/expense-business/src/main/java/bht/expense/business/enterprise/strategy/controller/StrategyController.java
|
b7cb761164b5ba98c0a7e2f04067fd0c499a8e93
|
[] |
no_license
|
helilangyan/expense
|
9484515d5bbbab9ea9c8328b2e1db2a086597952
|
9cc5e0edf76b7c7e8dc943f984ea5a8cd58d6269
|
refs/heads/main
| 2023-06-27T12:57:59.738879
| 2021-07-22T17:58:52
| 2021-07-22T17:58:52
| 388,550,452
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,797
|
java
|
package bht.expense.business.enterprise.strategy.controller;
import bht.expense.business.common.ResultDto;
import bht.expense.business.enterprise.strategy.detail.label.dto.StrategyLabelEntityDto;
import bht.expense.business.enterprise.strategy.dto.StrategyEntityDto;
import bht.expense.business.enterprise.strategy.service.StrategyService;
import bht.expense.business.security.entity.UserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author 姚轶文
* @date 2021/6/25 15:17
*/
@Api(tags = "费用策略")
@RestController
@RequestMapping("enterprise/strategy")
public class StrategyController {
@Autowired
StrategyService strategyService;
@ApiOperation("列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "第几页", required = true),
@ApiImplicitParam(name = "limit", value = "每页多少条记录", required = true),
@ApiImplicitParam(name = "enterpriseId", value = "企业ID", required = true)
})
@PostMapping("/list")
public ResultDto list(int page, int limit , Long enterpriseId)
{
return strategyService.list(page, limit, enterpriseId);
}
@ApiOperation("根据ID查询")
@ApiImplicitParam(name = "id", value = "id", required = true)
@GetMapping("/{id}")
public ResultDto findById(@PathVariable Long id)
{
return strategyService.findById(id);
}
@ApiOperation("插入,新增或修改,根据ID自动判断")
@PostMapping("/insert")
public ResultDto insert(@RequestBody StrategyEntityDto strategyEntityDto) {
return strategyService.insert(strategyEntityDto);
}
@ApiOperation("根据ID删除")
@ApiImplicitParam(name = "id", value = "ID", required = true)
@DeleteMapping("/del/{id}")
public ResultDto delete(@PathVariable Long id) {
return strategyService.delete(id);
}
@ApiOperation("批量删除,传入ID数组")
@DeleteMapping("/dels/{id}")
public ResultDto deletes(@PathVariable Long[] id) {
return strategyService.deletes(id);
}
@ApiOperation("查询用户匹配的策略费用分类")
@ApiImplicitParam(name = "enterpriseId", value = "企业ID", required = true)
@PostMapping("/user-classify")
public ResultDto findUserClassify(Long enterpriseId)
{
UserEntity userEntity = (UserEntity) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return strategyService.findUserClassify(Long.parseLong(userEntity.getId()), enterpriseId);
}
@ApiOperation("查询用户匹配的标签分类")
@ApiImplicitParam(name = "enterpriseId", value = "企业ID", required = true)
@PostMapping("/user-label")
public ResultDto findUserLabel(Long enterpriseId)
{
UserEntity userEntity = (UserEntity) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return strategyService.findUserLabel(Long.parseLong(userEntity.getId()), enterpriseId);
}
@ApiOperation("查询用户匹配的交通工具分类")
@ApiImplicitParam(name = "enterpriseId", value = "企业ID", required = true)
@PostMapping("/user-vehicle")
public ResultDto findUserVehicle(Long enterpriseId)
{
UserEntity userEntity = (UserEntity) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return strategyService.findUserVehicle(Long.parseLong(userEntity.getId()), enterpriseId);
}
}
|
[
"helilangyan@outlook.com"
] |
helilangyan@outlook.com
|
384f51d109c48fe2dbac268baf0a82f4d0dadd42
|
0a1f9e40d9651e7dad4d38cdc46b17a8bc5c184d
|
/nbone/nbone-core/src/main/java/org/nbone/mvc/rest/AbstractController.java
|
0027fdd915e1441471cad4042d7124fd2ab9df01
|
[
"Apache-2.0"
] |
permissive
|
thinking-github/nbone
|
ad464e05107ae9105155b1fadc1e2da3f7f731ca
|
e51024429244e408d41e1a4e13859ace7d7fdbdf
|
refs/heads/master
| 2023-03-04T11:18:15.806483
| 2023-03-01T06:41:01
| 2023-03-01T06:41:01
| 52,860,583
| 9
| 2
|
Apache-2.0
| 2020-10-13T07:45:51
| 2016-03-01T08:26:09
|
Java
|
UTF-8
|
Java
| false
| false
| 178
|
java
|
package org.nbone.mvc.rest;
/**
* Created by chenyicheng on 2018/5/27.
*
* @author chenyicheng
* @version 1.0
* @since 2018/5/27
*/
public class AbstractController {
}
|
[
"chenyicheng@protonmail.com"
] |
chenyicheng@protonmail.com
|
f11cb0dbb89547c006633d7d1a4922c3cc7a0116
|
c49b6618c505d94a03eafdd799a463d31caf4775
|
/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/Robot.java
|
485dfc3be69352595adc8a1114ebcd9bd5b1ccd7
|
[
"BSD-3-Clause"
] |
permissive
|
1481-tw1c3b0t/allwpilib-tw1c3b0t
|
565bba716673ebde3ae3cc07049032840a12c7fb
|
697554c09be0ee6e509a0e601f969fcff4e0b08e
|
refs/heads/master
| 2020-11-29T00:34:33.622569
| 2020-10-11T05:34:37
| 2020-10-11T05:34:37
| 229,962,941
| 0
| 1
|
NOASSERTION
| 2020-10-11T04:39:18
| 2019-12-24T15:19:12
|
C++
|
UTF-8
|
Java
| false
| false
| 2,275
|
java
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2020 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.examples.statespacedifferentialdrivesimulation;
import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj.simulation.RoboRioSim;
import edu.wpi.first.wpilibj.simulation.BatterySim;
import edu.wpi.first.wpilibj2.command.CommandScheduler;
/**
* This is a sample program to demonstrate the use of state-space classes in robot simulation.
* This robot has a flywheel, elevator, arm and differential drivetrain, and interfaces with
* the sim GUI's {@link edu.wpi.first.wpilibj.simulation.Field2d} class.
*/
public class Robot extends TimedRobot {
private RobotContainer m_robotContainer;
/**
* This function is run when the robot is first started up and should be used for any
* initialization code.
*/
@Override
public void robotInit() {
// Instantiate our RobotContainer. This will perform all our button bindings, and put our
// autonomous chooser on the dashboard.
m_robotContainer = new RobotContainer();
}
@Override
public void simulationPeriodic() {
// Here we calculate the battery voltage based on drawn current.
// As our robot draws more power from the battery its voltage drops.
// The estimated voltage is highly dependent on the battery's internal
// resistance.
double drawCurrent = m_robotContainer.getRobotDrive().getDrawnCurrentAmps();
double loadedVoltage = BatterySim.calculateDefaultBatteryLoadedVoltage(drawCurrent);
RoboRioSim.setVInVoltage(loadedVoltage);
}
@Override
public void robotPeriodic() {
CommandScheduler.getInstance().run();
}
@Override
public void autonomousInit() {
m_robotContainer.getAutonomousCommand().schedule();
}
@Override
public void disabledInit() {
CommandScheduler.getInstance().cancelAll();
}
}
|
[
"noreply@github.com"
] |
noreply@github.com
|
8f106ac4e1b5f29eee2e5b7da716b4e17d20a44e
|
a62d1806650f87186f8a6e6cfa6b30256a51acd1
|
/src/CusPro2/Test.java
|
6fb9c5d9a1af14efd94a023a128c93c42beb74b6
|
[] |
no_license
|
XiaYiTiao/Vcode
|
94958fd142c347cdff1eb9d9031c8c892737e408
|
3f22db0fc422092c605c980f8fed03fd316a4074
|
refs/heads/master
| 2020-05-14T12:34:46.825996
| 2019-04-09T16:03:10
| 2019-04-09T16:03:10
| 181,796,217
| 1
| 0
| null | 2019-04-17T01:43:30
| 2019-04-17T01:43:30
| null |
UTF-8
|
Java
| false
| false
| 1,309
|
java
|
package CusPro2;
/**
* <a href="http://lib.csdn.net/base/softwaretest" class='replace_word' title=
* "软件测试知识库" target='_blank' style='color:#df3434;
* font-weight:bold;'>测试</a>类Test
*
* Email:530025983@qq.com
*
* @author MONKEY.D.MENG 2011-03-15
*
*/
public class Test {
public static void main(String[] args) {
// 仓库对象
Storage storage = new Storage();
// 生产者对象
Producer p1 = new Producer(storage);
Producer p2 = new Producer(storage);
Producer p3 = new Producer(storage);
Producer p4 = new Producer(storage);
Producer p5 = new Producer(storage);
Producer p6 = new Producer(storage);
Producer p7 = new Producer(storage);
// 消费者对象
Consumer c1 = new Consumer(storage);
Consumer c2 = new Consumer(storage);
Consumer c3 = new Consumer(storage);
// 设置生产者产品生产数量
p1.setNum(10);
p2.setNum(10);
p3.setNum(10);
p4.setNum(10);
p5.setNum(10);
p6.setNum(10);
p7.setNum(80);
// 设置消费者产品消费数量
c1.setNum(50);
c2.setNum(20);
c3.setNum(30);
// 线程开始执行
c1.start();
c2.start();
c3.start();
p1.start();
p2.start();
p3.start();
p4.start();
p5.start();
p6.start();
p7.start();
}
}
|
[
"victorzsnail@qq.com"
] |
victorzsnail@qq.com
|
e2490f5d3b913e5a6ff9f43ae632202ce20ae03d
|
f59f3fac089a3311c69c19488387cd87be11ca34
|
/src/com/claro/cpymes/dto/UserDTO.java
|
3eff1d8fda2cb7e989d5e48fa3873891c573821d
|
[] |
no_license
|
julbarg/CPYMES
|
9819ebedbacd816f70874b57e126a691aee50b66
|
90892cc5866b694b55227b354ba5e301046c4493
|
refs/heads/master
| 2021-01-25T12:08:39.636213
| 2015-09-28T19:36:38
| 2015-09-28T19:36:38
| 34,672,981
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 660
|
java
|
package com.claro.cpymes.dto;
import java.io.Serializable;
/**
* UserDTO
* @author jbarragan
*
*/
public class UserDTO implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8134728024247578499L;
private String userName;
private String password;
public String getUserName() {
return userName != null ? userName : "";
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
[
"julbarg@gmail.com"
] |
julbarg@gmail.com
|
8e8681cb08abacec16be4022ba8c91f41689773a
|
1b0840cf836cd8b7a2298ffbd239d1e405d69e8b
|
/parquet-mr-apache-parquet-1.7.0/parquet-hadoop/src/main/java/org/apache/parquet/hadoop/ParquetOutputFormat.java
|
d849843b191875e079416400d59a8089bd3ffb04
|
[
"Apache-2.0"
] |
permissive
|
Lionel-Coding-Lee/readKafka
|
e64c3d0efdc561dada466edde702b6f81ec861d8
|
7308cb209419e3c81cb30d446cbba2ec44a6a156
|
refs/heads/master
| 2021-01-20T01:38:11.903866
| 2017-04-25T05:58:29
| 2017-04-25T05:58:29
| 89,309,380
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 14,509
|
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.parquet.hadoop;
import static org.apache.parquet.Log.INFO;
import static org.apache.parquet.Preconditions.checkNotNull;
import static org.apache.parquet.hadoop.ParquetWriter.DEFAULT_BLOCK_SIZE;
import static org.apache.parquet.hadoop.ParquetWriter.DEFAULT_PAGE_SIZE;
import static org.apache.parquet.hadoop.util.ContextUtil.getConfiguration;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.OutputCommitter;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.parquet.Log;
import org.apache.parquet.column.ParquetProperties.WriterVersion;
import org.apache.parquet.hadoop.api.WriteSupport;
import org.apache.parquet.hadoop.api.WriteSupport.WriteContext;
import org.apache.parquet.hadoop.codec.CodecConfig;
import org.apache.parquet.hadoop.metadata.CompressionCodecName;
import org.apache.parquet.hadoop.util.ConfigurationUtil;
/**
* OutputFormat to write to a Parquet file
*
* It requires a {@link WriteSupport} to convert the actual records to the underlying format.
* It requires the schema of the incoming records. (provided by the write support)
* It allows storing extra metadata in the footer (for example: for schema compatibility purpose when converting from a different schema language).
*
* The format configuration settings in the job configuration:
* <pre>
* # The block size is the size of a row group being buffered in memory
* # this limits the memory usage when writing
* # Larger values will improve the IO when reading but consume more memory when writing
* parquet.block.size=134217728 # in bytes, default = 128 * 1024 * 1024
*
* # The page size is for compression. When reading, each page can be decompressed independently.
* # A block is composed of pages. The page is the smallest unit that must be read fully to access a single record.
* # If this value is too small, the compression will deteriorate
* parquet.page.size=1048576 # in bytes, default = 1 * 1024 * 1024
*
* # There is one dictionary page per column per row group when dictionary encoding is used.
* # The dictionary page size works like the page size but for dictionary
* parquet.dictionary.page.size=1048576 # in bytes, default = 1 * 1024 * 1024
*
* # The compression algorithm used to compress pages
* parquet.compression=UNCOMPRESSED # one of: UNCOMPRESSED, SNAPPY, GZIP, LZO. Default: UNCOMPRESSED. Supersedes mapred.output.compress*
*
* # The write support class to convert the records written to the OutputFormat into the events accepted by the record consumer
* # Usually provided by a specific ParquetOutputFormat subclass
* parquet.write.support.class= # fully qualified name
*
* # To enable/disable dictionary encoding
* parquet.enable.dictionary=true # false to disable dictionary encoding
*
* # To enable/disable summary metadata aggregation at the end of a MR job
* # The default is true (enabled)
* parquet.enable.summary-metadata=true # false to disable summary aggregation
* </pre>
*
* If parquet.compression is not set, the following properties are checked (FileOutputFormat behavior).
* Note that we explicitely disallow custom Codecs
* <pre>
* mapred.output.compress=true
* mapred.output.compression.codec=org.apache.hadoop.io.compress.SomeCodec # the codec must be one of Snappy, GZip or LZO
* </pre>
*
* if none of those is set the data is uncompressed.
*
* @author Julien Le Dem
*
* @param <T> the type of the materialized records
*/
public class ParquetOutputFormat<T> extends FileOutputFormat<Void, T> {
private static final Log LOG = Log.getLog(ParquetOutputFormat.class);
public static final String BLOCK_SIZE = "parquet.block.size";
public static final String PAGE_SIZE = "parquet.page.size";
public static final String COMPRESSION = "parquet.compression";
public static final String WRITE_SUPPORT_CLASS = "parquet.write.support.class";
public static final String DICTIONARY_PAGE_SIZE = "parquet.dictionary.page.size";
public static final String ENABLE_DICTIONARY = "parquet.enable.dictionary";
public static final String VALIDATION = "parquet.validation";
public static final String WRITER_VERSION = "parquet.writer.version";
public static final String ENABLE_JOB_SUMMARY = "parquet.enable.summary-metadata";
public static final String MEMORY_POOL_RATIO = "parquet.memory.pool.ratio";
public static final String MIN_MEMORY_ALLOCATION = "parquet.memory.min.chunk.size";
public static void setWriteSupportClass(Job job, Class<?> writeSupportClass) {
getConfiguration(job).set(WRITE_SUPPORT_CLASS, writeSupportClass.getName());
}
public static void setWriteSupportClass(JobConf job, Class<?> writeSupportClass) {
job.set(WRITE_SUPPORT_CLASS, writeSupportClass.getName());
}
public static Class<?> getWriteSupportClass(Configuration configuration) {
final String className = configuration.get(WRITE_SUPPORT_CLASS);
if (className == null) {
return null;
}
final Class<?> writeSupportClass = ConfigurationUtil.getClassFromConfig(configuration, WRITE_SUPPORT_CLASS, WriteSupport.class);
return writeSupportClass;
}
public static void setBlockSize(Job job, int blockSize) {
getConfiguration(job).setInt(BLOCK_SIZE, blockSize);
}
public static void setPageSize(Job job, int pageSize) {
getConfiguration(job).setInt(PAGE_SIZE, pageSize);
}
public static void setDictionaryPageSize(Job job, int pageSize) {
getConfiguration(job).setInt(DICTIONARY_PAGE_SIZE, pageSize);
}
public static void setCompression(Job job, CompressionCodecName compression) {
getConfiguration(job).set(COMPRESSION, compression.name());
}
public static void setEnableDictionary(Job job, boolean enableDictionary) {
getConfiguration(job).setBoolean(ENABLE_DICTIONARY, enableDictionary);
}
public static boolean getEnableDictionary(JobContext jobContext) {
return getEnableDictionary(getConfiguration(jobContext));
}
public static int getBlockSize(JobContext jobContext) {
return getBlockSize(getConfiguration(jobContext));
}
public static int getPageSize(JobContext jobContext) {
return getPageSize(getConfiguration(jobContext));
}
public static int getDictionaryPageSize(JobContext jobContext) {
return getDictionaryPageSize(getConfiguration(jobContext));
}
public static CompressionCodecName getCompression(JobContext jobContext) {
return getCompression(getConfiguration(jobContext));
}
public static boolean isCompressionSet(JobContext jobContext) {
return isCompressionSet(getConfiguration(jobContext));
}
public static void setValidation(JobContext jobContext, boolean validating) {
setValidation(getConfiguration(jobContext), validating);
}
public static boolean getValidation(JobContext jobContext) {
return getValidation(getConfiguration(jobContext));
}
public static boolean getEnableDictionary(Configuration configuration) {
return configuration.getBoolean(ENABLE_DICTIONARY, true);
}
@Deprecated
public static int getBlockSize(Configuration configuration) {
return configuration.getInt(BLOCK_SIZE, DEFAULT_BLOCK_SIZE);
}
public static long getLongBlockSize(Configuration configuration) {
return configuration.getLong(BLOCK_SIZE, DEFAULT_BLOCK_SIZE);
}
public static int getPageSize(Configuration configuration) {
return configuration.getInt(PAGE_SIZE, DEFAULT_PAGE_SIZE);
}
public static int getDictionaryPageSize(Configuration configuration) {
return configuration.getInt(DICTIONARY_PAGE_SIZE, DEFAULT_PAGE_SIZE);
}
public static WriterVersion getWriterVersion(Configuration configuration) {
String writerVersion = configuration.get(WRITER_VERSION, WriterVersion.PARQUET_1_0.toString());
return WriterVersion.fromString(writerVersion);
}
public static CompressionCodecName getCompression(Configuration configuration) {
return CodecConfig.getParquetCompressionCodec(configuration);
}
public static boolean isCompressionSet(Configuration configuration) {
return CodecConfig.isParquetCompressionSet(configuration);
}
public static void setValidation(Configuration configuration, boolean validating) {
configuration.setBoolean(VALIDATION, validating);
}
public static boolean getValidation(Configuration configuration) {
return configuration.getBoolean(VALIDATION, false);
}
private CompressionCodecName getCodec(TaskAttemptContext taskAttemptContext) {
return CodecConfig.from(taskAttemptContext).getCodec();
}
private WriteSupport<T> writeSupport;
private ParquetOutputCommitter committer;
/**
* constructor used when this OutputFormat in wrapped in another one (In Pig for example)
* @param writeSupportClass the class used to convert the incoming records
* @param schema the schema of the records
* @param extraMetaData extra meta data to be stored in the footer of the file
*/
public <S extends WriteSupport<T>> ParquetOutputFormat(S writeSupport) {
this.writeSupport = writeSupport;
}
/**
* used when directly using the output format and configuring the write support implementation
* using parquet.write.support.class
*/
public <S extends WriteSupport<T>> ParquetOutputFormat() {
}
/**
* {@inheritDoc}
*/
@Override
public RecordWriter<Void, T> getRecordWriter(TaskAttemptContext taskAttemptContext)
throws IOException, InterruptedException {
final Configuration conf = getConfiguration(taskAttemptContext);
CompressionCodecName codec = getCodec(taskAttemptContext);
String extension = codec.getExtension() + ".parquet";
Path file = getDefaultWorkFile(taskAttemptContext, extension);
return getRecordWriter(conf, file, codec);
}
public RecordWriter<Void, T> getRecordWriter(TaskAttemptContext taskAttemptContext, Path file)
throws IOException, InterruptedException {
return getRecordWriter(getConfiguration(taskAttemptContext), file, getCodec(taskAttemptContext));
}
public RecordWriter<Void, T> getRecordWriter(Configuration conf, Path file, CompressionCodecName codec)
throws IOException, InterruptedException {
final WriteSupport<T> writeSupport = getWriteSupport(conf);
CodecFactory codecFactory = new CodecFactory(conf);
long blockSize = getLongBlockSize(conf);
if (INFO) LOG.info("Parquet block size to " + blockSize);
int pageSize = getPageSize(conf);
if (INFO) LOG.info("Parquet page size to " + pageSize);
int dictionaryPageSize = getDictionaryPageSize(conf);
if (INFO) LOG.info("Parquet dictionary page size to " + dictionaryPageSize);
boolean enableDictionary = getEnableDictionary(conf);
if (INFO) LOG.info("Dictionary is " + (enableDictionary ? "on" : "off"));
boolean validating = getValidation(conf);
if (INFO) LOG.info("Validation is " + (validating ? "on" : "off"));
WriterVersion writerVersion = getWriterVersion(conf);
if (INFO) LOG.info("Writer version is: " + writerVersion);
WriteContext init = writeSupport.init(conf);
ParquetFileWriter w = new ParquetFileWriter(conf, init.getSchema(), file);
w.start();
float maxLoad = conf.getFloat(ParquetOutputFormat.MEMORY_POOL_RATIO,
MemoryManager.DEFAULT_MEMORY_POOL_RATIO);
long minAllocation = conf.getLong(ParquetOutputFormat.MIN_MEMORY_ALLOCATION,
MemoryManager.DEFAULT_MIN_MEMORY_ALLOCATION);
if (memoryManager == null) {
memoryManager = new MemoryManager(maxLoad, minAllocation);
} else if (memoryManager.getMemoryPoolRatio() != maxLoad) {
LOG.warn("The configuration " + MEMORY_POOL_RATIO + " has been set. It should not " +
"be reset by the new value: " + maxLoad);
}
return new ParquetRecordWriter<T>(
w,
writeSupport,
init.getSchema(),
init.getExtraMetaData(),
blockSize, pageSize,
codecFactory.getCompressor(codec, pageSize),
dictionaryPageSize,
enableDictionary,
validating,
writerVersion,
memoryManager);
}
/**
* @param configuration to find the configuration for the write support class
* @return the configured write support
*/
@SuppressWarnings("unchecked")
public WriteSupport<T> getWriteSupport(Configuration configuration){
if (writeSupport != null) return writeSupport;
Class<?> writeSupportClass = getWriteSupportClass(configuration);
try {
return (WriteSupport<T>)checkNotNull(writeSupportClass, "writeSupportClass").newInstance();
} catch (InstantiationException e) {
throw new BadConfigurationException("could not instantiate write support class: " + writeSupportClass, e);
} catch (IllegalAccessException e) {
throw new BadConfigurationException("could not instantiate write support class: " + writeSupportClass, e);
}
}
@Override
public OutputCommitter getOutputCommitter(TaskAttemptContext context)
throws IOException {
if (committer == null) {
Path output = getOutputPath(context);
committer = new ParquetOutputCommitter(output, context);
}
return committer;
}
/**
* This memory manager is for all the real writers (InternalParquetRecordWriter) in one task.
*/
private static MemoryManager memoryManager;
static MemoryManager getMemoryManager() {
return memoryManager;
}
}
|
[
"lipf@dtdream.com"
] |
lipf@dtdream.com
|
a52d3fbba39937b30ebfd7d2ec613d955c1e0c48
|
e4f66a9395caa43722338d17a005749c5c352b62
|
/TicTacToeChallenge/src/tictactoe/TicTacToeBoardImpl.java
|
cf010ee626d216d1f02af6d112d0d57f33d7f40f
|
[] |
no_license
|
WillLuong97/Java-Kart-Homework
|
0b3944d4a30347b33774c180b8af215cb2fc9914
|
a03e6e81bbb93b9693f348072b40518b1eaee451
|
refs/heads/main
| 2023-04-03T12:57:16.701481
| 2021-04-11T22:17:40
| 2021-04-11T22:17:40
| 356,991,749
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 7,886
|
java
|
package tictactoe
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class TicTacToeBoardImpl implements TicTacToeBoard
{
//Symbolics:
protected static final int NO_MOVE = -1;
protected static final int NO_MATCH = -1;
protected int[] movesArray; //set of moves
//cell constructor.
public TicTacToeBoardImpl()
{
final int CELL_COUNT = ROW_COUNT*COLUMN_COUNT;
movesArray = new int[CELL_COUNT];
for(int i = 0 ; i< CELL_COUNT; i++)
{
movesArray[i] = NO_MOVE;
}
}//end of TicTacToeImpl()
//check to see if the move is O
public boolean isO(int index)
{
boolean oOrNot = false;
if(index > 0 && index%2==1)
{
oOrNot = true; //O only shows up in the odd index of the board.
}
return oOrNot;
}//end of isO()
//check to see if the move an X
public boolean isX(int index)
{
boolean xOrNot = false;
if(index >= 0 && index % 2 ==0)
{
xOrNot = true; //x only shows up in the even index of the board
}
return xOrNot;
}//end of isX()
//helper method to convert a row and column into the grid position on the board
public int rowAndColumnToInt(int row, int column)
{
int grid = 0;
if(row == 0)
{
grid = column;
}
if(row == 1)
{
grid = column + 3;
}
if(row == 2)
{
grid = column + 6;
}
return grid;
}//end of rowAndColumnToInt().
//part of pre: 0 <= row < ROW_COUNT && 0 <= column < COLUMN_COUNT
//part of post: rv == null <==> the (row, column) spot on the board is empty
//this function to determine what mark will return on the tictactoe board from the set of moves
public Mark getMark(int row, int column)
{
assert row >= 0;
assert row < ROW_COUNT;
assert column >=0;
assert column < COLUMN_COUNT;
int gridPosition = rowAndColumnToInt(row, column); //converting row and column into the grid position
int indexOfMoves = -1; //intial index
Mark retMark = null; //initial mark
//extracting the moves
for(int i = 0; i<movesArray.length; i++)
{
if(movesArray[i] == gridPosition)
{
indexOfMoves = i;
break;
}//end if.
}//end for.
//getting the mark
if(indexOfMoves != 1)
{
if(isO(indexOfMoves))
{
retMark = Mark.O;
}
else
{
retMark = Mark.X;
}
}//end if.
return retMark;
}//end of getMark(int row, int column)
//helper method to check if the integer representation of the row and column contains the moves
public boolean setMarkPreparation(int numericalRep)
{
boolean isMark = false;
for(int i = 0; i < movesArray.length; i++)
{
if(movesArray[i] == numericalRep) //the moves matches the row and column numerical representation.
{
isMark = true;
}
}//end for.
return isMark;
}//end of setMarkPreparation(int numericalRep)
//part of pre: 0<= row < ROW_COUNT && 0 <= column < COLUMN_COUNT
//part of pre: getMark(row, column) = null
//part of preL !isGameOver()
public void setMark(int row, int column)
{ //assertion:
assert row >= 0;
assert row < ROW_COUNT;
assert column >=0;
assert column < COLUMN_COUNT;
assert !isGameOver(); //the game cannot end
assert getMark(row, column) == null;
int gridPosition = rowAndColumnToInt(row, column); //converting row and column into an int
assert !setMarkPreparation(gridPosition);
//for loop to walk through the movesArray
for(int i = 0; i <movesArray.length; i++)
{
if(movesArray[i] == -1) //if there is no mark being set
{
movesArray[i] = gridPosition;
break;
}
}// end of for loop
}//end of setMark(int row, int column)
//part of post: rv==null <==> it is neither player's turn (i.e. game is over)
//part of post: "number of Marks on board is even" -> rv == Mark.X
//part of post: "number of Marks on board is odd" -> rv == Mark.o
public Mark getTurn()
{
Mark markVal = null;
int index = -2;
//loop through the movesArray
for(int i = 0; i < movesArray.length; i++)
{
if(movesArray[i]== NO_MOVE)
{
index = i;
break;
}
}
//if the index is within the valid moves
if(index!=-2)
{
if(isO(index)) //check if O
{
markVal = Mark.O;
}
else //check if X
{
markVal = Mark.X;
}
}
return markVal;
}//end of getTurn()
//helper method to determine the possibilities of winning the game
//rv: True if win and False if not
public boolean winOrNot(ArrayList<Integer>listOfMoves)
{
boolean foundWinner = false;
//possible ways to win the game
ArrayList<Set<Integer>> possibleWin = new ArrayList<Set<Integer>>(); //list to hold the possible way to win the game
Set<Integer> winByAcrossUp = new HashSet<>(Arrays.asList(0, 1, 2));
Set<Integer> winByAcrossBottom = new HashSet<>(Arrays.asList(6, 7, 8));
Set<Integer> winByAcrossMiddle = new HashSet<>(Arrays.asList(3, 4, 5));
Set<Integer> winByDiagonal1 = new HashSet<>(Arrays.asList(0, 4, 8));
Set<Integer> winByDiagonal2 = new HashSet<>(Arrays.asList(2, 4, 6));
Set<Integer> winByDown1= new HashSet<>(Arrays.asList(0, 3, 6));
Set<Integer> winByDown3 = new HashSet<>(Arrays.asList(2, 5, 8));
Set<Integer> winByDown2 = new HashSet<>(Arrays.asList(1, 4, 7));
//adding the possible win into a list
possibleWin.add(winByAcrossUp);
possibleWin.add(winByAcrossBottom);
possibleWin.add(winByAcrossMiddle);
possibleWin.add(winByDown1);
possibleWin.add(winByDown2);
possibleWin.add(winByDown3);
possibleWin.add(winByDiagonal1);
possibleWin.add(winByDiagonal2);
//loop through the list of possible winning moves
for(int i = 0; i< possibleWin.size(); i++)
{
if(listOfMoves.containsAll(possibleWin.get(i))) //if the moves in the list contains the winning move, then the winner is found.
{
foundWinner = true;
}
}
return foundWinner;
}//end of winOrNot()
//part of post: rv is True if the game is over and False if the game is not
public boolean isGameOver()
{
boolean isOver = false;
//creating two lists that hold O and X
ArrayList<Integer> listOfO = new ArrayList<Integer>();
ArrayList<Integer> listOfX = new ArrayList<Integer>();
//loop through the movesArray
for(int i = 0; i < movesArray.length; i++)
{
if(isO(i) && movesArray[i] != NO_MOVE) //if the index returns an O and there is a move in the board
{
listOfO.add(movesArray[i]); // then we add the index into the list
}
else if(isX(i) && movesArray[i] != NO_MOVE) // if the index returns an X and there is a move in the board
{
listOfX.add(movesArray[i]); //then we add the index into the list.
}
}//end for loop.
if(winOrNot(listOfO) || winOrNot(listOfX))
{
isOver = true;
}
else if(movesArray[8]!= NO_MOVE)
{
isOver = true;
}
return isOver;
}//end of isGameOver();
//part of pre: isGameOver()
//part of post: rv <==> neither player won (the game ended in a tie)
public Mark getWinner()
{
assert isGameOver();
Mark finalWinner = null; //two player ties
//list that hold the marks
ArrayList<Integer> listX = new ArrayList<Integer>();
ArrayList<Integer> listO = new ArrayList<Integer>();
//loop through the movesArray
for(int i = 0; i < movesArray.length; i++)
{
if( isX(i) && movesArray[i] != -1)
{
listX.add(movesArray[i]);
}//end if
if(isO(i) && movesArray[i] != -1)
{
listO.add(movesArray[i]);
}//end if
}//end for
if(winOrNot(listX))
{
finalWinner = Mark.X;
}
else if(winOrNot(listO))
{
finalWinner = Mark.O;
}
return finalWinner;
}//end of getWinner
//return a nicely formatted version of the string
public String toString()
{
String retStr = "";
for(int i = 0; i < movesArray.length; i++)
{
retStr += movesArray[i] + ",";
}
return retStr;
}//end of toString()
}//end of TicTacToeBoardImpl()
|
[
"tluong@stedwards.edu"
] |
tluong@stedwards.edu
|
aa9b577463945ff5ae200069767f3ac8b5969d88
|
9a58110748dc931c83ef29c2c811917c442ad696
|
/src/main/java/metier/Boutique.java
|
6dd78e60a647528fa18a7e0b87f29dfc23e958d3
|
[] |
no_license
|
PerrotLudovic/Nintendo
|
a8aa803516c1f40faa7375914ef041d13099e97c
|
ab844e14b797748496020f79b9fadeedb349494f
|
refs/heads/master
| 2023-03-25T20:55:02.991660
| 2021-03-12T17:54:09
| 2021-03-12T17:54:09
| 347,101,714
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 814
|
java
|
package metier;
import java.util.List;
public class Boutique {
private String nom;
private Adresse adresse;
private List<Jeu> listeJeux;
public Boutique() {
super();
}
public Boutique(String nom, Adresse adresse, List<Jeu> listeJeux) {
super();
this.nom = nom;
this.adresse = adresse;
this.listeJeux = listeJeux;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Adresse getAdresse() {
return adresse;
}
public void setAdresse(Adresse adresse) {
this.adresse = adresse;
}
public List<Jeu> getListeJeux() {
return listeJeux;
}
public void setListeJeux(List<Jeu> listeJeux) {
this.listeJeux = listeJeux;
}
@Override
public String toString() {
return "Boutique [nom=" + nom + ", adresse=" + adresse + "]";
}
}
|
[
"robelinjeremy@gmail.com"
] |
robelinjeremy@gmail.com
|
c73435f91ac5f15dd55ced16e28d3ddb565cc6ca
|
0290fe4f34a7b622faf7ae0e7c4403c7ab926a71
|
/module_3/src/main/java/com/alevel/entity/OperationCategories.java
|
5966d828d1d9309a82d0445ff29f9abcac58dba0
|
[] |
no_license
|
Diana-Kylymnyk/nix_7
|
1bd661db8c5449d0efdb12318e2409758addc82b
|
836d45dbac15f17dcd12f937706cde4df79b9d4d
|
refs/heads/master
| 2023-08-27T21:18:25.939616
| 2021-11-09T19:34:35
| 2021-11-09T19:34:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,076
|
java
|
package com.alevel.entity;
import javax.persistence.*;
@Entity
@Table(name = "operation_categories")
public class OperationCategories extends BasicEntity {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "operation_id")
private Operations operation;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "income_category_id")
private IncomeCategory incomeCategory;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "expense_category_id")
private ExpenseCategory expenseCategory;
public OperationCategories() {
}
public OperationCategories(Operations operation, IncomeCategory incomeCategory, ExpenseCategory expenseCategory) {
this.operation = operation;
this.incomeCategory = incomeCategory;
this.expenseCategory = expenseCategory;
}
public Operations getOperation() {
return operation;
}
public IncomeCategory getIncomeCategory() {
return incomeCategory;
}
public ExpenseCategory getExpenseCategory() {
return expenseCategory;
}
}
|
[
"Kylymnyk.n@gmail.com"
] |
Kylymnyk.n@gmail.com
|
fcd4db66b9f8f90c099f4e9e47364dc1486ebc35
|
44b78323a6e30a5f23085769c72665423a6152d9
|
/src/main/java/at/ac/webster/model/Event.java
|
7428d42b3c05dc5cbfcb1aa78d973284274a3645
|
[
"Apache-2.0"
] |
permissive
|
ginccc/lms-data-hub
|
9a471688bdf376ca3d5fcce631560c158c2c24c6
|
f5dc99c67cd84f34dc284a917e6db6e816d2c5a7
|
refs/heads/master
| 2020-09-14T15:09:42.382792
| 2019-12-23T15:56:30
| 2019-12-23T15:56:30
| 223,164,231
| 0
| 0
|
Apache-2.0
| 2020-05-09T21:30:53
| 2019-11-21T12:00:48
|
Java
|
UTF-8
|
Java
| false
| false
| 593
|
java
|
package at.ac.webster.model;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.util.Date;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class Event {
private String id;
private Type type;
private Date startAt;
private Date endAt;
private String cronSchedule;
private Interval interval;
private String studentGroupId;
public enum Type {
oneTime,
reoccurring
}
}
|
[
"gregor@jarisch.net"
] |
gregor@jarisch.net
|
c895483261e2038eaaa291d057451b1b87323803
|
b6cc6ccbbf740d6480cc1b77f05a0d640971ab98
|
/emu/src/net/katsuster/ememu/arm/core/DecodeStageThumb.java
|
b27ff3cceebf6d660e1bba41527c38afb4fb79a3
|
[
"Apache-2.0"
] |
permissive
|
indrajithbandara/ememu
|
7214173ff63d9818fc737c033d6478f556ff92c7
|
32fdc18bdacf5cb136eb655de9f800f0318fb286
|
refs/heads/master
| 2021-05-09T21:17:25.202666
| 2016-05-07T01:44:20
| 2016-05-07T01:44:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 16,426
|
java
|
package net.katsuster.ememu.arm.core;
import net.katsuster.ememu.generic.*;
/**
* Thumb 命令(Thumb v1, v2, v3)のデコードステージ。
*
* 参考: ARM アーキテクチャリファレンスマニュアル Second Edition
* ARM DDI0100DJ
*
* 最新版は、日本語版 ARM DDI0100HJ, 英語版 ARM DDI0100I
*
* @author katsuhiro
*/
public class DecodeStageThumb extends Stage {
/**
* ARMv5 CPU コア c のデコードステージを生成します。
*
* @param c デコードステージの持ち主となる ARMv5 CPU コア
*/
public DecodeStageThumb(ARMv5 c) {
super(c);
}
/**
* Thumbv1, v2, v3 命令をデコードします。
*
* @param inst Thumb 命令
* @return 命令の種類
*/
public OpIndex decode(InstructionThumb inst) {
int subcode = inst.getSubCodeField();
switch (subcode) {
case InstructionThumb.SUBCODE_ADDSUB:
return decodeAddSub(inst);
case InstructionThumb.SUBCODE_ALUIMM:
return decodeALUImm(inst);
case InstructionThumb.SUBCODE_ALUREG:
return decodeALUReg(inst);
case InstructionThumb.SUBCODE_LDWORD:
return decodeLdWord(inst);
case InstructionThumb.SUBCODE_LDHALF:
return decodeLdHalf(inst);
case InstructionThumb.SUBCODE_OTHERS:
return decodeOthers(inst);
case InstructionThumb.SUBCODE_LDMULT:
return decodeLdmult(inst);
case InstructionThumb.SUBCODE_BL_BLX:
return decodeBlBlx(inst);
default:
throw new IllegalArgumentException("Unknown Subcode" +
String.format("(%d).", subcode));
}
}
/**
* レジスタ加算、減算命令をデコードします。
*
* subcode = 0b000
*
* @param inst Thumb 命令
* @return 命令の種類
*/
public OpIndex decodeAddSub(InstructionThumb inst) {
int op = inst.getField(11, 2);
int opc = inst.getField(9, 2);
switch (op) {
case 0x0:
//lsl(1)
return OpIndex.INS_THUMB_LSL1;
case 0x1:
//lsr(1)
return OpIndex.INS_THUMB_LSR1;
case 0x2:
//asr(1)
return OpIndex.INS_THUMB_ASR1;
case 0x3:
//レジスタ、イミディエート加算、減算
switch (opc) {
case 0x0:
//add(3), レジスタ加算
return OpIndex.INS_THUMB_ADD3;
case 0x1:
//sub(3), レジスタ減算
return OpIndex.INS_THUMB_SUB3;
case 0x2:
//add(1), 小さいイミディエート加算
return OpIndex.INS_THUMB_ADD1;
case 0x3:
//sub(1), 小さいイミディエート減算
return OpIndex.INS_THUMB_SUB1;
default:
throw new IllegalArgumentException("Illegal opc(AddSub) bits " +
String.format("opc:0x%02x.", opc));
}
default:
throw new IllegalArgumentException("Illegal op(AddSub) bits " +
String.format("op:0x%02x.", op));
}
}
/**
* イミディエート加算、減算命令をデコードします。
*
* subcode = 0b001
*
* @param inst Thumb 命令
* @return 命令の種類
*/
public OpIndex decodeALUImm(InstructionThumb inst) {
int op = inst.getField(11, 2);
switch (op) {
case 0x0:
//mov(1)
return OpIndex.INS_THUMB_MOV1;
case 0x1:
//cmp(1)
return OpIndex.INS_THUMB_CMP1;
case 0x2:
//add(2)
return OpIndex.INS_THUMB_ADD2;
case 0x3:
//sub(2)
return OpIndex.INS_THUMB_SUB2;
default:
throw new IllegalArgumentException("Illegal op(ALLUImm) bits " +
String.format("op:0x%02x.", op));
}
}
/**
* レジスタへのデータ処理命令をデコードします。
*
* subcode = 0b010
*
* @param inst Thumb 命令
* @return 命令の種類
*/
public OpIndex decodeALUReg(InstructionThumb inst) {
int op = inst.getField(10, 3);
switch (op) {
case 0x0:
//データ処理レジスタ命令
return decodeALURegData(inst);
case 0x1:
//特殊データ処理、分岐、交換命令
return decodeALURegSpecial(inst);
case 0x2:
case 0x3:
//リテラルプールからのロード命令
return OpIndex.INS_THUMB_LDR3;
case 0x4:
case 0x5:
case 0x6:
case 0x7:
//ロード、ストアレジスタオフセット命令
return decodeALURegOffset(inst);
default:
throw new IllegalArgumentException("Illegal op(ALUReg) bits " +
String.format("op:0x%02x.", op));
}
}
/**
* レジスタへのデータ処理命令をデコードします。
*
* subcode = 0b010
* op[12:10] = 0b000
*
* @param inst Thumb 命令
* @return 命令の種類
*/
public OpIndex decodeALURegData(InstructionThumb inst) {
int op = inst.getOpcode5Field();
switch (op) {
case InstructionThumb.OPCODE5_AND:
return OpIndex.INS_THUMB_AND;
case InstructionThumb.OPCODE5_EOR:
return OpIndex.INS_THUMB_EOR;
case InstructionThumb.OPCODE5_LSL:
return OpIndex.INS_THUMB_LSL2;
case InstructionThumb.OPCODE5_LSR:
return OpIndex.INS_THUMB_LSR2;
case InstructionThumb.OPCODE5_ASR:
return OpIndex.INS_THUMB_ASR2;
case InstructionThumb.OPCODE5_ADC:
return OpIndex.INS_THUMB_ADC;
case InstructionThumb.OPCODE5_SBC:
return OpIndex.INS_THUMB_SBC;
case InstructionThumb.OPCODE5_ROR:
return OpIndex.INS_THUMB_ROR;
case InstructionThumb.OPCODE5_TST:
return OpIndex.INS_THUMB_TST;
case InstructionThumb.OPCODE5_NEG:
return OpIndex.INS_THUMB_NEG;
case InstructionThumb.OPCODE5_CMP:
return OpIndex.INS_THUMB_CMP2;
case InstructionThumb.OPCODE5_CMN:
return OpIndex.INS_THUMB_CMN;
case InstructionThumb.OPCODE5_ORR:
return OpIndex.INS_THUMB_ORR;
case InstructionThumb.OPCODE5_MUL:
return OpIndex.INS_THUMB_MUL;
case InstructionThumb.OPCODE5_BIC:
return OpIndex.INS_THUMB_BIC;
case InstructionThumb.OPCODE5_MVN:
return OpIndex.INS_THUMB_MVN;
default:
throw new IllegalArgumentException("Illegal op(ALURegData) bits " +
String.format("op:0x%02x.", op));
}
}
/**
* 特殊データ処理、分岐、交換命令をデコードします。
*
* subcode = 0b010
* op[12:10] = 0b001
*
* @param inst Thumb 命令
* @return 命令の種類
*/
public OpIndex decodeALURegSpecial(InstructionThumb inst) {
int op = inst.getField(6, 4);
switch (op) {
case 0x0:
//下位レジスタの加算(ADD)、ARMv6T2 以降
return OpIndex.INS_THUMB_ADD4;
case 0x1:
case 0x2:
case 0x3:
//上位レジスタの加算(ADD)
return OpIndex.INS_THUMB_ADD4;
//case 0x4:
//(予測不能)
case 0x5:
case 0x6:
case 0x7:
//上位レジスタの比較(CMP)
return OpIndex.INS_THUMB_CMP3;
case 0x8:
//下位レジスタの移動(MOV)、ARMv6 以降
return OpIndex.INS_THUMB_MOV3;
case 0x9:
case 0xa:
case 0xb:
//上位レジスタの移動(MOV)
return OpIndex.INS_THUMB_MOV3;
case 0xc:
case 0xd:
//分岐と状態遷移(BX)
return OpIndex.INS_THUMB_BX;
case 0xe:
case 0xf:
//リンク付き分岐と状態遷移(BLX)
return OpIndex.INS_THUMB_BLX2;
default:
throw new IllegalArgumentException("Illegal op(ALURegSpecial) bits " +
String.format("op:0x%02x.", op));
}
}
/**
* ロード、ストアレジスタオフセット命令をデコードします。
*
* subcode = 0b010
* op[12:10] = 0b1xx
*
* @param inst Thumb 命令
* @return 命令の種類
*/
public OpIndex decodeALURegOffset(InstructionThumb inst) {
int op = inst.getField(9, 3);
switch (op) {
case 0x0:
//レジスタストア(STR)
return OpIndex.INS_THUMB_STR2;
case 0x1:
//レジスタストア ハーフワード(STRH)
return OpIndex.INS_THUMB_STRH2;
case 0x2:
//レジスタストア バイト(STRB)
return OpIndex.INS_THUMB_STRB2;
case 0x3:
//レジスタロード 符号付きバイト(LDRSB)
return OpIndex.INS_THUMB_LDRSB;
case 0x4:
//レジスタロード(LDR)
return OpIndex.INS_THUMB_LDR2;
case 0x5:
//レジスタロード ハーフワード(LDRH)
return OpIndex.INS_THUMB_LDRH2;
case 0x6:
//レジスタロード バイト(LDRB)
return OpIndex.INS_THUMB_LDRB2;
case 0x7:
//レジスタロード 符号付きハーフワード(LDRSH)
return OpIndex.INS_THUMB_LDRSH;
default:
throw new IllegalArgumentException("Illegal op(RegOffset) bits " +
String.format("op:0x%02x.", op));
}
}
/**
* ワード、バイトのロード、ストア命令をデコードします。
*
* subcode = 0b011
*
* @param inst Thumb 命令
* @return 命令の種類
*/
public OpIndex decodeLdWord(InstructionThumb inst) {
int op = inst.getField(11, 2);
switch (op) {
case 0x0:
//レジスタストア(STR)
return OpIndex.INS_THUMB_STR1;
case 0x1:
//レジスタロード(LDR)
return OpIndex.INS_THUMB_LDR1;
case 0x2:
//レジスタストア バイト(STRB)
return OpIndex.INS_THUMB_STRB1;
case 0x3:
//レジスタロード バイト(LDRB)
return OpIndex.INS_THUMB_LDRB1;
default:
throw new IllegalArgumentException("Illegal op(LdWord) bits " +
String.format("op:0x%02x.", op));
}
}
/**
* ハーフワードのロード、ストア命令、スタックのロード、ストア命令をデコードします。
*
* subcode = 0b100
*
* @param inst Thumb 命令
* @return 命令の種類
*/
public OpIndex decodeLdHalf(InstructionThumb inst) {
int op = inst.getField(11, 2);
switch (op) {
case 0x0:
//ストア ハーフワード(STRH)
return OpIndex.INS_THUMB_STRH1;
case 0x1:
//ロード ハーフワード(LDRH)
return OpIndex.INS_THUMB_LDRH1;
case 0x2:
//ストア SP 相対(STR)
return OpIndex.INS_THUMB_STR3;
case 0x3:
//ロード SP 相対(LDR)
return OpIndex.INS_THUMB_LDR4;
default:
throw new IllegalArgumentException("Illegal op(LdHalf) bits " +
String.format("op:0x%02x.", op));
}
}
/**
* SP, PC 加算命令、その他の命令をデコードします。
*
* subcode = 0b101
*
* @param inst Thumb 命令
* @return 命令の種類
*/
public OpIndex decodeOthers(InstructionThumb inst) {
int op = inst.getField(11, 2);
switch (op) {
case 0x0:
//PC への加算(ADD)
return OpIndex.INS_THUMB_ADD5;
case 0x1:
//SP への加算(ADD)
return OpIndex.INS_THUMB_ADD6;
case 0x2:
//その他の命令
int op2 = inst.getField(5, 6);
switch (op2) {
case 0x00: //0b0000xx
case 0x01:
case 0x02:
case 0x03:
//スタックポインタの加算(ADD)
return OpIndex.INS_THUMB_ADD7;
case 0x04: //0b0001xx
case 0x05:
case 0x06:
case 0x07:
//スタックポインタの減算(SUB)
return OpIndex.INS_THUMB_SUB4;
case 0x20: case 0x21: case 0x22: case 0x23: //0b10xxxx
case 0x24: case 0x25: case 0x26: case 0x27:
case 0x28: case 0x29: case 0x2a: case 0x2b:
case 0x2c: case 0x2d: case 0x2e: case 0x2f:
//複数レジスタプッシュ(PUSH)
return OpIndex.INS_THUMB_PUSH;
default:
throw new IllegalArgumentException("Illegal op2(op=0b10, Others) bits " +
String.format("op2:0x%02x.", op2));
}
case 0x3:
//その他の命令
int op3 = inst.getField(5, 6);
switch (op3) {
case 0x20: case 0x21: case 0x22: case 0x23: //0b10xxxx
case 0x24: case 0x25: case 0x26: case 0x27:
case 0x28: case 0x29: case 0x2a: case 0x2b:
case 0x2c: case 0x2d: case 0x2e: case 0x2f:
//複数レジスタポップ(POP)
return OpIndex.INS_THUMB_POP;
case 0x30: case 0x31: case 0x32: case 0x33: //0b10xxxx
case 0x34: case 0x35: case 0x36: case 0x37:
//ブレークポイント(BKPT)
return OpIndex.INS_THUMB_BKPT;
default:
throw new IllegalArgumentException("Illegal op2(op=0x11, Others) bits " +
String.format("op3:0x%02x.", op3));
}
default:
throw new IllegalArgumentException("Illegal op(Others) bits " +
String.format("op:0x%02x.", op));
}
}
/**
* ロード、ストアマルチプル命令、条件付き分岐命令をデコードします。
*
* subcode = 0b110
*
* @param inst Thumb 命令
* @return 命令の種類
*/
public OpIndex decodeLdmult(InstructionThumb inst) {
int op = inst.getField(11, 2);
switch (op) {
case 0x0:
//ストアマルチプル(STMIA)
return OpIndex.INS_THUMB_STMIA;
case 0x1:
//ロードマルチプル(LDMIA)
return OpIndex.INS_THUMB_LDMIA;
case 0x2:
case 0x3:
//分岐命令
int cond = inst.getField(8, 4);
switch (cond) {
case InstructionARM.COND_AL:
//未定義命令
return OpIndex.INS_THUMB_UND;
case InstructionARM.COND_NV:
//swi
return OpIndex.INS_THUMB_SWI;
default:
//b
return OpIndex.INS_THUMB_B1;
}
default:
throw new IllegalArgumentException("Illegal op(Others) bits " +
String.format("op:0x%02x.", op));
}
}
/**
* 分岐命令をデコードします。
*
* subcode = 0b111
*
* @param inst Thumb 命令
* @return 命令の種類
*/
public OpIndex decodeBlBlx(InstructionThumb inst) {
int h = inst.getField(11, 2);
switch (h) {
case 0x0:
//b(無条件分岐)命令
return OpIndex.INS_THUMB_B2;
case 0x1:
case 0x2:
case 0x3:
//Thumb-2 命令
throw new IllegalArgumentException("Thumb-2 instruction detected.");
default:
//異常な値
throw new IllegalArgumentException("Illegal h bits " +
String.format("h:0x%02x.", h));
}
}
}
|
[
"katsuhiro@katsuster.net"
] |
katsuhiro@katsuster.net
|
f7823378ce87f5472c6e8e19e8da4d958c7801e1
|
340d6e8338453eb89c542a699bbee2fe79de26f1
|
/app/src/debug/java/com/ponyvillelive/pvlmobile/ui/ServerEndpointAdapter.java
|
9d14df1563fe1753718a5d8066d3cc7dd5a90beb
|
[
"Apache-2.0"
] |
permissive
|
berwyn/ponyville-live-android
|
3d33d4b82e41ec232abf0223977e281e597a1912
|
9c45d85fe7c6bbd8d021dea0db9a102d51a21146
|
refs/heads/master
| 2021-01-18T21:54:50.361825
| 2016-04-11T06:09:35
| 2016-04-11T06:09:35
| 19,476,405
| 9
| 3
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,264
|
java
|
package com.ponyvillelive.pvlmobile.ui;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ponyvillelive.pvlmobile.prefs.Endpoints;
class ServerEndpointAdapter extends BindableAdapter<Endpoints> {
ServerEndpointAdapter(Context context) {
super(context);
}
@Override public int getCount() {
return Endpoints.values().length;
}
@Override public Endpoints getItem(int position) {
return Endpoints.values()[position];
}
@Override public long getItemId(int position) {
return position;
}
@Override public View newView(LayoutInflater inflater, int position, ViewGroup container) {
return inflater.inflate(android.R.layout.simple_spinner_item, container, false);
}
@Override public void bindView(Endpoints item, int position, View view) {
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText(item.name);
}
@Override
public View newDropDownView(LayoutInflater inflater, int position, ViewGroup container) {
return inflater.inflate(android.R.layout.simple_spinner_dropdown_item, container, false);
}
}
|
[
"berwyn.codeweaver@gmail.com"
] |
berwyn.codeweaver@gmail.com
|
e9848a9b265130b94836fd4b661a5514900bbb3a
|
7240747102e2fe1e867cea0fa8580a31a2490f4f
|
/App/ITalker/app/src/main/java/net/qiujuer/italker/push/App.java
|
6805e245d7d05cc6858bb6b4e249f553d6095972
|
[] |
no_license
|
xxxidream/IMOOCMessager
|
6bca7c7263e8ccfd88d23b0b115262ede7406a7e
|
682d7bd7d99bdea66538b8af6da8f1e9e5c1db0f
|
refs/heads/master
| 2021-06-23T13:04:30.175286
| 2017-09-06T08:32:16
| 2017-09-06T08:32:16
| 100,321,573
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 474
|
java
|
package net.qiujuer.italker.push;
import com.igexin.sdk.PushManager;
import net.qiujuer.italker.common.app.Application;
import net.qiujuer.italker.factory.Factory;
/**
* Created by 16571 on 2017/8/15.
*/
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
//调用Factory进行初始化
Factory.setup();
//推送进行初始化
PushManager.getInstance().initialize(this);
}
}
|
[
"1657140647@qq.com"
] |
1657140647@qq.com
|
9f7ce789a3972cb53e3c8ccee82150ca4a3959d4
|
97d78a90429cfa444ef5d1bafe4c9a4dfdd7cc2d
|
/src/servlet/InitServlet.java
|
de7ad7adba7b9dcee50e1df297cd00f75a743f99
|
[] |
no_license
|
sun1752709589/sopan
|
79477aa9ef892c9b4c8d501b1f2ac7ad46a58af7
|
8ceef48a10de62301c1f4b3d2d5cff5d7bbeff3d
|
refs/heads/master
| 2020-04-23T22:15:26.839422
| 2015-06-29T02:26:44
| 2015-06-29T02:26:44
| 38,223,508
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,159
|
java
|
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class InitServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String key = request.getParameter("key");
String sotype=request.getParameter("sotype");
//String first = request.getParameter("first");
HttpSession session = request.getSession(true);
session.setAttribute("key", key);
session.setAttribute("first", "true");
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String url=basePath+"easysoso/"+sotype+"/index.jsp";
response.sendRedirect(url);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
|
[
"1752709589@qq.com"
] |
1752709589@qq.com
|
d50d554210be0f5af79f438bd1680ee60d3b881f
|
44d7dc2e6ea45df8ba0f48689551d3268ef82e41
|
/app/src/test/java/com/example/shanshan/test/ExampleUnitTest.java
|
3636f89a5222a7042c7717699325075e831b5e37
|
[] |
no_license
|
riyouxi/abc_test
|
ec5677f67d8e017cace9513a3a0b178ceaf2acfd
|
8da8298e0064a03ea8fa1ea51abfdb0ed196ea6a
|
refs/heads/master
| 2020-07-03T03:13:39.736056
| 2016-12-23T14:32:28
| 2016-12-23T14:32:28
| 74,201,896
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 403
|
java
|
package com.example.shanshan.test;
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() throws Exception {
assertEquals(4, 2 + 2);
}
}
|
[
"lw504540"
] |
lw504540
|
36f88516724950f37f3741d72a42d8a5513ef198
|
554dc416b64436edeb4fbdd4e246a5bcab7bc665
|
/hb-eager-vs-lazy-demo/src/com/moribenjamin/hibernate/demo/CreateCoursesDemo.java
|
4b74b3602f30866ccc75b822974ff8b922b510a9
|
[] |
no_license
|
moribenjamin/Hibernate-Mapping
|
82f3b0d1bd023f1eb34bcc4514440374df414c47
|
215be5c91f6cfa037e2eaf4587d80743d6dc049b
|
refs/heads/master
| 2020-06-21T14:42:14.448288
| 2019-07-18T00:58:19
| 2019-07-18T00:58:19
| 197,483,442
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,545
|
java
|
package com.moribenjamin.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.moribenjamin.hibernate.demo.entity.Course;
import com.moribenjamin.hibernate.demo.entity.Instructor;
import com.moribenjamin.hibernate.demo.entity.InstructorDetail;
public class CreateCoursesDemo {
public static void main(String[] args) {
//create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Instructor.class)
.addAnnotatedClass(InstructorDetail.class)
.addAnnotatedClass(Course.class)
.buildSessionFactory();
//create session
Session session = factory.getCurrentSession();
//use the session object to save Java object
try {
//start a transaction
session.beginTransaction();
//get the instructor from db
int theId = 1;
Instructor tempInstructor = session.get(Instructor.class, theId);
//Create some Courses
Course tempCourse1 = new Course("Break Dancing 101");
Course tempCourse2 = new Course("The Ultimate Camping Course");
//saver the courses
tempInstructor.add(tempCourse1);
tempInstructor.add(tempCourse2);
//saver the courses
session.save(tempCourse1);
session.save(tempCourse2);
//commit transaction
session.getTransaction().commit();
System.out.println("Done!");
} finally {
//add clean up code
session.close();
factory.close();
}
}
}
|
[
"noreply@github.com"
] |
noreply@github.com
|
551989b310a93be7c2a3a68d3f502f143b7cb324
|
68a288425fa0c9b8f19fcde1fa7a0880bbfeec88
|
/app/src/main/java/com/example/medicine/Database.java
|
a02c34d925a04589fb4bfbac0b6ba492add484cb
|
[] |
no_license
|
nhthuc/Medicine
|
5b1b473116f53a71aa77964c56442c105502dbb7
|
68a0675da632625e7a4c8b9930476d65657f5a05
|
refs/heads/master
| 2020-07-06T02:02:59.393779
| 2019-10-10T01:50:06
| 2019-10-10T01:50:06
| 202,853,739
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 859
|
java
|
package com.example.medicine;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Database extends SQLiteOpenHelper {
public Database(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public void QueryData(String sql){
SQLiteDatabase database = getWritableDatabase();
database.execSQL(sql);
}
public Cursor GetData(String sql){
SQLiteDatabase database = getReadableDatabase();
return database.rawQuery(sql, null);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
|
[
"nhthuc25@gmail.com"
] |
nhthuc25@gmail.com
|
7c27c76dd3f6b1d923068ec8aebb030fc2925712
|
17766619a8167bce832e243c77a1429d5f48b9ab
|
/RoD/src/com/rodnyroa/tienda_online_nativo/DetalleProductoActivity.java
|
f16c09428ff33d2130d1cf54d93054021faf0161
|
[] |
no_license
|
rodnyroa/RoD
|
e4f4571f79f4b666788cd28213642cd84361cf8c
|
ca2436670eadcbe3be156e1f97e466c9f049a27c
|
refs/heads/master
| 2021-01-13T14:04:55.813786
| 2014-07-21T19:03:36
| 2014-07-21T19:03:36
| null | 0
| 0
| null | null | null | null |
WINDOWS-1250
|
Java
| false
| false
| 6,852
|
java
|
package com.rodnyroa.tienda_online_nativo;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.rodnyroa.tienda_online_nativo.adapter.GridLayoutPreviewImagesAdapter;
import com.rodnyroa.tienda_online_nativo.handlerrequest.HandlerRequestHttp;
import com.rodnyroa.tienda_online_nativo.model.Response;
import com.rodnyroa.tienda_online_nativo.model.RowProducto;
import com.rodnyroa.tienda_online_nativo.parserjson.ParserJsonListadoProductos;
public class DetalleProductoActivity extends Activity implements
OnCreateContextMenuListener {
// http://tech.leolink.net/2013/02/create-simple-infinite-carousel-in.html
RowProducto producto;
GridView gridLayoutMsg;
TextView tvMainText, tvDescription, tvAmount;
String idUser, token;
Button btnNegociar;
ProgressDialog pd;
Response response;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detalle_producto);
pd = new ProgressDialog(DetalleProductoActivity.this);
pd.setTitle("Processing..");
pd.setMessage("Please wait..");
pd.setCancelable(false);
pd.setIndeterminate(true);
producto = (RowProducto) getIntent().getSerializableExtra("Producto");
Log.i("MainText:", producto.getMainText() + "");
Log.i("Cantidad Img:", producto.getImg().size() + "");
idUser = this.getPreferencesByKey("idUser");
gridLayoutMsg = (GridView) this.findViewById(R.id.gridView1);
tvMainText = (TextView) this.findViewById(R.id.tvMainText);
tvAmount = (TextView) this.findViewById(R.id.tvAmount);
tvDescription = (TextView) this.findViewById(R.id.tvDescription);
btnNegociar = (Button) this.findViewById(R.id.btnNegociar);
token = this.getPreferencesByKey("token");
tvMainText.setText(producto.getMainText());
tvAmount.setText(producto.getAmount());
tvDescription.setText(producto.getDescription());
gridLayoutMsg.setAdapter(new GridLayoutPreviewImagesAdapter(
getApplicationContext(), producto.getImg()));
Log.i("idUser:", idUser + "");
Log.i("idUser Producto:", producto.getUser() + "");
if(idUser==null){
idUser=producto.getUser();
}
if (idUser.equalsIgnoreCase(producto.getUser())) {
btnNegociar.setVisibility(View.GONE);
}
btnNegociar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Intent i = new Intent(getApplicationContext(),
// NegociarActivity.class);
// i.putExtra("IdProducto", producto.getId());
// startActivity(i);
// finish();
Log.i("token:", token + "");
Log.i("idProducto:", producto.getId() + "");
String[] data = { token, producto.getId() };
if(!haveInternet(getApplicationContext())){
showMessage("Por favor verifica tu conexión a internet.");
return;
}
new GetChat().execute(data);
}
});
}
private class GetChat extends AsyncTask<String, Void, Void> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.show();
}
@Override
protected Void doInBackground(String... arg0) {
// Creating service handler class instance
HandlerRequestHttp sh = new HandlerRequestHttp();
String urlChat = getResources().getString(R.urls.url_base)
+ getResources().getString(R.urls.url_get_chat);
// ANADIR PARAMETROS
List<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("token", arg0[0]));
data.add(new BasicNameValuePair("producto", arg0[1]));
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(urlChat,
HandlerRequestHttp.POST, data);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
ParserJsonListadoProductos parser = new ParserJsonListadoProductos(
jsonStr);
response = parser.getResponse();
Log.d("Response: ", "> " + response.getResponse());
Log.d("Response: ", "Token> " + response.getToken());
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Sin datos",
Toast.LENGTH_SHORT).show();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (response.getToken() != null) {
savePreferences("token", response.getToken());
Intent i = new Intent(DetalleProductoActivity.this,
NegociarActivity.class);
i.putExtra("Messages", response.getMessages());
i.putExtra("IdProducto", producto.getId());
startActivity(i);
finish();
}
pd.dismiss();
}
}
private String getPreferencesByKey(String key) {
SharedPreferences sharedPreferences = this.getSharedPreferences(
"MyPreferences", Context.MODE_PRIVATE);
return sharedPreferences.getString(key, null);
}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = this.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detalle_producto, menu);
return true;
}
public static boolean haveInternet(Context ctx) {
NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return false;
}
return true;
}
private void showMessage(String message) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
}
}
|
[
"RodnyAlberto@rod-pc"
] |
RodnyAlberto@rod-pc
|
3f6c7857231cbce9da33b8114e5ef4dcb5a25228
|
e44759c6e645b4d024e652ab050e7ed7df74eba3
|
/src/org/ace/insurance/system/common/district/service/interfaces/IDistrictService.java
|
530e66bf979b775699b7dfe77e605f6f018ca88d
|
[] |
no_license
|
LifeTeam-TAT/MI-Core
|
5f779870b1328c23b192668308ee25c532ab6280
|
8c5c4466da13c7a8bc61df12a804f840417e2513
|
refs/heads/master
| 2023-04-04T13:36:11.616392
| 2021-04-02T14:43:34
| 2021-04-02T14:43:34
| 354,033,545
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,158
|
java
|
/***************************************************************************************
* @author YYK
* @Date 2016-May-6
* @Version 1.0
* @Purpose This interface serves as the Service Layer to manipulate the <code>District</code> object.
*
*
***************************************************************************************/
package org.ace.insurance.system.common.district.service.interfaces;
import java.util.List;
import org.ace.insurance.system.common.district.DIS001;
import org.ace.insurance.system.common.district.District;
import org.ace.insurance.system.common.district.DistrictCriteria;
public interface IDistrictService {
/**
* This method serves as the service method to insert district instance into
* database.
*
* @param District
*/
public void addNewDistrict(District District);
/**
* This method serves as the service method to update district instance into
* database.
*
* @param District
*/
public void updateDistrict(District District);
/**
* This method serves as the service method to delete district instance into
* database.
*
* @param District
*/
public void deleteDistrict(District District);
/**
* This method serves as the service method to find district instance by ID
* from database.
*
* @param id
* @return District
*/
public District findDistrictById(String id);
/**
* This method serves as the service method to find all district instances
* from database.
*
* @return List<District>
*/
public List<District> findAllDistrict();
/**
* This method serves as the service method to find all District001
* instances by criteria from database.
*
* @return List<District001>
*/
public List<DIS001> findByCriteria(DistrictCriteria criteria);
/**
* This method serves as the service method to find all District001
* instances from database.
*
* @return List<District001>
*/
public List<DIS001> findAll_DIS001();
/**
* This method serves as the service method to delete district instances by
* id from database.
*
* @return List<District001>
*/
public void deleteDistrictById(String districtId);
}
|
[
"lifeteam.tat@gmail.com"
] |
lifeteam.tat@gmail.com
|
c4edfaf44fc56ff17d98e09f0bb0cb4d3d1a97fa
|
e3a6d5e642bcb27d06883de0e00120583555bafa
|
/src/main/java/com/feng/splitdbtb/TbAlgorithm.java
|
df81ddfec4b6c0187788b66519017d3afe30438f
|
[] |
no_license
|
809026027/springDemo
|
eb87d153f924e6034d0dd28115bc0721a207a259
|
9572b0cdd687bb0fbe69009a172c1a012043f416
|
refs/heads/master
| 2021-01-19T13:12:15.785167
| 2017-04-15T12:10:54
| 2017-04-15T12:10:54
| 88,071,431
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,041
|
java
|
package com.feng.splitdbtb;
import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.SingleKeyTableShardingAlgorithm;
import java.util.Collection;
public class TbAlgorithm implements SingleKeyTableShardingAlgorithm<Integer> {
@Override
public String doEqualSharding(Collection<String> availableTargetNames, ShardingValue<Integer> shardingValue) {
int id = shardingValue.getValue();
int index = id % 2;
for (String each : availableTargetNames) {
if (each.endsWith(index + "")) {
return each;
}
}
throw new UnsupportedOperationException();
}
@Override
public Collection<String> doInSharding(Collection<String> availableTargetNames, ShardingValue<Integer> shardingValue) {
return null;
}
@Override
public Collection<String> doBetweenSharding(Collection<String> availableTargetNames, ShardingValue<Integer> shardingValue) {
return null;
}
}
|
[
"songfeng_123@126.com"
] |
songfeng_123@126.com
|
262d1a0876bcbc5efbfe10316214008815e91576
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/15/15_039663230cff90535f2aa84c45c75fcd5e9deb00/MainActivity/15_039663230cff90535f2aa84c45c75fcd5e9deb00_MainActivity_s.java
|
a70e558bbb01d36dd248fd640154f101ac095461
|
[] |
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
| 53,902
|
java
|
/*******************************************************************************
* Mirakel is an Android App for managing your ToDo-Lists
*
* Copyright (c) 2013-2014 Anatolij Zelenin, Georg Semmler.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package de.azapps.mirakel.main_activity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Stack;
import java.util.Vector;
import sheetrock.panda.changelog.ChangeLog;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.speech.RecognizerIntent;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import de.azapps.ilovefs.ILoveFS;
import de.azapps.mirakel.DefinitionsHelper;
import de.azapps.mirakel.DefinitionsHelper.NoSuchListException;
import de.azapps.mirakel.adapter.PagerAdapter;
import de.azapps.mirakel.helper.BuildHelper;
import de.azapps.mirakel.helper.Helpers;
import de.azapps.mirakel.helper.ListDialogHelpers;
import de.azapps.mirakel.helper.MirakelCommonPreferences;
import de.azapps.mirakel.helper.MirakelModelPreferences;
import de.azapps.mirakel.helper.SharingHelper;
import de.azapps.mirakel.helper.TaskDialogHelpers;
import de.azapps.mirakel.helper.TaskHelper;
import de.azapps.mirakel.helper.UndoHistory;
import de.azapps.mirakel.main_activity.list_fragment.ListFragment;
import de.azapps.mirakel.main_activity.task_fragment.TaskFragment;
import de.azapps.mirakel.main_activity.task_fragment.TaskFragmentV14;
import de.azapps.mirakel.main_activity.task_fragment.TaskFragmentV8;
import de.azapps.mirakel.main_activity.tasks_fragment.TasksFragment;
import de.azapps.mirakel.model.account.AccountMirakel;
import de.azapps.mirakel.model.account.AccountMirakel.ACCOUNT_TYPES;
import de.azapps.mirakel.model.file.FileMirakel;
import de.azapps.mirakel.model.list.ListMirakel;
import de.azapps.mirakel.model.list.SearchList;
import de.azapps.mirakel.model.list.SpecialList;
import de.azapps.mirakel.model.semantic.Semantic;
import de.azapps.mirakel.model.task.Task;
import de.azapps.mirakel.reminders.ReminderAlarm;
import de.azapps.mirakel.services.NotificationService;
import de.azapps.mirakel.static_activities.DonationsActivity;
import de.azapps.mirakel.static_activities.SettingsActivity;
import de.azapps.mirakel.static_activities.SplashScreenActivity;
import de.azapps.mirakel.widget.MainWidgetProvider;
import de.azapps.mirakelandroid.R;
import de.azapps.tools.FileUtils;
import de.azapps.tools.Log;
/**
* This is our main activity. Here happens nearly everything.
*
* @author az
*/
public class MainActivity extends ActionBarActivity implements
ViewPager.OnPageChangeListener {
private static boolean isRTL;
// Intent variables
public static final int LEFT_FRAGMENT = 0, RIGHT_FRAGMENT = 1;
public static final int RESULT_SPEECH_NAME = 1, RESULT_SPEECH = 3,
RESULT_SETTINGS = 4, RESULT_ADD_FILE = 5, RESULT_CAMERA = 6,
RESULT_ADD_PICTURE = 7;
private static final String TAG = "MainActivity";
// TODO We should do this somehow else
public static boolean updateTasksUUID = false;
protected static int getTaskFragmentPosition() {
if (MainActivity.isRTL || MirakelCommonPreferences.isTablet())
return MainActivity.LEFT_FRAGMENT;
return MainActivity.RIGHT_FRAGMENT;
}
public static int getTasksFragmentPosition() {
if (MainActivity.isRTL && !MirakelCommonPreferences.isTablet())
return MainActivity.RIGHT_FRAGMENT;
return MainActivity.LEFT_FRAGMENT;
}
private boolean closeOnBack = false;
protected ListMirakel currentList;
protected int currentPosition;
// State variables
protected Task currentTask;
public boolean darkTheme;
private Uri fileUri;
private final FragmentManager fragmentManager = getSupportFragmentManager();
private final Stack<Task> goBackTo = new Stack<Task>();
// Foo variables (move them out of the MainActivity)
private boolean highlightSelected;
// User interaction variables
private boolean isResumend;
private boolean isTablet;
private List<ListMirakel> lists;
protected DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
protected Menu menu;
private PagerAdapter mPagerAdapter;
protected MainActivityBroadcastReceiver mSyncReciver;
// Layout variables
ViewPager mViewPager;
private String newTaskContent, newTaskSubject;
private View oldClickedList = null;
protected View oldClickedTask = null;
private boolean showNavDrawer = false;
private boolean skipSwipe;
private Intent startIntent;
protected TaskFragment taskFragment;
private void addFilesForTask(final Task t, final Intent intent) {
final String action = intent.getAction();
final String type = intent.getType();
this.currentPosition = getTaskFragmentPosition();
if (Intent.ACTION_SEND.equals(action) && type != null) {
final Uri uri = (Uri) intent
.getParcelableExtra(Intent.EXTRA_STREAM);
t.addFile(this, FileUtils.getPathFromUri(uri, this));
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
final ArrayList<Uri> imageUris = intent
.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
for (final Uri uri : imageUris) {
t.addFile(this, FileUtils.getPathFromUri(uri, this));
}
}
}
private void addTaskFromSharing(final ListMirakel list) {
if (this.newTaskSubject == null)
return;
final Task task = Semantic.createTask(this.newTaskSubject, list, true,
this);
task.setContent(this.newTaskContent == null ? "" : this.newTaskContent);
task.safeSave();
setCurrentTask(task);
if(this.startIntent!=null){
addFilesForTask(task, this.startIntent);
}
setCurrentList(task.getList());
setCurrentTask(task, true);
}
private void clearAllHighlights() {
if (this.oldClickedList != null) {
this.oldClickedList.setSelected(false);
this.oldClickedList.setBackgroundColor(0x00000000);
}
if (this.oldClickedTask != null) {
this.oldClickedTask.setSelected(false);
this.oldClickedTask.setBackgroundColor(0x00000000);
}
clearHighlighted();
}
private void clearHighlighted() {
if (this.oldClickedTask == null)
return;
try {
final ListView view = (ListView) getTasksFragment()
.getFragmentView().findViewById(R.id.tasks_list);
final int pos_old = view.getPositionForView(this.oldClickedTask);
if (pos_old != -1) {
view.getChildAt(pos_old).setBackgroundColor(0x00000000);
} else {
Log.wtf(MainActivity.TAG, "View not found");
}
} catch (final Exception e) {
Log.wtf(MainActivity.TAG, "Listview not found");
Log.e(MainActivity.TAG, Log.getStackTraceString(e));
}
}
private void draw() {
setContentView(R.layout.activity_main);
this.mPagerAdapter = null;
// Show ChangeLog
final ChangeLog cl = new ChangeLog(this);
if (cl.firstRun()) {
cl.getLogDialog().show();
this.showNavDrawer = true;
}
// currentList=preferences.getInt("s", defValue)
this.skipSwipe = false;
setupLayout();
this.isResumend = false;
}
private void forceRebuildLayout(final boolean tabletLocal) {
this.isTablet = tabletLocal;
this.mPagerAdapter = null;
this.isResumend = false;
this.skipSwipe = true;
setupLayout();
this.skipSwipe = true;
if(getTaskFragment()!=null){
getTaskFragment().update(MainActivity.this.currentTask);
}
loadMenu(this.currentPosition, false, false);
}
/**
* Return the currently showed List
*
* @return
*/
public ListMirakel getCurrentList() {
if (this.currentList == null) {
this.currentList = SpecialList.firstSpecialSafe(this);
}
return this.currentList;
}
public int getCurrentPosition() {
return this.currentPosition;
}
/**
* Return the currently showed tasks
*
* @return
*/
public Task getCurrentTask() {
this.currentTask = this.currentList.getFirstTask();
if (this.currentTask == null) {
this.currentTask = Task.getDummy(getApplicationContext());
}
return this.currentTask;
}
/**
* Returns the ListFragment
*
* @return
*/
public ListFragment getListFragment() {
return (ListFragment) this.fragmentManager
.findFragmentById(R.id.navigate_fragment);
}
public TaskFragment getTaskFragment() {
checkPageAdapter();
if (MirakelCommonPreferences.isTablet()){
//warning can be null
return this.taskFragment;
}
Fragment f = this.mPagerAdapter
.getItem(getTaskFragmentPosition());
if(f==null){
forceRebuildLayout(MirakelCommonPreferences.isTablet());
f = this.mPagerAdapter
.getItem(getTaskFragmentPosition());
if(f==null){
Log.wtf(TAG, "no taskfragment found");
//Helpers.restartApp(this);
return null;
}
}
try {
return (TaskFragment) f;
} catch (ClassCastException e) {
Log.wtf(TAG, "cannot cast fragment");
forceRebuildLayout(MirakelCommonPreferences.isTablet());
return (TaskFragment)this.mPagerAdapter
.getItem(getTaskFragmentPosition());
}
}
private void checkPageAdapter() {
if (this.mPagerAdapter == null){
forceRebuildLayout(MirakelCommonPreferences.isTablet());
if(this.mPagerAdapter==null){
//something terrible happened
Log.wtf(TAG, "pageadapter after init null");
//Helpers.restartApp(this);
}
}
}
public TasksFragment getTasksFragment() {
checkPageAdapter();
Fragment f = this.mPagerAdapter.getItem(MainActivity
.getTasksFragmentPosition());
if(f==null){
forceRebuildLayout(MirakelCommonPreferences.isTablet());
f = this.mPagerAdapter
.getItem(getTasksFragmentPosition());
if(f==null){
Log.wtf(TAG, "no taskfragment found");
//Helpers.restartApp(this);
return null;
}
}
try {
return (TasksFragment) f;
} catch (ClassCastException e) {
Log.wtf(TAG, "cannot cast fragment");
forceRebuildLayout(MirakelCommonPreferences.isTablet());
return getTasksFragment();
}
}
public void handleDestroyList(final List<ListMirakel> lists) {
String names = lists.get(0).getName();
for (int i = 1; i < lists.size(); i++) {
names += ", " + lists.get(i).getName();
}
new AlertDialog.Builder(this)
.setTitle(
getResources().getQuantityString(R.plurals.list_delete,
lists.size()))
.setMessage(this.getString(R.string.list_delete_content, names))
.setPositiveButton(this.getString(android.R.string.yes),
new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog,
final int which) {
new Thread(new Runnable() {
@Override
public void run() {
for (final ListMirakel list : lists) {
list.destroy();
if (getCurrentList().getId() == list
.getId()) {
setCurrentList(SpecialList
.firstSpecial());
}
}
if (getListFragment() != null) {
// getListFragment().getAdapter().changeData(
// ListMirakel.all());
// getListFragment().getAdapter()
// .notifyDataSetChanged();
getListFragment().update();
}
}
}).start();
}
})
.setNegativeButton(this.getString(android.R.string.no), null)
.show();
}
/**
* Handle the actions after clicking on a destroy-list button
*
* @param list
*/
public void handleDestroyList(final ListMirakel list) {
final List<ListMirakel> l = new ArrayList<ListMirakel>();
l.add(list);
handleDestroyList(l);
}
public void handleDestroyTask(final List<Task> tasks) {
if (tasks == null)
return;
final MainActivity main = this;
// This must then be a bug in a ROM
if (tasks.size() == 0 || tasks.get(0) == null)
return;
String names = tasks.get(0).getName();
for (int i = 1; i < tasks.size(); i++) {
names += ", " + tasks.get(i).getName();
}
new AlertDialog.Builder(this)
.setTitle(
getResources().getQuantityString(R.plurals.task_delete,
tasks.size()))
.setMessage(this.getString(R.string.task_delete_content, names))
.setPositiveButton(this.getString(android.R.string.yes),
new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog,
final int which) {
for (final Task t : tasks) {
t.destroy();
}
setCurrentList(MainActivity.this.currentList);
ReminderAlarm.updateAlarms(main);
updateShare();
}
})
.setNegativeButton(this.getString(android.R.string.no), null)
.show();
getTasksFragment().updateList(false);
}
/**
* Handle the actions after clicking on a destroy-task button
*
* @param task
*/
public void handleDestroyTask(final Task task) {
final List<Task> t = new ArrayList<Task>();
t.add(task);
handleDestroyTask(t);
}
public void handleMoveTask(final List<Task> tasks) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.dialog_move);
final List<CharSequence> items = new ArrayList<CharSequence>();
final List<Integer> list_ids = new ArrayList<Integer>();
int currentItem = 0, i = 0;
for (final ListMirakel list : this.lists) {
if (list.getId() > 0) {
items.add(list.getName());
if (tasks.get(0).getList().getId() == list.getId()
&& tasks.size() == 1) {
currentItem = i;
}
list_ids.add(list.getId());
++i;
}
}
builder.setSingleChoiceItems(
items.toArray(new CharSequence[items.size()]), currentItem,
new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog,
final int item) {
for (final Task t : tasks) {
t.setList(ListMirakel.getList(list_ids.get(item)),
true);
t.safeSave();
}
/*
* There are 3 possibilities how to handle the post-move
* of a task: 1: update the currentList to the List, the
* task was moved to setCurrentList(task.getList()); 2:
* update the tasksView but not update the taskView:
* getTasksFragment().updateList();
* getTasksFragment().update(); 3: Set the currentList
* to the old List
*/
if (MainActivity.this.currentPosition == getTaskFragmentPosition()) {
final Task task = tasks.get(0);
if (task == null) {
// What the hell?
Log.wtf(MainActivity.TAG, "Task vanished");
} else {
setCurrentList(task.getList());
setCurrentTask(task, true);
}
} else {
setCurrentList(getCurrentList());
getListFragment().update();
}
if (dialog != null) {
dialog.dismiss();
}
}
}).show();
}
/**
* Handle the actions after clicking on a move task button
*
* @param tasks
*/
public void handleMoveTask(final Task task) {
final List<Task> t = new ArrayList<Task>();
t.add(task);
handleMoveTask(t);
}
private int handleTaskFragmentMenu() {
if (getSupportActionBar() != null && this.currentTask != null
&& this.mViewPager != null) {
this.mViewPager.post(new Runnable() {
@Override
public void run() {
getTaskFragment().update(MainActivity.this.currentTask);
if (MainActivity.this.currentTask == null) {
MainActivity.this.currentTask = Task
.getDummy(MainActivity.this);
}
getSupportActionBar().setTitle(
MainActivity.this.currentTask.getName());
}
});
}
return R.menu.activity_task;
}
private int handleTasksFragmentMenu() {
int newmenu;
getListFragment().enableDrop(false);
// if (getTaskFragment() != null && getTaskFragment().adapter !=
// null&&this.mViewPager!=null) {
// this.mViewPager.post(new Runnable() {
//
// @Override
// public void run() {
// getTaskFragment().adapter.setEditContent(false);
//
// }
// });
//
// }
if (this.currentList == null)
return -1;
if (!MirakelCommonPreferences.isTablet()) {
newmenu = R.menu.tasks;
} else {
newmenu = R.menu.tablet_right;
}
if (this.mViewPager != null) {
this.mViewPager.post(new Runnable() {
@Override
public void run() {
getSupportActionBar().setTitle(
MainActivity.this.currentList.getName());
}
});
}
return newmenu;
}
void highlightCurrentTask(final Task currentTask, final boolean multiselect) {
if (getTaskFragment() == null || getTasksFragment() == null
|| getTasksFragment().getAdapter() == null
|| currentTask == null)
return;
Log.v(MainActivity.TAG, currentTask.getName());
final View currentView = getTasksFragment().getAdapter()
.getViewForTask(currentTask) == null ? getTasksFragment()
.getListView().getChildAt(0) : getTasksFragment().getAdapter()
.getViewForTask(currentTask);
if (currentView != null && this.highlightSelected && !multiselect) {
currentView.post(new Runnable() {
@Override
public void run() {
if (MainActivity.this.oldClickedTask != null) {
MainActivity.this.oldClickedTask.setSelected(false);
MainActivity.this.oldClickedTask
.setBackgroundColor(0x00000000);
}
currentView
.setBackgroundColor(getResources()
.getColor(
MainActivity.this.darkTheme ? R.color.highlighted_text_holo_dark
: R.color.highlighted_text_holo_light));
MainActivity.this.oldClickedTask = currentView;
}
});
}
}
/**
* Initialize ViewPager
*/
@SuppressLint("NewApi")
private void intializeFragments() {
/*
* Setup NavigationDrawer
*/
// listFragment = new ListFragment();
getListFragment().setActivity(this);
// fragments.add(listFragment);
final List<Fragment> fragments = new Vector<Fragment>();
this.mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
this.mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
this.mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.list_title, /* "open drawer" description */
R.string.list_title /* "close drawer" description */
) {
@Override
public void onDrawerClosed(final View view) {
loadMenu(MainActivity.this.currentPosition);
if (getListFragment() != null) {
getListFragment().closeNavDrawer();
}
}
@Override
public void onDrawerOpened(final View drawerView) {
loadMenu(-1, false, false);
getListFragment().refresh();
}
};
// Set the drawer toggle as the DrawerListener
this.mDrawerLayout.setDrawerListener(this.mDrawerToggle);
if (this.showNavDrawer) {
this.mDrawerLayout.openDrawer(DefinitionsHelper.GRAVITY_LEFT);
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
/*
* Setup other Fragments
*/
final TasksFragment tasksFragment = new TasksFragment();
tasksFragment.setActivity(this);
fragments.add(tasksFragment);
if (!MirakelCommonPreferences.isTablet()) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
fragments.add(new TaskFragmentV8());
} else {
fragments.add(new TaskFragmentV14());
}
}
if (MainActivity.isRTL && !MirakelCommonPreferences.isTablet()) {
final Fragment[] fragmentsLocal = new Fragment[fragments.size()];
for (int i = 0; i < fragments.size(); i++) {
fragmentsLocal[fragmentsLocal.length - 1 - i] = fragments
.get(i);
}
this.mPagerAdapter = new PagerAdapter(this.fragmentManager,
Arrays.asList(fragmentsLocal));
} else {
this.mPagerAdapter = new PagerAdapter(this.fragmentManager,
fragments);
}
//
if (this.mViewPager == null) {
this.mViewPager = (ViewPager) super.findViewById(R.id.viewpager);
}
if (this.mViewPager == null) {
Log.wtf(MainActivity.TAG, "viewpager null");
return;
}
this.mViewPager.setOffscreenPageLimit(MirakelCommonPreferences
.isTablet() ? 1 : 2);
this.mViewPager.setAdapter(this.mPagerAdapter);
this.mViewPager.setOnPageChangeListener(this);
this.mViewPager.setOffscreenPageLimit(MirakelCommonPreferences
.isTablet() ? 1 : 2);
}
public void loadMenu(final int position) {
loadMenu(position, true, false);
}
public void loadMenu(int position, boolean setPosition,
final boolean fromShare) {
if (getTaskFragment() != null && getTaskFragment().getView() != null) {
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getTaskFragment().getView()
.getWindowToken(), 0);
}
if (this.menu == null)
return;
final int newmenu;
if (this.isTablet && position != -1) {
newmenu = R.menu.tablet_right;
} else {
switch (position) {
case -1:
newmenu = R.menu.activity_list;
getSupportActionBar().setTitle(getString(R.string.list_title));
break;
case RIGHT_FRAGMENT:
newmenu = isRTL ? handleTasksFragmentMenu()
: handleTaskFragmentMenu();
break;
case LEFT_FRAGMENT:
newmenu = isRTL ? handleTaskFragmentMenu()
: handleTasksFragmentMenu();
break;
default:
Toast.makeText(getApplicationContext(),
"Where are the dragons?", Toast.LENGTH_LONG).show();
return;
}
}
if (setPosition) {
this.currentPosition = position;
}
// Configure to use the desired menu
if (newmenu == -1)
return;
if (this.mViewPager != null) {
this.mViewPager.post(new Runnable() {
@Override
public void run() {
MainActivity.this.menu.clear();
MenuInflater inflater = getMenuInflater();
inflater.inflate(newmenu, MainActivity.this.menu);
if (MainActivity.this.menu.findItem(R.id.menu_sync_now) != null) {
MainActivity.this.menu.findItem(R.id.menu_sync_now)
.setVisible(MirakelModelPreferences.useSync());
}
if (MainActivity.this.menu.findItem(R.id.menu_kill_button) != null) {
MainActivity.this.menu.findItem(R.id.menu_kill_button)
.setVisible(
MirakelCommonPreferences
.showKillButton());
}
if (MainActivity.this.menu.findItem(R.id.menu_contact) != null) {
MainActivity.this.menu.findItem(R.id.menu_contact)
.setVisible(BuildHelper.isBeta());
}
if (!fromShare) {
updateShare();
}
}
});
}
}
public void lockDrawer() {
this.mDrawerLayout
.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
}
@Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent intent) {
final boolean isOk = resultCode == Activity.RESULT_OK;
Log.v(MainActivity.TAG, "Result:" + requestCode);
switch (requestCode) {
case RESULT_SPEECH_NAME:
if (intent != null) {
final ArrayList<String> text = intent
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
((EditText) findViewById(R.id.edit_name)).setText(text.get(0));
}
break;
case RESULT_SPEECH:
if (intent != null) {
final ArrayList<String> text = intent
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
((EditText) getTasksFragment().getFragmentView().findViewById(
R.id.tasks_new)).setText(text.get(0));
}
break;
case RESULT_ADD_FILE:
if (intent != null) {
Log.d(TAG, "taskname " + this.currentTask.getName());
final String file_path = FileUtils.getPathFromUri(
intent.getData(), this);
if (FileMirakel.newFile(this, this.currentTask, file_path) == null) {
Toast.makeText(this, getString(R.string.file_vanished),
Toast.LENGTH_SHORT).show();
} else {
getTaskFragment().update(this.currentTask);
}
}
break;
case RESULT_SETTINGS:
getListFragment().update();
getTaskFragment().updateLayout();
this.highlightSelected = MirakelCommonPreferences
.highlightSelected();
if (!this.highlightSelected
&& (this.oldClickedList != null || this.oldClickedTask == null)) {
clearAllHighlights();
}
if (this.darkTheme != MirakelCommonPreferences.isDark()) {
finish();
if (this.startIntent == null) {
this.startIntent = new Intent(MainActivity.this,
MainActivity.class);
this.startIntent.setAction(DefinitionsHelper.SHOW_LISTS);
Log.wtf(MainActivity.TAG,
"startIntent is null by switching theme");
}
startActivity(this.startIntent);
}
if (this.isTablet != MirakelCommonPreferences.isTablet()) {
forceRebuildLayout(MirakelCommonPreferences.isTablet());
} else {
loadMenu(this.mViewPager.getCurrentItem());
}
if (getTasksFragment() != null) {
getTasksFragment().updateButtons();
}
if (getTaskFragment() != null) {
getTaskFragment().update(this.currentTask);
}
return;
case RESULT_CAMERA:
case RESULT_ADD_PICTURE:
if (isOk) {
Task task;
if (requestCode == MainActivity.RESULT_ADD_PICTURE) {
task = this.currentTask;
} else {
task = Semantic.createTask(
MirakelCommonPreferences.getPhotoDefaultTitle(),
this.currentList, false, this);
task.safeSave();
}
task.addFile(this, FileUtils.getPathFromUri(this.fileUri, this));
getTaskFragment().update(task);
}
break;
default:
Log.w(MainActivity.TAG, "unknown activity result");
break;
}
}
@Override
public void onBackPressed() {
// getTaskFragment().cancelEditing();
if (this.goBackTo.size() > 0
&& this.currentPosition == getTaskFragmentPosition()) {
final Task goBack = this.goBackTo.pop();
setCurrentList(goBack.getList(), null, false, false);
setCurrentTask(goBack, false, false);
return;
}
if (this.closeOnBack) {
super.onBackPressed();
return;
}
switch (this.mViewPager.getCurrentItem()) {
/*
* case TASKS_FRAGMENT: mDrawerLayout.openDrawer(Gravity.LEFT); break;
*/
case LEFT_FRAGMENT:
if (MainActivity.isRTL) {
this.mViewPager.setCurrentItem(MainActivity
.getTasksFragmentPosition());
return;
}
break;
case RIGHT_FRAGMENT:
if (!MainActivity.isRTL) {
this.mViewPager.setCurrentItem(MainActivity
.getTasksFragmentPosition());
return;
}
break;
default:
// Cannot be, do nothing
break;
}
super.onBackPressed();
}
@Override
public void onConfigurationChanged(final Configuration newConfig) {
Locale.setDefault(Helpers.getLocal(this));
super.onConfigurationChanged(newConfig);
final boolean tabletLocal = MirakelCommonPreferences.isTablet();
if (tabletLocal != this.isTablet) {
forceRebuildLayout(tabletLocal);
} else {
getListFragment().setActivity(this);
getTasksFragment().setActivity(this);
this.mDrawerToggle.onConfigurationChanged(newConfig);
}
}
@SuppressLint("NewApi")
@Override
protected void onCreate(final Bundle savedInstanceState) {
this.darkTheme = MirakelCommonPreferences.isDark();
if (this.darkTheme) {
setTheme(android.support.v7.appcompat.R.style.Theme_AppCompat);
} else {
setTheme(android.support.v7.appcompat.R.style.Theme_AppCompat_Light_DarkActionBar);
}
Locale.setDefault(Helpers.getLocal(this));
super.onCreate(savedInstanceState);
// Set Alarms
new Thread(new Runnable() {
@Override
public void run() {
ReminderAlarm.updateAlarms(getApplicationContext());
if (!MirakelCommonPreferences.containsHighlightSelected()) {
final SharedPreferences.Editor editor = MirakelCommonPreferences
.getEditor();
editor.putBoolean("highlightSelected",
MainActivity.this.isTablet);
editor.commit();
}
if (!MirakelCommonPreferences.containsStartupAllLists()) {
final SharedPreferences.Editor editor = MirakelCommonPreferences
.getEditor();
editor.putBoolean("startupAllLists", false);
editor.putString("startupList", ""
+ ListMirakel.first().getId());
editor.commit();
}
// We should remove this in the future, nobody uses such old
// versions (hopefully)
if (MainActivity.updateTasksUUID) {
final List<Task> tasks = Task.all();
for (final Task t : tasks) {
t.setUUID(java.util.UUID.randomUUID().toString());
t.safeSave();
}
}
MainActivity.this.mSyncReciver = new MainActivityBroadcastReceiver(
MainActivity.this);
registerReceiver(MainActivity.this.mSyncReciver,
new IntentFilter(DefinitionsHelper.SYNC_FINISHED));
if (DefinitionsHelper.freshInstall) {
String[] lists = getResources().getStringArray(
R.array.demo_lists);
for (String list : lists) {
ListMirakel.newList(list);
}
if (MirakelCommonPreferences.isDemoMode()) {
String[] tasks = getResources().getStringArray(
R.array.demo_tasks);
String[] task_lists = { lists[1], lists[1], lists[0],
lists[2], lists[2], lists[2] };
int[] priorities = { 2, -1, 1, 2, 0, 0 };
int i = 0;
for (String task : tasks) {
Task t = Semantic.createTask(task,
ListMirakel.findByName(task_lists[i]),
true, MainActivity.this);
t.setPriority(priorities[i]);
t.safeSave();
i++;
}
}
}
}
}).run();
this.isTablet = MirakelCommonPreferences.isTablet();
MainActivity.isRTL = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
&& getResources().getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
this.currentPosition = MainActivity.getTasksFragmentPosition();
this.highlightSelected = MirakelCommonPreferences.highlightSelected();
draw();
if (this.mViewPager.getCurrentItem() != this.currentPosition) {
this.mViewPager.postDelayed(new Runnable() {
@Override
public void run() {
MainActivity.this.mViewPager
.setCurrentItem(MainActivity.this.currentPosition);
}
}, 10);
}
setCurrentTask(this.currentTask, false);
ILoveFS ilfs = new ILoveFS(this, "mirakel@azapps.de",
DefinitionsHelper.APK_NAME);
if (ilfs.isILFSDay()) {
ilfs.donateListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this,
DonationsActivity.class);
startActivity(intent);
}
};
ilfs.show();
}
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
updateLists();
getMenuInflater().inflate(R.menu.main, menu);
this.menu = menu;
if (!this.showNavDrawer) {
loadMenu(this.currentPosition, false, false);
} else {
this.showNavDrawer = false;
loadMenu(-1, false, false);
}
return true;
}
@Override
protected void onDestroy() {
try {
unregisterReceiver(this.mSyncReciver);
} catch (Exception e) {
// eat it
}
super.onDestroy();
}
// Fix Intent-behavior
// default is not return new Intent by calling getIntent
@Override
protected void onNewIntent(final Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (this.mDrawerToggle.onOptionsItemSelected(item))
return true;
switch (item.getItemId()) {
case R.id.menu_delete:
handleDestroyTask(this.currentTask);
updateShare();
return true;
case R.id.menu_move:
handleMoveTask(this.currentTask);
return true;
case R.id.list_delete:
handleDestroyList(this.currentList);
return true;
case R.id.task_sorting:
this.currentList = ListDialogHelpers.handleSortBy(this,
this.currentList, new Helpers.ExecInterface() {
@Override
public void exec() {
setCurrentList(MainActivity.this.currentList);
}
}, null);
return true;
case R.id.menu_new_list:
getListFragment().editList(null);
return true;
case R.id.menu_sort_lists:
final boolean t = !item.isChecked();
getListFragment().enableDrop(t);
item.setChecked(t);
return true;
case R.id.menu_settings:
final Intent intent = new Intent(MainActivity.this,
SettingsActivity.class);
startActivityForResult(intent, MainActivity.RESULT_SETTINGS);
break;
case R.id.menu_contact:
Helpers.contact(this);
break;
case R.id.menu_sync_now:
final Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY, true);
// bundle.putBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE,true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
new Thread(new Runnable() {
@SuppressLint("InlinedApi")
@Override
public void run() {
List<AccountMirakel> accounts = AccountMirakel
.getEnabled(true);
for (AccountMirakel a : accounts) {
// davdroid accounts should be there only from
// API>=14...
ContentResolver.requestSync(
a.getAndroidAccount(),
a.getType() == ACCOUNT_TYPES.TASKWARRIOR ? DefinitionsHelper.AUTHORITY_TYP
: CalendarContract.AUTHORITY, bundle);
}
}
}).start();
break;
case R.id.share_task:
SharingHelper.share(this, getCurrentTask());
break;
case R.id.share_list:
SharingHelper.share(this, getCurrentList());
break;
case R.id.search:
onSearchRequested();
break;
case R.id.menu_kill_button:
// Only Close
final Intent killIntent = new Intent(getApplicationContext(),
SplashScreenActivity.class);
killIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
killIntent.setAction(SplashScreenActivity.EXIT);
startActivity(killIntent);
finish();
return false;
case R.id.menu_undo:
UndoHistory.undoLast();
updateCurrentListAndTask();
if (this.currentPosition == getTaskFragmentPosition()) {
setCurrentTask(this.currentTask);
} else if (getListFragment() != null && getTasksFragment() != null
&& getListFragment().getAdapter() != null
&& getTasksFragment().getAdapter() != null) {
getListFragment().getAdapter().changeData(ListMirakel.all());
getListFragment().getAdapter().notifyDataSetChanged();
getTasksFragment().getAdapter().changeData(
getCurrentList().tasks(), getCurrentList().getId());
getTasksFragment().getAdapter().notifyDataSetChanged();
if (!MirakelCommonPreferences.isTablet()
&& this.currentPosition == MainActivity
.getTasksFragmentPosition()) {
setCurrentList(getCurrentList());
}
}
ReminderAlarm.updateAlarms(this);
break;
case R.id.mark_as_subtask:
TaskDialogHelpers.handleSubtask(this, this.currentTask, null, true);
break;
case R.id.menu_task_clone:
try {
final Task newTask = this.currentTask.create();
setCurrentTask(newTask, true);
getListFragment().update();
updatesForTask(newTask);
} catch (final NoSuchListException e) {
Log.wtf(MainActivity.TAG, "List vanished on task cloning");
}
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public void onPageScrolled(final int position, final float positionOffset,
final int positionOffsetPixels) {
if (getTaskFragment() != null
&& getTasksFragment().getAdapter() != null
&& MirakelCommonPreferences.swipeBehavior() && !this.skipSwipe) {
this.skipSwipe = true;
setCurrentTask(getTasksFragment().getAdapter().lastTouched(), false);
}
}
@Override
public void onPageScrollStateChanged(final int state) {
if (this.mViewPager.getCurrentItem() == getTaskFragmentPosition()) {
this.skipSwipe = false;
}
}
@Override
public void onPageSelected(final int position) {
if (getTasksFragment() == null)
return;
getTasksFragment().closeActionMode();
getTaskFragment().closeActionMode();
runOnUiThread(new Runnable() {
@Override
public void run() {
if (MirakelCommonPreferences.lockDrawerInTaskFragment()
&& position == getTaskFragmentPosition()) {
MainActivity.this.mDrawerLayout
.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
} else {
MainActivity.this.mDrawerLayout
.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
}
});
loadMenu(position);
}
@SuppressLint("NewApi")
@Override
protected void onPause() {
if (getTasksFragment() != null) {
getTasksFragment().clearFocus();
}
final Intent intent = new Intent(this, MainWidgetProvider.class);
intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
// Use an array and EXTRA_APPWIDGET_IDS instead of
// AppWidgetManager.EXTRA_APPWIDGET_ID,
// since it seems the onUpdate() is only fired on that:
final Context context = getApplicationContext();
final ComponentName name = new ComponentName(context,
MainWidgetProvider.class);
final int widgets[] = AppWidgetManager.getInstance(context)
.getAppWidgetIds(name);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgets);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
for (final int id : widgets) {
AppWidgetManager.getInstance(this)
.notifyAppWidgetViewDataChanged(id,
R.id.widget_tasks_list);
}
}
sendBroadcast(intent);
TaskDialogHelpers.stopRecording();
super.onPause();
}
@Override
protected void onPostCreate(final Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
this.mDrawerToggle.syncState();
}
@Override
protected void onResume() {
super.onResume();
if (this.isResumend) {
setupLayout();
}
this.isResumend = true;
// showMessageFromSync();
}
/**
* (non-Javadoc)
*
* @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(final Bundle outState) {
// outState.putString("tab", mTabHost.getCurrentTabTag()); // save the
// tab
// selected
super.onSaveInstanceState(outState);
}
/**
* Ugly Wrapper TODO make it more beautiful
*
* @param task
*/
public void saveTask(final Task task) {
Log.v(MainActivity.TAG, "Saving task… (task:" + task.getId());
task.safeSave();
updatesForTask(task);
}
private void search(final String query) {
setCurrentList(new SearchList(this, query));
this.mViewPager.setCurrentItem(MainActivity.getTasksFragmentPosition());
}
public void setCurrentList(final ListMirakel currentList) {
setCurrentList(currentList, null, true, true);
}
/**
* Set the current list and update the views
*
* @param currentList
* @param switchFragment
*/
public void setCurrentList(final ListMirakel currentList,
final boolean switchFragment) {
setCurrentList(currentList, null, switchFragment, true);
}
public void setCurrentList(final ListMirakel currentList,
final View currentView) {
setCurrentList(currentList, currentView, true, true);
}
public void setCurrentList(final ListMirakel currentList, View currentView,
final boolean switchFragment, final boolean resetGoBackTo) {
if (currentList == null)
return;
if (resetGoBackTo) {
this.goBackTo.clear();
}
this.currentList = currentList;
if (this.mDrawerLayout != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
MainActivity.this.mDrawerLayout.closeDrawers();
}
});
}
this.currentTask = currentList.getFirstTask();
if (this.currentTask == null) {
this.currentTask = Task.getDummy(getApplicationContext());
}
if (getTasksFragment() != null) {
getTasksFragment().updateList(true);
if (!MirakelCommonPreferences.isTablet() && switchFragment) {
this.mViewPager.setCurrentItem(MainActivity
.getTasksFragmentPosition());
}
}
final View currentViewL=getCurrentView(currentView);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (currentViewL != null && MainActivity.this.highlightSelected) {
clearHighlighted();
if (MainActivity.this.oldClickedList != null) {
MainActivity.this.oldClickedList.setSelected(false);
MainActivity.this.oldClickedList.setBackgroundColor(0x00000000);
}
currentViewL.setBackgroundColor(getResources().getColor(
R.color.pressed_color));
MainActivity.this.oldClickedList = currentViewL;
}
}
});
if (switchFragment) {
setCurrentTask(this.currentTask);
}
if (this.currentPosition == getTasksFragmentPosition()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
getSupportActionBar().setTitle(currentList.getName());
}
});
}
}
private View getCurrentView(View currentView){
if (currentView == null && getListFragment() != null
&& getListFragment().getAdapter() != null) {
return getListFragment().getAdapter().getViewForList(
currentList);
}
return currentView;
}
/**
* Set the current task and update the view
*
* @param currentTask
*/
public void setCurrentTask(final Task currentTask) {
setCurrentTask(currentTask, false);
}
public void setCurrentTask(final Task currentTask,
final boolean switchFragment) {
setCurrentTask(currentTask, switchFragment, true);
}
public void setCurrentTask(final Task currentTask,
final boolean switchFragment, final boolean resetGoBackTo) {
if (currentTask == null)
return;
this.currentTask = currentTask;
if (resetGoBackTo) {
this.goBackTo.clear();
}
highlightCurrentTask(currentTask, false);
if (getTaskFragment() != null) {
getTaskFragment().update(currentTask);
final boolean smooth = this.mViewPager.getCurrentItem() != getTaskFragmentPosition();
if (!switchFragment)
return;
// Fix buggy behavior
runOnUiThread(new Runnable() {
@Override
public void run() {
MainActivity.this.mViewPager.setCurrentItem(
MainActivity.getTasksFragmentPosition(), false);
MainActivity.this.mViewPager.setCurrentItem(
getTaskFragmentPosition(), false);
MainActivity.this.mViewPager.setCurrentItem(
MainActivity.getTasksFragmentPosition(), false);
MainActivity.this.mViewPager.setCurrentItem(
getTaskFragmentPosition(), smooth);
}
});
}
}
public void setFileUri(final Uri file) {
this.fileUri = file;
}
/**
* Set the Task, to which we switch, if the user press the back-button. It
* is reseted, if one of the setCurrent*-functions on called
*
* @param t
*/
public void setGoBackTo(final Task t) {
this.goBackTo.push(t);
}
public void setSkipSwipe() {
this.skipSwipe = true;
}
public void setTaskFragment(final TaskFragment tf) {
this.taskFragment = tf;
if (getTaskFragment() != null ) {
Log.wtf(TAG,"update");
getTaskFragment().update(currentTask);
}else{
Log.d(TAG," is null");
}
}
/**
* Initialize the ViewPager and setup the rest of the layout
*/
private void setupLayout() {
this.closeOnBack = false;
if (this.currentList == null) {
setCurrentList(SpecialList.firstSpecial());
}
// Initialize ViewPager
if (!this.isResumend && this.mPagerAdapter == null) {
intializeFragments();
}
NotificationService.updateNotificationAndWidget(this);
this.startIntent = getIntent();
if (this.startIntent == null || this.startIntent.getAction() == null) {
Log.d(MainActivity.TAG, "action null");
} else if (this.startIntent.getAction().equals(
DefinitionsHelper.SHOW_TASK)
|| this.startIntent.getAction().equals(
DefinitionsHelper.SHOW_TASK_FROM_WIDGET)) {
final Task task = TaskHelper.getTaskFromIntent(this.startIntent);
if (task != null) {
this.skipSwipe = true;
this.currentList = task.getList();
// setCurrentList(task.getList());
this.mViewPager.postDelayed(new Runnable() {
@Override
public void run() {
setCurrentTask(task, true);
MainActivity.this.mViewPager.setCurrentItem(
getTaskFragmentPosition(), false);
}
}, 1);
runOnUiThread(new Runnable() {
@Override
public void run() {
MainActivity.this.mViewPager.setCurrentItem(
getTaskFragmentPosition(), false);
}
});
} else {
Log.d(MainActivity.TAG, "task null");
}
if (this.startIntent.getAction().equals(
DefinitionsHelper.SHOW_TASK_FROM_WIDGET)) {
this.closeOnBack = true;
}
} else if (this.startIntent.getAction().equals(Intent.ACTION_SEND)
|| this.startIntent.getAction().equals(
Intent.ACTION_SEND_MULTIPLE)) {
this.closeOnBack = true;
this.newTaskContent = this.startIntent
.getStringExtra(Intent.EXTRA_TEXT);
this.newTaskSubject = this.startIntent
.getStringExtra(Intent.EXTRA_SUBJECT);
// If from google now, the content is the subject…
if (this.startIntent.getCategories() != null
&& this.startIntent.getCategories().contains(
"com.google.android.voicesearch.SELF_NOTE")) {
if (!this.newTaskContent.equals("")) {
this.newTaskSubject = this.newTaskContent;
this.newTaskContent = "";
}
}
if (!this.startIntent.getType().equals("text/plain")) {
if (this.newTaskSubject == null) {
this.newTaskSubject = MirakelCommonPreferences
.getImportFileTitle();
}
}
final ListMirakel listFromSharing = MirakelModelPreferences
.getImportDefaultList(false);
if (listFromSharing != null) {
addTaskFromSharing(listFromSharing);
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setTitle(R.string.import_to);
final List<CharSequence> items = new ArrayList<CharSequence>();
final List<Integer> list_ids = new ArrayList<Integer>();
final int currentItem = 0;
for (final ListMirakel list : ListMirakel.all()) {
if (list.getId() > 0) {
items.add(list.getName());
list_ids.add(list.getId());
}
}
builder.setSingleChoiceItems(
items.toArray(new CharSequence[items.size()]),
currentItem, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog,
final int item) {
addTaskFromSharing(ListMirakel.getList(list_ids
.get(item)));
dialog.dismiss();
}
});
builder.create().show();
}
} else if (this.startIntent.getAction().equals(
DefinitionsHelper.SHOW_LIST)
|| this.startIntent.getAction().contains(
DefinitionsHelper.SHOW_LIST_FROM_WIDGET)) {
int listId;
if (this.startIntent.getAction()
.equals(DefinitionsHelper.SHOW_LIST)) {
listId = this.startIntent.getIntExtra(
DefinitionsHelper.EXTRA_ID, 0);
} else {
listId = Integer.parseInt(this.startIntent.getAction().replace(
DefinitionsHelper.SHOW_LIST_FROM_WIDGET, ""));
}
Log.v(MainActivity.TAG, "ListId: " + listId);
ListMirakel list = ListMirakel.getList(listId);
if (list == null) {
list = SpecialList.firstSpecial();
}
setCurrentList(list);
if (this.startIntent.getAction().contains(
DefinitionsHelper.SHOW_LIST_FROM_WIDGET)) {
this.closeOnBack = true;
}
setCurrentTask(list.getFirstTask());
} else if (this.startIntent.getAction().equals(
DefinitionsHelper.SHOW_LISTS)) {
this.mDrawerLayout.openDrawer(DefinitionsHelper.GRAVITY_LEFT);
} else if (this.startIntent.getAction().equals(Intent.ACTION_SEARCH)) {
final String query = this.startIntent
.getStringExtra(SearchManager.QUERY);
search(query);
} else if (this.startIntent.getAction().contains(
DefinitionsHelper.ADD_TASK_FROM_WIDGET)) {
final int listId = Integer.parseInt(this.startIntent.getAction()
.replace(DefinitionsHelper.ADD_TASK_FROM_WIDGET, ""));
setCurrentList(ListMirakel.getList(listId));
if (getTasksFragment() != null && getTasksFragment().isReady()) {
getTasksFragment().focusNew(true);
} else {
this.mViewPager.postDelayed(new Runnable() {
@Override
public void run() {
if (getTasksFragment() != null) {
getTasksFragment().focusNew(true);
} else {
Log.wtf(MainActivity.TAG, "Tasksfragment null");
}
}
}, 10);
}
} else {
this.mViewPager.setCurrentItem(getTaskFragmentPosition());
}
if ((this.startIntent == null || this.startIntent.getAction() == null || !this.startIntent
.getAction().contains(DefinitionsHelper.ADD_TASK_FROM_WIDGET))
&& getTasksFragment() != null) {
getTasksFragment().clearFocus();
}
setIntent(null);
if (this.currentList == null) {
setCurrentList(SpecialList.firstSpecial());
}
}
public void unlockDrawer() {
this.mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
private void updateCurrentListAndTask() {
if (this.currentTask == null && this.currentList == null)
return;
if (this.currentTask != null) {
this.currentTask = Task.get(this.currentTask.getId());
} else {
if (this.currentList != null) {
final List<Task> currentTasks = this.currentList
.tasks(MirakelCommonPreferences.showDoneMain());
if (currentTasks.size() == 0) {
this.currentTask = Task.getDummy(getApplicationContext());
} else {
this.currentTask = currentTasks.get(0);
}
}
}
if (this.currentList != null) {
this.currentList = ListMirakel.getList(this.currentList.getId());
} else {
this.currentList = this.currentTask.getList();
}
}
/**
* Update the internal List of Lists (e.g. for the Move Task dialog)
*/
public void updateLists() {
this.lists = ListMirakel.all(false);
}
/**
* Executes some View–Updates if a Task was changed
*
* @param task
*/
public void updatesForTask(final Task task) {
if (this.currentTask != null
&& task.getId() == this.currentTask.getId()) {
this.currentTask = task;
getTaskFragment().update(task);
}
getTasksFragment().updateList(false);
getListFragment().update();
NotificationService.updateNotificationAndWidget(this);
}
public void updateShare() {
if (this.menu != null) {
final MenuItem share_list = this.menu.findItem(R.id.share_list);
if (share_list != null && this.mViewPager != null) {
this.mViewPager.post(new Runnable() {
@Override
public void run() {
if (MainActivity.this.currentList.countTasks() == 0) {
share_list.setVisible(false);
} else if (MainActivity.this.currentList.countTasks() > 0) {
share_list.setVisible(true);
}
}
});
} else if (this.currentPosition == MainActivity
.getTasksFragmentPosition()
&& share_list == null
&& this.currentList != null
&& this.currentList.countTasks() > 0
&& !this.mDrawerLayout
.isDrawerOpen(DefinitionsHelper.GRAVITY_LEFT)) {
loadMenu(MainActivity.getTasksFragmentPosition(), true, true);
}
}
}
public void updateUI() {
getTasksFragment().updateList(false);
// This is very buggy
// getTaskFragment().updateLayout();
}
}
|
[
"yuzhongxing88@gmail.com"
] |
yuzhongxing88@gmail.com
|
d1450c4881dcf79770699c56a455dc6dec823989
|
774fc7272ad0d2ad0d879d527eb9d47aa430e410
|
/src/laboratorio6_gabrielvasquez/Bebida.java
|
7bffb00c1df9e62053e15815b024c2063527cfc9
|
[] |
no_license
|
gabriel-vsqz/Laboratorio6_GabrielVasquez
|
6ee7293a383c2c9ac0668f53a69827067335b165
|
16607689ac22bdcc5abc2e18d7d28f7a19ef70ec
|
refs/heads/master
| 2020-09-15T13:53:50.316794
| 2019-11-23T01:17:40
| 2019-11-23T01:17:40
| 221,985,417
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,371
|
java
|
package laboratorio6_gabrielvasquez;
import java.util.ArrayList;
import java.util.Scanner;
public class Bebida {
private String codigo;
private String marca;
private String nombre;
private int azucar;
private int alcohol;
private String pertenencia;
private int lote;
private ArrayList<String> colorantes = new ArrayList();
private int precio;
private int cantidad;
private String vencimiento;
public Bebida() {
}
public Bebida(String codigo, String marca, String nombre, int azucar, int alcohol, String pertenencia, int lote, int precio, int cantidad, String vencimiento) {
this.codigo = codigo;
this.marca = marca;
this.nombre = nombre;
this.azucar = azucar;
this.alcohol = alcohol;
this.pertenencia = pertenencia;
this.lote = lote;
this.precio = precio;
this.cantidad = cantidad;
this.vencimiento = vencimiento;
}
public Bebida(String codigo, String marca, String nombre, int azucar, int alcohol, String pertenencia, int lote, int precio, int cantidad, String vencimiento, String coloranteslist) {
this.codigo = codigo;
this.marca = marca;
this.nombre = nombre;
this.azucar = azucar;
this.alcohol = alcohol;
this.pertenencia = pertenencia;
this.lote = lote;
this.precio = precio;
this.cantidad = cantidad;
this.vencimiento = vencimiento;
Scanner sc = new Scanner(coloranteslist);
sc.useDelimiter(",");
while (sc.hasNext()) {
this.colorantes.add(sc.next());
}
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getAzucar() {
return azucar;
}
public void setAzucar(int azucar) {
this.azucar = azucar;
}
public int getAlcohol() {
return alcohol;
}
public void setAlcohol(int alcohol) {
this.alcohol = alcohol;
}
public String getPertenencia() {
return pertenencia;
}
public void setPertenencia(String pertenencia) {
this.pertenencia = pertenencia;
}
public int getLote() {
return lote;
}
public void setLote(int lote) {
this.lote = lote;
}
public ArrayList<String> getColorantes() {
return colorantes;
}
public void setColorantes(ArrayList<String> colorantes) {
this.colorantes = colorantes;
}
public int getPrecio() {
return precio;
}
public void setPrecio(int precio) {
this.precio = precio;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public String getVencimiento() {
return vencimiento;
}
public void setVencimiento(String vencimiento) {
this.vencimiento = vencimiento;
}
@Override
public String toString() {
return "" + nombre;
}
}
|
[
"gabevsqz04@gmail.com"
] |
gabevsqz04@gmail.com
|
6b924cec81017ad2e46c6e62d61a3356fcad52ac
|
b1d12aa10047e9be7c0abea3269645fa5b8eab30
|
/seckill/src/main/java/cn/xq/service/impl/SeckillServiceImpl.java
|
14780f5a5b95e9b3ceee442c3e24d4d78296c066
|
[] |
no_license
|
supursql/MySeckill
|
f48e0628404b505fe0699dbbf8265250e65c2936
|
97e5695b905b715b27ed9427bbdfecde78576889
|
refs/heads/master
| 2020-03-25T17:51:45.055600
| 2018-08-08T10:46:33
| 2018-08-08T10:46:33
| 143,999,823
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,446
|
java
|
package cn.xq.service.impl;
import cn.xq.dao.ISeckillDao;
import cn.xq.dao.ISuccessKilledDao;
import cn.xq.dao.cache.RedisDao;
import cn.xq.dto.Exposer;
import cn.xq.dto.SeckillExecution;
import cn.xq.entity.Seckill;
import cn.xq.entity.SuccessKilled;
import cn.xq.enums.SeckillStatEnum;
import cn.xq.exception.RepeatKillException;
import cn.xq.exception.SeckillCloseException;
import cn.xq.exception.SeckillException;
import cn.xq.service.ISeckillService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class SeckillServiceImpl implements ISeckillService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private ISeckillDao seckillDao;
@Autowired
private ISuccessKilledDao successKilledDao;
@Autowired
private RedisDao redisDao;
//salt value
private final String salt = "outg68ocgbmvfhsx3e5we895-+5952/*l;khnyifg567841+98";
@Override
public List<Seckill> getSeckillList() {
return seckillDao.queryAll(0, 4);
}
@Override
public Seckill getById(long seckillId) {
return seckillDao.queryById(seckillId);
}
@Override
public Exposer exportSeckillUrl(long seckillId) {
//优化点:缓存优化
//1.访问redis
Seckill seckill = redisDao.getSeckill(seckillId);
if (seckill == null) {
seckill = seckillDao.queryById(seckillId);
if (seckill == null) {
return new Exposer(false, seckillId);
} else {
redisDao.putSeckill(seckill);
}
}
Date startTime = seckill.getStartTime();
Date endTime = seckill.getEndTime();
Date nowTime = new Date();
if (nowTime.getTime() < startTime.getTime()
|| nowTime.getTime() > endTime.getTime()) {
return new Exposer(false, seckillId, nowTime.getTime(),
startTime.getTime(), endTime.getTime());
}
String md5 = getMD5(seckillId);
return new Exposer(true, md5,seckillId);
}
/**
* create md5
*/
private String getMD5(long seckillId) {
String base = seckillId + "/" + salt;
String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
return md5;
}
@Override
@Transactional
public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws SeckillException, SeckillCloseException, RepeatKillException {
if (md5 == null || !md5.equals(getMD5(seckillId))) {
throw new SeckillException("seckill data rewrite");
}
//execute seckill : reduce repertory + record purchase behavior
Date nowTime = new Date();
try {
int insertCount = successKilledDao.insertSuccessKilled(seckillId, userPhone);
if (insertCount <= 0) {
throw new RepeatKillException("seckill repeated");
} else {
int updateCount = seckillDao.reduceNumber(seckillId, nowTime);
if (updateCount <= 0) {
throw new SeckillCloseException("seckill is closed");
} else {
SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId,userPhone);
return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS, successKilled);
}
}
} catch (SeckillCloseException e1) {
throw e1;
} catch (RepeatKillException e2) {
throw e2;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new SeckillException("seckill inner error: " + e.getMessage());
}
}
@Override
public SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5) {
if (md5 == null || !md5.equals(getMD5(seckillId))) {
return new SeckillExecution(seckillId, SeckillStatEnum.DATA_REWRITE);
}
Date killTime = new Date();
Map<String, Object> map = new HashMap<>();
map.put("seckillId", seckillId);
map.put("phone", userPhone);
map.put("killTime", killTime);
map.put("result", null);
try {
seckillDao.killByProcedure(map);
//获取result
int result = MapUtils.getInteger(map, "result", -2);
System.out.println("==========================" + MapUtils.getInteger(map, "result", -2));
if (result == 1) {
SuccessKilled sk = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS, sk);
} else {
return new SeckillExecution(seckillId, SeckillStatEnum.stateOf(result));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new SeckillExecution(seckillId, SeckillStatEnum.INNER_ERROR);
}
}
}
|
[
"15771803174@163.com"
] |
15771803174@163.com
|
c435a13fdb42823d450dcf5db637f6c27e45bd1a
|
e949ab5a99ac25629fcde45d6445e42b776ba6f0
|
/uizacoresdk/src/main/java/vn/uiza/views/placeholderview/lib/placeholderview/Animation.java
|
7f526dfbc3a2bd7c246784c47d91a4688062e30e
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
GianhTran/uiza-android-sdk-player
|
056a29a315d2f41aca69a96d3e62f6dca4358bcf
|
13f78c299907867073bae21867c3533d31531cc4
|
refs/heads/master
| 2020-03-30T00:33:32.145718
| 2018-09-17T04:55:56
| 2018-09-17T04:55:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 6,076
|
java
|
package vn.uiza.views.placeholderview.lib.placeholderview;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
/**
* Created by janisharali on 20/08/16.
*/
public class Animation {
public static final int ENTER_LEFT_DESC = 1;
public static final int ENTER_LEFT_ASC = 2;
public static final int ENTER_RIGHT_DESC = 3;
public static final int ENTER_RIGHT_ASC = 4;
public static final int ENTER_TOP_DESC = 5;
public static final int ENTER_TOP_ASC = 6;
public static final int ENTER_BOTTOM_DESC = 7;
public static final int ENTER_BOTTOM_ASC = 8;
public static final int SCALE_UP_DESC = 9;
public static final int SCALE_UP_ASC = 10;
public static final int SCALE_DOWN_DESC = 11;
public static final int SCALE_DOWN_ASC = 12;
public static final int FADE_IN_DESC = 13;
public static final int FADE_IN_ASC = 14;
public static final int CARD_LEFT_IN_DESC = 15;
public static final int CARD_LEFT_IN_ASC = 16;
public static final int CARD_RIGHT_IN_DESC = 17;
public static final int CARD_RIGHT_IN_ASC = 18;
public static final int CARD_TOP_IN_DESC = 19;
public static final int CARD_TOP_IN_ASC = 20;
public static final int CARD_BOTTOM_IN_DESC = 21;
public static final int CARD_BOTTOM_IN_ASC = 22;
public static final int ANIM_DURATION = 300;
public static final float ANIM_INTERPOLATION_FACTOR = 0.3f;
protected static final float ANIM_SCALE_FACTOR_MIN = 0.5f;
protected static final float ANIM_SCALE_FACTOR_ORIGINAL = 1.0f;
protected static final float ANIM_SCALE_FACTOR_MAX = 1.25f;
protected static final float ANIM_ALPHA_MIN = 0f;
protected static final float ANIM_ALPHA_MAX = 1.0f;
/**
*
* @param view
* @param xInit
* @param xFinal
* @param factor
* @param duration
* @param <V>
*/
protected static <V extends View>void itemAnimFromXDesc(V view, float xInit, float xFinal, float factor, int duration){
view.setTranslationX(xInit);
view.animate()
.translationX(xFinal)
.setInterpolator(new DecelerateInterpolator(factor))
.setDuration(duration)
.start();
}
/**
*
* @param view
* @param xInit
* @param xFinal
* @param factor
* @param duration
* @param <V>
*/
protected static <V extends View>void itemAnimFromXAsc(V view, float xInit, float xFinal, float factor, int duration){
view.setTranslationX(xInit);
view.animate()
.translationX(xFinal)
.setInterpolator(new AccelerateInterpolator(factor))
.setDuration(duration)
.start();
}
/**
*
* @param view
* @param yInit
* @param yFinal
* @param factor
* @param duration
* @param <V>
*/
protected static <V extends View>void itemAnimFromYDesc(V view, float yInit, float yFinal, float factor, int duration){
view.setTranslationY(yInit);
view.animate()
.translationY(yFinal)
.setInterpolator(new DecelerateInterpolator(factor))
.setDuration(duration)
.start();
}
/**
*
* @param view
* @param yInit
* @param yFinal
* @param factor
* @param duration
* @param <V>
*/
protected static <V extends View>void itemAnimFromYAsc(V view, float yInit, float yFinal, float factor, int duration){
view.setTranslationY(yInit);
view.animate()
.translationY(yFinal)
.setInterpolator(new AccelerateInterpolator(factor))
.setDuration(duration)
.start();
}
/**
*
* @param view
* @param scaleInitial
* @param scaleFinal
* @param factor
* @param duration
* @param <V>
*/
protected static <V extends View>void itemAnimScaleDesc(V view, float scaleInitial, float scaleFinal, float factor, int duration){
view.setScaleX(scaleInitial);
view.setScaleY(scaleInitial);
view.animate()
.scaleX(scaleFinal)
.scaleY(scaleFinal)
.setInterpolator(new DecelerateInterpolator(factor))
.setDuration(duration)
.start();
}
/**
*
* @param view
* @param scaleInitial
* @param scaleFinal
* @param factor
* @param duration
* @param <V>
*/
protected static <V extends View>void itemAnimScaleAsc(V view, float scaleInitial, float scaleFinal, float factor, int duration){
view.setScaleX(scaleInitial);
view.setScaleY(scaleInitial);
view.animate()
.scaleX(scaleFinal)
.scaleY(scaleFinal)
.setInterpolator(new AccelerateInterpolator(factor))
.setDuration(duration)
.start();
}
/**
*
* @param view
* @param alphaInitial
* @param alphaFinal
* @param factor
* @param duration
* @param <V>
*/
protected static <V extends View>void itemAnimFadeDesc(V view, float alphaInitial, float alphaFinal, float factor, int duration){
view.setAlpha(alphaInitial);
view.animate()
.alpha(alphaFinal)
.setInterpolator(new DecelerateInterpolator(factor))
.setDuration(duration)
.start();
}
/**
*
* @param view
* @param alphaInitial
* @param alphaFinal
* @param factor
* @param duration
* @param <V>
*/
protected static <V extends View>void itemAnimFadeAsc(V view, float alphaInitial, float alphaFinal, float factor, int duration){
view.setAlpha(alphaInitial);
view.animate()
.alpha(alphaFinal)
.setInterpolator(new AccelerateInterpolator(factor))
.setDuration(duration)
.start();
}
}
|
[
"loitp@pateco.vn"
] |
loitp@pateco.vn
|
4250c11c2b7744394508b4b98ed8d989b3c7fbe0
|
5be118dd1866eb9487d9a0dfea9b383d7275d2df
|
/src/main/java/droidudes/hackathon/activities/HomeActivity.java
|
e8b737e0f5011808a2636dfa504972400f7d7493
|
[] |
no_license
|
IMDroidude/Hackathon
|
53e1a88a1a185ae77cabb44d5f2dd52c6595b608
|
f17042150fc1622b3f507ac299426545d2601a55
|
refs/heads/master
| 2021-01-19T12:41:57.730382
| 2017-08-20T12:14:02
| 2017-08-20T12:14:02
| 100,797,445
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 374
|
java
|
package droidudes.hackathon.activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import droidudes.hackathon.R;
public class HomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
}
|
[
"zareahmer89@gmail.com"
] |
zareahmer89@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.