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
60badfc2a87e13c8e97448ae3cc89a1195d58530
23f15844f798cade39a018421a04e7c8768edcbe
/src/main/java/com/sanitas/calculator/service/CalculatorService.java
53b74f295b2339c97fafaa6293931b1af9b654a9
[]
no_license
juaneda/calculatorSanitas
5cbd3bd1ebfc55f3bf41346852f783a8d3423f52
f8461842600396b427514a0ceb995345881c5183
refs/heads/main
2023-01-07T18:35:51.354645
2020-10-24T16:47:05
2020-10-24T16:47:05
304,905,937
0
0
null
null
null
null
UTF-8
Java
false
false
785
java
package com.sanitas.calculator.service; import com.sanitas.calculator.exception.OperationNotValid; import com.sanitas.calculator.request.CalculatorListRequest; import com.sanitas.calculator.request.CalculatorRequest; import com.sanitas.calculator.response.CalculatorResponse; public interface CalculatorService { /** * Realiza la operacion indicada en la request para dos parametros * @param request * @return * @throws OperationNotValid */ CalculatorResponse calculate (CalculatorRequest request) throws OperationNotValid ; /** * Realiza la operacion indicada en la request para un listado de parametros * @param request * @return * @throws OperationNotValid */ CalculatorResponse calculate (CalculatorListRequest request) throws OperationNotValid ; }
[ "juaneda84@hotmail.com" ]
juaneda84@hotmail.com
557380356b0b3c8d881eb31f70bf944ad4bc65a7
13df968e7c9fcd3c4d7ab0b1195903ae5c87ab0a
/nLayedDemo/src/nLayedDemo/core/LoggerService.java
b537c2db71bc7ea98b08443d832615d85678df95
[]
no_license
zehranuralkan/JavaCampLessons
c3d39c9e487cf6fb4f1e8312aa4d9180bb85b2cb
854d0944ba04f874a53579657ea324801d6e5e4a
refs/heads/main
2023-06-05T02:00:29.612080
2021-07-04T21:20:41
2021-07-04T21:20:41
363,640,476
3
0
null
null
null
null
UTF-8
Java
false
false
97
java
package nLayedDemo.core; public interface LoggerService { void logToSystem(String message); }
[ "z.nuralkan@gmail.com" ]
z.nuralkan@gmail.com
153e54c10d80eadc175354f3a685e076f39c7853
eb2e362c46327ef56afd863501115529d0e37dcf
/src/main/java/de/kohnlehome/Subject.java
9abb00102550b3e2d7620ec8f6b634cf246685cd
[]
no_license
meisterk/temperaturobserver
0ac9ab62029cca970b031445d972bf9eecb81afe
223cb38163d043abfa4a03f7801eabd5835e5ca7
refs/heads/master
2022-06-30T22:45:21.277149
2020-05-12T07:43:14
2020-05-12T07:43:14
263,266,885
0
0
null
null
null
null
UTF-8
Java
false
false
478
java
package de.kohnlehome; import java.util.ArrayList; import java.util.List; public abstract class Subject { private List<Observer> observers = new ArrayList(); public void attach(Observer observer){ this.observers.add(observer); } public void detach(Observer observer){ this.observers.remove(observer); } public void notifyObservers(){ for (Observer observer: this.observers) { observer.update(); } } }
[ "franz.kohnle@GBS.sabel.local" ]
franz.kohnle@GBS.sabel.local
aed01160c8ed00668db869e2189f26a3c0258af9
8c878b46ff1eeb733060fe1f3cccd4fe19dda2f4
/src/ch/usi/dag/disl/snippet/ShiftLocalVarSlotCodeTransformer.java
66fe2d291714434907a0e072a3de897669bd75da
[ "Apache-2.0" ]
permissive
rqu/PLuG
72bcdbc1f73c67bceb52ddd98d7d7b89cae84eb0
51b9bc4f25576b344356b851c61453c4e0d8da92
refs/heads/master
2021-06-17T09:38:51.233826
2021-06-04T15:40:31
2021-06-04T15:40:31
171,550,412
0
2
Apache-2.0
2021-06-04T15:40:32
2019-02-19T21:11:41
Java
UTF-8
Java
false
false
906
java
package ch.usi.dag.disl.snippet; import org.objectweb.asm.tree.IincInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.VarInsnNode; import ch.usi.dag.disl.util.CodeTransformer; import ch.usi.dag.disl.util.AsmHelper.Insns; /** * Shifts access to local variable slots by a given offset. */ final class ShiftLocalVarSlotCodeTransformer implements CodeTransformer { private final int __offset; public ShiftLocalVarSlotCodeTransformer (final int offset) { __offset = offset; } // @Override public void transform (final InsnList insns) { Insns.asList (insns).stream ().forEach (insn -> { if (insn instanceof VarInsnNode) { ((VarInsnNode) insn).var += __offset; } else if (insn instanceof IincInsnNode) { ((IincInsnNode) insn).var += __offset; } }); } }
[ "bulej@d3s.mff.cuni.cz" ]
bulej@d3s.mff.cuni.cz
87177e06fd4f341c7390d076e2be75f3d62ed622
dc000f1c01830ccc39c4b0104cd6d02ecbc662a2
/app/src/main/java/com/taijielan/cookbook/ui/view/ICookBookFragment.java
a8e911486220dacaa41defc69b9b0a0a72c64745
[]
no_license
tailanx/Cook
e71de8ac92dc24db87d5ed88e92833dfb6b7d44f
85027862fc55af6045c1e56888486e84584f9174
refs/heads/master
2020-02-26T16:50:12.669684
2018-11-02T02:34:28
2018-11-02T02:34:28
71,612,048
0
0
null
null
null
null
UTF-8
Java
false
false
600
java
package com.taijielan.cookbook.ui.view; import com.taijielan.cookbook.bean.BannerBean; import com.taijielan.cookbook.bean.CookBean; import java.util.List; /** * @author 作者 admin * @类名 * @实现的主要功能 * @创建日期 2016/10/18 17 36 * @修改者 admin * @修改日期 2016/10/18 17 36 * @修改内容 */ public interface ICookBookFragment { //获取banner数据 void getBannerData(List<BannerBean> bannerList); //下拉刷新 void refreshData(List<CookBean> foodGeneralItems); //加载更多 void loadMoreData(List<CookBean> loadMoreList); }
[ "liuyong@calfmobile.com" ]
liuyong@calfmobile.com
c680f8ebb9511dc52d9aba64ed5c1c62b70e5ba9
fda55e60f54351961f8acc36868cd1466171a0fc
/FirstServlet/src/Login/Sucess.java
c0ed358f26a980cd2b86748216f11a0c31e0c171
[]
no_license
suryapattnayak/javascript
e18d00e0268ae21a215313167b41aef3510332fd
4a74fccd2ce83bda871b22147bacc7034cbab28e
refs/heads/master
2021-07-11T23:29:14.587674
2019-09-13T04:25:08
2019-09-13T04:25:08
207,779,003
0
0
null
null
null
null
UTF-8
Java
false
false
856
java
package Login; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Sucess */ @WebServlet("/Sucess") public class Sucess extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
[ "surya@gmail.com" ]
surya@gmail.com
4346517c21651a69adecfdf493f924e6059fcb68
139aa575296282ad3d3756b2472e8f6518a5024c
/QHDemo3.1.0/app/src/main/java/com/qhcloud/demo/manager/model/biz/IAuth.java
42dc95ca315a7f46e1511a6e253c46b5552245e9
[]
no_license
Sarah-alsh/QLinqDemo
c02931f8057f34bbfa2d2986009aafcc83f02508
090de0cc2a4ebaee62c76b4be44a78e0ee608938
refs/heads/master
2020-04-18T02:26:12.445663
2019-01-23T10:22:24
2019-01-23T10:22:24
167,162,437
0
2
null
null
null
null
UTF-8
Java
false
false
486
java
package com.qhcloud.demo.manager.model.biz; /** * 验证码登录业务逻辑接口 */ public interface IAuth { /** * 获取验证码 * @param phone 手机号码 * @return 返回值:0-成功,其他-错误码 */ int getSmsCode(String phone); /** * 验证码登录 * @param tel 手机号码 * @param code 验证码 * @return 返回值:0-成功,其他-错误码 */ int loginBySmsCoder(String tel, String code); }
[ "sarah.shughri@gmail.com" ]
sarah.shughri@gmail.com
8bde10db9e53c2efdcec8de76458b972d74acf1e
9db139fb1cc17a8aad886c6d5c66546eb992fea4
/src/main/java/io/github/rbajek/rasa/action/server/action/custom/form/restaurant/validator/ValidateOutdoorSeatingSlot.java
06b6fb88c00794ad3ca0b9d6f9a01ea576926d42
[ "Apache-2.0" ]
permissive
rbajek/rasa-java-action-server
26124649dc57343faf9479b0c3a01092487fd6c2
8dc75134ed27b0f25fbb949154b86389de1df553
refs/heads/master
2021-12-25T20:10:02.227754
2019-11-29T07:32:07
2019-11-29T07:32:07
218,633,832
17
11
Apache-2.0
2021-12-14T21:35:42
2019-10-30T21:55:58
Java
UTF-8
Java
false
false
1,679
java
package io.github.rbajek.rasa.action.server.action.custom.form.restaurant.validator; import io.github.rbajek.rasa.action.server.action.custom.form.restaurant.data.Constants; import io.github.rbajek.rasa.sdk.CollectingDispatcher; import io.github.rbajek.rasa.sdk.action.form.AbstractFormAction; import io.github.rbajek.rasa.sdk.dto.Domain; import io.github.rbajek.rasa.sdk.dto.Tracker; import java.util.HashMap; import java.util.Map; /** * Validate outdoor_seating value. * * @author Rafał Bajek */ public class ValidateOutdoorSeatingSlot implements AbstractFormAction.ValidateSlot { @Override public Map<String, Object> validateAndConvert(Object value, CollectingDispatcher dispatcher, Tracker tracker, Domain domain) { Map<String, Object> validationMapResult = new HashMap<>(); if(String.class.isInstance(value)) { if ("out".equals(value)) { // convert "out..." to true validationMapResult.put(Constants.Slots.OUTDOOR_SEATING, true); } else if ("in".equals(value)) { // convert "in..." to false validationMapResult.put(Constants.Slots.OUTDOOR_SEATING, false); } else { dispatcher.utterTemplate(Constants.Templates.UTTER_WRONG_OUTDOOR_SEATING); // validation failed, set slot to None validationMapResult.put(Constants.Slots.OUTDOOR_SEATING, null); } } else { // affirm/deny was picked up as T/F validationMapResult.put(Constants.Slots.OUTDOOR_SEATING, value); } return validationMapResult; } }
[ "rafal.bajek@cometari.com" ]
rafal.bajek@cometari.com
ed507d671e5f20ae10f4d59397fa9756e0ad390b
21a024fa26f5eaaacd9bdb70d4b007930f1d601d
/construct-manager-api/src/test/java/fr/mathieugeissler/constructmanager/web/rest/DivisionResourceIntTest.java
d31ee4d3c3807c08d788a3a1db76fbe54950cf99
[]
no_license
BulkSecurityGeneratorProject/construct-manager
c62fed4cda2a12de8eaf7482a22674097c29dbab
e8da817d8ecdb95d1290bad9de366d3b7ec377aa
refs/heads/master
2022-12-16T07:42:07.376515
2019-01-27T22:05:44
2019-01-27T22:05:44
296,583,012
0
0
null
2020-09-18T09:59:34
2020-09-18T09:59:33
null
UTF-8
Java
false
false
12,030
java
package fr.mathieugeissler.constructmanager.web.rest; import fr.mathieugeissler.constructmanager.ConstructManagerApiApp; import fr.mathieugeissler.constructmanager.domain.Division; import fr.mathieugeissler.constructmanager.repository.DivisionRepository; import fr.mathieugeissler.constructmanager.service.DivisionService; import fr.mathieugeissler.constructmanager.service.dto.DivisionDTO; import fr.mathieugeissler.constructmanager.service.mapper.DivisionMapper; import fr.mathieugeissler.constructmanager.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Validator; import javax.persistence.EntityManager; import java.util.List; import static fr.mathieugeissler.constructmanager.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the DivisionResource REST controller. * * @see DivisionResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ConstructManagerApiApp.class) public class DivisionResourceIntTest { private static final String DEFAULT_NAME = "AAAAAAAAAA"; private static final String UPDATED_NAME = "BBBBBBBBBB"; private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAA"; private static final String UPDATED_DESCRIPTION = "BBBBBBBBBB"; @Autowired private DivisionRepository divisionRepository; @Autowired private DivisionMapper divisionMapper; @Autowired private DivisionService divisionService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; @Autowired private Validator validator; private MockMvc restDivisionMockMvc; private Division division; @Before public void setup() { MockitoAnnotations.initMocks(this); final DivisionResource divisionResource = new DivisionResource(divisionService); this.restDivisionMockMvc = MockMvcBuilders.standaloneSetup(divisionResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter) .setValidator(validator).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Division createEntity(EntityManager em) { Division division = new Division() .name(DEFAULT_NAME) .description(DEFAULT_DESCRIPTION); return division; } @Before public void initTest() { division = createEntity(em); } @Test @Transactional public void createDivision() throws Exception { int databaseSizeBeforeCreate = divisionRepository.findAll().size(); // Create the Division DivisionDTO divisionDTO = divisionMapper.toDto(division); restDivisionMockMvc.perform(post("/api/divisions") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(divisionDTO))) .andExpect(status().isCreated()); // Validate the Division in the database List<Division> divisionList = divisionRepository.findAll(); assertThat(divisionList).hasSize(databaseSizeBeforeCreate + 1); Division testDivision = divisionList.get(divisionList.size() - 1); assertThat(testDivision.getName()).isEqualTo(DEFAULT_NAME); assertThat(testDivision.getDescription()).isEqualTo(DEFAULT_DESCRIPTION); } @Test @Transactional public void createDivisionWithExistingId() throws Exception { int databaseSizeBeforeCreate = divisionRepository.findAll().size(); // Create the Division with an existing ID division.setId(1L); DivisionDTO divisionDTO = divisionMapper.toDto(division); // An entity with an existing ID cannot be created, so this API call must fail restDivisionMockMvc.perform(post("/api/divisions") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(divisionDTO))) .andExpect(status().isBadRequest()); // Validate the Division in the database List<Division> divisionList = divisionRepository.findAll(); assertThat(divisionList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void checkNameIsRequired() throws Exception { int databaseSizeBeforeTest = divisionRepository.findAll().size(); // set the field null division.setName(null); // Create the Division, which fails. DivisionDTO divisionDTO = divisionMapper.toDto(division); restDivisionMockMvc.perform(post("/api/divisions") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(divisionDTO))) .andExpect(status().isBadRequest()); List<Division> divisionList = divisionRepository.findAll(); assertThat(divisionList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void getAllDivisions() throws Exception { // Initialize the database divisionRepository.saveAndFlush(division); // Get all the divisionList restDivisionMockMvc.perform(get("/api/divisions?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(division.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))) .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString()))); } @Test @Transactional public void getDivision() throws Exception { // Initialize the database divisionRepository.saveAndFlush(division); // Get the division restDivisionMockMvc.perform(get("/api/divisions/{id}", division.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(division.getId().intValue())) .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString())) .andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString())); } @Test @Transactional public void getNonExistingDivision() throws Exception { // Get the division restDivisionMockMvc.perform(get("/api/divisions/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateDivision() throws Exception { // Initialize the database divisionRepository.saveAndFlush(division); int databaseSizeBeforeUpdate = divisionRepository.findAll().size(); // Update the division Division updatedDivision = divisionRepository.findById(division.getId()).get(); // Disconnect from session so that the updates on updatedDivision are not directly saved in db em.detach(updatedDivision); updatedDivision .name(UPDATED_NAME) .description(UPDATED_DESCRIPTION); DivisionDTO divisionDTO = divisionMapper.toDto(updatedDivision); restDivisionMockMvc.perform(put("/api/divisions") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(divisionDTO))) .andExpect(status().isOk()); // Validate the Division in the database List<Division> divisionList = divisionRepository.findAll(); assertThat(divisionList).hasSize(databaseSizeBeforeUpdate); Division testDivision = divisionList.get(divisionList.size() - 1); assertThat(testDivision.getName()).isEqualTo(UPDATED_NAME); assertThat(testDivision.getDescription()).isEqualTo(UPDATED_DESCRIPTION); } @Test @Transactional public void updateNonExistingDivision() throws Exception { int databaseSizeBeforeUpdate = divisionRepository.findAll().size(); // Create the Division DivisionDTO divisionDTO = divisionMapper.toDto(division); // If the entity doesn't have an ID, it will throw BadRequestAlertException restDivisionMockMvc.perform(put("/api/divisions") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(divisionDTO))) .andExpect(status().isBadRequest()); // Validate the Division in the database List<Division> divisionList = divisionRepository.findAll(); assertThat(divisionList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional public void deleteDivision() throws Exception { // Initialize the database divisionRepository.saveAndFlush(division); int databaseSizeBeforeDelete = divisionRepository.findAll().size(); // Delete the division restDivisionMockMvc.perform(delete("/api/divisions/{id}", division.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<Division> divisionList = divisionRepository.findAll(); assertThat(divisionList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(Division.class); Division division1 = new Division(); division1.setId(1L); Division division2 = new Division(); division2.setId(division1.getId()); assertThat(division1).isEqualTo(division2); division2.setId(2L); assertThat(division1).isNotEqualTo(division2); division1.setId(null); assertThat(division1).isNotEqualTo(division2); } @Test @Transactional public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(DivisionDTO.class); DivisionDTO divisionDTO1 = new DivisionDTO(); divisionDTO1.setId(1L); DivisionDTO divisionDTO2 = new DivisionDTO(); assertThat(divisionDTO1).isNotEqualTo(divisionDTO2); divisionDTO2.setId(divisionDTO1.getId()); assertThat(divisionDTO1).isEqualTo(divisionDTO2); divisionDTO2.setId(2L); assertThat(divisionDTO1).isNotEqualTo(divisionDTO2); divisionDTO1.setId(null); assertThat(divisionDTO1).isNotEqualTo(divisionDTO2); } @Test @Transactional public void testEntityFromId() { assertThat(divisionMapper.fromId(42L).getId()).isEqualTo(42); assertThat(divisionMapper.fromId(null)).isNull(); } }
[ "contact@mathieugeissler.fr" ]
contact@mathieugeissler.fr
338a08efd1591b6c91648113b71bb87d1f52886f
be78d7b94ae36d6d030b0983009d664b62120cb4
/src/main/java/BoardCommentingPage.java
7226ac224fe0ff43469f82304bcf7d76a91115bc
[]
no_license
MakTraDe/a1qa_kurs_8sem
a9cbccd5efc4a0ba83442c455cea9aefbb98fefc
a6af016de3447ca2108aa3d147476d367dc0dd34
refs/heads/master
2021-01-10T17:03:47.375658
2016-03-10T00:06:55
2016-03-10T00:06:55
53,540,902
0
0
null
null
null
null
UTF-8
Java
false
false
746
java
import io.appium.java_client.android.AndroidDriver; import org.openqa.selenium.WebElement; import java.util.List; /** * Created by New on 10.03.2016. */ public class BoardCommentingPage extends Page { public BoardCommentingPage(AndroidDriver driver) { super(driver); } public BoardSettingsSubBarPage setCommentsDisabled() { List<WebElement> buttons = getElementsById("android:id/text1"); executeClick(buttons.get(0)); return new BoardSettingsSubBarPage(driver); } public BoardSettingsSubBarPage setCommentsMembers() { List<WebElement> buttons = getElementsById("android:id/text1"); executeClick(buttons.get(1)); return new BoardSettingsSubBarPage(driver); } }
[ "roman243363@gmail.com" ]
roman243363@gmail.com
c0e6feb54ab85282ee954e607bda177d372b844e
265f1ac2878ab3c86c0c8a6a6d99a43060dc475f
/common/RpcResource.java
7d6ee8e8a0032a4a04bc8775416a4e463c451c88
[]
no_license
InfiniteXue/RPC
247559bec6e1e3f82bd6a453c7ecd34217176609
d49ad1bd00c07ae338ac85b1c0c377f9c08e17ef
refs/heads/master
2020-06-21T16:48:53.890028
2019-07-18T09:34:16
2019-07-18T09:34:16
197,506,446
0
0
null
null
null
null
UTF-8
Java
false
false
377
java
package rpc.common; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 注入rpc api接口(provider端注入Class对象;consumer端注入代理对象) */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface RpcResource { }
[ "infinitelikely@126.com" ]
infinitelikely@126.com
effbddd8f0f4e94230a52add937903d065e4dbbb
4f8dfcdd6f1494b59684438b8592c6c5c2e63829
/DiffTGen-result/output/Math_50_jkali/target/0/11/evosuite-tests/org/apache/commons/math/analysis/solvers/BaseSecantSolver_ESTest_scaffolding.java
e9ddd7cef100bf4c6f0b523bcdc26f2e627cef0f
[]
no_license
IntHelloWorld/Ddifferent-study
fa76c35ff48bf7a240dbe7a8b55dc5a3d2594a3b
9782867d9480e5d68adef635b0141d66ceb81a7e
refs/heads/master
2021-04-17T11:40:12.749992
2020-03-31T23:58:19
2020-03-31T23:58:19
249,439,516
0
0
null
null
null
null
UTF-8
Java
false
false
13,862
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Mon Mar 23 07:39:10 GMT 2020 */ package org.apache.commons.math.analysis.solvers; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; import org.junit.AfterClass; import org.evosuite.runtime.sandbox.Sandbox; import org.evosuite.runtime.sandbox.Sandbox.SandboxMode; @EvoSuiteClassExclude public class BaseSecantSolver_ESTest_scaffolding { @org.junit.Rule public org.junit.rules.Timeout globalTimeout = new org.junit.rules.Timeout(4000); private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); @BeforeClass public static void initEvoSuiteFramework() { org.evosuite.runtime.RuntimeSettings.className = "org.apache.commons.math.analysis.solvers.BaseSecantSolver"; org.evosuite.runtime.GuiSupport.initialize(); org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); org.evosuite.runtime.classhandling.JDKClassResetter.init(); initializeClasses(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); } @AfterClass public static void clearEvoSuiteFramework(){ Sandbox.resetDefaultSecurityManager(); java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); } @Before public void initTestCase(){ threadStopper.storeCurrentThreads(); threadStopper.startRecordingTime(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); setSystemProperties(); org.evosuite.runtime.GuiSupport.setHeadless(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); org.evosuite.runtime.agent.InstrumentingAgent.activate(); } @After public void doneWithTestCase(){ threadStopper.killAndJoinClientThreads(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); org.evosuite.runtime.classhandling.JDKClassResetter.reset(); resetClasses(); org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); } public void setSystemProperties() { java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); java.lang.System.setProperty("java.vm.vendor", "Oracle Corporation"); java.lang.System.setProperty("java.specification.version", "1.8"); java.lang.System.setProperty("java.home", "/usr/lib/jdk/jdk1.8.0_201/jre"); java.lang.System.setProperty("user.dir", "/home/hewitt/work/DiffTGen-master/output/Math_50_jkali/target/0/11"); java.lang.System.setProperty("java.io.tmpdir", "/tmp"); java.lang.System.setProperty("awt.toolkit", "sun.awt.X11.XToolkit"); java.lang.System.setProperty("file.encoding", "UTF-8"); java.lang.System.setProperty("file.separator", "/"); java.lang.System.setProperty("java.awt.graphicsenv", "sun.awt.X11GraphicsEnvironment"); java.lang.System.setProperty("java.awt.headless", "true"); java.lang.System.setProperty("java.awt.printerjob", "sun.print.PSPrinterJob"); java.lang.System.setProperty("java.class.path", "/tmp/EvoSuite_pathingJar3173986724484593651.jar"); java.lang.System.setProperty("java.class.version", "52.0"); java.lang.System.setProperty("java.endorsed.dirs", "/usr/lib/jdk/jdk1.8.0_201/jre/lib/endorsed"); java.lang.System.setProperty("java.ext.dirs", "/usr/lib/jdk/jdk1.8.0_201/jre/lib/ext:/usr/java/packages/lib/ext"); java.lang.System.setProperty("java.library.path", "lib"); java.lang.System.setProperty("java.runtime.name", "Java(TM) SE Runtime Environment"); java.lang.System.setProperty("java.runtime.version", "1.8.0_201-b09"); java.lang.System.setProperty("java.specification.name", "Java Platform API Specification"); java.lang.System.setProperty("java.specification.vendor", "Oracle Corporation"); java.lang.System.setProperty("java.vendor", "Oracle Corporation"); java.lang.System.setProperty("java.vendor.url", "http://java.oracle.com/"); java.lang.System.setProperty("java.version", "1.8.0_201"); java.lang.System.setProperty("java.vm.info", "mixed mode"); java.lang.System.setProperty("java.vm.name", "Java HotSpot(TM) 64-Bit Server VM"); java.lang.System.setProperty("java.vm.specification.name", "Java Virtual Machine Specification"); java.lang.System.setProperty("java.vm.specification.vendor", "Oracle Corporation"); java.lang.System.setProperty("java.vm.specification.version", "1.8"); java.lang.System.setProperty("java.vm.version", "25.201-b09"); java.lang.System.setProperty("line.separator", "\n"); java.lang.System.setProperty("os.arch", "amd64"); java.lang.System.setProperty("os.name", "Linux"); java.lang.System.setProperty("os.version", "4.15.0-91-generic"); java.lang.System.setProperty("path.separator", ":"); java.lang.System.setProperty("user.country", "US"); java.lang.System.setProperty("user.home", "/home/hewitt"); java.lang.System.setProperty("user.language", "en"); java.lang.System.setProperty("user.name", "hewitt"); java.lang.System.setProperty("user.timezone", "Asia/Chongqing"); } private static void initializeClasses() { org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(BaseSecantSolver_ESTest_scaffolding.class.getClassLoader() , "org.apache.commons.math.exception.MathIllegalStateException", "org.apache.commons.math.analysis.function.Asinh", "org.apache.commons.math.util.Incrementor", "org.apache.commons.math.exception.NumberIsTooSmallException", "org.apache.commons.math.analysis.function.Constant", "org.apache.commons.math.analysis.function.Inverse", "org.apache.commons.math.exception.NullArgumentException", "org.apache.commons.math.exception.util.ExceptionContext", "org.apache.commons.math.analysis.solvers.UnivariateRealSolverUtils", "org.apache.commons.math.analysis.function.Sinc", "org.apache.commons.math.exception.NonMonotonousSequenceException", "org.apache.commons.math.util.FastMath", "org.apache.commons.math.util.MathUtils", "org.apache.commons.math.analysis.polynomials.PolynomialFunctionLagrangeForm", "org.apache.commons.math.analysis.function.Sinh", "org.apache.commons.math.analysis.function.Logistic$1", "org.apache.commons.math.analysis.solvers.UnivariateRealSolver", "org.apache.commons.math.exception.NotStrictlyPositiveException", "org.apache.commons.math.analysis.function.Logit$1", "org.apache.commons.math.analysis.solvers.IllinoisSolver", "org.apache.commons.math.exception.NotFiniteNumberException", "org.apache.commons.math.analysis.DifferentiableUnivariateRealFunction", "org.apache.commons.math.analysis.UnivariateRealFunction", "org.apache.commons.math.analysis.solvers.BaseSecantSolver$1", "org.apache.commons.math.analysis.function.Ceil", "org.apache.commons.math.analysis.function.Logit", "org.apache.commons.math.exception.NotPositiveException", "org.apache.commons.math.analysis.function.HarmonicOscillator$1", "org.apache.commons.math.analysis.function.Gaussian", "org.apache.commons.math.analysis.function.Acos", "org.apache.commons.math.analysis.solvers.RegulaFalsiSolver", "org.apache.commons.math.analysis.function.Sin", "org.apache.commons.math.analysis.function.Sigmoid$1", "org.apache.commons.math.analysis.function.Log", "org.apache.commons.math.analysis.function.Tanh", "org.apache.commons.math.exception.MathIllegalArgumentException", "org.apache.commons.math.analysis.function.Minus", "org.apache.commons.math.analysis.function.Cbrt", "org.apache.commons.math.analysis.polynomials.PolynomialFunction", "org.apache.commons.math.analysis.solvers.AbstractUnivariateRealSolver", "org.apache.commons.math.exception.MathUserException", "org.apache.commons.math.analysis.solvers.BaseAbstractUnivariateRealSolver", "org.apache.commons.math.analysis.function.Asin", "org.apache.commons.math.analysis.function.Log1p", "org.apache.commons.math.util.Pair", "org.apache.commons.math.exception.DimensionMismatchException", "org.apache.commons.math.analysis.solvers.PegasusSolver", "org.apache.commons.math.analysis.function.Signum", "org.apache.commons.math.exception.MathIllegalNumberException", "org.apache.commons.math.analysis.solvers.BracketedUnivariateRealSolver", "org.apache.commons.math.util.MathUtils$2", "org.apache.commons.math.util.MathUtils$1", "org.apache.commons.math.analysis.function.Ulp", "org.apache.commons.math.analysis.function.Power", "org.apache.commons.math.analysis.function.Cosh", "org.apache.commons.math.analysis.function.Tan", "org.apache.commons.math.analysis.solvers.BaseSecantSolver", "org.apache.commons.math.analysis.solvers.BaseSecantSolver$Method", "org.apache.commons.math.analysis.function.Logistic", "org.apache.commons.math.analysis.function.Sigmoid", "org.apache.commons.math.analysis.function.Acosh", "org.apache.commons.math.analysis.solvers.AllowedSolution", "org.apache.commons.math.analysis.function.HarmonicOscillator", "org.apache.commons.math.exception.OutOfRangeException", "org.apache.commons.math.exception.NoDataException", "org.apache.commons.math.exception.NumberIsTooLargeException", "org.apache.commons.math.analysis.polynomials.PolynomialSplineFunction", "org.apache.commons.math.exception.MathInternalError", "org.apache.commons.math.analysis.function.Atanh", "org.apache.commons.math.analysis.solvers.BaseUnivariateRealSolver", "org.apache.commons.math.exception.TooManyEvaluationsException", "org.apache.commons.math.analysis.function.Exp", "org.apache.commons.math.analysis.function.Floor", "org.apache.commons.math.analysis.function.Rint", "org.apache.commons.math.exception.util.Localizable", "org.apache.commons.math.analysis.function.Atan", "org.apache.commons.math.exception.MaxCountExceededException", "org.apache.commons.math.exception.MathArithmeticException", "org.apache.commons.math.analysis.function.Cos", "org.apache.commons.math.analysis.function.StepFunction", "org.apache.commons.math.analysis.function.Expm1", "org.apache.commons.math.analysis.function.Log10", "org.apache.commons.math.analysis.function.Abs", "org.apache.commons.math.analysis.polynomials.PolynomialFunctionNewtonForm", "org.apache.commons.math.exception.util.LocalizedFormats", "org.apache.commons.math.util.MathUtils$OrderDirection", "org.apache.commons.math.analysis.function.Gaussian$1", "org.apache.commons.math.exception.util.ExceptionContextProvider", "org.apache.commons.math.analysis.function.Identity", "org.apache.commons.math.analysis.function.Sqrt", "org.apache.commons.math.exception.NoBracketingException", "org.apache.commons.math.exception.util.ArgUtils" ); } private static void resetClasses() { org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(BaseSecantSolver_ESTest_scaffolding.class.getClassLoader()); org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( "org.apache.commons.math.analysis.solvers.BaseSecantSolver$Method", "org.apache.commons.math.analysis.solvers.BaseAbstractUnivariateRealSolver", "org.apache.commons.math.analysis.solvers.BaseSecantSolver", "org.apache.commons.math.analysis.solvers.AllowedSolution", "org.apache.commons.math.analysis.solvers.BaseSecantSolver$1", "org.apache.commons.math.util.FastMath", "org.apache.commons.math.util.MathUtils", "org.apache.commons.math.exception.MathIllegalStateException", "org.apache.commons.math.exception.MaxCountExceededException", "org.apache.commons.math.exception.util.LocalizedFormats", "org.apache.commons.math.exception.util.ExceptionContext", "org.apache.commons.math.exception.TooManyEvaluationsException", "org.apache.commons.math.exception.MathIllegalArgumentException", "org.apache.commons.math.exception.NullArgumentException", "org.apache.commons.math.exception.NoBracketingException", "org.apache.commons.math.exception.MathIllegalNumberException", "org.apache.commons.math.exception.NumberIsTooLargeException", "org.apache.commons.math.exception.DimensionMismatchException", "org.apache.commons.math.exception.OutOfRangeException", "org.apache.commons.math.exception.NumberIsTooSmallException", "org.apache.commons.math.exception.NotStrictlyPositiveException", "org.apache.commons.math.util.MathUtils$OrderDirection", "org.apache.commons.math.util.MathUtils$2", "org.apache.commons.math.exception.NonMonotonousSequenceException" ); } }
[ "1009479460@qq.com" ]
1009479460@qq.com
8f8966a95a4049b5127a04dd4ed23fd4100d9831
8eaaf20f0f20240fb0e31cb62ff838b8bbca7770
/Owari [mc-1.7.10]/[v1]/se/proxus/owari/frames/components/Toggle.java
167108ac79073c78510049f5142532af40cecafc
[ "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
Olivki/minecraft-clients
aa7e5d94596c3c67fa748816566ccce17160d000
19e00b00d3556e6b3cee5f968005638593d12c01
refs/heads/master
2020-04-13T05:30:22.073886
2019-03-04T20:52:54
2019-03-04T20:52:54
162,994,258
4
0
null
null
null
null
UTF-8
Java
false
false
7,222
java
package se.proxus.owari.frames.components; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import org.lwjgl.opengl.GL11; import se.proxus.owari.config.Value; import se.proxus.owari.frames.Component; import se.proxus.owari.frames.FrameManager; import se.proxus.owari.mods.Mod; import se.proxus.owari.tools.Tools; public class Toggle extends Gui implements Component { private String text; private int x; private int y; private int width; private int height; private boolean state; private Mod mod; private Frame frame; public Toggle(final int x, final int y, final int width, final int height, final Mod mod, final Frame frame) { setText(mod.getName()); setX(x); setY(y); setWidth(width); setHeight(height); setMod(mod); setFrame(frame); } @Override public void draw(final FontRenderer font, final int x, final int y, final float ticks) { setState(getMod().getState()); boolean hovering = isHovering(x, y) && !getFrame().isObstructed(x, y); drawRect(getX(), getY(), getX() + getWidth(), getY() + getHeight(), getState() ? 0x90FF5600 : 0x50111111); drawRect(getX(), getY() + getHeight(), getX() + getWidth(), getY() + getHeight(), getState() ? 0xFF19548E : 0xFF1C1C1C); if (hovering) { drawRect(getX(), getY(), getX() + getWidth(), getY() + getHeight(), 0x30000000); } font.drawString(getText(), getX() + getWidth() / 2 - font.getStringWidth(getText()) / 2, getY() + 2, hovering ? 0xFFFFFF55 : 0xFFFFFFFF); } @Override public void mouseClicked(final int x, final int y, final int type) { boolean hovering = isHovering(x, y) && !getFrame().isObstructed(x, y); if (hovering && type == 0) { if (Minecraft.getMinecraft().thePlayer == null) { return; } Tools.playSound("random.click", 1.0F); getMod().toggle(); } if (hovering && type == 1) { Tools.playSound("random.click", 1.0F); Frame frame = new Frame(getMod().getName() + " Config", 0, 2) { @Override public void init() { for (final Value value : getMod().getValues()) { if (!value.isEditable() || value.getName().equalsIgnoreCase("State")) { continue; } if (Tools.isNumber(value.getValue())) { addComponent(new Slider(value, 0, 0, getWidth() - 6, 12, getMod(), value.getMax(), getFrame())); getClient().getLogger().info( "Found number: " + value.getName() + " Max: " + value.getMax()); } if (value.getValue() instanceof Boolean) { addComponent(new Button(value.getName().replace( getMod().getName() + " ", ""), 0, 0, getWidth() - 6, 12, getFrame()) { @Override public void init() { setState(value.getBoolean()); } @Override public void mouseClicked(final int x, final int y, final int type) { if (isHovering(x, y) && type == 0) { Tools.playSound("random.click", 0.5F); setState(!value.getBoolean()); getMod().setValue(value.getName(), getState(), true); } } }); } } addComponent(new Button("Keybind: " + getMod().getKeybind(), 0, 0, getWidth() - 6, 12, getFrame()) { private boolean keyTyped = false; @Override public void mouseClicked(final int x, final int y, final int type) { if (isHovering(x, y) && type == 0) { Tools.playSound("random.click", 1.0F); setText("Keybind: *"); setKeyTyped(!isKeyTyped()); } if (isHovering(x, y) && type == 2) { Tools.playSound("random.click", 1.0F); getMod().setValue("Keybind", "NONE", true); setText("Keybind: " + getMod().getKeybind()); setKeyTyped(false); } } @Override public void keyTyped(final String keyName, final char keyChar) { if (isKeyTyped() && !keyName.equalsIgnoreCase("ESCAPE")) { Tools.playSound("random.click", 1.0F); getMod().setValue("Keybind", keyName, true); setText("Keybind: " + getMod().getKeybind()); setKeyTyped(false); } } public boolean isKeyTyped() { return keyTyped; } public void setKeyTyped(final boolean keyTyped) { this.keyTyped = keyTyped; } }); } }; if (!FrameManager.getInstance().containsByName(frame.getText())) { FrameManager.getInstance().addFrame(frame); } else if (FrameManager.getInstance().containsByName(frame.getText())) { FrameManager.getInstance().removeFrameByName(frame.getText()); } } } @Override public void keyTyped(final String keyName, final char keyChar) { } @Override public void setText(final String text) { this.text = text; } @Override public String getText() { return text; } @Override public void setX(final int x) { this.x = x; } @Override public int getX() { return x; } @Override public void setY(final int y) { this.y = y; } @Override public int getY() { return y; } @Override public void setWidth(final int width) { this.width = width; } @Override public int getWidth() { return width; } @Override public void setHeight(final int height) { this.height = height; } @Override public int getHeight() { return height; } @Override public void setState(final boolean state) { this.state = state; } @Override public boolean getState() { return state; } public Mod getMod() { return mod; } public void setMod(final Mod mod) { this.mod = mod; } public Frame getFrame() { return frame; } public void setFrame(final Frame frame) { this.frame = frame; } @Override public boolean isHovering(final int x, final int y) { return x >= getX() && y >= getY() && x <= getX() + getWidth() && y <= getY() + getHeight(); } public void drawBaseBorderedRect(final int x, final int y, final int width, final int height, final int hex1, final int hex2) { drawRect(x, y + 1, width, height - 1, hex2); drawVerticalLine(x - 1, y, height - 1, hex1); drawVerticalLine(width, y, height - 1, hex1); drawHorizontalLine(x, width - 1, y, hex1); drawHorizontalLine(x, width - 1, height - 1, hex1); } public void drawBorderedRect(final int x, final int y, final int width, final int height, final int hex1, final int hex2) { GL11.glPushMatrix(); GL11.glScaled(0.5D, 0.5D, 0.5D); drawBaseBorderedRect(x * 2, y * 2, width * 2, height * 2, hex1, hex2); GL11.glPopMatrix(); } public void drawBaseBorderedGradientRect(final int x, final int y, final int width, final int height, final int hex1, final int hex2, final int hex3) { drawGradientRect(x, y + 1, width, height - 1, hex2, hex3); drawVerticalLine(x - 1, y, height - 1, hex1); drawVerticalLine(width, y, height - 1, hex1); drawHorizontalLine(x, width - 1, y, hex1); drawHorizontalLine(x, width - 1, height - 1, hex1); } public void drawBorderedGradientRect(final int x, final int y, final int width, final int height, final int hex1, final int hex2, final int hex3) { GL11.glPushMatrix(); GL11.glScaled(0.5D, 0.5D, 0.5D); drawBaseBorderedGradientRect(x * 2, y * 2, width * 2, height * 2, hex1, hex2, hex3); GL11.glPopMatrix(); } }
[ "0liverb3rg@gmail.com" ]
0liverb3rg@gmail.com
20f7e243ec382002929362c7fd5fecfda36ebdf7
275dc5952e8093a694e696c1f95bbcd867fc20fa
/src/unPaseoPorElInfierno/Main.java
d846215c24cda88b1eabd8b136d13bf5739971a4
[]
no_license
lean93/paseoPorElInfierno
b62d2ee40dea2bee20d360fa9739847e9db342ff
dcdeb2e55a089096627be658a0c8214fc0e42c54
refs/heads/master
2021-01-10T08:38:19.021977
2016-02-26T16:05:41
2016-02-26T16:05:41
52,458,590
0
0
null
null
null
null
UTF-8
Java
false
false
1,087
java
package unPaseoPorElInfierno; import java.util.ArrayList; import java.util.Collection; public class Main { public static void main(String args[]){ Sombras sombra = new Sombras(100); Sombras.setTolerancio(100); Collection<Alma> almitas = new ArrayList<Alma>(); Alma alma1 = new Alma(20, 20, true); Alma alma2 = new Alma(20, 20, true); Alma alma3 = new Alma(20, 20, true); Alma alma4 = new Alma(1000, 1000, false); almitas.add(alma1); almitas.add(alma2); almitas.add(alma3); almitas.add(alma4); Lugar casa = new Lugar(almitas); Collection<Lugar> lugares = new ArrayList<Lugar>(); lugares.add(casa); System.out.println(casa.getHabitantes().size()); System.out.println("Alma 4 tiene: " + alma4.getBondad() + " y " + alma4.getValor()); casa.esInvadidoPor(sombra); System.out.println(sombra.getAlmasCapturadas()); System.out.println("Alma 4 tiene: " + alma4.getBondad() + " y " + alma4.getValor()); } }
[ "leandro.rodriguez@despegar.com" ]
leandro.rodriguez@despegar.com
4c730ebc9bad314fee2fd6aa33864f0cdb555e09
a9f279e3d6be7c589786c503d9118a7eb1db9fd8
/Anotherproject/src/another_pakage/Varun.java
d25b4d5f6ab958ebcbd1d2399e78c0e0490262fe
[]
no_license
varungowda16/Anotherjava
27e371f780b1c8004190fc869b4f2deabe03ad63
bdbb8e07b069080e835fd849ab108e9c456af39d
refs/heads/master
2021-01-25T13:06:46.860195
2018-03-02T04:59:14
2018-03-02T04:59:14
123,530,579
0
0
null
null
null
null
UTF-8
Java
false
false
161
java
package another_pakage; public class Varun { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("varun"); } }
[ "tyss@198.105.254.11" ]
tyss@198.105.254.11
53e575eae8e2a07894f1e70c2f3c82a6da4cb414
5943f397bb35f0f850f6870d732cc5b9c28dc872
/src/main/java/com/blog/ljw/firstbolg/service/RedisService.java
a2a9bd6cba3bb41ff90a9388a00da72bedd5f263
[]
no_license
jinweiLiu/BlackBlog
482822d31ff81101303539b535905eb7e381ae86
005cf22d681010c3854da42e3ccb3d51addaef3a
refs/heads/master
2022-07-01T04:12:01.594920
2019-12-25T12:30:00
2019-12-25T12:30:00
228,193,548
0
0
null
2022-06-17T02:48:27
2019-12-15T14:00:51
CSS
UTF-8
Java
false
false
2,731
java
package com.blog.ljw.firstbolg.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.Set; @Service public class RedisService { @Autowired private RedisTemplate<String, String> redisTemplate; @Autowired private ArticleService articleService; private final String HOT = "hotArticle"; public String get(final String key) { return redisTemplate.opsForValue().get(key); } public boolean set(final String key, String value) { boolean result = false; try { redisTemplate.opsForValue().set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } public boolean delete(final String key) { boolean result = false; try { redisTemplate.delete(key); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } public boolean increment(final String key){ boolean result = false; try { redisTemplate.opsForValue().increment(key); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } public boolean getAndset(final String key,int index){ boolean result = false; try { String old = redisTemplate.opsForValue().get(key); int change = Integer.parseInt(old.split(":")[index])+1; if(index==0){ redisTemplate.opsForValue().set(key,change+":"+old.split(":")[1]); }else{ redisTemplate.opsForValue().set(key,old.split(":")[0]+":"+change); } result = true; } catch (Exception e) { e.printStackTrace(); } return result; } public boolean zsetadd(final String key,final String score){ boolean result = false; try { redisTemplate.opsForZSet().add(HOT, key, Double.parseDouble(score)); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } public Set<String> zrevenge(int start, int end){ Set<String> set = redisTemplate.opsForZSet().reverseRange(HOT,start,end); return set; } /*public List<Article> getHotArticle(){ List<Article> Hots = new ArrayList<>(); Set<String> set = zrevenge(0,6); for(String hot : set){ Hots.add(articleService.getArticlById(hot)); } return Hots; }*/ }
[ "jwliu0213@163.com" ]
jwliu0213@163.com
2286f6abfe91080c31e2901e8132fc4fc61158be
45ae5d872f1e55d38617984021494e0facdf3291
/src/main/java/gawky/json/JSONObject.java
8fab09c351168235f440382f2ed2c74474b3b197
[]
no_license
iharbeck/gawky
f8fc48a5f5cd3e23a3e649654a0c9d874540e447
b434e84b2a73d43ccd3e0143fe896085b7b49a36
refs/heads/master
2021-01-20T06:20:14.669429
2018-07-15T15:25:53
2018-07-15T15:25:53
34,203,519
0
0
null
null
null
null
UTF-8
Java
false
false
39,765
java
package gawky.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.io.IOException; import java.io.Writer; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * A JSONObject is an unordered collection of name/value pairs. Its * external form is a string wrapped in curly braces with colons between the * names and values, and commas between the values and names. The internal form * is an object having <code>get</code> and <code>opt</code> methods for * accessing the values by name, and <code>put</code> methods for adding or * replacing values by name. The values can be any of these types: * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, * <code>Number</code>, <code>String</code>, or the <code>JSONObject.NULL</code> * object. A JSONObject constructor can be used to convert an external form * JSON text into an internal form whose values can be retrieved with the * <code>get</code> and <code>opt</code> methods, or to convert values into a * JSON text using the <code>put</code> and <code>toString</code> methods. * A <code>get</code> method returns a value if one can be found, and throws an * exception if one cannot be found. An <code>opt</code> method returns a * default value instead of throwing an exception, and so is useful for * obtaining optional values. * <p> * The generic <code>get()</code> and <code>opt()</code> methods return an * object, which you can cast or query for type. There are also typed * <code>get</code> and <code>opt</code> methods that do type checking and type * coersion for you. * <p> * The <code>put</code> methods adds values to an object. For example, <pre> * myString = new JSONObject().put("JSON", "Hello, World!").toString();</pre> * produces the string <code>{"JSON": "Hello, World"}</code>. * <p> * The texts produced by the <code>toString</code> methods strictly conform to * the JSON sysntax rules. * The constructors are more forgiving in the texts they will accept: * <ul> * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just * before the closing brace.</li> * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single * quote)</small>.</li> * <li>Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, * and if they do not contain any of these characters: * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers * and if they are not the reserved words <code>true</code>, * <code>false</code>, or <code>null</code>.</li> * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as * by <code>:</code>.</li> * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as * well as by <code>,</code> <small>(comma)</small>.</li> * <li>Numbers may have the <code>0-</code> <small>(octal)</small> or * <code>0x-</code> <small>(hex)</small> prefix.</li> * <li>Comments written in the slashshlash, slashstar, and hash conventions * will be ignored.</li> * </ul> * @author JSON.org * @version 2 */ public class JSONObject { /** * JSONObject.NULL is equivalent to the value that JavaScript calls null, * whilst Java's null is equivalent to the value that JavaScript calls * undefined. */ private static final class Null { /** * There is only intended to be a single instance of the NULL object, * so the clone method returns itself. * @return NULL. */ @Override protected final Object clone() { return this; } /** * A Null object is equal to the null value and to itself. * @param object An object to test for nullness. * @return true if the object parameter is the JSONObject.NULL object * or null. */ @Override public boolean equals(Object object) { return object == null || object == this; } /** * Get the "null" string value. * @return The string "null". */ @Override public String toString() { return "null"; } } /** * The hash map where the JSONObject's properties are kept. */ private HashMap myHashMap; /** * It is sometimes more convenient and less ambiguous to have a * <code>NULL</code> object than to use Java's <code>null</code> value. * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>. * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>. */ public static final Object NULL = new Null(); /** * Construct an empty JSONObject. */ public JSONObject() { this.myHashMap = new HashMap(); } /** * Construct a JSONObject from a subset of another JSONObject. * An array of strings is used to identify the keys that should be copied. * Missing keys are ignored. * @param jo A JSONObject. * @param names An array of strings. * @exception JSONException If a value is a non-finite number. */ public JSONObject(JSONObject jo, String[] names) throws JSONException { this(); for(String name : names) { putOpt(name, jo.opt(name)); } } /** * Construct a JSONObject from a JSONTokener. * @param x A JSONTokener object containing the source string. * @throws JSONException If there is a syntax error in the source string. */ public JSONObject(JSONTokener x) throws JSONException { this(); char c; String key; if(x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } for(;;) { c = x.nextClean(); switch(c) { case 0: throw x.syntaxError("A JSONObject text must end with '}'"); case '}': return; default: x.back(); key = x.nextValue().toString(); } /* * The key is followed by ':'. We will also tolerate '=' or '=>'. */ c = x.nextClean(); if(c == '=') { if(x.next() != '>') { x.back(); } } else if(c != ':') { throw x.syntaxError("Expected a ':' after a key"); } put(key, x.nextValue()); /* * Pairs are separated by ','. We will also tolerate ';'. */ switch(x.nextClean()) { case ';': case ',': if(x.nextClean() == '}') { return; } x.back(); break; case '}': return; default: throw x.syntaxError("Expected a ',' or '}'"); } } } /** * Construct a JSONObject from a Map. * @param map A map object that can be used to initialize the contents of * the JSONObject. */ public JSONObject(Map map) { this.myHashMap = (map == null) ? new HashMap() : new HashMap(map); } /** * Construct a JSONObject from an Object using bean getters. * It reflects on all of the public methods of the object. * For each of the methods with no parameters and a name starting * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter, * the method is invoked, and a key and the value returned from the getter method * are put into the new JSONObject. * * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. If the second remaining * character is not upper case, then the first * character is converted to lower case. * * For example, if an object has a method named <code>"getName"</code>, and * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>, * then the JSONObject will contain <code>"name": "Larry Fine"</code>. * * @param bean An object that has getter methods that should be used * to make a JSONObject. */ public JSONObject(Object bean) { this(); Class klass = bean.getClass(); Method[] methods = klass.getMethods(); for(Method method : methods) { try { String name = method.getName(); String key = ""; if(name.startsWith("get")) { key = name.substring(3); } else if(name.startsWith("is")) { key = name.substring(2); } if(key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if(key.length() == 1) { key = key.toLowerCase(); } else if(!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } this.put(key, method.invoke(bean, null)); } } catch(Exception e) { /* forget about it */ } } } /** * Construct a JSONObject from an Object, using reflection to find the * public members. The resulting JSONObject's keys will be the strings * from the names array, and the values will be the field values associated * with those keys in the object. If a key is not found or not visible, * then it will not be copied into the new JSONObject. * @param object An object that has fields that should be used to make a * JSONObject. * @param names An array of strings, the names of the fields to be obtained * from the object. */ public JSONObject(Object object, String names[]) { this(); Class c = object.getClass(); for(String name : names) { try { Field field = c.getField(name); Object value = field.get(object); this.put(name, value); } catch(Exception e) { /* forget about it */ } } } /** * Construct a JSONObject from a source JSON text string. * This is the most commonly used JSONObject constructor. * @param source A string beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @exception JSONException If there is a syntax error in the source string. */ public JSONObject(String source) throws JSONException { this(new JSONTokener(source)); } /** * Accumulate values under a key. It is similar to the put method except * that if there is already an object stored under the key then a * JSONArray is stored under the key to hold all of the accumulated values. * If there is already a JSONArray, then the new value is appended to it. * In contrast, the put method replaces the previous value. * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number * or if the key is null. */ public JSONObject accumulate(String key, Object value) throws JSONException { testValidity(value); Object o = opt(key); if(o == null) { put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); } else if(o instanceof JSONArray) { ((JSONArray)o).put(value); } else { put(key, new JSONArray().put(o).put(value)); } return this; } /** * Append values to the array under a key. If the key does not exist in the * JSONObject, then the key is put in the JSONObject with its value being a * JSONArray containing the value parameter. If the key was already * associated with a JSONArray, then the value parameter is appended to it. * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the key is null or if the current value * associated with the key is not a JSONArray. */ public JSONObject append(String key, Object value) throws JSONException { testValidity(value); Object o = opt(key); if(o == null) { put(key, new JSONArray().put(value)); } else if(o instanceof JSONArray) { put(key, ((JSONArray)o).put(value)); } else { throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); } return this; } /** * Produce a string from a double. The string "null" will be returned if * the number is not finite. * @param d A double. * @return A String. */ static public String doubleToString(double d) { if(Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String s = Double.toString(d); if(s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { while(s.endsWith("0")) { s = s.substring(0, s.length() - 1); } if(s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } return s; } /** * Get the value object associated with a key. * * @param key A key string. * @return The object associated with the key. * @throws JSONException if the key is not found. */ public Object get(String key) throws JSONException { Object o = opt(key); if(o == null) { throw new JSONException("JSONObject[" + quote(key) + "] not found."); } return o; } /** * Get the boolean value associated with a key. * * @param key A key string. * @return The truth. * @throws JSONException * if the value is not a Boolean or the String "true" or "false". */ public boolean getBoolean(String key) throws JSONException { Object o = get(key); if(o.equals(Boolean.FALSE) || (o instanceof String && ((String)o).equalsIgnoreCase("false"))) { return false; } else if(o.equals(Boolean.TRUE) || (o instanceof String && ((String)o).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); } /** * Get the double value associated with a key. * @param key A key string. * @return The numeric value. * @throws JSONException if the key is not found or * if the value is not a Number object and cannot be converted to a number. */ public double getDouble(String key) throws JSONException { Object o = get(key); try { return o instanceof Number ? ((Number)o).doubleValue() : Double.valueOf((String)o).doubleValue(); } catch(Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } } /** * Get the int value associated with a key. If the number value is too * large for an int, it will be clipped. * * @param key A key string. * @return The integer value. * @throws JSONException if the key is not found or if the value cannot * be converted to an integer. */ public int getInt(String key) throws JSONException { Object o = get(key); return o instanceof Number ? ((Number)o).intValue() : (int)getDouble(key); } /** * Get the JSONArray value associated with a key. * * @param key A key string. * @return A JSONArray which is the value. * @throws JSONException if the key is not found or * if the value is not a JSONArray. */ public JSONArray getJSONArray(String key) throws JSONException { Object o = get(key); if(o instanceof JSONArray) { return (JSONArray)o; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); } /** * Get the JSONObject value associated with a key. * * @param key A key string. * @return A JSONObject which is the value. * @throws JSONException if the key is not found or * if the value is not a JSONObject. */ public JSONObject getJSONObject(String key) throws JSONException { Object o = get(key); if(o instanceof JSONObject) { return (JSONObject)o; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); } /** * Get the long value associated with a key. If the number value is too * long for a long, it will be clipped. * * @param key A key string. * @return The long value. * @throws JSONException if the key is not found or if the value cannot * be converted to a long. */ public long getLong(String key) throws JSONException { Object o = get(key); return o instanceof Number ? ((Number)o).longValue() : (long)getDouble(key); } /** * Get an array of field names from a JSONObject. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(JSONObject jo) { int length = jo.length(); if(length == 0) { return null; } Iterator i = jo.keys(); String[] names = new String[length]; int j = 0; while(i.hasNext()) { names[j] = (String)i.next(); j += 1; } return names; } /** * Get an array of field names from an Object. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(Object object) { if(object == null) { return null; } Class klass = object.getClass(); Field[] fields = klass.getFields(); int length = fields.length; if(length == 0) { return null; } String[] names = new String[length]; for(int i = 0; i < length; i += 1) { names[i] = fields[i].getName(); } return names; } /** * Get the string associated with a key. * * @param key A key string. * @return A string which is the value. * @throws JSONException if the key is not found. */ public String getString(String key) throws JSONException { return get(key).toString(); } /** * Determine if the JSONObject contains a specific key. * @param key A key string. * @return true if the key exists in the JSONObject. */ public boolean has(String key) { return this.myHashMap.containsKey(key); } /** * Determine if the value associated with the key is null or if there is * no value. * @param key A key string. * @return true if there is no value associated with the key or if * the value is the JSONObject.NULL object. */ public boolean isNull(String key) { return JSONObject.NULL.equals(opt(key)); } /** * Get an enumeration of the keys of the JSONObject. * * @return An iterator of the keys. */ public Iterator keys() { return this.myHashMap.keySet().iterator(); } /** * Get the number of keys stored in the JSONObject. * * @return The number of keys in the JSONObject. */ public int length() { return this.myHashMap.size(); } /** * Produce a JSONArray containing the names of the elements of this * JSONObject. * @return A JSONArray containing the key strings, or null if the JSONObject * is empty. */ public JSONArray names() { JSONArray ja = new JSONArray(); Iterator keys = keys(); while(keys.hasNext()) { ja.put(keys.next()); } return ja.length() == 0 ? null : ja; } /** * Produce a string from a Number. * @param n A Number * @return A String. * @throws JSONException If n is a non-finite number. */ static public String numberToString(Number n) throws JSONException { if(n == null) { throw new JSONException("Null pointer"); } testValidity(n); // Shave off trailing zeros and decimal point, if possible. String s = n.toString(); if(s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { while(s.endsWith("0")) { s = s.substring(0, s.length() - 1); } if(s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } return s; } /** * Get an optional value associated with a key. * @param key A key string. * @return An object which is the value, or null if there is no value. */ public Object opt(String key) { return key == null ? null : this.myHashMap.get(key); } /** * Get an optional boolean associated with a key. * It returns false if there is no such key, or if the value is not * Boolean.TRUE or the String "true". * * @param key A key string. * @return The truth. */ public boolean optBoolean(String key) { return optBoolean(key, false); } /** * Get an optional boolean associated with a key. * It returns the defaultValue if there is no such key, or if it is not * a Boolean or the String "true" or "false" (case insensitive). * * @param key A key string. * @param defaultValue The default. * @return The truth. */ public boolean optBoolean(String key, boolean defaultValue) { try { return getBoolean(key); } catch(Exception e) { return defaultValue; } } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONArray which is produced from a Collection. * @param key A key string. * @param value A Collection value. * @return this. * @throws JSONException */ public JSONObject put(String key, Collection value) throws JSONException { put(key, new JSONArray(value)); return this; } /** * Get an optional double associated with a key, * or NaN if there is no such key or if its value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A string which is the key. * @return An object which is the value. */ public double optDouble(String key) { return optDouble(key, Double.NaN); } /** * Get an optional double associated with a key, or the * defaultValue if there is no such key or if its value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public double optDouble(String key, double defaultValue) { try { Object o = opt(key); return o instanceof Number ? ((Number)o).doubleValue() : new Double((String)o).doubleValue(); } catch(Exception e) { return defaultValue; } } /** * Get an optional int value associated with a key, * or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @return An object which is the value. */ public int optInt(String key) { return optInt(key, 0); } /** * Get an optional int value associated with a key, * or the default if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public int optInt(String key, int defaultValue) { try { return getInt(key); } catch(Exception e) { return defaultValue; } } /** * Get an optional JSONArray associated with a key. * It returns null if there is no such key, or if its value is not a * JSONArray. * * @param key A key string. * @return A JSONArray which is the value. */ public JSONArray optJSONArray(String key) { Object o = opt(key); return o instanceof JSONArray ? (JSONArray)o : null; } /** * Get an optional JSONObject associated with a key. * It returns null if there is no such key, or if its value is not a * JSONObject. * * @param key A key string. * @return A JSONObject which is the value. */ public JSONObject optJSONObject(String key) { Object o = opt(key); return o instanceof JSONObject ? (JSONObject)o : null; } /** * Get an optional long value associated with a key, * or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @return An object which is the value. */ public long optLong(String key) { return optLong(key, 0); } /** * Get an optional long value associated with a key, * or the default if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public long optLong(String key, long defaultValue) { try { return getLong(key); } catch(Exception e) { return defaultValue; } } /** * Get an optional string associated with a key. * It returns an empty string if there is no such key. If the value is not * a string and is not null, then it is coverted to a string. * * @param key A key string. * @return A string which is the value. */ public String optString(String key) { return optString(key, ""); } /** * Get an optional string associated with a key. * It returns the defaultValue if there is no such key. * * @param key A key string. * @param defaultValue The default. * @return A string which is the value. */ public String optString(String key, String defaultValue) { Object o = opt(key); return o != null ? o.toString() : defaultValue; } /** * Put a key/boolean pair in the JSONObject. * * @param key A key string. * @param value A boolean which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, boolean value) throws JSONException { put(key, value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a key/double pair in the JSONObject. * * @param key A key string. * @param value A double which is the value. * @return this. * @throws JSONException If the key is null or if the number is invalid. */ public JSONObject put(String key, double value) throws JSONException { put(key, new Double(value)); return this; } /** * Put a key/int pair in the JSONObject. * * @param key A key string. * @param value An int which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, int value) throws JSONException { put(key, new Integer(value)); return this; } /** * Put a key/long pair in the JSONObject. * * @param key A key string. * @param value A long which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, long value) throws JSONException { put(key, new Long(value)); return this; } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONObject which is produced from a Map. * @param key A key string. * @param value A Map value. * @return this. * @throws JSONException */ public JSONObject put(String key, Map value) throws JSONException { put(key, new JSONObject(value)); return this; } /** * Put a key/value pair in the JSONObject. If the value is null, * then the key will be removed from the JSONObject if it is present. * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is non-finite number * or if the key is null. */ public JSONObject put(String key, Object value) throws JSONException { if(key == null) { throw new JSONException("Null key."); } if(value != null) { testValidity(value); this.myHashMap.put(key, value); } else { remove(key); } return this; } /** * Put a key/value pair in the JSONObject, but only if the * key and the value are both non-null. * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is a non-finite number. */ public JSONObject putOpt(String key, Object value) throws JSONException { if(key != null && value != null) { put(key, value); } return this; } /** * Produce a string in double quotes with backslash sequences in all the * right places. A backslash will be inserted within </, allowing JSON * text to be delivered in HTML. In JSON text, a string cannot contain a * control character or an unescaped quote or backslash. * @param string A String * @return A String correctly formatted for insertion in a JSON text. */ public static String quote(String string) { if(string == null || string.length() == 0) { return "\"\""; } char b; char c = 0; int i; int len = string.length(); StringBuffer sb = new StringBuffer(len + 4); String t; sb.append('"'); for(i = 0; i < len; i += 1) { b = c; c = string.charAt(i); switch(c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; case '/': if(b == '<') { sb.append('\\'); } sb.append(c); break; case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: if(c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { t = "000" + Integer.toHexString(c); sb.append("\\u" + t.substring(t.length() - 4)); } else { sb.append(c); } } } sb.append('"'); return sb.toString(); } /** * Remove a name and its value, if present. * @param key The name to be removed. * @return The value that was associated with the name, * or null if there was no value. */ public Object remove(String key) { return this.myHashMap.remove(key); } /** * Throw an exception if the object is an NaN or infinite number. * @param o The object to test. * @throws JSONException If o is a non-finite number. */ static void testValidity(Object o) throws JSONException { if(o != null) { if(o instanceof Double) { if(((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if(o instanceof Float) { if(((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } } /** * Produce a JSONArray containing the values of the members of this * JSONObject. * @param names A JSONArray containing a list of key strings. This * determines the sequence of the values in the result. * @return A JSONArray of values. * @throws JSONException If any of the values are non-finite numbers. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { if(names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); for(int i = 0; i < names.length(); i += 1) { ja.put(this.opt(names.getString(i))); } return ja; } /** * Make a JSON text of this JSONObject. For compactness, no whitespace * is added. If this would not result in a syntactically correct JSON text, * then null will be returned instead. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. */ @Override public String toString() { try { Iterator keys = keys(); StringBuffer sb = new StringBuffer("{"); while(keys.hasNext()) { if(sb.length() > 1) { sb.append(','); } Object o = keys.next(); sb.append(quote(o.toString())); sb.append(':'); sb.append(valueToString(this.myHashMap.get(o))); } sb.append('}'); return sb.toString(); } catch(Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONObject. * <p> * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, portable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ public String toString(int indentFactor) throws JSONException { return toString(indentFactor, 0); } /** * Make a prettyprinted JSON text of this JSONObject. * <p> * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ String toString(int indentFactor, int indent) throws JSONException { int i; int n = length(); if(n == 0) { return "{}"; } Iterator keys = keys(); StringBuffer sb = new StringBuffer("{"); int newindent = indent + indentFactor; Object o; if(n == 1) { o = keys.next(); sb.append(quote(o.toString())); sb.append(": "); sb.append(valueToString(this.myHashMap.get(o), indentFactor, indent)); } else { while(keys.hasNext()) { o = keys.next(); if(sb.length() > 1) { sb.append(",\n"); } else { sb.append('\n'); } for(i = 0; i < newindent; i += 1) { sb.append(' '); } sb.append(quote(o.toString())); sb.append(": "); sb.append(valueToString(this.myHashMap.get(o), indentFactor, newindent)); } if(sb.length() > 1) { sb.append('\n'); for(i = 0; i < indent; i += 1) { sb.append(' '); } } } sb.append('}'); return sb.toString(); } /** * Make a JSON text of an Object value. If the object has an * value.toJSONString() method, then that method will be used to produce * the JSON text. The method is required to produce a strictly * conforming text. If the object does not contain a toJSONString * method (which is the most common case), then a text will be * produced by other means. If the value is an array or Collection, * then a JSONArray will be made from it and its toJSONString method * will be called. If the value is a MAP, then a JSONObject will be made * from it and its toJSONString method will be called. Otherwise, the * value's toString method will be called, and the result will be quoted. * * <p> * Warning: This method assumes that the data structure is acyclical. * @param value The value to be serialized. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the value is or contains an invalid number. */ static String valueToString(Object value) throws JSONException { if(value == null || value.equals("null")) { return "null"; } if(value instanceof JSONString) { Object o; try { o = ((JSONString)value).toJSONString(); } catch(Exception e) { throw new JSONException(e); } if(o instanceof String) { return (String)o; } throw new JSONException("Bad value from toJSONString: " + o); } if(value instanceof Number) { return numberToString((Number)value); } if(value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { return value.toString(); } if(value instanceof Map) { return new JSONObject((Map)value).toString(); } if(value instanceof Collection) { return new JSONArray((Collection)value).toString(); } if(value.getClass().isArray()) { return new JSONArray(value).toString(); } return quote(value.toString()); } /** * Make a prettyprinted JSON text of an object value. * <p> * Warning: This method assumes that the data structure is acyclical. * @param value The value to be serialized. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ static String valueToString(Object value, int indentFactor, int indent) throws JSONException { if(value == null || value.equals("null")) { return "null"; } try { if(value instanceof JSONString) { Object o = ((JSONString)value).toJSONString(); if(o instanceof String) { return (String)o; } } } catch(Exception e) { /* forget about it */ } if(value instanceof Number) { return numberToString((Number)value); } if(value instanceof Boolean) { return value.toString(); } if(value instanceof JSONObject) { return ((JSONObject)value).toString(indentFactor, indent); } if(value instanceof JSONArray) { return ((JSONArray)value).toString(indentFactor, indent); } if(value instanceof Map) { return new JSONObject((Map)value).toString(indentFactor, indent); } if(value instanceof Collection) { return new JSONArray((Collection)value).toString(indentFactor, indent); } if(value.getClass().isArray()) { return new JSONArray(value).toString(indentFactor, indent); } return quote(value.toString()); } /** * Write the contents of the JSONObject as JSON text to a writer. * For compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean b = false; Iterator keys = keys(); writer.write('{'); while(keys.hasNext()) { if(b) { writer.write(','); } Object k = keys.next(); writer.write(quote(k.toString())); writer.write(':'); Object v = this.myHashMap.get(k); if(v instanceof JSONObject) { ((JSONObject)v).write(writer); } else if(v instanceof JSONArray) { ((JSONArray)v).write(writer); } else { writer.write(valueToString(v)); } b = true; } writer.write('}'); return writer; } catch(IOException e) { throw new JSONException(e); } } }
[ "iharbeck@91f012ad-703b-4ebb-b4ac-6d446edbf5f8" ]
iharbeck@91f012ad-703b-4ebb-b4ac-6d446edbf5f8
250e1c2017b286f35605a8aa3a3d04d70c2942d5
fa5b5995c5942a797889aef964483f470ddd0987
/FlourishAndBlotts.java
3cf6a618911f12afbb1d4342984900985d6d022a
[]
no_license
Granteur/Bookstore
404911449197b297a38ed5c9aaf4691c85d26a78
6343e651f1bfa873dbbcf40910c5802c20b4d45f
refs/heads/master
2022-07-16T06:58:46.990380
2020-05-15T00:57:01
2020-05-15T00:57:01
264,022,855
0
0
null
null
null
null
UTF-8
Java
false
false
90
java
public class FlourishAndBlotts.java{ public static void main(String[] args) { } }
[ "angelojgrant@gmail.com" ]
angelojgrant@gmail.com
be6e9652094305e99595ddaad249af0d138ae60c
5198458f65f338ec59bc89432cd1ff16905281e0
/How to separate initial data load from incremental children with Firebase.java
c8aa0d61b8be38bd0ccd36186ea0ae21e2cf6649
[]
no_license
jokamjohn/FirebaseRecipes
a7fe203af9d52d7fab41cbb95fa9e75e4c5a9511
a795b265a42358307c587311a2c31cbd6c9c1859
refs/heads/master
2021-01-11T14:17:07.502046
2017-02-08T07:51:37
2017-02-08T07:51:37
81,303,003
0
0
null
null
null
null
UTF-8
Java
false
false
1,017
java
// Since child_added events for the initial, pre-loaded data will fire before the value event fires on the parent, you can use the value event as a sort of "initial data loaded" notification. var initialDataLoaded = false; var ref = new Firebase('https://<your-Firebase>.firebaseio.com'); ref.on('child_added', function(snapshot) { if (initialDataLoaded) { var msg = snapshot.val().msg; // do something here } else { // we are ignoring this child since it is pre-existing data } }); ref.once('value', function(snapshot) { initialDataLoaded = true; }); // Thankfully, Firebase will smartly cache this data, meaning that creating both a child_added // and a value listener will only download the data one time. // Adding new Firebase listeners for data which has already crossed the wire is extremely cheap // and you should feel comfortable doing things like that regularly. // Or one add a timestamp to the children with Firebase.ServerValue.TIMESTAMP, this will be trivial // with startAt
[ "johnkagga@gmail.com" ]
johnkagga@gmail.com
c2a100c939453480a794b27a3c0d73e414023157
0007e1cac6ea95bd6cf8dc9667ad3407b603cdfd
/src/main/java/com/diandiancar/demo/service/impl/CarCategoryServiceImpl.java
25e039259c3189a8efd020ae866947ae185ab033
[]
no_license
viosam/diandiancar
8150c7db75d0a43e573449fdbf5c280077026eb0
2d4dc443afe1c8b2319aaef5e3e6e752ea97cabc
refs/heads/master
2022-11-30T23:41:34.140073
2020-05-30T00:25:51
2020-05-30T00:25:51
183,133,878
0
0
null
2022-11-24T09:59:07
2019-04-24T02:43:34
Java
UTF-8
Java
false
false
1,628
java
package com.diandiancar.demo.service.impl; import com.diandiancar.demo.entity.CarCategory; import com.diandiancar.demo.repository.CarCategoryRepository; import com.diandiancar.demo.service.CarCategoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.List; /** *汽车类型 */ @Service public class CarCategoryServiceImpl implements CarCategoryService { @Autowired private CarCategoryRepository repository; @Override public CarCategory findOne(Integer categoryId) { return repository.findById(categoryId).get(); } @Override public CarCategory save(CarCategory carCategory) { return repository.save(carCategory); } @Override public Page<CarCategory> findAll(Pageable pageable) { return repository.findAll(pageable); } @Override public List<CarCategory> findAll() { return repository.findAll(); } @Override public Page<CarCategory> findByCategoryNameLike(String categoryName, Pageable pageable) { return repository.findByCategoryNameLike("%"+categoryName+"%",pageable); } @Override public List<CarCategory> findByCarCategoryTypeIn(List<Integer> categoryTypeList) { return repository.findByCategoryTypeIn(categoryTypeList); } // @Override // public List<CarCategory> findByCarCategoryTypeIn(List<Integer> categoryTypeList) { // return repository.findByCategoryTypeIn(categoryTypeList); // } }
[ "123@163.com" ]
123@163.com
f7309955f7fc327593dbd62e7760ec9d0da94f32
9ba890fc4c3986b92d96ddd0502cc488c860cfcb
/bankAccount/src/com/company/Main.java
4fba12e351c3e6cb9e122371b30ca3e8b4ee1285
[]
no_license
alhussinosama/JAVA
94e5e3a8ea6df22f88d9015f25b4371a3271aa98
4d388e8a279eded4efb44839747c87ab2c3b39ac
refs/heads/main
2023-01-29T12:06:15.410846
2020-12-07T13:42:18
2020-12-07T13:42:18
312,364,322
1
0
null
null
null
null
UTF-8
Java
false
false
1,103
java
package com.company; public class Main { public static void main(String[] args) { /* - create a new class for a bank account. -create a fields for the account numbers , balance , customer name , email and phone numbers -create (getters a setters) for each field. -create 2 additional methods. 1- to allow the customers to deposit funds / this should increament the balance field. 2- to allow the customers to withdraw funds , this should deduct from the balance fiels. but not allow the withdrawal to complete if their are insufficient funds. - create a various code in the main class . -confirm your code is working. */ Account bobsAccount = new Account( "1235", 0.00 , " Jakob H" , "jakon@gml.com" , "05525586"); System.out.println( bobsAccount.getNumber()); System.out.println( bobsAccount.getBalance()); bobsAccount.withdrawal( 100.0); bobsAccount.deposit(50.0); bobsAccount.withdrawal(100.0); } }
[ "osamahossien@yahoo.com" ]
osamahossien@yahoo.com
325e092139659e5712c0c2973f84471f4af03903
2e7020495313511d2712efd1b56e52ddecc3d0bf
/src/util/trace/query/OrderedClassInstanceDisplaced.java
9fa7235d163364b63c1fae3bbb1a6a569d4b14a0
[]
no_license
pdewan/util
3bc79264ce10afe6337abe6d1128c80a2be54280
7cd83cc286dfb2a5eb87fb54bf74dc42165ceb75
refs/heads/master
2022-06-19T11:03:24.758011
2022-06-09T04:22:27
2022-06-09T04:22:27
16,309,230
0
1
null
null
null
null
UTF-8
Java
false
false
2,485
java
package util.trace.query; import util.trace.Traceable; public class OrderedClassInstanceDisplaced extends OrderedClassInstanceMissing { Integer displacement; public OrderedClassInstanceDisplaced(String aMessage, Integer aTestIndex, Integer aReferenceIndex, Class aPreviousObject, Class anExpectedObject, Class aLaterObject, Integer aDisplacement, Object aFinder) { super(aMessage, aTestIndex, aReferenceIndex, aPreviousObject, anExpectedObject, aLaterObject, aFinder); displacement = aDisplacement; } public OrderedClassInstanceDisplaced(String aMessage, Integer aTestIndex, Integer aReferenceIndex, Class aPreviousObject, Class anExpectedObject, Class aLaterObject, Integer aDisplacement) { super(aMessage, aTestIndex, aReferenceIndex, aPreviousObject, anExpectedObject, aLaterObject); displacement = aDisplacement; } public static OrderedClassInstanceDisplaced toTraceable(String aMessage) { try { return new OrderedClassInstanceDisplaced (aMessage, TraceableIndices.getIndex1(aMessage), TraceableIndices.getIndex2(aMessage), forName(getPrevious(aMessage)), forName(getExpected(aMessage)), forName(getLater(aMessage)), getDisplacement(aMessage) ); } catch (Exception e) { e.printStackTrace(); return null; } } public static Integer getDisplacement(String aMessage) { return Integer.parseInt(Traceable.getArgs(aMessage, DISPLACEMENT).get(0)); } public static final String DISPLACEMENT = "DISPLACEMENT"; public static String toString (Integer aTestIndex, Integer aReferenceIndex, Class aPreviousObject, Class anExpectedObject, Class aLaterObject, Integer aDisplacement) { return toString(aTestIndex, aReferenceIndex, aPreviousObject, anExpectedObject, aLaterObject) + DISPLACEMENT + Traceable.FLAT_LEFT_MARKER + aDisplacement + Traceable.FLAT_RIGHT_MARKER; } public static OrderedClassInstanceDisplaced newCase ( Integer aTestIndex, Integer aReferenceIndex, Class aPreviousObject, Class anExpectedObject, Class aLaterObject, Integer aDisplacement, Object aFinder) { String aMessage = toString(aTestIndex, aReferenceIndex, aPreviousObject, anExpectedObject, aLaterObject); OrderedClassInstanceDisplaced retVal = new OrderedClassInstanceDisplaced(aMessage, aTestIndex, aReferenceIndex, aPreviousObject, anExpectedObject, aLaterObject, aDisplacement, aFinder); retVal.announce(); return retVal; } }
[ "dewan@cs.unc.edu" ]
dewan@cs.unc.edu
19218da3c07a210df37199fc5f09bdccf22f6664
84fc9e2560b86d3564d98f4c2b4d9996ce995d90
/Portfolio2/src/com/company/Driver.java
c6c4f3e146b04fad09f049eec7b4f62c2f537969
[]
no_license
JacobGlumby1/Algorithms_and_datastructures
74c40bfd68c822d0ba842cd73b6a18ee71b291a5
710cb74c9338f767f0c181282cbe095c505e8fab
refs/heads/main
2023-01-23T14:42:01.076768
2020-11-25T09:03:28
2020-11-25T09:03:28
292,507,648
0
0
null
null
null
null
UTF-8
Java
false
false
585
java
package com.company; public class Driver { public static int MinimumSteps(int BoardHeight, int BoardWidth, int KnightStartXPosition, int KnightStartYPosition, int KnightEndXPosition, int KnightEndYPosition) { Tree tree = new Tree(BoardHeight,BoardWidth,KnightStartXPosition,KnightStartYPosition,KnightEndXPosition,KnightEndYPosition); return tree.getEndNode().getDepth(); } public static void main(String[] args) { // The example provided. System.out.println(MinimumSteps(8,8,4,4,3,2)); } }
[ "Jacso18@student.sdu.dk" ]
Jacso18@student.sdu.dk
7e727db21335a22c9bc2ef66e18c1509aa22a6f7
3ff2d9771da9401cf806ad82fb96dc01d62ace43
/Easy_Education/src/com/hwd/cw/test/news_detail_Activity.java
42110b588c8a961f50299ced3ed6c5e74a8da432
[]
no_license
nuaabox/ES
bcf9926475f140a8e537171723234a52b091ca96
da43d2293678bd517ec8d860cfd18aeb98dc0684
refs/heads/master
2021-01-10T05:49:37.657563
2016-01-20T05:56:29
2016-01-20T05:56:29
49,873,434
0
0
null
null
null
null
UTF-8
Java
false
false
2,188
java
package com.hwd.cw.test; import java.util.HashMap; import java.util.Map; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class news_detail_Activity extends Activity{ private ImageView news_back_btn; private TextView news_title; private TextView news_date; private TextView news_author; private ImageView news_img; private TextView news_text; @SuppressLint("NewApi") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); this.setContentView(R.layout.news_detail_xml); ExitApplication.getInstance().addActivity(this); news_back_btn=(ImageView)this.findViewById(R.id.news_back_main); news_title=(TextView)this.findViewById(R.id.news_title); news_date=(TextView)this.findViewById(R.id.news_date); news_author=(TextView)this.findViewById(R.id.news_author); news_text=(TextView)this.findViewById(R.id.news_text); news_img=(ImageView)this.findViewById(R.id.news_img); Intent intent=this.getIntent(); int n=intent.getExtras().getInt("position"); news_img.setBackground(MainActivity.news_pic_list.get(n)); Map map=MainActivity.news_list.get(n); news_title.setText((String) map.get("headline")); news_date.setText((String) map.get("time")); news_author.setText((String)map.get("author")); news_text.setText((String)map.get("content")); news_back_btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { // TODO 锟皆讹拷锟斤拷锟缴的凤拷锟斤拷锟斤拷锟� news_detail_Activity.this.finish(); } }); } }
[ "2594299515@qq.com" ]
2594299515@qq.com
6afb7ab0154ccf0c9c5ebd045360419fcfb6d346
2f044ea2dce3f336d8116a8da2f2719cdfb59133
/src/main/java/com/rentamaquina/maquinaria/app/repositories/AdminRepository.java
6514aa065a30009cb0b504c744a19f1ede62f28c
[]
no_license
PaulaRocha19/GitReto4
0fd5354903468936318ccbc7a7cdb8fa69a17ca4
88f1bdf07c30a4de24dd15d6de97421b7cbf9482
refs/heads/master
2023-08-30T12:00:53.862562
2021-11-02T19:40:19
2021-11-02T19:40:19
420,830,115
0
0
null
null
null
null
UTF-8
Java
false
false
1,359
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.rentamaquina.maquinaria.app.repositories; import com.rentamaquina.maquinaria.app.entities.Admin; import com.rentamaquina.maquinaria.app.repositories.crud.AdminCrudRepository; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; /** * * @author RubielaCifuentes */ @Repository public class AdminRepository { @Autowired private AdminCrudRepository adminCrudRepository; /** * Select * @return */ public List<Admin> getAll() { return (List<Admin>) adminCrudRepository.findAll(); } /** * Insert * @param admin * @return */ public Admin save(Admin admin) { return adminCrudRepository.save(admin); } /** * Buscar registro * @param adminId * @return */ public Optional<Admin> getAdmin(Integer adminId) { return adminCrudRepository.findById(adminId); } /** * Delete * @param admin */ public void delete(Admin admin) { adminCrudRepository.delete(admin); } }
[ "91512993+PaulaRocha19@users.noreply.github.com" ]
91512993+PaulaRocha19@users.noreply.github.com
b88a1da77f313347007dd5e157e76e280d56fae2
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/eclipseswt_cluster/35413/tar_1.java
7713836b02eab0a20c058f207db67550b5e0dd3f
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
139,366
java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.widgets; import org.eclipse.swt.internal.win32.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.accessibility.*; /** * Control is the abstract superclass of all windowed user interface classes. * <p> * <dl> * <dt><b>Styles:</b> * <dd>BORDER</dd> * <dd>LEFT_TO_RIGHT, RIGHT_TO_LEFT</dd> * <dt><b>Events:</b> * <dd>FocusIn, FocusOut, Help, KeyDown, KeyUp, MouseDoubleClick, MouseDown, MouseEnter, * MouseExit, MouseHover, MouseUp, MouseMove, Move, Paint, Resize</dd> * </dl> * <p> * Only one of LEFT_TO_RIGHT or RIGHT_TO_LEFT may be specified. * </p><p> * IMPORTANT: This class is intended to be subclassed <em>only</em> * within the SWT implementation. * </p> * * Note: Only one of LEFT_TO_RIGHT and RIGHT_TO_LEFT may be specified. */ public abstract class Control extends Widget implements Drawable { /** * the handle to the OS resource * (Warning: This field is platform dependent) */ public int handle; Composite parent; Cursor cursor; Menu menu; String toolTipText; Object layoutData; Accessible accessible; int drawCount, foreground, background; static final short [] ACCENTS = new short [] {'~', '`', '\'', '^', '"'}; /** * Prevents uninitialized instances from being created outside the package. */ Control () { } /** * Constructs a new instance of this class given its parent * and a style value describing its behavior and appearance. * <p> * The style value is either one of the style constants defined in * class <code>SWT</code> which is applicable to instances of this * class, or must be built by <em>bitwise OR</em>'ing together * (that is, using the <code>int</code> "|" operator) two or more * of those <code>SWT</code> style constants. The class description * lists the style constants that are applicable to the class. * Style bits are also inherited from superclasses. * </p> * * @param parent a composite control which will be the parent of the new instance (cannot be null) * @param style the style of control to construct * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li> * </ul> * * @see SWT#BORDER * @see Widget#checkSubclass * @see Widget#getStyle */ public Control (Composite parent, int style) { super (parent, style); this.parent = parent; createWidget (); } /** * Adds the listener to the collection of listeners who will * be notified when the control is moved or resized, by sending * it one of the messages defined in the <code>ControlListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see ControlListener * @see #removeControlListener */ public void addControlListener(ControlListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Resize,typedListener); addListener (SWT.Move,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the control gains or loses focus, by sending * it one of the messages defined in the <code>FocusListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see FocusListener * @see #removeFocusListener */ public void addFocusListener (FocusListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.FocusIn,typedListener); addListener (SWT.FocusOut,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when help events are generated for the control, * by sending it one of the messages defined in the * <code>HelpListener</code> interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see HelpListener * @see #removeHelpListener */ public void addHelpListener (HelpListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Help, typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when keys are pressed and released on the system keyboard, by sending * it one of the messages defined in the <code>KeyListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see KeyListener * @see #removeKeyListener */ public void addKeyListener (KeyListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.KeyUp,typedListener); addListener (SWT.KeyDown,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when mouse buttons are pressed and released, by sending * it one of the messages defined in the <code>MouseListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseListener * @see #removeMouseListener */ public void addMouseListener (MouseListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.MouseDown,typedListener); addListener (SWT.MouseUp,typedListener); addListener (SWT.MouseDoubleClick,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the mouse passes or hovers over controls, by sending * it one of the messages defined in the <code>MouseTrackListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseTrackListener * @see #removeMouseTrackListener */ public void addMouseTrackListener (MouseTrackListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.MouseEnter,typedListener); addListener (SWT.MouseExit,typedListener); addListener (SWT.MouseHover,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the mouse moves, by sending it one of the * messages defined in the <code>MouseMoveListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseMoveListener * @see #removeMouseMoveListener */ public void addMouseMoveListener (MouseMoveListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.MouseMove,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when the receiver needs to be painted, by sending it * one of the messages defined in the <code>PaintListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see PaintListener * @see #removePaintListener */ public void addPaintListener (PaintListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Paint,typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when traversal events occur, by sending it * one of the messages defined in the <code>TraverseListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see TraverseListener * @see #removeTraverseListener */ public void addTraverseListener (TraverseListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Traverse,typedListener); } abstract int callWindowProc (int msg, int wParam, int lParam); void checkMirrored () { if ((style & SWT.RIGHT_TO_LEFT) != 0) { int bits = OS.GetWindowLong (handle, OS.GWL_EXSTYLE); if ((bits & OS.WS_EX_LAYOUTRTL) != 0) style |= SWT.MIRRORED; } } /** * Returns the preferred size of the receiver. * <p> * The <em>preferred size</em> of a control is the size that it would * best be displayed at. The width hint and height hint arguments * allow the caller to ask a control questions such as "Given a particular * width, how high does the control need to be to show all of the contents?" * To indicate that the caller does not wish to constrain a particular * dimension, the constant <code>SWT.DEFAULT</code> is passed for the hint. * </p> * * @param wHint the width hint (can be <code>SWT.DEFAULT</code>) * @param hHint the height hint (can be <code>SWT.DEFAULT</code>) * @return the preferred size of the control * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Layout * @see #getBorderWidth * @see #getBounds * @see #getSize * @see #pack * @see "computeTrim, getClientArea for controls that implement them" */ public Point computeSize (int wHint, int hHint) { return computeSize (wHint, hHint, true); } /** * Returns the preferred size of the receiver. * <p> * The <em>preferred size</em> of a control is the size that it would * best be displayed at. The width hint and height hint arguments * allow the caller to ask a control questions such as "Given a particular * width, how high does the control need to be to show all of the contents?" * To indicate that the caller does not wish to constrain a particular * dimension, the constant <code>SWT.DEFAULT</code> is passed for the hint. * </p><p> * If the changed flag is <code>true</code>, it indicates that the receiver's * <em>contents</em> have changed, therefore any caches that a layout manager * containing the control may have been keeping need to be flushed. When the * control is resized, the changed flag will be <code>false</code>, so layout * manager caches can be retained. * </p> * * @param wHint the width hint (can be <code>SWT.DEFAULT</code>) * @param hHint the height hint (can be <code>SWT.DEFAULT</code>) * @param changed <code>true</code> if the control's contents have changed, and <code>false</code> otherwise * @return the preferred size of the control. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Layout * @see #getBorderWidth * @see #getBounds * @see #getSize * @see #pack * @see "computeTrim, getClientArea for controls that implement them" */ public Point computeSize (int wHint, int hHint, boolean changed) { checkWidget (); int width = DEFAULT_WIDTH; int height = DEFAULT_HEIGHT; if (wHint != SWT.DEFAULT) width = wHint; if (hHint != SWT.DEFAULT) height = hHint; int border = getBorderWidth (); width += border * 2; height += border * 2; return new Point (width, height); } Control computeTabGroup () { if (isTabGroup ()) return this; return parent.computeTabGroup (); } Control computeTabRoot () { Control [] tabList = parent._getTabList (); if (tabList != null) { int index = 0; while (index < tabList.length) { if (tabList [index] == this) break; index++; } if (index == tabList.length) { if (isTabGroup ()) return this; } } return parent.computeTabRoot (); } Control [] computeTabList () { if (isTabGroup ()) { if (getVisible () && getEnabled ()) { return new Control [] {this}; } } return new Control [0]; } void createHandle () { int hwndParent = widgetParent (); handle = OS.CreateWindowEx ( widgetExtStyle (), windowClass (), null, widgetStyle (), OS.CW_USEDEFAULT, 0, OS.CW_USEDEFAULT, 0, hwndParent, 0, OS.GetModuleHandle (null), widgetCreateStruct ()); if (handle == 0) error (SWT.ERROR_NO_HANDLES); int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.WS_CHILD) != 0) { OS.SetWindowLong (handle, OS.GWL_ID, handle); } if (OS.IsDBLocale && hwndParent != 0) { int hIMC = OS.ImmGetContext (hwndParent); OS.ImmAssociateContext (handle, hIMC); OS.ImmReleaseContext (hwndParent, hIMC); } } void createWidget () { foreground = background = -1; checkOrientation (parent); createHandle (); register (); subclass (); setDefaultFont (); checkMirrored (); } int defaultBackground () { if (OS.IsWinCE) return OS.GetSysColor (OS.COLOR_WINDOW); return OS.GetSysColor (OS.COLOR_BTNFACE); } int defaultFont () { return display.systemFont (); } int defaultForeground () { return OS.GetSysColor (OS.COLOR_WINDOWTEXT); } void deregister () { display.removeControl (handle); } void destroyWidget () { int hwnd = handle; releaseHandle (); if (hwnd != 0) { OS.DestroyWindow (hwnd); } } void drawBackground (int hDC) { RECT rect = new RECT (); OS.GetClientRect (handle, rect); drawBackground (hDC, rect); } void drawBackground (int hDC, RECT rect) { int hPalette = display.hPalette; if (hPalette != 0) { OS.SelectPalette (hDC, hPalette, false); OS.RealizePalette (hDC); } int pixel = getBackgroundPixel (); int hBrush = findBrush (pixel); OS.FillRect (hDC, rect, hBrush); } int findBrush (int pixel) { return parent.findBrush (pixel); } Cursor findCursor () { if (cursor != null) return cursor; return parent.findCursor (); } Menu [] findMenus (Control control) { if (menu != null && this != control) return new Menu [] {menu}; return new Menu [0]; } char findMnemonic (String string) { int index = 0; int length = string.length (); do { while (index < length && string.charAt (index) != '&') index++; if (++index >= length) return '\0'; if (string.charAt (index) != '&') return string.charAt (index); index++; } while (index < length); return '\0'; } void fixChildren (Shell newShell, Shell oldShell, Decorations newDecorations, Decorations oldDecorations, Menu [] menus) { oldShell.fixShell (newShell, this); oldDecorations.fixDecorations (newDecorations, this, menus); } void fixFocus () { Shell shell = getShell (); Control control = this; while ((control = control.parent) != null) { if (control.setFocus () || control == shell) return; } OS.SetFocus (0); } /** * Forces the receiver to have the <em>keyboard focus</em>, causing * all keyboard events to be delivered to it. * * @return <code>true</code> if the control got focus, and <code>false</code> if it was unable to. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #setFocus */ public boolean forceFocus () { checkWidget (); Decorations shell = menuShell (); shell.setSavedFocus (this); if (!isEnabled () || !isVisible () || !isActive ()) return false; if (isFocusControl ()) return true; /* * This code is intentionally commented. * * When setting focus to a control, it is * possible that application code can set * the focus to another control inside of * WM_SETFOCUS. In this case, the original * control will no longer have the focus * and the call to setFocus() will return * false indicating failure. * * We are still working on a solution at * this time. */ // if (OS.GetFocus () != OS.SetFocus (handle)) return false; OS.SetFocus (handle); return isFocusControl (); } void forceResize () { if (parent == null) return; WINDOWPOS [] lpwp = parent.lpwp; if (lpwp == null) return; for (int i=0; i<lpwp.length; i++) { WINDOWPOS wp = lpwp [i]; if (wp != null && wp.hwnd == handle) { /* * This code is intentionally commented. All widgets that * are created by SWT have WS_CLIPSIBLINGS to ensure that * application code does not draw outside of the control. */ // int count = parent.getChildrenCount (); // if (count > 1) { // int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); // if ((bits & OS.WS_CLIPSIBLINGS) == 0) wp.flags |= OS.SWP_NOCOPYBITS; // } OS.SetWindowPos (wp.hwnd, 0, wp.x, wp.y, wp.cx, wp.cy, wp.flags); lpwp [i] = null; return; } } } /** * Returns the accessible object for the receiver. * If this is the first time this object is requested, * then the object is created and returned. * * @return the accessible object * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Accessible#addAccessibleListener * @see Accessible#addAccessibleControlListener * * @since 2.0 */ public Accessible getAccessible () { checkWidget (); if (accessible == null) accessible = new_Accessible (this); return accessible; } /** * Returns the receiver's background color. * * @return the background color * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Color getBackground () { checkWidget (); return Color.win32_new (display, getBackgroundPixel ()); } int getBackgroundPixel () { if (background == -1) return defaultBackground (); return background; } /** * Returns the receiver's border width. * * @return the border width * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getBorderWidth () { checkWidget (); int bits1 = OS.GetWindowLong (handle, OS.GWL_EXSTYLE); if ((bits1 & OS.WS_EX_CLIENTEDGE) != 0) return OS.GetSystemMetrics (OS.SM_CXEDGE); if ((bits1 & OS.WS_EX_STATICEDGE) != 0) return OS.GetSystemMetrics (OS.SM_CXBORDER); int bits2 = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits2 & OS.WS_BORDER) != 0) return OS.GetSystemMetrics (OS.SM_CXBORDER); return 0; } /** * Returns a rectangle describing the receiver's size and location * relative to its parent (or its display if its parent is null). * * @return the receiver's bounding rectangle * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Rectangle getBounds () { checkWidget (); forceResize (); RECT rect = new RECT (); OS.GetWindowRect (handle, rect); int hwndParent = parent == null ? 0 : parent.handle; OS.MapWindowPoints (0, hwndParent, rect, 2); int width = rect.right - rect.left; int height = rect.bottom - rect.top; return new Rectangle (rect.left, rect.top, width, height); } int getCodePage () { if (OS.IsUnicode) return OS.CP_ACP; int hFont = OS.SendMessage (handle, OS.WM_GETFONT, 0, 0); LOGFONT logFont = OS.IsUnicode ? (LOGFONT) new LOGFONTW () : new LOGFONTA (); OS.GetObject (hFont, LOGFONT.sizeof, logFont); int cs = logFont.lfCharSet & 0xFF; int [] lpCs = new int [8]; if (OS.TranslateCharsetInfo (cs, lpCs, OS.TCI_SRCCHARSET)) { return lpCs [1]; } return OS.GetACP (); } /** * Returns <code>true</code> if the receiver is enabled, and * <code>false</code> otherwise. A disabled control is typically * not selectable from the user interface and draws with an * inactive or "grayed" look. * * @return the receiver's enabled state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #isEnabled */ public boolean getEnabled () { checkWidget (); return OS.IsWindowEnabled (handle); } /** * Returns the font that the receiver will use to paint textual information. * * @return the receiver's font * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Font getFont () { checkWidget (); int hFont = OS.SendMessage (handle, OS.WM_GETFONT, 0, 0); if (hFont == 0) hFont = defaultFont (); return Font.win32_new (display, hFont); } /** * Returns the foreground color that the receiver will use to draw. * * @return the receiver's foreground color * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Color getForeground () { checkWidget (); return Color.win32_new (display, getForegroundPixel ()); } int getForegroundPixel () { if (foreground == -1) return defaultForeground (); return foreground; } /** * Returns layout data which is associated with the receiver. * * @return the receiver's layout data * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Object getLayoutData () { checkWidget (); return layoutData; } /** * Returns a point describing the receiver's location relative * to its parent (or its display if its parent is null). * * @return the receiver's location * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point getLocation () { checkWidget (); forceResize (); RECT rect = new RECT (); OS.GetWindowRect (handle, rect); int hwndParent = parent == null ? 0 : parent.handle; OS.MapWindowPoints (0, hwndParent, rect, 2); return new Point (rect.left, rect.top); } /** * Returns the receiver's pop up menu if it has one, or null * if it does not. All controls may optionally have a pop up * menu that is displayed when the user requests one for * the control. The sequence of key strokes, button presses * and/or button releases that are used to request a pop up * menu is platform specific. * * @return the receiver's menu * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Menu getMenu () { checkWidget (); return menu; } /** * Returns the receiver's monitor. * * @return the receiver's monitor * * @since 3.0 */ public Monitor getMonitor () { checkWidget (); if (OS.IsWinCE || (OS.WIN32_MAJOR << 16 | OS.WIN32_MINOR) < (4 << 16 | 10)) { return display.getPrimaryMonitor (); } int hmonitor = OS.MonitorFromWindow (handle, OS.MONITOR_DEFAULTTONEAREST); MONITORINFO lpmi = new MONITORINFO (); lpmi.cbSize = MONITORINFO.sizeof; OS.GetMonitorInfo (hmonitor, lpmi); Monitor monitor = new Monitor (); monitor.handle = hmonitor; monitor.x = lpmi.rcMonitor_left; monitor.y = lpmi.rcMonitor_top; monitor.width = lpmi.rcMonitor_right - lpmi.rcMonitor_left; monitor.height = lpmi.rcMonitor_bottom - lpmi.rcMonitor_top; monitor.clientX = lpmi.rcWork_left; monitor.clientY = lpmi.rcWork_top; monitor.clientWidth = lpmi.rcWork_right - lpmi.rcWork_left; monitor.clientHeight = lpmi.rcWork_bottom - lpmi.rcWork_top; return monitor; } /** * Returns the receiver's parent, which must be a <code>Composite</code> * or null when the receiver is a shell that was created with null or * a display for a parent. * * @return the receiver's parent * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Composite getParent () { checkWidget (); return parent; } Control [] getPath () { int count = 0; Shell shell = getShell (); Control control = this; while (control != shell) { count++; control = control.parent; } control = this; Control [] result = new Control [count]; while (control != shell) { result [--count] = control; control = control.parent; } return result; } /** * Returns the receiver's shell. For all controls other than * shells, this simply returns the control's nearest ancestor * shell. Shells return themselves, even if they are children * of other shells. * * @return the receiver's shell * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #getParent */ public Shell getShell () { checkWidget (); return parent.getShell (); } /** * Returns a point describing the receiver's size. The * x coordinate of the result is the width of the receiver. * The y coordinate of the result is the height of the * receiver. * * @return the receiver's size * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point getSize () { checkWidget (); forceResize (); RECT rect = new RECT (); OS.GetWindowRect (handle, rect); int width = rect.right - rect.left; int height = rect.bottom - rect.top; return new Point (width, height); } /** * Returns the receiver's tool tip text, or null if it has * not been set. * * @return the receiver's tool tip text * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public String getToolTipText () { checkWidget (); return toolTipText; } /** * Returns <code>true</code> if the receiver is visible, and * <code>false</code> otherwise. * <p> * If one of the receiver's ancestors is not visible or some * other condition makes the receiver not visible, this method * may still indicate that it is considered visible even though * it may not actually be showing. * </p> * * @return the receiver's visibility state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean getVisible () { checkWidget (); if (drawCount != 0) return (style & HIDDEN) == 0; int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); return (bits & OS.WS_VISIBLE) != 0; } boolean hasCursor () { RECT rect = new RECT (); if (!OS.GetClientRect (handle, rect)) return false; if (OS.MapWindowPoints (handle, 0, rect, 2) == 0) return false; POINT pt = new POINT (); return (OS.GetCursorPos (pt) && OS.PtInRect (rect, pt)); } boolean hasFocus () { /* * If a non-SWT child of the control has focus, * then this control is considered to have focus * even though it does not have focus in Windows. */ int hwndFocus = OS.GetFocus (); while (hwndFocus != 0) { if (hwndFocus == handle) return true; if (display.getControl (hwndFocus) != null) { return false; } hwndFocus = OS.GetParent (hwndFocus); } return false; } /** * Invokes platform specific functionality to allocate a new GC handle. * <p> * <b>IMPORTANT:</b> This method is <em>not</em> part of the public * API for <code>Control</code>. It is marked public only so that it * can be shared within the packages provided by SWT. It is not * available on all platforms, and should never be called from * application code. * </p> * * @param data the platform specific GC data * @return the platform specific GC handle */ public int internal_new_GC (GCData data) { checkWidget(); int hDC; if (data == null || data.ps == null) { hDC = OS.GetDC (handle); } else { hDC = OS.BeginPaint (handle, data.ps); } if (hDC == 0) SWT.error(SWT.ERROR_NO_HANDLES); if (data != null) { if ((OS.WIN32_MAJOR << 16 | OS.WIN32_MINOR) >= (4 << 16 | 10)) { int mask = SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT; if ((data.style & mask) != 0) { data.layout = (data.style & SWT.RIGHT_TO_LEFT) != 0 ? OS.LAYOUT_RTL : 0; } else { int flags = OS.GetLayout (hDC); if ((flags & OS.LAYOUT_RTL) != 0) { data.style |= SWT.RIGHT_TO_LEFT | SWT.MIRRORED; } else { data.style |= SWT.LEFT_TO_RIGHT; } } } else { data.style |= SWT.LEFT_TO_RIGHT; } data.device = display; data.foreground = getForegroundPixel (); data.background = getBackgroundPixel (); data.hFont = OS.SendMessage (handle, OS.WM_GETFONT, 0, 0); data.hwnd = handle; } return hDC; } /** * Invokes platform specific functionality to dispose a GC handle. * <p> * <b>IMPORTANT:</b> This method is <em>not</em> part of the public * API for <code>Control</code>. It is marked public only so that it * can be shared within the packages provided by SWT. It is not * available on all platforms, and should never be called from * application code. * </p> * * @param handle the platform specific GC handle * @param data the platform specific GC data */ public void internal_dispose_GC (int hDC, GCData data) { checkWidget (); if (data == null || data.ps == null) { OS.ReleaseDC (handle, hDC); } else { OS.EndPaint (handle, data.ps); } } boolean isActive () { Shell shell = null; Shell [] modalShells = display.modalShells; if (modalShells != null) { int bits = SWT.APPLICATION_MODAL | SWT.SYSTEM_MODAL; int index = modalShells.length; while (--index >= 0) { Shell modal = modalShells [index]; if (modal != null) { if ((modal.style & bits) != 0) { Control control = this; while (control != null) { if (control == modal) break; control = control.parent; } if (control != modal) return false; break; } if ((modal.style & SWT.PRIMARY_MODAL) != 0) { if (shell == null) shell = getShell (); if (modal.parent == shell) return false; } } } } if (shell == null) shell = getShell (); return shell.getEnabled (); } /** * Returns <code>true</code> if the receiver is enabled and all * of the receiver's ancestors are enabled, and <code>false</code> * otherwise. A disabled control is typically not selectable from the * user interface and draws with an inactive or "grayed" look. * * @return the receiver's enabled state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #getEnabled */ public boolean isEnabled () { checkWidget (); return getEnabled () && parent.isEnabled (); } /** * Returns <code>true</code> if the receiver has the user-interface * focus, and <code>false</code> otherwise. * * @return the receiver's focus state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean isFocusControl () { checkWidget (); return hasFocus (); } boolean isFocusAncestor () { Control control = display.getFocusControl (); while (control != null && control != this) { control = control.parent; } return control == this; } /** * Returns <code>true</code> if the underlying operating * system supports this reparenting, otherwise <code>false</code> * * @return <code>true</code> if the widget can be reparented, otherwise <code>false</code> * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean isReparentable () { checkWidget (); return true; } boolean isShowing () { /* * This is not complete. Need to check if the * widget is obscurred by a parent or sibling. */ if (!isVisible ()) return false; Control control = this; while (control != null) { Point size = control.getSize (); if (size.x == 0 || size.y == 0) { return false; } control = control.parent; } return true; /* * Check to see if current damage is included. */ // if (!OS.IsWindowVisible (handle)) return false; // int flags = OS.DCX_CACHE | OS.DCX_CLIPCHILDREN | OS.DCX_CLIPSIBLINGS; // int hDC = OS.GetDCEx (handle, 0, flags); // int result = OS.GetClipBox (hDC, new RECT ()); // OS.ReleaseDC (handle, hDC); // return result != OS.NULLREGION; } boolean isTabGroup () { Control [] tabList = parent._getTabList (); if (tabList != null) { for (int i=0; i<tabList.length; i++) { if (tabList [i] == this) return true; } } int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); return (bits & OS.WS_TABSTOP) != 0; } boolean isTabItem () { Control [] tabList = parent._getTabList (); if (tabList != null) { for (int i=0; i<tabList.length; i++) { if (tabList [i] == this) return false; } } int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.WS_TABSTOP) != 0) return false; int code = OS.SendMessage (handle, OS.WM_GETDLGCODE, 0, 0); if ((code & OS.DLGC_STATIC) != 0) return false; if ((code & OS.DLGC_WANTALLKEYS) != 0) return false; if ((code & OS.DLGC_WANTARROWS) != 0) return false; if ((code & OS.DLGC_WANTTAB) != 0) return false; return true; } /** * Returns <code>true</code> if the receiver is visible and all * of the receiver's ancestors are visible and <code>false</code> * otherwise. * * @return the receiver's visibility state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #getVisible */ public boolean isVisible () { checkWidget (); return OS.IsWindowVisible (handle); } Decorations menuShell () { return parent.menuShell (); } boolean mnemonicHit (char key) { return false; } boolean mnemonicMatch (char key) { return false; } /** * Moves the receiver above the specified control in the * drawing order. If the argument is null, then the receiver * is moved to the top of the drawing order. The control at * the top of the drawing order will not be covered by other * controls even if they occupy intersecting areas. * * @param the sibling control (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the control has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void moveAbove (Control control) { checkWidget (); int hwndAbove = OS.HWND_TOP; if (control != null) { if (control.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); if (parent != control.parent) return; int hwnd = control.handle; if (hwnd == 0 || hwnd == handle) return; hwndAbove = OS.GetWindow (hwnd, OS.GW_HWNDPREV); /* * Bug in Windows. For some reason, when GetWindow () * with GW_HWNDPREV is used to query the previous window * in the z-order with the first child, Windows returns * the first child instead of NULL. The fix is to detect * this case and move the control to the top. */ if (hwndAbove == 0 || hwndAbove == hwnd) { hwndAbove = OS.HWND_TOP; } } int flags = OS.SWP_NOSIZE | OS.SWP_NOMOVE | OS.SWP_NOACTIVATE; OS.SetWindowPos (handle, hwndAbove, 0, 0, 0, 0, flags); } /** * Moves the receiver below the specified control in the * drawing order. If the argument is null, then the receiver * is moved to the bottom of the drawing order. The control at * the bottom of the drawing order will be covered by all other * controls which occupy intersecting areas. * * @param the sibling control (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the control has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void moveBelow (Control control) { checkWidget (); int hwndAbove = OS.HWND_BOTTOM; if (control != null) { if (control.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); if (parent != control.parent) return; hwndAbove = control.handle; } if (hwndAbove == 0 || hwndAbove == handle) return; int flags = OS.SWP_NOSIZE | OS.SWP_NOMOVE | OS.SWP_NOACTIVATE; OS.SetWindowPos (handle, hwndAbove, 0, 0, 0, 0, flags); } Accessible new_Accessible (Control control) { return Accessible.internal_new_Accessible (this); } /** * Causes the receiver to be resized to its preferred size. * For a composite, this involves computing the preferred size * from its layout, if there is one. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #computeSize */ public void pack () { checkWidget (); pack (true); } /** * Causes the receiver to be resized to its preferred size. * For a composite, this involves computing the preferred size * from its layout, if there is one. * <p> * If the changed flag is <code>true</code>, it indicates that the receiver's * <em>contents</em> have changed, therefore any caches that a layout manager * containing the control may have been keeping need to be flushed. When the * control is resized, the changed flag will be <code>false</code>, so layout * manager caches can be retained. * </p> * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #computeSize */ public void pack (boolean changed) { checkWidget (); setSize (computeSize (SWT.DEFAULT, SWT.DEFAULT, changed)); } /** * Causes the entire bounds of the receiver to be marked * as needing to be redrawn. The next time a paint request * is processed, the control will be completely painted. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #update */ public void redraw () { checkWidget (); if (!OS.IsWindowVisible (handle)) return; if (OS.IsWinCE) { OS.InvalidateRect (handle, null, true); } else { int flags = OS.RDW_ERASE | OS.RDW_FRAME | OS.RDW_INVALIDATE; OS.RedrawWindow (handle, null, 0, flags); } } /** * Causes the rectangular area of the receiver specified by * the arguments to be marked as needing to be redrawn. * The next time a paint request is processed, that area of * the receiver will be painted. If the <code>all</code> flag * is <code>true</code>, any children of the receiver which * intersect with the specified area will also paint their * intersecting areas. If the <code>all</code> flag is * <code>false</code>, the children will not be painted. * * @param x the x coordinate of the area to draw * @param y the y coordinate of the area to draw * @param width the width of the area to draw * @param height the height of the area to draw * @param all <code>true</code> if children should redraw, and <code>false</code> otherwise * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #update */ public void redraw (int x, int y, int width, int height, boolean all) { checkWidget (); if (width <= 0 || height <= 0) return; if (!OS.IsWindowVisible (handle)) return; RECT rect = new RECT (); OS.SetRect (rect, x, y, x + width, y + height); if (OS.IsWinCE) { OS.InvalidateRect (handle, rect, true); } else { int flags = OS.RDW_ERASE | OS.RDW_FRAME | OS.RDW_INVALIDATE; if (all) flags |= OS.RDW_ALLCHILDREN; OS.RedrawWindow (handle, rect, 0, flags); } } void register () { display.addControl (handle, this); } void releaseChild () { parent.removeControl (this); } void releaseHandle () { super.releaseHandle (); handle = 0; } void releaseWidget () { super.releaseWidget (); if (OS.IsDBLocale) { OS.ImmAssociateContext (handle, 0); } if (toolTipText != null) { Shell shell = getShell (); shell.setToolTipText (handle, null); } toolTipText = null; if (menu != null && !menu.isDisposed ()) { menu.dispose (); } menu = null; cursor = null; deregister (); unsubclass (); parent = null; layoutData = null; if (accessible != null) { accessible.internal_dispose_Accessible (); } accessible = null; } /** * Removes the listener from the collection of listeners who will * be notified when the control is moved or resized. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see ControlListener * @see #addControlListener */ public void removeControlListener (ControlListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.Move, listener); eventTable.unhook (SWT.Resize, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the control gains or loses focus. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see FocusListener * @see #addFocusListener */ public void removeFocusListener(FocusListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.FocusIn, listener); eventTable.unhook (SWT.FocusOut, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the help events are generated for the control. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see HelpListener * @see #addHelpListener */ public void removeHelpListener (HelpListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.Help, listener); } /** * Removes the listener from the collection of listeners who will * be notified when keys are pressed and released on the system keyboard. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see KeyListener * @see #addKeyListener */ public void removeKeyListener(KeyListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.KeyUp, listener); eventTable.unhook (SWT.KeyDown, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the mouse passes or hovers over controls. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseTrackListener * @see #addMouseTrackListener */ public void removeMouseTrackListener(MouseTrackListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.MouseEnter, listener); eventTable.unhook (SWT.MouseExit, listener); eventTable.unhook (SWT.MouseHover, listener); } /** * Removes the listener from the collection of listeners who will * be notified when mouse buttons are pressed and released. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseListener * @see #addMouseListener */ public void removeMouseListener (MouseListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.MouseDown, listener); eventTable.unhook (SWT.MouseUp, listener); eventTable.unhook (SWT.MouseDoubleClick, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the mouse moves. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see MouseMoveListener * @see #addMouseMoveListener */ public void removeMouseMoveListener(MouseMoveListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.MouseMove, listener); } /** * Removes the listener from the collection of listeners who will * be notified when the receiver needs to be painted. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see PaintListener * @see #addPaintListener */ public void removePaintListener(PaintListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook(SWT.Paint, listener); } /** * Removes the listener from the collection of listeners who will * be notified when traversal events occur. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see TraverseListener * @see #addTraverseListener */ public void removeTraverseListener(TraverseListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.Traverse, listener); } boolean sendKeyEvent (int type, int msg, int wParam, int lParam) { Event event = new Event (); if (!setKeyState (event, type)) return true; return sendKeyEvent (type, msg, wParam, lParam, event); } boolean sendKeyEvent (int type, int msg, int wParam, int lParam, Event event) { sendEvent (type, event); // widget could be disposed at this point /* * It is possible (but unlikely), that application * code could have disposed the widget in the key * events. If this happens, end the processing of * the key by returning false. */ if (isDisposed ()) return false; return event.doit; } boolean sendFocusEvent (int type, int hwnd) { Shell shell = getShell (); /* * It is possible (but unlikely), that application * code could have disposed the widget in the focus * out event. If this happens keep going to send * the deactivate events. */ sendEvent (type); // widget could be disposed at this point switch (type) { case SWT.FocusIn: /* * It is possible that the shell may be * disposed at this point. If this happens * don't send the activate and deactivate * events. */ if (!shell.isDisposed ()) { shell.setActiveControl (this); } break; case SWT.FocusOut: /* * It is possible that the shell may be * disposed at this point. If this happens * don't send the activate and deactivate * events. */ if (!shell.isDisposed ()) { Display display = shell.display; Control control = hwnd != -1 ? display.findControl (hwnd) : display.getFocusControl (); if (control == null || shell != control.getShell ()) { shell.setActiveControl (null); } } break; } return true; } boolean sendMouseEvent (int type, int button, int msg, int wParam, int lParam) { Event event = new Event (); event.button = button; event.x = (short) (lParam & 0xFFFF); event.y = (short) (lParam >> 16); setInputState (event, type); return sendMouseEvent (type, msg, wParam, lParam, event); } boolean sendMouseEvent (int type, int msg, int wParam, int lParam, Event event) { postEvent (type, event); return true; } /** * Sets the receiver's background color to the color specified * by the argument, or to the default system color for the control * if the argument is null. * * @param color the new color (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setBackground (Color color) { checkWidget (); int pixel = -1; if (color != null) { if (color.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); pixel = color.handle; } setBackgroundPixel (pixel); } void setBackgroundPixel (int pixel) { if (background == pixel) return; background = pixel; OS.InvalidateRect (handle, null, true); } /** * Sets the receiver's size and location to the rectangular * area specified by the arguments. The <code>x</code> and * <code>y</code> arguments are relative to the receiver's * parent (or its display if its parent is null). * <p> * Note: Attempting to set the width or height of the * receiver to a negative number will cause that * value to be set to zero instead. * </p> * * @param x the new x coordinate for the receiver * @param y the new y coordinate for the receiver * @param width the new width for the receiver * @param height the new height for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setBounds (int x, int y, int width, int height) { checkWidget (); int flags = OS.SWP_NOZORDER | OS.SWP_DRAWFRAME | OS.SWP_NOACTIVATE; setBounds (x, y, Math.max (0, width), Math.max (0, height), flags); } void setBounds (int x, int y, int width, int height, int flags) { if (parent == null) { OS.SetWindowPos (handle, 0, x, y, width, height, flags); return; } if (parent.lpwp == null) { /* * This code is intentionally commented. All widgets that * are created by SWT have WS_CLIPSIBLINGS to ensure that * application code does not draw outside of the control. */ // int count = parent.getChildrenCount (); // if (count > 1) { // int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); // if ((bits & OS.WS_CLIPSIBLINGS) == 0) flags |= OS.SWP_NOCOPYBITS; // } OS.SetWindowPos (handle, 0, x, y, width, height, flags); return; } forceResize (); WINDOWPOS [] lpwp = parent.lpwp; int index = 0; while (index < lpwp.length) { if (lpwp [index] == null) break; index ++; } if (index == lpwp.length) { WINDOWPOS [] newLpwp = new WINDOWPOS [lpwp.length + 4]; System.arraycopy (lpwp, 0, newLpwp, 0, lpwp.length); parent.lpwp = lpwp = newLpwp; } WINDOWPOS wp = new WINDOWPOS (); wp.hwnd = handle; wp.x = x; wp.y = y; wp.cx = width; wp.cy = height; wp.flags = flags; lpwp [index] = wp; } /** * Sets the receiver's size and location to the rectangular * area specified by the argument. The <code>x</code> and * <code>y</code> fields of the rectangle are relative to * the receiver's parent (or its display if its parent is null). * <p> * Note: Attempting to set the width or height of the * receiver to a negative number will cause that * value to be set to zero instead. * </p> * * @param rect the new bounds for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setBounds (Rectangle rect) { checkWidget (); if (rect == null) error (SWT.ERROR_NULL_ARGUMENT); setBounds (rect.x, rect.y, rect.width, rect.height); } /** * If the argument is <code>true</code>, causes the receiver to have * all mouse events delivered to it until the method is called with * <code>false</code> as the argument. * * @param capture <code>true</code> to capture the mouse, and <code>false</code> to release it * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setCapture (boolean capture) { checkWidget (); if (capture) { OS.SetCapture (handle); } else { if (OS.GetCapture () == handle) { OS.ReleaseCapture (); } } } void setCursor () { int lParam = OS.HTCLIENT | (OS.WM_MOUSEMOVE << 16); OS.SendMessage (handle, OS.WM_SETCURSOR, handle, lParam); } /** * Sets the receiver's cursor to the cursor specified by the * argument, or to the default cursor for that kind of control * if the argument is null. * <p> * When the mouse pointer passes over a control its appearance * is changed to match the control's cursor. * </p> * * @param cursor the new cursor (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setCursor (Cursor cursor) { checkWidget (); if (cursor != null && cursor.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); this.cursor = cursor; if (OS.IsWinCE) { int hCursor = cursor != null ? cursor.handle : 0; OS.SetCursor (hCursor); return; } int hwndCursor = OS.GetCapture (); if (hwndCursor == 0) { POINT pt = new POINT (); if (!OS.GetCursorPos (pt)) return; int hwnd = hwndCursor = OS.WindowFromPoint (pt); while (hwnd != 0 && hwnd != handle) { hwnd = OS.GetParent (hwnd); } if (hwnd == 0) return; } Control control = display.getControl (hwndCursor); if (control == null) control = this; control.setCursor (); } void setDefaultFont () { int hFont = display.systemFont (); OS.SendMessage (handle, OS.WM_SETFONT, hFont, 0); } /** * Enables the receiver if the argument is <code>true</code>, * and disables it otherwise. A disabled control is typically * not selectable from the user interface and draws with an * inactive or "grayed" look. * * @param enabled the new enabled state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setEnabled (boolean enabled) { checkWidget (); /* * Feature in Windows. If the receiver has focus, disabling * the receiver causes no window to have focus. The fix is * to assign focus to the first ancestor window that takes * focus. If no window will take focus, set focus to the * desktop. */ boolean fixFocus = false; if (!enabled) fixFocus = isFocusAncestor (); OS.EnableWindow (handle, enabled); if (fixFocus) fixFocus (); } /** * Causes the receiver to have the <em>keyboard focus</em>, * such that all keyboard events will be delivered to it. Focus * reassignment will respect applicable platform constraints. * * @return <code>true</code> if the control got focus, and <code>false</code> if it was unable to. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #forceFocus */ public boolean setFocus () { checkWidget (); return forceFocus (); } /** * Sets the font that the receiver will use to paint textual information * to the font specified by the argument, or to the default font for that * kind of control if the argument is null. * * @param font the new font (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setFont (Font font) { checkWidget (); int hFont = 0; if (font != null) { if (font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); hFont = font.handle; } if (hFont == 0) hFont = defaultFont (); OS.SendMessage (handle, OS.WM_SETFONT, hFont, 1); } /** * Sets the receiver's foreground color to the color specified * by the argument, or to the default system color for the control * if the argument is null. * * @param color the new color (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setForeground (Color color) { checkWidget (); int pixel = -1; if (color != null) { if (color.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); pixel = color.handle; } setForegroundPixel (pixel); } void setForegroundPixel (int pixel) { if (foreground == pixel) return; foreground = pixel; OS.InvalidateRect (handle, null, true); } /** * Sets the layout data associated with the receiver to the argument. * * @param layoutData the new layout data for the receiver. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setLayoutData (Object layoutData) { checkWidget (); this.layoutData = layoutData; } /** * Sets the receiver's location to the point specified by * the arguments which are relative to the receiver's * parent (or its display if its parent is null). * * @param x the new x coordinate for the receiver * @param y the new y coordinate for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setLocation (int x, int y) { checkWidget (); int flags = OS.SWP_NOSIZE | OS.SWP_NOZORDER | OS.SWP_NOACTIVATE; /* * Feature in WinCE. The SWP_DRAWFRAME flag for SetWindowPos() * causes a WM_SIZE message to be sent even when the SWP_NOSIZE * flag is specified. The fix is to set SWP_DRAWFRAME only when * not running on WinCE. */ if (!OS.IsWinCE) flags |= OS.SWP_DRAWFRAME; setBounds (x, y, 0, 0, flags); } /** * Sets the receiver's location to the point specified by * the argument which is relative to the receiver's * parent (or its display if its parent is null). * * @param location the new location for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setLocation (Point location) { checkWidget (); if (location == null) error (SWT.ERROR_NULL_ARGUMENT); setLocation (location.x, location.y); } /** * Sets the receiver's pop up menu to the argument. * All controls may optionally have a pop up * menu that is displayed when the user requests one for * the control. The sequence of key strokes, button presses * and/or button releases that are used to request a pop up * menu is platform specific. * * @param menu the new pop up menu * * @exception IllegalArgumentException <ul> * <li>ERROR_MENU_NOT_POP_UP - the menu is not a pop up menu</li> * <li>ERROR_INVALID_PARENT - if the menu is not in the same widget tree</li> * <li>ERROR_INVALID_ARGUMENT - if the menu has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setMenu (Menu menu) { checkWidget (); if (menu != null) { if (menu.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); if ((menu.style & SWT.POP_UP) == 0) { error (SWT.ERROR_MENU_NOT_POP_UP); } if (menu.parent != menuShell ()) { error (SWT.ERROR_INVALID_PARENT); } } this.menu = menu; } boolean setRadioFocus () { return false; } boolean setRadioSelection (boolean value) { return false; } /** * If the argument is <code>false</code>, causes subsequent drawing * operations in the receiver to be ignored. No drawing of any kind * can occur in the receiver until the flag is set to true. * Graphics operations that occurred while the flag was * <code>false</code> are lost. When the flag is set to <code>true</code>, * the entire widget is marked as needing to be redrawn. * <p> * Note: This operation is a hint and may not be supported on some * platforms or for some widgets. * </p> * * @param redraw the new redraw state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #redraw * @see #update */ public void setRedraw (boolean redraw) { checkWidget (); /* * Feature in Windows. When WM_SETREDRAW is used to turn * off drawing in a widget, it clears the WS_VISIBLE bits * and then sets them when redraw is turned back on. This * means that WM_SETREDRAW will make a widget unexpectedly * visible. The fix is to track the visibility state while * drawing is turned off and restore it when drawing is * turned back on. */ if (drawCount == 0) { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.WS_VISIBLE) == 0) state |= HIDDEN; } if (redraw) { if (--drawCount == 0) { OS.SendMessage (handle, OS.WM_SETREDRAW, 1, 0); if ((state & HIDDEN) != 0) { state &= ~HIDDEN; OS.ShowWindow (handle, OS.SW_HIDE); } else { if (OS.IsWinCE) { OS.InvalidateRect (handle, null, true); } else { int flags = OS.RDW_ERASE | OS.RDW_FRAME | OS.RDW_INVALIDATE | OS.RDW_ALLCHILDREN; OS.RedrawWindow (handle, null, 0, flags); } } } } else { if (drawCount++ == 0) { OS.SendMessage (handle, OS.WM_SETREDRAW, 0, 0); } } } boolean setSavedFocus () { return forceFocus (); } /** * Sets the receiver's size to the point specified by the arguments. * <p> * Note: Attempting to set the width or height of the * receiver to a negative number will cause that * value to be set to zero instead. * </p> * * @param width the new width for the receiver * @param height the new height for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setSize (int width, int height) { checkWidget (); int flags = OS.SWP_NOMOVE | OS.SWP_NOZORDER | OS.SWP_DRAWFRAME | OS.SWP_NOACTIVATE; setBounds (0, 0, Math.max (0, width), Math.max (0, height), flags); } /** * Sets the receiver's size to the point specified by the argument. * <p> * Note: Attempting to set the width or height of the * receiver to a negative number will cause them to be * set to zero instead. * </p> * * @param size the new size for the receiver * @param height the new height for the receiver * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setSize (Point size) { checkWidget (); if (size == null) error (SWT.ERROR_NULL_ARGUMENT); setSize (size.x, size.y); } boolean setTabGroupFocus () { return setTabItemFocus (); } boolean setTabItemFocus () { if (!isShowing ()) return false; return setFocus (); } /** * Sets the receiver's tool tip text to the argument, which * may be null indicating that no tool tip text should be shown. * * @param string the new tool tip text (or null) * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setToolTipText (String string) { checkWidget (); Shell shell = getShell (); shell.setToolTipText (handle, toolTipText = string); } /** * Marks the receiver as visible if the argument is <code>true</code>, * and marks it invisible otherwise. * <p> * If one of the receiver's ancestors is not visible or some * other condition makes the receiver not visible, marking * it visible may not actually cause it to be displayed. * </p> * * @param visible the new visibility state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setVisible (boolean visible) { checkWidget (); if (drawCount != 0) { if (((state & HIDDEN) == 0) == visible) return; } else { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if (((bits & OS.WS_VISIBLE) != 0) == visible) return; } if (visible) { /* * It is possible (but unlikely), that application * code could have disposed the widget in the show * event. If this happens, just return. */ sendEvent (SWT.Show); if (isDisposed ()) return; } /* * Feature in Windows. If the receiver has focus, hiding * the receiver causes no window to have focus. The fix is * to assign focus to the first ancestor window that takes * focus. If no window will take focus, set focus to the * desktop. */ boolean fixFocus = false; if (!visible) fixFocus = isFocusAncestor (); if (drawCount != 0) { state = visible ? state & ~HIDDEN : state | HIDDEN; } else { OS.ShowWindow (handle, visible ? OS.SW_SHOW : OS.SW_HIDE); } if (!visible) { /* * It is possible (but unlikely), that application * code could have disposed the widget in the show * event. If this happens, just return. */ sendEvent (SWT.Hide); if (isDisposed ()) return; } if (fixFocus) fixFocus (); } boolean showMenu (int x, int y) { Event event = new Event (); event.x = x; event.y = y; sendEvent (SWT.MenuDetect, event); if (!event.doit) return true; if (menu != null && !menu.isDisposed ()) { if (x != event.x || y != event.y) { menu.setLocation (event.x, event.y); } menu.setVisible (true); return true; } return false; } void sort (int [] items) { /* Shell Sort from K&R, pg 108 */ int length = items.length; for (int gap=length/2; gap>0; gap/=2) { for (int i=gap; i<length; i++) { for (int j=i-gap; j>=0; j-=gap) { if (items [j] <= items [j + gap]) { int swap = items [j]; items [j] = items [j + gap]; items [j + gap] = swap; } } } } } void subclass () { int oldProc = windowProc (); int newProc = display.windowProc; if (oldProc == newProc) return; OS.SetWindowLong (handle, OS.GWL_WNDPROC, newProc); } /** * Returns a point which is the result of converting the * argument, which is specified in display relative coordinates, * to coordinates relative to the receiver. * <p> * @param x the x coordinate to be translated * @param y the y coordinate to be translated * @return the translated coordinates * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 2.1 */ public Point toControl (int x, int y) { checkWidget (); POINT pt = new POINT (); pt.x = x; pt.y = y; OS.ScreenToClient (handle, pt); return new Point (pt.x, pt.y); } /** * Returns a point which is the result of converting the * argument, which is specified in display relative coordinates, * to coordinates relative to the receiver. * <p> * @param point the point to be translated (must not be null) * @return the translated coordinates * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point toControl (Point point) { checkWidget (); if (point == null) error (SWT.ERROR_NULL_ARGUMENT); return toControl (point.x, point.y); } /** * Returns a point which is the result of converting the * argument, which is specified in coordinates relative to * the receiver, to display relative coordinates. * <p> * @param x the x coordinate to be translated * @param y the y coordinate to be translated * @return the translated coordinates * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 2.1 */ public Point toDisplay (int x, int y) { checkWidget (); POINT pt = new POINT (); pt.x = x; pt.y = y; OS.ClientToScreen (handle, pt); return new Point (pt.x, pt.y); } /** * Returns a point which is the result of converting the * argument, which is specified in coordinates relative to * the receiver, to display relative coordinates. * <p> * @param point the point to be translated (must not be null) * @return the translated coordinates * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Point toDisplay (Point point) { checkWidget (); if (point == null) error (SWT.ERROR_NULL_ARGUMENT); return toDisplay (point.x, point.y); } boolean translateAccelerator (MSG msg) { return menuShell ().translateAccelerator (msg); } boolean translateMnemonic (Event event, Control control) { if (control == this) return false; if (!isVisible () || !isEnabled ()) return false; event.doit = mnemonicMatch (event.character); return traverse (event); } boolean translateMnemonic (MSG msg) { if (msg.wParam < 0x20) return false; int hwnd = msg.hwnd; if (OS.GetKeyState (OS.VK_MENU) >= 0) { int code = OS.SendMessage (hwnd, OS.WM_GETDLGCODE, 0, 0); if ((code & OS.DLGC_WANTALLKEYS) != 0) return false; if ((code & OS.DLGC_BUTTON) == 0) return false; } Decorations shell = menuShell (); if (shell.isVisible () && shell.isEnabled ()) { display.lastAscii = mbcsToWcs ((char) msg.wParam); display.lastVirtual = display.lastNull = false; Event event = new Event (); event.detail = SWT.TRAVERSE_MNEMONIC; if (setKeyState (event, SWT.Traverse)) { return translateMnemonic (event, null) || shell.translateMnemonic (event, this); } } return false; } boolean translateTraversal (MSG msg) { int key = msg.wParam; if (key == OS.VK_MENU) { Shell shell = getShell (); int hwndShell = shell.handle; OS.SendMessage (hwndShell, OS.WM_CHANGEUISTATE, OS.UIS_INITIALIZE, 0); return false; } int hwnd = msg.hwnd; int detail = SWT.TRAVERSE_NONE; boolean doit = true, all = false; boolean lastVirtual = false; int lastKey = key, lastAscii = 0; switch (key) { case OS.VK_ESCAPE: { all = true; lastAscii = 27; int code = OS.SendMessage (hwnd, OS.WM_GETDLGCODE, 0, 0); if ((code & OS.DLGC_WANTALLKEYS) != 0) { /* * Use DLGC_HASSETSEL to determine that the control * is a text widget. A text widget normally wants * all keys except VK_ESCAPE. If this bit is not * set, then assume the control wants all keys, * including VK_ESCAPE. */ if ((code & OS.DLGC_HASSETSEL) == 0) doit = false; } detail = SWT.TRAVERSE_ESCAPE; break; } case OS.VK_RETURN: { all = true; lastAscii = '\r'; int code = OS.SendMessage (hwnd, OS.WM_GETDLGCODE, 0, 0); if ((code & OS.DLGC_WANTALLKEYS) != 0) doit = false; detail = SWT.TRAVERSE_RETURN; break; } case OS.VK_TAB: { lastAscii = '\t'; boolean next = OS.GetKeyState (OS.VK_SHIFT) >= 0; int code = OS.SendMessage (hwnd, OS.WM_GETDLGCODE, 0, 0); if ((code & (OS.DLGC_WANTTAB | OS.DLGC_WANTALLKEYS)) != 0) { /* * Use DLGC_HASSETSEL to determine that the control is a * text widget. If the control is a text widget, then * Ctrl+Tab and Shift+Tab should traverse out of the widget. * If the control is not a text widget, the correct behavior * is to give every character, including Tab, Ctrl+Tab and * Shift+Tab to the control. */ if ((code & OS.DLGC_HASSETSEL) != 0) { if (next && OS.GetKeyState (OS.VK_CONTROL) >= 0) { doit = false; } } else { doit = false; } } if (parent != null && (parent.style & SWT.MIRRORED) != 0) { if (key == OS.VK_LEFT || key == OS.VK_RIGHT) next = !next; } detail = next ? SWT.TRAVERSE_TAB_NEXT : SWT.TRAVERSE_TAB_PREVIOUS; break; } case OS.VK_UP: case OS.VK_LEFT: case OS.VK_DOWN: case OS.VK_RIGHT: { /* * On WinCE SP there is no tab key. Focus is assigned * using the VK_UP and VK_DOWN keys, not with VK_LEFT * or VK_RIGHT. */ if (OS.IsSP) { if (key == OS.VK_LEFT || key == OS.VK_RIGHT) return false; } lastVirtual = true; int code = OS.SendMessage (hwnd, OS.WM_GETDLGCODE, 0, 0); if ((code & (OS.DLGC_WANTARROWS /*| OS.DLGC_WANTALLKEYS*/)) != 0) doit = false; boolean next = key == OS.VK_DOWN || key == OS.VK_RIGHT; detail = next ? SWT.TRAVERSE_ARROW_NEXT : SWT.TRAVERSE_ARROW_PREVIOUS; break; } case OS.VK_PRIOR: case OS.VK_NEXT: { all = true; lastVirtual = true; if (OS.GetKeyState (OS.VK_CONTROL) >= 0) return false; int code = OS.SendMessage (hwnd, OS.WM_GETDLGCODE, 0, 0); if ((code & OS.DLGC_WANTALLKEYS) != 0) { /* * Use DLGC_HASSETSEL to determine that the control is a * text widget. If the control is a text widget, then * Ctrl+PgUp and Ctrl+PgDn should traverse out of the widget. */ if ((code & OS.DLGC_HASSETSEL) == 0) doit = false; } detail = key == OS.VK_PRIOR ? SWT.TRAVERSE_PAGE_PREVIOUS : SWT.TRAVERSE_PAGE_NEXT; break; } default: return false; } Event event = new Event (); event.doit = doit; event.detail = detail; display.lastKey = lastKey; display.lastAscii = lastAscii; display.lastVirtual = lastVirtual; display.lastNull = false; if (!setKeyState (event, SWT.Traverse)) return false; Shell shell = getShell (); Control control = this; do { if (control.traverse (event)) { int hwndShell = shell.handle; OS.SendMessage (hwndShell, OS.WM_CHANGEUISTATE, OS.UIS_INITIALIZE, 0); return true; } if (!event.doit && control.hooks (SWT.Traverse)) return false; if (control == shell) return false; control = control.parent; } while (all && control != null); return false; } boolean traverse (Event event) { /* * It is possible (but unlikely), that application * code could have disposed the widget in the traverse * event. If this happens, return true to stop further * event processing. */ sendEvent (SWT.Traverse, event); if (isDisposed ()) return true; if (!event.doit) return false; switch (event.detail) { case SWT.TRAVERSE_NONE: return true; case SWT.TRAVERSE_ESCAPE: return traverseEscape (); case SWT.TRAVERSE_RETURN: return traverseReturn (); case SWT.TRAVERSE_TAB_NEXT: return traverseGroup (true); case SWT.TRAVERSE_TAB_PREVIOUS: return traverseGroup (false); case SWT.TRAVERSE_ARROW_NEXT: return traverseItem (true); case SWT.TRAVERSE_ARROW_PREVIOUS: return traverseItem (false); case SWT.TRAVERSE_MNEMONIC: return traverseMnemonic (event.character); case SWT.TRAVERSE_PAGE_NEXT: return traversePage (true); case SWT.TRAVERSE_PAGE_PREVIOUS: return traversePage (false); } return false; } /** * Based on the argument, perform one of the expected platform * traversal action. The argument should be one of the constants: * <code>SWT.TRAVERSE_ESCAPE</code>, <code>SWT.TRAVERSE_RETURN</code>, * <code>SWT.TRAVERSE_TAB_NEXT</code>, <code>SWT.TRAVERSE_TAB_PREVIOUS</code>, * <code>SWT.TRAVERSE_ARROW_NEXT</code> and <code>SWT.TRAVERSE_ARROW_PREVIOUS</code>. * * @param traversal the type of traversal * @return true if the traversal succeeded * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean traverse (int traversal) { checkWidget (); if (!isFocusControl () && !setFocus ()) return false; Event event = new Event (); event.doit = true; event.detail = traversal; return traverse (event); } boolean traverseEscape () { return false; } boolean traverseGroup (boolean next) { Control root = computeTabRoot (); Control group = computeTabGroup (); Control [] list = root.computeTabList (); int length = list.length; int index = 0; while (index < length) { if (list [index] == group) break; index++; } /* * It is possible (but unlikely), that application * code could have disposed the widget in focus in * or out events. Ensure that a disposed widget is * not accessed. */ if (index == length) return false; int start = index, offset = (next) ? 1 : -1; while ((index = ((index + offset + length) % length)) != start) { Control control = list [index]; if (!control.isDisposed () && control.setTabGroupFocus ()) { if (!isDisposed () && !isFocusControl ()) return true; } } if (group.isDisposed ()) return false; return group.setTabGroupFocus (); } boolean traverseItem (boolean next) { Control [] children = parent._getChildren (); int length = children.length; int index = 0; while (index < length) { if (children [index] == this) break; index++; } /* * It is possible (but unlikely), that application * code could have disposed the widget in focus in * or out events. Ensure that a disposed widget is * not accessed. */ int start = index, offset = (next) ? 1 : -1; while ((index = (index + offset + length) % length) != start) { Control child = children [index]; if (!child.isDisposed () && child.isTabItem ()) { if (child.setTabItemFocus ()) return true; } } return false; } boolean traverseMnemonic (char key) { return mnemonicHit (key); } boolean traversePage (boolean next) { return false; } boolean traverseReturn () { return false; } void unsubclass () { int newProc = windowProc (); int oldProc = display.windowProc; if (oldProc == newProc) return; OS.SetWindowLong (handle, OS.GWL_WNDPROC, newProc); } /** * Forces all outstanding paint requests for the widget * to be processed before this method returns. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #redraw */ public void update () { checkWidget (); update (false); } void update (boolean all) { // checkWidget (); if (OS.IsWinCE) { OS.UpdateWindow (handle); } else { int flags = OS.RDW_UPDATENOW; if (all) flags |= OS.RDW_ALLCHILDREN; OS.RedrawWindow (handle, null, 0, flags); } } void updateFont (Font oldFont, Font newFont) { Font font = getFont (); if (font.equals (oldFont)) setFont (newFont); } CREATESTRUCT widgetCreateStruct () { return null; } int widgetExtStyle () { int bits = 0; if (!OS.IsPPC) { if ((style & SWT.BORDER) != 0) bits |= OS.WS_EX_CLIENTEDGE; } // if ((style & SWT.BORDER) != 0) { // if ((style & SWT.FLAT) == 0) bits |= OS.WS_EX_CLIENTEDGE; // } /* * Feature in Windows NT. When CreateWindowEx() is called with * WS_EX_LAYOUTRTL or WS_EX_NOINHERITLAYOUT, CreateWindowEx() * fails to create the HWND. The fix is to not use these bits. */ if ((OS.WIN32_MAJOR << 16 | OS.WIN32_MINOR) < (4 << 16 | 10)) { return bits; } bits |= OS.WS_EX_NOINHERITLAYOUT; if ((style & SWT.RIGHT_TO_LEFT) != 0) bits |= OS.WS_EX_LAYOUTRTL; return bits; } int widgetParent () { return parent.handle; } int widgetStyle () { /* Force clipping of siblings by setting WS_CLIPSIBLINGS */ int bits = OS.WS_CHILD | OS.WS_VISIBLE | OS.WS_CLIPSIBLINGS; // if ((style & SWT.BORDER) != 0) { // if ((style & SWT.FLAT) != 0) bits |= OS.WS_BORDER; // } if (OS.IsPPC) { if ((style & SWT.BORDER) != 0) bits |= OS.WS_BORDER; } return bits; /* * This code is intentionally commented. When clipping * of both siblings and children is not enforced, it is * possible for application code to draw outside of the * control. */ // int bits = OS.WS_CHILD | OS.WS_VISIBLE; // if ((style & SWT.CLIP_SIBLINGS) != 0) bits |= OS.WS_CLIPSIBLINGS; // if ((style & SWT.CLIP_CHILDREN) != 0) bits |= OS.WS_CLIPCHILDREN; // return bits; } /** * Changes the parent of the widget to be the one provided if * the underlying operating system supports this feature. * Answers <code>true</code> if the parent is successfully changed. * * @param parent the new parent for the control. * @return <code>true</code> if the parent is changed and <code>false</code> otherwise. * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> * </ul> * @exception SWTError <ul> * <li>ERROR_THREAD_INVALID_ACCESS when called from the wrong thread</li> * <li>ERROR_WIDGET_DISPOSED when the widget has been disposed</li> * </ul> */ public boolean setParent (Composite parent) { checkWidget (); if (parent == null) error (SWT.ERROR_NULL_ARGUMENT); if (parent.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); if (this.parent == parent) return true; if (!isReparentable ()) return false; releaseChild (); Shell newShell = parent.getShell (), oldShell = getShell (); Decorations newDecorations = parent.menuShell (), oldDecorations = menuShell (); Menu [] menus = oldShell.findMenus (this); if (oldShell != newShell || oldDecorations != newDecorations) { fixChildren (newShell, oldShell, newDecorations, oldDecorations, menus); } if (OS.SetParent (handle, parent.handle) == 0) return false; this.parent = parent; int flags = OS.SWP_NOSIZE | OS.SWP_NOMOVE | OS.SWP_NOACTIVATE; OS.SetWindowPos (handle, OS.HWND_BOTTOM, 0, 0, 0, 0, flags); return true; } abstract TCHAR windowClass (); abstract int windowProc (); int windowProc (int hwnd, int msg, int wParam, int lParam) { LRESULT result = null; switch (msg) { case OS.WM_ACTIVATE: result = WM_ACTIVATE (wParam, lParam); break; case OS.WM_CHAR: result = WM_CHAR (wParam, lParam); break; case OS.WM_CLEAR: result = WM_CLEAR (wParam, lParam); break; case OS.WM_CLOSE: result = WM_CLOSE (wParam, lParam); break; case OS.WM_COMMAND: result = WM_COMMAND (wParam, lParam); break; case OS.WM_CONTEXTMENU: result = WM_CONTEXTMENU (wParam, lParam); break; case OS.WM_CTLCOLORBTN: case OS.WM_CTLCOLORDLG: case OS.WM_CTLCOLOREDIT: case OS.WM_CTLCOLORLISTBOX: case OS.WM_CTLCOLORMSGBOX: case OS.WM_CTLCOLORSCROLLBAR: case OS.WM_CTLCOLORSTATIC: result = WM_CTLCOLOR (wParam, lParam); break; case OS.WM_CUT: result = WM_CUT (wParam, lParam); break; case OS.WM_DESTROY: result = WM_DESTROY (wParam, lParam); break; case OS.WM_DRAWITEM: result = WM_DRAWITEM (wParam, lParam); break; case OS.WM_ENDSESSION: result = WM_ENDSESSION (wParam, lParam); break; case OS.WM_ERASEBKGND: result = WM_ERASEBKGND (wParam, lParam); break; case OS.WM_GETDLGCODE: result = WM_GETDLGCODE (wParam, lParam); break; case OS.WM_HELP: result = WM_HELP (wParam, lParam); break; case OS.WM_HSCROLL: result = WM_HSCROLL (wParam, lParam); break; case OS.WM_IME_CHAR: result = WM_IME_CHAR (wParam, lParam); break; case OS.WM_IME_COMPOSITION: result = WM_IME_COMPOSITION (wParam, lParam); break; case OS.WM_INITMENUPOPUP: result = WM_INITMENUPOPUP (wParam, lParam); break; case OS.WM_GETFONT: result = WM_GETFONT (wParam, lParam); break; case OS.WM_GETOBJECT: result = WM_GETOBJECT (wParam, lParam); break; case OS.WM_HOTKEY: result = WM_HOTKEY (wParam, lParam); break; case OS.WM_KEYDOWN: result = WM_KEYDOWN (wParam, lParam); break; case OS.WM_KEYUP: result = WM_KEYUP (wParam, lParam); break; case OS.WM_KILLFOCUS: result = WM_KILLFOCUS (wParam, lParam); break; case OS.WM_LBUTTONDBLCLK: result = WM_LBUTTONDBLCLK (wParam, lParam); break; case OS.WM_LBUTTONDOWN: result = WM_LBUTTONDOWN (wParam, lParam); break; case OS.WM_LBUTTONUP: result = WM_LBUTTONUP (wParam, lParam); break; case OS.WM_MBUTTONDBLCLK: result = WM_MBUTTONDBLCLK (wParam, lParam); break; case OS.WM_MBUTTONDOWN: result = WM_MBUTTONDOWN (wParam, lParam); break; case OS.WM_MBUTTONUP: result = WM_MBUTTONUP (wParam, lParam); break; case OS.WM_MEASUREITEM: result = WM_MEASUREITEM (wParam, lParam); break; case OS.WM_MENUCHAR: result = WM_MENUCHAR (wParam, lParam); break; case OS.WM_MENUSELECT: result = WM_MENUSELECT (wParam, lParam); break; case OS.WM_MOUSEACTIVATE: result = WM_MOUSEACTIVATE (wParam, lParam); break; case OS.WM_MOUSEHOVER: result = WM_MOUSEHOVER (wParam, lParam); break; case OS.WM_MOUSELEAVE: result = WM_MOUSELEAVE (wParam, lParam); break; case OS.WM_MOUSEMOVE: result = WM_MOUSEMOVE (wParam, lParam); break; case OS.WM_MOUSEWHEEL: result = WM_MOUSEWHEEL (wParam, lParam); break; case OS.WM_MOVE: result = WM_MOVE (wParam, lParam); break; case OS.WM_NCACTIVATE: result = WM_NCACTIVATE (wParam, lParam); break; case OS.WM_NCCALCSIZE: result = WM_NCCALCSIZE (wParam, lParam); break; case OS.WM_NCHITTEST: result = WM_NCHITTEST (wParam, lParam); break; case OS.WM_NCLBUTTONDOWN: result = WM_NCLBUTTONDOWN (wParam, lParam); break; case OS.WM_NOTIFY: result = WM_NOTIFY (wParam, lParam); break; case OS.WM_PAINT: result = WM_PAINT (wParam, lParam); break; case OS.WM_PALETTECHANGED: result = WM_PALETTECHANGED (wParam, lParam); break; case OS.WM_PARENTNOTIFY: result = WM_PARENTNOTIFY (wParam, lParam); break; case OS.WM_PASTE: result = WM_PASTE (wParam, lParam); break; case OS.WM_PRINTCLIENT: result = WM_PRINTCLIENT (wParam, lParam); break; case OS.WM_QUERYENDSESSION: result = WM_QUERYENDSESSION (wParam, lParam); break; case OS.WM_QUERYNEWPALETTE: result = WM_QUERYNEWPALETTE (wParam, lParam); break; case OS.WM_QUERYOPEN: result = WM_QUERYOPEN (wParam, lParam); break; case OS.WM_RBUTTONDBLCLK: result = WM_RBUTTONDBLCLK (wParam, lParam); break; case OS.WM_RBUTTONDOWN: result = WM_RBUTTONDOWN (wParam, lParam); break; case OS.WM_RBUTTONUP: result = WM_RBUTTONUP (wParam, lParam); break; case OS.WM_SETCURSOR: result = WM_SETCURSOR (wParam, lParam); break; case OS.WM_SETFOCUS: result = WM_SETFOCUS (wParam, lParam); break; case OS.WM_SETFONT: result = WM_SETFONT (wParam, lParam); break; case OS.WM_SETTINGCHANGE: result = WM_SETTINGCHANGE (wParam, lParam); break; case OS.WM_SETREDRAW: result = WM_SETREDRAW (wParam, lParam); break; case OS.WM_SHOWWINDOW: result = WM_SHOWWINDOW (wParam, lParam); break; case OS.WM_SIZE: result = WM_SIZE (wParam, lParam); break; case OS.WM_SYSCHAR: result = WM_SYSCHAR (wParam, lParam); break; case OS.WM_SYSCOLORCHANGE: result = WM_SYSCOLORCHANGE (wParam, lParam); break; case OS.WM_SYSCOMMAND: result = WM_SYSCOMMAND (wParam, lParam); break; case OS.WM_SYSKEYDOWN: result = WM_SYSKEYDOWN (wParam, lParam); break; case OS.WM_SYSKEYUP: result = WM_SYSKEYUP (wParam, lParam); break; case OS.WM_TIMER: result = WM_TIMER (wParam, lParam); break; case OS.WM_UNDO: result = WM_UNDO (wParam, lParam); break; case OS.WM_VSCROLL: result = WM_VSCROLL (wParam, lParam); break; case OS.WM_WINDOWPOSCHANGED: result = WM_WINDOWPOSCHANGED (wParam, lParam); break; case OS.WM_WINDOWPOSCHANGING: result = WM_WINDOWPOSCHANGING (wParam, lParam); break; } if (result != null) return result.value; return callWindowProc (msg, wParam, lParam); } LRESULT WM_ACTIVATE (int wParam, int lParam) { return null; } LRESULT WM_CHAR (int wParam, int lParam) { /* * Do not report a lead byte as a key pressed. */ if (!OS.IsUnicode && OS.IsDBLocale) { byte lead = (byte) (wParam & 0xFF); if (OS.IsDBCSLeadByte (lead)) return null; } /* * Feature in Windows. When the user presses Ctrl+Backspace * or Ctrl+Enter, Windows sends a WM_CHAR with Delete (0x7F) * and '\n' instead of '\b' and '\r'. This is the correct * platform behavior but is not portable. The fix is detect * these cases and convert the character. */ display.lastAscii = wParam; switch (display.lastAscii) { case SWT.DEL: if (display.lastKey == SWT.BS) display.lastAscii = SWT.BS; break; case SWT.LF: if (display.lastKey == SWT.CR) display.lastAscii = SWT.CR; break; } display.lastNull = wParam == 0; if (!sendKeyEvent (SWT.KeyDown, OS.WM_CHAR, wParam, lParam)) { return LRESULT.ZERO; } // widget could be disposed at this point return null; } LRESULT WM_CLEAR (int wParam, int lParam) { return null; } LRESULT WM_CLOSE (int wParam, int lParam) { return null; } LRESULT WM_COMMAND (int wParam, int lParam) { /* * When the WM_COMMAND message is sent from a * menu, the HWND parameter in LPARAM is zero. */ if (lParam == 0) { Decorations shell = menuShell (); if (shell.isEnabled ()) { int id = wParam & 0xFFFF; MenuItem item = shell.findMenuItem (id); if (item != null && item.isEnabled ()) { return item.wmCommandChild (wParam, lParam); } } return null; } Control control = display.getControl (lParam); if (control == null) return null; return control.wmCommandChild (wParam, lParam); } LRESULT WM_CONTEXTMENU (int wParam, int lParam) { if (wParam != handle) return null; /* * Feature in Windows. When the user presses WM_NCRBUTTONUP, * a WM_CONTEXTMENU message is generated. This happens when * the user releases the mouse over a scroll bar. Normally, * window displays the default scrolling menu but applications * can process WM_CONTEXTMENU to display a different menu. * Typically, an application does not want to supply a special * scroll menu. The fix is to look for a WM_CONTEXTMENU that * originated from a mouse event and display the menu when the * mouse was released in the client area. */ int x = 0, y = 0; if (lParam != -1) { POINT pt = new POINT (); x = pt.x = (short) (lParam & 0xFFFF); y = pt.y = (short) (lParam >> 16); OS.ScreenToClient (handle, pt); RECT rect = new RECT (); OS.GetClientRect (handle, rect); if (!OS.PtInRect (rect, pt)) return null; } else { int pos = OS.GetMessagePos (); x = (short) (pos & 0xFFFF); y = (short) (pos >> 16); } /* Show the menu */ return showMenu (x, y) ? LRESULT.ZERO : null; } LRESULT WM_CTLCOLOR (int wParam, int lParam) { int hPalette = display.hPalette; if (hPalette != 0) { OS.SelectPalette (wParam, hPalette, false); OS.RealizePalette (wParam); } Control control = display.getControl (lParam); if (control == null) return null; return control.wmColorChild (wParam, lParam); } LRESULT WM_CUT (int wParam, int lParam) { return null; } LRESULT WM_DESTROY (int wParam, int lParam) { return null; } LRESULT WM_DRAWITEM (int wParam, int lParam) { DRAWITEMSTRUCT struct = new DRAWITEMSTRUCT (); OS.MoveMemory (struct, lParam, DRAWITEMSTRUCT.sizeof); if (struct.CtlType == OS.ODT_MENU) { Decorations shell = menuShell (); MenuItem item = shell.findMenuItem (struct.itemID); if (item == null) return null; return item.wmDrawChild (wParam, lParam); } Control control = display.getControl (struct.hwndItem); if (control == null) return null; return control.wmDrawChild (wParam, lParam); } LRESULT WM_ENDSESSION (int wParam, int lParam) { return null; } LRESULT WM_ERASEBKGND (int wParam, int lParam) { return null; } LRESULT WM_GETDLGCODE (int wParam, int lParam) { return null; } LRESULT WM_GETFONT (int wParam, int lParam) { return null; } LRESULT WM_GETOBJECT (int wParam, int lParam) { if (accessible != null) { int result = accessible.internal_WM_GETOBJECT (wParam, lParam); if (result != 0) return new LRESULT (result); } return null; } LRESULT WM_HOTKEY (int wParam, int lParam) { return null; } LRESULT WM_HELP (int wParam, int lParam) { if (OS.IsWinCE) return null; HELPINFO lphi = new HELPINFO (); OS.MoveMemory (lphi, lParam, HELPINFO.sizeof); Decorations shell = menuShell (); if (!shell.isEnabled ()) return null; if (lphi.iContextType == OS.HELPINFO_MENUITEM) { MenuItem item = shell.findMenuItem (lphi.iCtrlId); if (item != null && item.isEnabled ()) { Widget widget = null; if (item.hooks (SWT.Help)) { widget = item; } else { Menu menu = item.parent; if (menu.hooks (SWT.Help)) widget = menu; } if (widget != null) { int hwndShell = shell.handle; OS.SendMessage (hwndShell, OS.WM_CANCELMODE, 0, 0); widget.postEvent (SWT.Help); return LRESULT.ONE; } } return null; } if (hooks (SWT.Help)) { postEvent (SWT.Help); return LRESULT.ONE; } return null; } LRESULT WM_HSCROLL (int wParam, int lParam) { if (lParam == 0) return null; Control control = display.getControl (lParam); if (control == null) return null; return control.wmScrollChild (wParam, lParam); } LRESULT WM_IME_CHAR (int wParam, int lParam) { Display display = this.display; display.lastKey = 0; display.lastAscii = wParam; display.lastVirtual = display.lastNull = false; if (!sendKeyEvent (SWT.KeyDown, OS.WM_IME_CHAR, wParam, lParam)) { return LRESULT.ZERO; } sendKeyEvent (SWT.KeyUp, OS.WM_IME_CHAR, wParam, lParam); // widget could be disposed at this point display.lastKey = display.lastAscii = 0; return LRESULT.ZERO; } LRESULT WM_IME_COMPOSITION (int wParam, int lParam) { return null; } LRESULT WM_INITMENUPOPUP (int wParam, int lParam) { /* Ignore WM_INITMENUPOPUP for an accelerator */ if (display.accelKeyHit) return null; /* * If the high order word of LPARAM is non-zero, * the menu is the system menu and we can ignore * WPARAM. Otherwise, use WPARAM to find the menu. */ Shell shell = getShell (); Menu oldMenu = shell.activeMenu, newMenu = null; if ((lParam >> 16) == 0) { newMenu = menuShell ().findMenu (wParam); } Menu menu = newMenu; while (menu != null && menu != oldMenu) { menu = menu.getParentMenu (); } if (menu == null) { menu = shell.activeMenu; while (menu != null) { /* * It is possible (but unlikely), that application * code could have disposed the widget in the hide * event. If this happens, stop searching up the * ancestor list because there is no longer a link * to follow. */ menu.sendEvent (SWT.Hide); if (menu.isDisposed ()) break; menu = menu.getParentMenu (); Menu ancestor = newMenu; while (ancestor != null && ancestor != menu) { ancestor = ancestor.getParentMenu (); } if (ancestor != null) break; } } /* * The shell and the new menu may be disposed because of * sending the hide event to the ancestor menus but setting * a field to null in a disposed shell is not harmful. */ if (newMenu != null && newMenu.isDisposed ()) newMenu = null; shell.activeMenu = newMenu; /* Send the show event */ if (newMenu != null && newMenu != oldMenu) { newMenu.sendEvent (SWT.Show); // widget could be disposed at this point } return null; } LRESULT WM_KEYDOWN (int wParam, int lParam) { /* Ignore repeating modifier keys by testing key down state */ switch (wParam) { case OS.VK_SHIFT: case OS.VK_MENU: case OS.VK_CONTROL: case OS.VK_CAPITAL: case OS.VK_NUMLOCK: case OS.VK_SCROLL: if ((lParam & 0x40000000) != 0) return null; } /* Clear last key and last ascii because a new key has been typed */ display.lastAscii = display.lastKey = 0; display.lastVirtual = display.lastNull = false; /* * Do not report a lead byte as a key pressed. */ if (!OS.IsUnicode && OS.IsDBLocale) { byte lead = (byte) (wParam & 0xFF); if (OS.IsDBCSLeadByte (lead)) return null; } /* Map the virtual key */ /* * Bug on WinCE. MapVirtualKey() returns incorrect values. * The fix is to rely on a key mappings table to determine * whether the key event must be sent now or if a WM_CHAR * event will follow. */ int mapKey = OS.IsWinCE ? 0 : OS.MapVirtualKey (wParam, 2); /* * Bug in Windows 95 and NT. When the user types an accent key such * as ^ to get an accented character on a German keyboard, the accent * key should be ignored and the next key that the user types is the * accented key. On Windows 95 and NT, a call to ToAscii (), clears the * accented state such that the next WM_CHAR loses the accent. The fix * is to detect the accent key stroke (called a dead key) by testing the * high bit of the value returned by MapVirtualKey (). A further problem * is that the high bit on Windows NT is bit 32 while the high bit on * Windows 95 is bit 16. They should both be bit 32. * * NOTE: This code is used to avoid a call to ToAscii (). */ if (OS.IsWinNT) { if ((mapKey & 0x80000000) != 0) return null; } else { if ((mapKey & 0x8000) != 0) return null; } /* * Bug in Windows. When the accent key is generated on an international * keyboard using Ctrl+Alt or the special key, MapVirtualKey () does not * have the high bit set indicating that this is an accent key stroke. * The fix is to iterate through all known accent, mapping them back to * their corresponding virtual key and key state. If the virtual key * and key state match the current key, then this is an accent that has * been generated using an international keyboard and calling ToAscii () * will clear the accent state. * * NOTE: This code is used to avoid a call to ToAscii (). */ if (!OS.IsWinCE) { if (OS.GetKeyState (OS.VK_CONTROL) < 0 && OS.GetKeyState (OS.VK_MENU) < 0) { for (int i=0; i<ACCENTS.length; i++) { int value = OS.VkKeyScan (ACCENTS [i]); if ((value & 0xFF) == wParam && (value & 0x600) == 0x600) { display.lastVirtual = (mapKey == 0); display.lastKey = display.lastVirtual ? wParam : mapKey; return null; } } } } /* * If we are going to get a WM_CHAR, ensure that last key has * the correct character value for the key down and key up * events. It is not sufficient to ignore the WM_KEYDOWN * (when we know we are going to get a WM_CHAR) and compute * the key in WM_CHAR because there is not enough information * by the time we get the WM_CHAR. For example, when the user * types Ctrl+Shift+6 on a US keyboard, we get a WM_CHAR with * wParam=30. When the user types Ctrl+Shift+6 on a German * keyboard, we also get a WM_CHAR with wParam=30. On the US * keyboard Shift+6 is ^, on the German keyboard Shift+6 is &. * There is no way to map wParam=30 in WM_CHAR to the correct * value. Also, on international keyboards, the control key * may be down when the user has not entered a control character. */ display.lastVirtual = (mapKey == 0); if (display.lastVirtual) { display.lastKey = wParam; /* * Feature in Windows. The virtual key VK_DELETE is not * treated as both a virtual key and an ASCII key by Windows. * Therefore, we will not receive a WM_CHAR for this key. * The fix is to treat VK_DELETE as a special case and map * the ASCII value explictly (Delete is 0x7F). */ if (display.lastKey == OS.VK_DELETE) { display.lastVirtual = false; display.lastKey = display.lastAscii = 0x7F; } /* * It is possible to get a WM_CHAR for a virtual key when * Num Lock is on. If the user types Home while Num Lock * is down, a WM_CHAR is issued with WPARM=55 (for the * character 7). If we are going to get a WM_CHAR we need * to ensure that the last key has the correct value. Note * that Ctrl+Home does not issue a WM_CHAR when Num Lock is * down. * * NOTE: This only happens on Windows 98. */ if (OS.VK_NUMPAD0 <= display.lastKey && display.lastKey <= OS.VK_DIVIDE) { if (display.asciiKey (display.lastKey) != 0) return null; display.lastAscii = display.numpadKey (display.lastKey); } } else { /* * Convert LastKey to lower case because Windows non-virtual * keys that are also ASCII keys, such as like VK_A, are have * upper case values in WM_KEYDOWN despite the fact that the * Shift was not pressed. */ display.lastKey = OS.CharLower ((short) mapKey); /* * Some key combinations map to Windows ASCII keys depending * on the keyboard. For example, Ctrl+Alt+Q maps to @ on a * German keyboard. If the current key combination is special, * the correct character is placed in wParam for processing in * WM_CHAR. If this is the case, issue the key down event from * inside WM_CHAR. */ int asciiKey = display.asciiKey (wParam); if (asciiKey != 0) { /* * When the user types Ctrl+Space, ToAscii () maps this to * Space. Normally, ToAscii () maps a key to a different * key if both a WM_KEYDOWN and a WM_CHAR will be issued. * To avoid the extra SWT.KeyDown, look for a space and * issue the event from WM_CHAR. */ if (asciiKey == ' ') return null; if (asciiKey != wParam) return null; } /* * If the control key is not down at this point, then * the key that was pressed was an accent key or a regular * key such as 'A' or Shift+A. In that case, issue the * key event from WM_CHAR. */ if (OS.GetKeyState (OS.VK_CONTROL) >= 0) return null; /* * Get the shifted state or convert to lower case if necessary. * If the user types Ctrl+A, LastAscii should be 'a', not 'A'. * If the user types Ctrl+Shift+A, LastAscii should be 'A'. * If the user types Ctrl+Shift+6, the value of LastAscii will * depend on the international keyboard. */ if (OS.GetKeyState (OS.VK_SHIFT) < 0) { display.lastAscii = display.shiftedKey (wParam); if (display.lastAscii == 0) display.lastAscii = mapKey; } else { display.lastAscii = OS.CharLower ((short) mapKey); } /* Note that Ctrl+'@' is ASCII NUL and is delivered in WM_CHAR */ if (display.lastAscii == '@') return null; display.lastAscii = display.controlKey (display.lastAscii); } if (!sendKeyEvent (SWT.KeyDown, OS.WM_KEYDOWN, wParam, lParam)) { return LRESULT.ZERO; } // widget could be disposed at this point return null; } LRESULT WM_KEYUP (int wParam, int lParam) { Display display = this.display; /* Check for hardware keys */ if (OS.IsWinCE) { if (OS.VK_APP1 <= wParam && wParam <= OS.VK_APP6) { display.lastKey = display.lastAscii = 0; display.lastVirtual = display.lastNull = false; Event event = new Event (); event.detail = wParam - OS.VK_APP1 + 1; /* Check the bit 30 to get the key state */ int type = (lParam & 0x40000000) != 0 ? SWT.HardKeyUp : SWT.HardKeyDown; if (setInputState (event, type)) sendEvent (type, event); // widget could be disposed at this point return null; } } /* * If the key up is not hooked, reset last key * and last ascii in case the key down is hooked. */ if (!hooks (SWT.KeyUp) && !display.filters (SWT.KeyUp)) { display.lastKey = display.lastAscii = 0; display.lastVirtual = display.lastNull = false; return null; } /* Map the virtual key. */ /* * Bug on WinCE. MapVirtualKey() returns incorrect values. * The fix is to rely on a key mappings table to determine * whether the key event must be sent now or if a WM_CHAR * event will follow. */ int mapKey = OS.IsWinCE ? 0 : OS.MapVirtualKey (wParam, 2); /* * Bug in Windows 95 and NT. When the user types an accent key such * as ^ to get an accented character on a German keyboard, the accent * key should be ignored and the next key that the user types is the * accented key. On Windows 95 and NT, a call to ToAscii (), clears the * accented state such that the next WM_CHAR loses the accent. The fix * is to detect the accent key stroke (called a dead key) by testing the * high bit of the value returned by MapVirtualKey (). A further problem * is that the high bit on Windows NT is bit 32 while the high bit on * Windows 95 is bit 16. They should both be bit 32. * * NOTE: This code is used to avoid a call to ToAscii (). * */ if (OS.IsWinNT) { if ((mapKey & 0x80000000) != 0) return null; } else { if ((mapKey & 0x8000) != 0) return null; } /* * Bug in Windows. When the accent key is generated on an international * keyboard using Ctrl+Alt or the special key, MapVirtualKey () does not * have the high bit set indicating that this is an accent key stroke. * The fix is to iterate through all known accent, mapping them back to * their corresponding virtual key and key state. If the virtual key * and key state match the current key, then this is an accent that has * been generated using an international keyboard. * * NOTE: This code is used to avoid a call to ToAscii (). */ if (!OS.IsWinCE) { if (OS.GetKeyState (OS.VK_CONTROL) < 0 && OS.GetKeyState (OS.VK_MENU) < 0) { for (int i=0; i<ACCENTS.length; i++) { int value = OS.VkKeyScan (ACCENTS [i]); if ((value & 0xFF) == wParam && (value & 0x600) == 0x600) { display.lastKey = display.lastAscii = 0; display.lastVirtual = display.lastNull = false; return null; } } } } display.lastVirtual = (mapKey == 0); if (display.lastVirtual) { display.lastKey = wParam; } else { if (display.lastKey == 0) { display.lastAscii = 0; display.lastNull = false; return null; } } LRESULT result = null; if (!sendKeyEvent (SWT.KeyUp, OS.WM_KEYUP, wParam, lParam)) { result = LRESULT.ZERO; } // widget could be disposed at this point display.lastKey = display.lastAscii = 0; display.lastVirtual = display.lastNull = false; return result; } LRESULT WM_KILLFOCUS (int wParam, int lParam) { int code = callWindowProc (OS.WM_KILLFOCUS, wParam, lParam); sendFocusEvent (SWT.FocusOut, wParam); // widget could be disposed at this point /* * It is possible (but unlikely), that application * code could have disposed the widget in the focus * or deactivate events. If this happens, end the * processing of the Windows message by returning * zero as the result of the window proc. */ if (isDisposed ()) return LRESULT.ZERO; if (code == 0) return LRESULT.ZERO; return new LRESULT (code); } LRESULT WM_LBUTTONDBLCLK (int wParam, int lParam) { /* * Feature in Windows. Windows sends the following * messages when the user double clicks the mouse: * * WM_LBUTTONDOWN - mouse down * WM_LBUTTONUP - mouse up * WM_LBUTTONDBLCLK - double click * WM_LBUTTONUP - mouse up * * Applications that expect matching mouse down/up * pairs will not see the second mouse down. The * fix is to send a mouse down event. */ sendMouseEvent (SWT.MouseDown, 1, OS.WM_LBUTTONDOWN, wParam, lParam); sendMouseEvent (SWT.MouseDoubleClick, 1, OS.WM_LBUTTONDBLCLK, wParam, lParam); int result = callWindowProc (OS.WM_LBUTTONDBLCLK, wParam, lParam); if (OS.GetCapture () != handle) OS.SetCapture (handle); return new LRESULT (result); } LRESULT WM_LBUTTONDOWN (int wParam, int lParam) { boolean dragging = false, mouseDown = true; boolean dragDetect = hooks (SWT.DragDetect); if (dragDetect) { if (!OS.IsWinCE) { /* * Feature in Windows. It's possible that the drag * operation will not be started while the mouse is * down, meaning that the mouse should be captured. * This can happen when the user types the ESC key * to cancel the drag. The fix is to query the state * of the mouse and capture the mouse accordingly. */ POINT pt = new POINT (); pt.x = (short) (lParam & 0xFFFF); pt.y = (short) (lParam >> 16); OS.ClientToScreen(handle, pt); dragging = OS.DragDetect (handle, pt); mouseDown = OS.GetKeyState (OS.VK_LBUTTON) < 0; } } sendMouseEvent (SWT.MouseDown, 1, OS.WM_LBUTTONDOWN, wParam, lParam); int result = callWindowProc (OS.WM_LBUTTONDOWN, wParam, lParam); if (OS.IsPPC) { /* * Note: On WinCE PPC, only attempt to recognize the gesture for * a context menu when the control contains a valid menu or there * are listeners for the MenuDetect event. */ boolean hasMenu = menu != null && !menu.isDisposed (); if (hasMenu || hooks (SWT.MenuDetect)) { int x = (short) (lParam & 0xFFFF); int y = (short) (lParam >> 16); SHRGINFO shrg = new SHRGINFO (); shrg.cbSize = SHRGINFO.sizeof; shrg.hwndClient = handle; shrg.ptDown_x = x; shrg.ptDown_y = y; shrg.dwFlags = OS.SHRG_RETURNCMD; int type = OS.SHRecognizeGesture (shrg); if (type == OS.GN_CONTEXTMENU) showMenu (x, y); } } if (mouseDown) { if (OS.GetCapture () != handle) OS.SetCapture (handle); } if (dragging) { postEvent (SWT.DragDetect); } else { if (dragDetect) { /* * Feature in Windows. DragDetect() captures the mouse * and tracks its movement until the user releases the * left mouse button, presses the ESC key, or moves the * mouse outside the drag rectangle. If the user moves * the mouse outside of the drag rectangle, DragDetect() * returns true and a drag and drop operation can be * started. When the left mouse button is released or * the ESC key is pressed, these events are consumed by * DragDetect() so that application code that matches * mouse down/up pairs or looks for the ESC key will not * function properly. The fix is to send these events * when the drag has not started. * * NOTE: For now, don't send a fake WM_KEYDOWN/WM_KEYUP * events for the ESC key. This would require computing * wParam (the key) and lParam (the repeat count, scan code, * extended-key flag, context code, previous key-state flag, * and transition-state flag) which is non-trivial. */ if (OS.GetKeyState (OS.VK_ESCAPE) >= 0) { OS.SendMessage (handle, OS.WM_LBUTTONUP, wParam, lParam); } } } return new LRESULT (result); } LRESULT WM_LBUTTONUP (int wParam, int lParam) { sendMouseEvent (SWT.MouseUp, 1, OS.WM_LBUTTONUP, wParam, lParam); int result = callWindowProc (OS.WM_LBUTTONUP, wParam, lParam); if ((wParam & (OS.MK_LBUTTON | OS.MK_MBUTTON | OS.MK_RBUTTON)) == 0) { if (OS.GetCapture () == handle) OS.ReleaseCapture (); } return new LRESULT (result); } LRESULT WM_MBUTTONDBLCLK (int wParam, int lParam) { /* * Feature in Windows. Windows sends the following * messages when the user double clicks the mouse: * * WM_MBUTTONDOWN - mouse down * WM_MBUTTONUP - mouse up * WM_MLBUTTONDBLCLK - double click * WM_MBUTTONUP - mouse up * * Applications that expect matching mouse down/up * pairs will not see the second mouse down. The * fix is to send a mouse down event. */ sendMouseEvent (SWT.MouseDown, 2, OS.WM_MBUTTONDOWN, wParam, lParam); sendMouseEvent (SWT.MouseDoubleClick, 2, OS.WM_MBUTTONDBLCLK, wParam, lParam); int result = callWindowProc (OS.WM_MBUTTONDBLCLK, wParam, lParam); if (OS.GetCapture () != handle) OS.SetCapture (handle); return new LRESULT (result); } LRESULT WM_MBUTTONDOWN (int wParam, int lParam) { sendMouseEvent (SWT.MouseDown, 2, OS.WM_MBUTTONDOWN, wParam, lParam); int result = callWindowProc (OS.WM_MBUTTONDOWN, wParam, lParam); if (OS.GetCapture () != handle) OS.SetCapture(handle); return new LRESULT (result); } LRESULT WM_MBUTTONUP (int wParam, int lParam) { sendMouseEvent (SWT.MouseUp, 2, OS.WM_MBUTTONUP, wParam, lParam); int result = callWindowProc (OS.WM_MBUTTONUP, wParam, lParam); if ((wParam & (OS.MK_LBUTTON | OS.MK_MBUTTON | OS.MK_RBUTTON)) == 0) { if (OS.GetCapture () == handle) OS.ReleaseCapture (); } return new LRESULT (result); } LRESULT WM_MEASUREITEM (int wParam, int lParam) { MEASUREITEMSTRUCT struct = new MEASUREITEMSTRUCT (); OS.MoveMemory (struct, lParam, MEASUREITEMSTRUCT.sizeof); if (struct.CtlType == OS.ODT_MENU) { Decorations shell = menuShell (); MenuItem item = shell.findMenuItem (struct.itemID); if (item == null) return null; return item.wmMeasureChild (wParam, lParam); } int hwnd = OS.GetDlgItem (handle, struct.CtlID); Control control = display.getControl (hwnd); if (control == null) return null; return control.wmMeasureChild (wParam, lParam); } LRESULT WM_MENUCHAR (int wParam, int lParam) { /* * Feature in Windows. When the user types Alt+<key> * and <key> does not match a mnemonic in the System * menu or the menu bar, Windows beeps. This beep is * unexpected and unwanted by applications that look * for Alt+<key>. The fix is to detect the case and * stop Windows from beeping by closing the menu. */ int type = wParam >> 16; if (type == 0 || type == OS.MF_SYSMENU) { display.mnemonicKeyHit = false; return new LRESULT (OS.MNC_CLOSE << 16); } return null; } LRESULT WM_MENUSELECT (int wParam, int lParam) { int code = wParam >> 16; Shell shell = getShell (); if (code == -1 && lParam == 0) { Menu menu = shell.activeMenu; while (menu != null) { /* * When the user cancels any menu that is not the * menu bar, assume a mnemonic key was pressed to open * the menu from WM_SYSCHAR. When the menu was invoked * using the mouse, this assumption is wrong but not * harmful. This variable is only used in WM_SYSCHAR * and WM_SYSCHAR is only sent after the user has pressed * a mnemonic. */ display.mnemonicKeyHit = true; /* * It is possible (but unlikely), that application * code could have disposed the widget in the hide * event. If this happens, stop searching up the * parent list because there is no longer a link * to follow. */ menu.sendEvent (SWT.Hide); if (menu.isDisposed ()) break; menu = menu.getParentMenu (); } /* * The shell may be disposed because of sending the hide * event to the last active menu menu but setting a field * to null in a destroyed widget is not harmful. */ shell.activeMenu = null; return null; } if ((code & OS.MF_SYSMENU) != 0) return null; if ((code & OS.MF_HILITE) != 0) { MenuItem item = null; Decorations menuShell = menuShell (); if ((code & OS.MF_POPUP) != 0) { int index = wParam & 0xFFFF; MENUITEMINFO info = new MENUITEMINFO (); info.cbSize = MENUITEMINFO.sizeof; info.fMask = OS.MIIM_SUBMENU; if (OS.GetMenuItemInfo (lParam, index, true, info)) { Menu newMenu = menuShell.findMenu (info.hSubMenu); if (newMenu != null) item = newMenu.cascade; } } else { Menu newMenu = menuShell.findMenu (lParam); if (newMenu != null) { int id = wParam & 0xFFFF; item = menuShell.findMenuItem (id); } Menu oldMenu = shell.activeMenu; if (oldMenu != null) { Menu ancestor = oldMenu; while (ancestor != null && ancestor != newMenu) { ancestor = ancestor.getParentMenu (); } if (ancestor == newMenu) { ancestor = oldMenu; while (ancestor != newMenu) { /* * It is possible (but unlikely), that application * code could have disposed the widget in the hide * event or the item about to be armed. If this * happens, stop searching up the ancestor list * because there is no longer a link to follow. */ ancestor.sendEvent (SWT.Hide); if (ancestor.isDisposed ()) break; ancestor = ancestor.getParentMenu (); } /* * The shell and/or the item could be disposed when * processing hide events from above. If this happens, * ensure that the shell is not accessed and that no * arm event is sent to the item. */ if (!shell.isDisposed ()) { if (newMenu != null && newMenu.isDisposed ()) { newMenu = null; } shell.activeMenu = newMenu; } if (item != null && item.isDisposed ()) item = null; } } } if (item != null) item.sendEvent (SWT.Arm); } return null; } LRESULT WM_MOUSEACTIVATE (int wParam, int lParam) { return null; } LRESULT WM_MOUSEHOVER (int wParam, int lParam) { sendMouseEvent (SWT.MouseHover, 0, OS.WM_MOUSEHOVER, wParam, lParam); return null; } LRESULT WM_MOUSELEAVE (int wParam, int lParam) { int pos = OS.GetMessagePos (); POINT pt = new POINT (); pt.x = (short) (pos & 0xFFFF); pt.y = (short) (pos >> 16); OS.ScreenToClient (handle, pt); lParam = pt.x | (pt.y << 16); sendMouseEvent (SWT.MouseExit, 0, OS.WM_MOUSELEAVE, wParam, lParam); return null; } LRESULT WM_MOUSEMOVE (int wParam, int lParam) { if (!OS.IsWinCE) { boolean mouseEnter = hooks (SWT.MouseEnter) || display.filters (SWT.MouseEnter); boolean mouseExit = hooks (SWT.MouseExit) || display.filters (SWT.MouseExit); boolean mouseHover = hooks (SWT.MouseHover) || display.filters (SWT.MouseHover); if (mouseEnter || mouseExit || mouseHover) { TRACKMOUSEEVENT lpEventTrack = new TRACKMOUSEEVENT (); lpEventTrack.cbSize = TRACKMOUSEEVENT.sizeof; lpEventTrack.dwFlags = OS.TME_QUERY; lpEventTrack.hwndTrack = handle; OS.TrackMouseEvent (lpEventTrack); if (lpEventTrack.dwFlags == 0) { lpEventTrack.dwFlags = OS.TME_LEAVE | OS.TME_HOVER; lpEventTrack.hwndTrack = handle; OS.TrackMouseEvent (lpEventTrack); if (mouseEnter) { /* * Force all outstanding WM_MOUSELEAVE messages to be dispatched before * issuing a mouse enter. This causes mouse exit events to be processed * before mouse enter events. */ MSG msg = new MSG (); while (OS.PeekMessage (msg, 0, OS.WM_MOUSELEAVE, OS.WM_MOUSELEAVE, OS.PM_REMOVE)) { OS.TranslateMessage (msg); OS.DispatchMessage (msg); } sendMouseEvent (SWT.MouseEnter, 0, OS.WM_MOUSEMOVE, wParam, lParam); } } else { lpEventTrack.dwFlags = OS.TME_HOVER; OS.TrackMouseEvent (lpEventTrack); } } } int pos = OS.GetMessagePos (); if (pos != display.lastMouse) { display.lastMouse = pos; sendMouseEvent (SWT.MouseMove, 0, OS.WM_MOUSEMOVE, wParam, lParam); } return null; } LRESULT WM_MOUSEWHEEL (int wParam, int lParam) { return null; } LRESULT WM_MOVE (int wParam, int lParam) { sendEvent (SWT.Move); // widget could be disposed at this point return null; } LRESULT WM_NCACTIVATE (int wParam, int lParam) { return null; } LRESULT WM_NCCALCSIZE (int wParam, int lParam) { return null; } LRESULT WM_NCHITTEST (int wParam, int lParam) { if (!OS.IsWindowEnabled (handle)) return null; if (!isActive ()) return new LRESULT (OS.HTTRANSPARENT); return null; } LRESULT WM_NCLBUTTONDOWN (int wParam, int lParam) { return null; } LRESULT WM_NOTIFY (int wParam, int lParam) { NMHDR hdr = new NMHDR (); OS.MoveMemory (hdr, lParam, NMHDR.sizeof); int hwnd = hdr.hwndFrom; if (hwnd == 0) return null; Control control = display.getControl (hwnd); if (control == null) return null; return control.wmNotifyChild (wParam, lParam); } LRESULT WM_PAINT (int wParam, int lParam) { /* Exit early - don't draw the background */ if (!hooks (SWT.Paint) && !filters (SWT.Paint)) { return null; } /* Get the damage */ int result = 0; if (OS.IsWinCE) { RECT rect = new RECT (); OS.GetUpdateRect (handle, rect, false); result = callWindowProc (OS.WM_PAINT, wParam, lParam); OS.InvalidateRect (handle, rect, false); } else { int rgn = OS.CreateRectRgn (0, 0, 0, 0); OS.GetUpdateRgn (handle, rgn, false); result = callWindowProc (OS.WM_PAINT, wParam, lParam); OS.InvalidateRgn (handle, rgn, false); OS.DeleteObject (rgn); } /* Create the paint GC */ PAINTSTRUCT ps = new PAINTSTRUCT (); GCData data = new GCData (); data.ps = ps; GC gc = GC.win32_new (this, data); /* Send the paint event */ Event event = new Event (); event.gc = gc; event.x = ps.left; event.y = ps.top; event.width = ps.right - ps.left; event.height = ps.bottom - ps.top; /* * It is possible (but unlikely), that application * code could have disposed the widget in the paint * event. If this happens, attempt to give back the * paint GC anyways because this is a scarce Windows * resource. */ sendEvent (SWT.Paint, event); // widget could be disposed at this point /* Dispose the paint GC */ event.gc = null; gc.dispose (); if (result == 0) return LRESULT.ZERO; return new LRESULT (result); } LRESULT WM_PALETTECHANGED (int wParam, int lParam) { return null; } LRESULT WM_PARENTNOTIFY (int wParam, int lParam) { return null; } LRESULT WM_PASTE (int wParam, int lParam) { return null; } LRESULT WM_PRINTCLIENT (int wParam, int lParam) { return null; } LRESULT WM_QUERYENDSESSION (int wParam, int lParam) { return null; } LRESULT WM_QUERYNEWPALETTE (int wParam, int lParam) { return null; } LRESULT WM_QUERYOPEN (int wParam, int lParam) { return null; } LRESULT WM_RBUTTONDBLCLK (int wParam, int lParam) { /* * Feature in Windows. Windows sends the following * messages when the user double clicks the mouse: * * WM_RBUTTONDOWN - mouse down * WM_RBUTTONUP - mouse up * WM_RBUTTONDBLCLK - double click * WM_LBUTTONUP - mouse up * * Applications that expect matching mouse down/up * pairs will not see the second mouse down. The * fix is to send a mouse down event. */ sendMouseEvent (SWT.MouseDown, 3, OS.WM_RBUTTONDOWN, wParam, lParam); sendMouseEvent (SWT.MouseDoubleClick, 3, OS.WM_RBUTTONDBLCLK, wParam, lParam); int result = callWindowProc (OS.WM_RBUTTONDBLCLK, wParam, lParam); if (OS.GetCapture () != handle) OS.SetCapture (handle); return new LRESULT (result); } LRESULT WM_RBUTTONDOWN (int wParam, int lParam) { sendMouseEvent (SWT.MouseDown, 3, OS.WM_RBUTTONDOWN, wParam, lParam); int result = callWindowProc (OS.WM_RBUTTONDOWN, wParam, lParam); if (OS.GetCapture () != handle) OS.SetCapture (handle); return new LRESULT (result); } LRESULT WM_RBUTTONUP (int wParam, int lParam) { sendMouseEvent (SWT.MouseUp, 3, OS.WM_RBUTTONUP, wParam, lParam); int result = callWindowProc (OS.WM_RBUTTONUP, wParam, lParam); if ((wParam & (OS.MK_LBUTTON | OS.MK_MBUTTON | OS.MK_RBUTTON)) == 0) { if (OS.GetCapture () == handle) OS.ReleaseCapture (); } return new LRESULT (result); } LRESULT WM_SETCURSOR (int wParam, int lParam) { int hitTest = lParam & 0xFFFF; if (hitTest == OS.HTCLIENT) { Control control = display.getControl (wParam); if (control == null) return null; Cursor cursor = control.findCursor (); if (cursor != null) { OS.SetCursor (cursor.handle); return LRESULT.ONE; } } return null; } LRESULT WM_SETFOCUS (int wParam, int lParam) { int code = callWindowProc (OS.WM_SETFOCUS, wParam, lParam); sendFocusEvent (SWT.FocusIn, wParam); // widget could be disposed at this point /* * It is possible (but unlikely), that application * code could have disposed the widget in the focus * or activate events. If this happens, end the * processing of the Windows message by returning * zero as the result of the window proc. */ if (isDisposed ()) return LRESULT.ZERO; if (code == 0) return LRESULT.ZERO; return new LRESULT (code); } LRESULT WM_SETTINGCHANGE (int wParam, int lParam) { return null; } LRESULT WM_SETFONT (int wParam, int lParam) { return null; } LRESULT WM_SETREDRAW (int wParam, int lParam) { return null; } LRESULT WM_SHOWWINDOW (int wParam, int lParam) { return null; } LRESULT WM_SIZE (int wParam, int lParam) { sendEvent (SWT.Resize); // widget could be disposed at this point return null; } LRESULT WM_SYSCHAR (int wParam, int lParam) { Display display = this.display; display.lastAscii = wParam; display.lastNull = false; /* Do not issue a key down if a menu bar mnemonic was invoked */ if (!hooks (SWT.KeyDown) && !display.filters (SWT.KeyDown)) { return null; } display.mnemonicKeyHit = true; int result = callWindowProc (OS.WM_SYSCHAR, wParam, lParam); if (!display.mnemonicKeyHit) { sendKeyEvent (SWT.KeyDown, OS.WM_SYSCHAR, wParam, lParam); } // widget could be disposed at this point display.mnemonicKeyHit = false; return new LRESULT (result); } LRESULT WM_SYSCOLORCHANGE (int wParam, int lParam) { return null; } LRESULT WM_SYSCOMMAND (int wParam, int lParam) { /* * Check to see if the command is a system command or * a user menu item that was added to the System menu. * When a user item is added to the System menu, * WM_SYSCOMMAND must always return zero. */ if ((wParam & 0xF000) == 0) { Decorations shell = menuShell (); if (shell.isEnabled ()) { MenuItem item = shell.findMenuItem (wParam & 0xFFFF); if (item != null) item.wmCommandChild (wParam, lParam); } return LRESULT.ZERO; } /* Process the System Command */ int cmd = wParam & 0xFFF0; switch (cmd) { case OS.SC_CLOSE: int hwndShell = menuShell ().handle; int bits = OS.GetWindowLong (hwndShell, OS.GWL_STYLE); if ((bits & OS.WS_SYSMENU) == 0) return LRESULT.ZERO; break; case OS.SC_KEYMENU: /* * When lParam is zero, one of F10, Shift+F10, Ctrl+F10 or * Ctrl+Shift+F10 was pressed. If there is no menu bar and * the focus control is interested in keystrokes, give the * key to the focus control. Normally, F10 with no menu bar * moves focus to the System menu but this can be achieved * using Alt+Space. To allow the application to see F10, * avoid running the default window proc. * * NOTE: When F10 is pressed, WM_SYSCOMMAND is sent to the * shell, not the focus control. This is undocumented Windows * behavior. */ if (lParam == 0) { Decorations shell = menuShell (); Menu menu = shell.getMenuBar (); if (menu == null) { Control control = display.getFocusControl (); if (control != null) { if (control.hooks (SWT.KeyDown) || control.hooks (SWT.KeyUp)) { display.mnemonicKeyHit = false; return LRESULT.ZERO; } } } } else { /* * When lParam is not zero, Alt+<key> was pressed. If the * application is interested in keystrokes and there is a * menu bar, check to see whether the key that was pressed * matches a mnemonic on the menu bar. Normally, Windows * matches the first character of a menu item as well as * matching the mnemonic character. To allow the application * to see the keystrokes in this case, avoid running the default * window proc. * * NOTE: When the user types Alt+Space, the System menu is * activated. In this case the application should not see * the keystroke. */ if (hooks (SWT.KeyDown) || hooks (SWT.KeyUp)) { if (lParam != ' ') { Decorations shell = menuShell (); Menu menu = shell.getMenuBar (); if (menu != null) { char key = mbcsToWcs (lParam); if (key != 0) { key = Character.toUpperCase (key); MenuItem [] items = menu.getItems (); for (int i=0; i<items.length; i++) { MenuItem item = items [i]; String text = item.getText (); char mnemonic = findMnemonic (text); if (text.length () > 0 && mnemonic == 0) { char ch = text.charAt (0); if (Character.toUpperCase (ch) == key) { display.mnemonicKeyHit = false; return LRESULT.ZERO; } } } } } else { display.mnemonicKeyHit = false; } } } } // FALL THROUGH case OS.SC_HSCROLL: case OS.SC_VSCROLL: /* * Do not allow keyboard traversal of the menu bar * or scrolling when the shell is not enabled. */ Decorations shell = menuShell (); if (!shell.isEnabled () || !shell.isActive ()) { return LRESULT.ZERO; } break; case OS.SC_MINIMIZE: /* Save the focus widget when the shell is minimized */ menuShell ().saveFocus (); break; } return null; } LRESULT WM_SYSKEYDOWN (int wParam, int lParam) { /* * Feature in Windows. WM_SYSKEYDOWN is sent when * the user presses ALT-<aKey> or F10 without the ALT key. * In order to issue events for F10 (without the ALT key) * but ignore all other key presses without the ALT key, * make F10 a special case. */ if (wParam != OS.VK_F10) { /* Make sure WM_SYSKEYDOWN was sent by ALT-<aKey>. */ if ((lParam & 0x20000000) == 0) return null; } /* Ignore repeating modifier keys by testing key down state */ switch (wParam) { case OS.VK_SHIFT: case OS.VK_MENU: case OS.VK_CONTROL: case OS.VK_CAPITAL: case OS.VK_NUMLOCK: case OS.VK_SCROLL: if ((lParam & 0x40000000) != 0) return null; } /* Clear last key and last ascii because a new key has been typed */ display.lastAscii = display.lastKey = 0; display.lastVirtual = display.lastNull = false; /* If are going to get a WM_SYSCHAR, ignore this message. */ /* * Bug on WinCE. MapVirtualKey() returns incorrect values. * The fix is to rely on a key mappings table to determine * whether the key event must be sent now or if a WM_SYSCHAR * event will follow. */ int mapKey = OS.IsWinCE ? 0 : OS.MapVirtualKey (wParam, 2); display.lastVirtual = (mapKey == 0); if (display.lastVirtual) { display.lastKey = wParam; /* * Feature in Windows. The virtual key VK_DELETE is not * treated as both a virtual key and an ASCII key by Windows. * Therefore, we will not receive a WM_CHAR for this key. * The fix is to treat VK_DELETE as a special case and map * the ASCII value explictly (Delete is 0x7F). */ if (display.lastKey == OS.VK_DELETE) { display.lastVirtual = false; display.lastKey = display.lastAscii = 0x7F; } /* * It is possible to get a WM_CHAR for a virtual key when * Num Lock is on. If the user types Home while Num Lock * is down, a WM_CHAR is issued with WPARM=55 (for the * character 7). If we are going to get a WM_CHAR we need * to ensure that the last key has the correct value. Note * that Ctrl+Home does not issue a WM_CHAR when Num Lock is * down. * * NOTE: This only happens on Windows 98. */ if (OS.VK_NUMPAD0 <= display.lastKey && display.lastKey <= OS.VK_DIVIDE) { if (display.asciiKey (display.lastKey) != 0) return null; display.lastAscii = display.numpadKey (display.lastKey); } } else { /* * Convert LastKey to lower case because Windows non-virtual * keys that are also ASCII keys, such as like VK_A, are have * upper case values in WM_KEYDOWN despite the fact that the * Shift was not pressed. */ display.lastKey = OS.CharLower ((short) mapKey); /* * Feature in Windows 98. MapVirtualKey() indicates that * a WM_SYSCHAR message will occur for Alt+Enter but * this message never happens. The fix is to issue the * event from WM_SYSKEYDOWN and map VK_RETURN to '\r'. */ if (OS.IsWinNT) return null; if (wParam != OS.VK_RETURN) return null; display.lastAscii = '\r'; } if (!sendKeyEvent (SWT.KeyDown, OS.WM_SYSKEYDOWN, wParam, lParam)) { return LRESULT.ZERO; } // widget could be disposed at this point return null; } LRESULT WM_SYSKEYUP (int wParam, int lParam) { return WM_KEYUP (wParam, lParam); } LRESULT WM_TIMER (int wParam, int lParam) { return null; } LRESULT WM_UNDO (int wParam, int lParam) { return null; } LRESULT WM_VSCROLL (int wParam, int lParam) { if (lParam == 0) return null; Control control = display.getControl (lParam); if (control == null) return null; return control.wmScrollChild (wParam, lParam); } LRESULT WM_WINDOWPOSCHANGED (int wParam, int lParam) { return null; } LRESULT WM_WINDOWPOSCHANGING (int wParam, int lParam) { return null; } LRESULT wmColorChild (int wParam, int lParam) { if (background == -1 && foreground == -1) return null; int forePixel = foreground, backPixel = background; if (forePixel == -1) forePixel = defaultForeground (); if (backPixel == -1) backPixel = defaultBackground (); OS.SetTextColor (wParam, forePixel); OS.SetBkColor (wParam, backPixel); return new LRESULT (findBrush (backPixel)); } LRESULT wmCommandChild (int wParam, int lParam) { return null; } LRESULT wmDrawChild (int wParam, int lParam) { return null; } LRESULT wmMeasureChild (int wParam, int lParam) { return null; } LRESULT wmNotifyChild (int wParam, int lParam) { return null; } LRESULT wmScrollChild (int wParam, int lParam) { return null; } }
[ "375833274@qq.com" ]
375833274@qq.com
0267f15a9fb7137ae24ee648f578b83c978b1562
32cd70512c7a661aeefee440586339211fbc9efd
/aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53/model/CreateReusableDelegationSetRequest.java
7dd333b86f4e4fee934d1abe3faf49dade61d2d9
[ "Apache-2.0" ]
permissive
twigkit/aws-sdk-java
7409d949ce0b0fbd061e787a5b39a93db7247d3d
0b8dd8cf5e52ad7ae57acd2ce7a584fd83a998be
refs/heads/master
2020-04-03T16:40:16.625651
2018-05-04T12:05:14
2018-05-04T12:05:14
60,255,938
0
1
Apache-2.0
2018-05-04T12:48:26
2016-06-02T10:40:53
Java
UTF-8
Java
false
false
10,359
java
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.route53.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; /** * */ public class CreateReusableDelegationSetRequest extends AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * A unique string that identifies the request and that allows failed * <code>CreateReusableDelegationSet</code> requests to be retried without * the risk of executing the operation twice. You must use a unique * <code>CallerReference</code> string every time you create a reusable * delegation set. <code>CallerReference</code> can be any unique string; * you might choose to use a string that identifies your project, such as * <code>DNSMigration_01</code>. * </p> * <p> * Valid characters are any Unicode code points that are legal in an XML 1.0 * document. The UTF-8 encoding of the value must be less than 128 bytes. * </p> */ private String callerReference; /** * <p> * The ID of the hosted zone whose delegation set you want to mark as * reusable. It is an optional parameter. * </p> */ private String hostedZoneId; /** * <p> * A unique string that identifies the request and that allows failed * <code>CreateReusableDelegationSet</code> requests to be retried without * the risk of executing the operation twice. You must use a unique * <code>CallerReference</code> string every time you create a reusable * delegation set. <code>CallerReference</code> can be any unique string; * you might choose to use a string that identifies your project, such as * <code>DNSMigration_01</code>. * </p> * <p> * Valid characters are any Unicode code points that are legal in an XML 1.0 * document. The UTF-8 encoding of the value must be less than 128 bytes. * </p> * * @param callerReference * A unique string that identifies the request and that allows failed * <code>CreateReusableDelegationSet</code> requests to be retried * without the risk of executing the operation twice. You must use a * unique <code>CallerReference</code> string every time you create a * reusable delegation set. <code>CallerReference</code> can be any * unique string; you might choose to use a string that identifies * your project, such as <code>DNSMigration_01</code>.</p> * <p> * Valid characters are any Unicode code points that are legal in an * XML 1.0 document. The UTF-8 encoding of the value must be less * than 128 bytes. */ public void setCallerReference(String callerReference) { this.callerReference = callerReference; } /** * <p> * A unique string that identifies the request and that allows failed * <code>CreateReusableDelegationSet</code> requests to be retried without * the risk of executing the operation twice. You must use a unique * <code>CallerReference</code> string every time you create a reusable * delegation set. <code>CallerReference</code> can be any unique string; * you might choose to use a string that identifies your project, such as * <code>DNSMigration_01</code>. * </p> * <p> * Valid characters are any Unicode code points that are legal in an XML 1.0 * document. The UTF-8 encoding of the value must be less than 128 bytes. * </p> * * @return A unique string that identifies the request and that allows * failed <code>CreateReusableDelegationSet</code> requests to be * retried without the risk of executing the operation twice. You * must use a unique <code>CallerReference</code> string every time * you create a reusable delegation set. * <code>CallerReference</code> can be any unique string; you might * choose to use a string that identifies your project, such as * <code>DNSMigration_01</code>.</p> * <p> * Valid characters are any Unicode code points that are legal in an * XML 1.0 document. The UTF-8 encoding of the value must be less * than 128 bytes. */ public String getCallerReference() { return this.callerReference; } /** * <p> * A unique string that identifies the request and that allows failed * <code>CreateReusableDelegationSet</code> requests to be retried without * the risk of executing the operation twice. You must use a unique * <code>CallerReference</code> string every time you create a reusable * delegation set. <code>CallerReference</code> can be any unique string; * you might choose to use a string that identifies your project, such as * <code>DNSMigration_01</code>. * </p> * <p> * Valid characters are any Unicode code points that are legal in an XML 1.0 * document. The UTF-8 encoding of the value must be less than 128 bytes. * </p> * * @param callerReference * A unique string that identifies the request and that allows failed * <code>CreateReusableDelegationSet</code> requests to be retried * without the risk of executing the operation twice. You must use a * unique <code>CallerReference</code> string every time you create a * reusable delegation set. <code>CallerReference</code> can be any * unique string; you might choose to use a string that identifies * your project, such as <code>DNSMigration_01</code>.</p> * <p> * Valid characters are any Unicode code points that are legal in an * XML 1.0 document. The UTF-8 encoding of the value must be less * than 128 bytes. * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateReusableDelegationSetRequest withCallerReference( String callerReference) { setCallerReference(callerReference); return this; } /** * <p> * The ID of the hosted zone whose delegation set you want to mark as * reusable. It is an optional parameter. * </p> * * @param hostedZoneId * The ID of the hosted zone whose delegation set you want to mark as * reusable. It is an optional parameter. */ public void setHostedZoneId(String hostedZoneId) { this.hostedZoneId = hostedZoneId; } /** * <p> * The ID of the hosted zone whose delegation set you want to mark as * reusable. It is an optional parameter. * </p> * * @return The ID of the hosted zone whose delegation set you want to mark * as reusable. It is an optional parameter. */ public String getHostedZoneId() { return this.hostedZoneId; } /** * <p> * The ID of the hosted zone whose delegation set you want to mark as * reusable. It is an optional parameter. * </p> * * @param hostedZoneId * The ID of the hosted zone whose delegation set you want to mark as * reusable. It is an optional parameter. * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateReusableDelegationSetRequest withHostedZoneId( String hostedZoneId) { setHostedZoneId(hostedZoneId); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getCallerReference() != null) sb.append("CallerReference: " + getCallerReference() + ","); if (getHostedZoneId() != null) sb.append("HostedZoneId: " + getHostedZoneId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateReusableDelegationSetRequest == false) return false; CreateReusableDelegationSetRequest other = (CreateReusableDelegationSetRequest) obj; if (other.getCallerReference() == null ^ this.getCallerReference() == null) return false; if (other.getCallerReference() != null && other.getCallerReference().equals(this.getCallerReference()) == false) return false; if (other.getHostedZoneId() == null ^ this.getHostedZoneId() == null) return false; if (other.getHostedZoneId() != null && other.getHostedZoneId().equals(this.getHostedZoneId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCallerReference() == null) ? 0 : getCallerReference() .hashCode()); hashCode = prime * hashCode + ((getHostedZoneId() == null) ? 0 : getHostedZoneId() .hashCode()); return hashCode; } @Override public CreateReusableDelegationSetRequest clone() { return (CreateReusableDelegationSetRequest) super.clone(); } }
[ "aws@amazon.com" ]
aws@amazon.com
c2817b70dd5cc4de302beaf9cccf7cd155752aae
b9189a64042dd5440f24b8ae8e41ae0359396334
/src/main/java/com/example/company/repository/DictionaryRepository.java
a76150f262b518ad6b999b08c0bebce5af6549e0
[]
no_license
only3c/company
8cea5b897426f39952e02eb29716529249ae27ab
2b7a20fdcf2b5d9a2a4e76db850c79d014087cf0
refs/heads/master
2022-07-14T23:58:31.404724
2019-10-09T03:42:40
2019-10-09T03:42:40
153,580,343
1
0
null
2022-06-29T17:00:57
2018-10-18T07:19:03
JavaScript
UTF-8
Java
false
false
1,015
java
package com.example.company.repository; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.example.company.model.Dictionary; public interface DictionaryRepository extends JpaRepository<Dictionary, Long> { List<Dictionary> findListByDatatypeAndParentcode(String datatype, String parentcode); // List<Dictionary> findListByDatatype(String datatype); Dictionary findOneByDatatypeAndDatacode(String datatype, String datacode); Dictionary findOneByDatatypeAndDatacodeAndParentcode(String datatype, String datacode, String parentcode); Page<Dictionary> findAllByDatatypeLikeAndDatatypenameLikeAndDatanameLike(String datatype, String datatypename, String dataname, Pageable pageable); @Query(value="select Max(id) from dictionary", nativeQuery = true) Integer findMaxId(); void deleteAllByIdIn(Long[] num); }
[ "caocongchao@yondervision.com.cn" ]
caocongchao@yondervision.com.cn
7ccc02427ed946999740990ebdad722ff8f85954
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/3/3_be99f230b6ef154a30e3144de69e1e516d11f7bf/TestApp/3_be99f230b6ef154a30e3144de69e1e516d11f7bf_TestApp_t.java
0d571c9eabace80ec382282affbc6bd769bd0e06
[]
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
45,610
java
/* * Copyright (c) 2008-2010, Hazel Ltd. All Rights Reserved. * * 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.hazelcast.examples; import com.hazelcast.core.*; import com.hazelcast.partition.Partition; import java.io.*; import java.lang.management.ManagementFactory; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.*; import java.util.concurrent.locks.Lock; /** * Special thanks to Alexandre Vasseur for providing this very nice test * application. * * @author alex, talip */ public class TestApp implements EntryListener, ItemListener, MessageListener { private IQueue<Object> queue = null; private ITopic<Object> topic = null; private IMap<Object, Object> map = null; private ISet<Object> set = null; private IList<Object> list = null; private String namespace = "default"; private boolean silent = false; private boolean echo = false; private volatile HazelcastInstance hazelcast; private volatile LineReader lineReader; private volatile boolean running = false; public TestApp(HazelcastInstance hazelcast) { this.hazelcast = hazelcast; } public IQueue<Object> getQueue() { // if (queue == null) { queue = hazelcast.getQueue(namespace); // } return queue; } public ITopic<Object> getTopic() { // if (topic == null) { topic = hazelcast.getTopic(namespace); // } return topic; } public IMap<Object, Object> getMap() { // if (map == null) { map = hazelcast.getMap(namespace); // } return map; } public ISet<Object> getSet() { // if (set == null) { set = hazelcast.getSet(namespace); // } return set; } public IList<Object> getList() { // if (list == null) { list = hazelcast.getList(namespace); // } return list; } public void setHazelcast(HazelcastInstance hazelcast) { this.hazelcast = hazelcast; map = null; list = null; set = null; queue = null; topic = null; } public static void main(String[] args) throws Exception { TestApp testApp = new TestApp(Hazelcast.getDefaultInstance()); testApp.start(args); } public void stop() { running = false; } public void start(String[] args) throws Exception { if (lineReader == null) { lineReader = new DefaultLineReader(); } running = true; while (running) { print("hazelcast[" + namespace + "] > "); try { final String command = lineReader.readLine(); handleCommand(command); } catch (Throwable e) { e.printStackTrace(); } } } public void setLineReader(LineReader lineReader) { this.lineReader = lineReader; } class DefaultLineReader implements LineReader { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public String readLine() throws Exception { return in.readLine(); } } class HistoricLineReader implements LineReader { InputStream in = System.in; public String readLine() throws Exception { while (true) { System.in.read(); println("char " + System.in.read()); } } int readCharacter() throws Exception { return in.read(); } } protected void handleCommand(String command) { if (echo) { if (Thread.currentThread().getName().toLowerCase().indexOf("main") < 0) println(" [" + Thread.currentThread().getName() + "] " + command); else println(command); } if (command == null || command.startsWith("//")) return; command = command.trim(); if (command == null || command.length() == 0) { return; } String first = command; int spaceIndex = command.indexOf(' '); String[] argsSplit = command.split(" "); String[] args = new String[argsSplit.length]; for (int i = 0; i < argsSplit.length; i++) { args[i] = argsSplit[i].trim(); } if (spaceIndex != -1) { first = args[0]; } if (command.startsWith("help")) { handleHelp(command); } else if (first.startsWith("#") && first.length() > 1) { int repeat = Integer.parseInt(first.substring(1)); long t0 = System.currentTimeMillis(); for (int i = 0; i < repeat; i++) { handleCommand(command.substring(first.length()).replaceAll("\\$i", "" + i)); } System.out.println("ops/s = " + repeat * 1000 / (System.currentTimeMillis() - t0)); return; } else if (first.startsWith("&") && first.length() > 1) { final int fork = Integer.parseInt(first.substring(1)); ExecutorService pool = Executors.newFixedThreadPool(fork); final String threadCommand = command.substring(first.length()); for (int i = 0; i < fork; i++) { final int threadID = i; pool.submit(new Runnable() { public void run() { String command = threadCommand; String[] threadArgs = command.replaceAll("\\$t", "" + threadID).trim() .split(" "); // TODO &t #4 m.putmany x k if ("m.putmany".equals(threadArgs[0]) || "m.removemany".equals(threadArgs[0])) { if (threadArgs.length < 4) { command += " " + Integer.parseInt(threadArgs[1]) * threadID; } } handleCommand(command); } }); } pool.shutdown(); try { pool.awaitTermination(60 * 60, TimeUnit.SECONDS);// wait 1h } catch (Exception e) { e.printStackTrace(); } } else if (first.startsWith("@")) { if (first.length() == 1) { println("usage: @<file-name>"); return; } File f = new File(first.substring(1)); println("Executing script file " + f.getAbsolutePath()); if (f.exists()) { try { BufferedReader br = new BufferedReader(new FileReader(f)); String l = br.readLine(); while (l != null) { handleCommand(l); l = br.readLine(); } br.close(); } catch (IOException e) { e.printStackTrace(); } } else { println("File not found! " + f.getAbsolutePath()); } } else if (command.indexOf(';') != -1) { StringTokenizer st = new StringTokenizer(command, ";"); while (st.hasMoreTokens()) { handleCommand(st.nextToken()); } return; } else if ("silent".equals(first)) { silent = Boolean.parseBoolean(args[1]); } else if ("restart".equals(first)) { hazelcast.restart(); } else if ("shutdown".equals(first)) { hazelcast.shutdown(); } else if ("echo".equals(first)) { echo = Boolean.parseBoolean(args[1]); println("echo: " + echo); } else if ("ns".equals(first)) { if (args.length > 1) { namespace = args[1]; println("namespace: " + namespace); // init(); } } else if ("whoami".equals(first)) { println(hazelcast.getCluster().getLocalMember()); } else if ("who".equals(first)) { println(hazelcast.getCluster()); } else if ("jvm".equals(first)) { System.gc(); println("Memory max: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "M"); println("Memory free: " + Runtime.getRuntime().freeMemory() / 1024 / 1024 + "M " + (int) (Runtime.getRuntime().freeMemory() * 100 / Runtime.getRuntime() .maxMemory()) + "%"); long total = Runtime.getRuntime().totalMemory(); long free = Runtime.getRuntime().freeMemory(); println("Used Memory:" + ((total - free) / 1024 / 1024) + "MB"); println("# procs: " + Runtime.getRuntime().availableProcessors()); println("OS info: " + ManagementFactory.getOperatingSystemMXBean().getArch() + " " + ManagementFactory.getOperatingSystemMXBean().getName() + " " + ManagementFactory.getOperatingSystemMXBean().getVersion()); println("JVM: " + ManagementFactory.getRuntimeMXBean().getVmVendor() + " " + ManagementFactory.getRuntimeMXBean().getVmName() + " " + ManagementFactory.getRuntimeMXBean().getVmVersion()); } else if (first.indexOf("ock") != -1 && first.indexOf(".") == -1) { handleLock(args); } else if (first.indexOf(".size") != -1) { handleSize(args); } else if (first.indexOf(".clear") != -1) { handleClear(args); } else if (first.indexOf(".destroy") != -1) { handleDestroy(args); } else if (first.indexOf(".iterator") != -1) { handleIterator(args); } else if (first.indexOf(".contains") != -1) { handleContains(args); } else if (first.indexOf(".stats") != -1) { handStats(args); } else if ("t.publish".equals(first)) { handleTopicPublish(args); } else if ("q.offer".equals(first)) { handleQOffer(args); } else if ("q.take".equals(first)) { handleQTake(args); } else if ("q.poll".equals(first)) { handleQPoll(args); } else if ("q.peek".equals(first)) { handleQPeek(args); } else if ("q.capacity".equals(first)) { handleQCapacity(args); } else if ("q.offermany".equals(first)) { handleQOfferMany(args); } else if ("q.pollmany".equals(first)) { handleQPollMany(args); } else if ("s.add".equals(first)) { handleSetAdd(args); } else if ("s.remove".equals(first)) { handleSetRemove(args); } else if ("s.addmany".equals(first)) { handleSetAddMany(args); } else if ("s.removemany".equals(first)) { handleSetRemoveMany(args); } else if (first.equals("m.replace")) { handleMapReplace(args); } else if (first.equalsIgnoreCase("m.putIfAbsent")) { handleMapPutIfAbsent(args); } else if (first.equals("m.putAsync")) { handleMapPutAsync(args); } else if (first.equals("m.getAsync")) { handleMapGetAsync(args); } else if (first.equals("m.put")) { handleMapPut(args); } else if (first.equals("m.get")) { handleMapGet(args); } else if (first.equalsIgnoreCase("m.getMapEntry")) { handleMapGetMapEntry(args); } else if (first.equals("m.remove")) { handleMapRemove(args); } else if (first.equals("m.evict")) { handleMapEvict(args); } else if (first.equals("m.putmany") || first.equalsIgnoreCase("m.putAll")) { handleMapPutMany(args); } else if (first.equals("m.getmany")) { handleMapGetMany(args); } else if (first.equals("m.removemany")) { handleMapRemoveMany(args); } else if (command.equalsIgnoreCase("m.localKeys")) { handleMapLocalKeys(); } else if (command.equals("m.keys")) { handleMapKeys(); } else if (command.equals("m.values")) { handleMapValues(); } else if (command.equals("m.entries")) { handleMapEntries(); } else if (first.equals("m.lock")) { handleMapLock(args); } else if (first.equalsIgnoreCase("m.tryLock")) { handleMapTryLock(args); } else if (first.equals("m.unlock")) { handleMapUnlock(args); } else if (first.indexOf(".addListener") != -1) { handleAddListener(args); } else if (first.equals("m.removeMapListener")) { handleRemoveListener(args); } else if (first.equals("m.unlock")) { handleMapUnlock(args); } else if (first.equals("l.add")) { handleListAdd(args); } else if ("l.addmany".equals(first)) { handleListAddMany(args); } else if (first.equals("l.remove")) { handleListRemove(args); } else if (first.equals("l.contains")) { handleListContains(args); } else if (first.equals("execute")) { execute(args); } else if (first.equals("partitions")) { handlePartitions(args); } else if (first.equals("txn")) { hazelcast.getTransaction().begin(); } else if (first.equals("commit")) { hazelcast.getTransaction().commit(); } else if (first.equals("rollback")) { hazelcast.getTransaction().rollback(); } else if (first.equalsIgnoreCase("executeOnKey")) { executeOnKey(args); } else if (first.equalsIgnoreCase("executeOnMember")) { executeOnMember(args); } else if (first.equalsIgnoreCase("executeOnMembers")) { executeOnMembers(args); } else if (first.equalsIgnoreCase("longOther") || first.equalsIgnoreCase("executeLongOther")) { executeLongTaskOnOtherMember(args); } else if (first.equalsIgnoreCase("long") || first.equalsIgnoreCase("executeLong")) { executeLong(args); } else if (first.equalsIgnoreCase("instances")) { handleInstances(args); } else if (first.equalsIgnoreCase("quit") || first.equalsIgnoreCase("exit")) { System.exit(0); } else { println("type 'help' for help"); } } protected void handlePartitions(String[] args) { Set<Partition> partitions = hazelcast.getPartitionService().getPartitions(); Map<Member, Integer> partitionCounts = new HashMap<Member, Integer>(); for (Partition partition : partitions) { Member owner = partition.getOwner(); if (owner != null) { Integer count = partitionCounts.get(owner); int newCount = 1; if (count != null) { newCount = count + 1; } partitionCounts.put(owner, newCount); } println(partition); } Set<Map.Entry<Member, Integer>> entries = partitionCounts.entrySet(); for (Map.Entry<Member, Integer> entry : entries) { println(entry.getKey() + ":" + entry.getValue()); } } protected void handleInstances(String[] args) { Collection<Instance> instances = hazelcast.getInstances(); for (Instance instance : instances) { println(instance); } } protected void handleListContains(String[] args) { println(getList().contains(args[1])); } protected void handleListRemove(String[] args) { println(getList().remove(args[1])); } protected void handleListAdd(String[] args) { println(getList().add(args[1])); } protected void handleMapPut(String[] args) { println(getMap().put(args[1], args[2])); } protected void handleMapPutAsync(String[] args) { try { println(getMap().putAsync(args[1], args[2]).get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } protected void handleMapPutIfAbsent(String[] args) { println(getMap().putIfAbsent(args[1], args[2])); } protected void handleMapReplace(String[] args) { println(getMap().replace(args[1], args[2])); } protected void handleMapGet(String[] args) { println(getMap().get(args[1])); } protected void handleMapGetAsync(String[] args) { try { println(getMap().getAsync(args[1]).get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } protected void handleMapGetMapEntry(String[] args) { println(getMap().getMapEntry(args[1])); } protected void handleMapRemove(String[] args) { println(getMap().remove(args[1])); } protected void handleMapEvict(String[] args) { println(getMap().evict(args[1])); } protected void handleMapPutMany(String[] args) { int count = 1; if (args.length > 1) count = Integer.parseInt(args[1]); int b = 100; byte[] value = new byte[b]; if (args.length > 2) { b = Integer.parseInt(args[2]); value = new byte[b]; } int start = getMap().size(); if (args.length > 3) { start = Integer.parseInt(args[3]); } Map theMap = new HashMap(count); for (int i = 0; i < count; i++) { theMap.put("key" + (start + i), value); } long t0 = System.currentTimeMillis(); getMap().putAll(theMap); long t1 = System.currentTimeMillis(); if (t1 - t0 > 1) { println("size = " + getMap().size() + ", " + count * 1000 / (t1 - t0) + " evt/s, " + (count * 1000 / (t1 - t0)) * (b * 8) / 1024 + " Kbit/s, " + count * b / 1024 + " KB added"); } } private void handStats(String[] args) { String iteratorStr = args[0]; if (iteratorStr.startsWith("s.")) { } else if (iteratorStr.startsWith("m.")) { println(getMap().getLocalMapStats()); } else if (iteratorStr.startsWith("q.")) { println(getQueue().getLocalQueueStats()); } else if (iteratorStr.startsWith("l.")) { } } protected void handleMapGetMany(String[] args) { int count = 1; if (args.length > 1) count = Integer.parseInt(args[1]); for (int i = 0; i < count; i++) { println(getMap().get("key" + i)); } } protected void handleMapRemoveMany(String[] args) { int count = 1; if (args.length > 1) count = Integer.parseInt(args[1]); int start = 0; if (args.length > 2) start = Integer.parseInt(args[2]); long t0 = System.currentTimeMillis(); for (int i = 0; i < count; i++) { getMap().remove("key" + (start + i)); } long t1 = System.currentTimeMillis(); println("size = " + getMap().size() + ", " + count * 1000 / (t1 - t0) + " evt/s"); } protected void handleMapLock(String[] args) { getMap().lock(args[1]); println("true"); } protected void handleLock(String[] args) { String lockStr = args[0]; String key = args[1]; Lock lock = hazelcast.getLock(key); if (lockStr.equalsIgnoreCase("lock")) { lock.lock(); println("true"); } else if (lockStr.equalsIgnoreCase("unlock")) { lock.unlock(); println("true"); } else if (lockStr.equalsIgnoreCase("trylock")) { String timeout = args.length > 2 ? args[2] : null; if (timeout == null) { println(lock.tryLock()); } else { long time = Long.valueOf(timeout); try { println(lock.tryLock(time, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } } } } protected void handleMapTryLock(String[] args) { String key = args[1]; long time = (args.length > 2) ? Long.valueOf(args[2]) : 0; boolean locked = false; if (time == 0) locked = getMap().tryLock(key); else locked = getMap().tryLock(key, time, TimeUnit.SECONDS); println(locked); } protected void handleMapUnlock(String[] args) { getMap().unlock(args[1]); println("true"); } protected void handleAddListener(String[] args) { String first = args[0]; if (first.startsWith("s.")) { getSet().addItemListener(this, true); } else if (first.startsWith("m.")) { if (args.length > 1) { getMap().addEntryListener(this, args[1], true); } else { getMap().addEntryListener(this, true); } } else if (first.startsWith("q.")) { getQueue().addItemListener(this, true); } else if (first.startsWith("t.")) { getTopic().addMessageListener(this); } else if (first.startsWith("l.")) { getList().addItemListener(this, true); } } protected void handleRemoveListener(String[] args) { String first = args[0]; if (first.startsWith("s.")) { getSet().removeItemListener(this); } else if (first.startsWith("m.")) { if (args.length > 1) { getMap().removeEntryListener(this, args[1]); } else { getMap().removeEntryListener(this); } } else if (first.startsWith("q.")) { getQueue().removeItemListener(this); } else if (first.startsWith("t.")) { getTopic().removeMessageListener(this); } else if (first.startsWith("l.")) { getList().removeItemListener(this); } } protected void handleMapLocalKeys() { Set set = getMap().localKeySet(); Iterator it = set.iterator(); int count = 0; while (it.hasNext()) { count++; println(it.next()); } println("Total " + count); } protected void handleMapKeys() { Set set = getMap().keySet(); Iterator it = set.iterator(); int count = 0; while (it.hasNext()) { count++; println(it.next()); } println("Total " + count); } protected void handleMapEntries() { Set set = getMap().entrySet(); Iterator it = set.iterator(); int count = 0; long time = System.currentTimeMillis(); while (it.hasNext()) { count++; Map.Entry entry = (Entry) it.next(); println(entry.getKey() + " : " + entry.getValue()); } println("Total " + count); } protected void handleMapValues() { Collection set = getMap().values(); Iterator it = set.iterator(); int count = 0; while (it.hasNext()) { count++; println(it.next()); } println("Total " + count); } protected void handleSetAdd(String[] args) { println(getSet().add(args[1])); } protected void handleSetRemove(String[] args) { println(getSet().remove(args[1])); } protected void handleSetAddMany(String[] args) { int count = 1; if (args.length > 1) count = Integer.parseInt(args[1]); int successCount = 0; long t0 = System.currentTimeMillis(); for (int i = 0; i < count; i++) { boolean success = getSet().add("obj" + i); if (success) successCount++; } long t1 = System.currentTimeMillis(); println("Added " + successCount + " objects."); println("size = " + getSet().size() + ", " + successCount * 1000 / (t1 - t0) + " evt/s"); } protected void handleListAddMany(String[] args) { int count = 1; if (args.length > 1) count = Integer.parseInt(args[1]); int successCount = 0; long t0 = System.currentTimeMillis(); for (int i = 0; i < count; i++) { boolean success = getList().add("obj" + i); if (success) successCount++; } long t1 = System.currentTimeMillis(); println("Added " + successCount + " objects."); println("size = " + list.size() + ", " + successCount * 1000 / (t1 - t0) + " evt/s"); } protected void handleSetRemoveMany(String[] args) { int count = 1; if (args.length > 1) count = Integer.parseInt(args[1]); int successCount = 0; long t0 = System.currentTimeMillis(); for (int i = 0; i < count; i++) { boolean success = getSet().remove("obj" + i); if (success) successCount++; } long t1 = System.currentTimeMillis(); println("Removed " + successCount + " objects."); println("size = " + getSet().size() + ", " + successCount * 1000 / (t1 - t0) + " evt/s"); } protected void handleIterator(String[] args) { Iterator it = null; String iteratorStr = args[0]; if (iteratorStr.startsWith("s.")) { it = getSet().iterator(); } else if (iteratorStr.startsWith("m.")) { it = getMap().keySet().iterator(); } else if (iteratorStr.startsWith("q.")) { it = getQueue().iterator(); } else if (iteratorStr.startsWith("l.")) { it = getList().iterator(); } boolean remove = false; if (args.length > 1) { String removeStr = args[1]; remove = removeStr.equals("remove"); } int count = 1; while (it.hasNext()) { print(count++ + " " + it.next()); if (remove) { it.remove(); print(" removed"); } println(""); } } protected void handleContains(String[] args) { String iteratorStr = args[0]; boolean key = false; boolean value = false; if (iteratorStr.toLowerCase().endsWith("key")) { key = true; } else if (iteratorStr.toLowerCase().endsWith("value")) { value = true; } String data = args[1]; boolean result = false; if (iteratorStr.startsWith("s.")) { result = getSet().contains(data); } else if (iteratorStr.startsWith("m.")) { result = (key) ? getMap().containsKey(data) : getMap().containsValue(data); } else if (iteratorStr.startsWith("q.")) { result = getQueue().contains(data); } else if (iteratorStr.startsWith("l.")) { result = getList().contains(data); } println("Contains : " + result); } protected void handleSize(String[] args) { int size = 0; String iteratorStr = args[0]; if (iteratorStr.startsWith("s.")) { size = getSet().size(); } else if (iteratorStr.startsWith("m.")) { size = getMap().size(); } else if (iteratorStr.startsWith("q.")) { size = getQueue().size(); } else if (iteratorStr.startsWith("l.")) { size = getList().size(); } println("Size = " + size); } protected void handleClear(String[] args) { String iteratorStr = args[0]; if (iteratorStr.startsWith("s.")) { getSet().clear(); } else if (iteratorStr.startsWith("m.")) { getMap().clear(); } else if (iteratorStr.startsWith("q.")) { getQueue().clear(); } else if (iteratorStr.startsWith("l.")) { getList().clear(); } println("Cleared all."); } protected void handleDestroy(String[] args) { String iteratorStr = args[0]; if (iteratorStr.startsWith("s.")) { getSet().destroy(); } else if (iteratorStr.startsWith("m.")) { getMap().destroy(); } else if (iteratorStr.startsWith("q.")) { getQueue().destroy(); } else if (iteratorStr.startsWith("l.")) { getList().destroy(); } else if (iteratorStr.startsWith("t.")) { getTopic().destroy(); } println("Destroyed!"); } protected void handleQOffer(String[] args) { long timeout = 0; if (args.length > 2) { timeout = Long.valueOf(args[2]); } try { boolean offered = getQueue().offer(args[1], timeout, TimeUnit.SECONDS); println(offered); } catch (InterruptedException e) { e.printStackTrace(); } } protected void handleQTake(String[] args) { try { println(getQueue().take()); } catch (InterruptedException e) { e.printStackTrace(); } } protected void handleQPoll(String[] args) { long timeout = 0; if (args.length > 1) { timeout = Long.valueOf(args[1]); } try { println(getQueue().poll(timeout, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } } protected void handleTopicPublish(String[] args) { getTopic().publish(args[1]); } protected void handleQOfferMany(String[] args) { int count = 1; if (args.length > 1) count = Integer.parseInt(args[1]); Object value = null; if (args.length > 2) value = new byte[Integer.parseInt(args[2])]; long t0 = System.currentTimeMillis(); for (int i = 0; i < count; i++) { if (value == null) getQueue().offer("obj"); else getQueue().offer(value); } long t1 = System.currentTimeMillis(); print("size = " + getQueue().size() + ", " + count * 1000 / (t1 - t0) + " evt/s"); if (value == null) { println(""); } else { int b = Integer.parseInt(args[2]); println(", " + (count * 1000 / (t1 - t0)) * (b * 8) / 1024 + " Kbit/s, " + count * b / 1024 + " KB added"); } } protected void handleQPollMany(String[] args) { int count = 1; if (args.length > 1) count = Integer.parseInt(args[1]); int c = 1; for (int i = 0; i < count; i++) { Object obj = getQueue().poll(); if (obj instanceof byte[]) { println(c++ + " " + ((byte[]) obj).length); } else { println(c++ + " " + obj); } } } protected void handleQPeek(String[] args) { println(getQueue().peek()); } protected void handleQCapacity(String[] args) { println(getQueue().remainingCapacity()); } private void execute(String[] args) { // execute <echo-string> doExecute(false, false, args); } private void executeOnKey(String[] args) { // executeOnKey <echo-string> <key> doExecute(true, false, args); } private void executeOnMember(String[] args) { // executeOnMember <echo-string> <memberIndex> doExecute(false, true, args); } private void ex(String input) throws Exception { FutureTask<String> task = new DistributedTask<String>(new Echo(input)); ExecutorService executorService = hazelcast.getExecutorService(); executorService.execute(task); String echoResult = task.get(); } private void doExecute(boolean onKey, boolean onMember, String[] args) { // executeOnKey <echo-string> <key> try { ExecutorService executorService = hazelcast.getExecutorService(); Echo callable = new Echo(args[1]); FutureTask<String> task = null; if (onKey) { String key = args[2]; task = new DistributedTask<String>(callable, key); } else if (onMember) { int memberIndex = Integer.parseInt(args[2]); Member member = (Member) hazelcast.getCluster().getMembers().toArray()[memberIndex]; task = new DistributedTask<String>(callable, member); } else { task = new DistributedTask<String>(callable); } executorService.execute(task); println("Result: " + task.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } private void executeOnMembers(String[] args) { // executeOnMembers <echo-string> try { ExecutorService executorService = hazelcast.getExecutorService(); MultiTask<String> echoTask = new MultiTask(new Echo(args[1]), hazelcast.getCluster() .getMembers()); executorService.execute(echoTask); Collection<String> results = echoTask.get(); for (String result : results) { println(result); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } private void executeLong(String[] args) { // executeOnMembers <echo-string> try { ExecutorService executorService = hazelcast.getExecutorService(); MultiTask<String> echoTask = new MultiTask(new LongTask(args[1]), hazelcast.getCluster() .getMembers()) { @Override public void setMemberLeft(Member member) { println("Member Left " + member); } @Override public void done() { println("Done!"); } }; executorService.execute(echoTask); Collection<String> results = echoTask.get(); for (String result : results) { println(result); } } catch (Exception e) { e.printStackTrace(); } } private void executeLongTaskOnOtherMember(String[] args) { // executeOnMembers <echo-string> try { ExecutorService executorService = hazelcast.getExecutorService(); Member otherMember = null; Set<Member> members = hazelcast.getCluster().getMembers(); for (Member member : members) { if (!member.localMember()) { otherMember = member; } } if (otherMember == null) { otherMember = hazelcast.getCluster().getLocalMember(); } DistributedTask<String> echoTask = new DistributedTask(new LongTask(args[1]), otherMember) { @Override public void setMemberLeft(Member member) { println("Member Left " + member); } @Override public void done() { println("Done!"); } }; executorService.execute(echoTask); Object result = echoTask.get(); println(result); } catch (Exception e) { e.printStackTrace(); } } public void entryAdded(EntryEvent event) { println(event); } public void entryRemoved(EntryEvent event) { println(event); } public void entryUpdated(EntryEvent event) { println(event); } public void entryEvicted(EntryEvent event) { println(event); } public void itemAdded(Object item) { println("Item added = " + item); } public void itemRemoved(Object item) { println("Item removed = " + item); } public void onMessage(Object msg) { println("Topic received = " + msg); } public static class LongTask extends HazelcastInstanceAwareObject implements Callable<String>, Serializable { String input = null; public LongTask() { super(); } public LongTask(String input) { super(); this.input = input; } public String call() { try { Thread.sleep(5000); } catch (InterruptedException e) { System.out.println("Interrupted! Cancelling task!"); return "No-result"; } return getHazelcastInstance().getCluster().getLocalMember().toString() + ":" + input; } } public static class Echo extends HazelcastInstanceAwareObject implements Callable<String>, Serializable { String input = null; public Echo() { super(); } public Echo(String input) { super(); this.input = input; } public String call() { return getHazelcastInstance().getCluster().getLocalMember().toString() + ":" + input; } } protected void handleHelp(String command) { boolean silentBefore = silent; silent = false; println("Commands:"); println("-- General commands"); println("echo true|false //turns on/off echo of commands (default false)"); println("silent true|false //turns on/off silent of command output (default false)"); println("#<number> <command> //repeats <number> time <command>, replace $i in <command> with current iteration (0..<number-1>)"); println("&<number> <command> //forks <number> threads to execute <command>, replace $t in <command> with current thread number (0..<number-1>"); println(" When using #x or &x, is is advised to use silent true as well."); println(" When using &x with m.putmany and m.removemany, each thread will get a different share of keys unless a start key index is specified"); println("jvm //displays info about the runtime"); println("who //displays info about the cluster"); println("whoami //displays info about this cluster member"); println("ns <string> //switch the namespace for using the distributed queue/map/set/list <string> (defaults to \"default\""); println("@<file> //executes the given <file> script. Use '//' for comments in the script"); println(""); println("-- Queue commands"); println("q.offer <string> //adds a string object to the queue"); println("q.poll //takes an object from the queue"); println("q.offermany <number> [<size>] //adds indicated number of string objects to the queue ('obj<i>' or byte[<size>]) "); println("q.pollmany <number> //takes indicated number of objects from the queue"); println("q.iterator [remove] //iterates the queue, remove if specified"); println("q.size //size of the queue"); println("q.clear //clears the queue"); println(""); println("-- Set commands"); println("s.add <string> //adds a string object to the set"); println("s.remove <string> //removes the string object from the set"); println("s.addmany <number> //adds indicated number of string objects to the set ('obj<i>')"); println("s.removemany <number> //takes indicated number of objects from the set"); println("s.iterator [remove] //iterates the set, removes if specified"); println("s.size //size of the set"); println("s.clear //clears the set"); println(""); println("-- Lock commands"); println("lock <key> //same as Hazelcast.getLock(key).lock()"); println("tryLock <key> //same as Hazelcast.getLock(key).tryLock()"); println("tryLock <key> <time> //same as tryLock <key> with timeout in seconds"); println("unlock <key> //same as Hazelcast.getLock(key).unlock()"); println(""); println("-- Map commands"); println("m.put <key> <value> //puts an entry to the map"); println("m.remove <key> //removes the entry of given key from the map"); println("m.get <key> //returns the value of given key from the map"); println("m.putmany <number> [<size>] [<index>]//puts indicated number of entries to the map ('key<i>':byte[<size>], <index>+(0..<number>)"); println("m.removemany <number> [<index>] //removes indicated number of entries from the map ('key<i>', <index>+(0..<number>)"); println(" When using &x with m.putmany and m.removemany, each thread will get a different share of keys unless a start key <index> is specified"); println("m.keys //iterates the keys of the map"); println("m.values //iterates the values of the map"); println("m.entries //iterates the entries of the map"); println("m.iterator [remove] //iterates the keys of the map, remove if specified"); println("m.size //size of the map"); println("m.clear //clears the map"); println("m.destroy //destroys the map"); println("m.lock <key> //locks the key"); println("m.tryLock <key> //tries to lock the key and returns immediately"); println("m.tryLock <key> <time> //tries to lock the key within given seconds"); println("m.unlock <key> //unlocks the key"); println(""); println("-- List commands:"); println("l.add <string>"); println("l.contains <string>"); println("l.remove <string>"); println("l.iterator [remove]"); println("l.size"); println("l.clear"); println("execute <echo-input> //executes an echo task on random member"); println("execute0nKey <echo-input> <key> //executes an echo task on the member that owns the given key"); println("execute0nMember <echo-input> <key> //executes an echo task on the member with given index"); println("execute0nMembers <echo-input> //executes an echo task on all of the members"); println(""); silent = silentBefore; } public void println(Object obj) { if (!silent) System.out.println(obj); } public void print(Object obj) { if (!silent) System.out.print(obj); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
a8e72862abb62ee51c0aecfbbb3e9f673b086676
caecf26c07434fca594fd35834bafac175cda7c0
/GSpy + JNetLib/GSpyServer/src/jwoo/apps/GSpyServer/Program.java
6ddd8431f93c0c0cb5e519a58d1109907dcfb586
[ "BSD-3-Clause" ]
permissive
jwoo1601/Java-Minecraft-Mods
b390dca652a893e3ef5b927094ab272db65a5d19
1029d5ddd35cd7289b63ff34db6bb95b67763dc7
refs/heads/master
2020-12-27T10:22:46.668158
2020-02-03T02:04:42
2020-02-03T02:04:42
237,867,633
0
0
null
null
null
null
UTF-8
Java
false
false
5,344
java
package jwoo.apps.GSpyServer; import java.io.IOException; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.zip.CRC32; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufUtil; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import jwoo.apps.GSpyServer.packets.PacketVersion; import jwoo.apps.GSpyServer.test.TestApp; public class Program { public static void main(String[] args) { //TestApp testApp = new TestApp(); //testApp.Execute(args); /* int value = 0b10110110100101110010010110111011; byte[] values = new byte[] { 0x32, 0x5A, 0x4C, 0x1F }; long crc_start = System.currentTimeMillis(); CRC32 crc = new CRC32(); crc.update(values); long crc_checksum = crc.getValue(); long crc_end = System.currentTimeMillis(); System.out.printf("CRC32 Elapsed Time: %dms", crc_end - crc_start); try { long md5_start = System.currentTimeMillis(); MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] hash = md5.digest(values); long md5_end = System.currentTimeMillis(); System.out.printf("MD5 Elapsed Time: %dms", md5_end - md5_start); long sha_start = System.currentTimeMillis(); MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] hash2 = sha.digest(values); long sha_end = System.currentTimeMillis(); System.out.printf("SHA-1 Elapsed Time: %dms\n", sha_end - sha_start); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } long l = Integer.MAX_VALUE, l2 = 0b1111111111111111111111111111111100000000000000000000000000000000L, l3 = 0b0000000000000000000000000000000011111111111111111111111111111111L; long l4 = 0b1111111111111111111111111111111011111111111111111111111111111101L; int i2 = (int) (l4 & 0xFFFFFFFFL); byte[] bytes = new byte[] { 25, 10, 25, 3 }; for (byte b : bytes) { System.out.printf("%s ", Integer.toBinaryString(b)); } System.out.println(); int sb = ((int)bytes[0]) << 25 | ((int)bytes[1]) << 17 | ((int)bytes[2]) << 9 | ((int)bytes[3]); System.out.println(Integer.toBinaryString(sb)); int i = (int) l; Consumer<Integer> TempDecoder = (n) -> { int[] extInts = new int[] { 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF }; byte result = 0; switch (n) { case 1: result = (byte) Integer.rotateLeft(sb & extInts[n-1], 7); break; case 2: result = (byte) Integer.rotateLeft(sb & extInts[n-1], 15); break; case 3: result = (byte) ((sb & extInts[n-1]) >>> 9); break; case 4: result = (byte) (sb & extInts[n-1]); break; default: break; } System.out.println(Integer.toBinaryString(extInts[n-1]) + " / " + result + " | " + Integer.toBinaryString(result) + " | 0x" + Integer.toHexString(result)); }; for (int k = 1; k < 5; k++) { TempDecoder.accept(k); } long start = System.nanoTime(); byte t = (byte) Integer.rotateLeft(sb & 0xFF000000, 7); long end = System.nanoTime(); System.out.println(t); long diff1 = end - start; start = System.nanoTime(); t = (byte) ((sb & 0x00FF0000) >>> 17); end = System.nanoTime(); long diff2 = end - start; System.out.println(t + " & 1: " + diff1 + " 2: " + diff2); // 00000000000000000000000000000000 long C1 = 0b10000000000000000000000000000001L, C2 = 0b0000000000000000000000000000000010000000000000000000000000000001L; System.out.println(Long.toBinaryString(Long.MAX_VALUE) + " " + Long.toBinaryString(C1 << 32 | C1) + " " + Integer.toBinaryString((int)(C1 << 32 | C2) >>> 32)); */ /* byte b1 = (byte) Integer.rotateLeft(sb & 0xFF000000, 7); System.out.println(Integer.toBinaryString(0xFF000000) + " / " + b1 + " | " + Integer.toBinaryString(b1) + " | 0x" + Integer.toHexString(b1)); */ //System.out.printf("\n%d\n%s\n%d\n", Long.BYTES, Integer.toBinaryString(sb), l3); // System.out.printf("CRC32 Checksum: value=%s, checksum=%s", Integer.toBinaryString(value), Long.toBinaryString(crc_checksum)); try { byte[] buf = ObjectUtils.convertToBytes(new PacketVersion((byte)18, (byte)1, (byte)16, (byte)1)); System.out.printf("length: %d\ndata:", buf.length); for (byte b : buf) { System.out.print(b + " "); } System.out.println(); System.out.println(Charset.forName("UTF-8").decode(ByteBuffer.wrap(buf)).toString()); PacketVersion version = ObjectUtils.convertFromBytes(buf); System.out.println(version); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static class A implements Serializable { private static final long serialVersionUID = 5102419072560417461L; public A(int a, int b) { this.a = a; this.b = b; } @Override public String toString() { return String.format("a=%d, b=%d", a, b); } private int a; private int b; } }
[ "jkim504@myseneca.ca" ]
jkim504@myseneca.ca
f38bdc60223dc4856fbfac0805f665d187cb477c
bb7946a7084cd17e5fb823f44cd184196ade1fa4
/webservices/server-integration/src/main/java/org/jboss/as/webservices/dmr/WSEndpointsListOperationHandler.java
22e62d6e5cbab37958240a5f95dec6ae12e39c45
[]
no_license
ErikWRasmussen/jboss-as
0138e2502e65fc0b49274e3eee6a8963ce10c698
47b7a510820d848e83e11f090f610f06801bf99c
refs/heads/master
2021-12-14T19:43:23.154861
2011-05-05T19:25:19
2011-05-05T19:25:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,625
java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.webservices.dmr; import javax.management.ObjectName; import org.jboss.as.controller.BasicOperationResult; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationHandler; import org.jboss.as.controller.OperationResult; import org.jboss.as.controller.ResultHandler; import org.jboss.as.controller.RuntimeTask; import org.jboss.as.controller.RuntimeTaskContext; import org.jboss.as.webservices.util.WSServices; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceController; import org.jboss.wsf.spi.deployment.Endpoint; import org.jboss.wsf.spi.management.EndpointRegistry; /** * @author <a href="mailto:ema@redhat.com">Jim Ma</a> */ public class WSEndpointsListOperationHandler implements OperationHandler { public static final String OPERATION_NAME = "list-endpoints"; static final WSEndpointsListOperationHandler INSTANCE = new WSEndpointsListOperationHandler(); /** {@inheritDoc} */ @Override public OperationResult execute(final OperationContext context, final ModelNode operation, final ResultHandler resultHandler) throws OperationFailedException { if (context.getRuntimeContext() != null) { context.getRuntimeContext().setRuntimeTask(new RuntimeTask() { public void execute(RuntimeTaskContext context) throws OperationFailedException { final ServiceController<?> controller = context.getServiceRegistry() .getService(WSServices.REGISTRY_SERVICE); if (controller != null) { try { final EndpointRegistry registry = (EndpointRegistry) controller.getValue(); final ModelNode result = new ModelNode(); result.get("deployed-count").set(registry.getEndpoints().size()); for (ObjectName obj : registry.getEndpoints()) { Endpoint endpoint = registry.getEndpoint(obj); String endpointName = obj.toString(); result.get(endpointName).add("address", endpoint.getAddress()); result.get(endpointName).add("wsdlURL", endpoint.getAddress() + "?wsdl"); result.get(endpointName).add("shortName", endpoint.getShortName()); result.get(endpointName).add("implClass", endpoint.getTargetBeanClass().getName()); } resultHandler.handleResultFragment(new String[0], result); resultHandler.handleResultComplete(); } catch (Exception e) { throw new OperationFailedException(new ModelNode().set("failed to get webservice endpoints list" + e.getMessage())); } } else { resultHandler.handleResultFragment(ResultHandler.EMPTY_LOCATION, new ModelNode().set("no webserivce endpoints available")); resultHandler.handleResultComplete(); } } }); } else { resultHandler.handleResultFragment(ResultHandler.EMPTY_LOCATION, new ModelNode().set("no webservice endpoints available")); resultHandler.handleResultComplete(); } return new BasicOperationResult(); } }
[ "ema@redhat.com" ]
ema@redhat.com
d6151412b701f6125cdeaaf48fd27b256b9837a8
674f4f3d8a676d7ff5cd0e86825aae3887ae5531
/app/src/main/java/com/elysino/comicapp/sqllite/DatabaseHelper.java
7c086c6e42ae03e7fe4817340b7ac348b28334fe
[]
no_license
Sagar268380/ComicApp
d74b05f50a86289053bdadfee4bf5ba3745e7792
6f9ade162fbc67bd26401af5d94de357068892c0
refs/heads/master
2023-03-14T17:53:05.801791
2021-02-24T07:44:58
2021-02-24T07:44:58
341,554,926
0
0
null
null
null
null
UTF-8
Java
false
false
1,202
java
package com.elysino.comicapp.sqllite; import android.content.Context; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper { private final static int version=1; private final static String dbName="ComicData"; public static final String KEY_NAME = "NAME"; private static final String TAG = "DataBase"; private SQLiteDatabase sqLiteDatabase; public DatabaseHelper(Context context) { super(context, dbName, null, version); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { this.sqLiteDatabase=sqLiteDatabase; String sql="CREATE TABLE COMIC(_id INTEGER PRIMARY KEY AUTOINCREMENT,"+KEY_NAME+" TEXT,IMAGE TEXT,ALT TEXT,DAY TEXT, MONTH TEXT, YEAR TEXT,NUM INTEGER)"; sqLiteDatabase.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } public int getCount(){ SQLiteDatabase db = this.getReadableDatabase(); long count = DatabaseUtils.queryNumEntries(db, "COMIC"); return (int) count+1; } }
[ "sagarjain268380@gmail.com" ]
sagarjain268380@gmail.com
3b27f9c561bc571337aad58acb2235f950fd51f1
1c2d75fe27f857818f1af32256f8a3ebdfc96f81
/itrip-dao/src/main/java/com/cskt/mapper/ItripHotelRoomMapper.java
90f46813e6dc3a59c618853e6a4edd97d84b9f66
[]
no_license
shenjunwang/itrip-project
306c98eacd4035630f6d09c29808b64113033eef
dbfd33e3555f8b42f0d226d4a990c094fad8f2bb
refs/heads/master
2023-02-18T04:55:30.975130
2021-01-07T02:05:25
2021-01-07T02:05:25
326,902,394
0
0
null
null
null
null
UTF-8
Java
false
false
302
java
package com.cskt.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.cskt.entity.ItripHotelRoom; import org.apache.ibatis.annotations.Mapper; /** @author 申钧旺 @create 2021-01-05 11:30 */ @Mapper public interface ItripHotelRoomMapper extends BaseMapper<ItripHotelRoom> { }
[ "780816856@qq.com" ]
780816856@qq.com
1059cf0571a7f3e53fd063b13d6e30647acfd032
2e6d8e8baf277d73ec2cd7a1df5cd67b8d706a7b
/client/src/alexmog/rulemastersworld/scenes/debug/RamGraph.java
cca488800788a2ae32d0c2a98b952bff5345f276
[ "MIT" ]
permissive
vsoltys/MMO-Rulemasters-World
8cff1f89d4f981599f2e32ddbdd6a2645808fa38
fe2e4e42b7e5adbd524fe1e70b4520e36fe7ceb3
refs/heads/master
2020-03-23T20:36:28.574018
2015-12-29T10:34:17
2015-12-29T10:34:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,028
java
package alexmog.rulemastersworld.scenes.debug; import alexmog.rulemastersworld.gui.FadeFrame; import de.matthiasmann.twl.GUI; import de.matthiasmann.twl.Graph; import de.matthiasmann.twl.model.SimpleGraphLineModel; import de.matthiasmann.twl.model.SimpleGraphModel; public class RamGraph extends FadeFrame { private SimpleGraphLineModel gmRamPerFrame; private Runtime mRuntime = Runtime.getRuntime(); public RamGraph() { gmRamPerFrame = new SimpleGraphLineModel("default", 100, 0, 30); gmRamPerFrame.setMinValue(0); Graph graph = new Graph(new SimpleGraphModel(gmRamPerFrame)); graph.setTheme("/graph"); setPosition(0, 300); setTheme("resizableframe-title"); setTitle("Memory Usage"); add(graph); } @Override protected void paint(GUI gui) { gmRamPerFrame.setMaxValue(mRuntime.totalMemory()); gmRamPerFrame.addPoint((float)(mRuntime.totalMemory() - mRuntime.freeMemory())); super.paint(gui); } }
[ "moghra_a@epitech.eu" ]
moghra_a@epitech.eu
6547360e6abd50cf9905551a3905b1a4d7924c8d
90bf5b6a3008c52178cd2a7bf2136006ad32ce68
/app/src/main/java/com/shahriar/hasan/monthlyexpenserecorder/enums/CategoryTypeEnum.java
b73067e12ecc44215ff4952379c14e3eb1a86cb1
[ "MIT" ]
permissive
Shahriar07/ExpenseTracker
ba1e046ada52bc1f92cc1f2a54767d6587595a93
a33bfc5ae7171377c842877c76afdafd3939b656
refs/heads/master
2021-05-05T19:12:18.203649
2017-10-17T19:05:10
2017-10-17T19:05:10
103,843,166
0
0
null
null
null
null
UTF-8
Java
false
false
346
java
package com.shahriar.hasan.monthlyexpenserecorder.enums; /** * Created by H. M. Shahriar on 8/6/2017. */ public enum CategoryTypeEnum { INCOME_CATEGORY(1), EXPENSE_CATEGORY(0); CategoryTypeEnum (int i) { this.type = i; } private int type; public int getNumericType() { return type; } }
[ "mshahriar.h@gmail.com" ]
mshahriar.h@gmail.com
3d341e644bfe6f381512b685195e4513e774025c
4d0f2d62d1c156d936d028482561585207fb1e49
/Ma nguon/zcs-8.0.2_GA_5570-src/ZimbraCommon/src/java/com/zimbra/perf/chart/SummaryAnalyzer.java
75437d58b4ee73dfdef34ea45cefd1a928d73ed8
[]
no_license
vuhung/06-email-captinh
e3f0ff2e84f1c2bc6bdd6e4167cd7107ec42c0bd
af828ac73fc8096a3cc096806c8080e54d41251f
refs/heads/master
2020-07-08T09:09:19.146159
2013-05-18T12:57:24
2013-05-18T12:57:24
32,319,083
0
2
null
null
null
null
UTF-8
Java
false
false
8,581
java
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2007, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.perf.chart; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.zimbra.common.util.CsvReader; public class SummaryAnalyzer { private Map<String, List<PlotSettings>> mOutfilePlotsMap = null; private List<ReportEntry> mEntryList = new ArrayList<ReportEntry>(); public SummaryAnalyzer(List<ChartSettings> chartSettings) { mOutfilePlotsMap = new HashMap<String, List<PlotSettings>>(chartSettings.size()); for (ChartSettings cs : chartSettings) { mOutfilePlotsMap.put(cs.getOutfile(), cs.getPlots()); } } private static String buildKey(String infile, String data, String aggregateFun) { return infile + ":" + data + ":" + aggregateFun; } private static String getVolume(String dataColumn) { return dataColumn.split(":")[0]; } private void buildSingleVolume(String volumeName, String name){ String key; key = buildKey(SummaryConstants.IO_IN,volumeName + ":" + SummaryConstants.IO_UTIL, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry( name + " Disk Util",key)); key = buildKey( SummaryConstants.IO_IN, volumeName + ":" + SummaryConstants.R_THROUGHPUT, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry( name + " Read Throughput",key)); key = buildKey( SummaryConstants.IO_IN, volumeName + ":" + SummaryConstants.W_THROUGHPUT, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry(name + " Write Throughput",key)); key = buildKey( SummaryConstants.IO_IN, volumeName + ":" + SummaryConstants.R_IOPS, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry(name + " Read IOPS",key)); key = buildKey( SummaryConstants.IO_IN, volumeName + ":" + SummaryConstants.W_IOPS, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry(name + " write IOPS",key)); } private List<PlotSettings> getIOPlotSettings(){ Iterator<String> it = mOutfilePlotsMap.keySet().iterator(); List<PlotSettings> settings = null; String key; while (it.hasNext()) { key = (String) it.next(); if (key.indexOf(SummaryConstants.KEY_TO_DISK_UTIL) != -1 ) { settings = mOutfilePlotsMap.get(key); break; } } return settings; } private void buildIOKeys() { List<PlotSettings> settings = getIOPlotSettings(); for (PlotSettings ps : settings) { String legend = ps.getLegend(); String volume = getVolume(ps.getDataColumn()); buildSingleVolume(volume, legend); } } private void buildCPUKeys() { String key; key = buildKey(SummaryConstants.CPU_IN, SummaryConstants.SYS, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry("Mail Server CPU Sys ",key)); key = buildKey(SummaryConstants.CPU_IN, SummaryConstants.USER, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry("Mail Server CPU User ",key)); key = buildKey(SummaryConstants.CPU_IN, SummaryConstants.IDLE, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry("Mail Server CPU Idle ",key)); key = buildKey(SummaryConstants.CPU_IN, SummaryConstants.IOWAIT, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry("Mail Server CPU Iowait ",key)); } private void buildMemKeys() { String key; key = buildKey(SummaryConstants.GC_IN, SummaryConstants.F_GC, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry("Full GC% ",key)); key = buildKey(SummaryConstants.GC_IN, SummaryConstants.Y_GC, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry("Young GC% ",key)); } private void buildServerResponseKeys() { String key; key = buildKey(SummaryConstants.SERVER_IN, SummaryConstants.ADD_COUNT, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry("Mailbox add rate ",key)); key = buildKey(SummaryConstants.SERVER_IN, SummaryConstants.ADD_LATENCY, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry("Mailbox add latency ",key)); key = buildKey(SummaryConstants.SERVER_IN, SummaryConstants.GET_LATENCY, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry("Mailbox get latency ",key)); key = buildKey(SummaryConstants.SERVER_IN, SummaryConstants.SOAP_RESPONSE, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry("Soap response time",key)); key = buildKey(SummaryConstants.SERVER_IN, SummaryConstants.POP_RESPONSE, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry("Pop response time",key)); key = buildKey(SummaryConstants.SERVER_IN, SummaryConstants.IMAP_RESPONSE, PlotSettings.AGG_FUNCTION_AVG); mEntryList.add(new ReportEntry("Imap response time",key)); } public class ReportEntry{ String entryName; String entryKey; public ReportEntry(String keyName, String keyVal){ this.entryName = keyName; this.entryKey = keyVal; } public String getEntryKey() { return entryKey; } public void setEntryKey(String entryKey) { this.entryKey = entryKey; } public String getEntryName() { return entryName; } public void setEntryName(String entryName) { this.entryName = entryName; } } public void writeReport(File summaryCsv) throws IOException { buildIOKeys(); buildCPUKeys(); buildMemKeys(); buildServerResponseKeys(); FileReader reader = null; CsvReader csv = null; FileWriter writer = null; try { reader = new FileReader(summaryCsv); csv = new CsvReader(reader); File summaryTxt = new File(summaryCsv.getParentFile(), SummaryConstants.SUMMARY_TXT); writer = new FileWriter(summaryTxt); writer.write("===========================================\n"); writer.write("# Perf Stats #\n"); writer.write("===========================================\n"); if(csv.hasNext()){ for(ReportEntry entry : mEntryList){ if(csv.columnExists(entry.entryKey)){ writer.write(entry.entryName + ":" + csv.getValue(entry.entryKey)); }else{ writer.write(entry.entryName + ":"); } writer.write("\n"); } } } finally { if (writer != null) writer.close(); if (csv != null) csv.close(); else if (reader != null) reader.close(); } } }
[ "vuhung16plus@gmail.com@ec614674-f94a-24a8-de76-55dc00f2b931" ]
vuhung16plus@gmail.com@ec614674-f94a-24a8-de76-55dc00f2b931
0fdd7f334aca30a1b0afc2e06250d9c5c9dfa875
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/8/8_cb790e9f64ec00fc8b0e3d255101594fb642bdc8/GridSweeper/8_cb790e9f64ec00fc8b0e3d255101594fb642bdc8_GridSweeper_t.java
34a0ff7342f5de6eb705850ab74673d23f2cdb8d
[]
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
21,503
java
package edu.umich.lsa.cscs.gridsweeper; import org.ggf.drmaa.*; import java.io.*; import java.text.DateFormat; import java.util.*; import static edu.umich.lsa.cscs.gridsweeper.StringUtils.*; import static edu.umich.lsa.cscs.gridsweeper.DateUtils.*; import static edu.umich.lsa.cscs.gridsweeper.DLogger.*; /** * The GridSweeper command-line tool for job submission. Takes a .gsexp * XML experiment file and/or a bunch of command line options and submits * the resulting experiment to the grid via DRMAA. * Warning: begun on a houseboat in Paris. May still contain strange French bugs. * * @author Ed Baskerville * */ public class GridSweeper { enum RunType { RUN, DRY, NORUN } class CaseRun { ExperimentCase expCase; String caseId; int runNum; int rngSeed; JobInfo jobInfo = null; RunResults runResults = null; public CaseRun(ExperimentCase expCase, String caseId, int runNum, int rngSeed) { this.expCase = expCase; this.caseId = caseId; this.runNum = runNum; this.rngSeed = rngSeed; } public String getRunString() { String runStr; if(caseId.equals("")) runStr = "run " + runNum; else runStr = caseId + ", run " + runNum; return runStr; } } static String className; static { className = GridSweeper.class.toString(); } String root; String pid; Experiment experiment; RunType runType = RunType.RUN; List<ExperimentCase> cases = null; boolean useFileTransfer = false; Calendar cal; String dateStr; String timeStr; String expDir; String email; String fileTransferSubpath; Session drmaaSession; StringMap caseIdToJobIdMap; Map<String, CaseRun> jobIdToRunMap; PrintStream msgOut; public GridSweeper() throws GridSweeperException { root = System.getenv("GRIDSWEEPER_ROOT"); if(root == null) throw new GridSweeperException("GRIDSWEEPER_ROOT environment variable not set."); pid = getPid(); cal = Calendar.getInstance(); msgOut = System.err; } private String getPid() throws GridSweeperException { String pid; try { String getPidPath = appendPathComponent(root, "bin/gsgetpid"); Process pidProc = Runtime.getRuntime().exec(getPidPath); BufferedReader getPidReader = new BufferedReader(new InputStreamReader(pidProc.getInputStream())); pid = getPidReader.readLine(); } catch(Exception e) { throw new GridSweeperException("Could not get pid."); } if(pid == null) { throw new GridSweeperException("Could not get pid."); } return pid; } /** * Generates experiment cases and sets up in preparation for grid submission. * Experiment results are collated in a master experiment directory, * specified in the user settings, in a subdirectory tagged with the experiment name * and date/time ({@code <name>/YYYY-MM-DD/hh-mm-ss}). If a shared filesystem is not * available, files are first staged to the experiment results directory on the * file transfer system. * Finally, a DRMAA session is established, and each case is submitted. * @throws GridSweeperException */ public void submitExperiment() throws GridSweeperException { if(runType == RunType.NORUN) return; email = experiment.getSettings().getSetting("EmailAddress"); if(email == null) { msgOut.println("Warning: no email address provided; " + " using local user account."); email = System.getProperty("user.name"); } String expName = experiment.getName(); if(runType == RunType.DRY) { msgOut.println("Performing dry run for experiment \"" + expName + "\"..."); } else { msgOut.println("Running experiment \"" + experiment.getName() + "\"..."); } Settings settings = experiment.getSettings(); // Assemble cases try { cases = experiment.generateCases(); } catch (ExperimentException e) { // TODO: use ExperimentException to create better error information throw new GridSweeperException("Could not generate experiment cases", e); } // Set up main experiment directory setUpExperimentDirectory(settings); // Set up directory & input files on file transfer system if asked for if(runType == RunType.RUN && settings.getBooleanProperty("UseFileTransfer")) { setUpFileTransfer(settings); } // Create experiment XML in output directory String xmlPath = appendPathComponent(expDir, "experiment.gsexp"); try { experiment.writeToFile(xmlPath, true); } catch(Exception e) { throw new GridSweeperException("Could not write experiment XML to" + xmlPath, e); } // Enumerate and submit cases submitCases(); // Finally, switch(runType) { case DRY: msgOut.println("Dry run complete."); break; case RUN: msgOut.println("Experiment submitted."); break; } } private void setUpExperimentDirectory(Settings settings) throws GridSweeperException { try { String expsDir = expandTildeInPath(settings.getProperty("ExperimentsDirectory")); // First set up big directory for the whole experiment // Located in <experimentDir>/<experimentName>/<experimentDate>/<experimentTime> String expName = experiment.getName(); if(expName == null) { throw new GridSweeperException("Experiment name must be specified."); } dateStr = getDateString(cal); timeStr = getTimeString(cal); String expSubDir = String.format("%s%s%s%s%s", expName, getFileSeparator(), dateStr, getFileSeparator(), timeStr); expDir = appendPathComponent(expsDir, expSubDir); finer("Experiment subdirectory: " + expDir); File expDirFile = new File(expDir); expDirFile.mkdirs(); msgOut.println("Created experiment directory \"" + expDir + "\"."); } catch(Exception e) { throw new GridSweeperException("Could not create experiment directory " + expDir, e); } } private void setUpFileTransfer(Settings settings) throws GridSweeperException { FileTransferSystem fts = null; try { msgOut.println("Setting up file transfer system..."); String className = settings.getSetting("FileTransferSystemClassName"); Settings ftsSettings = settings.getSettingsForClass(className); fts = FileTransferSystemFactory.getFactory().getFileTransferSystem(className, ftsSettings); fts.connect(); boolean alreadyExists; do { fileTransferSubpath = UUID.randomUUID().toString(); alreadyExists = fts.fileExists(fileTransferSubpath); } while(alreadyExists); msgOut.println("Done setting up file transfer."); // If file transfer is on, make the directory // and upload input files StringMap inputFiles = experiment.getInputFiles(); if(inputFiles.size() > 0) { msgOut.println("Uploading input files..."); String inputDir = appendPathComponent(fileTransferSubpath, "input"); fts.makeDirectory(inputDir); for(String localPath : inputFiles.keySet()) { String remotePath = appendPathComponent(inputDir, inputFiles.get(localPath)); msgOut.println("Uploading file \"" + localPath + "\" to \"" + remotePath + "\""); fts.uploadFile(localPath, remotePath); } msgOut.println("Done uploading input files."); } fts.disconnect(); } catch(Exception e) { throw new GridSweeperException("Could not set up file trasfer system", e); } } public void submitCases() throws GridSweeperException { if(runType == RunType.NORUN) return; try { // Establish DRMAA session, unless this is a dry run if(runType == RunType.RUN) { msgOut.println("Establishing grid session"); drmaaSession = SessionFactory.getFactory().getSession(); drmaaSession.init(null); } // Set up and run each case caseIdToJobIdMap = new StringMap(); jobIdToRunMap = new HashMap<String, CaseRun>(); if(cases.size() > 1) msgOut.println("Submitting cases:"); for(ExperimentCase expCase : cases) { runCase(expCase); } if(cases.size() > 1) msgOut.println("All cases submitted."); } catch(Exception e) { throw new GridSweeperException("Could not run experiment", e); } } /** * Submits a single experiment case. This means running one job for each * run of the case (one for each random seed). * @param expCase The experiment case to run. * @throws FileNotFoundException If the case directory cannot be found/created. * @throws DrmaaException If a DRMAA error occurs (in {@link #runCaseRun}). * @throws IOException If the case XML cannot be written out (in {@link #runCaseRun}). */ public void runCase(ExperimentCase expCase) throws FileNotFoundException, DrmaaException, IOException { String caseSubDir = experiment.getDirectoryNameForCase(expCase); String caseDir = appendPathComponent(expDir, caseSubDir); finer("Case subdirectory: " + caseDir); File caseDirFile = new File(caseDir); caseDirFile.mkdirs(); String caseName; if(caseSubDir.equals("")) { caseName = experiment.getName() + " (" + dateStr + ", " + timeStr + ")"; } else { caseName = experiment.getName() + " - " + caseSubDir + " (" + dateStr + ", " + timeStr + ")"; } // Write XML String xmlPath = appendPathComponent(caseDir, "case.gscase"); ExperimentCaseXMLWriter xmlWriter = new ExperimentCaseXMLWriter( xmlPath, expCase, caseName); xmlWriter.writeXML(); if(!caseSubDir.equals("")) { msgOut.println(caseSubDir); } // Run each individual run on the grid List<Integer> rngSeeds = expCase.getRngSeeds(); for(int i = 0; i < rngSeeds.size(); i++) { CaseRun run = new CaseRun(expCase, caseSubDir, i, rngSeeds.get(i)); runCaseRun(run); } } /** * Submits a single run of an experiment case. * @param expCase The case to run. * @param caseDir The full path to where files are stored for this case. * @param caseSubDir The case directory relative to the experiment results directory. * @param i The run number for this run. * @param rngSeed The random seed for this run. * @throws DrmaaException If a DRMAA error occurs during job submission. * @throws IOException If the case XML cannot be written out. */ public void runCaseRun(CaseRun run) throws DrmaaException, IOException { ExperimentCase expCase = run.expCase; String caseId = run.caseId; int runNum = run.runNum; int rngSeed = run.rngSeed; String caseDir; if(caseId.equals("")) caseDir = expDir; else caseDir = appendPathComponent(expDir, caseId); Settings settings = experiment.getSettings(); String caseRunName; if(caseId.equals("")) { caseRunName = experiment.getName() + " - run " + runNum + " (" + dateStr + ", " + timeStr + ")"; } else { caseRunName = experiment.getName() + " - " + caseId + " - run " + runNum + " (" + dateStr + ", " + timeStr + ")"; } if(runType == RunType.RUN) { // Write setup file String stdinPath = appendPathComponent(caseDir, ".gsweep_in." + runNum); RunSetup setup = new RunSetup(settings, experiment.getInputFiles(), caseId, expCase.getParameterMap(), runNum, rngSeed, experiment.getOutputFiles()); ObjectOutputStream stdinStream = new ObjectOutputStream(new FileOutputStream(stdinPath)); stdinStream.writeObject(setup); stdinStream.close(); // Generate job template JobTemplate jt = drmaaSession.createJobTemplate(); jt.setJobName(caseRunName); jt.setRemoteCommand(appendPathComponent(root, "bin/gsrunner")); if(!useFileTransfer) jt.setWorkingDirectory(caseDir); jt.setInputPath(":" + stdinPath); jt.setOutputPath(":" + appendPathComponent(caseDir, ".gsweep_out." + runNum)); jt.setErrorPath(":" + appendPathComponent(caseDir, ".gsweep_err." + runNum)); jt.setBlockEmail(true); try { jt.setTransferFiles(new FileTransferMode(true, true, true)); } catch(DrmaaException e) { // If setTransferFiles isn't supported, we'll hope that the system defaults to // transfering them. This works for SGE. } Properties environment = new Properties(); environment.setProperty("GRIDSWEEPER_ROOT", root); String classpath = System.getenv("CLASSPATH"); if(classpath != null) environment.setProperty("CLASSPATH", classpath); jt.setJobEnvironment(environment); String jobId = drmaaSession.runJob(jt); caseIdToJobIdMap.put(caseId + "." + runNum, jobId); jobIdToRunMap.put(jobId, run); fine("run in runmap: " + jobIdToRunMap.get(jobId)); drmaaSession.deleteJobTemplate(jt); msgOut.println(" Submitted run " + runNum + " (DRMAA job ID " + jobId + ")"); } else { msgOut.println(" Not submitting run " + runNum + " (dry run)"); } fine("run: " + run); } public void daemonize() throws GridSweeperException { try { // Open PrintStream to status.log in experiment directory String logPath = appendPathComponent(expDir, "status.log"); PrintStream logOut = new PrintStream(new FileOutputStream(logPath)); msgOut.println("Detaching from console " + "(monitoring process id: " + pid + ")..."); msgOut.println("Status output will be written to:"); msgOut.println(" " + logPath); msgOut.println("and an email will be sent to " + email + " upon experiment completion."); msgOut.println("You may now close this console or log out" + " without disturbing the experiment."); msgOut = logOut; System.out.close(); System.err.close(); msgOut.println("Job monitoring process ID: " + pid); } catch(Exception e) { throw new GridSweeperException("An error occurred trying to " + "detach from the console."); } } /** * Cleans up: for now, just closes the DRMAA session. * @throws GridSweeperException If the DRMAA {@code exit()} call fails. */ public void finish() throws GridSweeperException { if(runType != RunType.RUN) return; msgOut.println("Waiting for jobs to complete..."); StringList drmaaErrorList = new StringList(); StringList gsErrorList = new StringList(); StringList execErrorList = new StringList(); int runCount = jobIdToRunMap.size(); for(int i = 0; i < runCount; i++) { JobInfo info; try { info = drmaaSession.wait( Session.JOB_IDS_SESSION_ANY, Session.TIMEOUT_WAIT_FOREVER); } catch(DrmaaException e) { throw new GridSweeperException("Waiting for job completion failed.", e); } String jobId = info.getJobId(); fine("got wait for job ID " + jobId); fine("jobIdToRunMap: " + jobIdToRunMap.toString()); CaseRun run = jobIdToRunMap.get(jobId); fine("run: " + run); run.jobInfo = info; String caseId = run.caseId; int runNum = run.runNum; String runStr = run.getRunString(); msgOut.println("Completed run " + runStr + " (DRMAA job ID " + jobId + ")"); // Check for DRMAA errors if(info.hasCoreDump() || info.hasSignaled() || info.wasAborted() || info.getExitStatus() != 0) { drmaaErrorList.add(jobId); msgOut.println(" (Warning: DRMAA reports that the run did not" + "complete normally.)"); } // Load RunResults from disk else try { String caseDir = appendPathComponent(expDir, caseId); String stdoutPath = appendPathComponent(caseDir, ".gsweep_out." + runNum); fine("Loading RunResults from " + stdoutPath); FileInputStream fileStream = new FileInputStream(stdoutPath); ObjectInputStream objStream = new ObjectInputStream(fileStream); RunResults runResults = (RunResults)objStream.readObject(); run.runResults = runResults; if(runResults == null || runResults.getException() != null) { gsErrorList.add(jobId); msgOut.println(" (Warning: a GridSweeper exception occurred" + " while performing this run.)"); } else if(runResults.getStatus() != 0) { execErrorList.add(jobId); msgOut.println(" (Warning: this run exited with an" + "error code.)"); } } catch(Exception e) { msgOut.print(" (Warning: an exception occurred loading the" + " run results for this run: "); e.printStackTrace(msgOut); msgOut.println(" .)"); gsErrorList.add(jobId); } msgOut.format("%d of %d complete (%.1f%%).\n", i + 1, runCount, (double)(i + 1)/runCount * 100); } msgOut.println("All jobs completed."); sendEmail(drmaaErrorList, gsErrorList, execErrorList); try { // Finish it up drmaaSession.exit(); } catch(DrmaaException e) { throw new GridSweeperException("Received exception ending DRMAA session", e); } } private void sendEmail(StringList drmaaErrorList, StringList gsErrorList, StringList execErrorList) throws GridSweeperException { String expName = experiment.getName(); String subject = expName + " complete"; // Construct and write out message String messagePath = appendPathComponent(expDir, ".gsweep_email"); StringBuffer message = new StringBuffer(); message.append("GridSweeper experiment complete.\n\n"); message.append(" Experiment name: " + expName + "\n"); message.append(" Submitted at: "); DateFormat format = DateFormat.getDateTimeInstance(); message.append(format.format(new Date(cal.getTimeInMillis()))); message.append("\n"); message.append(" Elapsed time: "); long elapsedMilli = (new Date()).getTime() - cal.getTimeInMillis(); elapsedMilli /= 1000; long seconds = elapsedMilli % 60; elapsedMilli /= 60; long minutes = elapsedMilli % 60; elapsedMilli /= 60; long hours = elapsedMilli; message.append("" + hours + "h" + minutes + "m" + seconds + "s"); message.append("\n\n"); // Print error messages, if present if(drmaaErrorList.size() == 0 && gsErrorList.size() == 0 && execErrorList.size() == 0) { message.append("No errors occurred.\n"); } else { message.append("Some errors occurred during the experiment...\n\n"); // Start with DRMAA-detected errors for(String jobId : drmaaErrorList) { CaseRun run = jobIdToRunMap.get(jobId); JobInfo info = run.jobInfo; String runStr = run.getRunString(); message.append("DRMAA returned an error for " + runStr + ":\n"); if(info.hasCoreDump()) { message.append(" A core dump occurred.\n"); } if(info.hasSignaled()) { message.append(" The job ended with signal " + info.getTerminatingSignal() + ".\n"); } if(info.wasAborted()) { message.append(" The job was aborted.\n"); } if(info.hasExited() && info.getExitStatus() != 0) { message.append(" The job exited with status " + info.getExitStatus() + ".\n"); } message.append("\n"); } // And then GridSweeper errors... for(String jobId : gsErrorList) { CaseRun run = jobIdToRunMap.get(jobId); RunResults results = run.runResults; String runStr = run.getRunString(); message.append("An internal error occurred in GridSweeper for " + runStr + ": \n"); if(results == null) { message.append(" The run results object could not be loaded.\n"); } else { Exception exception = results.getException(); if(exception != null) { message.append(" A Java exception occurred:\n "); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); String stackStr = sw.getBuffer().toString(); message.append(stackStr); } else { message.append(" An unknown error occurred.\n"); } } message.append("\n"); } // And finally nonzero status from the executable itself... for(String jobId : execErrorList) { CaseRun run = jobIdToRunMap.get(jobId); RunResults results = run.runResults; String runStr = run.getRunString(); message.append("The " + runStr + " exited with status " + results.getStatus() + ".\n\n"); } } try { FileWriter fw = new FileWriter(messagePath); fw.write(message.toString()); fw.close(); } catch(IOException e) { throw new GridSweeperException("Could not write email file."); } String command = appendPathComponent(root, "bin/gsmail"); String[] commandAndArgs = {command, subject, email, messagePath}; try { Runtime.getRuntime().exec(commandAndArgs); } catch (IOException e) { throw new GridSweeperException("Could not send email.", e); } msgOut.println("Sent notification email to " + email + "."); } public void setRunType(RunType runType) { this.runType = runType; } public void setExperiment(Experiment experiment) { this.experiment = experiment; } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
530ae8f2659b97439853c8ddda5494d314c8ed16
02294fa88ce23cff8abe9bda4f1e149986a8ba55
/JavaThreads/src/com/javathreads/chapter9/GuidedLoopHandler.java
6aed4873fb17ad7ac022fbc6a4141f59e2b5b29d
[]
no_license
hahmad92/OCA
ca5a0469d58b5f76e758456fa70ed4e83e0725c1
bdd1faa817c6bc7410fb7b21738e48e932bb6fa2
refs/heads/master
2023-01-23T23:13:12.219497
2020-12-07T17:14:00
2020-12-07T17:14:00
152,113,940
0
0
null
null
null
null
UTF-8
Java
false
false
1,906
java
package com.javathreads.chapter9; /* * * Copyright (c) 1997-1999 Scott Oaks and Henry Wong. All Rights Reserved. * * Permission to use, copy, modify, and distribute this software * and its documentation for NON-COMMERCIAL purposes and * without fee is hereby granted. * * This sample source code is provided for example only, * on an unsupported, as-is basis. * * AUTHOR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. AUTHOR SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. * * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). AUTHOR * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR * HIGH RISK ACTIVITIES. */ public class GuidedLoopHandler extends LoopHandler { protected int minSize; public GuidedLoopHandler(int start, int end, int min, int threads) { super(start, end, threads); minSize = min; } protected synchronized LoopRange loopGetRange() { if (curLoop >= endLoop) return null; LoopRange ret = new LoopRange(); ret.start = curLoop; int sizeLoop = (endLoop - curLoop) / numThreads; curLoop += (sizeLoop > minSize) ? sizeLoop : minSize; ret.end = (curLoop < endLoop) ? curLoop : endLoop; return ret; } }
[ "hammadawan50@yahoo.com" ]
hammadawan50@yahoo.com
c2928d87c34589c169a365bbf65ad044d3095c4e
76da73a33f6d9e3a24fa8e8047085e0273791b10
/OpenCV-android-sdk/sdk/java/src/org/opencv/highgui/VideoCapture.java
f51815dca399aa6a5e7d9cada4c960b9815967ac
[ "BSD-3-Clause" ]
permissive
qq524787275/OpenCVForAndroid
32f28c3321eac61ba033f8d3495f19588050e424
22486aa4385c5d4917f1f5e5e2502cfeba0b4700
refs/heads/master
2021-01-25T13:11:40.062571
2018-03-06T05:02:23
2018-03-06T05:02:23
123,539,419
15
1
null
null
null
null
UTF-8
Java
false
false
13,922
java
package org.opencv.highgui; import org.opencv.core.Mat; import org.opencv.core.Size; import java.util.LinkedList; import java.util.List; // C++: class VideoCapture /** * <p>Class for video capturing from video files, image sequences or cameras. * The class provides C++ API for capturing video from cameras or for reading * video files and image sequences. Here is how the class can be used:</p> * * <p>#include "opencv2/opencv.hpp" <code></p> * * <p>// C++ code:</p> * * <p>using namespace cv;</p> * * <p>int main(int, char)</p> * * * <p>VideoCapture cap(0); // open the default camera</p> * * <p>if(!cap.isOpened()) // check if we succeeded</p> * * <p>return -1;</p> * * <p>Mat edges;</p> * * <p>namedWindow("edges",1);</p> * * <p>for(;;)</p> * * * <p>Mat frame;</p> * * <p>cap >> frame; // get a new frame from camera</p> * * <p>cvtColor(frame, edges, CV_BGR2GRAY);</p> * * <p>GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);</p> * * <p>Canny(edges, edges, 0, 30, 3);</p> * * <p>imshow("edges", edges);</p> * * <p>if(waitKey(30) >= 0) break;</p> * * * <p>// the camera will be deinitialized automatically in VideoCapture destructor</p> * * <p>return 0;</p> * * * <p>Note: In C API the black-box structure <code>CvCapture</code> is used instead * of <code>VideoCapture</code>. * </code></p> * * <p>Note:</p> * <ul> * <li> A basic sample on using the VideoCapture interface can be found at * opencv_source_code/samples/cpp/starter_video.cpp * <li> Another basic video processing sample can be found at * opencv_source_code/samples/cpp/video_dmtx.cpp * <li> (Python) A basic sample on using the VideoCapture interface can be * found at opencv_source_code/samples/python2/video.py * <li> (Python) Another basic video processing sample can be found at * opencv_source_code/samples/python2/video_dmtx.py * <li> (Python) A multi threaded video processing sample can be found at * opencv_source_code/samples/python2/video_threaded.py * </ul> * * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture">org.opencv.highgui.VideoCapture</a> */ public class VideoCapture { protected final long nativeObj; protected VideoCapture(long addr) { nativeObj = addr; } // // C++: VideoCapture::VideoCapture() // /** * <p>VideoCapture constructors.</p> * * <p>Note: In C API, when you finished working with video, release * <code>CvCapture</code> structure with <code>cvReleaseCapture()</code>, or use * <code>Ptr<CvCapture></code> that calls <code>cvReleaseCapture()</code> * automatically in the destructor.</p> * * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-videocapture">org.opencv.highgui.VideoCapture.VideoCapture</a> */ public VideoCapture() { nativeObj = n_VideoCapture(); return; } // // C++: VideoCapture::VideoCapture(int device) // /** * <p>VideoCapture constructors.</p> * * <p>Note: In C API, when you finished working with video, release * <code>CvCapture</code> structure with <code>cvReleaseCapture()</code>, or use * <code>Ptr<CvCapture></code> that calls <code>cvReleaseCapture()</code> * automatically in the destructor.</p> * * @param device id of the opened video capturing device (i.e. a camera index). * If there is a single camera connected, just pass 0. * * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-videocapture">org.opencv.highgui.VideoCapture.VideoCapture</a> */ public VideoCapture(int device) { nativeObj = n_VideoCapture(device); return; } // // C++: double VideoCapture::get(int propId) // /** * Returns the specified "VideoCapture" property. * * Note: When querying a property that is not supported by the backend used by * the "VideoCapture" class, value 0 is returned. * * @param propId property identifier; it can be one of the following: * * CV_CAP_PROP_FRAME_WIDTH width of the frames in the video stream. * * CV_CAP_PROP_FRAME_HEIGHT height of the frames in the video stream. * * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-get">org.opencv.highgui.VideoCapture.get</a> */ public double get(int propId) { double retVal = n_get(nativeObj, propId); return retVal; } public List<Size> getSupportedPreviewSizes() { String[] sizes_str = n_getSupportedPreviewSizes(nativeObj).split(","); List<Size> sizes = new LinkedList<Size>(); for (String str : sizes_str) { String[] wh = str.split("x"); sizes.add(new Size(Double.parseDouble(wh[0]), Double.parseDouble(wh[1]))); } return sizes; } // // C++: bool VideoCapture::grab() // /** * <p>Grabs the next frame from video file or capturing device.</p> * * <p>The methods/functions grab the next frame from video file or camera and * return true (non-zero) in the case of success.</p> * * <p>The primary use of the function is in multi-camera environments, especially * when the cameras do not have hardware synchronization. That is, you call * <code>VideoCapture.grab()</code> for each camera and after that call the * slower method <code>VideoCapture.retrieve()</code> to decode and get frame * from each camera. This way the overhead on demosaicing or motion jpeg * decompression etc. is eliminated and the retrieved frames from different * cameras will be closer in time.</p> * * <p>Also, when a connected camera is multi-head (for example, a stereo camera or * a Kinect device), the correct way of retrieving data from it is to call * "VideoCapture.grab" first and then call "VideoCapture.retrieve" one or more * times with different values of the <code>channel</code> parameter. See * https://github.com/opencv/opencv/tree/master/samples/cpp/openni_capture.cpp</p> * * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-grab">org.opencv.highgui.VideoCapture.grab</a> */ public boolean grab() { boolean retVal = n_grab(nativeObj); return retVal; } // // C++: bool VideoCapture::isOpened() // /** * <p>Returns true if video capturing has been initialized already.</p> * * <p>If the previous call to <code>VideoCapture</code> constructor or * <code>VideoCapture.open</code> succeeded, the method returns true.</p> * * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-isopened">org.opencv.highgui.VideoCapture.isOpened</a> */ public boolean isOpened() { boolean retVal = n_isOpened(nativeObj); return retVal; } // // C++: bool VideoCapture::open(int device) // /** * <p>Open video file or a capturing device for video capturing</p> * * <p>The methods first call "VideoCapture.release" to close the already opened * file or camera.</p> * * @param device id of the opened video capturing device (i.e. a camera index). * * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-open">org.opencv.highgui.VideoCapture.open</a> */ public boolean open(int device) { boolean retVal = n_open(nativeObj, device); return retVal; } // // C++: bool VideoCapture::read(Mat image) // /** * <p>Grabs, decodes and returns the next video frame.</p> * * <p>The methods/functions combine "VideoCapture.grab" and "VideoCapture.retrieve" * in one call. This is the most convenient method for reading video files or * capturing data from decode and return the just grabbed frame. If no frames * has been grabbed (camera has been disconnected, or there are no more frames * in video file), the methods return false and the functions return NULL * pointer.</p> * * <p>Note: OpenCV 1.x functions <code>cvRetrieveFrame</code> and <code>cv.RetrieveFrame</code> * return image stored inside the video capturing structure. It is not allowed * to modify or release the image! You can copy the frame using "cvCloneImage" * and then do whatever you want with the copy.</p> * * @param image a image * * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-read">org.opencv.highgui.VideoCapture.read</a> */ public boolean read(Mat image) { boolean retVal = n_read(nativeObj, image.nativeObj); return retVal; } // // C++: void VideoCapture::release() // /** * <p>Closes video file or capturing device.</p> * * <p>The methods are automatically called by subsequent "VideoCapture.open" and * by <code>VideoCapture</code> destructor.</p> * * <p>The C function also deallocates memory and clears <code>*capture</code> * pointer.</p> * * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-release">org.opencv.highgui.VideoCapture.release</a> */ public void release() { n_release(nativeObj); return; } // // C++: bool VideoCapture::retrieve(Mat image, int channel = 0) // /** * <p>Decodes and returns the grabbed video frame.</p> * * <p>The methods/functions decode and return the just grabbed frame. If no frames * has been grabbed (camera has been disconnected, or there are no more frames * in video file), the methods return false and the functions return NULL * pointer.</p> * * <p>Note: OpenCV 1.x functions <code>cvRetrieveFrame</code> and <code>cv.RetrieveFrame</code> * return image stored inside the video capturing structure. It is not allowed * to modify or release the image! You can copy the frame using "cvCloneImage" * and then do whatever you want with the copy.</p> * * @param image a image * @param channel a channel * * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-retrieve">org.opencv.highgui.VideoCapture.retrieve</a> */ public boolean retrieve(Mat image, int channel) { boolean retVal = n_retrieve(nativeObj, image.nativeObj, channel); return retVal; } /** * <p>Decodes and returns the grabbed video frame.</p> * * <p>The methods/functions decode and return the just grabbed frame. If no frames * has been grabbed (camera has been disconnected, or there are no more frames * in video file), the methods return false and the functions return NULL * pointer.</p> * * <p>Note: OpenCV 1.x functions <code>cvRetrieveFrame</code> and <code>cv.RetrieveFrame</code> * return image stored inside the video capturing structure. It is not allowed * to modify or release the image! You can copy the frame using "cvCloneImage" * and then do whatever you want with the copy.</p> * * @param image a image * * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-retrieve">org.opencv.highgui.VideoCapture.retrieve</a> */ public boolean retrieve(Mat image) { boolean retVal = n_retrieve(nativeObj, image.nativeObj); return retVal; } // // C++: bool VideoCapture::set(int propId, double value) // /** * Sets a property in the "VideoCapture". * * @param propId property identifier; it can be one of the following: * * CV_CAP_PROP_FRAME_WIDTH width of the frames in the video stream. * * CV_CAP_PROP_FRAME_HEIGHT height of the frames in the video stream. * @param value value of the property. * * @see <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-set">org.opencv.highgui.VideoCapture.set</a> */ public boolean set(int propId, double value) { boolean retVal = n_set(nativeObj, propId, value); return retVal; } @Override protected void finalize() throws Throwable { n_delete(nativeObj); super.finalize(); } // C++: VideoCapture::VideoCapture() private static native long n_VideoCapture(); // C++: VideoCapture::VideoCapture(string filename) private static native long n_VideoCapture(java.lang.String filename); // C++: VideoCapture::VideoCapture(int device) private static native long n_VideoCapture(int device); // C++: double VideoCapture::get(int propId) private static native double n_get(long nativeObj, int propId); // C++: bool VideoCapture::grab() private static native boolean n_grab(long nativeObj); // C++: bool VideoCapture::isOpened() private static native boolean n_isOpened(long nativeObj); // C++: bool VideoCapture::open(string filename) private static native boolean n_open(long nativeObj, java.lang.String filename); // C++: bool VideoCapture::open(int device) private static native boolean n_open(long nativeObj, int device); // C++: bool VideoCapture::read(Mat image) private static native boolean n_read(long nativeObj, long image_nativeObj); // C++: void VideoCapture::release() private static native void n_release(long nativeObj); // C++: bool VideoCapture::retrieve(Mat image, int channel = 0) private static native boolean n_retrieve(long nativeObj, long image_nativeObj, int channel); private static native boolean n_retrieve(long nativeObj, long image_nativeObj); // C++: bool VideoCapture::set(int propId, double value) private static native boolean n_set(long nativeObj, int propId, double value); private static native String n_getSupportedPreviewSizes(long nativeObj); // native support for java finalize() private static native void n_delete(long nativeObj); }
[ "524787275@qq.com" ]
524787275@qq.com
ff6de87cb52670c393f226eb4ffdd80786852e57
40c4bb59ea751994a92c122a1100e9be08ab3677
/src/main/java/com/kh/naturephone/member/controller/MemberController.java
4529e0949d3528a25e2b27cd7c684a4108b55708
[]
no_license
parkjeongchan/naturephone
59ac4bc3cc6d6d8dd4e749dcdc47d9fee8beaf21
f3064216080d99ba86a314268f3da7e3e6ea4187
refs/heads/master
2023-07-13T13:14:26.460395
2021-08-23T06:37:40
2021-08-23T06:37:40
370,708,573
0
5
null
2021-07-22T18:04:57
2021-05-25T13:47:07
Java
UTF-8
Java
false
false
16,203
java
package com.kh.naturephone.member.controller; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; import java.util.List; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.github.scribejava.core.model.OAuth2AccessToken; import com.kh.naturephone.common.PageInfo; import com.kh.naturephone.common.Pagination; import com.kh.naturephone.member.model.service.MemberService; import com.kh.naturephone.member.model.vo.KeyPublish; import com.kh.naturephone.member.model.vo.MailUtil; import com.kh.naturephone.member.model.vo.Member; import com.kh.naturephone.member.model.vo.MyBoard; import com.kh.naturephone.member.model.vo.MyReply; @Controller @RequestMapping("/member") @SessionAttributes({ "loginUser" }) public class MemberController { /* NaverLoginBO */ private NaverLoginBO naverLoginBO; private String apiResult = null; @Autowired private MemberService mService; @Autowired private BCryptPasswordEncoder bcryptPasswordEncoder; @Autowired private void setNaverLoginBO(NaverLoginBO naverLoginBO) { this.naverLoginBO = naverLoginBO; } /* ----------------------페이지 이동---------------------- */ // 로그인 페이지 이동 @GetMapping("/loginPage") public String loginView(Model model, HttpSession session) { /* 네이버아이디로 인증 URL을 생성하기 위하여 naverLoginBO클래스의 getAuthorizationUrl메소드 호출 */ String naverAuthUrl = naverLoginBO.getAuthorizationUrl(session); // 네이버 model.addAttribute("url", naverAuthUrl); return "member/loginPage"; } // 회원가입 1단계 : 약관페이지 이동 @GetMapping("/joinPage") public String joinView() { return "member/joinPageTerms"; } // 회원가입 2단계 : 신상적기 페이지 이동 @GetMapping("/joinPage2") public String joinView2() { return "member/joinPage"; } // 마이페이지 클릭 -> 회원정보 페이지 이동 @GetMapping("/myPage") public String memberInfoView() { return "member/memberInfoPage"; } // 탈퇴 새창띄우기 @GetMapping("/quitPage") public String quitView() { return "member/quitPage"; } // 아이디 비밀번호 찾기 새창 띄우기 @GetMapping("/searchMemberPage") public String searchMemberView() { return "member/searchMemberPage"; } /*---------------------- 기능 구현(DB접근 X) ----------------------*/ // 로그아웃 메소드 @GetMapping("/logout") public String memberLogout(SessionStatus status, RedirectAttributes rd) { status.setComplete(); rd.addFlashAttribute("msg", "정상적으로 로그아웃 되었습니다."); return "redirect:/"; } /*---------------------- 기능 구현(DB접근 O) ----------------------*/ // 1. 회원 로그인 서비스를 위한 메소드 @PostMapping("/login") public String memberLogin(@ModelAttribute Member m, Model model, RedirectAttributes rd) { Member loginUser = mService.loginMember(m); if (loginUser != null && bcryptPasswordEncoder.matches(m.getPwd(), loginUser.getPwd())) { model.addAttribute("loginUser", loginUser); rd.addFlashAttribute("msg", "네이처폰에 오신것을 환영합니다!"); return "redirect:/"; } else { model.addAttribute("msg", "로그인에 실패하였습니다."); return "member/loginPage"; } } // 2-1. 아이디 중복 검사 메소드 (Ajax) @RequestMapping(value = "/idOverlap", method = RequestMethod.POST) public void idOverlapCheck(String id, HttpServletResponse response) throws Exception { mService.idOverlapCheck(id, response); } // 2-2. 이메일 중복 검사 메소드 (Ajax) @RequestMapping(value = "/emailOverlap", method = RequestMethod.POST) public void emailOverlapCheck(String email, HttpServletResponse response) throws Exception { mService.emailOverlapCheck(email, response); } // 3-1. 메일 인증 메소드 (Ajax) @RequestMapping(value = "/joinSendMail", method = RequestMethod.POST) @ResponseBody public void joinSendMail(@ModelAttribute Member m, HttpSession session) throws Exception { String keyCode = KeyPublish.createKey(); session.setAttribute("keyCode", keyCode); String subject = ""; String msg = ""; // 회원가입 메일 내용 subject = "Nature Phone 회원가입 인증 코드입니다."; msg += "<div align='center' style='border:1px solid black; font-family:verdana'>"; msg += "<div style='font-size: 130%'>"; msg += "회원가입 페이지에서 인증코드 <strong>"; msg += keyCode + "</strong> 를 입력해 주세요.</div><br/>"; MailUtil.sendMail(m.getEmail(), subject, msg); } // 3-2. 메일 인증키 확인 메소드(Ajax) @RequestMapping(value = "/keyCheck", method = RequestMethod.POST) @ResponseBody public String keyCheck(@RequestParam("modalInput") String key, @SessionAttribute("keyCode") String keyCode) { if (key != null && key.equals(keyCode)) { return "success"; } else { return "false"; } } // 4. 회원가입 메소드 @PostMapping("/join") public String memberJoin(@ModelAttribute Member m, @RequestParam("postcode") String postcode, @RequestParam("address1") String address1, @RequestParam("address2") String address2, @RequestParam("hp1") String hp1, @RequestParam("hp2") String hp2, @RequestParam("hp3") String hp3, Model model, RedirectAttributes rd) throws Exception { m.setAddress(postcode + "*" + address1 + "*" + address2); m.setPhone(hp1 + "-" + hp2 + "-" + hp3); m.setPwd(bcryptPasswordEncoder.encode(m.getPwd())); int result = mService.insertMember(m); if (result > 0) { rd.addFlashAttribute("msg", "회원 가입이 성공적으로 이루어졌습니다. 로그인 해주세요!"); return "redirect:/"; } else { model.addAttribute("msg", "회원 가입에 실패하였습니다."); return "common/errorPage"; } } // 5. 회원정보 수정 메소드 @PostMapping("/update") public String memberUpdate(@ModelAttribute("loginUser") Member m, @RequestParam("postcode") String postcode, @RequestParam("address1") String address1, @RequestParam("address2") String address2, @RequestParam("hp1") String hp1, @RequestParam("hp2") String hp2, @RequestParam("hp3") String hp3, Model model) { m.setAddress(postcode + "*" + address1 + "*" + address2); m.setPhone(hp1 + "-" + hp2 + "-" + hp3); int result = mService.updateMember(m); if (result > 0) { model.addAttribute("msg", "회원정보가 성공적으로 수정되었습니다."); return "member/memberInfoPage"; } else { model.addAttribute("msg", "회원 정보 수정에 실패하였습니다."); return "common/errorPage"; } } // 6. 비밀번호 변경 메소드 @PostMapping("/pwdupdate") public String pwdUpdate(@RequestParam("pwdOrigin") String pwdOrigin, @RequestParam("pwdChange") String pwdChange, @SessionAttribute("loginUser") Member loginUser, RedirectAttributes rd, SessionStatus status, Model model) { if (bcryptPasswordEncoder.matches(pwdOrigin, loginUser.getPwd()) == true) { loginUser.setPwd(bcryptPasswordEncoder.encode(pwdChange)); int result = mService.pwdUpdate(loginUser); if (result > 0) { status.setComplete(); rd.addFlashAttribute("msg", "비밀번호 변경이 성공적으로 이루어졌습니다. 다시 로그인해주세요!"); return "redirect:/"; } else { model.addAttribute("msg", "비밀번호 변경에 실패하였습니다."); return "common/errorPage"; } } else { model.addAttribute("msg", "비밀번호가 일치하지 않습니다."); return "member/memberInfoPage"; } } // 7. 회원 탈퇴 - 비밀번호 확인 메소드 (Ajax) @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public String deleteMember(@RequestBody Member m, @SessionAttribute("loginUser") Member loginUser, SessionStatus status) throws Exception { // session에 저장 된 비밀번호와 일치 하다면 탈퇴 처리 진행 if (bcryptPasswordEncoder.matches(m.getPwd(), loginUser.getPwd()) == true) { m.setUserNo(loginUser.getUserNo()); int result = mService.deleteMember(m); if (result > 0) { status.setComplete(); return "success"; } else { return "error"; } // session에 저장 된 비밀번호와 일치하지 않다면 탈퇴 처리 중단 } else { return "inconsistency"; } } // 8. 아이디 찾기 메소드 @RequestMapping(value = "/findIdSendMailAjax", method = RequestMethod.POST) @ResponseBody public String findIdSendMail(@RequestParam(value = "findIdEmail") String findIdEmail) throws Exception { String searchId = mService.findIdSendMail(findIdEmail); String subject = ""; String msg = ""; // 사용자가 입력한 이메일이 DB에 존재한다면, 이메일로 ID를 보내준다 if (searchId != null) { // 회원가입 메일 내용 subject = "Nature Phone 아이디입니다."; msg += "<div align='center' style='border:1px solid black; font-family:verdana'>"; msg += "<div style='font-size: 130%'>"; msg += "회원님의 아이디는 <strong>"; msg += searchId + "</strong> 입니다. </div><br/>"; MailUtil.sendMail(findIdEmail, subject, msg); return "success"; } else { return "null"; } } // 9. 비밀번호 찾기 메소드 @RequestMapping(value = "/findPwdEmailAjax", method = RequestMethod.POST) @ResponseBody public String findPwdSendEmail(@RequestBody Member m) throws Exception { String searchId = mService.findIdSendMail(m.getEmail()); // 사용자가 입력한 이메일이 DB에 존재한다면, KeyPublish 객체를 이용해 새로운 비밀번호를 생성해서 DB에 저장 후 이메일로 전달한다. if (searchId != null) { String keyCode = KeyPublish.createKey() + "Q" + "v" + "!" + "5"; m.setApprovalKey(bcryptPasswordEncoder.encode(keyCode)); String subject = ""; String msg = ""; int result = mService.findPwdSendEmail(m); if (result > 0) { // 회원가입 메일 내용 subject = "Nature Phone 새로운 비밀번호를 발급해드립니다."; msg += "<div align='center' style='border:1px solid black; font-family:verdana'>"; msg += "<div style='font-size: 130%'>"; msg += "새로운 비밀번호 <strong>"; msg += keyCode + "</strong> 를 발급해드렸습니다. 로그인 하신 후 비밀번호를 꼭 변경해주세요.</div><br/>"; MailUtil.sendMail(m.getEmail(), subject, msg); return "success"; } else { return "fail"; } // 사용자가 입력한 이메일이 DB에 존재하지 않을 때 } else { return "null"; } } /*---------------------- 네이버 간편 로그인 ----------------------*/ // 네이버 로그인창 호출 @RequestMapping(value = "/getNaverAuthUrl") public @ResponseBody String getNaverAuthUrl(HttpSession session) throws Exception { String reqUrl = naverLoginBO.getAuthorizationUrl(session); return reqUrl; } // 네이버 로그인 @RequestMapping(value = "/callback", method = { RequestMethod.GET, RequestMethod.POST }) public String callback(Model model, @RequestParam String code, @RequestParam String state, RedirectAttributes rd, HttpSession session, HttpServletResponse response) throws IOException, ParseException { OAuth2AccessToken oauthToken; oauthToken = naverLoginBO.getAccessToken(session, code, state); // 1. 로그인 사용자 정보를 읽어온다. apiResult = naverLoginBO.getUserProfile(oauthToken); // String형식의 json데이터 // 2. String형식인 apiResult를 json형태로 바꿈 JSONParser parser = new JSONParser(); Object obj = parser.parse(apiResult); JSONObject jsonObj = (JSONObject) obj; // 3. 데이터 파싱 // Top레벨 단계 _response 파싱 JSONObject response_obj = (JSONObject) jsonObj.get("response"); // 필수값 - 이름, 휴대전화 번호, 이메일 String nName = (String) response_obj.get("name"); String nEmail = (String) response_obj.get("email"); String nPhone = (String) response_obj.get("mobile"); String nTokenId = (String) response_obj.get("id"); // 4. 가입된 회원인지 확인 Member loginUser = mService.searchNEmail(nEmail); // 4-1. 가입된 회원일 시 로그인 처리 if (loginUser != null) { model.addAttribute("loginUser", loginUser); rd.addFlashAttribute("msg", "네이처폰에 오신것을 환영합니다!"); return "redirect:/"; // 4-2. 가입되지 않은 회원일 때 회원가입 처리 } else { // 필수입력값이 다 들어왔다면 DB에 저장후 로그인 if (nName != null && nEmail != null && nPhone != null) { Member m = new Member(); String nPwd = KeyPublish.createKey(); m.setPwd(bcryptPasswordEncoder.encode(nPwd)); m.setName(nName); m.setPhone(nPhone); m.setEmail(nEmail); m.setToken(nTokenId); // DB 저장 mService.naverInsert(m); // 로그인 m = mService.loginMember(m); model.addAttribute("loginUser", m); rd.addFlashAttribute("msg", "네이처폰에 오신것을 환영합니다!"); return "redirect:/"; // 필수입력값 다 들어오지 않았다면 네아로 재요청 } else { String url = URLEncoder.encode("http://localhost:8800/naturephone/member/callback", "UTF-8"); return "redirect:https://nid.naver.com/oauth2.0/authorize?response_type=code&client_id=_neJ4MDnS0PpuxFf3FQU&state=" + state + "&redirect_uri=" + url + "&auth_type=reprompt"; } } } /*---------------------- 마이페이지 - 나의 게시글, 나의 댓글 조회 ----------------------*/ // 나의 게시글 조회 @GetMapping("/myBoardList") public ModelAndView selectMyBoardList(ModelAndView mv, @SessionAttribute("loginUser") Member loginUser, @RequestParam(value = "page", required = false, defaultValue = "1") int currentPage) { int userNo = loginUser.getUserNo(); int listCount = mService.selectListCount(userNo); PageInfo pi = Pagination.getPageInfo(currentPage, listCount); List<MyBoard> list = mService.selectMyBoardList(userNo, pi); if (list != null) { mv.addObject("list", list); mv.addObject("pi", pi); mv.setViewName("member/myBoardPage"); } return mv; } // 나의 댓글 조회 @GetMapping("/myReplyList") public ModelAndView selectMyReplyList(ModelAndView mv, @SessionAttribute("loginUser") Member loginUser, @RequestParam(value = "page", required = false, defaultValue = "1") int currentPage) { int userNo = loginUser.getUserNo(); int listCount = mService.selectReplyListCount(userNo); PageInfo pi = Pagination.getPageInfo(currentPage, listCount); List<MyReply> list = mService.selectMyReplyList(userNo, pi); if (list != null) { mv.addObject("list", list); mv.addObject("pi", pi); mv.setViewName("member/myReplyPage"); } return mv; } }
[ "hj.liventure@gmail.com" ]
hj.liventure@gmail.com
69982a6eda55565186e9899afdade452d73c3f9e
d0a6784c047f92e5cb898ee16bdbeef6a7f25db1
/src/main/java/group/msg/entities/RightType.java
84c1e2a7e4780ef688ccf5a009f0a26812249578
[]
no_license
gnicoleta/TeamCookies
8a9a55a7e781be9988e0f90cac5b7b3df56ca11c
728cb52d73f20e4a7aeb9962eb514d5a6f33a2ff
refs/heads/master
2020-04-05T11:55:19.396145
2018-08-17T10:49:24
2018-08-17T10:49:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
157
java
package group.msg.entities; public enum RightType { PERMISSION_MANAGEMENT, USER_MANAGEMENT, BUG_MANAGEMENT, BUG_CLOSE, BUG_EXPORT_PDF }
[ "petrutstoica123@yahoo.com" ]
petrutstoica123@yahoo.com
5d4e9dea9e782c0ee95717b8bbf20a9c68862226
8d8874cf53871beec60568318415390d73a44329
/src/main/java/portfolioshop/cart/CartGoodsRepository.java
eaad242245d58ac452534765037eabedd3ec2eb2
[]
no_license
whd0714/PortFolioShop2
87b05a9fca1c82f370a7aacfc0ae6c55115d1d22
84006a75390ee96ebe8853700b9aa073f35bce30
refs/heads/master
2023-05-07T17:27:03.486138
2021-05-15T12:47:43
2021-05-15T12:47:43
351,035,998
0
0
null
null
null
null
UTF-8
Java
false
false
432
java
package portfolioshop.cart; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; public interface CartGoodsRepository extends JpaRepository<CartGoods, Long> { @Query("select cg from CartGoods cg join fetch cg.cart c join fetch cg.goods g where c.id = :cartId and g.id = :goodsId") CartGoods findByCartGoodsByCartIdAndGoodsId(Long cartId, Long goodsId); }
[ "whd0714@naver.com" ]
whd0714@naver.com
3db73d8e5160a79b062481ca0f5430168bb1877d
113954a1a384bd1e32772cf170bf73c4fd0b47c6
/CMB/app/src/main/java/com/justicecoder/cmb/UtilsActivity.java
dc44c781e93687985fdde07644cb4f8812149f2a
[ "Apache-2.0" ]
permissive
kaungkhantjc/Call-Me-Back
b6d6e2b940cd6b9fa86ef7c8a74b38e20a5b9c39
b38ebc1cee89ec472e7c93d1c320104f7903b9ff
refs/heads/master
2020-09-16T10:55:44.569423
2020-08-24T03:57:17
2020-08-24T03:57:17
223,748,196
1
1
null
null
null
null
UTF-8
Java
false
false
4,602
java
package com.justicecoder.cmb; import android.util.Base64; import android.os.Build; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.app.*; import android.content.DialogInterface; import android.Manifest; import android.content.pm.*; import android.content.Intent; import android.net.Uri; public class UtilsActivity extends Activity { public final String DEV_STR = "Q01CIGFwcCB3YXMgZGV2ZWxvcGVkIGJ5IEthdW5nIEtoYW50IEt5YXcu"; public final String PREF_OPERATOR = "PREF_OPERATOR"; public final String PREF_SWITCH_STATE = "PREF_SWITCH_STATE"; public final String PREF_PHONE_NUMBER = "PREF_PHONE_NUMBER"; public final int REQUEST_CODE_READ_CONTACT = 1; public final int REQUEST_CODE_CALL_PHONE = 2; public final int ACTIVITY_RESULT_PICK_CONTACT = 3; public String decodeString (String s){ return new String (Base64.decode(s, Base64.DEFAULT)); } public boolean isCurrentApiLevelLowerThanOrEquals (int sdk){ return Build.VERSION.SDK_INT <= sdk; } public void hideKeyboard (EditText edt){ InputMethodManager im = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); if(im.isActive() && edt!= null){ im.hideSoftInputFromWindow(edt.getWindowToken(), 0); } } public void closeApp (){ finish(); } public void showAlert (Exception e){ final AlertDialog ad = new AlertDialog.Builder(UtilsActivity.this).create(); ad.setMessage(e.getClass().getName() + "\n" + e.getMessage()); ad.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface p1, int p2) { ad.dismiss(); }}); ad.show(); } public void showContactRationale (){ final AlertDialog ad = new AlertDialog.Builder(UtilsActivity.this).create(); ad.setMessage(getString(R.string.read_contact_rationale)); ad.setButton(AlertDialog.BUTTON_POSITIVE, "Allow", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface p1, int p2) { requestContactPermission(); }}); ad.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface p1, int p2) { ad.dismiss(); }}); ad.show(); } public void showCallRationale (){ final AlertDialog ad = new AlertDialog.Builder(UtilsActivity.this).create(); ad.setMessage(getString(R.string.call_phone_rationale)); ad.setButton(AlertDialog.BUTTON_POSITIVE, "Allow", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface p1, int p2) { requestCallPermission(); }}); ad.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface p1, int p2) { ad.dismiss(); }}); ad.show(); } // Request Permission methods for API level 22 and above private boolean isPermissionGranted (String permission){ return checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED; } public boolean isContactPermissionGranted (){ return isCurrentApiLevelLowerThanOrEquals(21) || isPermissionGranted(Manifest.permission.READ_CONTACTS); }; public boolean isCallPermissionGranted (){ return isCurrentApiLevelLowerThanOrEquals(21) || isPermissionGranted(Manifest.permission.CALL_PHONE); }; public boolean shouldShowContactRationale(){ return shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS); } public boolean shouldShowCallRationale(){ return shouldShowRequestPermissionRationale(Manifest.permission.CALL_PHONE); } public void requestContactPermission (){ requestPermissions(new String[] {Manifest.permission.READ_CONTACTS}, REQUEST_CODE_READ_CONTACT ); } public void requestCallPermission (){ requestPermissions(new String[] {Manifest.permission.CALL_PHONE}, REQUEST_CODE_CALL_PHONE ); } public void visitDev(){ try { PackageManager packageManager = getPackageManager(); ApplicationInfo appInfo = packageManager.getApplicationInfo("com.facebook.katana", 0); if (appInfo.enabled) { Intent i1 = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/100012183557720")); startActivity(i1); } else { Intent i2 = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/kaungkhantkyawprofile")); startActivity(i2); } } catch (Exception e) { Intent i3 = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/kaungkhantkyawprofile")); startActivity(i3); } } }
[ "noreply@github.com" ]
noreply@github.com
899b1ed945c62ad3f7ad7471e771029036ebbf45
c9ec08ac22843af88442dba781c6d51ccce6b33f
/src/Week12Homework/DataTypes.java
69efdb2643d579e06e96551ae7dddad778751e4a
[]
no_license
rinalpatel1/week12-homework
04c5574c7552cd5150a69722cfa1e428a645b25f
59a38862226896b192b00c7bccccc89033d59279
refs/heads/master
2023-08-16T03:18:01.424402
2021-10-18T23:09:04
2021-10-18T23:09:04
418,693,807
0
0
null
null
null
null
UTF-8
Java
false
false
522
java
package Week12Homework; public class DataTypes { public static void main(String[] args){ int a = 5; int b = 10; System.out.println(a+b); int a1 = 30; int b1 = 10; System.out.println(a1-b1); int a2 = 5; int b2 = 10; System.out.println(a2*b2); int a3 = 100; int b3 = 2; System.out.println(a3/b3); int a4 = 20; int b4 = 30; System.out.println(a4+1); System.out.println(b4-1); } }
[ "rinalpatel2017@hotmail.com" ]
rinalpatel2017@hotmail.com
2a7e77a71f77253157228b89d82ad0b1d9b846d5
7961133bd042d73e83871877378ef55579b63058
/src/main/java/com/siwuxie095/spring/chapter8th/example2nd/Main.java
4e3491e2341eeb74f30d5e7b570eebec4835f404
[]
no_license
siwuxie095/spring-practice
f234c14f33e468538fb620b4dd8648526fc2d28c
7fa5aeaa5c81efd30a5c3d9e0d1396d0f866b056
refs/heads/master
2023-04-08T03:33:46.620416
2021-04-03T06:57:19
2021-04-03T06:57:19
319,481,337
0
0
null
null
null
null
UTF-8
Java
false
false
6,674
java
package com.siwuxie095.spring.chapter8th.example2nd; /** * @author Jiajing Li * @date 2021-02-09 16:24:08 */ @SuppressWarnings("all") public class Main { /** * 在 Spring 中配置 Web Flow * * Spring Web Flow 是构建于 Spring MVC 基础之上的。这意味着所有的流程请求都需要首先经过 Spring MVC * 的 DispatcherServlet。需要在 Spring 应用上下文中配置一些 bean 来处理流程请求并执行流程。 * * 现在,还不支持在 Java 中配置 Spring Web Flow,所以别无选择,只能在 XML 中对其进行配置。有一些 bean * 会使用 Spring Web Flow 的 Spring 配置文件命名空间来进行声明。因此,需要在上下文定义XML文件中添加这 * 个命名空间声明: * * <?xml version="1.0" encoding="UTF-8"?> * <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" * xmlns:flow="http://www.springframework.org/schema/webflow-config" * xmlns:context="http://www.springframework.org/schema/context" * xmlns="http://www.springframework.org/schema/beans" * xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd * http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd * http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config.xsd"> * * 在声明了命名空间之后,就为装配 Web Flow 的 bean 做好了准备,下面从流程执行器(flow executor)开始吧。 * * * * 1、装配流程执行器 * * 正如其名字所示,流程执行器(flow executor)驱动流程的执行。当用户进入一个流程时,流程执行器会为用户创建 * 并启动一个流程执行实例。当流程暂停的时候(如为用户展示视图时),流程执行器会在用户执行操作后恢复流程。 * * 在Spring中,<flow:flow-executor> 元素会创建一个流程执行器: * * <flow:flow-executor id="flowExecutor"/> * * 尽管流程执行器负责创建和执行流程,但它并不负责加载流程定义。这个责任落在了流程注册表(flow registry)身 * 上,接下来会创建它。 * * * * 2、配置流程注册表 * * 流程注册表(flow registry)的工作是加载流程定义并让流程执行器能够使用它们。可以在 Spring 中使用 * <flow:flow-registry> 配置流程注册表,如下所示: * * <flow:flow-registry id="flowRegistry" * base-path="/WEB-INF/flows"> * <flow:flow-location-pattern value="*-flow.xml"/> * </flow:flow-registry> * * 在这里的声明中,流程注册表会在 "/WEB-INF/flows" 目录下查找流程定义,这是通过 base-path 属性指明的。 * 依据 <flow:flow-location-pattern> 元素的值,任何文件名以 "-flow.xml" 结尾的 XML 文件都将视为流程 * 定义。 * * 所有的流程都是通过其 ID 来进行引用的。这里使用了 <flow:flow-location-pattern> 元素,流程的 ID 就是 * 相对于 base-path 的路径或者双星号所代表的路径。 * * 如下示例展示了流程 ID 是如何计算的: * * /WEB-INF/flows/order/order-flow.xml * * (1)WEB-INF/flows 即 流程注册表基本路径; * (2)order 即 流程 ID; * (3)order-flow.xml 即 流程定义。 * * PS:在使用流程定位模式的时候,流程定义文件相对于基本路径的路径将被用作流程的 ID。 * * 作为另一种方式,可以去除 base-path 属性,而显式声明流程定义文件的位置: * * <flow:flow-registry id="flowRegistry"> * <flow:flow-location path="/WEB-INF/flows/springpizza.xml"/> * </flow:flow-registry> * * 在这里,使用了 <flow:flow-location> 而不是 <flow:flow-location-pattern>,path 属性直接指明了 * "/WEB-INF/flows/springpizza.xml" 作为流程定义。当这样配置的话,流程的 ID 是从流程定义文件的文件 * 名中获得的,在这里就是 springpizza。 * * 如果你希望更显式地指定流程 ID,那你可以通过 <flow:flow-location> 元素的 id 属性来进行设置。例如, * 要将 pizza 作为流程 ID,可以像这样配置: * * <flow:flow-registry id="flowRegistry"> * <flow:flow-location id="pizza" path="/WEB-INF/flows/springpizza.xml"/> * </flow:flow-registry> * * * * 3、处理流程请求 * * DispatcherServlet 一般将请求分发给控制器。但是对于流程而言,需要一个 FlowHandlerMapping 来帮助 * DispatcherServlet 将流程请求发送给 Spring Web Flow。在 Spring 应用上下文中,FlowHandlerMapping * 的配置如下: * * <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping"> * <property name="flowRegistry" ref="flowRegistry"/> * </bean> * * 可以看到,FlowHandlerMapping 装配了流程注册表的引用,这样它就能知道如何将请求的 URL 匹配到流程上。例如, * 如果有一个 ID 为 pizza 的流程,FlowHandlerMapping 就会知道如果请求的 URL 模式(相对于应用程序的上下文 * 路径)是 "/pizza" 的话,就要将其匹配到这个流程上。 * * 然而,FlowHandlerMapping 的工作仅仅是将流程请求定向到 Spring Web Flow 上,响应请求的是 FlowHandlerAdapter。 * FlowHandlerAdapter 等同于 Spring MVC 的控制器,它会响应发送的流程请求并对其进行处理。FlowHandlerAdapter 可 * 以像下面这样装配成一个 Spring bean,如下所示: * * <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter"> * <property name="flowExecutor" ref="flowExecutor"/> * </bean> * * 这个处理适配器是 DispatcherServlet 和 Spring Web Flow 之间的桥梁。它会处理流程请求并管理基于这些请求的流程。 * 在这里,它装配了流程执行器的引用,而后者是为所处理的请求执行流程的。 * * 已经配置了 Spring Web Flow 所需的 bean 和组件,剩下的就是真正定义流程了。 */ public static void main(String[] args) { } }
[ "834879583@qq.com" ]
834879583@qq.com
0ab59ffd310f7f85a3d0298d482ad5fe15978eed
88252dad1b411dd2a580f1182af707d0c0981841
/JavaSE210301/day24/src/com/atguigu/java1/MyInterface.java
70f1bc69f6d41b4bc4140b2bd64a177203ef703c
[]
no_license
FatterXiao/myJavaLessons
37db50d24cbcc5524e5b8060803ab08ab3b3ac0c
fa6ff208b46048527b899001561bd952f48bbe15
refs/heads/main
2023-04-20T09:18:06.694611
2021-04-29T10:18:30
2021-04-29T10:18:30
347,562,482
0
1
null
null
null
null
UTF-8
Java
false
false
125
java
package com.atguigu.java1; /** * @author shkstart * @create 14:09 */ public interface MyInterface { void method(); }
[ "xuweijunxinlan@yeah.net" ]
xuweijunxinlan@yeah.net
fe2292f1839ec57b1caa8f67219ca1a35253a7aa
c371d23fe53241e8c0b6f1e040d7da3104bf955c
/src/main/java/eu/smartdatalake/simsearch/ranking/SingletonRanking.java
02135208681a725ccb605623cfdf21bcfb72c26f
[ "Apache-2.0" ]
permissive
xmzhao/simsearch
a13a6d7bd0bdc6563ef70e414b8a6273ac1655f4
a8ed6833bb9f166cf77503cc580148edcb355498
refs/heads/master
2023-03-14T17:19:34.401794
2021-03-22T14:35:04
2021-03-22T14:35:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,515
java
package eu.smartdatalake.simsearch.ranking; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import eu.smartdatalake.simsearch.Assistant; import eu.smartdatalake.simsearch.Constants; import eu.smartdatalake.simsearch.Logger; import eu.smartdatalake.simsearch.engine.IResult; import eu.smartdatalake.simsearch.engine.PartialResult; import eu.smartdatalake.simsearch.manager.DatasetIdentifier; import eu.smartdatalake.simsearch.measure.ISimilarity; /** * Wrapper to handle similarity search requests involving a single attribute, where no rank aggregation is actually required. * This actually returns the top-k results from the priority queue as obtained by the individual kNN query executed against the data source (a single attribute). */ public class SingletonRanking implements IRankAggregator { Logger log = null; Assistant myAssistant; String val; double score; int topk; // Number of ranked aggregated results to collect // Collection of queues that collect results from each running task Map<String, ConcurrentLinkedQueue<PartialResult>> queues; Map<String, Thread> tasks; // Collection of all data/index datasetIdentifiers involved in the search Map<String, DatasetIdentifier> datasetIdentifiers; // Weights Map<String, Double[]> weights; int weightCombinations; // Collection of atomic booleans to control execution of the various threads Map<String, AtomicBoolean> runControl = new HashMap<String, AtomicBoolean>(); // Collection of similarity functions to be used in random access calculations Map<String, ISimilarity> similarities; // Collection of the ranked results to be given as output per weight combination ResultCollection[] results; // Sum of weights per combination double[] sumWeights; /** * Constructor * @param datasetIdentifiers List of the attributes involved in similarity search queries. * @param similarities Dictionary of the similarity measures applied in each search query. * @param weights Dictionary of the (possibly multiple alternative) weights per attribute to be applied in scoring the final results. * @param tasks Collection of running threads; each one executes a query and it is associated with its respective queue that collects its results. * @param queues Collection of the queues collecting results from each search query. * @param runControl Collection of boolean values indicating the status of each thread. * @param topk The count of ranked aggregated results to collect, i.e., those with the top-k (highest) aggregated similarity scores. * @param log Handle to the log file for notifications and execution statistics. */ public SingletonRanking(Map<String, DatasetIdentifier> datasetIdentifiers, Map<String, ISimilarity> similarities, Map<String, Double[]> weights, Map<String, Thread> tasks, Map<String, ConcurrentLinkedQueue<PartialResult>> queues, Map<String, AtomicBoolean> runControl, int topk, Logger log) { myAssistant = new Assistant(); this.log = log; this.datasetIdentifiers = datasetIdentifiers; this.similarities = similarities; this.tasks = tasks; this.queues = queues; this.weights = weights; this.runControl = runControl; this.topk = topk; // Number of combinations of weights to apply weightCombinations = weights.entrySet().iterator().next().getValue().length; // Array of collection of results; one collection (list) per combination of weights results = new ResultCollection[weightCombinations]; // Initialize all array structures for (int w = 0; w < weightCombinations; w++) { results[w] = new ResultCollection(); } } /** * Inserts or updates the ranked aggregated results based on a result from the i-th queue * @param taskKey The hashKey of the task to be checked for its next result. * @param n The rank of the new result. * @return A Boolean value: True, if the ranked aggregated list has been updated; otherwise, False. */ private boolean updateRankedList(String taskKey, int n) { PartialResult cand = queues.get(taskKey).peek(); if (cand != null) { // Create a new resulting item and report its rank and its original identifier... RankedResult res = new RankedResult(1); // A single attribute will be reported res.setId((String)cand.getId()); res.setRank(n); // ... also its original attribute value and its calculated similarity score // Assuming a SINGLE, NOT NULL attribute value ResultFacet attr = new ResultFacet(); attr.setName(this.datasetIdentifiers.get(taskKey).getValueAttribute()); attr.setValue(myAssistant.formatAttrValue(cand.getValue())); // Also its individual similarity score attr.setScore(cand.getScore()); res.attributes[0] = attr; //... and its overall aggregated score res.setScore(cand.getScore()); // Aggregate score is equal to that on the singleton attribute // Indicate whether this ranking should be considered exact or not res.setExact(true); for (int w = 0; w < weightCombinations; w++) { // Issue result to the output queue results[w].add(res); } return true; } return false; } /** * Implements the processing logic of the threshold-based algorithm. */ @Override public IResult[][] proc() { boolean running = true; int n = 0; // This is the key of the single task fetching candidates String taskKey = tasks.keySet().stream().findFirst().get(); try { // Number of ranked aggregated results so far int[] k = new int[weightCombinations]; // Each k is monitoring progress for each combination of weights Arrays.fill(k, 0); // Calculate the sum of weights for each combination sumWeights = new double[weightCombinations]; Arrays.fill(sumWeights, 0.0); for (int w = 0; w < weightCombinations; w++) { sumWeights[w] += this.weights.get(taskKey)[w]; } boolean allScalesSet = false; long startTime = System.currentTimeMillis(); while (running) { // Wait until the scale factor for similarity scores has been set while (allScalesSet == false) { allScalesSet = true; TimeUnit.NANOSECONDS.sleep(100); // In case that the task is completed and no scale has been set, this means that all results are exact and no scale is needed allScalesSet = allScalesSet && (!runControl.get(taskKey).get() || this.similarities.get(taskKey).isScaleSet()); } n++; // Showing rank as 1,2,3,... instead of 0,1,2,... running = false; // Wait until the examined queue has been updated with its n-th result boolean stop = true; // Wait a while and then try again to fetch results from the queue while (updateRankedList(taskKey, n) == false) { TimeUnit.NANOSECONDS.sleep(1); if (System.currentTimeMillis() - startTime > Constants.RANKING_MAX_TIME) break; } // Stop if all results have been acquired stop = stop && (( n > topk )); // Determine whether to continue polling results from queue // Once top-k ranked results are returned, stop the running task gracefully // If the process times out, then stop any further examination if (stop || (System.currentTimeMillis() - startTime > Constants.RANKING_MAX_TIME)) { runControl.get(taskKey).set(false); //Stop each task running = false; // Quit the ranked aggregation process } else { // Otherwise, the task is still running, so continue fetching results queues.get(taskKey).poll(); // Remove already processed result from this queue // Once a queue is exhausted, it is no longer considered and search continues with the remaining queues if (tasks.get(taskKey).isAlive() || !queues.get(taskKey).isEmpty()) { running = true; } } } } catch (Exception e) { e.printStackTrace(); } this.log.writeln("In total " + n + " results have been fetched from the queue."); // Prepare array of final results IResult[][] allResults = new IResult[weightCombinations][topk]; for (int w = 0; w < weightCombinations; w++) { allResults[w] = results[w].toArray(); } return allResults; } }
[ "kpatro@athenarc.gr" ]
kpatro@athenarc.gr
c87aeca8b51d806cb4997e4edd079826769a3ad4
17af5929668dfe82f2852c00e7bbb93283de6e1e
/app/src/main/java/activity/basic/BaseViewModel.java
6b628dd94a19a10b9c16d60b5814ec6ed2c607eb
[]
no_license
Khyatinaik07/khyati
2f5ac4740d55d9a2235e26ca3ee37582b1afe032
21f180579999fbca6b480c7ba00ae17caa9811ce
refs/heads/master
2020-12-03T03:32:41.559592
2020-03-11T11:11:30
2020-03-11T11:11:30
231,197,113
0
0
null
null
null
null
UTF-8
Java
false
false
2,061
java
package activity.basic; import androidx.databinding.ObservableBoolean; import androidx.lifecycle.ViewModel; import java.lang.ref.WeakReference; import data.DataManager; import io.reactivex.disposables.CompositeDisposable; import utils.rx.SchedulerProvider; public abstract class BaseViewModel<N extends BaseNevigator> extends ViewModel { private final DataManager mDataManager; private final SchedulerProvider mSchedulerProvider; private final CompositeDisposable mCompositeDisposable; private final int mBackgroundColor; private final int mEventColor; private WeakReference<N> mNavigator; private ObservableBoolean isSearchVisible = new ObservableBoolean(false); private final ObservableBoolean isEmpty = new ObservableBoolean(false); public BaseViewModel(DataManager dataManager, SchedulerProvider schedulerProvider) { this.mDataManager = dataManager; this.mSchedulerProvider = schedulerProvider; this.mCompositeDisposable = new CompositeDisposable(); this.mBackgroundColor = getDataManager().getBackgroundColor(); this.mEventColor = getDataManager().getEventColor(); } public DataManager getDataManager() { return mDataManager; } public int getBackgroundColor() { return mBackgroundColor; } public int getEventColor() { return mEventColor; } public N getNavigator() { return mNavigator.get(); } public void setNavigator(N navigator) { this.mNavigator = new WeakReference<>(navigator); } public SchedulerProvider getSchedulerProvider() { return mSchedulerProvider; } public CompositeDisposable getCompositeDisposable() { return mCompositeDisposable; } public void setIsSearchVisible(boolean isSearchVisible) { this.isSearchVisible.set(isSearchVisible); } public ObservableBoolean getIsSearchVisible() { return isSearchVisible; } public void setIsEmpty(boolean isEmpty) { this.isEmpty.set(isEmpty); } }
[ "khyatinaik101@gmail.com" ]
khyatinaik101@gmail.com
5500a618f2bc452f1aad5344ed002995f4af590b
62f4aaa64e4a7d054b6267ecad92837cdab64488
/src/main/java/leetcode/leetcode_18_4sum/Main.java
07bcd471ee09e1da9fa61e915c3a23ccde7615dd
[]
no_license
danielnorberg/katas
f61cec77141a0046022050801d42f31c9c0e7da4
4697ad26facafa13e237568e4ee498f11813d2a1
refs/heads/master
2021-01-25T07:08:02.787014
2019-01-30T01:13:05
2019-01-30T01:13:05
20,840,188
1
2
null
null
null
null
UTF-8
Java
false
false
471
java
package leetcode.leetcode_18_4sum; import java.util.List; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertThat; public class Main { public static void main(final String... args) { assertThat(fourSum(3, -1, 2, 2, -5, 0, -1, 4), contains( contains(-5, 2, 2, 4), contains(-1, 0, 2, 2))); } static List<List<Integer>> fourSum(int target, int... nums) { return new Solution().fourSum(nums, target); } }
[ "daniel.norberg@gmail.com" ]
daniel.norberg@gmail.com
acfaac7b5679c6f44deecb215aad98cb7d4337ce
7f271adb80fdd3fae825ffadad0d3bd837f9090c
/tappweb/src/main/java/org/tapp/dal/DocumentDAOInter.java
6f1528f41f4f79ef05ef314b9294bd96bdac713f
[]
no_license
Williamfo/TAPP
591271537f239abc2971c9228d21ba6657ea2a7f
c8d3014654e923af493bdee5a5532e7ffa3d45bb
refs/heads/master
2020-05-31T23:38:49.014344
2015-05-29T08:56:12
2015-05-29T08:56:12
32,852,170
0
0
null
null
null
null
UTF-8
Java
false
false
256
java
package org.tapp.dal; import java.util.ArrayList; import org.tapp.bll.Document; public interface DocumentDAOInter { public ArrayList<Document> Listedocs(); public void ajoutdoc(String nom); public Document selectdoc(String nom); }
[ "nicolas.valadier@gmail.com" ]
nicolas.valadier@gmail.com
2137b914fe81282f0160167ea2ec084dbf27e1ab
97bfca9c15c070dd0f1560b26cd7d296f65aa660
/WEBUI/src/main/java/it/prisma/presentationlayer/webui/configs/Environment.java
1a7baf2c79822f8cf6f46690a1a416b577cb2392
[ "Apache-2.0" ]
permissive
pon-prisma/PrismaDemo
f0b9c6d4cff3f1a011d2880263f3831174771dcd
0ea106c07b257628bc4ed5ad45b473c1d99407c7
refs/heads/master
2016-09-06T15:37:22.099913
2015-07-06T15:28:10
2015-07-06T15:28:10
35,619,420
0
1
null
null
null
null
UTF-8
Java
false
false
581
java
package it.prisma.presentationlayer.webui.configs; public enum Environment { // LOCALHOST("localhost"), // REPLY("reply"), // SIELTE("sielte"), // INFN("infn"); // // // private String name; // // private Environment(String name){ // this.name = name; // } // // public String getName(){ // return name; // } // public static Environment lookup(String name) { // for(Environment env: Environment.values()){ // if(env.getName().equalsIgnoreCase(name)); // return env; // } // throw new IllegalArgumentException("Cannot find Environment with name: " + name); // } }
[ "pon.prisma@gmail.com" ]
pon.prisma@gmail.com
9046e75356b82ab8e5ffb278d74e52bb98541243
1338bc08cf55d1818d9525f05f87bae182bcdaa5
/PosManager/src/main/java/com/jc/pico/ext/pg/PayBean.java
b6df0dc73997c378e47110a8f4f5292f4f6b4f11
[]
no_license
JamesAreuming/PosManager
83ebf1615666cdaf8530e3e037522966d66449ef
0dae16f2efccfffeee09da16a2cdd5d0d939766a
refs/heads/master
2023-03-23T12:12:28.227846
2021-03-15T07:37:01
2021-03-15T07:37:01
313,203,570
0
0
null
null
null
null
UTF-8
Java
false
false
2,998
java
/** * <pre> * Filename : PayBean.java * Function : payment bean * Comment : * History : * * Version : 1.0 * Author : * </pre> */ package com.jc.pico.ext.pg; public class PayBean { private String pgKind = null; // PG사 종류(공통코드 356), PayOnline, BAK_pg, etc. private String merchantID = null; // PG 정보, merchant ID private String privateKey = null; // PG 정보, private key private String paymentKey = null; // PG 정보, payment key private String payMethod = null; // 결제수단, CARD private String transactionId = null; // PG사 거래 ID (결제취소용) private String orderId = null; // 주문 ID private double amount = 0; // 금액 private String currency = null; // 통화기호, ISO 3자리 private String cardHolderName = null; // 카드 소유자명 (카드에 명기된 성명) private String cardNumber = null; // 카드번호 private String cardExpDate = null; // 유효기한(MMYY) private String cardCvv = null; // CVC/CVV 3자리 private String country = null; // 고객 거주 나라 (ISO 3116 alphabet 2) public void setPgKind(String pgKind) {this.pgKind = pgKind;} public String getPgKind() {return this.pgKind;} public void setMerchantID(String merchantID) {this.merchantID = merchantID;} public String getMerchantID() {return this.merchantID;} public void setPrivateKey(String privateKey) {this.privateKey = privateKey;} public String getPrivateKey() {return this.privateKey;} public void setPaymentKey(String paymentKey) {this.paymentKey = paymentKey;} public String getPaymentKey() {return this.paymentKey;} public void setPayMethod(String payMethod) {this.payMethod = payMethod;} public String getPayMethod() {return this.payMethod;} public void setTransactionId(String transactionId) {this.transactionId = transactionId;} public String getTransactionId() {return this.transactionId;} public void setOrderId(String orderId) {this.orderId = orderId;} public String getOrderId() {return this.orderId;} public void setAmount(double amount) {this.amount = amount;} public double getAmount() {return this.amount;} public void setCurrency(String currency) {this.currency = currency;} public String getCurrency() {return this.currency;} public void setCardHolderName(String cardHolderName) {this.cardHolderName = cardHolderName;} public String getCardHolderName() {return this.cardHolderName;} public void setCardNumber(String cardNumber) {this.cardNumber = cardNumber;} public String getCardNumber() {return this.cardNumber;} public void setCardExpDate(String cardExpDate) {this.cardExpDate = cardExpDate;} public String getCardExpDate() {return this.cardExpDate;} public void setCardCvv(String cardCvv) {this.cardCvv = cardCvv;} public String getCardCvv() {return this.cardCvv;} public String getCountry() {return country;} public void setCountry(String country) {this.country = country;} }
[ "hothihi5@gmail.com" ]
hothihi5@gmail.com
a4f4da17029f53432d810b4519a08a42ab98aecd
3fbc9015328aeb73dc5fa95c7f749cbcbef8965c
/Comp201Examples/src/Doctor.java
23155d637547777e004007a795d13fb77923da90
[]
no_license
coopes-dev/hotelbooking
a40cf3f73038dd372103421c1bb3018191274a81
2b60c72320bd8ea7a5263bdf5d3f6f445749762f
refs/heads/master
2023-03-17T11:35:01.141869
2021-03-08T12:13:22
2021-03-08T12:13:22
344,808,880
0
0
null
null
null
null
UTF-8
Java
false
false
1,227
java
import java.util.Date; import java.util.Vector; public class Doctor extends PersonMultipleAddress { private Date qualificationDate; Vector<Patient> patientList = new Vector<Patient>(); // patients assigned to the Doctor public Doctor(String surname, String forename1, String forename2, DateOfBirth dateOfBirth) { super(surname, forename1, forename2, dateOfBirth); // chain to super class } public Date getQualificationDate() { return qualificationDate; } public void setQualificationDate(Date qualificationDate) { this.qualificationDate = qualificationDate; } public void addPatientToList(Patient patient) { patientList.add(patient); patient.addDoctor(this); // reflect addition to the other list } public void removePatient(Patient patient) { Vector<Patient> removeList = new Vector<Patient>(); synchronized (patientList) { patientList.forEach((patientInList) -> { if (patient.equals(patientInList)) { removeList.add(patientInList); } }); } patientList.removeAll(removeList); // We now remove this Doctor from the associated Patient.. the other way round patient.removeDoctor(this); } public Vector<Patient> getPatientList() { return patientList; } }
[ "coopes@liv.ac.uk" ]
coopes@liv.ac.uk
94aa631799536b264175332e747a33b97a12be47
4a6c7a44b5df9e995e2a890a64893930d3941d25
/src/Users/Student.java
01fab3d95462459561db0b7e9dfee07b323cf1e3
[]
no_license
Alibek120699/intranetProject
36e105cdb49052bd16bbd404d42a869ce10f26a3
94eb037d77dfa2fad435d4f700e609f207d5044a
refs/heads/master
2020-04-06T16:45:23.897393
2018-11-27T17:45:10
2018-11-27T17:45:10
157,632,857
0
0
null
null
null
null
UTF-8
Java
false
false
10,764
java
package Users; import Course.*; import Enums.AccessRights; import Exceptions.InvalidYearException; import Interfaces.View; import Storage.Storage; import javafx.util.Pair; import java.io.*; import java.util.HashMap; import java.util.Iterator; import java.util.Scanner; import java.util.Vector; public class Student extends User implements Serializable, View { private int yearOfStudy; private double gpa; private HashMap<Course, Vector<Integer>> marks; private HashMap<Course, Teacher> courses; public Student(String id, String name, String surname, AccessRights accessRights, int yearOfStudy) throws InvalidYearException { super(id, name, surname, accessRights); if (yearOfStudy < 0) { throw new InvalidYearException("The year of study field can not be negative!"); } else { this.yearOfStudy = yearOfStudy; marks = new HashMap<Course, Vector<Integer>>(); courses = new HashMap<Course, Teacher>(); } } public void addMark(String idc, int mark) { Course course = Storage.courses.get(idc); marks.get(course).add(mark); } public int getYearOfStudy() { return yearOfStudy; } public void setYearOfStudy(int yearOfStudy) { this.yearOfStudy = yearOfStudy; } public void registerCourse() { Course course; Teacher teacher; int pos = 1; Vector<Course> myCourses = new Vector<Course>(); Iterator it = Storage.courses.entrySet().iterator(); while (it.hasNext()) { HashMap.Entry pair = (HashMap.Entry) it.next(); String id = (String) pair.getKey(); course = Storage.courses.get(id); if (course.getYearOfStudy() == this.getYearOfStudy()) { myCourses.add(course); } } if (myCourses.isEmpty()) { System.out.println("There is no available courses\n"); return; } for (Course c : myCourses) { System.out.println(String.format("[%d] - ID: %s; %s, %d credits", pos++, c.getId(), c.getName(), c.getCredits())); } Scanner scanner = new Scanner(System.in); System.out.println("Please, enter course's number: "); int choice = scanner.nextInt(); while (choice < 1 || choice > myCourses.size()) { System.out.println("Course didn't found, try again"); System.out.println("Please, enter course's number: "); choice = scanner.nextInt(); } System.out.println(); course = myCourses.elementAt(choice - 1); pos = 1; System.out.println("Teachers for chosen course: "); for (Teacher t : course.getTeachers()) { System.out.println(String.format("[%d] - %s %s", pos++, t.getName(), t.getSurname())); } System.out.println("Please, enter number of chosen teacher: "); choice = scanner.nextInt(); while (choice < 1 || choice > course.getTeachers().size()) { System.out.println("Wrong input format, try again"); System.out.println("Please, enter number of chosen teacher: "); choice = scanner.nextInt(); } teacher = course.getTeachers().elementAt(choice - 1); courses.put(course, teacher); marks.put(course, new Vector<>()); teacher.addStudent(course.getId(), id); } public void dropCourse() { Course course; Teacher teacher; int pos = 1; Vector<Course> myCourses = new Vector<Course>(); Iterator it = courses.entrySet().iterator(); while (it.hasNext()) { HashMap.Entry pair = (HashMap.Entry) it.next(); course = (Course) pair.getKey(); myCourses.add(course); } if (myCourses.isEmpty()) { System.out.println("There is no available courses\n"); return; } for (Course c : myCourses) { System.out.println(String.format("[%d] - ID: %s; %s, %d credits", pos++, c.getId(), c.getName(), c.getCredits())); } Scanner scanner = new Scanner(System.in); System.out.println("Please, enter course's number: "); int choice = scanner.nextInt(); while (choice < 1 || choice > myCourses.size()) { System.out.println("Course didn't found, try again"); System.out.println("Please, enter course's number: "); choice = scanner.nextInt(); } System.out.println(); course = myCourses.elementAt(choice - 1); courses.get(course).dropStudent(course.getId(), this.id); courses.remove(course); marks.remove(course); System.out.println(String.format("%s is successfully removed", Storage.courses.get(course.getId()).getName())); System.out.println(); } @Override public void viewMarks() { Course course; int pos = 1; if (marks.isEmpty()) { System.out.println("There is no available courses\n"); return; } Vector<Course> myCourses = new Vector<Course>(); Iterator it = marks.entrySet().iterator(); while (it.hasNext()) { HashMap.Entry pair = (HashMap.Entry) it.next(); course = (Course) pair.getKey(); System.out.println(String.format("[%d] - ID: %s; %s, %d credits", pos++, course.getId(), course.getName(), course.getCredits())); myCourses.add(course); } Scanner scanner = new Scanner(System.in); System.out.println("Please, enter course's number: "); int choice = scanner.nextInt(); while (choice < 1 || choice > myCourses.size()) { System.out.println("Course didn't found, try again"); System.out.println("Please, enter course's number: "); choice = scanner.nextInt(); } course = myCourses.elementAt(choice - 1); if (marks.get(course).isEmpty()) { System.out.println("There is no marks for this course!"); return; } System.out.print(String.format("ID: %s - %s: ", course.getId(), course.getName())); Vector<Integer> m = marks.get(course); for (int i = 0; i < m.size(); i++) { System.out.print(m.elementAt(i) + ", "); } System.out.println("\n"); } @Override public void viewTranscript() { //marks Iterator it = marks.entrySet().iterator(); if (marks.isEmpty()) { System.out.println("There is no available courses\n"); return; } Course course; int pos = 1; Double calc_gpa = 0.0; Double gpaMultiply = 0.0; Integer sumOfCredits = 0; System.out.format("%-10s%-10s%-10s%-10s%-10s%-10s\n", "ID", "Name", "Credits", "Points", "Mark", "GPA"); while (it.hasNext()) { HashMap.Entry pair = (HashMap.Entry) it.next(); String id; String name; int credits; int points = 0; String pointsEqual = "F"; course = (Course) pair.getKey(); id = course.getId(); name = course.getName(); credits = course.getCredits(); pointsEqual = getMark(course).getKey(); calc_gpa = getMark(course).getValue(); gpaMultiply += calc_gpa * credits * 1.0; sumOfCredits += credits; System.out.format("%-10s%-10s%-10d%-10d%-10s%-10f\n", id, name, credits, points, pointsEqual, calc_gpa); } this.gpa = (gpaMultiply) / (sumOfCredits * 1.0); System.out.format("GPA: %.3f", this.gpa); } private Pair<String, Double> getMark(Course course) { Vector<Integer> vector = marks.get(course); int finalPoint = 0; for (int i = 0; i < vector.size(); ++i) { finalPoint += vector.elementAt(i); } String equevivalence = null; Double gpaMark = 0.0; if (finalPoint >= 95) { equevivalence = "A"; gpaMark = 4.00; } else if (finalPoint >= 90) { equevivalence = "A-"; gpaMark = 3.67; } else if (finalPoint >= 85) { equevivalence = "B+"; gpaMark = 3.33; } else if (finalPoint >= 80) { equevivalence = "B"; gpaMark = 3.00; } else if (finalPoint >= 75) { equevivalence = "B-"; gpaMark = 2.67; } else if (finalPoint >= 70) { equevivalence = "C+"; gpaMark = 2.33; } else if (finalPoint >= 65) { equevivalence = "C"; gpaMark = 2.00; } else if (finalPoint >= 60) { equevivalence = "C-"; gpaMark = 1.67; } else if (finalPoint >= 55) { equevivalence = "D"; gpaMark = 1.33; } else { equevivalence = "F"; gpaMark = 0.0; } return new Pair<>(equevivalence, gpaMark); } @Override public void viewFiles() { Scanner scanner = new Scanner(System.in); HashMap<String, Course> mp = Storage.courses; if (mp.isEmpty()) { System.out.println("There is no courses yet\n"); return; } Iterator it = mp.entrySet().iterator(); Course course = null; String id; int pos = 1; int isHere = 1; Vector<CourseFile> idCourses = new Vector<CourseFile>(); while (it.hasNext()) { HashMap.Entry pair = (HashMap.Entry) it.next(); id = (String) pair.getKey(); course = mp.get(id); if (course.getCourseFiles().isEmpty()) continue; System.out.println(String.format("ID: %s; %s", id, course.getName())); Vector<CourseFile> courseFiles = course.getCourseFiles(); for (int i = 0; i < courseFiles.size(); ++i) { System.out.println("[" + isHere++ + "]" + " - " + courseFiles.elementAt(i).getName()); idCourses.add(courseFiles.elementAt(i)); } } if (idCourses.size() == 0) { System.out.println("No files!"); return; } System.out.println("Choose file,which you want to read"); int choice = scanner.nextInt(); while (choice < 0 || choice > idCourses.size() + 1) { System.out.println("Wrong input format"); System.out.println("Try again!"); choice = scanner.nextInt(); } System.out.println("Text:"); System.out.println(idCourses.elementAt(choice - 1).getText()); } }
[ "sayakalibek1@gmail.com" ]
sayakalibek1@gmail.com
b137ce7530d5fd1065cf1f67780352fb92af23ce
5be4918c92749e5ecf898d1adcf5e5a695790375
/src/main/java/com/proofpoint/discovery/DiscoveryModule.java
4996dd26269407b439b6eaebe9db2aec30a34678
[]
no_license
pphnl/discovery-server
5dc637ab8d84469e0a28beba7e53a4d97c420a49
2921d607abf8366ece546be61178a26a7abe1c7e
refs/heads/master
2020-05-27T03:35:22.364645
2011-08-08T17:23:53
2011-08-08T17:23:53
2,174,808
0
0
null
null
null
null
UTF-8
Java
false
false
2,160
java
package com.proofpoint.discovery; import com.google.common.net.InetAddresses; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Provides; import com.google.inject.Scopes; import com.proofpoint.cassandra.CassandraServerInfo; import com.proofpoint.configuration.ConfigurationModule; import com.proofpoint.node.NodeInfo; import me.prettyprint.cassandra.service.CassandraHostConfigurator; import me.prettyprint.cassandra.service.clock.MillisecondsClockResolution; import me.prettyprint.hector.api.Cluster; import me.prettyprint.hector.api.factory.HFactory; import org.joda.time.DateTime; import static java.lang.String.format; public class DiscoveryModule implements Module { public void configure(Binder binder) { binder.bind(DynamicAnnouncementResource.class).in(Scopes.SINGLETON); binder.bind(StaticAnnouncementResource.class).in(Scopes.SINGLETON); binder.bind(ServiceResource.class).in(Scopes.SINGLETON); binder.bind(DynamicStore.class).to(CassandraDynamicStore.class).in(Scopes.SINGLETON); binder.bind(CassandraDynamicStore.class).in(Scopes.SINGLETON); binder.bind(StaticStore.class).to(CassandraStaticStore.class).in(Scopes.SINGLETON); binder.bind(CassandraStaticStore.class).in(Scopes.SINGLETON); binder.bind(DateTime.class).toProvider(RealTimeProvider.class); ConfigurationModule.bindConfig(binder).to(DiscoveryConfig.class); ConfigurationModule.bindConfig(binder).to(CassandraStoreConfig.class); } @Provides public Cluster getCluster(CassandraServerInfo cassandraInfo, NodeInfo nodeInfo) { CassandraHostConfigurator configurator = new CassandraHostConfigurator(format("%s:%s", InetAddresses.toUriString(nodeInfo.getPublicIp()), cassandraInfo.getRpcPort())); configurator.setClockResolution(new MillisecondsClockResolution()); return HFactory.getOrCreateCluster("discovery", configurator); } }
[ "hliu@proofpoint.com" ]
hliu@proofpoint.com
5582efb26e6aa60ce3655b95b2e13ba8bf464643
b9021bbab93e6ce6d540f85f3b0688ab686f5969
/src/main/java/org/benben/modules/business/commen/dto/SmsDTO.java
1bacfd6d4596402325a0ffaef3c86aeeec6897fb
[]
no_license
tanlei945/MyProject
007dce310137e70cce99f3b56fe59b1ad00ea109
fba90c2e1db30027b51ca043a43b617d3f797683
refs/heads/master
2023-08-04T10:37:00.449397
2019-05-24T03:04:40
2019-05-24T03:04:40
200,945,208
0
0
null
2023-07-22T12:53:35
2019-08-07T00:54:21
Java
UTF-8
Java
false
false
980
java
package org.benben.modules.business.commen.dto; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * @author: WangHao * @date: 2019/4/10 11:21 * @description: 短信传输DTO */ @Data public class SmsDTO { @NotNull(message = "手机号不能为空") @NotBlank(message = "手机号不能为空") @ApiModelProperty(value = "手机号",name = "mobile",required = true) private String mobile; @NotNull(message = "事件不能为空") @NotBlank(message = "事件不能为空") @ApiModelProperty(value = "短信事件",name = "event",required = true,example = "1、register2、login3、forget") private String event; @NotNull(message = "验证码不能为空") @NotBlank(message = "验证码不能为空") @ApiModelProperty(value = "短信验证码",name = "captcha") private String captcha; }
[ "wanghao@8b70f4e1-b3c0-4b97-97da-73496876a715" ]
wanghao@8b70f4e1-b3c0-4b97-97da-73496876a715
eb5d6c4e6de3f2ca9382a0ae8375379111096096
b631ba777aa24f3762dfeb6c9282effc9515ae70
/android/BookFinderApp/app/src/main/java/com/example/bookfinderapp/module/camera/AndroidCameraApi.java
6c21bccf6ae3a62c198aae72810871123528a62c
[]
no_license
BlueYamato/Book-Finder
c37c2e360d3666639ec161287c8787d45c0a45a1
b4bf5a740cd2cffce714c71ea49fb7b003f814ad
refs/heads/master
2023-02-28T09:31:32.663574
2021-01-29T02:35:58
2021-01-29T02:35:58
315,873,380
0
0
null
null
null
null
UTF-8
Java
false
false
14,467
java
package com.example.bookfinderapp.module.camera; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.ImageFormat; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CameraMetadata; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.TotalCaptureResult; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.Image; import android.media.ImageReader; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.util.Size; import android.util.SparseIntArray; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import com.example.bookfinderapp.R; import com.example.bookfinderapp.module.book.BookDetailActivity; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class AndroidCameraApi extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "AndroidCameraApi"; private Button takePictureButton; private TextureView textureView; private static final SparseIntArray ORIENTATION = new SparseIntArray(); static { ORIENTATION.append(Surface.ROTATION_0,90); ORIENTATION.append(Surface.ROTATION_90,0); ORIENTATION.append(Surface.ROTATION_180,270); ORIENTATION.append(Surface.ROTATION_270,180); } private String cameraId; protected CameraDevice cameraDevice; protected CameraCaptureSession cameraCaptureSession; protected CaptureRequest captureRequest; protected CaptureRequest.Builder captureRequestBuilder; private Size imageDimension; private ImageReader imageReader; private File file; private static final int REQUEST_CAMERA_PERMISSION = 200; private boolean mFlashSupported; private Handler mBackgroundHandler; private HandlerThread mBackgroundThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_android_camera_api); this.textureView = findViewById(R.id.texture); assert textureView!=null; this.textureView.setSurfaceTextureListener(textureListener); this.takePictureButton = findViewById(R.id.btb_takepicture); assert takePictureButton!=null; takePictureButton.setOnClickListener(this); } TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { openCamera(); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return false; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { } }; private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() { @Override public void onOpened(@NonNull CameraDevice camera) { Log.e(TAG,"onOpened"); cameraDevice = camera; createCameraPreview(); } @Override public void onDisconnected(@NonNull CameraDevice camera) { cameraDevice.close(); } @Override public void onError(@NonNull CameraDevice camera, int error) { cameraDevice.close(); cameraDevice=null; } }; final CameraCaptureSession.CaptureCallback captureCallbackListener = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) { super.onCaptureCompleted(session,request,result); Toast.makeText(AndroidCameraApi.this,"saved: "+file,Toast.LENGTH_LONG); createCameraPreview(); } }; protected void startBackgroundThread(){ mBackgroundThread = new HandlerThread("Camera Background"); mBackgroundThread.start(); mBackgroundHandler = new Handler(mBackgroundThread.getLooper()); } protected void stopBackgroundThread(){ mBackgroundThread.quitSafely(); try{ mBackgroundThread.join(); mBackgroundThread = null; mBackgroundHandler = null; } catch (InterruptedException e){ e.printStackTrace(); } } protected void takePicture() throws CameraAccessException { if(null==cameraDevice){ Log.e(TAG, "camera device is null" ); return; } CameraManager manager = (CameraManager)getSystemService(Context.CAMERA_SERVICE); try{ CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId()); Size[] jpegSizes = null; if(characteristics!=null){ jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG); } int width = 640; int height = 480; if(jpegSizes!=null && 0<jpegSizes.length){ width = jpegSizes[0].getWidth(); height = jpegSizes[0].getHeight(); } ImageReader reader = ImageReader.newInstance(width,height, ImageFormat.JPEG,1); List<Surface> outputSurface = new ArrayList<Surface>(2); outputSurface.add(reader.getSurface()); outputSurface.add(new Surface(textureView.getSurfaceTexture())); final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); captureBuilder.addTarget(reader.getSurface()); captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO); int rotation = getWindowManager().getDefaultDisplay().getRotation(); captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATION.get(rotation)); final File file = new File(Environment.getExternalStorageDirectory()+"/pic.jpg"); ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() { @Override public void onImageAvailable(ImageReader reader) { Image image = null; try{ image = reader.acquireLatestImage(); ByteBuffer buffer = image.getPlanes()[0].getBuffer(); byte[] bytes = new byte[buffer.capacity()]; buffer.get(bytes); save(bytes); } catch (FileNotFoundException e){ e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } finally { startActivity(new Intent(AndroidCameraApi.this, BookDetailActivity.class)); if(image!=null){ image.close(); } } } private void save(byte[] bytes)throws IOException{ OutputStream output = null; try{ output = new FileOutputStream(file); output.write(bytes); }finally { if(null!=output){ output.close(); } } } }; reader.setOnImageAvailableListener(readerListener,mBackgroundHandler); final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) { super.onCaptureCompleted(session, request, result); // Toast.makeText(AndroidCameraApi.this, "saved: "+file, Toast.LENGTH_SHORT).show(); // UploadAsyncTask uploadAT = new UploadAsyncTask(getApplicationContext()); // // uploadAT.execute(data); // createCameraPreview(); } }; cameraDevice.createCaptureSession(outputSurface, new CameraCaptureSession.StateCallback() { @Override public void onConfigured(@NonNull CameraCaptureSession session) { try{ session.capture(captureBuilder.build(),captureListener,mBackgroundHandler); } catch (CameraAccessException e){ e.printStackTrace(); } } @Override public void onConfigureFailed(@NonNull CameraCaptureSession session) { } },mBackgroundHandler); } catch (CameraAccessException e){ e.printStackTrace(); } } protected void createCameraPreview(){ try { SurfaceTexture texture = textureView.getSurfaceTexture(); assert texture!=null; texture.setDefaultBufferSize(imageDimension.getWidth(),imageDimension.getHeight()); Surface surface = new Surface(texture); captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); captureRequestBuilder.addTarget(surface); cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() { @Override public void onConfigured(@NonNull CameraCaptureSession session) { if(null==cameraDevice){ return; } cameraCaptureSession = session; updatePreview(); } @Override public void onConfigureFailed(@NonNull CameraCaptureSession session) { Toast.makeText(AndroidCameraApi.this,"Configuration failed",Toast.LENGTH_LONG); } },null); } catch (CameraAccessException e){ e.printStackTrace(); } } private void openCamera(){ CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); Log.e(TAG, "is camera open"); try{ cameraId = manager.getCameraIdList()[0]; CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); assert map !=null; imageDimension = map.getOutputSizes(SurfaceTexture.class)[0]; if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(AndroidCameraApi.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_CAMERA_PERMISSION); return; } manager.openCamera(cameraId,stateCallback,null); } catch (CameraAccessException e){ e.printStackTrace(); } Log.e(TAG, "openCamera X " ); } protected void updatePreview(){ if(null==cameraDevice){ Log.e(TAG, "updatePreview error, return" ); } captureRequestBuilder.set(CaptureRequest.CONTROL_MODE,CameraMetadata.CONTROL_MODE_AUTO); try{ cameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(),null,mBackgroundHandler); } catch (CameraAccessException e){ e.printStackTrace(); } } private void closeCamera(){ if(null==cameraDevice){ cameraDevice.close(); cameraDevice=null; } if(null!=imageReader){ imageReader.close(); imageReader=null; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){ if(requestCode==REQUEST_CAMERA_PERMISSION){ if(grantResults[0]==PackageManager.PERMISSION_DENIED){ Toast.makeText(AndroidCameraApi.this,"Sorry, you can't use this app without granting permission",Toast.LENGTH_LONG).show(); finish(); } } } @Override protected void onResume(){ super.onResume(); Log.e(TAG, "onResume" ); startBackgroundThread(); if(textureView.isAvailable()){ openCamera(); } else { textureView.setSurfaceTextureListener(textureListener); } } @Override protected void onPause(){ Log.e(TAG, "onPause" ); stopBackgroundThread(); super.onPause(); } @Override public void onClick(View v) { if(v.getId() == takePictureButton.getId()){ try { takePicture(); } catch (CameraAccessException e) { e.printStackTrace(); } } } }
[ "fraxinusratatoshkr@gmail.com" ]
fraxinusratatoshkr@gmail.com
dbac28f6ef646daddf267ad38e9abe18099eb970
a5f4b3a5b0f3606a6cbb8795b96603fafc3d156e
/Sample123/src/main/java/stepdefinitions/sampleStepDefinitions.java
693d297b22f44c340228c64747456811cbdc9552
[]
no_license
ManikantaSunkari/Practice
4c3bea9a18c133103de512d32e865b5aa4c95f21
71931a0c3d5f784d3d2b45efcc4f95c90df57edc
refs/heads/master
2021-07-05T23:21:56.378314
2019-06-15T10:53:53
2019-06-15T10:53:53
191,294,349
0
0
null
2019-06-11T05:17:37
2019-06-11T04:34:17
null
UTF-8
Java
false
false
2,012
java
package stepdefinitions; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import stepactions.sampleStepActions; public class sampleStepDefinitions { sampleStepActions action; public sampleStepDefinitions() { action = new sampleStepActions(); } @Given("^User opens browser$") public void user_opens_browser() throws Throwable { // Write code here that turns the phrase above into concrete actions action.OpenBrowser(); } @Given("^User login with credentials$") public void user_login_with_credentials() throws Throwable { // Write code here that turns the phrase above into concrete actions action.Login(); } @When("^User click on logout button$") public void user_click_on_logout_button() throws Throwable { // Write code here that turns the phrase above into concrete actions } @Then("^User logout from the web site$") public void user_logout_from_the_web_site() throws Throwable { // Write code here that turns the phrase above into concrete actions } @When("^User clicks on Trouble logging in link$") public void user_clicks_on_Trouble_logging_in_link() throws Throwable { // Write code here that turns the phrase above into concrete actions //action.TroubleLogin(); } @Then("^User naviagtes to Forgot User ID / IPIN page$") public void user_naviagtes_to_Forgot_User_ID_IPIN_page() throws Throwable { // Write code here that turns the phrase above into concrete actions } @When("^User clicks on Retrieve ID link$") public void user_clicks_on_Retrieve_ID_link() throws Throwable { // Write code here that turns the phrase above into concrete actions // action.RetrieveID(); } @Then("^User navigates to Forgot your User ID page$") public void user_navigates_to_Forgot_your_User_ID_page() throws Throwable { // Write code here that turns the phrase above into concrete actions } }
[ "MANIKANTA SUNKARI@LAPTOP-S767KDL8" ]
MANIKANTA SUNKARI@LAPTOP-S767KDL8
0c87a75c8166e344a29d026a5a47e67e7229c66b
1e80f67884deb0925671232a715a5c8945a66c1b
/src/main/Java/com/common/vo/TreeNode.java
298d42b8ee6d3683dadd72a66819ba8bdc3a2bf9
[]
no_license
lifei636/medicaltriagesystem
b23968ba13bbaaeb4d5f3235564e972b24d6283f
2423ca2a3d2bd705b02253e8ca755d0228108224
refs/heads/master
2022-07-12T17:54:04.425718
2019-06-19T08:39:30
2019-06-19T08:39:30
189,930,284
0
1
null
2022-06-29T17:25:02
2019-06-03T03:43:23
JavaScript
UTF-8
Java
false
false
5,061
java
package com.common.vo; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * 节点数据封装 */ public class TreeNode { /** * 节点id */ private String id; /** * 父节点id */ private String parentId; /** * 序号 */ private String num; /** * 节点名称 */ private String name; /** * 是否上级节点 */ private boolean isParent; /** * 是否有上级节点 */ private boolean hasParent; /** * 是否选中 */ private boolean checked; /** * 是否选中 */ private boolean nocheck; /** * 节点图标 */ private String icon; /** * 子节点数据 */ private List<TreeNode> children; /** * 父节点数据 */ private List<TreeNode> parent; private List<TreeNode> linkedList = new ArrayList<TreeNode>(); private List<TreeNode> linkedListP = new ArrayList<TreeNode>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isParent() { return isParent; } public void setIsParent(boolean isParent) { this.isParent = isParent; } public boolean hasParent() { return hasParent; } public void setHasParent(boolean hasParent) { this.hasParent = hasParent; } public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } public boolean isNocheck() { return nocheck; } public void setNocheck(boolean nocheck) { this.nocheck = nocheck; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public List<TreeNode> getChildren() { return children; } public void setChildren(List<TreeNode> children) { this.children = children; } public List<TreeNode> getParent() { return parent; } public void setParent(List<TreeNode> parent) { this.parent = parent; } public void buildNodes(List<TreeNode> nodeList) { for (TreeNode treeNode : nodeList) { List<TreeNode> linkedList = treeNode.findChildNodes(nodeList, treeNode.getId()); List<TreeNode> linkedListp = treeNode.findParentNodes(nodeList, treeNode.getParentId()); if (linkedList.size() > 0) { treeNode.setIsParent(true); treeNode.setChildren(linkedList); } if (linkedListp.size() > 0) { treeNode.setHasParent(true); treeNode.setParent(linkedListp); } } } public List<TreeNode> findChildNodes(List<TreeNode> list, Object parentId) { if (list == null && parentId == null) return null; for (Iterator<TreeNode> iterator = list.iterator(); iterator.hasNext();) { TreeNode node = iterator.next(); // 根据传入的某个父节点ID,遍历该父节点的所有子节点 if (node.getParentId() != "0" && parentId.toString().equals(node.getParentId())) { recursionFn(list, node); } } return linkedList; } public List<TreeNode> findParentNodes(List<TreeNode> list, Object childId) { if (list == null && childId == null) return null; for (Iterator<TreeNode> iterator = list.iterator(); iterator.hasNext();) { TreeNode node = iterator.next(); if (childId.toString().equals(node.getId())) { recursionFnP(list, node); } } return linkedListP; } private void recursionFn(List<TreeNode> list, TreeNode node) { List<TreeNode> childList = getChildList(list, node);// 得到子节点列表 if (childList.size() > 0) {// 判断是否有子节点 linkedList.add(node); Iterator<TreeNode> it = childList.iterator(); while (it.hasNext()) { TreeNode n = it.next(); recursionFn(list, n); } } else { linkedList.add(node); } } private void recursionFnP(List<TreeNode> list, TreeNode node) { List<TreeNode> parentList = getParentList(list, node);// 得到父节点列表 if (parentList.size() > 0) {// 判断是否有父节点 linkedListP.add(node); Iterator<TreeNode> it = parentList.iterator(); while (it.hasNext()) { TreeNode n = it.next(); recursionFnP(list, n); } } else { linkedListP.add(node); } } // 得到子节点列表 private List<TreeNode> getChildList(List<TreeNode> list, TreeNode node) { List<TreeNode> nodeList = new ArrayList<TreeNode>(); Iterator<TreeNode> it = list.iterator(); while (it.hasNext()) { TreeNode n = it.next(); if (n.getParentId().equals(node.getId())) { nodeList.add(n); } } return nodeList; } // 得到子节点列表 private List<TreeNode> getParentList(List<TreeNode> list, TreeNode node) { List<TreeNode> nodeList = new ArrayList<TreeNode>(); Iterator<TreeNode> it = list.iterator(); while (it.hasNext()) { TreeNode n = it.next(); if (n.getId().equals(node.getParentId())) { nodeList.add(n); } } return nodeList; } }
[ "396314029@qq.com" ]
396314029@qq.com
609e912007ad53ee5767dd397db1018645180cdd
ce958df9b2e7cbbe23ade6d3c70372e73ce6016b
/Animales/src/Modelo/Perro.java
98152e5fe204f9591a4542885070463a0a1bb539
[]
no_license
andreapabon/POO2021-1
6c428ce31660016f446895d594532860a3124e7f
1ac2d208e24176be34092e9440aa0fbeb9330a7e
refs/heads/main
2023-04-04T10:55:38.729325
2021-04-22T13:10:19
2021-04-22T13:10:19
357,384,321
0
0
null
null
null
null
UTF-8
Java
false
false
850
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 Modelo; /** * * @author AndreaPabon */ public class Perro extends Canino implements iMascota{ public Perro(String foto, int nivelHambre, String comida, String nombre) { super(foto, nivelHambre, comida, nombre); } @Override public void comer(){ System.out.println("Comiendo como un perro"); } @Override public void hacerRuido(){ System.out.println("Haciendo ruido como un perro, guau guau"); } @Override public void serAmistoso() { System.out.println("Soy amistoso"); } @Override public void jugar() { System.out.println("Estoy jugando"); } }
[ "andreapabon@unicauca.edu.co" ]
andreapabon@unicauca.edu.co
8174dfd3ee8b808a4334a1fc0144ef8d6af71cde
75fa11b13ddab8fd987428376f5d9c42dff0ba44
/metadata-service/factories/src/main/java/com/linkedin/metadata/boot/kafka/DataHubUpgradeKafkaListener.java
11d12072e12b79d9976bea8d442cea39e3b4bbaf
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause", "MIT" ]
permissive
RyanHolstien/datahub
163d0ff6b4636919ed223ee63a27cba6db2d0156
8cf299aeb43fa95afb22fefbc7728117c727f0b3
refs/heads/master
2023-09-04T10:59:12.931758
2023-08-21T18:33:10
2023-08-21T18:33:10
246,685,891
0
0
Apache-2.0
2021-02-16T23:48:05
2020-03-11T21:43:58
TypeScript
UTF-8
Java
false
false
6,937
java
package com.linkedin.metadata.boot.kafka; import com.linkedin.gms.factory.config.ConfigurationProvider; import com.linkedin.metadata.EventUtils; import com.linkedin.metadata.boot.dependencies.BootstrapDependency; import com.linkedin.metadata.utils.metrics.MetricUtils; import com.linkedin.metadata.version.GitVersion; import com.linkedin.mxe.DataHubUpgradeHistoryEvent; import com.linkedin.mxe.Topics; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.apache.avro.generic.GenericRecord; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.common.TopicPartition; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.config.KafkaListenerEndpointRegistry; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.listener.ConsumerSeekAware; import org.springframework.kafka.listener.MessageListenerContainer; import org.springframework.stereotype.Component; // We don't disable this on GMS since we want GMS to also wait until the system is ready to read in case of // backwards incompatible query logic dependent on system updates. @Component("dataHubUpgradeKafkaListener") @Slf4j @EnableKafka public class DataHubUpgradeKafkaListener implements ConsumerSeekAware, BootstrapDependency { private final KafkaListenerEndpointRegistry registry; private static final String CONSUMER_GROUP = "${DATAHUB_UPGRADE_HISTORY_KAFKA_CONSUMER_GROUP_ID:generic-duhe-consumer-job-client}"; private static final String SUFFIX = "temp"; public static final String TOPIC_NAME = "${DATAHUB_UPGRADE_HISTORY_TOPIC_NAME:" + Topics.DATAHUB_UPGRADE_HISTORY_TOPIC_NAME + "}"; private final DefaultKafkaConsumerFactory<String, GenericRecord> _defaultKafkaConsumerFactory; @Value("#{systemEnvironment['DATAHUB_REVISION'] ?: '0'}") private String revision; private final GitVersion _gitVersion; private final ConfigurationProvider _configurationProvider; @Value(CONSUMER_GROUP) private String consumerGroup; @Value(TOPIC_NAME) private String topicName; private final static AtomicBoolean IS_UPDATED = new AtomicBoolean(false); public DataHubUpgradeKafkaListener(KafkaListenerEndpointRegistry registry, @Qualifier("duheKafkaConsumerFactory") DefaultKafkaConsumerFactory<String, GenericRecord> defaultKafkaConsumerFactory, GitVersion gitVersion, ConfigurationProvider configurationProvider) { this.registry = registry; this._defaultKafkaConsumerFactory = defaultKafkaConsumerFactory; this._gitVersion = gitVersion; this._configurationProvider = configurationProvider; } // Constructs a consumer to read determine final offset to assign, prevents re-reading whole topic to get the latest version @Override public void onPartitionsAssigned(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) { try (Consumer<String, GenericRecord> kafkaConsumer = _defaultKafkaConsumerFactory.createConsumer(consumerGroup, SUFFIX)) { final Map<TopicPartition, Long> offsetMap = kafkaConsumer.endOffsets(assignments.keySet()); assignments.entrySet().stream() .filter(entry -> topicName.equals(entry.getKey().topic())) .forEach(entry -> { log.info("Partition: {} Current Offset: {}", entry.getKey(), offsetMap.get(entry.getKey())); long newOffset = offsetMap.get(entry.getKey()) - 1; callback.seek(entry.getKey().topic(), entry.getKey().partition(), Math.max(0, newOffset)); }); } } @KafkaListener(id = CONSUMER_GROUP, topics = {TOPIC_NAME}, containerFactory = "duheKafkaEventConsumer", concurrency = "1") public void checkSystemVersion(final ConsumerRecord<String, GenericRecord> consumerRecord) { final GenericRecord record = consumerRecord.value(); final String expectedVersion = String.format("%s-%s", _gitVersion.getVersion(), revision); DataHubUpgradeHistoryEvent event; try { event = EventUtils.avroToPegasusDUHE(record); log.info("Latest system update version: {}", event.getVersion()); if (expectedVersion.equals(event.getVersion())) { IS_UPDATED.getAndSet(true); } else if (!_configurationProvider.getSystemUpdate().isWaitForSystemUpdate()) { log.warn("Wait for system update is disabled. Proceeding with startup."); IS_UPDATED.getAndSet(true); } else { log.warn("System version is not up to date: {}. Waiting for datahub-upgrade to complete...", expectedVersion); } } catch (Exception e) { MetricUtils.counter(this.getClass(), "avro_to_pegasus_conversion_failure").inc(); log.error("Error deserializing message due to: ", e); log.error("Message: {}", record.toString()); return; } } public void waitForUpdate() { if (!_configurationProvider.getSystemUpdate().isWaitForSystemUpdate()) { log.warn("Wait for system update is disabled. Proceeding with startup."); IS_UPDATED.getAndSet(true); } int maxBackOffs = Integer.parseInt(_configurationProvider.getSystemUpdate().getMaxBackOffs()); long initialBackOffMs = Long.parseLong(_configurationProvider.getSystemUpdate().getInitialBackOffMs()); int backOffFactor = Integer.parseInt(_configurationProvider.getSystemUpdate().getBackOffFactor()); long backOffMs = initialBackOffMs; for (int i = 0; i < maxBackOffs; i++) { if (IS_UPDATED.get()) { log.debug("Finished waiting for updated indices."); try { log.info("Containers: {}", registry.getListenerContainers().stream() .map(MessageListenerContainer::getListenerId) .collect(Collectors.toList())); registry.getListenerContainer(consumerGroup).stop(); } catch (NullPointerException e) { log.error("Expected consumer `{}` to shutdown.", consumerGroup); } return; } try { Thread.sleep(backOffMs); } catch (InterruptedException e) { log.error("Thread interrupted while sleeping for exponential backoff: {}", e.getMessage()); throw new RuntimeException(e); } backOffMs = backOffMs * backOffFactor; } if (!IS_UPDATED.get()) { throw new IllegalStateException("Indices are not updated after exponential backoff." + " Please try restarting and consider increasing back off settings."); } } @Override public boolean waitForBootstrap() { this.waitForUpdate(); return true; } }
[ "noreply@github.com" ]
noreply@github.com
9f89794c3c69da356f769ab1d194caacfbcb4025
c538dcbb9a04aa638d9ea0db1e851ab919580cb9
/com-sys-model/src/main/java/com/sys/model/basecode/Barbecue.java
b2234d972042ae3ad3a2ad8b483cf8b3367b4e6c
[]
no_license
qiufeng001/com-sys
e86548b92881182f992156e4efc8d726735489b5
30841ba4a56f0fba4a9a32016f98d9c72b4249a1
refs/heads/master
2022-12-25T18:02:34.092157
2020-11-27T09:57:34
2020-11-27T09:57:34
227,324,685
0
1
null
2022-12-15T23:25:29
2019-12-11T09:20:41
Java
UTF-8
Java
false
false
1,550
java
package com.sys.model.basecode; import com.baomidou.mybatisplus.annotation.TableName; import com.sys.core.base.Entity; /** * <p> * 烧烤 * </p> * * @author zhong.h * @since 2020-11-19 */ public class Barbecue extends Entity { private static final long serialVersionUID=1L; /** * 名称 */ private String name; /** * 烤制方式方法 */ private String method; /** * 配料 */ private String ingredients; /** * 说明 */ private String remark; /** * 标签 */ private String tag; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getIngredients() { return ingredients; } public void setIngredients(String ingredients) { this.ingredients = ingredients; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } @Override public String toString() { return "Barbecue{" + "name=" + name + ", method=" + method + ", ingredients=" + ingredients + ", remark=" + remark + ", tag=" + tag + "}"; } }
[ "oncwnuCW0oYGIFY0bySSfNeJYSk4@git.weixin.qq.com" ]
oncwnuCW0oYGIFY0bySSfNeJYSk4@git.weixin.qq.com
abbdb133645e5380ba1f42cd9dc32cbc6807cd01
d96bef4c2cadc6caab4aeedcca3e083468f39c5c
/sasi/src/Arrays/Multiplactionmatrix.java
0ead48736dc4771f51e387798cf8b7de7f0defb2
[]
no_license
TechieFrogs-Achievers/JavaBasics
a06d46a9b912c587982a52975d61c84722b5b1b1
9a5c5653610449dc7265406fb4343079089328e9
refs/heads/main
2023-03-20T20:42:30.820354
2021-03-12T06:17:19
2021-03-12T06:17:19
313,300,339
4
0
null
null
null
null
UTF-8
Java
false
false
2,008
java
package Arrays; import java.util.Scanner; public class Multiplactionmatrix { public static void main(String[] args) { System.out.println("Enter the elements:"); Scanner sc = new Scanner(System.in); //scanner class object int row = sc.nextInt(); //initializing the row int column = sc.nextInt(); //initializing the column //matrix array that stores the elements int matrix1[][] = new int[row][column]; int matrix2[][] = new int[row][column]; System.out.println("Enter the first matrix:"); //loop that checks the matrix1 elements for(int i=0;i<matrix1.length;i++) { for(int j=0;j<matrix1.length;j++) { matrix1[i][j] = sc.nextInt(); //reads the matrix1 elements } } System.out.println("Enter the second matrix:"); //loop that checks the matrix2 elements for(int i=0;i<matrix2.length;i++) { for(int j=0;j<matrix2.length;j++) { matrix2[i][j]=sc.nextInt(); //reads the matrix2 elements } } int matrix3[][] = new int[row][column]; System.out.println("Multiplication of two matrices:"); for(int i=0;i<matrix3.length;i++) { for(int j=0;j<matrix3.length;j++) { matrix3[i][j] =0; for(int k=0;k<matrix3.length;k++) { matrix3[i][j]=matrix1[i][k]*matrix2[k][j]; //performs the multiplication3 of matrix1 and matrix2 } System.out.print(matrix3[i][j]+" "); //prints the result } System.out.println(); } sc.close(); //scanner close } }
[ "sasibhanukrovvidi@gmail.com" ]
sasibhanukrovvidi@gmail.com
d227a80a2bd0828163ddcfac3c6d19000adee2ce
20e327caafd32deb5f0b8fbcce30db96cbfea1a3
/src/database/DBConnectionFactory.java
f03102bde708cdb2af04f6e9bab5b00c9ebd4423
[]
no_license
jpyan/EventRec
3c1431040abf27f28e25e52a8ca42079d3c2e085
03acb450048f854924b3c16ddaecc2f2fbc7c0d7
refs/heads/master
2020-07-23T02:59:05.985269
2019-09-15T20:37:04
2019-09-15T20:37:04
207,426,708
0
0
null
null
null
null
UTF-8
Java
false
false
554
java
package database; import database.mysql.MySQLConnection; public class DBConnectionFactory { // This should change based on the pipeline. private static final String DEFAULT_DB = "mysql"; public static DBConnection getConnection(String db) { switch (db) { case "mysql": return new MySQLConnection(); case "mongodb": // return new MongoDBConnection(); return null; default: throw new IllegalArgumentException("Invalid db:" + db); } } public static DBConnection getConnection() { return getConnection(DEFAULT_DB); } }
[ "jpyan@umich.edu" ]
jpyan@umich.edu
694518799b0024f4f642f2921073a850bf09ff31
6df4c8cb1c5503b047996036d9424d893d892a0e
/src/main/java/org/chsi/model/Category.java
87802968bd378fe285279c5641e59e34d8c23ec4
[]
no_license
chsi13/springbootdemo
fc766f0180d9573fcf66916fa002fabbc0a0f827
6aa4a2c323af5d203d3ff74e733ceb0c37b12c37
refs/heads/master
2021-05-08T14:49:50.658461
2018-02-06T04:44:58
2018-02-06T04:44:58
120,095,605
0
0
null
null
null
null
UTF-8
Java
false
false
162
java
package org.chsi.model; /** * Created by chsi on 20/01/2018. */ public enum Category { JVM, System, Database, Devops, Java, Agile; }
[ "christopher.siciliano@smals.be" ]
christopher.siciliano@smals.be
57f59da280325070f49853103482a419559f146e
1f36cb5dcdae379cd95fb549ee6862aeeb32115f
/payment/src/main/java/movie/PaymentController.java
299354ec56b8242c41a576317167ae22697c9da5
[ "MIT" ]
permissive
jaeheeshim/movie-booking
4e54258b7a89ca8f139d8867749c72aafda71c9e
532d06d102f945161cd340b150f4117efcf70e73
refs/heads/master
2023-03-08T07:46:34.442438
2021-02-24T08:53:39
2021-02-24T08:53:39
339,084,217
0
3
null
null
null
null
UTF-8
Java
false
false
501
java
package movie; import org.springframework.beans.factory.annotation.Autowired; 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.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; @RestController public class PaymentController { }
[ "jaehee.shim@sk.com" ]
jaehee.shim@sk.com
8119a0061d2359e11fca55928a53aa51898d2933
c94ca7b42d7da151ee74b1f5f8790e79fa769e9b
/src/psm7/Thermometer.java
58470eec7365c848662098e04102482410e2c624
[]
no_license
WhiteShootingStar/PSM
60077b70b43f76a11a1b717bf87661c859478c4b
996735a3806ad39cc293d57d5d719ef75e2a8baa
refs/heads/master
2020-04-27T13:41:50.549312
2019-05-11T22:13:15
2019-05-11T22:13:15
174,379,914
0
1
null
null
null
null
UTF-8
Java
false
false
4,178
java
package psm7; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.function.IntFunction; public class Thermometer { public PartOfThePlate[][] plates; public Thermometer() { Scanner scan = new Scanner(System.in); System.out.println("Please enter width of the plate"); double width = scan.nextDouble(); System.out.println("Please enter heigth of the plate"); double heigth = scan.nextDouble(); System.out.println( "Please enter 4 temperatures, they would be assigned in clockwise direction to the sides of the plate"); String line = scan.next(); String[] temp = line.split(","); int[] temperatures = new int[temp.length]; for (int i = 0; i < temp.length; i++) { temperatures[i] = Integer.parseInt(temp[i]); } scan.nextLine(); System.out.println("Please enter on how much you would like to divide width"); int dX = scan.nextInt(); System.out.println("Please enter on how much you would like to divide heigth"); int dY = scan.nextInt(); plates = new PartOfThePlate[dY + 1][dX + 1]; for (int i = 0; i < plates.length; i++) { for (int k = 0; k < plates[i].length; k++) { if ((i == 0 && k == 0) || (i == 0 && k == plates[i].length - 1) || (i == plates.length - 1 && k == 0) || (i == plates.length - 1 && k == plates[i].length - 1)) { plates[i][k] = new PartOfThePlate(false); } else if (i == 0) { plates[i][k] = new PartOfThePlate(temperatures[0], true, false, i, k); } else if (k == 0) { plates[i][k] = new PartOfThePlate(temperatures[3], true, false, i, k); } else if (i == plates.length - 1) { plates[i][k] = new PartOfThePlate(temperatures[2], true, false, i, k); } else if (k == plates[i].length - 1) { plates[i][k] = new PartOfThePlate(temperatures[1], true, false, i, k); } else plates[i][k] = new PartOfThePlate(0, true, true, i, k); } } System.out.println((dY + 1) + " " + (dX + 1)); } Matrices createMatrix() { int unKnownAmount = 0; for (int i = 0; i < plates.length; i++) { for (int k = 0; k < plates[i].length; k++) { if (plates[i][k].isNeeded == true && plates[i][k].needToCalculate == true) { unKnownAmount++; } } } double[][] matrix = new double[unKnownAmount][unKnownAmount]; double[] answerMatrix = new double[unKnownAmount]; List<PartOfThePlate> list = getList(); int temp = 0; for (PartOfThePlate partOfThePlate : list) { // Arrays.toString(getNeigbours(partOfThePlate.height, partOfThePlate.width, // unKnownAmount,aaa)); matrix[temp] = getNeigbours(partOfThePlate.height, partOfThePlate.width, unKnownAmount, list); answerMatrix[temp] = caclulatesum(partOfThePlate.height, partOfThePlate.width); temp++; } Matrices finalMatrix = new Matrices(matrix, answerMatrix); System.out.println(unKnownAmount); return finalMatrix; } int caclulatesum(int ind1, int ind2) { int sum = 0; for (int i = ind1 - 1; i <=ind1 + 1; i++) { for (int k = ind2 - 1; k <= ind2 + 1; k++) { if (plates[i][k].isNeeded == true && plates[i][k].needToCalculate == false && (Math.abs(ind1 - i) == 1 && ind2 == k) || (Math.abs(ind2 - k) == 1 && ind1 == i)) { sum += plates[i][k].temperature; } } } return -sum; } double[] getNeigbours(int ind1, int ind2, int matrixSize, List<PartOfThePlate> list) { double[] matrix = new double[matrixSize]; int a = 0; for (PartOfThePlate partOfThePlate : list) { matrix[a] = isNeigbour(ind1, ind2, partOfThePlate.height, partOfThePlate.width); a++; } return matrix; } int isNeigbour(int ind1, int ind2, int i1, int i2) { if (ind1 == i1 && ind2 == i2) { return -4; } else if ((Math.abs(ind1 - i1) == 1 && ind2 == i2) || (Math.abs(ind2 - i2) == 1 && ind1 == i1)) { return 1; } else { return 0; } } List<PartOfThePlate> getList() { List<PartOfThePlate> list = new ArrayList<>(); for (int i = 0; i < plates.length; i++) { for (int k = 0; k < plates[i].length; k++) { if (plates[i][k].isNeeded == true && plates[i][k].needToCalculate == true) { list.add(plates[i][k]); } } } return list; } }
[ "palart2000@gmail.com" ]
palart2000@gmail.com
ce57ab0d6371e8f2c324bc32a94bc3185666ba46
cdb72cf07a1e44a93f89fdcb6d1699be32f2ae2a
/JAVA/LojadeInformatica/src/main/java/br/edu/etec/TelaDeCadastro.java
238fee5b862901e014982fe3649013bb00732d46
[]
no_license
matheuspmedeiros/JAVA
b08e2f07e96c8211c65dd16f4d25ddffd1c25f9b
fe84ed618789800a00f15d40599f255c6a037536
refs/heads/master
2020-03-18T04:50:20.976482
2018-05-21T19:56:13
2018-05-21T19:56:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,177
java
package br.edu.etec; import java.awt.BorderLayout; import java.awt.GridLayout; import java.sql.SQLException; import javax.swing.JButton; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JTextField; public abstract class TelaDeCadastro extends JPanel{ JPanel painelDeBotoes = new JPanel(); JPanel painelParaCampos = new JPanel(); JPanel painelListagem = new JPanel(); JButton btnSalvar = new JButton("Salvar"); JButton btnLimpar = new JButton("Limpar"); JButton btnCancelar = new JButton("Cancelar"); JButton btnListar = new JButton("Listar"); JButton btnAlterar = new JButton("Alterar"); JTextField txtId = new JTextField("Digite Id Para Alterar"); JList<String> list; public TelaDeCadastro(int nLinhas,int nColunas) { //https://docs.oracle.com/javase/tutorial/uiswing/layout/layoutlist.html //https://docs.oracle.com/javase/tutorial/uiswing/layout/border.html BorderLayout borderLayout = new BorderLayout(); this.setLayout(borderLayout); //PAINEL PARA CAMPOS DO FORMULARIO //https://docs.oracle.com/javase/tutorial/uiswing/layout/grid.html GridLayout layoutParaCampos = new GridLayout(nLinhas,nColunas); painelParaCampos.setLayout(layoutParaCampos); this.add(painelParaCampos, BorderLayout.CENTER); //PAINEL DE BOTOES this.painelDeBotoes = new JPanel(); this.btnSalvar = new JButton("Salvar"); this.btnLimpar = new JButton("Limpar"); this.btnCancelar = new JButton("Cancelar"); this.painelDeBotoes.add(btnSalvar); this.painelDeBotoes.add(btnLimpar); this.painelDeBotoes.add(btnCancelar); this.painelDeBotoes.add(btnListar); this.painelDeBotoes.add(btnAlterar); this.painelDeBotoes.add(txtId); this.add(painelDeBotoes,BorderLayout.SOUTH); //PAINEL PARA LISTAGEM list = new JList<String>(); this.painelListagem.add(list); this.add(painelListagem, BorderLayout.EAST); } abstract void limparFormulario() throws SQLException; abstract void salvar() throws SQLException; abstract void cancelar() throws SQLException; abstract void alterar() throws SQLException; abstract void excluir() throws SQLException; abstract void listar() throws SQLException; }
[ "mpmedeiros17@gmail.com" ]
mpmedeiros17@gmail.com
50447343fe6eeec0c6f778590e7c14484ed7c287
ceab19a7632794a11896cdef7037725550b5269f
/src/Eclipse-IDE/org.robotframework.ide.eclipse.main.plugin.tests/src/org/robotframework/ide/eclipse/main/plugin/tableeditor/source/colouring/TokenTypeBasedRuleTest.java
44180dbf759a529305daf5d78116ee8842827145
[ "Apache-2.0" ]
permissive
aihuasxy/RED
79729b0b8c9b8b3c837b7fc6eaff3010aaa25ebf
aab80218fa42656310ca1ee97b87c039ae988a0a
refs/heads/master
2021-01-13T04:25:20.808371
2017-01-10T13:28:14
2017-01-10T13:28:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,314
java
package org.robotframework.ide.eclipse.main.plugin.tableeditor.source.colouring; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.robotframework.red.junit.Conditions.absent; import static org.robotframework.red.junit.Conditions.present; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.rules.Token; import org.junit.Test; import org.rf.ide.core.testdata.text.read.IRobotLineElement; import org.rf.ide.core.testdata.text.read.IRobotTokenType; import org.rf.ide.core.testdata.text.read.VersionAvailabilityInfo; import org.rf.ide.core.testdata.text.read.VersionAvailabilityInfo.VersionAvailabilityInfoBuilder; import org.rf.ide.core.testdata.text.read.recognizer.RobotToken; import org.rf.ide.core.testdata.text.read.separators.Separator; import org.robotframework.ide.eclipse.main.plugin.tableeditor.source.colouring.ISyntaxColouringRule.PositionedTextToken; import com.google.common.base.Optional; public class TokenTypeBasedRuleTest { private final IRobotTokenType recognizedType1 = new RecognizedTokenTypeMock1(); private final IRobotTokenType recognizedType2 = new RecognizedTokenTypeMock2(); private final IRobotTokenType unrecognizedType = new UnrecognizedTokenTypeMock(); private final TokenTypeBasedRule testedRule = new TokenTypeBasedRule(new Token("token"), newArrayList(recognizedType1, recognizedType2)); @Test public void ruleIsApplicableOnlyForRobotTokens() { assertThat(testedRule.isApplicable(new RobotToken())).isTrue(); assertThat(testedRule.isApplicable(new Separator())).isFalse(); assertThat(testedRule.isApplicable(mock(IRobotLineElement.class))).isFalse(); } @Test public void tokenIsRecognized_whenItHasExpectedTypeAtFirstPosition_1() { final RobotToken token = RobotToken.create("text", newArrayList(recognizedType1, recognizedType2)); token.setStartOffset(42); final Optional<PositionedTextToken> evaluatedToken = testedRule.evaluate(token, 0, new ArrayList<IRobotLineElement>()); assertThat(evaluatedToken).is(present()); assertThat(evaluatedToken.get().getToken().getData()).isEqualTo("token"); assertThat(evaluatedToken.get().getPosition()) .isEqualTo(new Position(token.getStartOffset(), token.getText().length())); } @Test public void tokenIsRecognized_whenItHasExpectedTypeAtFirstPosition_2() { final RobotToken token = RobotToken.create("text", newArrayList(recognizedType2, recognizedType1)); token.setStartOffset(42); final Optional<PositionedTextToken> evaluatedToken = testedRule.evaluate(token, 0, new ArrayList<IRobotLineElement>()); assertThat(evaluatedToken).is(present()); assertThat(evaluatedToken.get().getToken().getData()).isEqualTo("token"); assertThat(evaluatedToken.get().getPosition()) .isEqualTo(new Position(token.getStartOffset(), token.getText().length())); } @Test public void tokenIsRecognized_whenItHasExpectedTypeAtFirstPositionRegardlesGivenOffsetInside() { final RobotToken token = RobotToken.create("text", newArrayList(recognizedType2, recognizedType1)); token.setStartOffset(42); final int offsetInside = new Random().nextInt(token.getText().length()); final Optional<PositionedTextToken> evaluatedToken = testedRule.evaluate(token, offsetInside, new ArrayList<IRobotLineElement>()); assertThat(evaluatedToken).is(present()); assertThat(evaluatedToken.get().getToken().getData()).isEqualTo("token"); assertThat(evaluatedToken.get().getPosition()) .isEqualTo(new Position(token.getStartOffset(), token.getText().length())); } @Test public void tokenIsNotRecognized_whenItHasUnrecognizedType() { final RobotToken token = RobotToken.create("text", newArrayList(unrecognizedType)); token.setStartOffset(42); final Optional<PositionedTextToken> evaluatedToken = testedRule.evaluate(token, 0, new ArrayList<IRobotLineElement>()); assertThat(evaluatedToken).is(absent()); } @Test public void tokenIsNotRecognized_evenIfItHasRecognizedTypeButNotOnFirstPosition() { final RobotToken token = RobotToken.create("text", newArrayList(unrecognizedType, recognizedType1, recognizedType2)); token.setStartOffset(42); final Optional<PositionedTextToken> evaluatedToken = testedRule.evaluate(token, 0, new ArrayList<IRobotLineElement>()); assertThat(evaluatedToken).is(absent()); } @Test public void tokenIsNotRecognized_whenItHasUnrecognizedTypeRegardlesGivenOffsetInside() { final RobotToken token = RobotToken.create("text", newArrayList(unrecognizedType)); token.setStartOffset(42); final int offsetInside = new Random().nextInt(token.getText().length()); final Optional<PositionedTextToken> evaluatedToken = testedRule.evaluate(token, offsetInside, new ArrayList<IRobotLineElement>()); assertThat(evaluatedToken).is(absent()); } private class RecognizedTokenTypeMock1 implements IRobotTokenType { @Override public List<String> getRepresentation() { return new ArrayList<>(); } @Override public List<VersionAvailabilityInfo> getVersionAvailabilityInfos() { return newArrayList(VersionAvailabilityInfoBuilder.create().build()); } @Override public VersionAvailabilityInfo findVersionAvailablilityInfo(final String text) { return VersionAvailabilityInfoBuilder.create().build(); } } private class RecognizedTokenTypeMock2 extends RecognizedTokenTypeMock1 { // nothing to reimplement } private class UnrecognizedTokenTypeMock extends RecognizedTokenTypeMock1 { // nothing to reimplement } }
[ "test009@nsn.com.not.available" ]
test009@nsn.com.not.available
a30360f55feda0bc05f3694b72569b4ff130a9ec
0c8464275690b54c0a6300cb03b3f834390ce2f3
/TAGS/BEFORE_RCP-3.5/sernet.gs.reveng/src/sernet/gs/reveng/MbZeiteinheitenTxtDAO.java
f0a7d10781f1f07bedf1c50e28ad3e4052fc5eec
[]
no_license
nandaTF/svnroot
ef20097c44eb2f5c460886518889277d145871b5
bcce753556e3ba8f7f56bbeb479993c5a0d0de69
refs/heads/master
2020-07-05T05:59:26.617175
2015-07-29T16:35:38
2015-07-29T16:35:38
39,940,740
0
0
null
null
null
null
UTF-8
Java
false
false
5,013
java
package sernet.gs.reveng; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.criterion.Example; /** * A data access object (DAO) providing persistence and search support for * MbZeiteinheitenTxt entities. Transaction control of the save(), update() and * delete() operations can directly support Spring container-managed * transactions or they can be augmented to handle user-managed Spring * transactions. Each of these methods provides additional information for how * to configure it for the desired type of transaction control. * * @see sernet.gs.reveng.MbZeiteinheitenTxt * @author MyEclipse Persistence Tools */ public class MbZeiteinheitenTxtDAO extends BaseHibernateDAO { private static final Log log = LogFactory .getLog(MbZeiteinheitenTxtDAO.class); // property constants public static final String NAME = "name"; public static final String BESCHREIBUNG = "beschreibung"; public static final String GUID = "guid"; public static final String IMP_NEU = "impNeu"; public static final String GUID_ORG = "guidOrg"; public void save(MbZeiteinheitenTxt transientInstance) { log.debug("saving MbZeiteinheitenTxt instance"); try { getSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(MbZeiteinheitenTxt persistentInstance) { log.debug("deleting MbZeiteinheitenTxt instance"); try { getSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public MbZeiteinheitenTxt findById(sernet.gs.reveng.MbZeiteinheitenTxtId id) { log.debug("getting MbZeiteinheitenTxt instance with id: " + id); try { MbZeiteinheitenTxt instance = (MbZeiteinheitenTxt) getSession() .get("sernet.gs.reveng.MbZeiteinheitenTxt", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(MbZeiteinheitenTxt instance) { log.debug("finding MbZeiteinheitenTxt instance by example"); try { List results = getSession().createCriteria( "sernet.gs.reveng.MbZeiteinheitenTxt").add( Example.create(instance)).list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding MbZeiteinheitenTxt instance with property: " + propertyName + ", value: " + value); try { String queryString = "from MbZeiteinheitenTxt as model where model." + propertyName + "= ?"; Query queryObject = getSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByName(Object name) { return findByProperty(NAME, name); } public List findByBeschreibung(Object beschreibung) { return findByProperty(BESCHREIBUNG, beschreibung); } public List findByGuid(Object guid) { return findByProperty(GUID, guid); } public List findByImpNeu(Object impNeu) { return findByProperty(IMP_NEU, impNeu); } public List findByGuidOrg(Object guidOrg) { return findByProperty(GUID_ORG, guidOrg); } public List findAll() { log.debug("finding all MbZeiteinheitenTxt instances"); try { String queryString = "from MbZeiteinheitenTxt"; Query queryObject = getSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public MbZeiteinheitenTxt merge(MbZeiteinheitenTxt detachedInstance) { log.debug("merging MbZeiteinheitenTxt instance"); try { MbZeiteinheitenTxt result = (MbZeiteinheitenTxt) getSession() .merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(MbZeiteinheitenTxt instance) { log.debug("attaching dirty MbZeiteinheitenTxt instance"); try { getSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(MbZeiteinheitenTxt instance) { log.debug("attaching clean MbZeiteinheitenTxt instance"); try { getSession().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } }
[ "dmurygin@4c0145ca-515c-4d1a-a6bc-f9bd594c3410" ]
dmurygin@4c0145ca-515c-4d1a-a6bc-f9bd594c3410
c8550b1ddca8729130989825bc22bc29d9ffcb5f
27511a2f9b0abe76e3fcef6d70e66647dd15da96
/src/com/instagram/common/k/a/b.java
750ebb1f7964c94df2925d8bfe3b2178bd9a931b
[]
no_license
biaolv/com.instagram.android
7edde43d5a909ae2563cf104acfc6891f2a39ebe
3fcd3db2c3823a6d29a31ec0f6abcf5ceca995de
refs/heads/master
2022-05-09T15:05:05.412227
2016-07-21T03:48:36
2016-07-21T03:48:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
380
java
package com.instagram.common.k.a; import java.util.concurrent.atomic.AtomicLong; final class b implements Runnable { b(c paramc) {} public final void run() { if ((c.a(a).get() > c.b(a)) || (a.a() > c.c(a))) { c.d(a); } } } /* Location: * Qualified Name: com.instagram.common.k.a.b * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
[ "reverseengineeringer@hackeradmin.com" ]
reverseengineeringer@hackeradmin.com
73f1d2c62635123dc34cb933801519b006cce42a
c8269845b4f4b12f6eb08d6be79482940de18d11
/src/main/java/com/dockerplugindemo/server/FirstServerHandler.java
4b932df69931a7ce1b90371e19359b71e0c2ad7f
[]
no_license
2430546168/dockerplugindemo
02dd7717508eb4764eeb58df7fdeb7c08806bb21
a2db0e81754f1d0b20f25730f8517628e56d4dfc
refs/heads/master
2022-12-09T03:09:59.674535
2020-09-10T06:43:12
2020-09-10T06:43:12
293,737,552
0
0
null
null
null
null
UTF-8
Java
false
false
1,110
java
package com.dockerplugindemo.server; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.nio.charset.StandardCharsets; import java.util.Date; /** * @author: zsg * @create: 2020/9/9 16:16 * @description: */ public class FirstServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf byteBuf = (ByteBuf) msg; System.out.println(new Date() + ": 服务端读到数据 -> " + byteBuf.toString(StandardCharsets.UTF_8)); // 回复数据到客户端 System.out.println(new Date() + ": 服务端写出数据"); ByteBuf out = getByteBuf(ctx); ctx.channel().writeAndFlush(out); } private ByteBuf getByteBuf(ChannelHandlerContext ctx) { byte[] bytes = "你好,欢迎关注我的微信公众号,《闪电侠的博客》!".getBytes(StandardCharsets.UTF_8); ByteBuf buffer = ctx.alloc().buffer(); buffer.writeBytes(bytes); return buffer; } }
[ "2430546168@qq.com" ]
2430546168@qq.com
6f7f125e64b5e4371a8e89d3ed800bbcf43967a8
232f16900ceb6cb7eca365eeb29988c0c92f49e2
/src/main/java/sandy/entity/Product.java
8233485df43b42598323e57972bd0cce0fdbb15e
[]
no_license
sandeepnegi1996/product_inventory_api_SpringBoot
c1f4bf4e17c9bea5ac66745d0809c923339b2bec
80ceea116f259763f2dd1864223449e846e01022
refs/heads/master
2020-12-23T15:51:16.925688
2020-01-30T11:09:25
2020-01-30T11:09:25
237,195,750
0
0
null
null
null
null
UTF-8
Java
false
false
621
java
package sandy.entity; public class Product { private int pid; private String pName; private int PQuantity; public Product(int pid, String pName, int pQuantity) { super(); this.pid = pid; this.pName = pName; PQuantity = pQuantity; } public Product(){ } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getpName() { return pName; } public void setpName(String pName) { this.pName = pName; } public int getPQuantity() { return PQuantity; } public void setPQuantity(int pQuantity) { PQuantity = pQuantity; } }
[ "9041128179sandy@gmail.com" ]
9041128179sandy@gmail.com
1fa9c19c5d93397d195d5dc90968f3f4b8b8abae
1dc4f2c2e441482ccd558ba5b874b5ab9a673878
/ web-academy-erp/AcademyERP/src/academy/faq_board/action/ActionForward.java
30d9062a1f54767b0e57ea3ad2d7e447a8083a9b
[]
no_license
ricardoard12/web-academy-erp
d10161fcabc1cb9bb1a9423372e7342fb7c67740
4122d3524848bb1e4c15479a3801b9d2fd930efa
refs/heads/master
2021-01-10T05:08:03.790652
2013-03-21T05:45:39
2013-03-21T05:45:39
45,357,209
0
0
null
null
null
null
UTF-8
Java
false
false
455
java
package academy.faq_board.action; public class ActionForward { private boolean isRedirect = false; private String path = ""; public boolean isRedirect() { return isRedirect; } public void setRedirect(boolean isRedirect) { this.isRedirect = isRedirect; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } }
[ "skawodn65@db77fb09-7fbe-7500-95d4-d0ba2e8cd75c" ]
skawodn65@db77fb09-7fbe-7500-95d4-d0ba2e8cd75c
7c5b84b9217ae547d4b121706b585413560a1a76
81cd45713bcf3a86de1ab422bb5e235c857b7fd5
/main/java/com/evershy/yeet/proxy/ClientProxy.java
43ad9d4cc4693128a2d33e207e4df5d1cfc8f0b2
[]
no_license
IjiMendeleev/src
c2a241dfa38c45f0cf37526c60d829d2efe11dc2
6520fe00e526295ce2d2e67313c44617ec567552
refs/heads/master
2020-09-30T01:22:21.728863
2019-12-18T21:25:48
2019-12-18T21:25:48
227,165,351
0
0
null
null
null
null
UTF-8
Java
false
false
623
java
package com.evershy.yeet.proxy; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.entity.Render; import net.minecraft.entity.Entity; import net.minecraft.item.Item; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.client.registry.RenderingRegistry; public class ClientProxy extends CommonProxy { public void registerItemRenderer(Item item, int meta, String id) { ModelLoader.setCustomModelResourceLocation(item, meta, new ModelResourceLocation(item.getRegistryName(), id)); } }
[ "32820323+IjiMendeleev@users.noreply.github.com" ]
32820323+IjiMendeleev@users.noreply.github.com
ba2f0075d2a0ee24bb0107f3e225d88b9b04f5e6
ed91c77afaeb0e075da38153aa89c6ee8382d3fc
/mediasoup-client/deps/webrtc/src/sdk/android/api/org/webrtc/Camera2Enumerator.java
2c6bb57b68b0d13214b3848fbdb8d7056729cc2c
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-google-patent-license-webrtc", "LicenseRef-scancode-google-patent-license-webm", "MIT" ]
permissive
whatisor/mediasoup-client-android
37bf1aeaadc8db642cff449a26545bf15da27539
dc3d812974991d9b94efbc303aa2deb358928546
refs/heads/master
2023-04-26T12:24:18.355241
2023-01-02T16:55:19
2023-01-02T16:55:19
243,833,549
0
0
MIT
2020-02-28T18:56:36
2020-02-28T18:56:36
null
UTF-8
Java
false
false
9,997
java
/* * Copyright 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package org.webrtc; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Rect; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CameraMetadata; import android.hardware.camera2.params.StreamConfigurationMap; import android.os.Build; import android.os.SystemClock; import android.support.annotation.Nullable; import android.util.AndroidException; import android.util.Range; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.webrtc.CameraEnumerationAndroid.CaptureFormat; @TargetApi(21) public class Camera2Enumerator implements CameraEnumerator { private final static String TAG = "Camera2Enumerator"; private final static double NANO_SECONDS_PER_SECOND = 1.0e9; // Each entry contains the supported formats for a given camera index. The formats are enumerated // lazily in getSupportedFormats(), and cached for future reference. private static final Map<String, List<CaptureFormat>> cachedSupportedFormats = new HashMap<String, List<CaptureFormat>>(); final Context context; @Nullable final CameraManager cameraManager; public Camera2Enumerator(Context context) { this.context = context; this.cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); } @Override public String[] getDeviceNames() { try { return cameraManager.getCameraIdList(); // On Android OS pre 4.4.2, a class will not load because of VerifyError if it contains a // catch statement with an Exception from a newer API, even if the code is never executed. // https://code.google.com/p/android/issues/detail?id=209129 } catch (/* CameraAccessException */ AndroidException e) { Logging.e(TAG, "Camera access exception", e); return new String[] {}; } } @Override public boolean isFrontFacing(String deviceName) { CameraCharacteristics characteristics = getCameraCharacteristics(deviceName); return characteristics != null && characteristics.get(CameraCharacteristics.LENS_FACING) == CameraMetadata.LENS_FACING_FRONT; } @Override public boolean isBackFacing(String deviceName) { CameraCharacteristics characteristics = getCameraCharacteristics(deviceName); return characteristics != null && characteristics.get(CameraCharacteristics.LENS_FACING) == CameraMetadata.LENS_FACING_BACK; } @Nullable @Override public List<CaptureFormat> getSupportedFormats(String deviceName) { return getSupportedFormats(context, deviceName); } @Override public CameraVideoCapturer createCapturer( String deviceName, CameraVideoCapturer.CameraEventsHandler eventsHandler) { return new Camera2Capturer(context, deviceName, eventsHandler); } private @Nullable CameraCharacteristics getCameraCharacteristics(String deviceName) { try { return cameraManager.getCameraCharacteristics(deviceName); // On Android OS pre 4.4.2, a class will not load because of VerifyError if it contains a // catch statement with an Exception from a newer API, even if the code is never executed. // https://code.google.com/p/android/issues/detail?id=209129 } catch (/* CameraAccessException */ AndroidException e) { Logging.e(TAG, "Camera access exception", e); return null; } } /** * Checks if API is supported and all cameras have better than legacy support. */ public static boolean isSupported(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { return false; } CameraManager cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); try { String[] cameraIds = cameraManager.getCameraIdList(); for (String id : cameraIds) { CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id); if (characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL) == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) { return false; } } // On Android OS pre 4.4.2, a class will not load because of VerifyError if it contains a // catch statement with an Exception from a newer API, even if the code is never executed. // https://code.google.com/p/android/issues/detail?id=209129 } catch (/* CameraAccessException */ AndroidException | RuntimeException e) { Logging.e(TAG, "Failed to check if camera2 is supported", e); return false; } return true; } static int getFpsUnitFactor(Range<Integer>[] fpsRanges) { if (fpsRanges.length == 0) { return 1000; } return fpsRanges[0].getUpper() < 1000 ? 1000 : 1; } static List<Size> getSupportedSizes(CameraCharacteristics cameraCharacteristics) { final StreamConfigurationMap streamMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); final int supportLevel = cameraCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); final android.util.Size[] nativeSizes = streamMap.getOutputSizes(SurfaceTexture.class); final List<Size> sizes = convertSizes(nativeSizes); // Video may be stretched pre LMR1 on legacy implementations. // Filter out formats that have different aspect ratio than the sensor array. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1 && supportLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) { final Rect activeArraySize = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE); final ArrayList<Size> filteredSizes = new ArrayList<Size>(); for (Size size : sizes) { if (activeArraySize.width() * size.height == activeArraySize.height() * size.width) { filteredSizes.add(size); } } return filteredSizes; } else { return sizes; } } @Nullable static List<CaptureFormat> getSupportedFormats(Context context, String cameraId) { return getSupportedFormats( (CameraManager) context.getSystemService(Context.CAMERA_SERVICE), cameraId); } @Nullable static List<CaptureFormat> getSupportedFormats(CameraManager cameraManager, String cameraId) { synchronized (cachedSupportedFormats) { if (cachedSupportedFormats.containsKey(cameraId)) { return cachedSupportedFormats.get(cameraId); } Logging.d(TAG, "Get supported formats for camera index " + cameraId + "."); final long startTimeMs = SystemClock.elapsedRealtime(); final CameraCharacteristics cameraCharacteristics; try { cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId); } catch (Exception ex) { Logging.e(TAG, "getCameraCharacteristics()", ex); return new ArrayList<CaptureFormat>(); } final StreamConfigurationMap streamMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); Range<Integer>[] fpsRanges = cameraCharacteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES); List<CaptureFormat.FramerateRange> framerateRanges = convertFramerates(fpsRanges, getFpsUnitFactor(fpsRanges)); List<Size> sizes = getSupportedSizes(cameraCharacteristics); int defaultMaxFps = 0; for (CaptureFormat.FramerateRange framerateRange : framerateRanges) { defaultMaxFps = Math.max(defaultMaxFps, framerateRange.max); } final List<CaptureFormat> formatList = new ArrayList<CaptureFormat>(); for (Size size : sizes) { long minFrameDurationNs = 0; try { minFrameDurationNs = streamMap.getOutputMinFrameDuration( SurfaceTexture.class, new android.util.Size(size.width, size.height)); } catch (Exception e) { // getOutputMinFrameDuration() is not supported on all devices. Ignore silently. } final int maxFps = (minFrameDurationNs == 0) ? defaultMaxFps : (int) Math.round(NANO_SECONDS_PER_SECOND / minFrameDurationNs) * 1000; formatList.add(new CaptureFormat(size.width, size.height, 0, maxFps)); Logging.d(TAG, "Format: " + size.width + "x" + size.height + "@" + maxFps); } cachedSupportedFormats.put(cameraId, formatList); final long endTimeMs = SystemClock.elapsedRealtime(); Logging.d(TAG, "Get supported formats for camera index " + cameraId + " done." + " Time spent: " + (endTimeMs - startTimeMs) + " ms."); return formatList; } } // Convert from android.util.Size to Size. private static List<Size> convertSizes(android.util.Size[] cameraSizes) { final List<Size> sizes = new ArrayList<Size>(); for (android.util.Size size : cameraSizes) { sizes.add(new Size(size.getWidth(), size.getHeight())); } return sizes; } // Convert from android.util.Range<Integer> to CaptureFormat.FramerateRange. static List<CaptureFormat.FramerateRange> convertFramerates( Range<Integer>[] arrayRanges, int unitFactor) { final List<CaptureFormat.FramerateRange> ranges = new ArrayList<CaptureFormat.FramerateRange>(); for (Range<Integer> range : arrayRanges) { ranges.add(new CaptureFormat.FramerateRange( range.getLower() * unitFactor, range.getUpper() * unitFactor)); } return ranges; } }
[ "wuhaiyang1213@gmail.com" ]
wuhaiyang1213@gmail.com
af6dd69aec230f2627c9b4bc57c06f794c18bd44
ccf9c4f38da30f02359bcb7ff3fa5c406c58b2b3
/src/jaeyoung96/MainLine.java
73bd80f971e6e1676f5ef0071c14160c1c320de8
[]
no_license
phm3241/RentalProject
2b0436e625a21c898bcafc5f16f01c994a63e6d0
f6be9a521bef44fb446cb6176b59fcaa9482cc1f
refs/heads/master
2022-07-05T03:43:08.658226
2020-05-12T05:14:28
2020-05-12T05:14:28
263,653,378
0
0
null
null
null
null
UTF-8
Java
false
false
3,550
java
package jaeyoung96; public class MainLine { public static void main(String[] args) { AdminManager adm = AdminManager.getInstance(); MemberManager mem = new MemberManager(); while (true) { System.out.println(); System.out.println("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■"); System.out.println(); System.out.println("- - - - - - - - - - - - - - 대 여 대 여 L I B R A R Y     - - - - - - - - - - - - - - "); System.out.println(); System.out.println("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ"); System.out.println("1. 검색/대여 | 2.로그인 | 3.이용안내/회원가입 | 4.내 대여내역(반납/연장) | 5.로그아웃 | 6.관리자페이지 | 7.프로그램 종료"); System.out.println("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ"); System.out.println(); int selectNum; try { selectNum = adm.sc.nextInt(); adm.sc.nextLine(); } catch (Exception e) { System.out.println("1~7사이 숫자를 입력해 주세요."); adm.sc.nextLine(); continue; } switch (selectNum) { // 1. 검색/대여----------------------------- case 1: mem.searchItemInfo(); break; // 2. 로그인----------------------------- case 2: adm.login(); break; // 3.회원가입/이용안내----------------------------- case 3: System.out.println("1. 이용안내 | 2.회원가입"); selectNum = adm.sc.nextInt(); adm.sc.nextLine(); switch (selectNum) { case 1: mem.showGuide(); break; case 2: adm.addInfo(); break; } break; // 4. 내 대여내역----------------------------- case 4: if (adm.loginCheck()) { mem.returnExtends(); break; } else { System.out.println("먼저 로그인 해주세요."); continue; } // 5.로그아웃----------------------------- case 5: adm.logOut(); break; // 6.관리자페이지----------------------------- case 6: adm.AdminLogin(); while (true) { System.out.println("1. 회원관리 | 2. 도서관리 | 3. DVD관리 | 4. 게임관리 | 5. 대여내역관리 | 6. 로그아웃"); selectNum = adm.sc.nextInt(); adm.sc.nextLine(); switch (selectNum) { case 1: RentalMenu.memeberView(); continue; case 2: RentalMenu.bookView(); continue; case 3: RentalMenu.dvdView(); continue; case 4: RentalMenu.gameView(); continue; case 5: RentalMenu.rentalListView(); continue; case 6: break; default: System.out.println("잘못된 입력입니다."); continue; } break; } // while end continue; case 7: System.out.println("프로그램이 종료됩니다."); System.exit(0); default: System.out.println("1~7사이 숫자를 입력해 주세요."); continue; } // switch end } // while end } // main end } // class end
[ "lgrnsdk@naver.com" ]
lgrnsdk@naver.com
bccfb32f2b7badcf0b95dd4c91b692a40950262d
ed0f378dc7265e1538ab18229729c5f624677c2a
/源代码/taojin-manage/taojin-manage-entity/src/main/java/com/ms/taojin/manage/entity/ItemEntity.java
63078fe5069ac173c3ff882f1063555d75fd9dd0
[]
no_license
ms930602/TaoJin
8dead7e6bc08d4d0b48dda0993e935cde2201ef8
398af018bc30b52a7feb302ae2dcbc61dc0b7f88
refs/heads/master
2020-04-08T06:19:36.257454
2018-11-30T10:00:41
2018-11-30T10:00:41
159,092,740
0
0
null
null
null
null
UTF-8
Java
false
false
6,389
java
package com.ms.taojin.manage.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.ms.taojin.common.entity.BaseEntity; import com.ms.taojin.common.vo.TableName; /** * 物品信息 * @author 蒙赛 * @Date 2018-11-29 10:06:48 * @since 1.0 */ @TableName("t_ms_item") public class ItemEntity extends BaseEntity { /** serialVersionUID */ private static final long serialVersionUID = 1L; /** 主键. */ private Long id; /** 首字母. */ private String firstCode; /** 游戏主键. */ private Long gameId; /** 名称. */ private String name; /** 类型 1永久 2 时限 3元宝. */ private String type; /** 备注. */ private String remark; /** 创建时间. */ private java.util.Date createtime; /** 创建人外键. */ private Long createUserId; /** 创建人姓名. */ private String createUserName; /** 最后修改人外键. */ private Long lastModifyPersonId; /** 最后修改人姓名. */ private String lastModifyPersonName; /** set 主键. */ public void setId(Long id) { this.id = id; } /** get 主键. */ public Long getId() { return this.id; } @JsonIgnore public Long getIdByLike() { return this.id; } /** set 首字母. */ public void setFirstCode(String firstCode) { this.firstCode = firstCode; } /** get 首字母. */ public String getFirstCode() { return this.firstCode; } @JsonIgnore public String getFirstCodeByLike() { return this.firstCode; } /** set 游戏主键. */ public void setGameId(Long gameId) { this.gameId = gameId; } /** get 游戏主键. */ public Long getGameId() { return this.gameId; } @JsonIgnore public Long getGameIdByLike() { return this.gameId; } /** set 名称. */ public void setName(String name) { this.name = name; } /** get 名称. */ public String getName() { return this.name; } @JsonIgnore public String getNameByLike() { return "%"+this.name+"%"; } /** set 类型 1永久 2 时限 3元宝. */ public void setType(String type) { this.type = type; } /** get 类型 1永久 2 时限 3元宝. */ public String getType() { return this.type; } @JsonIgnore public String getTypeByLike() { return this.type; } /** set 备注. */ public void setRemark(String remark) { this.remark = remark; } /** get 备注. */ public String getRemark() { return this.remark; } @JsonIgnore public String getRemarkByLike() { return "%"+this.remark+"%"; } /** set 创建时间. */ public void setCreatetime(java.util.Date createtime) { this.createtime = createtime; } /** get 创建时间. */ public java.util.Date getCreatetime() { return this.createtime; } @JsonIgnore public java.util.Date getCreatetimeByLike() { return this.createtime; } /** set 创建人外键. */ public void setCreateUserId(Long createUserId) { this.createUserId = createUserId; } /** get 创建人外键. */ public Long getCreateUserId() { return this.createUserId; } @JsonIgnore public Long getCreateUserIdByLike() { return this.createUserId; } /** set 创建人姓名. */ public void setCreateUserName(String createUserName) { this.createUserName = createUserName; } /** get 创建人姓名. */ public String getCreateUserName() { return this.createUserName; } @JsonIgnore public String getCreateUserNameByLike() { return "%"+this.createUserName+"%"; } /** set 最后修改人外键. */ public void setLastModifyPersonId(Long lastModifyPersonId) { this.lastModifyPersonId = lastModifyPersonId; } /** get 最后修改人外键. */ public Long getLastModifyPersonId() { return this.lastModifyPersonId; } @JsonIgnore public Long getLastModifyPersonIdByLike() { return this.lastModifyPersonId; } /** set 最后修改人姓名. */ public void setLastModifyPersonName(String lastModifyPersonName) { this.lastModifyPersonName = lastModifyPersonName; } /** get 最后修改人姓名. */ public String getLastModifyPersonName() { return this.lastModifyPersonName; } @JsonIgnore public String getLastModifyPersonNameByLike() { return "%"+this.lastModifyPersonName+"%"; } /** constructor */ public ItemEntity() { super(); } /** * constructor.<p> * @param firstCode 首字母 * @param gameId 游戏主键 * @param name 名称 * @param type 类型 1永久 2 时限 3元宝 * @param remark 备注 * @param createtime 创建时间 * @param createUserId 创建人外键 * @param createUserName 创建人姓名 * @param lastModifyPersonId 最后修改人外键 * @param lastModifyPersonName 最后修改人姓名 */ public ItemEntity(String firstCode,Long gameId,String name,String type,String remark,java.util.Date createtime,Long createUserId,String createUserName,Long lastModifyPersonId,String lastModifyPersonName){ this(); this.firstCode = firstCode; this.gameId = gameId; this.name = name; this.type = type; this.remark = remark; this.createtime = createtime; this.createUserId = createUserId; this.createUserName = createUserName; this.lastModifyPersonId = lastModifyPersonId; this.lastModifyPersonName = lastModifyPersonName; } @Override public String toString() { return new StringBuilder().append("ItemEntity[") .append("Id=").append(getId()).append(", ") .append("FirstCode=").append(getFirstCode()).append(", ") .append("GameId=").append(getGameId()).append(", ") .append("Name=").append(getName()).append(", ") .append("Type=").append(getType()).append(", ") .append("Remark=").append(getRemark()).append(", ") .append("Createtime=").append(getCreatetime()).append(", ") .append("CreateUserId=").append(getCreateUserId()).append(", ") .append("CreateUserName=").append(getCreateUserName()).append(", ") .append("LastModifyPersonId=").append(getLastModifyPersonId()).append(", ") .append("LastModifyPersonName=").append(getLastModifyPersonName()) .append("]").toString(); } @Override public int hashCode() { return toString().hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) return false; if(obj instanceof ItemEntity == false) return false; if(this == obj) return true; ItemEntity other = (ItemEntity)obj; return this.toString().equals(other.toString()); } }
[ "ms930602@sina.cn" ]
ms930602@sina.cn
8cd64da934d1ed30974f156bee8670cba075b4a2
da4c910c15e79edcd13d12ef2aeee348f71fac08
/src/main/java/com/docusign/controller/click/examples/C004ControllerGetListClickwraps.java
18725d4a7ed13257844b93f33b623e8cba41dac4
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
prafullkotecha/docusign-hackathon
6c3f73518d3a2aeed1018b4ca5131347ccf4e549
4ed463d41983301d5421921b9b4f02a790ec264f
refs/heads/main
2023-06-26T23:40:00.638449
2021-08-01T13:46:30
2021-08-01T13:46:30
390,871,672
0
0
MIT
2021-07-29T23:12:37
2021-07-29T23:10:43
null
UTF-8
Java
false
false
1,895
java
package com.docusign.controller.click.examples; import com.docusign.DSConfiguration; import com.docusign.click.api.AccountsApi; import com.docusign.click.client.ApiException; import com.docusign.click.model.*; import com.docusign.common.WorkArguments; import com.docusign.core.model.DoneExample; import com.docusign.core.model.Session; import com.docusign.core.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Get a list of clickwraps. */ @Controller @RequestMapping("/c004") public class C004ControllerGetListClickwraps extends AbstractClickController { private final Session session; private final User user; @Autowired public C004ControllerGetListClickwraps(DSConfiguration config, Session session, User user) { super(config, "c004", "Get a list of clickwraps"); this.session = session; this.user = user; } @Override // ***DS.snippet.0.start protected Object doWork(WorkArguments args, ModelMap model, HttpServletResponse response) throws ApiException { // Step 2: Construct your API headers AccountsApi accountsApi = this.createAccountsApiClient(this.session.getBasePath(), this.user.getAccessToken()); // Step 3: Call the v1 Click API ClickwrapVersionsResponse clickwrapsResponse = accountsApi.getClickwraps(this.session.getAccountId()); DoneExample.createDefault(this.title) .withJsonObject(clickwrapsResponse) .withMessage("Clickwraps have been returned!") .addToModel(model); return DONE_EXAMPLE_PAGE; } // ***DS.snippet.0.end }
[ "prafull.kotecha@gmail.com" ]
prafull.kotecha@gmail.com
6f612662ee2f521a75a73cf94be554d9c654e714
0a850bdb161e32b71e1515e3d16c1b82be86dff0
/src/main/java/com/zhiyou100/video/web/controller/AdminVideoController.java
d49af59dda3b50a4a16a3de5dd6558bc8269980c
[]
no_license
yuanman1/video
86cb0f9a60801b3fae10a19687b0c7929a27da83
c0b12b32e57670e09f9e5258ca21548d7f342e7e
refs/heads/master
2021-08-30T00:07:10.425231
2017-12-15T11:10:30
2017-12-15T11:10:30
114,361,696
0
0
null
null
null
null
UTF-8
Java
false
false
3,482
java
package com.zhiyou100.video.web.controller; import java.util.Arrays; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.mysql.fabric.xmlrpc.base.Data; import com.zhiyou100.video.model.Course; import com.zhiyou100.video.model.Speaker; import com.zhiyou100.video.model.Video; import com.zhiyou100.video.service.AdminVideoService; import com.zhiyou100.video.utils.Page; @Controller public class AdminVideoController { @Autowired private AdminVideoService as; @RequestMapping("/admin/videolist.action") /*public String adminvideolist(Model md,Page page,String video_title,String speaker_name,String course_name){ int page1=page.getPage()==0?1:page.getPage(); video_title = video_title==null?"":video_title; speaker_name = speaker_name==null?"":speaker_name; course_name = course_name==null?"":course_name;*/ public String adminvideolist(Model md,@RequestParam(defaultValue="1")Integer page,@RequestParam(defaultValue="")String video_title,@RequestParam(defaultValue="")String speaker_name,@RequestParam(defaultValue="")String course_name){ List<Speaker> speaker=as.findAllByspeakername(); List<Course> course=as.findAllBycoursename(); Page<Video> a=as.findAllvideo(page,video_title,speaker_name,course_name); md.addAttribute("page", a); md.addAttribute("speaker", speaker); md.addAttribute("course", course); return "admin/video/videolist"; } @RequestMapping(value="/admin/addvideo.action",method=RequestMethod.GET) public String adminaddvideo(Model md){ List<Speaker> speaker=as.findAllByspeakername(); List<Course> course=as.findAllBycoursename(); md.addAttribute("speaker", speaker); md.addAttribute("course", course); return "admin/video/addvideo"; } @RequestMapping(value="/admin/addvideo.action",method=RequestMethod.POST) public String adminaddvideo1(Video video){ Date date=new Date(); video.setInsert_time(date); as.adminaddvideo1(video); return "redirect:/admin/videolist.action"; } @RequestMapping(value="/admin/updatevideo.action",method=RequestMethod.GET) public String adminupdatevideo(Model md,Integer id){ List<Speaker> speaker=as.findAllByspeakername(); List<Course> course=as.findAllBycoursename(); Video video=as.findvideoById(id); md.addAttribute("speaker", speaker); md.addAttribute("course", course); md.addAttribute("video", video); return "admin/video/updatevideo"; } @RequestMapping(value="/admin/updatevideo.action",method=RequestMethod.POST) public String adminupdatevideo1(Video video){ Date date=new Date(); video.setUpdate_time(date); as.adminupdatevideo1(video); return "redirect:/admin/videolist.action"; } @RequestMapping("/admin/deletevideo.action") public String admindeletevideo(Integer id){ as.admindeletevideo(id); return "redirect:/admin/videolist.action"; } @RequestMapping("/admin/deleteallvideo.action") public String admindeleteallvideo(int[] id){ if(id==null){ return "redirect:/admin/videolist.action"; } for (int i : id) { as.admindeletevideo(i); } return "redirect:/admin/videolist.action"; } }
[ "1412668325@qq.com" ]
1412668325@qq.com
715a0ce3c3e3240940960b3620d3603f36320371
22907b20e3778f15906bd77c582f9d64b65e708f
/java_eclipse-plugin_sharpdev/org.emonic.debugger/src/org/emonic/debugger/ui/EmonicModelPresentation.java
065b81c26e84703f493aa4f0c9b0edf1a9a458fc
[]
no_license
liamzebedee/misc
8888ec8961d83668dc4b56f31ff4469761f83711
bf3455bfdd682a547727cd9d381fe8988b5ee22c
refs/heads/master
2016-09-05T09:29:49.294517
2014-09-24T00:16:31
2014-09-24T00:16:31
6,121,970
1
1
null
null
null
null
UTF-8
Java
false
false
2,499
java
/** * Virtual Machines for Embedded Multimedia - VIMEM * * Copyright (c) 2008 University of Technology Vienna, ICT * (http://www.ict.tuwien.ac.at) * All rights reserved. * * This file is made available under the terms of the * Eclipse Public License v1.0 which is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Harald Krapfenbauer - initial implementation */ package org.emonic.debugger.ui; import org.eclipse.core.resources.IFile; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.model.ILineBreakpoint; import org.eclipse.debug.core.model.IValue; import org.eclipse.debug.ui.IDebugModelPresentation; import org.eclipse.debug.ui.IValueDetailListener; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.part.FileEditorInput; import org.emonic.debugger.frontend.EmonicDebugTarget; import org.emonic.debugger.frontend.EmonicLineBreakpoint; import org.emonic.debugger.frontend.EmonicStackFrame; import org.emonic.debugger.frontend.EmonicThread; public class EmonicModelPresentation extends LabelProvider implements IDebugModelPresentation { public void computeDetail(IValue value, IValueDetailListener listener) { String detail = ""; try { detail = value.getValueString(); } catch (DebugException e) { } listener.detailComputed(value, detail); } public void setAttribute(String attribute, Object value) { } public String getEditorId(IEditorInput input, Object element) { if (element instanceof IFile || element instanceof ILineBreakpoint) { return org.emonic.base.editors.CSharpEditor.EMONIC_CSHARP_EDITOR_ID; } return null; } public IEditorInput getEditorInput(Object element) { if (element instanceof IFile) { return new FileEditorInput((IFile)element); } if (element instanceof ILineBreakpoint) { return new FileEditorInput((IFile)((ILineBreakpoint)element).getMarker() .getResource()); } return null; } public String getText(Object element) { if (element == null) return ""; if (element instanceof EmonicDebugTarget) return ((EmonicDebugTarget)element).getName(); if (element instanceof EmonicThread) return ((EmonicThread)element).getName(); if (element instanceof EmonicStackFrame) return ((EmonicStackFrame)element).getName(); if (element instanceof EmonicLineBreakpoint) return ((EmonicLineBreakpoint)element).getName(); // fall back return element.toString(); } }
[ "liamzebedee@yahoo.com.au" ]
liamzebedee@yahoo.com.au
2f1a607cd762555ccd86eb1c4afb1cd77af94ab8
f0d8026a797d0974241780eb53311bfa55e918e1
/tech_website/src/com/alipay/api/response/AlipayMemberCouponQuerydetailResponse.java
f0bbdb4f55e988e4e2f50cd5e4ca4859f2a59fb7
[]
no_license
boberhu/1yuango
19762c1dc556337ad74f64e4704bbb30050a7757
2b5c8e6a8c2c888e7b81fe793b7e4cd541b0a244
refs/heads/master
2020-04-17T11:18:27.293198
2016-08-29T14:14:12
2016-08-29T14:14:12
66,846,025
1
1
null
null
null
null
UTF-8
Java
false
false
1,115
java
package com.alipay.api.response; import com.alipay.api.AlipayResponse; import com.alipay.api.domain.Coupon; import com.alipay.api.internal.mapping.ApiField; public class AlipayMemberCouponQuerydetailResponse extends AlipayResponse { private static final long serialVersionUID = 1498225184312227364L; @ApiField("coupon") private Coupon coupon; @ApiField("error_code") private String errorCode; @ApiField("error_msg") private String errorMsg; @ApiField("success_code") private String successCode; public void setCoupon(Coupon coupon) { this.coupon = coupon; } public Coupon getCoupon() { return coupon; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorCode() { return errorCode; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public String getErrorMsg() { return errorMsg; } public void setSuccessCode(String successCode) { this.successCode = successCode; } public String getSuccessCode() { return successCode; } }
[ "bober.hu@outlook.com" ]
bober.hu@outlook.com
c93d193c186e8acf0eaffbecbf496f5d642076b8
48843bf40cde0265193b5503839a4fd0c7e36481
/app/src/main/java/com/lenovo/guaguaview/DrawView.java
b2c1059c974231300fe1aa981d8ee7880e2bb49a
[]
no_license
zhangyalong123feiyu/GuaGuaView
ad7e7fd69d281c894aa8902b7b6195a11164cefc
72c416126a7b3f2ff5af0ee1bce1b899ddd03117
refs/heads/master
2020-04-09T10:40:01.103788
2018-12-04T06:27:48
2018-12-04T06:27:48
160,278,568
0
0
null
null
null
null
UTF-8
Java
false
false
2,048
java
package com.lenovo.guaguaview; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class DrawView extends View { private Paint mPaint; private Canvas mCanvas; private Bitmap mBitmap; private PorterDuffXfermode xFreClear; private PorterDuffXfermode xFerDraw; private Path mPath; public DrawView(Context context) { this(context,null); } public DrawView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } private void init() { mPaint=new Paint(); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(30); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.BLACK); xFerDraw=new PorterDuffXfermode(PorterDuff.Mode.SRC); xFreClear=new PorterDuffXfermode(PorterDuff.Mode.CLEAR); mPaint.setXfermode(xFerDraw); mBitmap=Bitmap.createBitmap(getWidth(),getHeight(),Bitmap.Config.ARGB_8888); mCanvas=new Canvas(mBitmap); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: mPath.reset(); if (mPath==null){ mPath=new Path(); } mPath.moveTo(event.getX(),event.getY()); break; case MotionEvent.ACTION_MOVE: mPath.lineTo(event.getX(),event.getY()); mCanvas.drawPath(mPath,mPaint); invalidate(); break; } return super.onTouchEvent(event); } }
[ "zhangyl46@lenovo.com" ]
zhangyl46@lenovo.com
cad6c62cd7c71806f82c21bbe79f7c72c4db4756
6bfddea9dee5f4c31e0931b0fc07a0f93a8ef717
/src/test/java/br/com/fatecmc/joaodebarro/stepdefinition/ClienteStep.java
a638f5c0e144f8109975e2b435994d57abcc065e
[]
no_license
PHCarmo/JoaoDeBarro
606e2f6365962cdbccda2d2308617ab0d6d4f20d
05566fcf0d3c3d5d273e2a53a3637d94bb52d76f
refs/heads/main
2023-07-05T17:13:03.257091
2021-08-29T21:31:40
2021-08-29T21:31:40
340,524,508
0
0
null
null
null
null
UTF-8
Java
false
false
3,062
java
package br.com.fatecmc.joaodebarro.stepdefinition; import br.com.fatecmc.joaodebarro.util.WebDriverSingleton; import br.com.fatecmc.joaodebarro.pageobject.*; import io.cucumber.java.pt.*; import junit.framework.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class ClienteStep { protected WebDriver driver; public ClienteStep() { this.driver = WebDriverSingleton.getInstance().getDriver(); } @Dado("a página inicial é acessada") public void a_página_inicial_é_acessada() { new LoginPage(driver).acessar("http://localhost:8080/JoaoDeBarro/faces/index.jsp"); } @Dado("a página de login é acessada") public void a_página_de_login_é_acessada() { new LoginPage(driver).acessarLogin(); } @Dado("a página de perfil é acessada") public void a_página_de_perfil_é_acessada() { new LoginPage(driver).acessar("http://localhost:8080/JoaoDeBarro/faces/cliente?operacao=CONSULTAR"); } @Quando("{string} é visualizado") public void é_visualizado(String titulo) { new ClientePage(driver).acessarMenu(titulo); } @Quando("o cadastro de {string} é inicializado") public void o_cadastro_de_é_inicializado(String item) { new ClientePage(driver).iniciarCadastro(item); } @Quando("os dados de registro {string} {string} são preenchidos") public void os_dados_de_registro_são_preenchidos(String email, String senha) throws InterruptedException { new LoginPage(driver).preencherRegistro(email, senha); } @Quando("os dados do cliente {string} são preenchidos") public void os_dados_do_cliente_são_preenchidos(String cpf) { new FormularioClientePage(driver).preencherDadosPessoais(cpf); new FormularioClientePage(driver).preencherTelefone(); } @Quando("os dados de endereço {string} são preenchidos") public void os_dados_de_endereço_são_preenchidos(String cep) throws InterruptedException { new FormularioClientePage(driver).preencherEndereco(cep); } @Quando("os dados de cartão {string} são preenchidos") public void os_dados_de_cartão_são_preenchidos(String numero) throws InterruptedException { new FormularioCartaoPage(driver).preencherDadosProprios(numero); } @Quando("os dados de cartão inválido {string} são preenchidos") public void os_dados_de_cartão_inválido_são_preenchidos(String numero) throws InterruptedException { new FormularioCartaoPage(driver).preencherDadosPropriosInvalidos(numero); } @Quando("a página de cadastro de cliente é exibida") public void a_página_de_cadastro_de_cliente_é_exibida() { Assert.assertTrue(driver.findElements(By.xpath("//h2[contains(text(),'Cliente')]")).size() > 0); } @Então("a página de perfil de cliente é exibida") public void a_página_de_perfil_de_cliente_é_exibida() { Assert.assertTrue(driver.findElements(By.xpath("//h2[contains(text(),'Perfil')]")).size() > 0); } }
[ "paulo.henrique.carmo@hotmail.com" ]
paulo.henrique.carmo@hotmail.com
d4cbbbf073292dfe25288a3a19b091acf7d06b8b
5a64670b5a897470d6b4c7523be1f6bf9f62661c
/src/top/jiaway/headfirst/Proxy/GumballMachineTestDrive.java
12640df825fa4080732be57c05c440cfbe3aded5
[]
no_license
andjiawei/headfirst
56f969d4e4c9a776001a0cea0d0771d43729b401
6eb74309074b1711f2c29ed2bb965e7e48ac30f2
refs/heads/master
2022-11-24T19:42:35.809514
2020-07-23T23:15:53
2020-07-23T23:15:53
262,091,262
0
0
null
null
null
null
UTF-8
Java
false
false
1,581
java
package top.jiaway.headfirst.Proxy; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; public class GumballMachineTestDrive { private static GumballMachine gumballMachine; public static void main(String[] args) throws RemoteException { GumballMachineRemote gumballMachineRemote = null ; int count; String[] location = { "rmi://santafe.mightygumball.com/gumballmachine" , "rmi://boulder.mightygumball.com/gumballmachine", "rmi://santafe.mightygumball.com/gumballmachine"}; GumballMonitor[] monitor = new GumballMonitor[location.length]; for (int i = 0;i <location.length; i++){ GumballMachineRemote machine = null; try { machine = (GumballMachineRemote) Naming.lookup(location[i]); monitor[i] = new GumballMonitor(machine); System.out.println( monitor[i] ); } catch (Exception e) { e.printStackTrace(); } } for (int i = 0;i < monitor.length; i++){ monitor[i].report(); } // if (args.length < 2){ // System.out.println("GumballMachine"); // System.exit(1); // } // // try { // count = Integer.parseInt(args[1]); // gumballMachine = new GumballMachine(args[0],count);//location count // }catch (Exception e){ // e.printStackTrace(); // } } }
[ "jiawei@qq.com" ]
jiawei@qq.com
e611aa35fc2f1134affdf6d75ffa259dad55533f
a8f7d781cb24074b5c4a6b252bb898d812fd9502
/app/src/main/java/com/example/android_seminar_8_2/UserAdapter.java
146dd5e1e7f74f20e7e3afcaa5c856107cf03994
[]
no_license
KyriakosOuzounis/Android_Seminar_8_2
0604a81b1fe4285b69e3e7ff9703b97bf27602cc
08ebac5dfc6a6e0fbd1aa4940047f64d3ab84191
refs/heads/master
2021-01-16T07:39:17.657328
2020-02-25T14:59:52
2020-02-25T14:59:52
243,027,209
0
0
null
null
null
null
UTF-8
Java
false
false
2,691
java
package com.example.android_seminar_8_2; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class UserAdapter extends RecyclerView.Adapter<UserAdapter.MyViewHolder> { private Context context; private ArrayList<Suntagi> suntages; public UserAdapter(Context context, ArrayList<Suntagi> suntages) { this.context = context; this.suntages = suntages; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(context); View row = inflater.inflate(R.layout.suntagi_item , parent , false); MyViewHolder item = new MyViewHolder(row); return item; } @Override public void onBindViewHolder(@NonNull MyViewHolder holder,final int position) { ((MyViewHolder)holder).textView_onoma.setText(suntages.get(position).getOnoma()); ((MyViewHolder)holder).textView_perilipsi.setText(suntages.get(position).getPerilipsi()); ((MyViewHolder)holder).textView_id.setText(String.valueOf(suntages.get(position).getId())); ((MyViewHolder)holder).imageView.setImageResource(suntages.get(position).getId()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView = v.findViewById(R.id.textView_id); Log.d("CLICK_ITEM", textView.getText().toString()); Intent intent = new Intent(context, SecondActivity.class); intent.putExtra("user_id", suntages.get(position).getId()); context.startActivity(intent); } }); } @Override public int getItemCount() { return this.suntages.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { TextView textView_onoma; TextView textView_perilipsi; TextView textView_id; ImageView imageView; public MyViewHolder(@NonNull View itemView) { super(itemView); imageView = itemView.findViewById(R.id.imageView); textView_id = itemView.findViewById(R.id.textView_id); textView_onoma = itemView.findViewById(R.id.textView_onoma); textView_perilipsi = itemView.findViewById(R.id.textView_perilipsi); } } }
[ "57915478+KyriakosOuzounis@users.noreply.github.com" ]
57915478+KyriakosOuzounis@users.noreply.github.com
85270c4abab982ac566b3be71288d9fabe37d9b0
fb84fb991eb4d6ca36b893c1598d4e24cd0261f1
/common/src/main/java/me/tinggu/common/utils/ScreenUtils.java
815ae785cf6017885f09d1155921a380b5143ab5
[]
no_license
tinggu/MrBaozi
c4cd06eb047ca7fe735b5bbca2296c7475b8c48e
bfc160ef1124e855f6afae8f5d56820f3aefc519
refs/heads/master
2021-01-10T02:38:30.358257
2016-01-21T07:17:51
2016-01-21T07:17:51
49,554,880
0
0
null
null
null
null
UTF-8
Java
false
false
797
java
package me.tinggu.common.utils; import android.content.Context; import android.util.DisplayMetrics; import android.view.WindowManager; public class ScreenUtils { public static int getWidth(Context context) { WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); manager.getDefaultDisplay().getMetrics(outMetrics); return outMetrics.widthPixels; } public static int getHeight(Context context) { WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); manager.getDefaultDisplay().getMetrics(outMetrics); return outMetrics.heightPixels; } }
[ "tinggu@126.com" ]
tinggu@126.com
57d0142bcfc6350df08c17214ebb4814d5539ac8
d6267a448e056b47d79cc716d18edec6dd91154c
/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/IgniteCacheContinuousQueryNoUnsubscribeTest.java
d7beb02ec867469f4c55db55a2d0434da52faa40
[ "Apache-2.0", "LicenseRef-scancode-gutenberg-2020", "CC0-1.0", "BSD-3-Clause" ]
permissive
sk8tz/ignite
1635163cc2309aa0f9fd65734317af861679679f
2774d879a72b0eeced862cc9a3fbd5d9c5ff2d72
refs/heads/master
2023-04-19T03:07:50.202953
2017-01-04T21:01:13
2017-01-04T21:01:13
78,094,618
0
0
Apache-2.0
2023-04-17T19:45:36
2017-01-05T08:30:14
Java
UTF-8
Java
false
false
4,718
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.ignite.internal.processors.cache.query.continuous; import java.util.concurrent.atomic.AtomicInteger; import javax.cache.configuration.FactoryBuilder; import javax.cache.event.CacheEntryEvent; import javax.cache.event.CacheEntryListenerException; import javax.cache.event.CacheEntryUpdatedListener; import org.apache.ignite.Ignite; import org.apache.ignite.cache.CacheEntryEventSerializableFilter; import org.apache.ignite.cache.query.ContinuousQuery; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; /** * */ public class IgniteCacheContinuousQueryNoUnsubscribeTest extends GridCommonAbstractTest { /** */ private static final TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true); /** */ private static AtomicInteger cntr = new AtomicInteger(); /** */ private boolean client; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(ipFinder); cfg.setPeerClassLoadingEnabled(false); cfg.setClientMode(client); CacheConfiguration ccfg = new CacheConfiguration(); cfg.setCacheConfiguration(ccfg); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); startGridsMultiThreaded(3); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); super.afterTest(); } /** * @throws Exception If failed. */ public void testNoUnsubscribe() throws Exception { checkNoUnsubscribe(false); } /** * @throws Exception If failed. */ public void testNoUnsubscribeClient() throws Exception { checkNoUnsubscribe(true); } /** * @param client Client node flag. * @throws Exception If failed. */ private void checkNoUnsubscribe(boolean client) throws Exception { cntr.set(0); this.client = client; try (Ignite ignite = startGrid(3)) { ContinuousQuery qry = new ContinuousQuery(); qry.setLocalListener(new CacheEntryUpdatedListener() { @Override public void onUpdated(Iterable evts) { // No-op. } }); qry.setRemoteFilterFactory(FactoryBuilder.factoryOf(CacheTestRemoteFilter.class)); qry.setAutoUnsubscribe(false); ignite.cache(null).query(qry); ignite.cache(null).put(1, 1); assertEquals(1, cntr.get()); } this.client = false; try (Ignite newSrv = startGrid(3)) { Integer key = primaryKey(newSrv.cache(null)); newSrv.cache(null).put(key, 1); assertEquals(2, cntr.get()); for (int i = 0; i < 10; i++) ignite(0).cache(null).put(i, 1); assertEquals(12, cntr.get()); } for (int i = 10; i < 20; i++) ignite(0).cache(null).put(i, 1); assertEquals(22, cntr.get()); } /** * */ public static class CacheTestRemoteFilter implements CacheEntryEventSerializableFilter<Object, Object> { /** {@inheritDoc} */ @Override public boolean evaluate(CacheEntryEvent<?, ?> evt) throws CacheEntryListenerException { cntr.incrementAndGet(); return true; } } }
[ "sboikov@gridgain.com" ]
sboikov@gridgain.com
6ab832770e7e8fed3a95c8d4a511ec3270be1f20
d2cb1f4f186238ed3075c2748552e9325763a1cb
/methods_all/nonstatic_methods/javax_imageio_IIOParam_getSubsamplingYOffset.java
03f9ca3208ce7695588c6e47e381191755f70445
[]
no_license
Adabot1/data
9e5c64021261bf181b51b4141aab2e2877b9054a
352b77eaebd8efdb4d343b642c71cdbfec35054e
refs/heads/master
2020-05-16T14:22:19.491115
2019-05-25T04:35:00
2019-05-25T04:35:00
183,001,929
4
0
null
null
null
null
UTF-8
Java
false
false
171
java
class javax_imageio_IIOParam_getSubsamplingYOffset{ public static void function() {javax.imageio.IIOParam obj = new javax.imageio.IIOParam();obj.getSubsamplingYOffset();}}
[ "peter2008.ok@163.com" ]
peter2008.ok@163.com
d19888891658fd2f45d841477c5f986520c8ac24
d1a6d1e511df6db8d8dd0912526e3875c7e1797d
/genny_JavaWithoutLambdasApi21/applicationModule/src/test/java/applicationModulepackageJava16/Foo345Test.java
f07f36459764c115c68064933f12fe2ef803a3d5
[]
no_license
NikitaKozlov/generated-project-for-desugaring
0bc1443ab3ddc84cd289331c726761585766aea7
81506b3711004185070ca4bb9a93482b70011d36
refs/heads/master
2020-03-20T00:35:06.996525
2018-06-12T09:30:37
2018-06-12T09:30:37
137,049,317
0
0
null
null
null
null
UTF-8
Java
false
false
482
java
package applicationModulepackageJava16; import org.junit.Test; public class Foo345Test { @Test public void testFoo0() { new Foo345().foo0(); } @Test public void testFoo1() { new Foo345().foo1(); } @Test public void testFoo2() { new Foo345().foo2(); } @Test public void testFoo3() { new Foo345().foo3(); } @Test public void testFoo4() { new Foo345().foo4(); } @Test public void testFoo5() { new Foo345().foo5(); } }
[ "nikita.e.kozlov@gmail.com" ]
nikita.e.kozlov@gmail.com
df0386c0bce889d0d9acf5d7d5606a8a225feaf1
45649d2f8bae338bceb923e022d84ad041d57bce
/app/src/main/java/jmessage/example/com/nongshangtong/homepage/MainActivity.java
0e896ffe4ab806d40c1d171acd151eaf8297a77a
[]
no_license
qinhuangdaoStation/NongShangTong
afb025f24ebcd5ee11818c030f2379c49c4472b3
3af6e917775e9099676efa676908640498f5b29f
refs/heads/master
2021-01-01T03:37:43.200377
2016-04-13T12:25:12
2016-04-13T12:25:12
56,149,569
0
0
null
null
null
null
UTF-8
Java
false
false
3,419
java
package jmessage.example.com.nongshangtong.homepage; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.util.Log; import android.view.MotionEvent; import android.view.View; import jmessage.example.com.nongshangtong.R; import jmessage.example.com.nongshangtong.homepage.HomePageUtil; import jmessage.example.com.nongshangtong.more.MoreActivity; /** * Created by ii on 2016/4/9. */ public class MainActivity extends AppCompatActivity{ private int screenWidth; private int screenHeight; private HomePageUtil util; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //从这里跳转到更多界面 util.activityStart(MoreActivity.class); MainActivity.this.finish(); } }); //以上暂且保留,以下是正常开始 //获取屏幕长宽,并捕捉外部触摸屏幕的坐标 getScreenWidthHeight(); } private void getScreenWidthHeight() { //方法一 DisplayMetrics dm = new DisplayMetrics(); dm = getResources().getDisplayMetrics(); screenWidth = dm.widthPixels; screenHeight = dm.heightPixels; Log.i("test", "第一种方法," + "宽度为:" + screenWidth + ",长度为:" + screenHeight); // //方法二 // DisplayMetrics dm2 = new DisplayMetrics(); // getWindowManager().getDefaultDisplay().getMetrics(dm2); // screenWidth = dm2.widthPixels; // screenHeight = dm2.heightPixels; // Log.i("test", "第二种方法," + "宽度为:" + screenWidth + ",长度为:" + screenHeight); //工具类 util = new HomePageUtil(this, screenWidth, screenHeight); } // 获取整个activity屏幕触摸事件 @Override public boolean onTouchEvent(MotionEvent event) { handleTouch(event); return true; // 注意!!这里一定要返回true!! } /** * 获得触摸事件 * @param event */ private void handleTouch(MotionEvent event) { float x = event.getX(); float y = event.getY(); Log.i("test", "触摸的位置坐标为:" + x + "," + y); int touch = event.getAction(); switch (touch) { case MotionEvent.ACTION_DOWN: // 按下 break; case MotionEvent.ACTION_MOVE: // 移动 break; case MotionEvent.ACTION_UP: // 抬起 //获取对应界面的序号 int numActivity = util.returnAcitivityNum(x, y); //跳转到相应的界面 util.NumActivityStart(numActivity); break; default: break; } } }
[ "xuridongshenghe@163.com" ]
xuridongshenghe@163.com
6474c0dbc4337c9574a91bf1a9981ece6e388b70
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/OpenTabsTest.java
b2e6626ea47b4daadb8951db0e16261fc0b6709d
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
Java
false
false
14,839
java
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.sync; import android.test.suitebuilder.annotation.LargeTest; import android.util.Pair; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.FlakyTest; import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tabmodel.TabModelUtils; import org.chromium.chrome.test.util.browser.sync.SyncTestUtil; import org.chromium.components.sync.protocol.EntitySpecifics; import org.chromium.components.sync.protocol.SessionHeader; import org.chromium.components.sync.protocol.SessionSpecifics; import org.chromium.components.sync.protocol.SessionTab; import org.chromium.components.sync.protocol.SessionWindow; import org.chromium.components.sync.protocol.SyncEnums; import org.chromium.components.sync.protocol.TabNavigation; import org.chromium.content.browser.test.util.Criteria; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; /** * Test suite for the open tabs (sessions) sync data type. */ @RetryOnFailure // crbug.com/637448 public class OpenTabsTest extends SyncTestBase { private static final String TAG = "OpenTabsTest"; private static final String OPEN_TABS_TYPE = "Sessions"; // EmbeddedTestServer is preferred here but it can't be used. The test server // serves pages on localhost and Chrome doesn't sync localhost URLs as typed URLs. // This type of URL requires no external data connection or resources. private static final String URL = "data:text,OpenTabsTestURL"; private static final String URL2 = "data:text,OpenTabsTestURL2"; private static final String URL3 = "data:text,OpenTabsTestURL3"; private static final String SESSION_TAG_PREFIX = "FakeSessionTag"; private static final String FAKE_CLIENT = "FakeClient"; // The client name for tabs generated locally will vary based on the device the test is // running on, so it is determined once in the setUp() method and cached here. private String mClientName; // A counter used for generating unique session tags. Resets to 0 in setUp(). private int mSessionTagCounter; // A container to store OpenTabs information for data verification. private static class OpenTabs { public final String headerId; public final List<String> tabIds; public final List<String> urls; private OpenTabs(String headerId, List<String> tabIds, List<String> urls) { this.headerId = headerId; this.tabIds = tabIds; this.urls = urls; } } @Override protected void setUp() throws Exception { super.setUp(); setUpTestAccountAndSignIn(); mClientName = getClientName(); mSessionTagCounter = 0; } // Test syncing an open tab from client to server. @LargeTest @Feature({"Sync"}) public void testUploadOpenTab() throws Exception { loadUrl(URL); waitForLocalTabsForClient(mClientName, URL); waitForServerTabs(URL); } /* // Test syncing multiple open tabs from client to server. @LargeTest @Feature({"Sync"}) */ @FlakyTest(message = "https://crbug.com/592437") public void testUploadMultipleOpenTabs() throws Exception { loadUrl(URL); loadUrlInNewTab(URL2); loadUrlInNewTab(URL3); waitForLocalTabsForClient(mClientName, URL, URL2, URL3); waitForServerTabs(URL, URL2, URL3); } /* // Test syncing an open tab from client to server. @LargeTest @Feature({"Sync"}) */ @FlakyTest(message = "https://crbug.com/592437") public void testUploadAndCloseOpenTab() throws Exception { loadUrl(URL); // Can't have zero tabs, so we have to open two to test closing one. loadUrlInNewTab(URL2); waitForLocalTabsForClient(mClientName, URL, URL2); waitForServerTabs(URL, URL2); ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { TabModelSelector selector = getActivity().getTabModelSelector(); assertTrue(TabModelUtils.closeCurrentTab(selector.getCurrentModel())); } }); waitForLocalTabsForClient(mClientName, URL); waitForServerTabs(URL); } // Test syncing an open tab from server to client. @LargeTest @Feature({"Sync"}) public void testDownloadOpenTab() throws Exception { addFakeServerTabs(FAKE_CLIENT, URL); SyncTestUtil.triggerSync(); waitForLocalTabsForClient(FAKE_CLIENT, URL); } // Test syncing multiple open tabs from server to client. @LargeTest @Feature({"Sync"}) public void testDownloadMultipleOpenTabs() throws Exception { addFakeServerTabs(FAKE_CLIENT, URL, URL2, URL3); SyncTestUtil.triggerSync(); waitForLocalTabsForClient(FAKE_CLIENT, URL, URL2, URL3); } // Test syncing a tab deletion from server to client. @LargeTest @Feature({"Sync"}) public void testDownloadDeletedOpenTab() throws Exception { // Add the entity to test deleting. addFakeServerTabs(FAKE_CLIENT, URL); SyncTestUtil.triggerSync(); waitForLocalTabsForClient(FAKE_CLIENT, URL); // Delete on server, sync, and verify deleted locally. deleteServerTabsForClient(FAKE_CLIENT); SyncTestUtil.triggerSync(); waitForLocalTabsForClient(FAKE_CLIENT); } // Test syncing multiple tab deletions from server to client. @LargeTest @Feature({"Sync"}) public void testDownloadMultipleDeletedOpenTabs() throws Exception { // Add the entity to test deleting. addFakeServerTabs(FAKE_CLIENT, URL, URL2, URL3); SyncTestUtil.triggerSync(); waitForLocalTabsForClient(FAKE_CLIENT, URL, URL2, URL3); // Delete on server, sync, and verify deleted locally. deleteServerTabsForClient(FAKE_CLIENT); SyncTestUtil.triggerSync(); waitForLocalTabsForClient(FAKE_CLIENT); } private String makeSessionTag() { return SESSION_TAG_PREFIX + (mSessionTagCounter++); } private void addFakeServerTabs(String clientName, String... urls) throws InterruptedException { String tag = makeSessionTag(); EntitySpecifics header = makeSessionEntity(tag, clientName, urls.length); mFakeServerHelper.injectUniqueClientEntity(tag, header); for (int i = 0; i < urls.length; i++) { EntitySpecifics tab = makeTabEntity(tag, urls[i], i); // It is critical that the name here is "<tag> <tabNodeId>", otherwise sync crashes // when it tries to sync due to the use of TabIdToTag in sessions_sync_manager.cc. mFakeServerHelper.injectUniqueClientEntity(tag + " " + i, tab); } } private EntitySpecifics makeSessionEntity(String tag, String clientName, int numTabs) { EntitySpecifics specifics = new EntitySpecifics(); specifics.session = new SessionSpecifics(); specifics.session.sessionTag = tag; specifics.session.header = new SessionHeader(); specifics.session.header.clientName = clientName; specifics.session.header.deviceType = SyncEnums.TYPE_PHONE; SessionWindow window = new SessionWindow(); window.windowId = 0; window.selectedTabIndex = 0; window.tab = new int[numTabs]; for (int i = 0; i < numTabs; i++) { window.tab[i] = i; } specifics.session.header.window = new SessionWindow[] { window }; return specifics; } private EntitySpecifics makeTabEntity(String tag, String url, int id) { EntitySpecifics specifics = new EntitySpecifics(); specifics.session = new SessionSpecifics(); specifics.session.sessionTag = tag; specifics.session.tabNodeId = id; SessionTab tab = new SessionTab(); tab.tabId = id; tab.currentNavigationIndex = 0; TabNavigation nav = new TabNavigation(); nav.virtualUrl = url; tab.navigation = new TabNavigation[] { nav }; specifics.session.tab = tab; return specifics; } private void deleteServerTabsForClient(String clientName) throws JSONException { OpenTabs openTabs = getLocalTabsForClient(clientName); mFakeServerHelper.deleteEntity(openTabs.headerId); for (String tabId : openTabs.tabIds) { mFakeServerHelper.deleteEntity(tabId); } } private void waitForLocalTabsForClient(final String clientName, String... urls) throws InterruptedException { final List<String> urlList = new ArrayList<>(urls.length); for (String url : urls) urlList.add(url); pollInstrumentationThread(Criteria.equals(urlList, new Callable<List<String>>() { @Override public List<String> call() throws Exception { return getLocalTabsForClient(clientName).urls; } })); } private void waitForServerTabs(final String... urls) throws InterruptedException { pollInstrumentationThread( new Criteria("Expected server open tabs: " + Arrays.toString(urls)) { @Override public boolean isSatisfied() { try { return mFakeServerHelper.verifySessions(urls); } catch (Exception e) { throw new RuntimeException(e); } } }); } private String getClientName() throws Exception { pollInstrumentationThread(new Criteria("Expected at least one tab entity to exist.") { @Override public boolean isSatisfied() { try { return SyncTestUtil.getLocalData(mContext, OPEN_TABS_TYPE).size() > 0; } catch (JSONException e) { return false; } } }); List<Pair<String, JSONObject>> tabEntities = SyncTestUtil.getLocalData( mContext, OPEN_TABS_TYPE); for (Pair<String, JSONObject> tabEntity : tabEntities) { if (tabEntity.second.has("header")) { return tabEntity.second.getJSONObject("header").getString("client_name"); } } throw new IllegalStateException("No client name found."); } private static class HeaderInfo { public final String sessionTag; public final String headerId; public final List<String> tabIds; public HeaderInfo(String sessionTag, String headerId, List<String> tabIds) { this.sessionTag = sessionTag; this.headerId = headerId; this.tabIds = tabIds; } } // Distills the local session data into a simple data object for the given client. private OpenTabs getLocalTabsForClient(String clientName) throws JSONException { List<Pair<String, JSONObject>> tabEntities = SyncTestUtil.getLocalData( mContext, OPEN_TABS_TYPE); // Output lists. List<String> urls = new ArrayList<>(); List<String> tabEntityIds = new ArrayList<>(); HeaderInfo info = findHeaderInfoForClient(clientName, tabEntities); if (info.sessionTag == null) { // No client was found. Here we still want to return an empty list of urls. return new OpenTabs("", tabEntityIds, urls); } Map<String, String> tabIdsToUrls = new HashMap<>(); Map<String, String> tabIdsToEntityIds = new HashMap<>(); findTabMappings(info.sessionTag, tabEntities, tabIdsToUrls, tabIdsToEntityIds); // Convert the tabId list to the url list. for (String tabId : info.tabIds) { urls.add(tabIdsToUrls.get(tabId)); tabEntityIds.add(tabIdsToEntityIds.get(tabId)); } return new OpenTabs(info.headerId, tabEntityIds, urls); } // Find the header entity for clientName and extract its sessionTag and tabId list. private HeaderInfo findHeaderInfoForClient( String clientName, List<Pair<String, JSONObject>> tabEntities) throws JSONException { String sessionTag = null; String headerId = null; List<String> tabIds = new ArrayList<>(); for (Pair<String, JSONObject> tabEntity : tabEntities) { JSONObject header = tabEntity.second.optJSONObject("header"); if (header != null && header.getString("client_name").equals(clientName)) { sessionTag = tabEntity.second.getString("session_tag"); headerId = tabEntity.first; JSONArray windows = header.getJSONArray("window"); if (windows.length() == 0) { // The client was found but there are no tabs. break; } assertEquals("Only single windows are supported.", 1, windows.length()); JSONArray tabs = windows.getJSONObject(0).getJSONArray("tab"); for (int i = 0; i < tabs.length(); i++) { tabIds.add(tabs.getString(i)); } break; } } return new HeaderInfo(sessionTag, headerId, tabIds); } // Find the associated tabs and record their tabId -> url and entityId mappings. private void findTabMappings(String sessionTag, List<Pair<String, JSONObject>> tabEntities, // Populating these maps is the output of this function. Map<String, String> tabIdsToUrls, Map<String, String> tabIdsToEntityIds) throws JSONException { for (Pair<String, JSONObject> tabEntity : tabEntities) { JSONObject json = tabEntity.second; if (json.has("tab") && json.getString("session_tag").equals(sessionTag)) { JSONObject tab = json.getJSONObject("tab"); int i = tab.getInt("current_navigation_index"); String tabId = tab.getString("tab_id"); String url = tab.getJSONArray("navigation") .getJSONObject(i).getString("virtual_url"); tabIdsToUrls.put(tabId, url); tabIdsToEntityIds.put(tabId, tabEntity.first); } } } }
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
9eede2ac04d47f2425839e300857ac30bec9b3d4
f0ec508f4b480d8d5399a2880e4cbb0533fc2fc1
/com.gzedu.xlims.biz/src/main/java/com/gzedu/xlims/serviceImpl/exam/wk/dto/ExamRoomDistribute.java
a0df16a0c0264c4a512d9bfec8820912547ed0b3
[]
no_license
lizm335/MyLizm
a327bd4d08a33c79e9b6ef97144d63dae7114a52
1bcca82395b54d431fb26817e61a294f9d7dd867
refs/heads/master
2020-03-11T17:25:25.687426
2018-04-19T03:10:28
2018-04-19T03:10:28
130,146,458
3
0
null
null
null
null
UTF-8
Java
false
false
1,794
java
/** * Copyright(c) 2013 版权所有:广州远程教育中心 www.969300.com */ package com.gzedu.xlims.serviceImpl.exam.wk.dto; /** * 功能说明:考场分配 * * @author 李明 liming@eenet.com * @Date 2016年7月14日 * @version 2.5 * */ public class ExamRoomDistribute { String DISTRIBUTE_ID;// String 考室分配ID 否 String EXAM_ROOM_ID;// String 考室ID 否 String PROJECT_TERM_ID;// String 考试安排ID 否 String EXAM_ROOM_TYPE;// String 考试形式 是 线下offline 在线online String START_DT;// String 开始时间 是 String FINISH_DT;// String 结束时间 是 /** * @param dISTRIBUTE_ID * @param eXAM_ROOM_ID * @param pROJECT_TERM_ID */ public ExamRoomDistribute(String dISTRIBUTE_ID, String eXAM_ROOM_ID, String pROJECT_TERM_ID) { super(); DISTRIBUTE_ID = dISTRIBUTE_ID; EXAM_ROOM_ID = eXAM_ROOM_ID; PROJECT_TERM_ID = pROJECT_TERM_ID; } public String getDISTRIBUTE_ID() { return DISTRIBUTE_ID; } public void setDISTRIBUTE_ID(String dISTRIBUTE_ID) { DISTRIBUTE_ID = dISTRIBUTE_ID; } public String getEXAM_ROOM_ID() { return EXAM_ROOM_ID; } public void setEXAM_ROOM_ID(String eXAM_ROOM_ID) { EXAM_ROOM_ID = eXAM_ROOM_ID; } public String getPROJECT_TERM_ID() { return PROJECT_TERM_ID; } public void setPROJECT_TERM_ID(String pROJECT_TERM_ID) { PROJECT_TERM_ID = pROJECT_TERM_ID; } public String getEXAM_ROOM_TYPE() { return EXAM_ROOM_TYPE; } public void setEXAM_ROOM_TYPE(String eXAM_ROOM_TYPE) { EXAM_ROOM_TYPE = eXAM_ROOM_TYPE; } public String getSTART_DT() { return START_DT; } public void setSTART_DT(String sTART_DT) { START_DT = sTART_DT; } public String getFINISH_DT() { return FINISH_DT; } public void setFINISH_DT(String fINISH_DT) { FINISH_DT = fINISH_DT; } }
[ "lizengming@eenet.com" ]
lizengming@eenet.com
dce67e6646e3abce0ba7e07840eec590c3565080
554ddc83de16bcdf6d133241b3e71127cdafb1e5
/src/main/java/com/yiang/ssm/yrn/model/User.java
3c29a2dea7e72eab61ff797fd5b3de8f3cc67d44
[]
no_license
buildingMonster/ssm
640610cc3f33e6199b9fe4b6d75a5a39bf3f00c1
1aac5ad124540c5af1b0be46d366052dae47126e
refs/heads/master
2020-04-25T14:21:51.586524
2019-03-01T01:31:40
2019-03-01T01:31:40
172,839,383
0
0
null
null
null
null
UTF-8
Java
false
false
4,800
java
package com.yiang.ssm.yrn.model; import java.util.Date; public class User { private String user_id; private String user_name; private String user_password; private Integer user_flag; private String user_email; private String user_phone; private String user_sex; private Date user_register_date; private String user_qq; private Date user_lastlogin_date; private String user_lastlogin_ip; private String user_signature; private String user_image; private String user_birthdaty; private String user_address; private String user_profession; private String user_school; public User(String user_id, String user_name, String user_password, Integer user_flag, String user_email, String user_phone, String user_sex, Date user_register_date, String user_qq, Date user_lastlogin_date, String user_lastlogin_ip, String user_signature, String user_image, String user_birthdaty, String user_address, String user_profession, String user_school) { this.user_id = user_id; this.user_name = user_name; this.user_password = user_password; this.user_flag = user_flag; this.user_email = user_email; this.user_phone = user_phone; this.user_sex = user_sex; this.user_register_date = user_register_date; this.user_qq = user_qq; this.user_lastlogin_date = user_lastlogin_date; this.user_lastlogin_ip = user_lastlogin_ip; this.user_signature = user_signature; this.user_image = user_image; this.user_birthdaty = user_birthdaty; this.user_address = user_address; this.user_profession = user_profession; this.user_school = user_school; } public User() { super(); } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public String getUser_password() { return user_password; } public void setUser_password(String user_password) { this.user_password = user_password; } public Integer getUser_flag() { return user_flag; } public void setUser_flag(Integer user_flag) { this.user_flag = user_flag; } public String getUser_email() { return user_email; } public void setUser_email(String user_email) { this.user_email = user_email; } public String getUser_phone() { return user_phone; } public void setUser_phone(String user_phone) { this.user_phone = user_phone; } public String getUser_sex() { return user_sex; } public void setUser_sex(String user_sex) { this.user_sex = user_sex; } public Date getUser_register_date() { return user_register_date; } public void setUser_register_date(Date user_register_date) { this.user_register_date = user_register_date; } public String getUser_qq() { return user_qq; } public void setUser_qq(String user_qq) { this.user_qq = user_qq; } public Date getUser_lastlogin_date() { return user_lastlogin_date; } public void setUser_lastlogin_date(Date user_lastlogin_date) { this.user_lastlogin_date = user_lastlogin_date; } public String getUser_lastlogin_ip() { return user_lastlogin_ip; } public void setUser_lastlogin_ip(String user_lastlogin_ip) { this.user_lastlogin_ip = user_lastlogin_ip; } public String getUser_signature() { return user_signature; } public void setUser_signature(String user_signature) { this.user_signature = user_signature; } public String getUser_image() { return user_image; } public void setUser_image(String user_image) { this.user_image = user_image; } public String getUser_birthdaty() { return user_birthdaty; } public void setUser_birthdaty(String user_birthdaty) { this.user_birthdaty = user_birthdaty; } public String getUser_address() { return user_address; } public void setUser_address(String user_address) { this.user_address = user_address; } public String getUser_profession() { return user_profession; } public void setUser_profession(String user_profession) { this.user_profession = user_profession; } public String getUser_school() { return user_school; } public void setUser_school(String user_school) { this.user_school = user_school; } }
[ "1905566173@qq.com" ]
1905566173@qq.com
c56ef490d11cc82ea1e80c7fc89880dabe5dcdf6
2817e620defafc279aea7abd7382d9907c6f8bd1
/manager/src/main/java/io/atomix/manager/util/ResourceManagerTypeResolver.java
c5e69f8cac838d1fafce418bb50925db701c4315
[ "Apache-2.0" ]
permissive
dmvk/atomix
23f820bc4e97a3088982809addbfe8b698414728
559f25a06324746d7fbb71947ac2c2b546386fa7
refs/heads/master
2021-01-22T04:41:01.901860
2016-04-13T19:36:37
2016-04-13T19:36:37
56,785,227
0
0
null
null
null
null
UTF-8
Java
false
false
2,012
java
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package io.atomix.manager.util; import io.atomix.catalyst.serializer.SerializableTypeResolver; import io.atomix.catalyst.serializer.SerializerRegistry; import io.atomix.manager.internal.*; import io.atomix.resource.ResourceType; import io.atomix.resource.internal.InstanceTypeResolver; import io.atomix.resource.internal.ResourceCommand; import io.atomix.resource.internal.ResourceQuery; /** * Resource manager serializable type resolver. * * @author <a href="http://github.com/kuujo>Jordan Halterman</a> */ public class ResourceManagerTypeResolver implements SerializableTypeResolver { @Override public void resolve(SerializerRegistry registry) { // Register instance types. registry.resolve(new InstanceTypeResolver()); // Register resource state machine types. registry.register(ResourceCommand.class, -50); registry.register(ResourceQuery.class, -51); registry.register(ResourceCommand.Config.class, -52); registry.register(ResourceCommand.Delete.class, -53); registry.register(ResourceType.class, -54); // Register resource manager types. registry.register(GetResource.class, -58); registry.register(GetResourceIfExists.class, -59); registry.register(GetResourceKeys.class, -60); registry.register(ResourceExists.class, -61); registry.register(CloseResource.class, -62); registry.register(DeleteResource.class, -63); } }
[ "jordan.halterman@gmail.com" ]
jordan.halterman@gmail.com
2f1b380ebbb8bbfbc048b82597e74a43ffde1810
9a2400d5e803e5ee22fef7a0bd6d7a8d976e60ba
/src/test/java/br/com/dio/pointcontrol/PointControlApplicationTests.java
0e1a01d94cf0aee83c2b2c8faf70e7bb7ed52506
[]
no_license
CalelCosta/PointController
185b4343da21621f40f95627438f3d2f467fefc1
595fb498821c71fbf77ffdbf93f3f75b5fcf1d18
refs/heads/master
2023-07-08T22:34:54.627111
2021-08-09T00:27:42
2021-08-09T00:27:42
394,050,886
0
0
null
null
null
null
UTF-8
Java
false
false
230
java
package br.com.dio.pointcontrol; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class PointControlApplicationTests { @Test void contextLoads() { } }
[ "calel.costa@gmail.com" ]
calel.costa@gmail.com
32b69452b5e03688c3d229a9b9c4e98d3e080bf4
79990b9f9ba15a6908dfb0a5ccfec46d85eeabf6
/Ch04_TreesAndGraphs/Five.java
a1d64827738bc0e5c5a584423c1aa6c2e87351d6
[ "MIT" ]
permissive
deepcover96/coding-problems
3b8c49221f6b8d8420df3e015a858a7f7b67b9d2
6f16773b1aa85d5417746d6e57e8a95c494a0e5d
refs/heads/master
2021-01-18T20:40:10.991511
2017-07-23T23:37:03
2017-07-23T23:37:03
86,984,171
0
0
null
null
null
null
UTF-8
Java
false
false
1,582
java
import java.util.*; class Five { public static void main(String[] args) { int[] arr = new int[] {1,2,3,4,5,6,7,8,9,10,20,45,55,56,67,69,100,111}; // create a binary tree using the method from problem Two. TreeNode root = Two.createTree(arr); TreeNode.print(root); boolean isBst = isBinarySearchTree(root); System.out.println("Is BST: " + isBst); TreeNode node7 = new TreeNode(7); TreeNode node6 = new TreeNode(6); TreeNode node5 = new TreeNode(5); TreeNode node4 = new TreeNode(4); TreeNode node3 = new TreeNode(3); TreeNode node2 = new TreeNode(2); TreeNode node1 = new TreeNode(1); TreeNode node0 = new TreeNode(0); node5.setRight(node6); node6.setRight(node7); //node6.setLeft(node0); // makes it fail node5.setLeft(node3); node3.setRight(node4); node3.setLeft(node2); node2.setLeft(node1); TreeNode.print(node5); isBst = isBinarySearchTree(node5); System.out.println("Is BST: " + isBst); } // Validate BST: Implement a function to check if a binary tree is a // binary search tree. public static boolean isBinarySearchTree(TreeNode root) { return isBst(root, null, null); } private static boolean isBst(TreeNode node, Integer low, Integer high) { if (node == null) return true; int val = node.getValue(); if (low != null && val <= low) return false; if (high != null && val > high) return false; boolean left = isBst(node.getLeft(), low, node.getValue()); boolean right = isBst(node.getRight(), node.getValue(), high); return left && right; } }
[ "wil.ruiz@gmail.com" ]
wil.ruiz@gmail.com
91ce3d45c8f964cf4fc86ef394235e2b1294b7dd
54dab4c3a1362823399897ca426092b91c92b61d
/src/common/LoginManager.java
9a7accffdb2337237882a09ca18ebeb1c72a7715
[]
no_license
jableader/FS_Assignment
7b6a6721078905899ce245d1d5661e94d81b5906
f08b73b59423d7f2bb052e51b690969299272353
refs/heads/master
2020-12-30T19:44:59.385084
2015-06-03T22:42:58
2015-06-03T22:42:58
35,246,966
0
0
null
null
null
null
UTF-8
Java
false
false
1,697
java
package common; import logging.LogType; import logging.Logger; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import static common.Tools.fromBase64; public class LoginManager { protected Map<String, Login> users = new HashMap<>(); protected final Logger logger; public LoginManager(Logger logger, Iterable<Login> logins) { this.logger = logger; for (Login l : logins) addLogin(l); logger.Log(LogType.Standard, "Loaded " + users.size() + " users"); } public LoginManager(Logger logger, File source) { this.logger = logger; try { logger.Log(LogType.Standard, "Loading logins from file"); Scanner sc = new Scanner(new FileInputStream(source)); while (sc.hasNextLine()) { String[] details = sc.nextLine().split(" "); addLogin(new Login(details[0], fromBase64(details[1]))); } } catch (IOException ex) { logger.Log(LogType.Warning, "Could not load from logins.txt"); } if (users.size() == 0) { addLogin(new Login("bob", "password123".getBytes())); } logger.Log(LogType.Standard, "Loaded " + users.size() + " users"); } protected void addLogin(Login login) { logger.Log(LogType.Verbose, "Adding user " + login.id); users.put(login.id, login); } public Login getLogin(String id) { Login l = users.get(id); logger.Log(LogType.Verbose, "Looking for user " + id + "; Found: " + (l != null)); return l; } }
[ "jacobdunk@gmail.com" ]
jacobdunk@gmail.com
f93125341b8172e58b1f96b52e0cf98e0536be08
3c6f4bb030a42d19ce8c25a931138641fb6fd495
/finance-user/finance-user-model/src/main/java/com/hongkun/finance/user/utils/IDCardUtil.java
bacadc65a7697b27209551e8084dcf98f2eecf73
[]
no_license
happyjianguo/finance-hkjf
93195df26ebb81a8b951a191e25ab6267b73aaca
0389a6eac966ee2e4887b6db4f99183242ba2d4e
refs/heads/master
2020-07-28T13:42:40.924633
2019-08-03T00:22:19
2019-08-03T00:22:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,115
java
package com.hongkun.finance.user.utils; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; /** * add by mzx 2016-08-29 * 身份证验证的工具(支持5位或18位省份证) * 身份证号码结构: * 17位数字和1位校验码:6位地址码数字,8位生日数字,3位出生时间顺序号,1位校验码。 * 地址码(前6位):表示对象常住户口所在县(市、镇、区)的行政区划代码,按GB/T2260的规定执行。 * 出生日期码,(第七位 至十四位):表示编码对象出生年、月、日,按GB按GB/T7408的规定执行,年、月、日代码之间不用分隔符。 * 顺序码(第十五位至十七位):表示在同一地址码所标示的区域范围内,对同年、同月、同日出生的人编订的顺序号, * 顺序码的奇数分配给男性,偶数分配给女性。 * 校验码(第十八位数): * 十七位数字本体码加权求和公式 s = sum(Ai*Wi), i = 0,,16,先对前17位数字的权求和; * Ai:表示第i位置上的身份证号码数字值.Wi:表示第i位置上的加权因.Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2; * 计算模 Y = mod(S, 11) * 通过模得到对应的校验码 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码: 1 0 X 9 8 7 6 5 4 3 2 */ public class IDCardUtil { static final Map<Integer, String> zoneNum = new HashMap<>(); static { zoneNum.put(11, "北京"); zoneNum.put(12, "天津"); zoneNum.put(13, "河北"); zoneNum.put(14, "山西"); zoneNum.put(15, "内蒙古"); zoneNum.put(21, "辽宁"); zoneNum.put(22, "吉林"); zoneNum.put(23, "黑龙江"); zoneNum.put(31, "上海"); zoneNum.put(32, "江苏"); zoneNum.put(33, "浙江"); zoneNum.put(34, "安徽"); zoneNum.put(35, "福建"); zoneNum.put(36, "江西"); zoneNum.put(37, "山东"); zoneNum.put(41, "河南"); zoneNum.put(42, "湖北"); zoneNum.put(43, "湖南"); zoneNum.put(44, "广东"); zoneNum.put(45, "广西"); zoneNum.put(46, "海南"); zoneNum.put(50, "重庆"); zoneNum.put(51, "四川"); zoneNum.put(52, "贵州"); zoneNum.put(53, "云南"); zoneNum.put(54, "西藏"); zoneNum.put(61, "陕西"); zoneNum.put(62, "甘肃"); zoneNum.put(63, "青海"); zoneNum.put(64, "新疆"); zoneNum.put(71, "台湾"); zoneNum.put(81, "香港"); zoneNum.put(82, "澳门"); zoneNum.put(91, "外国"); } static final int[] PARITYBIT = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'}; static final int[] POWER_LIST = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; /** * 身份证验证 *@param s 号码内容 *@return 是否有效 null和"" 都是false */ public static boolean isIDCard(String certNo){ if(certNo == null || (certNo.length() != 15 && certNo.length() != 18)) return false; final char[] cs = certNo.toUpperCase().toCharArray(); //校验位数 int power = 0; for(int i=0; i<cs.length; i++){ if(i==cs.length-1 && cs[i] == 'X') break;//最后一位可以 是X或x if(cs[i]<'0' || cs[i]>'9') return false; if(i < cs.length -1){ power += (cs[i] - '0') * POWER_LIST[i]; } } //校验区位码 if(!zoneNum.containsKey(Integer.valueOf(certNo.substring(0,2)))){ return false; } //校验年份 String year = certNo.length() == 15 ? getIdcardCalendar() + certNo.substring(6,8) :certNo.substring(6, 10); final int iyear = Integer.parseInt(year); if(iyear < 1900 || iyear > Calendar.getInstance().get(Calendar.YEAR)) return false;//1900年的PASS,超过今年的PASS //校验月份 String month = certNo.length() == 15 ? certNo.substring(8, 10) : certNo.substring(10,12); final int imonth = Integer.parseInt(month); if(imonth <1 || imonth >12){ return false; } //校验天数 String day = certNo.length() ==15 ? certNo.substring(10, 12) : certNo.substring(12, 14); final int iday = Integer.parseInt(day); if(iday < 1 || iday > 31) return false; //校验"校验码" if(certNo.length() == 15) return true; return cs[cs.length -1 ] == PARITYBIT[power % 11]; } private static int getIdcardCalendar() { GregorianCalendar curDay = new GregorianCalendar(); int curYear = curDay.get(Calendar.YEAR); return Integer.parseInt(String.valueOf(curYear).substring(2)); } public static void main(String[] args) { boolean mark = isIDCard("23"); System.out.println(mark); } }
[ "zc.ding@foxmail.com" ]
zc.ding@foxmail.com
75f1407ac7a5d57927b2a98a271e32a8045b8a56
3c898029f96d19e15f46fe881bba19420ee8b77e
/src/main/java/cloud/estimator/user/config/DatabaseConfiguration.java
a2209894aed274b968e4ad3e3137f87cf15ffe5f
[]
no_license
cloud-estimator/user-service
4d53006070d4d1801a44d5231564b4f3d8e70526
dd2f851ab9b36b14b1fcd6a3ddd96e6f7823679d
refs/heads/master
2020-03-10T08:53:40.497631
2018-05-22T22:13:44
2018-05-22T22:13:44
129,296,782
0
0
null
null
null
null
UTF-8
Java
false
false
683
java
package cloud.estimator.user.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.AuditorAware; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.transaction.annotation.EnableTransactionManagement; import cloud.estimator.user.security.SpringSecurityAuditorAware; @Configuration @EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware") @EnableTransactionManagement public class DatabaseConfiguration { @Bean AuditorAware<String> auditorProvider() { return new SpringSecurityAuditorAware(); } }
[ "dharminder@stellar.aero" ]
dharminder@stellar.aero