blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
โŒ€
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
914b1948ef82f19175ae2206065594de13ebf373
f62d14014018e7f29c6fcaed2a3a4d358ba75585
/abc098_a/Main.java
7d0efbfcad38a0db5f3588a06580c3fb4d3e66d8
[]
no_license
charles-wangkai/atcoder
b84ae7ef6ef32d611b5a68a13d0566a0695b26f1
603115202d7ed1768694801d9f722d6a0324b615
refs/heads/master
2023-01-27T20:59:54.086893
2020-12-07T12:04:45
2020-12-07T12:04:45
257,650,353
0
0
null
null
null
null
UTF-8
Java
false
false
368
java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int A = sc.nextInt(); int B = sc.nextInt(); System.out.println(solve(A, B)); sc.close(); } static int solve(int A, int B) { return Math.max(Math.max(A + B, A - B), A * B); } }
[ "charles.wangkai@gmail.com" ]
charles.wangkai@gmail.com
aa8d0c5e4e8d711865c636333f6b200a193d7cbc
9ed7d55fac670dbb473dccd92d7f4582b2a3daf1
/hongbaoPlus/src/main/java/chinaums/dao/impl/HongBaoPlusDaoImpl.java
6d4915016ae7297fe341f7034aaaaeb342603a84
[]
no_license
wustnlp/hongbaoPlus
c55829ba9c0307e2fa3dce7724b6693843f6a34c
ac41475afe803ce2157dc77eced70fda93fdf73e
refs/heads/master
2021-01-23T02:40:04.647847
2017-03-23T01:42:29
2017-03-23T01:42:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,321
java
package chinaums.dao.impl; import java.io.Serializable; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import chinaums.dao.BaseDaoI; import chinaums.model.THongBaoPlus; @Repository("HongBaoPlusDao") public class HongBaoPlusDaoImpl implements BaseDaoI<THongBaoPlus> { private Logger log = Logger.getLogger(HongBaoPlusDaoImpl.class); private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public Serializable save(THongBaoPlus o) { // TODO Auto-generated method stub sessionFactory.getCurrentSession().save(o); sessionFactory.getCurrentSession().flush(); return null; } @Override public THongBaoPlus getByHql(String hql, Map<String, Object> params) { // TODO Auto-generated method stub Query q=sessionFactory.getCurrentSession().createQuery(hql); if(params!=null&&!params.isEmpty()){ for(String key:params.keySet()){ q.setParameter(key, params.get(key)); } } List<THongBaoPlus> l = q.list(); if (l != null && l.size() > 0) { return l.get(0); } return null; } public List<THongBaoPlus> getAllByHql(String hql, Map<String, Object> params) { // TODO Auto-generated method stub Query q=sessionFactory.getCurrentSession().createQuery(hql); if(params!=null&&!params.isEmpty()){ for(String key:params.keySet()){ q.setParameter(key, params.get(key)); } } List<THongBaoPlus> l = q.list(); if (l != null && l.size() > 0) { return l; } return null; } @SuppressWarnings("finally") @Override public int save(List<THongBaoPlus> list) { // TODO Auto-generated method stub int len = list.size(); int i = 0; for (; i < len; i++) { sessionFactory.getCurrentSession().save(list.get(i)); if (i % 20 == 19) { sessionFactory.getCurrentSession().flush(); sessionFactory.getCurrentSession().clear(); } } return i; } @Override public int countByHql(String hql) { // TODO Auto-generated method stub Query query = sessionFactory.getCurrentSession().createQuery(hql); return (Integer) query.uniqueResult(); } @Override public int countByHql(String hql, Map<String, Object> params) { // TODO Auto-generated method stub return 0; } @Override public THongBaoPlus getByHql(String hql) { // TODO Auto-generated method stub Query q = sessionFactory.getCurrentSession().createQuery(hql); List<THongBaoPlus> l = q.list(); if (l != null && l.size() > 0) { return l.get(0); } return null; } @Override public int update(String hql,Map<String, Object> params) { // TODO Auto-generated method stub Query q=sessionFactory.getCurrentSession().createQuery(hql); if(params!=null&&!params.isEmpty()){ for(String key:params.keySet()){ q.setParameter(key, params.get(key)); } } int deteleEntity=q.executeUpdate(); return deteleEntity; } @Override public int updates(String hql, String[] id,Map<String, Object> params) { // TODO Auto-generated method stub Query q=sessionFactory.getCurrentSession().createQuery(hql); if(params!=null&&!params.isEmpty()){ for(String key:params.keySet()){ q.setParameter(key, params.get(key)); } } q.setParameterList("id", id); return q.executeUpdate(); } @Override public List<THongBaoPlus> find(String hql, int page, int rows) { // TODO Auto-generated method stub Query q = sessionFactory.getCurrentSession().createQuery(hql); return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list(); } @Override public void update(THongBaoPlus t) { // TODO Auto-generated method stub //sessionFactory.getCurrentSession().update(t); //sessionFactory.getCurrentSession().flush(); String userid = t.getUserid(); Integer amount = t.getAmount(); String sql = "update t_hongbao_plus set amount=%s where userid='%s'"; sql = String.format(sql, amount, userid); Query q=sessionFactory.getCurrentSession().createSQLQuery(sql); q.executeUpdate(); } @Override public List<THongBaoPlus> find(String hql, Map<String, Object> params, int page,int rows) { Query q=sessionFactory.getCurrentSession().createQuery(hql); if(params!=null&&!params.isEmpty()){ for(String key:params.keySet()){ q.setParameter(key, params.get(key)); } } return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list(); } @Override public List<THongBaoPlus> find(String hql, Map<String, Object> params) { // TODO Auto-generated method stub Query q=sessionFactory.getCurrentSession().createQuery(hql); if(params!=null&&!params.isEmpty()){ for(String key:params.keySet()){ q.setParameter(key, params.get(key)); } } return q.list(); } @Override public Long count(String hql) { Query q=sessionFactory.getCurrentSession().createQuery(hql); return (Long) q.uniqueResult(); } @Override public List<THongBaoPlus> find(String hql) { Query q=sessionFactory.getCurrentSession().createQuery(hql); return q.list(); } }
[ "sunxiaolei1989@gmail.com" ]
sunxiaolei1989@gmail.com
2f5d8e9ee5de71f70e484e849228e385fefcd7f0
5646286478a88828ecc121ff53a3e2bfbe497651
/src/main/java/io/github/cepr0/demo/person/service/CarService.java
85477472bbbc1c0469b3eddf9b877640b85656f9
[]
no_license
Cepr0/sb-mongo-generic-crud-demo
35b963065e05334e5d1900a5aa323b91cec9fc9a
95fae8af9574d9086eb50b2d591fa93034825dd7
refs/heads/master
2020-05-16T05:19:01.460389
2019-05-11T10:01:17
2019-05-11T10:01:17
182,813,043
0
1
null
null
null
null
UTF-8
Java
false
false
979
java
package io.github.cepr0.demo.person.service; import io.github.cepr0.crud.event.EntityEvent; import io.github.cepr0.crud.service.AbstractCrudService; import io.github.cepr0.demo.model.Car; import io.github.cepr0.demo.person.dto.CarRequest; import io.github.cepr0.demo.person.dto.CarResponse; import io.github.cepr0.demo.person.mapper.CarMapper; import io.github.cepr0.demo.person.repo.CarRepo; import org.springframework.stereotype.Service; @Service public class CarService extends AbstractCrudService<Car, String, CarRequest, CarResponse> { public CarService(final CarRepo repo, final CarMapper mapper) { super(repo, mapper); } @Override protected EntityEvent<Car> onCreateEvent(final Car entity) { return new CarCreateEvent(entity); } @Override protected EntityEvent<Car> onUpdateEvent(final Car entity) { return new CarUpdateEvent(entity); } @Override protected EntityEvent<Car> onDeleteEvent(final Car entity) { return new CarDeleteEvent(entity); } }
[ "cepr0@ukr.net" ]
cepr0@ukr.net
a395f28afe8b20caf3f681f84b8f9a0eb07a4643
5ec43b22e8ce82bfc5e9cba3cdbae01fd1a38dfc
/src/controller/UserEntryFormController.java
c02e3b2e2591ffa47e8192120eff6b4b25449af4
[]
no_license
unasd/test2
85021089c64858be66479fbd01d058755e263f02
110b03e724c1a1846fd711bb830759ff7cfdd40a
refs/heads/master
2020-04-14T03:11:34.234780
2015-02-28T12:53:13
2015-02-28T12:53:13
31,462,589
0
0
null
null
null
null
UTF-8
Java
false
false
4,048
java
package controller; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpSession; import logic.Shop; import logic.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.context.MessageSource; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import dao.UserDaoImpl; import utils.UserEntryValidator; import utils.WebConstants; @Controller public class UserEntryFormController { @Autowired private Shop shopService; @Autowired private UserEntryValidator userEntryValidator; @Autowired private MessageSource messageSource; @Autowired private UserDaoImpl userDaoImpl; @RequestMapping(method = RequestMethod.GET) public String toUserEntryView() { return "userentryform/userEntry"; } // ์œ ์ € ์ •๋ณด ์ˆ˜์ • ํŽ˜์ด์ง€ ์ด๋™ @RequestMapping(value="/userModify.html", method = RequestMethod.GET) public ModelAndView userModify(HttpSession session) { User loginUser = (User) session.getAttribute(WebConstants.USER_KEY); //userDaoImpl.findByUserIdAndPassword(userId, password); ModelAndView view = new ModelAndView(); view.setViewName("userentryform/userModify"); view.addObject("loginUser", loginUser); return view; } // ์œ ์ € ์ •๋ณด ์ˆ˜์ • ํผ ์ „์†ก @RequestMapping(value="/userModify.html", method = RequestMethod.POST) public ModelAndView userModifySubmit(User user, HttpSession session) { User loginUser = (User) session.getAttribute(WebConstants.USER_KEY); ModelAndView view = new ModelAndView(); view.setViewName("userentryform/userModifySuccess"); view.addObject("loginUser", loginUser); userDaoImpl.modify(user); return view; } @ModelAttribute public User setUpForm() { User user = new User(); MessageSourceAccessor accessor = new MessageSourceAccessor(this.messageSource); user.setUserId(accessor.getMessage("user.userId.default")); user.setUserName(accessor.getMessage("user.userName.default")); return user; } @InitBinder public void initBinder(WebDataBinder binder) throws Exception { // Date ํƒ€์ž…์ธ birthDay ํ”„๋กœํผํ‹ฐ๋ฅผ ์ปค์Šคํ„ฐ๋งˆ์ด์ฆˆ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, "birthDay", new CustomDateEditor(dateFormat, false)); } @RequestMapping(method = RequestMethod.POST) public ModelAndView onSubmit(User user, BindingResult bindingResult, HttpSession session) throws Exception { this.userEntryValidator.validate(user, bindingResult); ModelAndView modelAndView = new ModelAndView(); if (bindingResult.hasErrors()) { modelAndView.getModel().putAll(bindingResult.getModel()); return modelAndView; } try { this.shopService.entryUser(user); session.setAttribute(WebConstants.USER_KEY, user); if (this.shopService.getCart() == null) { session.setAttribute(WebConstants.CART_KEY, this.shopService.getCart()); } modelAndView.setViewName("userentryform/userEntrySuccess"); modelAndView.addObject("user", user); return modelAndView; } catch (DataIntegrityViolationException e) { // ์œ ์ €ID ์ค‘๋ณต ์‹œ, ํผ์„ ์†ก์‹ ํ–ˆ๋˜ ๊ณณ์œผ๋กœ ์ด๋™ bindingResult.reject("error.duplicate.user"); modelAndView.getModel().putAll(bindingResult.getModel()); return modelAndView; } } }
[ "secondlinedragonfly@gmail.com" ]
secondlinedragonfly@gmail.com
8b6e44f362be4142caa6df43dee0c3a99a4fefad
9cf92cd17f7979d7a80f71bffee49564272280fe
/java-recommender/google-cloud-recommender/src/test/java/com/google/cloud/recommender/v1beta1/RecommenderClientHttpJsonTest.java
67da760a8bff3fbde96fe2419c5d0471c8fc472c
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
sumodgeorge/google-cloud-java
32aea14097af929420b25abf71443aa22286e88b
389ac8dca201302a2ceb2299b32eb69fd0d79077
refs/heads/master
2023-08-31T10:56:49.958206
2023-08-17T21:26:13
2023-08-17T21:26:13
162,004,285
0
0
Apache-2.0
2023-06-27T15:15:51
2018-12-16T13:33:36
Java
UTF-8
Java
false
false
56,597
java
/* * Copyright 2023 Google LLC * * 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 * * https://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.google.cloud.recommender.v1beta1; import static com.google.cloud.recommender.v1beta1.RecommenderClient.ListInsightsPagedResponse; import static com.google.cloud.recommender.v1beta1.RecommenderClient.ListRecommendationsPagedResponse; import com.google.api.gax.core.NoCredentialsProvider; import com.google.api.gax.httpjson.GaxHttpJsonProperties; import com.google.api.gax.httpjson.testing.MockHttpService; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ApiException; import com.google.api.gax.rpc.ApiExceptionFactory; import com.google.api.gax.rpc.InvalidArgumentException; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.testing.FakeStatusCode; import com.google.cloud.recommender.v1beta1.stub.HttpJsonRecommenderStub; import com.google.common.collect.Lists; import com.google.protobuf.Duration; import com.google.protobuf.FieldMask; import com.google.protobuf.Struct; import com.google.protobuf.Timestamp; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Generated; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @Generated("by gapic-generator-java") public class RecommenderClientHttpJsonTest { private static MockHttpService mockService; private static RecommenderClient client; @BeforeClass public static void startStaticServer() throws IOException { mockService = new MockHttpService( HttpJsonRecommenderStub.getMethodDescriptors(), RecommenderSettings.getDefaultEndpoint()); RecommenderSettings settings = RecommenderSettings.newHttpJsonBuilder() .setTransportChannelProvider( RecommenderSettings.defaultHttpJsonTransportProviderBuilder() .setHttpTransport(mockService) .build()) .setCredentialsProvider(NoCredentialsProvider.create()) .build(); client = RecommenderClient.create(settings); } @AfterClass public static void stopServer() { client.close(); } @Before public void setUp() {} @After public void tearDown() throws Exception { mockService.reset(); } @Test public void listInsightsTest() throws Exception { Insight responsesElement = Insight.newBuilder().build(); ListInsightsResponse expectedResponse = ListInsightsResponse.newBuilder() .setNextPageToken("") .addAllInsights(Arrays.asList(responsesElement)) .build(); mockService.addResponse(expectedResponse); InsightTypeName parent = InsightTypeName.ofProjectLocationInsightTypeName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]"); ListInsightsPagedResponse pagedListResponse = client.listInsights(parent); List<Insight> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getInsightsList().get(0), resources.get(0)); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void listInsightsExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { InsightTypeName parent = InsightTypeName.ofProjectLocationInsightTypeName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]"); client.listInsights(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listInsightsTest2() throws Exception { Insight responsesElement = Insight.newBuilder().build(); ListInsightsResponse expectedResponse = ListInsightsResponse.newBuilder() .setNextPageToken("") .addAllInsights(Arrays.asList(responsesElement)) .build(); mockService.addResponse(expectedResponse); String parent = "projects/project-8290/locations/location-8290/insightTypes/insightType-8290"; ListInsightsPagedResponse pagedListResponse = client.listInsights(parent); List<Insight> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getInsightsList().get(0), resources.get(0)); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void listInsightsExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String parent = "projects/project-8290/locations/location-8290/insightTypes/insightType-8290"; client.listInsights(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getInsightTest() throws Exception { Insight expectedResponse = Insight.newBuilder() .setName( InsightName.ofProjectLocationInsightTypeInsightName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]") .toString()) .setDescription("description-1724546052") .addAllTargetResources(new ArrayList<String>()) .setInsightSubtype("insightSubtype841535170") .setContent(Struct.newBuilder().build()) .setLastRefreshTime(Timestamp.newBuilder().build()) .setObservationPeriod(Duration.newBuilder().build()) .setStateInfo(InsightStateInfo.newBuilder().build()) .setEtag("etag3123477") .addAllAssociatedRecommendations(new ArrayList<Insight.RecommendationReference>()) .build(); mockService.addResponse(expectedResponse); InsightName name = InsightName.ofProjectLocationInsightTypeInsightName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"); Insight actualResponse = client.getInsight(name); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void getInsightExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { InsightName name = InsightName.ofProjectLocationInsightTypeInsightName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"); client.getInsight(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getInsightTest2() throws Exception { Insight expectedResponse = Insight.newBuilder() .setName( InsightName.ofProjectLocationInsightTypeInsightName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]") .toString()) .setDescription("description-1724546052") .addAllTargetResources(new ArrayList<String>()) .setInsightSubtype("insightSubtype841535170") .setContent(Struct.newBuilder().build()) .setLastRefreshTime(Timestamp.newBuilder().build()) .setObservationPeriod(Duration.newBuilder().build()) .setStateInfo(InsightStateInfo.newBuilder().build()) .setEtag("etag3123477") .addAllAssociatedRecommendations(new ArrayList<Insight.RecommendationReference>()) .build(); mockService.addResponse(expectedResponse); String name = "projects/project-3636/locations/location-3636/insightTypes/insightType-3636/insights/insight-3636"; Insight actualResponse = client.getInsight(name); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void getInsightExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String name = "projects/project-3636/locations/location-3636/insightTypes/insightType-3636/insights/insight-3636"; client.getInsight(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void markInsightAcceptedTest() throws Exception { Insight expectedResponse = Insight.newBuilder() .setName( InsightName.ofProjectLocationInsightTypeInsightName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]") .toString()) .setDescription("description-1724546052") .addAllTargetResources(new ArrayList<String>()) .setInsightSubtype("insightSubtype841535170") .setContent(Struct.newBuilder().build()) .setLastRefreshTime(Timestamp.newBuilder().build()) .setObservationPeriod(Duration.newBuilder().build()) .setStateInfo(InsightStateInfo.newBuilder().build()) .setEtag("etag3123477") .addAllAssociatedRecommendations(new ArrayList<Insight.RecommendationReference>()) .build(); mockService.addResponse(expectedResponse); InsightName name = InsightName.ofProjectLocationInsightTypeInsightName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"); Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; Insight actualResponse = client.markInsightAccepted(name, stateMetadata, etag); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void markInsightAcceptedExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { InsightName name = InsightName.ofProjectLocationInsightTypeInsightName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]"); Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; client.markInsightAccepted(name, stateMetadata, etag); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void markInsightAcceptedTest2() throws Exception { Insight expectedResponse = Insight.newBuilder() .setName( InsightName.ofProjectLocationInsightTypeInsightName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]", "[INSIGHT]") .toString()) .setDescription("description-1724546052") .addAllTargetResources(new ArrayList<String>()) .setInsightSubtype("insightSubtype841535170") .setContent(Struct.newBuilder().build()) .setLastRefreshTime(Timestamp.newBuilder().build()) .setObservationPeriod(Duration.newBuilder().build()) .setStateInfo(InsightStateInfo.newBuilder().build()) .setEtag("etag3123477") .addAllAssociatedRecommendations(new ArrayList<Insight.RecommendationReference>()) .build(); mockService.addResponse(expectedResponse); String name = "projects/project-3636/locations/location-3636/insightTypes/insightType-3636/insights/insight-3636"; Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; Insight actualResponse = client.markInsightAccepted(name, stateMetadata, etag); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void markInsightAcceptedExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String name = "projects/project-3636/locations/location-3636/insightTypes/insightType-3636/insights/insight-3636"; Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; client.markInsightAccepted(name, stateMetadata, etag); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listRecommendationsTest() throws Exception { Recommendation responsesElement = Recommendation.newBuilder().build(); ListRecommendationsResponse expectedResponse = ListRecommendationsResponse.newBuilder() .setNextPageToken("") .addAllRecommendations(Arrays.asList(responsesElement)) .build(); mockService.addResponse(expectedResponse); RecommenderName parent = RecommenderName.ofProjectLocationRecommenderName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]"); String filter = "filter-1274492040"; ListRecommendationsPagedResponse pagedListResponse = client.listRecommendations(parent, filter); List<Recommendation> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getRecommendationsList().get(0), resources.get(0)); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void listRecommendationsExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { RecommenderName parent = RecommenderName.ofProjectLocationRecommenderName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]"); String filter = "filter-1274492040"; client.listRecommendations(parent, filter); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listRecommendationsTest2() throws Exception { Recommendation responsesElement = Recommendation.newBuilder().build(); ListRecommendationsResponse expectedResponse = ListRecommendationsResponse.newBuilder() .setNextPageToken("") .addAllRecommendations(Arrays.asList(responsesElement)) .build(); mockService.addResponse(expectedResponse); String parent = "projects/project-6437/locations/location-6437/recommenders/recommender-6437"; String filter = "filter-1274492040"; ListRecommendationsPagedResponse pagedListResponse = client.listRecommendations(parent, filter); List<Recommendation> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getRecommendationsList().get(0), resources.get(0)); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void listRecommendationsExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String parent = "projects/project-6437/locations/location-6437/recommenders/recommender-6437"; String filter = "filter-1274492040"; client.listRecommendations(parent, filter); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getRecommendationTest() throws Exception { Recommendation expectedResponse = Recommendation.newBuilder() .setName( RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]") .toString()) .setDescription("description-1724546052") .setRecommenderSubtype("recommenderSubtype1811451601") .setLastRefreshTime(Timestamp.newBuilder().build()) .setPrimaryImpact(Impact.newBuilder().build()) .addAllAdditionalImpact(new ArrayList<Impact>()) .setContent(RecommendationContent.newBuilder().build()) .setStateInfo(RecommendationStateInfo.newBuilder().build()) .setEtag("etag3123477") .addAllAssociatedInsights(new ArrayList<Recommendation.InsightReference>()) .setXorGroupId("xorGroupId-2095769825") .build(); mockService.addResponse(expectedResponse); RecommendationName name = RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"); Recommendation actualResponse = client.getRecommendation(name); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void getRecommendationExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { RecommendationName name = RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"); client.getRecommendation(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getRecommendationTest2() throws Exception { Recommendation expectedResponse = Recommendation.newBuilder() .setName( RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]") .toString()) .setDescription("description-1724546052") .setRecommenderSubtype("recommenderSubtype1811451601") .setLastRefreshTime(Timestamp.newBuilder().build()) .setPrimaryImpact(Impact.newBuilder().build()) .addAllAdditionalImpact(new ArrayList<Impact>()) .setContent(RecommendationContent.newBuilder().build()) .setStateInfo(RecommendationStateInfo.newBuilder().build()) .setEtag("etag3123477") .addAllAssociatedInsights(new ArrayList<Recommendation.InsightReference>()) .setXorGroupId("xorGroupId-2095769825") .build(); mockService.addResponse(expectedResponse); String name = "projects/project-9152/locations/location-9152/recommenders/recommender-9152/recommendations/recommendation-9152"; Recommendation actualResponse = client.getRecommendation(name); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void getRecommendationExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String name = "projects/project-9152/locations/location-9152/recommenders/recommender-9152/recommendations/recommendation-9152"; client.getRecommendation(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void markRecommendationClaimedTest() throws Exception { Recommendation expectedResponse = Recommendation.newBuilder() .setName( RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]") .toString()) .setDescription("description-1724546052") .setRecommenderSubtype("recommenderSubtype1811451601") .setLastRefreshTime(Timestamp.newBuilder().build()) .setPrimaryImpact(Impact.newBuilder().build()) .addAllAdditionalImpact(new ArrayList<Impact>()) .setContent(RecommendationContent.newBuilder().build()) .setStateInfo(RecommendationStateInfo.newBuilder().build()) .setEtag("etag3123477") .addAllAssociatedInsights(new ArrayList<Recommendation.InsightReference>()) .setXorGroupId("xorGroupId-2095769825") .build(); mockService.addResponse(expectedResponse); RecommendationName name = RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"); Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; Recommendation actualResponse = client.markRecommendationClaimed(name, stateMetadata, etag); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void markRecommendationClaimedExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { RecommendationName name = RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"); Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; client.markRecommendationClaimed(name, stateMetadata, etag); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void markRecommendationClaimedTest2() throws Exception { Recommendation expectedResponse = Recommendation.newBuilder() .setName( RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]") .toString()) .setDescription("description-1724546052") .setRecommenderSubtype("recommenderSubtype1811451601") .setLastRefreshTime(Timestamp.newBuilder().build()) .setPrimaryImpact(Impact.newBuilder().build()) .addAllAdditionalImpact(new ArrayList<Impact>()) .setContent(RecommendationContent.newBuilder().build()) .setStateInfo(RecommendationStateInfo.newBuilder().build()) .setEtag("etag3123477") .addAllAssociatedInsights(new ArrayList<Recommendation.InsightReference>()) .setXorGroupId("xorGroupId-2095769825") .build(); mockService.addResponse(expectedResponse); String name = "projects/project-9152/locations/location-9152/recommenders/recommender-9152/recommendations/recommendation-9152"; Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; Recommendation actualResponse = client.markRecommendationClaimed(name, stateMetadata, etag); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void markRecommendationClaimedExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String name = "projects/project-9152/locations/location-9152/recommenders/recommender-9152/recommendations/recommendation-9152"; Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; client.markRecommendationClaimed(name, stateMetadata, etag); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void markRecommendationSucceededTest() throws Exception { Recommendation expectedResponse = Recommendation.newBuilder() .setName( RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]") .toString()) .setDescription("description-1724546052") .setRecommenderSubtype("recommenderSubtype1811451601") .setLastRefreshTime(Timestamp.newBuilder().build()) .setPrimaryImpact(Impact.newBuilder().build()) .addAllAdditionalImpact(new ArrayList<Impact>()) .setContent(RecommendationContent.newBuilder().build()) .setStateInfo(RecommendationStateInfo.newBuilder().build()) .setEtag("etag3123477") .addAllAssociatedInsights(new ArrayList<Recommendation.InsightReference>()) .setXorGroupId("xorGroupId-2095769825") .build(); mockService.addResponse(expectedResponse); RecommendationName name = RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"); Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; Recommendation actualResponse = client.markRecommendationSucceeded(name, stateMetadata, etag); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void markRecommendationSucceededExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { RecommendationName name = RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"); Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; client.markRecommendationSucceeded(name, stateMetadata, etag); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void markRecommendationSucceededTest2() throws Exception { Recommendation expectedResponse = Recommendation.newBuilder() .setName( RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]") .toString()) .setDescription("description-1724546052") .setRecommenderSubtype("recommenderSubtype1811451601") .setLastRefreshTime(Timestamp.newBuilder().build()) .setPrimaryImpact(Impact.newBuilder().build()) .addAllAdditionalImpact(new ArrayList<Impact>()) .setContent(RecommendationContent.newBuilder().build()) .setStateInfo(RecommendationStateInfo.newBuilder().build()) .setEtag("etag3123477") .addAllAssociatedInsights(new ArrayList<Recommendation.InsightReference>()) .setXorGroupId("xorGroupId-2095769825") .build(); mockService.addResponse(expectedResponse); String name = "projects/project-9152/locations/location-9152/recommenders/recommender-9152/recommendations/recommendation-9152"; Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; Recommendation actualResponse = client.markRecommendationSucceeded(name, stateMetadata, etag); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void markRecommendationSucceededExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String name = "projects/project-9152/locations/location-9152/recommenders/recommender-9152/recommendations/recommendation-9152"; Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; client.markRecommendationSucceeded(name, stateMetadata, etag); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void markRecommendationFailedTest() throws Exception { Recommendation expectedResponse = Recommendation.newBuilder() .setName( RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]") .toString()) .setDescription("description-1724546052") .setRecommenderSubtype("recommenderSubtype1811451601") .setLastRefreshTime(Timestamp.newBuilder().build()) .setPrimaryImpact(Impact.newBuilder().build()) .addAllAdditionalImpact(new ArrayList<Impact>()) .setContent(RecommendationContent.newBuilder().build()) .setStateInfo(RecommendationStateInfo.newBuilder().build()) .setEtag("etag3123477") .addAllAssociatedInsights(new ArrayList<Recommendation.InsightReference>()) .setXorGroupId("xorGroupId-2095769825") .build(); mockService.addResponse(expectedResponse); RecommendationName name = RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"); Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; Recommendation actualResponse = client.markRecommendationFailed(name, stateMetadata, etag); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void markRecommendationFailedExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { RecommendationName name = RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"); Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; client.markRecommendationFailed(name, stateMetadata, etag); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void markRecommendationFailedTest2() throws Exception { Recommendation expectedResponse = Recommendation.newBuilder() .setName( RecommendationName.ofProjectLocationRecommenderRecommendationName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]") .toString()) .setDescription("description-1724546052") .setRecommenderSubtype("recommenderSubtype1811451601") .setLastRefreshTime(Timestamp.newBuilder().build()) .setPrimaryImpact(Impact.newBuilder().build()) .addAllAdditionalImpact(new ArrayList<Impact>()) .setContent(RecommendationContent.newBuilder().build()) .setStateInfo(RecommendationStateInfo.newBuilder().build()) .setEtag("etag3123477") .addAllAssociatedInsights(new ArrayList<Recommendation.InsightReference>()) .setXorGroupId("xorGroupId-2095769825") .build(); mockService.addResponse(expectedResponse); String name = "projects/project-9152/locations/location-9152/recommenders/recommender-9152/recommendations/recommendation-9152"; Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; Recommendation actualResponse = client.markRecommendationFailed(name, stateMetadata, etag); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void markRecommendationFailedExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String name = "projects/project-9152/locations/location-9152/recommenders/recommender-9152/recommendations/recommendation-9152"; Map<String, String> stateMetadata = new HashMap<>(); String etag = "etag3123477"; client.markRecommendationFailed(name, stateMetadata, etag); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getRecommenderConfigTest() throws Exception { RecommenderConfig expectedResponse = RecommenderConfig.newBuilder() .setName( RecommenderConfigName.ofProjectLocationRecommenderName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]") .toString()) .setRecommenderGenerationConfig(RecommenderGenerationConfig.newBuilder().build()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .setRevisionId("revisionId-1507445162") .putAllAnnotations(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .build(); mockService.addResponse(expectedResponse); RecommenderConfigName name = RecommenderConfigName.ofProjectLocationRecommenderName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]"); RecommenderConfig actualResponse = client.getRecommenderConfig(name); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void getRecommenderConfigExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { RecommenderConfigName name = RecommenderConfigName.ofProjectLocationRecommenderName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]"); client.getRecommenderConfig(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getRecommenderConfigTest2() throws Exception { RecommenderConfig expectedResponse = RecommenderConfig.newBuilder() .setName( RecommenderConfigName.ofProjectLocationRecommenderName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]") .toString()) .setRecommenderGenerationConfig(RecommenderGenerationConfig.newBuilder().build()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .setRevisionId("revisionId-1507445162") .putAllAnnotations(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .build(); mockService.addResponse(expectedResponse); String name = "projects/project-3367/locations/location-3367/recommenders/recommender-3367/config"; RecommenderConfig actualResponse = client.getRecommenderConfig(name); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void getRecommenderConfigExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String name = "projects/project-3367/locations/location-3367/recommenders/recommender-3367/config"; client.getRecommenderConfig(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void updateRecommenderConfigTest() throws Exception { RecommenderConfig expectedResponse = RecommenderConfig.newBuilder() .setName( RecommenderConfigName.ofProjectLocationRecommenderName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]") .toString()) .setRecommenderGenerationConfig(RecommenderGenerationConfig.newBuilder().build()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .setRevisionId("revisionId-1507445162") .putAllAnnotations(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .build(); mockService.addResponse(expectedResponse); RecommenderConfig recommenderConfig = RecommenderConfig.newBuilder() .setName( RecommenderConfigName.ofProjectLocationRecommenderName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]") .toString()) .setRecommenderGenerationConfig(RecommenderGenerationConfig.newBuilder().build()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .setRevisionId("revisionId-1507445162") .putAllAnnotations(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .build(); FieldMask updateMask = FieldMask.newBuilder().build(); RecommenderConfig actualResponse = client.updateRecommenderConfig(recommenderConfig, updateMask); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void updateRecommenderConfigExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { RecommenderConfig recommenderConfig = RecommenderConfig.newBuilder() .setName( RecommenderConfigName.ofProjectLocationRecommenderName( "[PROJECT]", "[LOCATION]", "[RECOMMENDER]") .toString()) .setRecommenderGenerationConfig(RecommenderGenerationConfig.newBuilder().build()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .setRevisionId("revisionId-1507445162") .putAllAnnotations(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .build(); FieldMask updateMask = FieldMask.newBuilder().build(); client.updateRecommenderConfig(recommenderConfig, updateMask); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getInsightTypeConfigTest() throws Exception { InsightTypeConfig expectedResponse = InsightTypeConfig.newBuilder() .setName( InsightTypeConfigName.ofProjectLocationInsightTypeName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]") .toString()) .setInsightTypeGenerationConfig(InsightTypeGenerationConfig.newBuilder().build()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .setRevisionId("revisionId-1507445162") .putAllAnnotations(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .build(); mockService.addResponse(expectedResponse); InsightTypeConfigName name = InsightTypeConfigName.ofProjectLocationInsightTypeName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]"); InsightTypeConfig actualResponse = client.getInsightTypeConfig(name); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void getInsightTypeConfigExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { InsightTypeConfigName name = InsightTypeConfigName.ofProjectLocationInsightTypeName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]"); client.getInsightTypeConfig(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getInsightTypeConfigTest2() throws Exception { InsightTypeConfig expectedResponse = InsightTypeConfig.newBuilder() .setName( InsightTypeConfigName.ofProjectLocationInsightTypeName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]") .toString()) .setInsightTypeGenerationConfig(InsightTypeGenerationConfig.newBuilder().build()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .setRevisionId("revisionId-1507445162") .putAllAnnotations(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .build(); mockService.addResponse(expectedResponse); String name = "projects/project-5840/locations/location-5840/insightTypes/insightType-5840/config"; InsightTypeConfig actualResponse = client.getInsightTypeConfig(name); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void getInsightTypeConfigExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String name = "projects/project-5840/locations/location-5840/insightTypes/insightType-5840/config"; client.getInsightTypeConfig(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void updateInsightTypeConfigTest() throws Exception { InsightTypeConfig expectedResponse = InsightTypeConfig.newBuilder() .setName( InsightTypeConfigName.ofProjectLocationInsightTypeName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]") .toString()) .setInsightTypeGenerationConfig(InsightTypeGenerationConfig.newBuilder().build()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .setRevisionId("revisionId-1507445162") .putAllAnnotations(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .build(); mockService.addResponse(expectedResponse); InsightTypeConfig insightTypeConfig = InsightTypeConfig.newBuilder() .setName( InsightTypeConfigName.ofProjectLocationInsightTypeName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]") .toString()) .setInsightTypeGenerationConfig(InsightTypeGenerationConfig.newBuilder().build()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .setRevisionId("revisionId-1507445162") .putAllAnnotations(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .build(); FieldMask updateMask = FieldMask.newBuilder().build(); InsightTypeConfig actualResponse = client.updateInsightTypeConfig(insightTypeConfig, updateMask); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void updateInsightTypeConfigExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { InsightTypeConfig insightTypeConfig = InsightTypeConfig.newBuilder() .setName( InsightTypeConfigName.ofProjectLocationInsightTypeName( "[PROJECT]", "[LOCATION]", "[INSIGHT_TYPE]") .toString()) .setInsightTypeGenerationConfig(InsightTypeGenerationConfig.newBuilder().build()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .setRevisionId("revisionId-1507445162") .putAllAnnotations(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .build(); FieldMask updateMask = FieldMask.newBuilder().build(); client.updateInsightTypeConfig(insightTypeConfig, updateMask); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } }
[ "noreply@github.com" ]
sumodgeorge.noreply@github.com
1ad441faa23401b09fc6f94114d057766f609ba9
746cd1d11eb24e7a987f2dd4db72b68a8e0a5b99
/android/tools/adt/idea/android/guiTestSrc/com/android/tools/idea/tests/gui/framework/fixture/IdeFrameFixture.java
4850c60953f8325c97046b53dd6f1c342927d6bd
[]
no_license
binsys/BPI-A64-Android7
c49b0d3a785811b7f0376c92100c6ac102bb858c
751fadaacec8493a10461661d80fce4b775dd5de
refs/heads/master
2023-05-11T18:31:41.505222
2020-07-13T04:27:40
2020-07-13T12:08:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
36,003
java
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.tests.gui.framework.fixture; import com.android.tools.idea.gradle.GradleSyncState; import com.android.tools.idea.gradle.IdeaAndroidProject; import com.android.tools.idea.gradle.compiler.AndroidGradleBuildConfiguration; import com.android.tools.idea.gradle.compiler.PostProjectBuildTasksExecutor; import com.android.tools.idea.gradle.invoker.GradleInvocationResult; import com.android.tools.idea.gradle.util.BuildMode; import com.android.tools.idea.gradle.util.GradleUtil; import com.android.tools.idea.gradle.util.ProjectBuilder; import com.android.tools.idea.tests.gui.framework.fixture.avdmanager.AvdManagerDialogFixture; import com.google.common.base.Charsets; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.common.io.Files; import com.intellij.codeInspection.ui.InspectionTree; import com.intellij.execution.BeforeRunTask; import com.intellij.execution.BeforeRunTaskProvider; import com.intellij.execution.RunnerAndConfigurationSettings; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.impl.RunManagerImpl; import com.intellij.ide.RecentProjectsManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.CompilationStatusListener; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompilerManager; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.externalSystem.model.ExternalSystemException; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.options.ex.IdeConfigurablesGroup; import com.intellij.openapi.options.ex.ProjectConfigurablesGroup; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ContentEntry; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.SourceFolder; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.impl.IdeFrameImpl; import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame; import com.intellij.ui.EditorNotificationPanel; import com.intellij.util.ThreeState; import com.intellij.util.messages.MessageBusConnection; import org.fest.swing.core.GenericTypeMatcher; import org.fest.swing.core.Robot; import org.fest.swing.core.matcher.JButtonMatcher; import org.fest.swing.core.matcher.JLabelMatcher; import org.fest.swing.edt.GuiQuery; import org.fest.swing.edt.GuiTask; import org.fest.swing.timing.Condition; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.module.JpsModuleSourceRootType; import org.jetbrains.plugins.gradle.settings.GradleProjectSettings; import org.jetbrains.plugins.gradle.settings.GradleSettings; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.android.SdkConstants.FD_GRADLE; import static com.android.SdkConstants.FN_BUILD_GRADLE; import static com.android.tools.idea.gradle.GradleSyncState.GRADLE_SYNC_TOPIC; import static com.android.tools.idea.gradle.compiler.PostProjectBuildTasksExecutor.GRADLE_BUILD_TOPIC; import static com.android.tools.idea.gradle.util.BuildMode.COMPILE_JAVA; import static com.android.tools.idea.gradle.util.BuildMode.SOURCE_GEN; import static com.android.tools.idea.gradle.util.GradleUtil.findWrapperPropertiesFile; import static com.android.tools.idea.gradle.util.GradleUtil.updateGradleDistributionUrl; import static com.android.tools.idea.tests.gui.framework.GuiTests.*; import static com.android.tools.idea.tests.gui.framework.fixture.LibraryPropertiesDialogFixture.showPropertiesDialog; import static com.google.common.io.Files.write; import static com.intellij.ide.impl.ProjectUtil.closeAndDispose; import static com.intellij.openapi.util.io.FileUtil.*; import static com.intellij.openapi.util.text.StringUtil.isNotEmpty; import static com.intellij.openapi.vfs.VfsUtilCore.urlToPath; import static junit.framework.Assert.fail; import static org.fest.assertions.Assertions.assertThat; import static org.fest.swing.edt.GuiActionRunner.execute; import static org.fest.swing.timing.Pause.pause; import static org.fest.util.Strings.quote; import static org.jetbrains.android.AndroidPlugin.*; import static org.jetbrains.plugins.gradle.settings.DistributionType.LOCAL; import static org.junit.Assert.*; public class IdeFrameFixture extends ComponentFixture<IdeFrameFixture, IdeFrameImpl> { @NotNull private final File myProjectPath; @NotNull private final GradleProjectEventListener myGradleProjectEventListener; private EditorFixture myEditor; @NotNull public static IdeFrameFixture find(@NotNull final Robot robot, @NotNull final File projectPath, @Nullable final String projectName) { final GenericTypeMatcher<IdeFrameImpl> matcher = new GenericTypeMatcher<IdeFrameImpl>(IdeFrameImpl.class) { @Override protected boolean isMatching(@NotNull IdeFrameImpl frame) { Project project = frame.getProject(); if (project != null && projectPath.getPath().equals(project.getBasePath())) { return projectName == null || projectName.equals(project.getName()); } return false; } }; pause(new Condition("IdeFrame " + quote(projectPath.getPath()) + " to show up") { @Override public boolean test() { Collection<IdeFrameImpl> frames = robot.finder().findAll(matcher); return !frames.isEmpty(); } }, LONG_TIMEOUT); IdeFrameImpl ideFrame = robot.finder().find(matcher); return new IdeFrameFixture(robot, ideFrame, projectPath); } public IdeFrameFixture(@NotNull Robot robot, @NotNull IdeFrameImpl target, @NotNull File projectPath) { super(IdeFrameFixture.class, robot, target); myProjectPath = projectPath; final Project project = getProject(); Disposable disposable = new NoOpDisposable(); Disposer.register(project, disposable); myGradleProjectEventListener = new GradleProjectEventListener(); MessageBusConnection connection = project.getMessageBus().connect(disposable); connection.subscribe(GRADLE_SYNC_TOPIC, myGradleProjectEventListener); connection.subscribe(GRADLE_BUILD_TOPIC, myGradleProjectEventListener); } @NotNull public File getProjectPath() { return myProjectPath; } @NotNull public List<String> getModuleNames() { List<String> names = Lists.newArrayList(); for (Module module : getModuleManager().getModules()) { names.add(module.getName()); } return names; } @NotNull public IdeFrameFixture requireModuleCount(int expected) { Module[] modules = getModuleManager().getModules(); assertThat(modules).as("Module count in project " + quote(getProject().getName())).hasSize(expected); return this; } @NotNull public IdeaAndroidProject getAndroidProjectForModule(@NotNull String name) { Module module = getModule(name); AndroidFacet facet = AndroidFacet.getInstance(module); if (facet != null && facet.requiresAndroidModel()) { IdeaAndroidProject androidModel = facet.getAndroidModel(); if (androidModel != null) { return androidModel; } } throw new AssertionError("Unable to find IdeaAndroidProject for module " + quote(name)); } @NotNull public Multimap<JpsModuleSourceRootType, String> getSourceFolderRelativePaths(@NotNull String moduleName) { final Multimap<JpsModuleSourceRootType, String> sourceFoldersByType = ArrayListMultimap.create(); Module module = getModule(moduleName); final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); execute(new GuiTask() { @Override protected void executeInEDT() throws Throwable { ModifiableRootModel rootModel = moduleRootManager.getModifiableModel(); try { for (ContentEntry contentEntry : rootModel.getContentEntries()) { for (SourceFolder folder : contentEntry.getSourceFolders()) { String path = urlToPath(folder.getUrl()); String relativePath = getRelativePath(myProjectPath, new File(toSystemDependentName(path))); sourceFoldersByType.put(folder.getRootType(), relativePath); } } } finally { rootModel.dispose(); } } }); return sourceFoldersByType; } @NotNull public Collection<String> getSourceFolderRelativePaths(@NotNull String moduleName, @NotNull final JpsModuleSourceRootType<?> sourceType) { final Set<String> paths = Sets.newHashSet(); Module module = getModule(moduleName); final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); execute(new GuiTask() { @Override protected void executeInEDT() throws Throwable { ModifiableRootModel rootModel = moduleRootManager.getModifiableModel(); try { for (ContentEntry contentEntry : rootModel.getContentEntries()) { for (SourceFolder folder : contentEntry.getSourceFolders()) { JpsModuleSourceRootType<?> rootType = folder.getRootType(); if (rootType.equals(sourceType)) { String path = urlToPath(folder.getUrl()); String relativePath = getRelativePath(myProjectPath, new File(toSystemDependentName(path))); paths.add(relativePath); } } } } finally { rootModel.dispose(); } } }); return paths; } @NotNull public Module getModule(@NotNull String name) { for (Module module : getModuleManager().getModules()) { if (name.equals(module.getName())) { return module; } } throw new AssertionError("Unable to find module with name " + quote(name)); } @NotNull private ModuleManager getModuleManager() { return ModuleManager.getInstance(getProject()); } @NotNull public EditorFixture getEditor() { if (myEditor == null) { myEditor = new EditorFixture(robot(), this); } return myEditor; } @NotNull public IdeaAndroidProject getAndroidModel(@NotNull String moduleName) { Module module = getModule(moduleName); assertNotNull("Could not find module " + moduleName, module); AndroidFacet facet = AndroidFacet.getInstance(module); assertNotNull("Module " + moduleName + " is not an Android module", facet); assertTrue("Module " + moduleName + " is not a Gradle project", facet.requiresAndroidModel()); IdeaAndroidProject androidModel = facet.getAndroidModel(); assertNotNull("Module " + moduleName + " does not have a Gradle project (not synced yet or sync failed?)", androidModel); return androidModel; } @NotNull public GradleInvocationResult invokeProjectMake() { return invokeProjectMake(null); } @NotNull public GradleInvocationResult invokeProjectMake(@Nullable Runnable executeAfterInvokingMake) { myGradleProjectEventListener.reset(); final AtomicReference<GradleInvocationResult> resultRef = new AtomicReference<GradleInvocationResult>(); ProjectBuilder.getInstance(getProject()).addAfterProjectBuildTask(new ProjectBuilder.AfterProjectBuildTask() { @Override public void execute(@NotNull GradleInvocationResult result) { resultRef.set(result); } @Override public boolean execute(CompileContext context) { return false; } }); selectProjectMakeAction(); if (executeAfterInvokingMake != null) { executeAfterInvokingMake.run(); } waitForBuildToFinish(COMPILE_JAVA); GradleInvocationResult result = resultRef.get(); assertNotNull(result); return result; } @NotNull public IdeFrameFixture invokeProjectMakeAndSimulateFailure(@NotNull final String failure) { Runnable failTask = new Runnable() { @Override public void run() { throw new ExternalSystemException(failure); } }; ApplicationManager.getApplication().putUserData(EXECUTE_BEFORE_PROJECT_BUILD_IN_GUI_TEST_KEY, failTask); selectProjectMakeAction(); return this; } @NotNull public IdeFrameFixture invokeProjectMakeWithGradleOutput(@NotNull String output) { ApplicationManager.getApplication().putUserData(GRADLE_BUILD_OUTPUT_IN_GUI_TEST_KEY, output); selectProjectMakeAction(); return this; } @NotNull public IdeFrameFixture waitUntilFakeGradleOutputIsApplied() { final Application application = ApplicationManager.getApplication(); if (application.getUserData(GRADLE_BUILD_OUTPUT_IN_GUI_TEST_KEY) == null) { fail("No fake gradle output is configured"); } pause(new Condition("Waiting for fake gradle output to be applied") { @Override public boolean test() { return application.getUserData(GRADLE_BUILD_OUTPUT_IN_GUI_TEST_KEY) == null; } }, SHORT_TIMEOUT); String fakeOutput = application.getUserData(GRADLE_BUILD_OUTPUT_IN_GUI_TEST_KEY); if (fakeOutput != null) { fail(String.format("Fake gradle output (%s) is not applied in %d ms", fakeOutput, SHORT_TIMEOUT.duration())); } return this; } @NotNull public CompileContext invokeProjectMakeUsingJps() { final Project project = getProject(); AndroidGradleBuildConfiguration buildConfiguration = AndroidGradleBuildConfiguration.getInstance(project); buildConfiguration.USE_EXPERIMENTAL_FASTER_BUILD = false; final AtomicReference<CompileContext> contextRef = new AtomicReference<CompileContext>(); CompilerManager compilerManager = CompilerManager.getInstance(project); Disposable disposable = new NoOpDisposable(); compilerManager.addCompilationStatusListener(new CompilationStatusListener() { @Override public void compilationFinished(boolean aborted, int errors, int warnings, CompileContext compileContext) { contextRef.set(compileContext); } @Override public void fileGenerated(String outputRoot, String relativePath) { } }, disposable); try { selectProjectMakeAction(); pause(new Condition("Build (" + COMPILE_JAVA + ") for project " + quote(project.getName()) + " to finish'") { @Override public boolean test() { CompileContext context = contextRef.get(); return context != null; } }, LONG_TIMEOUT); CompileContext context = contextRef.get(); assertNotNull(context); return context; } finally { Disposer.dispose(disposable); } } /** * Finds the Run button in the IDE interface. * * @return ActionButtonFixture for the run button. */ @NotNull public ActionButtonFixture findRunApplicationButton() { return findActionButtonByActionId("Run"); } public void debugApp(@NotNull String appName) throws ClassNotFoundException { selectApp(appName); findActionButtonByActionId("Debug").click(); } public void runApp(@NotNull String appName) throws ClassNotFoundException { selectApp(appName); findActionButtonByActionId("Run").click(); } @NotNull public ChooseDeviceDialogFixture findChooseDeviceDialog() { return ChooseDeviceDialogFixture.find(robot()); } @NotNull public RunToolWindowFixture getRunToolWindow() { return new RunToolWindowFixture(this); } @NotNull public DebugToolWindowFixture getDebugToolWindow() { return new DebugToolWindowFixture(this); } protected void selectProjectMakeAction() { invokeMenuPath("Build", "Make Project"); } /** * Invokes an action by menu path * * @param path the series of menu names, e.g. {@link invokeActionByMenuPath("Build", "Make Project")} */ public void invokeMenuPath(@NotNull String... path) { getMenuFixture().invokeMenuPath(path); } /** * Invokes an action by menu path (where each segment is a regular expression). This is particularly * useful when the menu items can change dynamically, such as the labels of Undo actions, Run actions, * etc. * * @param path the series of menu name regular expressions, e.g. {@link invokeActionByMenuPath("Build", "Make( Project)?")} */ public void invokeMenuPathRegex(@NotNull String... path) { getMenuFixture().invokeMenuPathRegex(path); } @NotNull private MenuFixture getMenuFixture() { return new MenuFixture(robot(), target()); } @NotNull public IdeFrameFixture waitForBuildToFinish(@NotNull final BuildMode buildMode) { final Project project = getProject(); if (buildMode == SOURCE_GEN && !ProjectBuilder.getInstance(project).isSourceGenerationEnabled()) { return this; } pause(new Condition("Build (" + buildMode + ") for project " + quote(project.getName()) + " to finish'") { @Override public boolean test() { if (buildMode == SOURCE_GEN) { PostProjectBuildTasksExecutor tasksExecutor = PostProjectBuildTasksExecutor.getInstance(project); if (tasksExecutor.getLastBuildTimestamp() > -1) { // This will happen when creating a new project. Source generation happens before the IDE frame is found and build listeners // are created. It is fairly safe to assume that source generation happened if we have a timestamp for a "last performed build". return true; } } return myGradleProjectEventListener.isBuildFinished(buildMode); } }, LONG_TIMEOUT); waitForBackgroundTasksToFinish(); robot().waitForIdle(); return this; } @NotNull public FileFixture findExistingFileByRelativePath(@NotNull String relativePath) { VirtualFile file = findFileByRelativePath(relativePath, true); return new FileFixture(getProject(), file); } @Nullable @Contract("_, true -> !null") public VirtualFile findFileByRelativePath(@NotNull String relativePath, boolean requireExists) { //noinspection Contract assertFalse("Should use '/' in test relative paths, not File.separator", relativePath.contains("\\")); Project project = getProject(); VirtualFile file = project.getBaseDir().findFileByRelativePath(relativePath); if (requireExists) { //noinspection Contract assertNotNull("Unable to find file with relative path " + quote(relativePath), file); } return file; } @NotNull public IdeFrameFixture requestProjectSyncAndExpectFailure() { requestProjectSync(); return waitForGradleProjectSyncToFail(); } @NotNull public IdeFrameFixture requestProjectSyncAndSimulateFailure(@NotNull final String failure) { Runnable failTask = new Runnable() { @Override public void run() { throw new RuntimeException(failure); } }; ApplicationManager.getApplication().putUserData(EXECUTE_BEFORE_PROJECT_SYNC_TASK_IN_GUI_TEST_KEY, failTask); // When simulating the error, we don't have to wait for sync to happen. Sync never happens because the error is thrown before it (sync) // is started. return requestProjectSync(); } @NotNull public IdeFrameFixture requestProjectSync() { myGradleProjectEventListener.reset(); // We wait until all "Run Configurations" are populated in the toolbar combo-box. Until then the "Project Sync" button is not in its // final position, and FEST will click the wrong button. pause(new Condition("Waiting for 'Run Configurations' to be populated") { @Override public boolean test() { RunConfigurationComboBoxFixture runConfigurationComboBox = RunConfigurationComboBoxFixture.find(IdeFrameFixture.this); return isNotEmpty(runConfigurationComboBox.getText()); } }, SHORT_TIMEOUT); findActionButtonByActionId("Android.SyncProject").click(); return this; } @NotNull public IdeFrameFixture waitForGradleProjectSyncToFail() { try { waitForGradleProjectSyncToFinish(true); fail("Expecting project sync to fail"); } catch (RuntimeException expected) { // expected failure. } return waitForBackgroundTasksToFinish(); } @NotNull public IdeFrameFixture waitForGradleProjectSyncToStart() { Project project = getProject(); final GradleSyncState syncState = GradleSyncState.getInstance(project); if (!syncState.isSyncInProgress()) { pause(new Condition("Syncing project " + quote(project.getName()) + " to finish") { @Override public boolean test() { return myGradleProjectEventListener.isSyncStarted(); } }, SHORT_TIMEOUT); } return this; } @NotNull public IdeFrameFixture waitForGradleProjectSyncToFinish() { waitForGradleProjectSyncToFinish(false); return this; } private void waitForGradleProjectSyncToFinish(final boolean expectSyncFailure) { final Project project = getProject(); // ensure GradleInvoker (in-process build) is always enabled. AndroidGradleBuildConfiguration buildConfiguration = AndroidGradleBuildConfiguration.getInstance(project); buildConfiguration.USE_EXPERIMENTAL_FASTER_BUILD = true; pause(new Condition("Syncing project " + quote(project.getName()) + " to finish") { @Override public boolean test() { GradleSyncState syncState = GradleSyncState.getInstance(project); boolean syncFinished = (myGradleProjectEventListener.isSyncFinished() || syncState.isSyncNeeded() != ThreeState.YES) && !syncState.isSyncInProgress(); if (expectSyncFailure) { syncFinished = syncFinished && myGradleProjectEventListener.hasSyncError(); } return syncFinished; } }, LONG_TIMEOUT); if (myGradleProjectEventListener.hasSyncError()) { RuntimeException syncError = myGradleProjectEventListener.getSyncError(); myGradleProjectEventListener.reset(); throw syncError; } if (!myGradleProjectEventListener.isSyncSkipped()) { waitForBuildToFinish(SOURCE_GEN); } waitForBackgroundTasksToFinish(); } @NotNull public IdeFrameFixture waitForBackgroundTasksToFinish() { pause(new Condition("Background tasks to finish") { @Override public boolean test() { ProgressManager progressManager = ProgressManager.getInstance(); return !progressManager.hasModalProgressIndicator() && !progressManager.hasProgressIndicator() && !progressManager.hasUnsafeProgressIndicator(); } }, LONG_TIMEOUT); robot().waitForIdle(); return this; } @NotNull private ActionButtonFixture findActionButtonByActionId(String actionId) { return ActionButtonFixture.findByActionId(actionId, robot(), target()); } @NotNull public AndroidToolWindowFixture getAndroidToolWindow() { return new AndroidToolWindowFixture(getProject(), robot()); } @NotNull public CapturesToolWindowFixture getCapturesToolWindow() { return new CapturesToolWindowFixture(getProject(), robot()); } @NotNull public BuildVariantsToolWindowFixture getBuildVariantsWindow() { return new BuildVariantsToolWindowFixture(this); } @NotNull public MessagesToolWindowFixture getMessagesToolWindow() { return new MessagesToolWindowFixture(getProject(), robot()); } @NotNull public GradleToolWindowFixture getGradleToolWindow() { return new GradleToolWindowFixture(getProject(), robot()); } @NotNull public EditorNotificationPanelFixture requireEditorNotification(@NotNull final String message) { final Ref<EditorNotificationPanel> notificationPanelRef = new Ref<EditorNotificationPanel>(); pause(new Condition("Notification with message '" + message + "' shows up") { @Override public boolean test() { EditorNotificationPanel notificationPanel = findNotificationPanel(message); notificationPanelRef.set(notificationPanel); return notificationPanel != null; } }); EditorNotificationPanel notificationPanel = notificationPanelRef.get(); assertNotNull(notificationPanel); return new EditorNotificationPanelFixture(robot(), notificationPanel); } public void requireNoEditorNotification() { assertNull(findNotificationPanel(null)); } /** * Locates an editor notification with the given main message (unless the message is {@code null}, in which case we assert that there are * no visible editor notifications. Will fail if the given notification is not found. */ @Nullable private EditorNotificationPanel findNotificationPanel(@Nullable String message) { Collection<EditorNotificationPanel> panels = robot().finder().findAll(target(), new GenericTypeMatcher<EditorNotificationPanel>( EditorNotificationPanel.class, true) { @Override protected boolean isMatching(@NotNull EditorNotificationPanel panel) { return panel.isShowing(); } }); if (message == null) { if (!panels.isEmpty()) { List<String> labels = Lists.newArrayList(); for (EditorNotificationPanel panel : panels) { labels.addAll(getEditorNotificationLabels(panel)); } fail("Found editor notifications when none were expected" + labels); } return null; } List<String> labels = Lists.newArrayList(); for (EditorNotificationPanel panel : panels) { List<String> found = getEditorNotificationLabels(panel); labels.addAll(found); for (String label : found) { if (label.contains(message)) { return panel; } } } return null; } /** Looks up the main label for a given editor notification panel */ private List<String> getEditorNotificationLabels(@NotNull EditorNotificationPanel panel) { final List<String> allText = Lists.newArrayList(); final Collection<JLabel> labels = robot().finder().findAll(panel, JLabelMatcher.any().andShowing()); for (final JLabel label : labels) { String text = execute(new GuiQuery<String>() { @Override @Nullable protected String executeInEDT() throws Throwable { return label.getText(); } }); if (isNotEmpty(text)) { allText.add(text); } } return allText; } @NotNull public IdeSettingsDialogFixture openIdeSettings() { // Using invokeLater because we are going to show a *modal* dialog via API (instead of clicking a button, for example.) If we use // GuiActionRunner the test will hang until the modal dialog is closed. ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { Project project = getProject(); ShowSettingsUtil.getInstance().showSettingsDialog(project, new ProjectConfigurablesGroup(project), new IdeConfigurablesGroup()); } }); return IdeSettingsDialogFixture.find(robot()); } @NotNull public IdeFrameFixture deleteGradleWrapper() { deleteWrapper(getProjectPath()); return this; } @NotNull public IdeFrameFixture requireGradleWrapperSet() { File wrapperDirPath = getGradleWrapperDirPath(getProjectPath()); assertThat(wrapperDirPath).as("Gradle wrapper").isDirectory(); return this; } public static void deleteWrapper(@NotNull File projectDirPath) { File wrapperDirPath = getGradleWrapperDirPath(projectDirPath); delete(wrapperDirPath); assertThat(wrapperDirPath).as("Gradle wrapper").doesNotExist(); } @NotNull private static File getGradleWrapperDirPath(@NotNull File projectDirPath) { return new File(projectDirPath, FD_GRADLE); } @NotNull public IdeFrameFixture useLocalGradleDistribution(@NotNull File gradleHomePath) { return useLocalGradleDistribution(gradleHomePath.getPath()); } @NotNull public IdeFrameFixture useLocalGradleDistribution(@NotNull String gradleHome) { GradleProjectSettings settings = getGradleSettings(); settings.setDistributionType(LOCAL); settings.setGradleHome(gradleHome); return this; } @NotNull public GradleProjectSettings getGradleSettings() { GradleProjectSettings settings = GradleUtil.getGradleProjectSettings(getProject()); assertNotNull(settings); return settings; } @NotNull public AvdManagerDialogFixture invokeAvdManager() { ActionButtonFixture button = findActionButtonByActionId("Android.RunAndroidAvdManager"); button.requireVisible(); button.requireEnabled(); button.click(); return AvdManagerDialogFixture.find(robot()); } @NotNull public RunConfigurationsDialogFixture invokeRunConfigurationsDialog() { invokeMenuPath("Run", "Edit Configurations..."); return RunConfigurationsDialogFixture.find(robot()); } @NotNull public InspectionsFixture inspectCode() { invokeMenuPath("Analyze", "Inspect Code..."); //final Ref<FileChooserDialogImpl> wrapperRef = new Ref<FileChooserDialogImpl>(); JDialog dialog = robot().finder().find(new GenericTypeMatcher<JDialog>(JDialog.class) { @Override protected boolean isMatching(@NotNull JDialog dialog) { return "Specify Inspection Scope".equals(dialog.getTitle()); } }); JButton button = robot().finder().find(dialog, JButtonMatcher.withText("OK").andShowing()); robot().click(button); final InspectionTree tree = waitUntilFound(robot(), new GenericTypeMatcher<InspectionTree>(InspectionTree.class) { @Override protected boolean isMatching(@NotNull InspectionTree component) { return true; } }); return new InspectionsFixture(robot(), getProject(), tree); } @NotNull public ProjectViewFixture getProjectView() { return new ProjectViewFixture(getProject(), robot()); } @NotNull public Project getProject() { Project project = target().getProject(); assertNotNull(project); return project; } public void closeProject() { execute(new GuiTask() { @Override protected void executeInEDT() throws Throwable { closeAndDispose(getProject()); RecentProjectsManager.getInstance().updateLastProjectPath(); WelcomeFrame.showIfNoProjectOpened(); } }); pause(new Condition("Waiting for 'Welcome' page to show up") { @Override public boolean test() { for (Frame frame : Frame.getFrames()) { if (frame instanceof WelcomeFrame && frame.isShowing()) { return true; } } return false; } }); } @NotNull public LibraryPropertiesDialogFixture showPropertiesForLibrary(@NotNull String libraryName) { return showPropertiesDialog(robot(), libraryName, getProject()); } @NotNull public MessagesFixture findMessageDialog(@NotNull String title) { return MessagesFixture.findByTitle(robot(), target(), title); } @NotNull public IdeFrameFixture setGradleJvmArgs(@NotNull final String jvmArgs) { Project project = getProject(); final GradleSettings settings = GradleSettings.getInstance(project); settings.setGradleVmOptions(jvmArgs); pause(new Condition("Gradle settings to be set") { @Override public boolean test() { return jvmArgs.equals(settings.getGradleVmOptions()); } }, SHORT_TIMEOUT); return this; } @NotNull public IdeFrameFixture updateGradleWrapperVersion(@NotNull String version) throws IOException { File wrapperPropertiesFile = findWrapperPropertiesFile(getProject()); assertNotNull(wrapperPropertiesFile); updateGradleDistributionUrl(version, wrapperPropertiesFile); return this; } @NotNull public IdeFrameFixture updateAndroidModelVersion(@NotNull String version) throws IOException { File buildFile = new File(getProjectPath(), FN_BUILD_GRADLE); assertThat(buildFile).isFile(); String contents = Files.toString(buildFile, Charsets.UTF_8); Pattern pattern = Pattern.compile("classpath ['\"]com.android.tools.build:gradle:(.+)['\"]"); Matcher matcher = pattern.matcher(contents); if (matcher.find()) { contents = contents.substring(0, matcher.start(1)) + version + contents.substring(matcher.end(1)); write(contents, buildFile, Charsets.UTF_8); } else { fail("Cannot find declaration of Android plugin"); } return this; } /** * Sets the "Before Launch" tasks in the "JUnit Run Configuration" template. * @param taskName the name of the "Before Launch" task (e.g. "Make", "Gradle-aware Make") */ @NotNull public IdeFrameFixture setJUnitDefaultBeforeRunTask(@NotNull String taskName) { Project project = getProject(); RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(project); ConfigurationType junitConfigurationType = runManager.getConfigurationType("JUnit"); assertNotNull("Failed to find run configuration type 'JUnit'", junitConfigurationType); for (ConfigurationFactory configurationFactory : junitConfigurationType.getConfigurationFactories()) { RunnerAndConfigurationSettings template = runManager.getConfigurationTemplate(configurationFactory); RunConfiguration runConfiguration = template.getConfiguration(); BeforeRunTaskProvider<BeforeRunTask>[] taskProviders = Extensions.getExtensions(BeforeRunTaskProvider.EXTENSION_POINT_NAME, project); BeforeRunTaskProvider targetProvider = null; for (BeforeRunTaskProvider<? extends BeforeRunTask> provider : taskProviders) { if (taskName.equals(provider.getName())) { targetProvider = provider; break; } } assertNotNull(String.format("Failed to find task provider '%1$s'", taskName), targetProvider); BeforeRunTask task = targetProvider.createTask(runConfiguration); assertNotNull(task); task.setEnabled(true); runManager.setBeforeRunTasks(runConfiguration, Collections.singletonList(task), false); } return this; } @NotNull public FindDialogFixture invokeFindInPathDialog() { invokeMenuPath("Edit", "Find", "Find in Path..."); return FindDialogFixture.find(robot()); } @NotNull public FindToolWindowFixture getFindToolWindow() { return new FindToolWindowFixture(this); } private static class NoOpDisposable implements Disposable { @Override public void dispose() { } } private void selectApp(@NotNull String appName) throws ClassNotFoundException { ComboBoxActionFixture comboBoxActionFixture = new ComboBoxActionFixture(robot(), this); comboBoxActionFixture.selectApp(appName); } }
[ "mingxin.android@gmail.com" ]
mingxin.android@gmail.com
d683b24cdd1b9d8f080f78e66e037221947c0fb5
01e25b532e9468fd35330266de10183a99a3dc15
/commons-dict-wordnet-indexbyname/src/main/java/org/swtk/commons/dict/wordnet/indexbyname/instance/c/y/g/WordnetNounIndexNameInstanceCYG.java
538c1a3407796a6f332361c169bc06ad175d0577
[ "Apache-2.0" ]
permissive
torrances/swtk-commons
a3f95206204becf138718e297f2bb939c65cafa5
78ee97835e4437d91fd4ba0cf6ccab40be5c8889
refs/heads/master
2021-01-17T11:31:27.004328
2016-01-07T17:26:09
2016-01-07T17:26:09
43,841,418
0
0
null
null
null
null
UTF-8
Java
false
false
1,991
java
package org.swtk.commons.dict.wordnet.indexbyname.instance.c.y.g; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounIndexNameInstanceCYG { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("{\"term\":\"cygnet\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01861547\"]}"); add("{\"term\":\"cygnus\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"01861630\", \"09285396\"]}"); add("{\"term\":\"cygnus atratus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01862828\"]}"); add("{\"term\":\"cygnus buccinator\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01862643\"]}"); add("{\"term\":\"cygnus columbianus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01862137\"]}"); add("{\"term\":\"cygnus columbianus bewickii\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01862493\"]}"); add("{\"term\":\"cygnus columbianus columbianus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01862330\"]}"); add("{\"term\":\"cygnus cygnus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01861966\"]}"); add("{\"term\":\"cygnus olor\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"01861831\"]}"); } private static void add(final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(indexNoun.getTerm())) ? map.get(indexNoun.getTerm()) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(indexNoun.getTerm(), list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> terms() { return map.keySet(); } }
[ "cmtrim@us.ibm.com" ]
cmtrim@us.ibm.com
76c139fc7b860e87ae28c88490d4489dcd21459b
930c207e245c320b108e9699bbbb036260a36d6a
/BRICK-RDF4J/generatedCode/src/main/java/brickschema/org/schema/_1_0_2/Brick/IEconomizer_Disable_Differential_Enthalpy.java
0258b8064594053fc17e70917d0494878ea8d7d0
[]
no_license
InnovationSE/BRICK-Generated-By-OLGA
24d278f543471e1ce622f5f45d9e305790181fff
7874dfa450a8a2b6a6f9927c0f91f9c7d2abd4d2
refs/heads/master
2021-07-01T14:13:11.302860
2017-09-21T12:44:17
2017-09-21T12:44:17
104,251,784
1
0
null
null
null
null
UTF-8
Java
false
false
437
java
/** * This file is automatically generated by OLGA * @author OLGA * @version 1.0 */ package brickschema.org.schema._1_0_2.Brick; import java.util.ArrayList; import java.util.List; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.vocabulary.RDF; import brickschema.org.schema._1_0_2.Brick.IEconomizer; public interface IEconomizer_Disable_Differential_Enthalpy extends IEconomizer { public IRI iri(); }
[ "Andre.Ponnouradjane@non.schneider-electric.com" ]
Andre.Ponnouradjane@non.schneider-electric.com
84d247eb52b8ef3945d3a1d3e129fbcff87f1ec2
41027f68ddf54caadd7da277b7c395ffaee8e261
/app/src/main/java/com/example/bitirme/bolum_liste_adaptoru.java
e5eceec5c7e7fd4fef1f3015e52144a7eeb5f75f
[]
no_license
Mustecep/Bitirme
0e53a4bede1ce2d3557824bdd9cad38bc13196d9
3b06f241b822f69895b694b3b26f3558bb7246f8
refs/heads/master
2023-04-17T06:27:12.814884
2021-04-29T21:02:41
2021-04-29T21:02:41
362,946,046
0
0
null
null
null
null
UTF-8
Java
false
false
2,422
java
package com.example.bitirme; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class bolum_liste_adaptoru extends RecyclerView.Adapter<bolum_liste_adaptoru.ViewHolder> { ArrayList<Bolum> puan_sirali_liste= new ArrayList<Bolum>(); LayoutInflater layoutInflater; Context context; public bolum_liste_adaptoru(ArrayList<Bolum> puan_sirali_liste, BolumARA context) { this.puan_sirali_liste = puan_sirali_liste; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { layoutInflater=layoutInflater.from(context); View v=layoutInflater.inflate(R.layout.puan_sirali_liste_layout,parent,false); ViewHolder vh= new ViewHolder(v); return vh; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { holder.universite_adฤฑ.setText(puan_sirali_liste.get(position).getUniversite_adi()); holder.sehir_adฤฑ.setText("Aรงฤฑklama : "+puan_sirali_liste.get(position).getSehir()); if (Integer.valueOf(puan_sirali_liste.get(position).getPuan())==0) holder.taban_puan.setText("Kontenjan Dolmadฤฑ!!!"); else if (Integer.valueOf(puan_sirali_liste.get(position).getPuan())<0) holder.taban_puan.setText("-------"); else holder.taban_puan.setText("Taban Puan : "+puan_sirali_liste.get(position).getPuan()); if(position % 2==1) holder.layout.setBackgroundColor(0x22000062); else holder.layout.setBackgroundColor(0x99000062); } @Override public int getItemCount() { return puan_sirali_liste.size(); } class ViewHolder extends RecyclerView.ViewHolder{ TextView universite_adฤฑ,sehir_adฤฑ,taban_puan; LinearLayout layout; public ViewHolder(@NonNull View itemView) { super(itemView); universite_adฤฑ=itemView.findViewById(R.id.Universite_adi); sehir_adฤฑ=itemView.findViewById(R.id.Sehir_adi); taban_puan=itemView.findViewById(R.id.Taban_puan); layout=itemView.findViewById(R.id.linear); } } }
[ "mustecep13@gmail.com" ]
mustecep13@gmail.com
a665f2eee9fcf3b8a5c4bd4a326c8955616c57e2
7dbc69f56e80cfaf2b50e5899e60f14e798461b2
/src/protocol/jms/org/apache/jmeter/protocol/jms/control/gui/JMSPublisherGui.java
0f26c77ddc44076c1aaf0a3a58f76b8adf541c35
[]
no_license
tangliangecq/jmeter
39c57b041ae2abc76f91efb43cf0e1a4663ede0e
0c89beb0f50b59cd8fd6203156d5ef7741236d23
refs/heads/master
2021-01-15T11:58:37.565348
2018-05-07T05:59:22
2018-05-07T05:59:22
99,639,461
0
0
null
null
null
null
UTF-8
Java
false
false
15,249
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.jmeter.protocol.jms.control.gui; import java.awt.BorderLayout; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.apache.jmeter.gui.util.FilePanel; import org.apache.jmeter.gui.util.JLabeledRadioI18N; import org.apache.jmeter.gui.util.JSyntaxTextArea; import org.apache.jmeter.gui.util.JTextScrollPane; import org.apache.jmeter.gui.util.VerticalPanel; import org.apache.jmeter.protocol.jms.sampler.JMSProperties; import org.apache.jmeter.protocol.jms.sampler.PublisherSampler; import org.apache.jmeter.samplers.gui.AbstractSamplerGui; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.gui.JLabeledPasswordField; import org.apache.jorphan.gui.JLabeledTextField; /** * This is the GUI for JMS Publisher * */ public class JMSPublisherGui extends AbstractSamplerGui implements ChangeListener { private static final long serialVersionUID = 240L; private static final String ALL_FILES = "*.*"; //$NON-NLS-1$ //++ These names are used in the JMX files, and must not be changed /** Take source from the named file */ public static final String USE_FILE_RSC = "jms_use_file"; //$NON-NLS-1$ /** Take source from a random file */ public static final String USE_RANDOM_RSC = "jms_use_random_file"; //$NON-NLS-1$ /** Take source from the text area */ private static final String USE_TEXT_RSC = "jms_use_text"; //$NON-NLS-1$ /** Create a TextMessage */ public static final String TEXT_MSG_RSC = "jms_text_message"; //$NON-NLS-1$ /** Create a MapMessage */ public static final String MAP_MSG_RSC = "jms_map_message"; //$NON-NLS-1$ /** Create an ObjectMessage */ public static final String OBJECT_MSG_RSC = "jms_object_message"; //$NON-NLS-1$ /** Create a BytesMessage */ public static final String BYTES_MSG_RSC = "jms_bytes_message"; //$NON-NLS-1$ //-- End of names used in JMX files // Button group resources when Bytes Message is selected private static final String[] CONFIG_ITEMS_BYTES_MSG = { USE_FILE_RSC, USE_RANDOM_RSC}; // Button group resources private static final String[] CONFIG_ITEMS = { USE_FILE_RSC, USE_RANDOM_RSC, USE_TEXT_RSC }; private static final String[] MSGTYPES_ITEMS = { TEXT_MSG_RSC, MAP_MSG_RSC, OBJECT_MSG_RSC, BYTES_MSG_RSC }; private final JCheckBox useProperties = new JCheckBox(JMeterUtils.getResString("jms_use_properties_file"), false); //$NON-NLS-1$ private final JLabeledRadioI18N configChoice = new JLabeledRadioI18N("jms_config", CONFIG_ITEMS, USE_TEXT_RSC); //$NON-NLS-1$ private final JLabeledTextField jndiICF = new JLabeledTextField(JMeterUtils.getResString("jms_initial_context_factory")); //$NON-NLS-1$ private final JLabeledTextField urlField = new JLabeledTextField(JMeterUtils.getResString("jms_provider_url")); //$NON-NLS-1$ private final JLabeledTextField jndiConnFac = new JLabeledTextField(JMeterUtils.getResString("jms_connection_factory")); //$NON-NLS-1$ private final JLabeledTextField jmsDestination = new JLabeledTextField(JMeterUtils.getResString("jms_topic")); //$NON-NLS-1$ private final JCheckBox useAuth = new JCheckBox(JMeterUtils.getResString("jms_use_auth"), false); //$NON-NLS-1$ private final JLabeledTextField jmsUser = new JLabeledTextField(JMeterUtils.getResString("jms_user")); //$NON-NLS-1$ private final JLabeledTextField jmsPwd = new JLabeledPasswordField(JMeterUtils.getResString("jms_pwd")); //$NON-NLS-1$ private final JLabeledTextField iterations = new JLabeledTextField(JMeterUtils.getResString("jms_itertions")); //$NON-NLS-1$ private final FilePanel messageFile = new FilePanel(JMeterUtils.getResString("jms_file"), ALL_FILES); //$NON-NLS-1$ private final FilePanel randomFile = new FilePanel(JMeterUtils.getResString("jms_random_file"), ALL_FILES); //$NON-NLS-1$ private final JSyntaxTextArea textMessage = new JSyntaxTextArea(10, 50); // $NON-NLS-1$ private final JLabeledRadioI18N msgChoice = new JLabeledRadioI18N("jms_message_type", MSGTYPES_ITEMS, TEXT_MSG_RSC); //$NON-NLS-1$ private JCheckBox useNonPersistentDelivery; // These are the names of properties used to define the labels private static final String DEST_SETUP_STATIC = "jms_dest_setup_static"; // $NON-NLS-1$ private static final String DEST_SETUP_DYNAMIC = "jms_dest_setup_dynamic"; // $NON-NLS-1$ // Button group resources private static final String[] DEST_SETUP_ITEMS = { DEST_SETUP_STATIC, DEST_SETUP_DYNAMIC }; private final JLabeledRadioI18N destSetup = new JLabeledRadioI18N("jms_dest_setup", DEST_SETUP_ITEMS, DEST_SETUP_STATIC); // $NON-NLS-1$ private JMSPropertiesPanel jmsPropertiesPanel; public JMSPublisherGui() { init(); } /** * the name of the property for the JMSPublisherGui is jms_publisher. */ @Override public String getLabelResource() { return "jms_publisher"; //$NON-NLS-1$ } /** * @see org.apache.jmeter.gui.JMeterGUIComponent#createTestElement() */ @Override public TestElement createTestElement() { PublisherSampler sampler = new PublisherSampler(); setupSamplerProperties(sampler); return sampler; } /** * Modifies a given TestElement to mirror the data in the gui components. * * @see org.apache.jmeter.gui.JMeterGUIComponent#modifyTestElement(TestElement) */ @Override public void modifyTestElement(TestElement s) { PublisherSampler sampler = (PublisherSampler) s; setupSamplerProperties(sampler); sampler.setDestinationStatic(destSetup.getText().equals(DEST_SETUP_STATIC)); } /** * Initialize the provided {@link PublisherSampler} with all the values as configured in the GUI. * * @param sampler {@link PublisherSampler} instance */ private void setupSamplerProperties(final PublisherSampler sampler) { this.configureTestElement(sampler); sampler.setUseJNDIProperties(String.valueOf(useProperties.isSelected())); sampler.setJNDIIntialContextFactory(jndiICF.getText()); sampler.setProviderUrl(urlField.getText()); sampler.setConnectionFactory(jndiConnFac.getText()); sampler.setDestination(jmsDestination.getText()); sampler.setUsername(jmsUser.getText()); sampler.setPassword(jmsPwd.getText()); sampler.setTextMessage(textMessage.getText()); sampler.setInputFile(messageFile.getFilename()); sampler.setRandomPath(randomFile.getFilename()); sampler.setConfigChoice(configChoice.getText()); sampler.setMessageChoice(msgChoice.getText()); sampler.setIterations(iterations.getText()); sampler.setUseAuth(useAuth.isSelected()); sampler.setUseNonPersistentDelivery(useNonPersistentDelivery.isSelected()); JMSProperties args = (JMSProperties) jmsPropertiesPanel.createTestElement(); sampler.setJMSProperties(args); } /** * init() adds jndiICF to the mainPanel. The class reuses logic from * SOAPSampler, since it is common. */ private void init() { setLayout(new BorderLayout()); setBorder(makeBorder()); add(makeTitlePanel(), BorderLayout.NORTH); JPanel mainPanel = new VerticalPanel(); add(mainPanel, BorderLayout.CENTER); mainPanel.add(useProperties); mainPanel.add(jndiICF); mainPanel.add(urlField); mainPanel.add(jndiConnFac); mainPanel.add(createDestinationPane()); mainPanel.add(createAuthPane()); mainPanel.add(iterations); jmsPropertiesPanel = new JMSPropertiesPanel(); //$NON-NLS-1$ mainPanel.add(jmsPropertiesPanel); configChoice.setLayout(new BoxLayout(configChoice, BoxLayout.X_AXIS)); mainPanel.add(configChoice); msgChoice.setLayout(new BoxLayout(msgChoice, BoxLayout.X_AXIS)); mainPanel.add(msgChoice); mainPanel.add(messageFile); mainPanel.add(randomFile); JPanel messageContentPanel = new JPanel(new BorderLayout()); messageContentPanel.add(new JLabel(JMeterUtils.getResString("jms_text_area")), BorderLayout.NORTH); messageContentPanel.add(new JTextScrollPane(textMessage), BorderLayout.CENTER); mainPanel.add(messageContentPanel); useProperties.addChangeListener(this); useAuth.addChangeListener(this); configChoice.addChangeListener(this); msgChoice.addChangeListener(this); } @Override public void clearGui(){ super.clearGui(); useProperties.setSelected(false); jndiICF.setText(""); // $NON-NLS-1$ urlField.setText(""); // $NON-NLS-1$ jndiConnFac.setText(""); // $NON-NLS-1$ jmsDestination.setText(""); // $NON-NLS-1$ jmsUser.setText(""); // $NON-NLS-1$ jmsPwd.setText(""); // $NON-NLS-1$ textMessage.setInitialText(""); // $NON-NLS-1$ messageFile.setFilename(""); // $NON-NLS-1$ randomFile.setFilename(""); // $NON-NLS-1$ msgChoice.setText(""); // $NON-NLS-1$ configChoice.setText(USE_TEXT_RSC); updateConfig(USE_TEXT_RSC); msgChoice.setText(TEXT_MSG_RSC); iterations.setText("1"); // $NON-NLS-1$ useAuth.setSelected(false); jmsUser.setEnabled(false); jmsPwd.setEnabled(false); destSetup.setText(DEST_SETUP_STATIC); useNonPersistentDelivery.setSelected(false); jmsPropertiesPanel.clearGui(); } /** * the implementation loads the URL and the soap action for the request. */ @Override public void configure(TestElement el) { super.configure(el); PublisherSampler sampler = (PublisherSampler) el; useProperties.setSelected(sampler.getUseJNDIPropertiesAsBoolean()); jndiICF.setText(sampler.getJNDIInitialContextFactory()); urlField.setText(sampler.getProviderUrl()); jndiConnFac.setText(sampler.getConnectionFactory()); jmsDestination.setText(sampler.getDestination()); jmsUser.setText(sampler.getUsername()); jmsPwd.setText(sampler.getPassword()); textMessage.setInitialText(sampler.getTextMessage()); textMessage.setCaretPosition(0); messageFile.setFilename(sampler.getInputFile()); randomFile.setFilename(sampler.getRandomPath()); configChoice.setText(sampler.getConfigChoice()); msgChoice.setText(sampler.getMessageChoice()); iterations.setText(sampler.getIterations()); useAuth.setSelected(sampler.isUseAuth()); jmsUser.setEnabled(useAuth.isSelected()); jmsPwd.setEnabled(useAuth.isSelected()); destSetup.setText(sampler.isDestinationStatic() ? DEST_SETUP_STATIC : DEST_SETUP_DYNAMIC); useNonPersistentDelivery.setSelected(sampler.getUseNonPersistentDelivery()); jmsPropertiesPanel.configure(sampler.getJMSProperties()); updateChoice(msgChoice.getText()); updateConfig(sampler.getConfigChoice()); } /** * When a widget state changes, it will notify this class so we can * enable/disable the correct items. */ @Override public void stateChanged(ChangeEvent event) { if (event.getSource() == configChoice) { updateConfig(configChoice.getText()); } else if (event.getSource() == msgChoice) { updateChoice(msgChoice.getText()); } else if (event.getSource() == useProperties) { jndiICF.setEnabled(!useProperties.isSelected()); urlField.setEnabled(!useProperties.isSelected()); } else if (event.getSource() == useAuth) { jmsUser.setEnabled(useAuth.isSelected()); jmsPwd.setEnabled(useAuth.isSelected()); } } /** * Update choice contains the actual logic for hiding or showing Textarea if Bytes message * is selected * * @param command * @since 2.9 */ private void updateChoice(String command) { String oldChoice = configChoice.getText(); if (BYTES_MSG_RSC.equals(command)) { String newChoice = USE_TEXT_RSC.equals(oldChoice) ? USE_FILE_RSC : oldChoice; configChoice.resetButtons(CONFIG_ITEMS_BYTES_MSG, newChoice); textMessage.setEnabled(false); } else { configChoice.resetButtons(CONFIG_ITEMS, oldChoice); textMessage.setEnabled(true); } validate(); } /** * Update config contains the actual logic for enabling or disabling text * message, file or random path. * * @param command */ private void updateConfig(String command) { if (command.equals(USE_TEXT_RSC)) { textMessage.setEnabled(true); messageFile.enableFile(false); randomFile.enableFile(false); } else if (command.equals(USE_RANDOM_RSC)) { textMessage.setEnabled(false); messageFile.enableFile(false); randomFile.enableFile(true); } else { textMessage.setEnabled(false); messageFile.enableFile(true); randomFile.enableFile(false); } } /** * @return JPanel that contains destination infos */ private JPanel createDestinationPane() { JPanel pane = new JPanel(new BorderLayout(3, 0)); pane.add(jmsDestination, BorderLayout.WEST); destSetup.setLayout(new BoxLayout(destSetup, BoxLayout.X_AXIS)); pane.add(destSetup, BorderLayout.CENTER); useNonPersistentDelivery = new JCheckBox(JMeterUtils.getResString("jms_use_non_persistent_delivery"),false); //$NON-NLS-1$ pane.add(useNonPersistentDelivery, BorderLayout.EAST); return pane; } /** * @return JPanel Panel with checkbox to choose auth , user and password */ private JPanel createAuthPane() { JPanel pane = new JPanel(); pane.setLayout(new BoxLayout(pane, BoxLayout.X_AXIS)); pane.add(useAuth); pane.add(Box.createHorizontalStrut(10)); pane.add(jmsUser); pane.add(Box.createHorizontalStrut(10)); pane.add(jmsPwd); return pane; } }
[ "9070586@qq.com" ]
9070586@qq.com
e4049459a48659c78cb014738fd6fb480bfcda61
74b47b895b2f739612371f871c7f940502e7165b
/aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/EndpointTypesElement.java
b911e006cad2bfa6730b4ccbc7a3be4c0e1ac971
[ "Apache-2.0" ]
permissive
baganda07/aws-sdk-java
fe1958ed679cd95b4c48f971393bf03eb5512799
f19bdb30177106b5d6394223a40a382b87adf742
refs/heads/master
2022-11-09T21:55:43.857201
2022-10-24T21:08:19
2022-10-24T21:08:19
221,028,223
0
0
Apache-2.0
2019-11-11T16:57:12
2019-11-11T16:57:11
null
UTF-8
Java
false
false
2,060
java
/* * Copyright 2017-2022 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.pinpoint.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum EndpointTypesElement { PUSH("PUSH"), GCM("GCM"), APNS("APNS"), APNS_SANDBOX("APNS_SANDBOX"), APNS_VOIP("APNS_VOIP"), APNS_VOIP_SANDBOX("APNS_VOIP_SANDBOX"), ADM("ADM"), SMS("SMS"), VOICE("VOICE"), EMAIL("EMAIL"), BAIDU("BAIDU"), CUSTOM("CUSTOM"), IN_APP("IN_APP"); private String value; private EndpointTypesElement(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return EndpointTypesElement corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static EndpointTypesElement fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (EndpointTypesElement enumEntry : EndpointTypesElement.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
[ "" ]
d3a747a888eed8a5951a0092fe4162450b198a6a
8361f060ab37e0d894f723bb22b1fdd2f70c2639
/AplikacjaMobila/app/src/androidTest/java/com/example/l/aplikacjamobila/ExampleInstrumentedTest.java
d5f37c67434c6b2f248b1e24e4b1a0f06cdd8b08
[]
no_license
PatrykM5/Projekt_PT
faca82d3fc24a037668fcb70383ed244e7f56d29
f932623a835124dcb9be94d1198e0ea4fb9be45e
refs/heads/master
2021-01-22T18:42:37.808056
2017-06-18T14:01:16
2017-06-18T14:01:16
85,104,623
0
0
null
null
null
null
UTF-8
Java
false
false
762
java
package com.example.l.aplikacjamobila; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.l.aplikacjamobila", appContext.getPackageName()); } }
[ "jakub.kostrzewski@tlen.pl" ]
jakub.kostrzewski@tlen.pl
4e064c4b132290d69f31c4c56c610d19916c9d5b
8c47aa7e18c79131a9788e39e8b8e258924f8d53
/dac/backend/src/main/java/com/dremio/dac/service/catalog/CatalogServiceHelper.java
b30240dbaec15b400d242122a28d691a2ce394ef
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
kunichan2013/dremio-oss
68eb8e27e81d3d9288c43710ac5dea787d68db99
72666ba69ed580899856cc9d504790c652a42328
refs/heads/master
2020-03-30T09:39:16.462913
2018-10-17T13:15:56
2018-10-17T13:15:56
151,085,852
0
0
Apache-2.0
2018-10-01T12:33:55
2018-10-01T12:33:54
null
UTF-8
Java
false
false
42,712
java
/* * Copyright (C) 2017-2018 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.dac.service.catalog; import static com.dremio.dac.util.DatasetsUtil.toDatasetConfig; import static com.dremio.service.namespace.dataset.proto.DatasetType.VIRTUAL_DATASET; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.List; import java.util.Objects; import javax.inject.Inject; import javax.ws.rs.core.SecurityContext; import org.apache.commons.collections.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.dremio.common.exceptions.ExecutionSetupException; import com.dremio.common.exceptions.UserException; import com.dremio.common.utils.PathUtils; import com.dremio.dac.api.CatalogEntity; import com.dremio.dac.api.CatalogItem; import com.dremio.dac.api.Dataset; import com.dremio.dac.api.File; import com.dremio.dac.api.Folder; import com.dremio.dac.api.Home; import com.dremio.dac.api.Source; import com.dremio.dac.api.Space; import com.dremio.dac.explore.model.DatasetPath; import com.dremio.dac.homefiles.HomeFileSystemStoragePlugin; import com.dremio.dac.homefiles.HomeFileTool; import com.dremio.dac.model.sources.PhysicalDatasetPath; import com.dremio.dac.model.spaces.HomeName; import com.dremio.dac.model.spaces.HomePath; import com.dremio.dac.model.spaces.SpaceName; import com.dremio.dac.service.datasets.DatasetVersionMutator; import com.dremio.dac.service.errors.SourceNotFoundException; import com.dremio.dac.service.reflection.ReflectionServiceHelper; import com.dremio.dac.service.source.SourceService; import com.dremio.dac.util.DatasetsUtil; import com.dremio.exec.catalog.Catalog; import com.dremio.exec.catalog.DremioTable; import com.dremio.exec.server.SabotContext; import com.dremio.exec.store.SchemaEntity; import com.dremio.exec.store.StoragePlugin; import com.dremio.exec.store.dfs.FileSystemPlugin; import com.dremio.service.namespace.NamespaceAttribute; import com.dremio.service.namespace.NamespaceException; import com.dremio.service.namespace.NamespaceKey; import com.dremio.service.namespace.NamespaceService; import com.dremio.service.namespace.dataset.proto.AccelerationSettings; import com.dremio.service.namespace.dataset.proto.DatasetConfig; import com.dremio.service.namespace.dataset.proto.PhysicalDataset; import com.dremio.service.namespace.dataset.proto.VirtualDataset; import com.dremio.service.namespace.file.FileFormat; import com.dremio.service.namespace.file.proto.FileConfig; import com.dremio.service.namespace.physicaldataset.proto.PhysicalDatasetConfig; import com.dremio.service.namespace.proto.EntityId; import com.dremio.service.namespace.proto.NameSpaceContainer; import com.dremio.service.namespace.source.proto.SourceConfig; import com.dremio.service.namespace.space.proto.FolderConfig; import com.dremio.service.namespace.space.proto.HomeConfig; import com.dremio.service.namespace.space.proto.SpaceConfig; import com.dremio.service.reflection.proto.ReflectionGoal; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; /** * Catalog Service Helper * * A helper that allows interacting with the Dremio catalog. Allows browsing and created/editing/deleting of sources, * spaces, datasets, files and folders where allowed. * */ public class CatalogServiceHelper { private static final Logger logger = LoggerFactory.getLogger(CatalogServiceHelper.class); public static final NamespaceAttribute[] DEFAULT_NS_ATTRIBUTES = new NamespaceAttribute[]{}; private final Catalog catalog; private final SecurityContext context; private final SourceService sourceService; private final NamespaceService namespaceService; private final SabotContext sabotContext; private final ReflectionServiceHelper reflectionServiceHelper; private final HomeFileTool homeFileTool; private final DatasetVersionMutator datasetVersionMutator; @Inject public CatalogServiceHelper(Catalog catalog, SecurityContext context, SourceService sourceService, NamespaceService namespaceService, SabotContext sabotContext, ReflectionServiceHelper reflectionServiceHelper, HomeFileTool homeFileTool, DatasetVersionMutator datasetVersionMutator) { this.catalog = catalog; this.context = context; this.sourceService = sourceService; this.namespaceService = namespaceService; this.sabotContext = sabotContext; this.reflectionServiceHelper = reflectionServiceHelper; this.homeFileTool = homeFileTool; this.datasetVersionMutator = datasetVersionMutator; } public Optional<DatasetConfig> getDatasetById(String datasetId) { DremioTable table = catalog.getTable(datasetId); if (table == null) { return Optional.absent(); } return Optional.fromNullable(table.getDatasetConfig()); } private HomeConfig getHomeForCurrentUser() throws NamespaceException { HomePath homePath = new HomePath(HomeName.getUserHomePath(context.getUserPrincipal().getName())); return namespaceService.getHome(homePath.toNamespaceKey()); } public List<CatalogItem> getTopLevelCatalogItems() { List<CatalogItem> topLevelItems = new ArrayList<>(); try { HomeConfig homeForCurrentUser = getHomeForCurrentUser(); topLevelItems.add(CatalogItem.fromHomeConfig(homeForCurrentUser)); } catch (NamespaceException e) { // if for some reason we can't find a home space, log it but keep going logger.warn("Failed to find home space for user [{}]", context.getUserPrincipal().getName()); } for (SpaceConfig spaceConfig : namespaceService.getSpaces()) { topLevelItems.add(CatalogItem.fromSpaceConfig(spaceConfig)); } for (SourceConfig sourceConfig : sourceService.getSources()) { topLevelItems.add(CatalogItem.fromSourceConfig(sourceConfig)); } return topLevelItems; } private NameSpaceContainer getNamespaceEntity(NamespaceKey namespaceKey) throws NamespaceException { return namespaceService.getEntities(Collections.singletonList(namespaceKey)).get(0); } protected NameSpaceContainer getRootContainer(List<String> path) throws NamespaceException { NamespaceKey parentKey = new NamespaceKey(path.get(0)); List<NameSpaceContainer> entities = namespaceService.getEntities(Collections.singletonList(parentKey)); return entities.get(0); } public Optional<CatalogEntity> getCatalogEntityByPath(List<String> path) throws NamespaceException { NameSpaceContainer entity = getNamespaceEntity(new NamespaceKey(path)); if (entity == null) { // if we can't find it in the namespace, check if its a non-promoted file/folder in a filesystem source Optional<CatalogItem> internalItem = getInternalItemByPath(path); if (!internalItem.isPresent()) { return Optional.absent(); } return getCatalogEntityFromCatalogItem(internalItem.get()); } else { return getCatalogEntityFromNamespaceContainer(extractFromNamespaceContainer(entity).get()); } } public Optional<CatalogEntity> getCatalogEntityById(String id) throws NamespaceException { Optional<?> entity = getById(id); if (!entity.isPresent()) { return Optional.absent(); } return getCatalogEntityFromNamespaceContainer(entity.get()); } private Optional<CatalogEntity> getCatalogEntityFromNamespaceContainer(Object object) throws NamespaceException { if (object instanceof SourceConfig) { SourceConfig config = (SourceConfig) object; Source source = fromSourceConfig(config, getChildrenForPath(new NamespaceKey(config.getName()))); return Optional.of((CatalogEntity) source); } else if (object instanceof SpaceConfig) { SpaceConfig config = (SpaceConfig) object; Space space = getSpaceFromConfig(config, getChildrenForPath(new NamespaceKey(config.getName()))); return Optional.of((CatalogEntity) space); } else if (object instanceof DatasetConfig) { DatasetConfig config = (DatasetConfig) object; Dataset dataset; // only set acceleration settings if one exists in the store - we don't want inherited settings Optional<AccelerationSettings> settings = getStoredReflectionSettingsForDataset(config); if (settings.isPresent()) { dataset = getDatasetFromConfig(config, new Dataset.RefreshSettings(settings.get())); } else { dataset = getDatasetFromConfig(config, null); } return Optional.of((CatalogEntity) dataset); } else if (object instanceof HomeConfig) { HomeConfig config = (HomeConfig) object; Home home = getHomeFromConfig(config, getChildrenForPath(new NamespaceKey(HomeName.getUserHomePath(config.getOwner()).getName()))); return Optional.of((CatalogEntity) home); } else if (object instanceof FolderConfig) { FolderConfig config = (FolderConfig) object; Folder folder = getFolderFromConfig(config, getChildrenForPath(new NamespaceKey(config.getFullPathList()))); return Optional.of((CatalogEntity) folder); } else if (object instanceof CatalogEntity) { // this is something not in the namespace, a file/folder from a filesystem source CatalogEntity catalogEntity = (CatalogEntity) object; return Optional.of(catalogEntity); } else { throw new IllegalArgumentException(String.format("Unexpected catalog type found [%s].", object.getClass().getName())); } } /** * Given an id, retrieves the entity from the namespace. Also handles fake ids (using generateInternalId) that we * generate for folders/files that exist in file-based sources that are not in the namespace. * * Note: this returns the namespace object (DatasetConfig, etc) for entites found in the namespace. For non-namespace * items it returns the appropriate CatalogEntity item (Folder/File only). */ private Optional<?> getById(String id) { try { if (isInternalId(id)) { Optional<CatalogItem> catalogItem = getInternalItemByPath(getPathFromInternalId(id)); if (!catalogItem.isPresent()) { return Optional.absent(); } return getCatalogEntityFromCatalogItem(catalogItem.get()); } else { Optional<?> optional = extractFromNamespaceContainer(namespaceService.getEntityById(id)); if (!optional.isPresent()) { logger.warn("Could not find entity with id [{}]", id); } return optional; } } catch (NamespaceException e) { logger.warn("Failed to get entity ", e); return Optional.absent(); } } private Optional<CatalogEntity> getCatalogEntityFromCatalogItem(CatalogItem catalogItem) throws NamespaceException { // can either be a folder or a file if (catalogItem.getContainerType() == CatalogItem.ContainerSubType.FOLDER) { Folder folder = new Folder(catalogItem.getId(), catalogItem.getPath(), null, getListingForInternalItem(getPathFromInternalId(catalogItem.getId()))); return Optional.of(folder); } else if (catalogItem.getType() == CatalogItem.CatalogItemType.FILE) { File file = new File(catalogItem.getId(), catalogItem.getPath()); return Optional.of(file); } throw new RuntimeException(String.format("Could not retrieve internal item [%s]", catalogItem.toString())); } private Optional<?> extractFromNamespaceContainer(NameSpaceContainer entity) { if (entity == null) { // if we can't find it by id, maybe its not in the namespace return Optional.absent(); } Optional result = Optional.absent(); switch (entity.getType()) { case SOURCE: { result = Optional.of(entity.getSource()); break; } case SPACE: { result = Optional.of(entity.getSpace()); break; } case DATASET: { // for datasets go to the catalog to ensure we have schema. DatasetConfig dataset = entity.getDataset(); result = Optional.of(catalog.getTable(dataset.getId().getId()).getDatasetConfig()); break; } case HOME: { result = Optional.of(entity.getHome()); break; } case FOLDER: { result = Optional.of(entity.getFolder()); break; } default: { throw new RuntimeException(String.format("Unsupported namespace entity type [%s]", entity.getType())); } } return result; } private List<CatalogItem> getListingForInternalItem(List<String> path) throws NamespaceException { NameSpaceContainer rootEntity = getNamespaceEntity(new NamespaceKey(path.get(0))); if (rootEntity.getType() == NameSpaceContainer.Type.SOURCE) { return getChildrenForPath(new NamespaceKey(path)); } throw new IllegalArgumentException(String.format("Can only get listing for sources, but [%s] is of type [%s]", path, rootEntity.getType())); } private Optional<CatalogItem> getInternalItemByPath(List<String> path) throws NamespaceException { NameSpaceContainer rootEntity = getNamespaceEntity(new NamespaceKey(path.get(0))); if (rootEntity != null && rootEntity.getType() == NameSpaceContainer.Type.SOURCE) { return Optional.of(getInternalItemFromSource(rootEntity.getSource(), path)); } else { logger.warn("Can not find internal item with path [%s].", path); return Optional.absent(); } } private CatalogItem getInternalItemFromSource(SourceConfig sourceConfig, List<String> path) { final StoragePlugin plugin = getStoragePlugin(sourceConfig.getName()); if (!(plugin instanceof FileSystemPlugin)) { throw new IllegalArgumentException(String.format("Can not get internal item from non-filesystem source [%s] of type [%s]", sourceConfig.getName(), plugin.getClass().getName())); } SchemaEntity entity = ((FileSystemPlugin) plugin).get(path, context.getUserPrincipal().getName()); return convertSchemaEntityToCatalogItem(entity, path.subList(0, path.size() - 1)); } private CatalogItem convertSchemaEntityToCatalogItem(SchemaEntity entity, List<String> parentPath) { final List<String> entityPath = Lists.newArrayList(parentPath); entityPath.add(entity.getPath()); CatalogItem catalogItem = null; switch(entity.getType()) { case FILE: { catalogItem = new CatalogItem(generateInternalId(entityPath), entityPath, null, CatalogItem.CatalogItemType.FILE, null, null); break; } case FOLDER: { catalogItem = new CatalogItem(generateInternalId(entityPath), entityPath, null, CatalogItem.CatalogItemType.CONTAINER, null, CatalogItem.ContainerSubType.FOLDER); break; } case FILE_TABLE: case FOLDER_TABLE: { try { final NamespaceKey namespaceKey = new NamespaceKey(PathUtils.toPathComponents(PathUtils.toFSPath(entityPath))); final DatasetConfig dataset = namespaceService.getDataset(namespaceKey); catalogItem = new CatalogItem(dataset.getId().getId(), entityPath, null, CatalogItem.CatalogItemType.DATASET, CatalogItem.DatasetSubType.PROMOTED, null); } catch (NamespaceException e) { logger.warn("Can not find item with path [%s]", entityPath, e); } break; } default: { throw new RuntimeException(String.format("Trying to convert unexpected schema entity [%s] of type [%s].", entity.getPath(), entity.getType())); } } return catalogItem; } @VisibleForTesting public List<CatalogItem> getChildrenForPath(NamespaceKey path) throws NamespaceException { final List<CatalogItem> catalogItems = new ArrayList<>(); // get parent info NameSpaceContainer rootEntity = getNamespaceEntity(new NamespaceKey(path.getPathComponents().get(0))); if (rootEntity.getType() == NameSpaceContainer.Type.SOURCE) { catalogItems.addAll(getChildrenForSourcePath(rootEntity.getSource().getName(), path.getPathComponents())); } else { // for non-source roots, go straight to the namespace catalogItems.addAll(getNamespaceChildrenForPath(path)); } return catalogItems; } private List<CatalogItem> getNamespaceChildrenForPath(NamespaceKey path) { final List<CatalogItem> catalogItems = new ArrayList<>(); try { final List<NameSpaceContainer> list = namespaceService.list(path); for (NameSpaceContainer container : list) { final Optional<CatalogItem> item = CatalogItem.fromNamespaceContainer(container); if (item.isPresent()) { catalogItems.add(item.get()); } } } catch (NamespaceException e) { logger.warn(e.getMessage()); } return catalogItems; } /** * Returns all children of the listingPath for a source */ private List<CatalogItem> getChildrenForSourcePath(String sourceName, List<String> listingPath) { final List<CatalogItem> catalogItems = new ArrayList<>(); final StoragePlugin plugin = getStoragePlugin(sourceName); if (plugin instanceof FileSystemPlugin) { // For file based plugins, use the list method to get the listing. That code will merge in any promoted datasets // that are in the namespace for us. This is in line with what the UI does. final List<SchemaEntity> list = ((FileSystemPlugin) plugin).list(listingPath, context.getUserPrincipal().getName()); for (SchemaEntity entity : list) { final CatalogItem catalogItem = convertSchemaEntityToCatalogItem(entity, listingPath); if (catalogItem != null) { catalogItems.add(catalogItem); } } } else { // for non-file based plugins we can go directly to the namespace catalogItems.addAll(getNamespaceChildrenForPath(new NamespaceKey(listingPath))); } return catalogItems; } public CatalogEntity createCatalogItem(CatalogEntity entity) throws NamespaceException, UnsupportedOperationException, ExecutionSetupException { if (entity instanceof Space) { Space space = (Space) entity; return createSpace(space, getNamespaceAttributes(entity)); } else if (entity instanceof Source) { return createSource((Source) entity, getNamespaceAttributes(entity)); } else if (entity instanceof Dataset) { Dataset dataset = (Dataset) entity; return createDataset(dataset, getNamespaceAttributes(entity)); } else if (entity instanceof Folder) { try { return createFolder((Folder) entity, getNamespaceAttributes(entity)); } catch (UserException e) { throw new ConcurrentModificationException(e); } } else { throw new UnsupportedOperationException(String.format("Catalog item of type [%s] can not be edited", entity.getClass().getName())); } } protected CatalogEntity createDataset(Dataset dataset, NamespaceAttribute... attributes) throws NamespaceException { validateDataset(dataset); // only handle VDS Preconditions.checkArgument(dataset.getType() != Dataset.DatasetType.PHYSICAL_DATASET, "Phyiscal Datasets can only be created by promoting other entities."); Preconditions.checkArgument(dataset.getId() == null, "Dataset id is immutable."); // verify we can save NamespaceKey topLevelKey = new NamespaceKey(dataset.getPath().get(0)); NamespaceKey parentNamespaceKey = new NamespaceKey(dataset.getPath().subList(0, dataset.getPath().size() - 1)); NamespaceKey namespaceKey = new NamespaceKey(dataset.getPath()); Preconditions.checkArgument(namespaceService.exists(parentNamespaceKey), String.format("Dataset parent path [%s] doesn't exist.", parentNamespaceKey.toString())); // can only create VDs in a space or home NameSpaceContainer entity = getNamespaceEntity(topLevelKey); List<NameSpaceContainer.Type> types = Arrays.asList(NameSpaceContainer.Type.SPACE, NameSpaceContainer.Type.HOME); Preconditions.checkArgument(types.contains(entity.getType()), "Virtual datasets can only be saved into spaces or home space."); sabotContext.getViewCreator(context.getUserPrincipal().getName()).createView(dataset.getPath(), dataset.getSql(), dataset.getSqlContext(), attributes); DatasetConfig created = namespaceService.getDataset(namespaceKey); return getDatasetFromConfig(created, null); } /** * Promotes the target to a PDS using the formatting options submitted via dataset. */ public Dataset promoteToDataset(String targetId, Dataset dataset) throws NamespaceException, UnsupportedOperationException { Preconditions.checkArgument(dataset.getType() == Dataset.DatasetType.PHYSICAL_DATASET, "Promoting can only create physical datasets."); // verify we can promote the target entity List<String> path = getPathFromInternalId(targetId); Preconditions.checkArgument(CollectionUtils.isEqualCollection(path, dataset.getPath()), "Entity id does not match the path specified in the dataset."); // validation validateDataset(dataset); Preconditions.checkArgument(dataset.getFormat() != null, "To promote a dataset, format settings are required."); NamespaceKey namespaceKey = new NamespaceKey(path); Optional<CatalogItem> catalogItem = getInternalItemByPath(path); if (!catalogItem.isPresent()) { throw new IllegalArgumentException(String.format("Could not find entity to promote with path [%s]", path)); } // can only promote a file or folder from a source (which getInternalItemByPath verifies) if (catalogItem.get().getContainerType() == CatalogItem.ContainerSubType.FOLDER || catalogItem.get().getType() == CatalogItem.CatalogItemType.FILE) { PhysicalDatasetConfig physicalDatasetConfig = new PhysicalDatasetConfig(); physicalDatasetConfig.setName(namespaceKey.getName()); physicalDatasetConfig.setFormatSettings(dataset.getFormat().asFileConfig()); if (catalogItem.get().getContainerType() == CatalogItem.ContainerSubType.FOLDER) { physicalDatasetConfig.setType(com.dremio.service.namespace.dataset.proto.DatasetType.PHYSICAL_DATASET_SOURCE_FOLDER); } else { physicalDatasetConfig.setType(com.dremio.service.namespace.dataset.proto.DatasetType.PHYSICAL_DATASET_SOURCE_FILE); } physicalDatasetConfig.setFullPathList(path); catalog.createOrUpdateDataset(namespaceService, new NamespaceKey(namespaceKey.getRoot()), new PhysicalDatasetPath(path).toNamespaceKey(), toDatasetConfig(physicalDatasetConfig, null), getNamespaceAttributes(dataset)); } else { throw new UnsupportedOperationException(String.format("Can only promote a folder or a file but found [%s]", catalogItem.get().getType())); } return getDatasetFromConfig(namespaceService.getDataset(namespaceKey), null); } private void updateDataset(Dataset dataset, NamespaceAttribute... attributes) throws NamespaceException { Preconditions.checkArgument(dataset.getId() != null, "Dataset Id is missing."); DatasetConfig currentDatasetConfig = namespaceService.findDatasetByUUID(dataset.getId()); if (currentDatasetConfig == null) { throw new IllegalArgumentException(String.format("Could not find dataset with id [%s]", dataset.getId())); } validateDataset(dataset); // use the version of the dataset to check for concurrency issues currentDatasetConfig.setVersion(Long.valueOf(dataset.getTag())); NamespaceKey namespaceKey = new NamespaceKey(dataset.getPath()); // check type if (dataset.getType() == Dataset.DatasetType.PHYSICAL_DATASET) { // cannot change the path of a physical dataset Preconditions.checkArgument(CollectionUtils.isEqualCollection(dataset.getPath(), currentDatasetConfig.getFullPathList()), "Dataset path can not be modified."); Preconditions.checkArgument( currentDatasetConfig.getType() != VIRTUAL_DATASET, "Dataset type can not be modified"); // PDS specific config currentDatasetConfig.getPhysicalDataset().setAllowApproxStats(dataset.getApproximateStatisticsAllowed()); if (currentDatasetConfig.getType() == com.dremio.service.namespace.dataset.proto.DatasetType.PHYSICAL_DATASET_HOME_FILE) { DatasetConfig datasetConfig = toDatasetConfig(dataset.getFormat().asFileConfig(), currentDatasetConfig.getType(), context.getUserPrincipal().getName(), currentDatasetConfig.getId()); catalog.createOrUpdateDataset(namespaceService, new NamespaceKey(HomeFileSystemStoragePlugin.HOME_PLUGIN_NAME), namespaceKey, datasetConfig, attributes); } else if (currentDatasetConfig.getType() == com.dremio.service.namespace.dataset.proto.DatasetType.PHYSICAL_DATASET_SOURCE_FILE || currentDatasetConfig.getType() == com.dremio.service.namespace.dataset.proto.DatasetType.PHYSICAL_DATASET_SOURCE_FOLDER) { Preconditions.checkArgument(dataset.getFormat() != null, "Promoted dataset needs to have a format set."); //DatasetConfig datasetConfig = toDatasetConfig(dataset.getFormat().asFileConfig(), currentDatasetConfig.getType(), context.getUserPrincipal().getName(), currentDatasetConfig.getId()); // only thing that can change is the formatting currentDatasetConfig.getPhysicalDataset().setFormatSettings(dataset.getFormat().asFileConfig()); catalog.createOrUpdateDataset(namespaceService, new NamespaceKey(HomeFileSystemStoragePlugin.HOME_PLUGIN_NAME), namespaceKey, currentDatasetConfig, attributes); } // update refresh settings Optional<AccelerationSettings> storedReflectionSettingsForDataset = getStoredReflectionSettingsForDataset(currentDatasetConfig); if (dataset.getAccelerationRefreshPolicy() == null && storedReflectionSettingsForDataset.isPresent()) { // we are clearing the acceleration settings for the dataset reflectionServiceHelper.getReflectionSettings().removeSettings(namespaceKey); } else if (dataset.getAccelerationRefreshPolicy() != null){ reflectionServiceHelper.getReflectionSettings().setReflectionSettings(namespaceKey, dataset.getAccelerationRefreshPolicy().toAccelerationSettings()); } } else if (dataset.getType() == Dataset.DatasetType.VIRTUAL_DATASET) { Preconditions.checkArgument(currentDatasetConfig.getType() == VIRTUAL_DATASET, "Dataset type can not be modified"); // Check if the dataset is being renamed if (!Objects.equals(currentDatasetConfig.getFullPathList(), dataset.getPath())) { datasetVersionMutator.renameDataset(new DatasetPath(currentDatasetConfig.getFullPathList()), new DatasetPath(dataset.getPath())); currentDatasetConfig = namespaceService.getDataset(namespaceKey); } VirtualDataset virtualDataset = currentDatasetConfig.getVirtualDataset(); virtualDataset.setSql(dataset.getSql()); virtualDataset.setContextList(dataset.getSqlContext()); currentDatasetConfig.setVirtualDataset(virtualDataset); namespaceService.addOrUpdateDataset(namespaceKey, currentDatasetConfig, attributes); } } private void deleteDataset(DatasetConfig config, String tag) throws NamespaceException, UnsupportedOperationException, IOException { // if no tag is passed in, use the latest version long version = config.getVersion(); if (tag != null) { version = Long.parseLong(tag); } switch (config.getType()) { case PHYSICAL_DATASET: { throw new UnsupportedOperationException("A physical dataset can not be deleted."); } case PHYSICAL_DATASET_SOURCE_FILE: case PHYSICAL_DATASET_SOURCE_FOLDER: { // remove the formatting removeFormatFromDataset(config, version); break; } case PHYSICAL_DATASET_HOME_FILE: case PHYSICAL_DATASET_HOME_FOLDER: { deleteHomeDataset(config, version); break; } case VIRTUAL_DATASET: { namespaceService.deleteDataset(new NamespaceKey(config.getFullPathList()), version); break; } default: { throw new RuntimeException(String.format("Dataset [%s] of unknown type [%s] found.", config.getId().getId(), config.getType())); } } } public void deleteHomeDataset(DatasetConfig config, long version) throws IOException, NamespaceException { FileConfig formatSettings = config.getPhysicalDataset().getFormatSettings(); homeFileTool.deleteFile(formatSettings.getLocation()); namespaceService.deleteDataset(new NamespaceKey(config.getFullPathList()), version); } public void removeFormatFromDataset(DatasetConfig config, long version) { Iterable<ReflectionGoal> reflections = reflectionServiceHelper.getReflectionsForDataset(config.getId().getId()); for (ReflectionGoal reflection : reflections) { reflectionServiceHelper.removeReflection(reflection.getId().getId()); } PhysicalDatasetPath datasetPath = new PhysicalDatasetPath(config.getFullPathList()); sourceService.deletePhysicalDataset(datasetPath.getSourceName(), datasetPath, version); } private void validateDataset(Dataset dataset) { Preconditions.checkArgument(dataset.getType() != null, "Dataset type is required."); Preconditions.checkArgument(dataset.getPath() != null, "Dataset path is required."); if (dataset.getType() == Dataset.DatasetType.VIRTUAL_DATASET) { // VDS requires sql Preconditions.checkArgument(dataset.getSql() != null, "Virtual dataset must have sql defined."); Preconditions.checkArgument(dataset.getSql().trim().length() > 0, "Virtual dataset cannot have empty sql defined."); Preconditions.checkArgument(dataset.getFormat() == null, "Virtual dataset cannot have a format defined."); } else { // PDS Preconditions.checkArgument(dataset.getSql() == null, "Physical dataset can not have sql defined."); Preconditions.checkArgument(dataset.getSqlContext() == null, "Physical dataset can not have sql context defined."); } } protected CatalogEntity createSpace(Space space, NamespaceAttribute... attributes) throws NamespaceException { String spaceName = space.getName(); Preconditions.checkArgument(space.getId() == null, "Space id is immutable."); Preconditions.checkArgument(spaceName != null, "Space name is required."); Preconditions.checkArgument(spaceName.trim().length() > 0, "Space name cannot be empty."); // TODO: move the space name validation somewhere reusable instead of having to create a new SpaceName new SpaceName(spaceName); NamespaceKey namespaceKey = new NamespaceKey(spaceName); // check if space already exists with the given name. if (namespaceService.exists(namespaceKey, NameSpaceContainer.Type.SPACE)) { throw new ConcurrentModificationException(String.format("A space with the name [%s] already exists.", spaceName)); } namespaceService.addOrUpdateSpace(namespaceKey, getSpaceConfig(space), attributes); return getSpaceFromConfig(namespaceService.getSpace(namespaceKey), null); } protected void updateSpace(Space space, NamespaceAttribute... attributes) throws NamespaceException { NamespaceKey namespaceKey = new NamespaceKey(space.getName()); SpaceConfig spaceConfig = namespaceService.getSpace(namespaceKey); Preconditions.checkArgument(space.getName().equals(spaceConfig.getName()), "Space name is immutable."); namespaceService.addOrUpdateSpace(namespaceKey, getSpaceConfig(space), attributes); } protected void deleteSpace(SpaceConfig spaceConfig, long version) throws NamespaceException { namespaceService.deleteSpace(new NamespaceKey(spaceConfig.getName()), version); } protected CatalogEntity createSource(Source source, NamespaceAttribute... attributes) throws NamespaceException, ExecutionSetupException { SourceConfig sourceConfig = sourceService.createSource(source.toSourceConfig(), attributes); return fromSourceConfig(sourceConfig, getChildrenForPath(new NamespaceKey(sourceConfig.getName()))); } public CatalogEntity updateCatalogItem(CatalogEntity entity, String id) throws NamespaceException, UnsupportedOperationException, ExecutionSetupException { Preconditions.checkArgument(entity.getId().equals(id), "Ids must match."); if (entity instanceof Dataset) { Dataset dataset = (Dataset) entity; updateDataset(dataset, getNamespaceAttributes(entity)); } else if (entity instanceof Source) { Source source = (Source) entity; sourceService.updateSource(id, source.toSourceConfig(), getNamespaceAttributes(entity)); } else if (entity instanceof Space) { Space space = (Space) entity; updateSpace(space, getNamespaceAttributes(space)); } else if (entity instanceof Folder) { Folder folder = (Folder) entity; updateFolder(folder, getNamespaceAttributes(entity)); } else { throw new UnsupportedOperationException(String.format("Catalog item [%s] of type [%s] can not be edited.", id, entity.getClass().getName())); } Optional<CatalogEntity> newEntity = getCatalogEntityById(id); if (newEntity.isPresent()) { return newEntity.get(); } else { throw new RuntimeException(String.format("Catalog item [%s] of type [%s] could not be found", id, entity.getClass().getName())); } } public void deleteCatalogItem(String id, String tag) throws NamespaceException, UnsupportedOperationException { Optional<?> entity = getById(id); if (!entity.isPresent()) { throw new IllegalArgumentException(String.format("Could not find entity with id [%s].", id)); } Object object = entity.get(); if (object instanceof SourceConfig) { SourceConfig config = (SourceConfig) object; if (tag != null) { config.setVersion(Long.valueOf(tag)); } sourceService.deleteSource(config); } else if (object instanceof SpaceConfig) { SpaceConfig config = (SpaceConfig) object; long version = config.getVersion(); if (tag != null) { version = Long.parseLong(tag); } deleteSpace(config, version); } else if (object instanceof DatasetConfig) { DatasetConfig config = (DatasetConfig) object; try { deleteDataset(config, tag); } catch (IOException e) { throw new IllegalArgumentException(e); } } else if (object instanceof FolderConfig) { FolderConfig config = (FolderConfig) object; long version = config.getVersion(); if (tag != null) { version = Long.parseLong(tag); } namespaceService.deleteFolder(new NamespaceKey(config.getFullPathList()), version); } else { throw new UnsupportedOperationException(String.format("Catalog item [%s] of type [%s] can not be deleted.", id, object.getClass().getName())); } } protected Folder createFolder(Folder folder, NamespaceAttribute... attributes) throws NamespaceException { NamespaceKey parentKey = new NamespaceKey(folder.getPath().subList(0, folder.getPath().size() - 1)); List<NameSpaceContainer> entities = namespaceService.getEntities(Collections.singletonList(parentKey)); NameSpaceContainer container = entities.get(0); if (container == null) { // if we can't find it by id, maybe its not in the namespace throw new IllegalArgumentException(String.format("Could not find entity with path [%s].", folder.getPath())); } NamespaceKey key = new NamespaceKey(folder.getPath()); switch (container.getType()) { case SPACE: case HOME: case FOLDER: { namespaceService.addOrUpdateFolder(key, getFolderConfig(folder), attributes); break; } default: { throw new UnsupportedOperationException(String.format("Can not create a folder inside a [%s].", container.getType())); } } return getFolderFromConfig(namespaceService.getFolder(key), null); } protected void updateFolder(Folder folder, NamespaceAttribute... attributes) throws NamespaceException { NamespaceKey namespaceKey = new NamespaceKey(folder.getPath()); FolderConfig folderConfig = namespaceService.getFolder(namespaceKey); Preconditions.checkArgument(CollectionUtils.isEqualCollection(folder.getPath(), folderConfig.getFullPathList()), "Folder path is immutable."); NameSpaceContainer rootContainer = getRootContainer(folder.getPath()); if (rootContainer.getType() == NameSpaceContainer.Type.SOURCE) { throw new UnsupportedOperationException("Can not update a folder inside a source"); } namespaceService.addOrUpdateFolder(namespaceKey, getFolderConfig(folder), attributes); } public Source fromSourceConfig(SourceConfig config, List<CatalogItem> children) { // TODO: clean up source config creation, move it all into this class return sourceService.fromSourceConfig(config, children); } /** * Refresh a catalog item. Only supports datasets currently. */ public void refreshCatalogItem(String id) throws UnsupportedOperationException { Optional<?> entity = getById(id); if (!entity.isPresent()) { throw new IllegalArgumentException(String.format("Could not find entity with id [%s].", id)); } Object object = entity.get(); if (object instanceof DatasetConfig) { reflectionServiceHelper.refreshReflectionsForDataset(id); } else { throw new UnsupportedOperationException(String.format("Can only refresh datasets but found [%s].", object.getClass().getName())); } } private Optional<AccelerationSettings> getStoredReflectionSettingsForDataset(DatasetConfig datasetConfig) { return reflectionServiceHelper.getReflectionSettings().getStoredReflectionSettings(new NamespaceKey(datasetConfig.getFullPathList())); } public Dataset getDatasetFromConfig(DatasetConfig config, Dataset.RefreshSettings refreshSettings) { if (config.getType() == VIRTUAL_DATASET) { String sql = null; List<String> sqlContext = null; VirtualDataset virtualDataset = config.getVirtualDataset(); if (virtualDataset != null) { sql = virtualDataset.getSql(); sqlContext = virtualDataset.getContextList(); } return new Dataset( config.getId().getId(), Dataset.DatasetType.VIRTUAL_DATASET, config.getFullPathList(), DatasetsUtil.getArrowFieldsFromDatasetConfig(config), config.getCreatedAt(), String.valueOf(config.getVersion()), refreshSettings, sql, sqlContext, null, null ); } else { FileFormat format = null; PhysicalDataset physicalDataset = config.getPhysicalDataset(); if (physicalDataset != null) { FileConfig formatSettings = physicalDataset.getFormatSettings(); if (formatSettings != null) { if (config.getType() == com.dremio.service.namespace.dataset.proto.DatasetType.PHYSICAL_DATASET_SOURCE_FILE || config.getType() == com.dremio.service.namespace.dataset.proto.DatasetType.PHYSICAL_DATASET_HOME_FILE) { format = FileFormat.getForFile(formatSettings); } else { format = FileFormat.getForFolder(formatSettings); } } } return new Dataset( config.getId().getId(), Dataset.DatasetType.PHYSICAL_DATASET, config.getFullPathList(), DatasetsUtil.getArrowFieldsFromDatasetConfig(config), config.getCreatedAt(), String.valueOf(config.getVersion()), refreshSettings, null, null, format, physicalDataset.getAllowApproxStats() ); } } private static Home getHomeFromConfig(HomeConfig config, List<CatalogItem> children) { return new Home( config.getId().getId(), HomeName.getUserHomePath(config.getOwner()).toString(), String.valueOf(config.getVersion()), children ); } protected Space getSpaceFromConfig(SpaceConfig config, List<CatalogItem> children) { return new Space( config.getId().getId(), config.getName(), String.valueOf(config.getVersion()), config.getCtime(), children ); } public static SpaceConfig getSpaceConfig(Space space) { SpaceConfig config = new SpaceConfig(); config.setName(space.getName()); config.setId(new EntityId(space.getId())); if (space.getTag() != null) { config.setVersion(Long.valueOf(space.getTag())); } config.setCtime(space.getCreatedAt()); return config; } protected Folder getFolderFromConfig(FolderConfig config, List<CatalogItem> children) { return new Folder(config.getId().getId(), config.getFullPathList(), String.valueOf(config.getVersion()), children); } public static FolderConfig getFolderConfig(Folder folder) { FolderConfig config = new FolderConfig(); config.setId(new EntityId(folder.getId())); config.setFullPathList(folder.getPath()); config.setName(Iterables.getLast(folder.getPath())); if (folder.getTag() != null) { config.setVersion(Long.valueOf(folder.getTag())); } return config; } protected NamespaceAttribute[] getNamespaceAttributes(CatalogEntity entity) { return DEFAULT_NS_ATTRIBUTES; } // Catalog items that are not in the namespace (files/folders in file based sources are given a fake id that // is dremio:/path/to/entity - the prefix helps us distinguish between fake and real ids. private static String INTERNAL_ID_PREFIX = "dremio:"; public static String generateInternalId(List<String> path) { return INTERNAL_ID_PREFIX + com.dremio.common.utils.PathUtils.toFSPathString(path); } private static boolean isInternalId(String id) { return id.startsWith(INTERNAL_ID_PREFIX); } public static List<String> getPathFromInternalId(String id) { return com.dremio.common.utils.PathUtils.toPathComponents(id.substring(INTERNAL_ID_PREFIX.length())); } private StoragePlugin getStoragePlugin(String sourceName) { final StoragePlugin plugin = catalog.getSource(sourceName); if (plugin == null) { throw new SourceNotFoundException(sourceName); } return plugin; } }
[ "laurent@dremio.com" ]
laurent@dremio.com
afb30cee31c8bf6a317d073456365c4071f8a43e
97e1647d7e9eb807e23ed15bff63f842c1e47608
/easymis-crm-leads/easymis-crm-leads-client/src/main/java/org/easymis/crm/leads/client/service/LeadsRestService.java
a682bf62b2ecb45e8965a23d6265e302ca3efdb6
[]
no_license
tanyujie/easymis-crm
8a5065af32039385df566b646ddf11a0a468fe8b
92e104abf86d21c7a7083d4336b7648c0bb76a41
refs/heads/master
2020-05-26T22:46:10.263385
2019-05-31T03:01:12
2019-05-31T03:01:12
188,403,139
0
1
null
null
null
null
UTF-8
Java
false
false
1,143
java
package org.easymis.crm.leads.client.service; import java.util.ArrayList; import org.easymis.crm.leads.object.LeadsQo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestParam; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; @Service public class LeadsRestService { @Autowired private LeadsClient leadsClient; @HystrixCommand(fallbackMethod = "findByIdFallback") public String findById(String id) { String temp = leadsClient.findById(id); System.out.println(id + ":" + temp); return leadsClient.findById(id); } @HystrixCommand(fallbackMethod = "findByPageFallback") public String findByPage(Integer page,Integer size) { System.out.println("size:"+size); return leadsClient.findByPage(page, size); } public void remove(String id) { } public ArrayList<LeadsQo> find() { return null; } private String findByIdFallback(String id) { return null; } private String findByPageFallback(Integer page,Integer size) { return null; } }
[ "13551259347@139.com" ]
13551259347@139.com
cac879316e50a5596decce0122a5e1710a2d2224
c8885c64e14ae34a3dc0b2f1f1c1a8933e50a7f9
/collections/src/main/java/net/kuujo/copycat/collections/AsyncSetConfig.java
6c087b2fb2c02bde80917e19bc7b20f34c0c79f7
[ "Apache-2.0" ]
permissive
akoshibe/copycat
4cce717a09daae21a67e30c48202754ca3f20458
e58fe12e37d1f7b97ea8b275d26222623ac7d4a6
refs/heads/master
2021-01-18T08:00:02.311937
2015-02-03T07:06:11
2015-02-03T07:06:11
30,261,734
0
0
null
2015-02-03T20:00:48
2015-02-03T20:00:48
null
UTF-8
Java
false
false
1,903
java
/* * Copyright 2014 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 net.kuujo.copycat.collections; import net.kuujo.copycat.cluster.ClusterConfig; import net.kuujo.copycat.cluster.internal.coordinator.CoordinatedResourceConfig; import net.kuujo.copycat.collections.internal.collection.DefaultAsyncSet; import net.kuujo.copycat.state.StateLogConfig; import java.util.Map; /** * Asynchronous set configuration. * * @author <a href="http://github.com/kuujo">Jordan Halterman</a> */ public class AsyncSetConfig extends AsyncCollectionConfig<AsyncSetConfig> { private static final String DEFAULT_CONFIGURATION = "set-defaults"; private static final String CONFIGURATION = "set"; public AsyncSetConfig() { super(CONFIGURATION, DEFAULT_CONFIGURATION); } public AsyncSetConfig(Map<String, Object> config) { super(config, CONFIGURATION, DEFAULT_CONFIGURATION); } public AsyncSetConfig(String resource) { super(resource, CONFIGURATION, DEFAULT_CONFIGURATION); } protected AsyncSetConfig(AsyncSetConfig config) { super(config); } @Override public AsyncSetConfig copy() { return new AsyncSetConfig(this); } @Override public CoordinatedResourceConfig resolve(ClusterConfig cluster) { return new StateLogConfig(toMap()) .resolve(cluster) .withResourceType(DefaultAsyncSet.class); } }
[ "jordan.halterman@gmail.com" ]
jordan.halterman@gmail.com
9b22e8575b1db72d345626c5aac80c57069f7f7c
b00dc3c0e56d832ca98cd70df090c0273b8adf69
/src/main/java/com/augus/form/PageForm.java
a11b66ffc58e74ca9573a0950f0590af5f54a119
[]
no_license
AugusChenEnc/InterfaceManager
68e165788bc834c2f8c462a327cf7ceecf704e78
e10dac13d851686da13bb9932699e8e69f1cdbf7
refs/heads/master
2020-03-22T15:29:11.745724
2018-08-21T14:43:06
2018-08-21T14:43:06
140,256,684
0
0
null
null
null
null
UTF-8
Java
false
false
578
java
package com.augus.form; import lombok.Data; /** * @author Augus * @date 2018/7/19 18:10 */ @Data public class PageForm { /** * page Content */ private Integer pageNum; private Integer pageSize; private String sort; public Integer getPageNum() { if (this.pageNum == null || this.pageNum < 1) { this.pageNum = 1; } return pageNum; } public Integer getPageSize() { if (this.pageSize == null || this.pageSize < 1) { this.pageSize = 10; } return pageSize; } }
[ "PC-1211-02@PC-1211-03.POC.ET" ]
PC-1211-02@PC-1211-03.POC.ET
c0d3c7226324a628ea84b1c2f8789106e828f05e
249f5f82cf3250909ed4ee47684777fc535672af
/GPSParser.java
1bf3b87f3080874d443ce3dc0f4811837cd810de
[]
no_license
mainoramg/tgc-gprs-server
fdc42bd36c355521d4723df51e7a54d40d0683ef
8f3abc8749c378a9ecea5071afb8386cbae98303
refs/heads/master
2020-04-10T07:08:21.600074
2019-02-04T00:15:24
2019-02-04T00:15:24
160,873,346
0
1
null
2019-02-03T23:42:55
2018-12-07T20:41:06
null
UTF-8
Java
false
false
2,624
java
import java.io.*; import java.net.*; import java.sql.Timestamp; import java.util.*; class GPSParser { public static void main( String args[] ) { while( true ) { try { String sql = "select * from gps_raw_data order by stamp limit 100"; ArrayList al = DB.getData( sql ); if( al.size()==0 ) { System.out.println( new Timestamp( System.currentTimeMillis() ) + ": NO DATA ..." ); try { Thread.sleep( 3*1000 ); } catch( Exception e2 ) {} continue; } for( int i=0; i<al.size(); i++ ) { HashMap hm = (HashMap) al.get(i); String id = (String) hm.get( "id" ); id = id==null?"":id.toString(); String data = (String) hm.get( "data" ); data = data==null?"":data.toString(); if( data != null && data.length() >= 2 && data.substring( 0, 1 ).equals("*") && data.substring( data.length()-1, data.length() ).equals( "#" ) ) { String[] dataArray = data.split("#"); for( int j = 0 ; j < dataArray.length ; j++ ) { GPSEvent event = new GPSEvent( dataArray[j]+"#" ); if( !event.getStatus().equals( "E" ) && !event.getStatus().equals( "" ) ) { System.out.println( new Timestamp( System.currentTimeMillis() ) + ": " + event.getQueryToSaveIntoDB( id ) ); DB.executeSQL( event.getQueryToSaveIntoDB( id ) ); } else { System.out.println( new Timestamp( System.currentTimeMillis() ) + ": " + event.getQueryToRemoveFromDB( id ) ); DB.executeSQL( event.getQueryToRemoveFromDB( id ) ); } } } else { GPSEvent event = new GPSEvent( data ); System.out.println( new Timestamp( System.currentTimeMillis() ) + ": " + event.getQueryToRemoveFromDB( id ) ); DB.executeSQL( event.getQueryToRemoveFromDB( id ) ); } } } catch( Exception e ) { e.printStackTrace(); try { Thread.sleep( 60*1000 ); } catch( Exception e2 ) {} } } } }
[ "mainor.miranda@bvmedia.cr" ]
mainor.miranda@bvmedia.cr
d5d4822ec82cab9e1d4268d85356382af501fc3f
5b15e8ec91ee9eb59871b733fe90310b962aba06
/app/src/main/java/fit5046/test/touchme/FQuiz.java
ecdfaf1c1e6d4d9dd2745355b51c334e8308b4b3
[]
no_license
Haisonvh/BarkMeow_app
dc9bfe90ce9bf8353d7015e9374fae1c73e6c58c
31bbf934ec0911a7e5ce800a6fab81e8fb093b9a
refs/heads/master
2022-02-18T00:01:39.146442
2019-09-04T06:28:36
2019-09-04T06:28:36
206,241,348
0
0
null
null
null
null
UTF-8
Java
false
false
13,864
java
package fit5046.test.touchme; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import pl.droidsonroids.gif.GifImageView; public class FQuiz extends Fragment { private View fQuiz; private ImageButton ibAnswer1; private ImageButton ibAnswer2; private ImageButton ibAnswer3; private ImageButton ibAnswer4; private ImageView ivAnswer1; private ImageView ivAnswer2; private ImageView ivAnswer3; private ImageView ivAnswer4; private ImageView ivQuestion; private ImageView ivTeller; private TextView tvQuestion; private Animation animMoveRight; private Animation animFadeIn; private Animation animSlideDown; private GlobalClass globalClass; private ArrayList<QuizData> OfflineQuiz = new ArrayList<QuizData>(); private int indexQuiz = 0; private boolean isCorrect = false; private int correct = 0; private ImageButton ib_option; private MyDialogBuilder alertDialogBuilder; private AlertDialog alertDialog; Timer timerCloseEmotion = new Timer("timer",false); TimerTask tickCloseEmotion = new TimerTask() { @Override public void run() { handlerCloseEmotion.sendEmptyMessage(0); } }; final Handler handlerCloseEmotion = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (alertDialog.isShowing()) alertDialog.dismiss(); return true; } }); @Override public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if(fQuiz == null) fQuiz = inflater.inflate(R.layout.fragment_quiz, container, false); globalClass = (GlobalClass)getContext().getApplicationContext(); ibAnswer1 = (ImageButton)fQuiz.findViewById(R.id.ib_answer1); ibAnswer2 = (ImageButton)fQuiz.findViewById(R.id.ib_answer2); ibAnswer3 = (ImageButton)fQuiz.findViewById(R.id.ib_answer3); ibAnswer4 = (ImageButton)fQuiz.findViewById(R.id.ib_answer4); ivAnswer1 = (ImageView)fQuiz.findViewById(R.id.iv_answer1); ivAnswer2 = (ImageView)fQuiz.findViewById(R.id.iv_answer2); ivAnswer3 = (ImageView)fQuiz.findViewById(R.id.iv_answer3); ivAnswer4 = (ImageView)fQuiz.findViewById(R.id.iv_answer4); ivQuestion = (ImageView)fQuiz.findViewById(R.id.iv_conversation_bubble); ivTeller = (ImageView)fQuiz.findViewById(R.id.iv_teller); tvQuestion = (TextView)fQuiz.findViewById(R.id.tv_quiz); final FragmentManager fragmentManager = getFragmentManager(); ib_option = (ImageButton)fQuiz.findViewById(R.id.ib_option); ib_option.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { globalClass.currentFragment = new FWelcome(); fragmentManager.beginTransaction().replace(R.id.fl_main, globalClass.currentFragment).commit(); } }); animMoveRight = AnimationUtils.loadAnimation(container.getContext(), R.anim.move_right); animFadeIn = AnimationUtils.loadAnimation(container.getContext(), R.anim.fade_in); animSlideDown = AnimationUtils.loadAnimation(container.getContext(), R.anim.slide_down); ibAnswer1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hideAllCheck(); ivAnswer1.setVisibility(View.VISIBLE); if (correct == 0 || correct ==-1) showResponse(true); else showResponse(false); } }); ibAnswer2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hideAllCheck(); ivAnswer2.setVisibility(View.VISIBLE); if (correct == 1 || correct ==-1) showResponse(true); else showResponse(false); } }); ibAnswer3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hideAllCheck(); ivAnswer3.setVisibility(View.VISIBLE); if (correct == 2 || correct ==-1) showResponse(true); else showResponse(false); } }); ibAnswer4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hideAllCheck(); ivAnswer4.setVisibility(View.VISIBLE); if (correct == 3 || correct ==-1) showResponse(true); else showResponse(false); } }); hideAllCheck(); hideAllOption(); ivTeller.startAnimation(animMoveRight); animMoveRight.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { ivQuestion.post(new Runnable() { @Override public void run() { ivQuestion.setVisibility(View.VISIBLE); tvQuestion.setVisibility(View.VISIBLE); ivQuestion.startAnimation(animSlideDown); QuizData temp = OfflineQuiz.get(0); startNewQuestion(temp.getQuestion(),temp.options); indexQuiz=1; correct = temp.correctIndex; } }); } @Override public void onAnimationRepeat(Animation animation) { } }); QuizData temp1 = new QuizData(); temp1.setQuestion("What breeds of dogs have you recently seen the most?"); ArrayList<Integer> dogBreads = new ArrayList(); dogBreads.add(R.drawable.staffy); dogBreads.add(R.drawable.malteseshihtzu); dogBreads.add(R.drawable.labrador); dogBreads.add(R.drawable.jackrussel); dogBreads.add(R.drawable.deerhound); dogBreads.add(R.drawable.bullmastiff); dogBreads.add(R.drawable.briard); dogBreads.add(R.drawable.bassetthound); Collections.shuffle(dogBreads); ArrayList<Integer> aa = new ArrayList<>(); for (int i = 0; i< 4;i++){ aa.add(dogBreads.get(i)); } temp1.setOptions(aa); //Random random = new Random(); temp1.setCorrectIndex(-1); OfflineQuiz.add(temp1); QuizData temp2 = new QuizData(); temp2.setQuestion("which dog do you least see most?"); Collections.shuffle(dogBreads); ArrayList<Integer> bb = new ArrayList<>(); for (int i = 0; i< 4;i++){ bb.add(dogBreads.get(i)); } temp2.setOptions(bb); temp2.setCorrectIndex(-1); OfflineQuiz.add(temp2); QuizData temp3 = new QuizData(); temp3.setQuestion("Which dog look HAPPY?"); ArrayList<Integer> cc = new ArrayList<>(); cc.add(R.drawable.angry_th); cc.add(R.drawable.cute_th); cc.add(R.drawable.happy_th); cc.add(R.drawable.mad_th); temp3.setOptions(cc); temp3.setCorrectIndex(2); OfflineQuiz.add(temp3); QuizData temp4 = new QuizData(); temp4.setQuestion("Which dog looks MAD?"); ArrayList<Integer> dd = new ArrayList<>(); dd.add(R.drawable.mad_fo); dd.add(R.drawable.cute_fo); dd.add(R.drawable.happy_fo); dd.add(R.drawable.stare_fo); temp4.setCorrectIndex(0); temp4.setOptions(dd); OfflineQuiz.add(temp4); QuizData temp5 = new QuizData(); temp5.setQuestion("What food CAN you feed to dogs"); ArrayList<Integer> ee = new ArrayList<>(); ee.add(R.drawable.alcohol_fi); ee.add(R.drawable.chocolate_fi); ee.add(R.drawable.onions_fi); ee.add(R.drawable.corn_fi); temp5.setCorrectIndex(3); temp5.setOptions(ee); OfflineQuiz.add(temp5); /* ArrayList<String> food = new ArrayList<>(); food.add("CHOCOLATE"); food.add("CANDY"); food.add("AVOCADO"); food.add("CARROT"); food.add("WHITE RICE"); food.add("MILK"); Collections.shuffle(food); QuizData temp6 = new QuizData(); temp6.setQuestion("Can we feed dog with "+food.get(0)); ArrayList<Integer> ff = new ArrayList<>(); ff.add(R.drawable.no); ff.add(R.drawable.yes); temp6.setOptions(ff); if (food.get(0).equals("CARROT") || food.get(0).equals("WHITE RICE")||food.get(0).equals("MILK")) temp6.setCorrectIndex(2); else temp6.setCorrectIndex(1); OfflineQuiz.add(temp6);*/ Collections.shuffle(OfflineQuiz); alertDialogBuilder = new MyDialogBuilder(getContext(),container,MyDialogBuilder.TYPE_YES); alertDialog = alertDialogBuilder.create(); alertDialogBuilder.setYesOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if(isCorrect){ if (indexQuiz<4){ QuizData temp = OfflineQuiz.get(indexQuiz); startNewQuestion(temp.getQuestion(),temp.options); indexQuiz+=1; correct = temp.correctIndex; } else { globalClass.currentFragment = new FGame(); fragmentManager.beginTransaction().replace(R.id.fl_main, globalClass.currentFragment).commit(); } } } }); alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); return fQuiz; } private void startNewQuestion(String question, ArrayList<Integer> imageUrl){ isCorrect = false; tvQuestion.setText(question); tvQuestion.startAnimation(animFadeIn); hideAllCheck(); hideAllOption(); if(imageUrl.size() == 4){ ibAnswer1.setVisibility(View.VISIBLE); ibAnswer2.setVisibility(View.VISIBLE); ibAnswer3.setVisibility(View.VISIBLE); ibAnswer4.setVisibility(View.VISIBLE); ibAnswer1.setImageResource(imageUrl.get(0)); ibAnswer2.setImageResource(imageUrl.get(1)); ibAnswer3.setImageResource(imageUrl.get(2)); ibAnswer4.setImageResource(imageUrl.get(3)); ibAnswer1.startAnimation(animSlideDown); ibAnswer2.startAnimation(animSlideDown); ibAnswer3.startAnimation(animSlideDown); ibAnswer4.startAnimation(animSlideDown); } else if(imageUrl.size() == 2){ ibAnswer2.setVisibility(View.VISIBLE); ibAnswer3.setVisibility(View.VISIBLE); ibAnswer2.setImageResource(imageUrl.get(0)); ibAnswer3.setImageResource(imageUrl.get(1)); ibAnswer2.startAnimation(animSlideDown); ibAnswer3.startAnimation(animSlideDown); } } private void hideAllCheck(){ ivAnswer1.setVisibility(View.GONE); ivAnswer2.setVisibility(View.GONE); ivAnswer3.setVisibility(View.GONE); ivAnswer4.setVisibility(View.GONE); } private void hideAllOption(){ ibAnswer1.setVisibility(View.INVISIBLE); ibAnswer2.setVisibility(View.INVISIBLE); ibAnswer3.setVisibility(View.INVISIBLE); ibAnswer4.setVisibility(View.INVISIBLE); ibAnswer1.clearAnimation(); ibAnswer2.clearAnimation(); ibAnswer3.clearAnimation(); ibAnswer4.clearAnimation(); } private void showResponse(boolean isCorrect){ timerCloseEmotion.cancel(); tickCloseEmotion.cancel(); timerCloseEmotion = new Timer("timer",false); tickCloseEmotion = new TimerTask() { @Override public void run() { handlerCloseEmotion.sendEmptyMessage(0); } }; if (isCorrect){ this.isCorrect = true; alertDialogBuilder.setImageTeller(R.drawable.answer_correct); alertDialogBuilder.setMessage(getString(R.string.answer_correct)); } else{ this.isCorrect = false; alertDialogBuilder.setImageTeller(R.drawable.answer_wrong); alertDialogBuilder.setMessage(getString(R.string.answer_wrong)); } timerCloseEmotion.schedule(tickCloseEmotion,4000); alertDialog.show(); } }
[ "hvuu0005@student.monash.edu" ]
hvuu0005@student.monash.edu
cdd41fba9d31668edf047828c16373229f388d01
95a952eced9b98dba4119f2e52528fc9ae9cf14d
/app/src/main/java/br/com/udacity/popularmovies/util/ItemClickListener.java
e07f607685dac95db2d57d61f27e36a71ea1ab70
[]
no_license
SilvanoP/PopularMovies
8f2122506e5be606f1019adbe99305478fbdcad3
bba1949a44df01277f77ab58a98e1fcaeedb7039
refs/heads/master
2020-12-30T11:03:02.483017
2019-08-16T02:44:20
2019-08-16T02:44:20
98,841,107
0
0
null
null
null
null
UTF-8
Java
false
false
180
java
package br.com.udacity.popularmovies.util; /** * Interface used for onItemClick on adapter */ public interface ItemClickListener { void onItemClick(int clickedItemIndex); }
[ "silvano.pereira@gmail.com" ]
silvano.pereira@gmail.com
4d2ddbabb47aa8099e75feb8fe873414fd5d98a4
c3149d2cb04a48101de4f853ef2cbd856e93b643
/SegaBank/SegaBank/src/bo/CompteEpargne.java
a515a6d310e77e61e78511b7233774ab90b9a8bd
[]
no_license
WilMont/Projet_SegaBank
29fcb8c029e7e11fe16a1f8e8d733944f3386d3c
f4bd4dc7957064e6ffa9fcd00819792e80a3e0c6
refs/heads/master
2020-08-08T05:10:34.242883
2019-10-13T20:40:57
2019-10-13T20:40:57
213,658,660
0
0
null
null
null
null
UTF-8
Java
false
false
588
java
package bo; public class CompteEpargne extends Compte { private double tauxInteret; public CompteEpargne(int id, double solde, int agenceID, double tauxInteret) { super(id, solde, agenceID); this.tauxInteret = tauxInteret; } public void calculInteret(){ double interets = this.getSolde()/tauxInteret; this.setSolde(this.getSolde() + interets); System.out.println("La somme de " + interets + "โ‚ฌ a รฉtรฉ ajoutรฉe ce compte."); System.out.println("Solde actuel: " + this.getSolde() + "โ‚ฌ."); } }
[ "noreply@github.com" ]
WilMont.noreply@github.com
1328966744388c98097e97e5691ed3fac226f092
5439d4509666c16f6e10c5e45c9478c359237562
/Raspberry_pi/RaspberryPi/src/main/java/com/raspberrypi/raspberrypi/OBD/commands/control/DistanceSinceCCCommand.java
6e5759b00374bf4b585ec7a5d9daedf05560e911
[]
no_license
kevind992/Driver-Monitoring-System
d568430eb8c5b4dc4c52c776abb7a84c6573e13f
b4361d0aa10875572ba6bd528f2f7f2dd4de5c99
refs/heads/master
2021-09-13T09:33:28.571589
2018-04-27T21:24:10
2018-04-27T21:24:10
119,375,087
7
1
null
null
null
null
UTF-8
Java
false
false
2,609
java
/** * 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.raspberrypi.raspberrypi.OBD.commands.control; import com.raspberrypi.raspberrypi.OBD.commands.ObdCommand; import com.raspberrypi.raspberrypi.OBD.commands.SystemOfUnits; import com.raspberrypi.raspberrypi.OBD.enums.AvailableCommandNames; /** * Distance traveled since codes cleared-up. * */ public class DistanceSinceCCCommand extends ObdCommand implements SystemOfUnits { private int km = 0; /** * Default ctor. */ public DistanceSinceCCCommand() { super("01 31"); } public DistanceSinceCCCommand( DistanceSinceCCCommand other) { super(other); } /** {@inheritDoc} */ @Override protected void performCalculations() { // ignore first two bytes [01 31] of the response km = buffer.get(2) * 256 + buffer.get(3); } /** * <p>getFormattedResult.</p> * * @return a {@link String} object. */ public String getFormattedResult() { return useImperialUnits ? String.format("%.2f%s", getImperialUnit(), getResultUnit()) : String.format("%d%s", km, getResultUnit()); } /** {@inheritDoc} */ @Override public String getCalculatedResult() { return useImperialUnits ? String.valueOf(getImperialUnit()) : String.valueOf(km); } /** {@inheritDoc} */ @Override public String getResultUnit() { return useImperialUnits ? "m" : "km"; } /** {@inheritDoc} */ @Override public float getImperialUnit() { return km * 0.621371192F; } /** * <p>Getter for the field <code>km</code>.</p> * * @return a int. */ public int getKm() { return km; } /** * <p>Setter for the field <code>km</code>.</p> * * @param km a int. */ public void setKm(int km) { this.km = km; } /** {@inheritDoc} */ @Override public String getName() { return AvailableCommandNames.DISTANCE_TRAVELED_AFTER_CODES_CLEARED .getValue(); } }
[ "g00270791@gmit.ie" ]
g00270791@gmit.ie
332e588bde3b93d176a0496857298636ebf5a268
3ee4da89cd649b7e087a138ba84354890be67652
/src/main/java/com/cisc181/core/Student.java
14844db5541f6a13f9fe9888b874849818ca1a2f
[]
no_license
msayanlar/Midterm-Coding-Problem
8de313bb900aeaa2b2a8d229844598dc7aea5c34
06582c234ddba7f92131c04ad06fbb7c18287192
refs/heads/master
2021-01-11T03:10:27.596611
2016-10-17T04:46:35
2016-10-17T04:46:35
71,084,040
0
0
null
null
null
null
UTF-8
Java
false
false
966
java
package com.cisc181.core; import java.util.Date; import java.util.UUID; import com.cisc181.eNums.eMajor; public class Student extends Person { private eMajor eMajor; private UUID StudentID; public eMajor geteMajor ( ) { return this.eMajor; } public void seteMajor (eMajor eMajor) { this.eMajor = eMajor; } public UUID getStudentID(){ return this.StudentID; } public Student(String FirstName, String MiddleName, String LastName,Date DOB, eMajor Major, String Address, String Phone_number, String Email) { super(FirstName, MiddleName, LastName, DOB, Address, Phone_number, Email); this.StudentID = UUID.randomUUID(); this.eMajor = eMajor; } @Override public void PrintName() { System.out.println(getLastName() + "," + getFirstName() + ' ' + getMiddleName()); } public void PrintName(boolean bnormal) { super.PrintName(); } }
[ "sayanlar@udel.edu" ]
sayanlar@udel.edu
8e6c61002541ff748a743aa250fe4824ee1ead64
6f94218c3632634bfe24e87b9fbe9acc668396fa
/vteba/src/main/java/com/vteba/product/men/dao/spi/MenDao.java
22bba22294eb99652b556506f0d6611684141675
[]
no_license
skmbw/vteba
99155e2a770eca33cbf680319536e555ca16faae
b27b03d64fe0cca535d24045a6ddd4ca82b5a00c
refs/heads/master
2016-09-06T17:41:30.573209
2014-11-02T05:34:59
2014-11-02T05:34:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
287
java
package com.vteba.product.men.dao.spi; import com.vteba.tx.hibernate.BaseGenericDao; import com.vteba.product.men.model.Men; /** * ็”ท่ฃ…็ฑปๅ•†ๅ“DaoๆŽฅๅฃใ€‚ * @author yinlei * date 2013-10-5 17:00:08 */ public interface MenDao extends BaseGenericDao<Men, Long> { }
[ "tongku2008@126.com" ]
tongku2008@126.com
ea6cd5e48d4d158414a5b43622c668a4bfeb6d4d
acc488a4b3fcad75bd97c4ee38a910749f1534e0
/src/main/java/com/yida/boottracer/domain/EntDictDealer.java
4186d6d3e6437467cc30bb5da0f6e5f2ebd27c6d
[]
no_license
fxwdl/boottracer
c4d28d62d394ad0fc1b8c876fd37f8842f59900f
7f373a1fc177b86e1841060b0266874c1afcdeae
refs/heads/master
2022-06-25T22:32:25.731868
2019-09-20T09:35:34
2019-09-20T09:46:17
158,079,992
1
0
null
2022-06-21T00:52:53
2018-11-18T12:10:32
TSQL
UTF-8
Java
false
false
4,187
java
package com.yida.boottracer.domain; // Generated 2019-1-5 11:24:46 by Hibernate Tools 5.2.10.Final import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedAttributeNode; import javax.persistence.NamedEntityGraph; import javax.persistence.NamedEntityGraphs; import javax.persistence.Table; import javax.persistence.Version; import com.fasterxml.jackson.annotation.JsonBackReference; /** * EntDictSupplier generated by hbm2java */ @Entity @Table(name = "ent_dict_dealer") @NamedEntityGraphs(value = { @NamedEntityGraph(name = "SysMember.dictRegion", attributeNodes = { @NamedAttributeNode("dictRegion") }) }) public class EntDictDealer extends AuditModel implements java.io.Serializable { private int id; private Long version; private SysMember sysMember; private String name; private String code; private String linkman; private String tel; private String mobile; private String email; private String address; private String fax; private String comment; private boolean isDeleted; private DictRegion dictRegion; public EntDictDealer() { } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID", unique = true, nullable = false) public int getId() { return this.id; } public void setId(int id) { this.id = id; } @Version @Column(name = "Version", nullable = false) public Long getVersion() { return this.version; } public void setVersion(Long version) { this.version = version; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "SysMemberID") @JsonBackReference(value="EntDictDealer-SysMember") public SysMember getSysMember() { return this.sysMember; } public void setSysMember(SysMember sysMember) { this.sysMember = sysMember; } @Column(name = "Name", nullable = false, length = 256) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "Code", length = 45) public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } @Column(name = "Linkman", length = 45) public String getLinkman() { return this.linkman; } public void setLinkman(String linkman) { this.linkman = linkman; } @Column(name = "Tel", length = 45) public String getTel() { return this.tel; } public void setTel(String tel) { this.tel = tel; } @Column(name = "Mobile", length = 45) public String getMobile() { return this.mobile; } public void setMobile(String mobile) { this.mobile = mobile; } @Column(name = "Email", length = 45) public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } @Column(name = "Address", length = 45) public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } @Column(name = "Fax", length = 45) public String getFax() { return this.fax; } public void setFax(String fax) { this.fax = fax; } @Column(name = "Comment", length = 45) public String getComment() { return this.comment; } public void setComment(String comment) { this.comment = comment; } @Column(name = "IsDeleted", nullable = false) public boolean isIsDeleted() { return this.isDeleted; } public void setIsDeleted(boolean isDeleted) { this.isDeleted = isDeleted; } @ManyToOne(fetch = FetchType.LAZY,cascade= {CascadeType.REFRESH}) @JoinColumn(name = "Region_ID", nullable = true) public DictRegion getDictRegion() { return this.dictRegion; } public void setDictRegion(DictRegion dictRegion) { this.dictRegion = dictRegion; } }
[ "fx__wdl@hotmail.com" ]
fx__wdl@hotmail.com
4c7ae76f0b19151143044f94171f2afbcd09f346
46c67394d505f41281ca8f6157cebf1a690a6d71
/NetBeansProjects/spring-rest/src/main/java/com/digitallschool/training/spiders/springrest/SpringRestApplication.java
28300f5fa14289cb0b051fe592c0d835730d2c1c
[]
no_license
stphnvijay/vijay
5fc0683689e68d01e138ed9f238106366a04db07
354e47a1b3a09be3afa313354d49ac32bbe7b7d1
refs/heads/master
2023-01-09T02:33:47.867298
2020-03-18T17:38:36
2020-03-18T17:38:36
237,964,803
0
0
null
2023-01-06T01:54:32
2020-02-03T12:54:57
Java
UTF-8
Java
false
false
347
java
package com.digitallschool.training.spiders.springrest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringRestApplication { public static void main(String[] args) { SpringApplication.run(SpringRestApplication.class, args); } }
[ "stphnvijay@gmail.com" ]
stphnvijay@gmail.com
0b4f35953e0de5708924babd1055fc4863d56ede
f907a37da773b94749652937aace95bb58f732b5
/src/main/java/com/isabellabarbosa/cursomc/repositories/EstadoRepository.java
660ace72bcfb62dbcf1a271f340c6002b0eb562b
[]
no_license
bellargb/spring-boot-ionic-backend
3447584d71d3e5fde703f797ac34ba7e83ba5d45
fe1bcf583c3699886bd0526ead2747997f6c5422
refs/heads/master
2023-03-05T16:42:25.488505
2021-02-19T11:49:31
2021-02-19T11:49:31
340,024,708
0
0
null
null
null
null
UTF-8
Java
false
false
304
java
package com.isabellabarbosa.cursomc.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.isabellabarbosa.cursomc.domain.Estado; @Repository public interface EstadoRepository extends JpaRepository<Estado, Integer>{ }
[ "bellargbarbosa@hotmail.com" ]
bellargbarbosa@hotmail.com
5f9c4331e68abb47695b5daa1124530073052067
b10cb87512f93264f9fd7ab4f0b2db55673d6e83
/src/main/java/cn/javabus/generator/plugins/MySQLForUpdatePlugin.java
9902882c5b9033034bf624084dd031861170af15
[]
no_license
javastar920905/code-generator
83cfc06e8e6b7d29780a5f5b78cc947c4e2ea100
518c35e333672426a929df2bdfb2affcc6308746
refs/heads/master
2023-01-10T23:04:04.113567
2020-04-13T02:50:53
2020-04-13T02:50:53
250,738,049
0
1
null
2023-01-05T17:33:31
2020-03-28T07:29:06
Java
UTF-8
Java
false
false
2,574
java
package cn.javabus.generator.plugins; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.PluginAdapter; import org.mybatis.generator.api.dom.java.*; import org.mybatis.generator.api.dom.xml.Attribute; import org.mybatis.generator.api.dom.xml.TextElement; import org.mybatis.generator.api.dom.xml.XmlElement; import java.util.List; /** * Project: mybatis-generator-gui * * @author slankka on 2017/11/4. */ public class MySQLForUpdatePlugin extends PluginAdapter { @Override public boolean validate(List<String> warnings) { return true; } @Override public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { PrimitiveTypeWrapper booleanWrapper = FullyQualifiedJavaType.getBooleanPrimitiveInstance().getPrimitiveTypeWrapper(); Field forUpdate = new Field(); forUpdate.setName("forUpdate"); forUpdate.setVisibility(JavaVisibility.PRIVATE); forUpdate.setType(booleanWrapper); topLevelClass.addField(forUpdate); Method setForUpdate = new Method(); setForUpdate.setVisibility(JavaVisibility.PUBLIC); setForUpdate.setName("setForUpdate"); setForUpdate.addParameter(new Parameter(booleanWrapper, "forUpdate")); setForUpdate.addBodyLine("this.forUpdate = forUpdate;"); topLevelClass.addMethod(setForUpdate); Method getForUpdate = new Method(); getForUpdate.setVisibility(JavaVisibility.PUBLIC); getForUpdate.setReturnType(booleanWrapper); getForUpdate.setName("getForUpdate"); getForUpdate.addBodyLine("return forUpdate;"); topLevelClass.addMethod(getForUpdate); return true; } private void appendForUpdate(XmlElement element, IntrospectedTable introspectedTable) { XmlElement forUpdateElement = new XmlElement("if"); forUpdateElement.addAttribute(new Attribute("test", "forUpdate != null and forUpdate == true")); forUpdateElement.addElement(new TextElement("for update")); element.addElement(forUpdateElement); } @Override public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { appendForUpdate(element, introspectedTable); return true; } @Override public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) { appendForUpdate(element, introspectedTable); return true; } }
[ "axing0905@gmail.com" ]
axing0905@gmail.com
d75fab2a3669c2c02b043391d9d58f9b9d2d22dd
b0e99b4d08f83bd7c2bcb310d75d0beb07d65eb5
/Application/src/Settings.java
69f3d4f6bb07601de0cb0e42d99821e59f0a5ddd
[]
no_license
zack0518/2017-S2-SEP-UG12
7878e2c2e341226ccd8447e6eaa8141c8703b7a5
06e710aa5b469262104ac0a3cabb8f68ee8a3d18
refs/heads/master
2020-04-08T11:47:51.959952
2018-11-27T10:51:45
2018-11-27T10:51:45
159,320,440
0
0
null
null
null
null
UTF-8
Java
false
false
2,419
java
/** * Contains application-wide constant values. * @author jkortman */ public class Settings { /** * Constructor is not allowed, Settings is not a class that can be instantiated. */ private Settings() {} // The allowed MSE error for colors. public static final float allowedColorMSE = 1.0f; // TODO: NEEDS TO BE TESTED AND REVISED public static final float allowedGrayscaleError = 0.09f; // TODO: NEEDS TO BE TESTED AND REVISED // The reference colors for color detection. public static class ReferenceColors { public static final RGBColor black = new RGBColor(0.013722f, 0.015861f, 0.013028f); public static final RGBColor white = new RGBColor(0.146857f, 0.171757f, 0.135786f); public static final RGBColor purple = new RGBColor(0.095f, 0.095f, 0.115f); // TODO public static final RGBColor green = new RGBColor(0.016f, 0.060f, 0.021f); // TODO public static final RGBColor blue = new RGBColor(0.037f, 0.141f, 0.145f); // TODO } /** * Map properties. */ public static class Map { public static final int rows = 120; public static final int cols = 120; public static final float gridSize = 0.02f; // metres } /** * Debugging output settings. */ public static class Debug { // Prints from Robot.java public static final boolean showUpdatePositionOutput = false; public static final boolean showRobotMessages = false; public static final boolean showRobotCommands = true; public static final boolean showRobotJobStatus = true; public static final boolean showRobotSetup = true; // Prints from Handler public static final boolean showCommandParameters = false; public static final boolean showManualCommands = true; public static final boolean showColorSensor = false; public static final boolean showLocation = false; public static final boolean usePresetMap = false; // Prints from other sources public static final boolean showMap = true; public static final boolean showDetectedColorPropery = false; public static final boolean showColorSensorInterpretation = false; } }
[ "774726628@qq.com" ]
774726628@qq.com
ac12b6ac9aa10a0f1748b6cab3293964b6df4651
354ef76b95099859fa234d8e6c648e4b6bcd23e9
/src/main/java/gregtech/common/GT_Worldgen_Stone.java
ecd3df92adec51aff0d00d67931b340b54fb3d21
[]
no_license
draknyte1/GT5-Unofficial-Ex
0ee613fc18e6df8709a3538877f879951dcaca5c
6c27f2b264531c262d31e939b28e72792f943d2a
refs/heads/master
2021-01-18T00:19:09.467262
2016-07-11T06:35:30
2016-07-11T06:35:30
53,850,588
1
1
null
null
null
null
UTF-8
Java
false
false
5,606
java
package gregtech.common; import gregtech.api.GregTech_API; import gregtech.api.world.GT_Worldgen_Ore; import gregtech.common.blocks.GT_TileEntity_Ores; import java.util.Collection; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; public class GT_Worldgen_Stone extends GT_Worldgen_Ore { public GT_Worldgen_Stone(String aName, boolean aDefault, Block aBlock, int aBlockMeta, int aDimensionType, int aAmount, int aSize, int aProbability, int aMinY, int aMaxY, Collection<String> aBiomeList, boolean aAllowToGenerateinVoid) { super(aName, aDefault, aBlock, aBlockMeta, aDimensionType, aAmount, aSize, aProbability, aMinY, aMaxY, aBiomeList, aAllowToGenerateinVoid); } public boolean executeWorldgen(World aWorld, Random aRandom, String aBiome, int aDimensionType, int aChunkX, int aChunkZ, IChunkProvider aChunkGenerator, IChunkProvider aChunkProvider) { if ((isGenerationAllowed(aWorld, aDimensionType, this.mDimensionType)) && ((this.mBiomeList.isEmpty()) || (this.mBiomeList.contains(aBiome))) && ((this.mProbability <= 1) || (aRandom.nextInt(this.mProbability) == 0))) { for (int i = 0; i < this.mAmount; i++) { int tX = aChunkX + aRandom.nextInt(16); int tY = this.mMinY + aRandom.nextInt(this.mMaxY - this.mMinY); int tZ = aChunkZ + aRandom.nextInt(16); if ((this.mAllowToGenerateinVoid) || (!aWorld.getBlock(tX, tY, tZ).isAir(aWorld, tX, tY, tZ))) { float var6 = aRandom.nextFloat() * 3.141593F; double var7 = tX + 8 + MathHelper.sin(var6) * this.mSize / 8.0F; double var9 = tX + 8 - MathHelper.sin(var6) * this.mSize / 8.0F; double var11 = tZ + 8 + MathHelper.cos(var6) * this.mSize / 8.0F; double var13 = tZ + 8 - MathHelper.cos(var6) * this.mSize / 8.0F; double var15 = tY + aRandom.nextInt(3) - 2; double var17 = tY + aRandom.nextInt(3) - 2; for (int var19 = 0; var19 <= this.mSize; var19++) { double var20 = var7 + (var9 - var7) * var19 / this.mSize; double var22 = var15 + (var17 - var15) * var19 / this.mSize; double var24 = var11 + (var13 - var11) * var19 / this.mSize; double var26 = aRandom.nextDouble() * this.mSize / 16.0D; double var28 = (MathHelper.sin(var19 * 3.141593F / this.mSize) + 1.0F) * var26 + 1.0D; double var30 = (MathHelper.sin(var19 * 3.141593F / this.mSize) + 1.0F) * var26 + 1.0D; int tMinX = MathHelper.floor_double(var20 - var28 / 2.0D); int tMinY = MathHelper.floor_double(var22 - var30 / 2.0D); int tMinZ = MathHelper.floor_double(var24 - var28 / 2.0D); int tMaxX = MathHelper.floor_double(var20 + var28 / 2.0D); int tMaxY = MathHelper.floor_double(var22 + var30 / 2.0D); int tMaxZ = MathHelper.floor_double(var24 + var28 / 2.0D); for (int eX = tMinX; eX <= tMaxX; eX++) { double var39 = (eX + 0.5D - var20) / (var28 / 2.0D); if (var39 * var39 < 1.0D) { for (int eY = tMinY; eY <= tMaxY; eY++) { double var42 = (eY + 0.5D - var22) / (var30 / 2.0D); if (var39 * var39 + var42 * var42 < 1.0D) { for (int eZ = tMinZ; eZ <= tMaxZ; eZ++) { double var45 = (eZ + 0.5D - var24) / (var28 / 2.0D); if (var39 * var39 + var42 * var42 + var45 * var45 < 1.0D) { Block tTargetedBlock = aWorld.getBlock(eX, eY, eZ); if (tTargetedBlock == GregTech_API.sBlockOres1) { TileEntity tTileEntity = aWorld.getTileEntity(eX, eY, eZ); if ((tTileEntity instanceof GT_TileEntity_Ores)) { ((GT_TileEntity_Ores) tTileEntity).overrideOreBlockMaterial(this.mBlock, (byte) this.mBlockMeta); } } else if (((this.mAllowToGenerateinVoid) && (aWorld.getBlock(eX, eY, eZ).isAir(aWorld, eX, eY, eZ))) || ((tTargetedBlock != null) && ((tTargetedBlock.isReplaceableOreGen(aWorld, eX, eY, eZ, Blocks.stone)) || (tTargetedBlock.isReplaceableOreGen(aWorld, eX, eY, eZ, Blocks.end_stone)) || (tTargetedBlock.isReplaceableOreGen(aWorld, eX, eY, eZ, Blocks.netherrack))))) { aWorld.setBlock(eX, eY, eZ, this.mBlock, this.mBlockMeta, 0); } } } } } } } } } } return true; } return false; } }
[ "Draknyte1@hotmail.com" ]
Draknyte1@hotmail.com
c6c1f973f5046db648ced11a779391e27e36c5eb
8533485cf660105e2ac86a32618a95569be1eaf7
/com/sbrf/bc/processor/selfservdevice/fix/BillingDownloadProcessor.java
af81ce49af3643e051288ba92ac51a73696cccb7
[]
no_license
zhivenkov-an/paymentServer
0ba7f8a2e026931d3f8a84bf215b2d4d9996aea6
4170e1fbb2aff1af11585638d3ce5c7501007845
refs/heads/main
2023-01-18T22:24:20.875464
2020-12-06T21:06:46
2020-12-06T21:06:46
319,129,536
0
0
null
null
null
null
UTF-8
Java
false
false
7,187
java
package com.sbrf.bc.processor.selfservdevice.fix; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import com.epam.sbrf.bc.jdbc.SpecialConnectionSource; import com.sberbank.sbclients.admin.businessdelegate.AdminBusinessDelegate; import com.sberbank.sbclients.util.dao.ConnectionSource; import com.sberbank.sbclients.util.dao.J2EEContainerConnectionSource; import com.sberbank.sbclients.util.dao.db2.DAOUtil; import com.sbrf.bc.command.Command; import com.sbrf.bc.command.CommandException; import com.sbrf.bc.command.CommandServerDelegate; import com.sbrf.bc.plugin.PluginNotFoundException; import com.sbrf.bc.processor.FileMetadata; import com.sbrf.bc.processor.OutgoingRegistryProcessor; import com.sbrf.bc.processor.ProcessorException; import com.sbrf.bc.processor.RegistryContext; import com.sbrf.bc.processor.operday.OperDayFactory; import com.sbrf.util.classloader.ResourceHelper; import com.sbrf.util.io.CrlfPrintWriter; import com.sbrf.util.logging.SBRFLogger; import com.sbrf.util.sql.group.GroupSelector; import com.sbrf.util.sql.group.NameFieldDescription; import com.sbrf.util.sql.group.SelectorException; import com.sbrf.util.text.LightDateFormat; import com.sbrf.util.text.MessageFormat; import com.sbrf.util.text.NamedMessageFormat; public class BillingDownloadProcessor implements OutgoingRegistryProcessor { private final BillingDownloadProcessorConfig config; private final Date downloadDate; private final Logger logger; private String login; private final ConnectionSource insertConnectionSource; private final ConnectionSource dataConnectionSource; public BillingDownloadProcessor(BillingDownloadProcessorConfig config, Date date) { this.config = config; this.downloadDate = date; this.logger = SBRFLogger.getInstance(this.getClass().getSimpleName()); this.insertConnectionSource = new SpecialConnectionSource(); this.dataConnectionSource = new J2EEContainerConnectionSource(config.billingDatasourceJDBCName); try { CommandServerDelegate serv = new CommandServerDelegate(CommandServerDelegate.DEFAULT_JNDI_NAME); login = (String) serv.executeCommand(new Command() { public Object execute() throws CommandException { return AdminBusinessDelegate.get(AdminBusinessDelegate.DEFAULT_JNDI_NAME).getUserAttributes().getLogin(); } }); } catch (Throwable e) { logger.log(Level.WARNING, "ะžัˆะธะฑะบะฐ ะฟั€ะธ ะฟะพะฟั‹ั‚ะบะต ะฟะพะปัƒั‡ะธั‚ัŒ ะปะพะณะธะฝ ะทะฐะณั€ัƒะถะฐัŽั‰ะตะณะพ ะฟะปะฐั‚ะตะถ: " + e.getMessage(), e); } } public FileMetadata[] download(RegistryContext registryContext) throws ProcessorException { List<FileMetadata> result = new ArrayList<FileMetadata>(); String fileName = null; String warningsFileName = null; File receipt = null; File warningsFile = null; CrlfPrintWriter outputWriter = null; CrlfPrintWriter warningsWriter = null; Date currDate = Calendar.getInstance().getTime(); BillingDownloadHandler handler = null; Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("currentDate", currDate); parameters.put("transferDate", OperDayFactory.getOperDayPlugin().getOperationDay()); parameters.put("paymentDate", downloadDate); fileName = NamedMessageFormat.format(config.outputFileNameFormat, parameters); warningsFileName = NamedMessageFormat.format(config.warningsOutputFileNameFormat, parameters); receipt = File.createTempFile(fileName, ""); warningsFile = File.createTempFile(warningsFileName, ""); outputWriter = new CrlfPrintWriter(new FileOutputStream(receipt), config.lineSeparator); warningsWriter = new CrlfPrintWriter(new FileOutputStream(warningsFile), config.lineSeparator); outputWriter.println("ะกั‚ะฐั€ั‚ ะฒั‹ะณั€ัƒะทะบะธ ะฟะปะฐั‚ะตะถะตะน: " + new LightDateFormat("dd.MM.yyyy:HH:mm:ss").format(new Date())); connection = dataConnectionSource.getConnection(); connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); connection.setReadOnly(true); String sql = ResourceHelper.getResourceAsString(this.getClass(), config.SQLQueryPath); sql = new MessageFormat(sql).format(new Object[] { downloadDate, config.additionalWhere }); logger.info(sql); statement = connection.prepareStatement(sql); resultSet = statement.executeQuery(); NameFieldDescription fields[] = new NameFieldDescription[] {new NameFieldDescription("NOOSB"), new NameFieldDescription("LINUM") }; GroupSelector selector = new GroupSelector(fields); handler = new BillingDownloadHandler(insertConnectionSource, config, registryContext, outputWriter, warningsWriter, logger, login, downloadDate); selector.parse(resultSet, handler); } catch (IOException e) { throw new ProcessorException(e); } catch (SQLException e) { if (outputWriter != null) { outputWriter.println("ะŸั€ะพะธะทะพัˆะปะฐ ะพัˆะธะฑะบะฐ ะฟั€ะธ ะพะฑั€ะฐั‰ะตะฝะธะธ ะบ ะฑะฐะทะต ะดะฐะฝะฝั‹ั… Billing."); } logger.log(Level.WARNING, "ะŸั€ะพะธะทะพัˆะปะฐ ะพัˆะธะฑะบะฐ ะฟั€ะธ ะพะฑั€ะฐั‰ะตะฝะธะธ ะบ ะฑะฐะทะต ะดะฐะฝะฝั‹ั… Billing.", e); throw new ProcessorException(e); } catch (SelectorException e) { logger.log(Level.WARNING, "GroupSelector: ะŸั€ะพะธะทะพัˆะปะฐ ะฝะตะฟั€ะตะดะฒะธะดะตะฝะฝะฐั ะพัˆะธะฑะบะฐ ะฟั€ะธ ะพะฑั€ะฐะฑะพั‚ะบะต ะฟะปะฐั‚ะตะถะฐ.", e); if (outputWriter != null) { outputWriter.println("GroupSelector: ะŸั€ะพะธะทะพัˆะปะฐ ะฝะตะฟั€ะตะดะฒะธะดะตะฝะฝะฐั ะพัˆะธะฑะบะฐ ะฟั€ะธ ะพะฑั€ะฐะฑะพั‚ะบะต ะฟะปะฐั‚ะตะถะฐ."); } } catch (PluginNotFoundException e) { logger.log(Level.SEVERE, "ะะต ะฝะฐะนะดะตะฝ ะฟะปะฐะณะธะฝ ั ะบะพะฝัั‚ะฐะฝั‚ะฐะผะธ ะฟัะตะฒะดะพะฝะธะผะพะฒ ะธ ั„ะพั€ะผะฐั‚ะพะผ XML ะดะพะบัƒะผะตะฝั‚ะฐ", e); throw new ProcessorException(e); } finally { DAOUtil.close(resultSet); DAOUtil.close(statement); DAOUtil.close(connection); } result.add(new FileMetadata(receipt, config.outputDirectory, fileName)); result.add(new FileMetadata(warningsFile, config.outputDirectory, warningsFileName)); if (handler != null) { result.addAll(handler.getPaymentFiles()); } return result.toArray(new FileMetadata[] {}); } }
[ "zhivenkov@mail.ru" ]
zhivenkov@mail.ru
55c0e983c884382bdb762a80308cafa58a081aae
fbf27d453d933352a2c8ef76e0445f59e6b5d304
/server/src/com/fy/engineserver/util/NeedBuildExtraData.java
8f11d85c23a0beca3bd0684fa36454b454d12063
[]
no_license
JoyPanda/wangxian_server
0996a03d86fa12a5a884a4c792100b04980d3445
d4a526ecb29dc1babffaf607859b2ed6947480bb
refs/heads/main
2023-06-29T05:33:57.988077
2021-04-06T07:29:03
2021-04-06T07:29:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
123
java
package com.fy.engineserver.util; public interface NeedBuildExtraData { public void buildExtraData() throws Exception; }
[ "1414464063@qq.com" ]
1414464063@qq.com
22fa8efeddca83f3c8fbf18899ef45787f83a275
7130aa55111830a02bb46787fab9c95996dd717a
/flightcheckin/src/main/java/com/tanmay/flightcheckin/integration/ReservationRestClientImpl.java
f2ee6f38218f5eedd9420138cf78661d801ec59d
[]
no_license
tans105/flight-management-system
aa9ef6b2ff884aff570744111eb098c6305d6bcb
96bcb3e3b4a661a636dd738a43c1c0e38fa75d4b
refs/heads/master
2022-07-13T16:51:14.944680
2020-01-06T16:28:42
2020-01-06T16:28:42
225,027,857
0
0
null
2022-06-30T20:22:06
2019-11-30T14:57:03
Java
UTF-8
Java
false
false
1,060
java
package com.tanmay.flightcheckin.integration; import com.tanmay.flightcheckin.integration.dto.Reservation; import com.tanmay.flightcheckin.integration.dto.ReservationUpdateRequest; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; /** * @author Tanmay * @date 08/12/19 **/ @Component public class ReservationRestClientImpl implements ReservationRestClient { public static final String RESERVATION_REST_URL = "http://localhost:8080/flightreservation/reservations/"; @Override public Reservation findReservation(Long id) { RestTemplate restTemplate = new RestTemplate(); Reservation reservation = restTemplate.getForObject(RESERVATION_REST_URL + id, Reservation.class); return reservation; } @Override public Reservation updateReservation(ReservationUpdateRequest req) { RestTemplate restTemplate = new RestTemplate(); Reservation res = restTemplate.postForObject(RESERVATION_REST_URL, req, Reservation.class); return res; } }
[ "tanmayawasthi105@gmail.com" ]
tanmayawasthi105@gmail.com
96cdfd78f2b297c1059599445efbea85a3625951
40352b5e8b2bc8113ebab8ab53c31faa2e342406
/src/main/java/com/urservices/web/rest/MatiereResource.java
4accc7d53d04a72e7440996fd5cea2dfe5554b4f
[]
no_license
brice-dymas/pedag
b0e0d18efe51e63e40971f7989fd4071cfac8daa
8cd55656639a7265877e59e74c27a814322689ee
refs/heads/master
2023-06-17T12:07:09.975004
2021-07-15T13:47:24
2021-07-15T13:47:24
374,268,671
0
0
null
2021-06-09T08:03:06
2021-06-06T04:39:15
TypeScript
UTF-8
Java
false
false
7,936
java
package com.urservices.web.rest; import com.urservices.domain.Matiere; import com.urservices.repository.MatiereRepository; import com.urservices.service.MatiereService; import com.urservices.web.rest.errors.BadRequestAlertException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.validation.Valid; import javax.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import tech.jhipster.web.util.HeaderUtil; import tech.jhipster.web.util.PaginationUtil; import tech.jhipster.web.util.ResponseUtil; /** * REST controller for managing {@link com.urservices.domain.Matiere}. */ @RestController @RequestMapping("/api") public class MatiereResource { private final Logger log = LoggerFactory.getLogger(MatiereResource.class); private static final String ENTITY_NAME = "matiere"; @Value("${jhipster.clientApp.name}") private String applicationName; private final MatiereService matiereService; private final MatiereRepository matiereRepository; public MatiereResource(MatiereService matiereService, MatiereRepository matiereRepository) { this.matiereService = matiereService; this.matiereRepository = matiereRepository; } /** * {@code POST /matieres} : Create a new matiere. * * @param matiere the matiere to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new matiere, or with status {@code 400 (Bad Request)} if the matiere has already an ID. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PostMapping("/matieres") public ResponseEntity<Matiere> createMatiere(@Valid @RequestBody Matiere matiere) throws URISyntaxException { log.debug("REST request to save Matiere : {}", matiere); if (matiere.getId() != null) { throw new BadRequestAlertException("A new matiere cannot already have an ID", ENTITY_NAME, "idexists"); } Matiere result = matiereService.save(matiere); return ResponseEntity .created(new URI("/api/matieres/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())) .body(result); } /** * {@code PUT /matieres/:id} : Updates an existing matiere. * * @param id the id of the matiere to save. * @param matiere the matiere to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated matiere, * or with status {@code 400 (Bad Request)} if the matiere is not valid, * or with status {@code 500 (Internal Server Error)} if the matiere couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PutMapping("/matieres/{id}") public ResponseEntity<Matiere> updateMatiere( @PathVariable(value = "id", required = false) final Long id, @Valid @RequestBody Matiere matiere ) throws URISyntaxException { log.debug("REST request to update Matiere : {}, {}", id, matiere); if (matiere.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } if (!Objects.equals(id, matiere.getId())) { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } if (!matiereRepository.existsById(id)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } Matiere result = matiereService.save(matiere); return ResponseEntity .ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, matiere.getId().toString())) .body(result); } /** * {@code PATCH /matieres/:id} : Partial updates given fields of an existing matiere, field will ignore if it is null * * @param id the id of the matiere to save. * @param matiere the matiere to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated matiere, * or with status {@code 400 (Bad Request)} if the matiere is not valid, * or with status {@code 404 (Not Found)} if the matiere is not found, * or with status {@code 500 (Internal Server Error)} if the matiere couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PatchMapping(value = "/matieres/{id}", consumes = "application/merge-patch+json") public ResponseEntity<Matiere> partialUpdateMatiere( @PathVariable(value = "id", required = false) final Long id, @NotNull @RequestBody Matiere matiere ) throws URISyntaxException { log.debug("REST request to partial update Matiere partially : {}, {}", id, matiere); if (matiere.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } if (!Objects.equals(id, matiere.getId())) { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } if (!matiereRepository.existsById(id)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } Optional<Matiere> result = matiereService.partialUpdate(matiere); return ResponseUtil.wrapOrNotFound( result, HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, matiere.getId().toString()) ); } /** * {@code GET /matieres} : get all the matieres. * * @param pageable the pagination information. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of matieres in body. */ @GetMapping("/matieres") public ResponseEntity<List<Matiere>> getAllMatieres(Pageable pageable) { log.debug("REST request to get a page of Matieres"); Page<Matiere> page = matiereService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); return ResponseEntity.ok().headers(headers).body(page.getContent()); } /** * {@code GET /matieres/:id} : get the "id" matiere. * * @param id the id of the matiere to retrieve. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the matiere, or with status {@code 404 (Not Found)}. */ @GetMapping("/matieres/{id}") public ResponseEntity<Matiere> getMatiere(@PathVariable Long id) { log.debug("REST request to get Matiere : {}", id); Optional<Matiere> matiere = matiereService.findOne(id); return ResponseUtil.wrapOrNotFound(matiere); } /** * {@code DELETE /matieres/:id} : delete the "id" matiere. * * @param id the id of the matiere to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/matieres/{id}") public ResponseEntity<Void> deleteMatiere(@PathVariable Long id) { log.debug("REST request to delete Matiere : {}", id); matiereService.delete(id); return ResponseEntity .noContent() .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())) .build(); } }
[ "brice.guemkam@iforce5.com" ]
brice.guemkam@iforce5.com
ea126605eed8e0e7e19d4f6dc235a707689a187d
09c12d179be0ddd27311820dcbc5dc0190b0e1b2
/jonix/src/main/java/com/tectonica/jonix/unify/base/onix2/BaseSubject2.java
bb8b88d2889c08481d659dcd05c69a6be1a5bec3
[ "Apache-2.0" ]
permissive
zach-m/jonix
3a2053309d8df96f406b0eca93de6b25b4aa3e98
c7586ed7669ced7f26e937d98b4b437513ec1ea9
refs/heads/master
2023-08-23T19:42:15.570453
2023-07-31T19:02:35
2023-07-31T19:02:35
32,450,400
67
23
Apache-2.0
2023-06-01T03:43:12
2015-03-18T09:47:36
Java
UTF-8
Java
false
false
1,671
java
/* * Copyright (C) 2012-2023 Zach Melamed * * Latest version available online at https://github.com/zach-m/jonix * Contact me at zach@tectonica.co.il * * 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.tectonica.jonix.unify.base.onix2; import com.tectonica.jonix.common.codelist.SubjectSchemeIdentifiers; import com.tectonica.jonix.onix2.Subject; import com.tectonica.jonix.unify.base.BaseSubject; /** * ONIX2 concrete implementation for {@link BaseSubject} * * @author Zach Melamed */ public class BaseSubject2 extends BaseSubject { private static final long serialVersionUID = 1L; public BaseSubject2(SubjectSchemeIdentifiers subjectSchemeIdentifier, String subjectCode, String subjectHeadingText) { super(subjectSchemeIdentifier, subjectCode, subjectHeadingText); } public BaseSubject2(Subject s) { extract(s, this); } public static void extract(Subject s, BaseSubject dest) { dest.subjectSchemeIdentifier = s.subjectSchemeIdentifier().value; dest.subjectCode = s.subjectCode().value; dest.subjectHeadingText = s.subjectHeadingText().value; } }
[ "zach@tectonica.co.il" ]
zach@tectonica.co.il
0c7a2605ab86304cf7f848822408914903489e8a
a1852d4614d703b62def5e3c327820696203c8fa
/Capita-VPM-602_01_19/src/com/acconsys/test/JSpinnerTest.java
9bf4e4b87bb981d75e1a0b06c2b10f4cf637cf4b
[]
no_license
burnszp/Capital_VPM_602
0fb010fb296474c2551377c668d442644f99b7c4
ef8fd0270c0dde2a291e56ec5ed66ed44c6188b9
refs/heads/master
2016-08-11T19:16:19.637697
2016-02-04T08:19:29
2016-02-04T08:19:29
51,062,135
0
0
null
null
null
null
UTF-8
Java
false
false
1,645
java
package com.acconsys.test; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class JSpinnerTest { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public JSpinnerTest() { prepareGUI(); } public static void main(String[] args) { JSpinnerTest swingControlDemo = new JSpinnerTest(); swingControlDemo.showSpinnerDemo(); } private void prepareGUI() { mainFrame = new JFrame("Java Swing Examples"); mainFrame.setSize(400, 400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent) { System.exit(0); } }); headerLabel = new JLabel("", JLabel.CENTER); statusLabel = new JLabel("", JLabel.CENTER); statusLabel.setSize(350, 100); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showSpinnerDemo() { headerLabel.setText("Control in action: JSpinner"); SpinnerModel spinnerModel = new SpinnerNumberModel(10, // initial value 0, // min 100, // max 1);// step JSpinner spinner = new JSpinner(spinnerModel); spinner.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { statusLabel.setText("Value : " + ((JSpinner) e.getSource()).getValue()); } }); controlPanel.add(spinner); mainFrame.setVisible(true); } }
[ "357252539@qq.com" ]
357252539@qq.com
d4d3d6115193ce0d1f1164c11bdf436cc1217151
d6ef88c0d346ed3021a70e3de35ea6e59653e27e
/paas/src/main/java/jit/edu/paas/domain/vo/ContainerNetworkVO.java
080f79b46a69a713ed8d26a05837ebc9a9b282a9
[ "Apache-2.0" ]
permissive
forTWOS/paas
f7acf634757e66b4da328bafa931a4d2f397391e
cbcb21e8a2f574488ea685a92f7f5bd88ea4fc9b
refs/heads/master
2022-03-04T21:52:55.158686
2018-12-01T16:08:05
2018-12-01T16:08:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
251
java
package jit.edu.paas.domain.vo; import jit.edu.paas.domain.entity.ContainerNetwork; import jit.edu.paas.domain.entity.SysNetwork; import lombok.Data; @Data public class ContainerNetworkVO extends ContainerNetwork { private SysNetwork network; }
[ "2212557736@qq.com" ]
2212557736@qq.com
ad01dcc10817294601c48b988fcc1745134515c6
2fab438060f41d6b3082a13c001d296ab0401d2f
/Valid-Parentheses/src/ArrayStack.java
85a372065619dc858826ed7fcc5e86ea526712e0
[]
no_license
wangchen1206/data-stractures
54e037e3b1304dc9f2961cc5c6ddd84c0d6ce4a6
aa4b6c2b573c8cdce86af17fb1ff03aef539851b
refs/heads/master
2020-09-28T20:20:21.330694
2020-01-11T06:13:55
2020-01-11T06:13:55
226,856,453
0
0
null
null
null
null
UTF-8
Java
false
false
1,192
java
package src; /** * @Author: cc * @Date: 2019/12/10 16:15 */ public class ArrayStack<E> implements Stack<E> { Array<E> array; public ArrayStack(int capasity) { this.array = new Array<>(capasity); } public ArrayStack() { this.array = new Array<>(); } @Override public int getSize() { return this.array.getSize(); } @Override public boolean isEmpty() { return this.array.isEmpty(); } public int getCapasity() { return this.array.getCapasity(); } @Override public void push(E e) { this.array.addLast(e); } @Override public E pop() { return this.array.removeLast(); } @Override public E peek() { return this.array.getLast(); } @Override public String toString() { StringBuilder res = new StringBuilder(); res.append("Stack: "); res.append("["); for (int i = 0; i < this.array.getSize(); i++) { res.append(array.get(i)); if (i != this.array.getSize() - 1) res.append(", "); } res.append("] top"); return res.toString(); } }
[ "chen.wang1@hp.com" ]
chen.wang1@hp.com
3aad78226156439c4e80b8cf2d0b6f640fc6628f
70aa72b9b2ed6415cf78bf0b34585de6622d92f0
/org/poreid/cc/CitizenCardIdAttributes.java
87443dc21ea7b66d82165f436f8ccc79d182f0dc
[]
no_license
pussman/SignPro
7abb8c92fb92c3aae2695335debf4d6da422dfaa
606d286e7e837782c06565730fac705432013c3c
refs/heads/master
2021-01-12T00:30:00.792829
2018-02-21T14:46:34
2018-02-21T14:46:34
78,733,564
0
2
null
null
null
null
UTF-8
Java
false
false
10,903
java
/* * The MIT License * * Copyright 2014, 2015, 2016 Rui Martinho (rmartinho@gmail.com), Antรณnio Braz (antoniocbraz@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.poreid.cc; import java.nio.charset.StandardCharsets; import java.util.Arrays; /** * Contem os atributos de identificaรงรฃo do cidadรฃo * @author POReID */ public final class CitizenCardIdAttributes { private boolean isdataLoaded = false; private String issuingEntity; private String country; private String documentType; private String documentNumber; private String documentNumberPAN; private String documentVersion; private String validityBeginDate; private String localofRequest; private String validityEndDate; private String surname; private String name; private String gender; private String nationality; private String dateOfBirth; private String heigh; private String civilianIdNumber; private String surnameMother; private String givenNameMother; private String surnameFather; private String givenNameFather; private String taxNo; private String socialSecurityNo; private String healthNo; private String accidentalIndications; private String mrz1; private String mrz2; private String mrz3; private final byte[] data; protected CitizenCardIdAttributes(byte[] data){ this.data = data; } /** * Retorna o nome completo do cidadรฃo * @return nome completo do cidadรฃo */ public String getCitizenFullName(){ checkNLoad(); return name + " " + surname; } /** * Retorna as indicaรงรตes eventuais * @return indicaรงรตes eventuais */ public String getAccidentalIndications(){ checkNLoad(); return accidentalIndications; } /** * Retorna o nรบmero de identificaรงรฃo civil (nic) * @return nรบmero de identificaรงรฃo civil */ public String getCivilianIdNumber(){ checkNLoad(); return civilianIdNumber; } /** * Retorna o paรญs no formato ISO 3166-1 alpha-3 * @return paรญs no formato ISO 3166-1 alpha-3 */ public String getCountry(){ checkNLoad(); return country; } /** * Retorna a data de nascimento * @return data de nascimento */ public String getDateOfBirth(){ checkNLoad(); return dateOfBirth; } /** * Retorna o nรบmero do documento de identificaรงรฃo (nรบmero do cartรฃo de cidadรฃo) * @return nรบmero do documento de identificaรงรฃo */ public String getDocumentNumber(){ checkNLoad(); return documentNumber; } /** * Retorna o Primary Account Number do cartรฃo de cidadรฃo * @return Primary Account Number do cartรฃo de cidadรฃo */ public String getDocumentNumberPAN(){ checkNLoad(); return documentNumberPAN; } /** * Retorna o tipo de documento (Cartรฃo de Cidadรฃo) * @return tipo de documento */ public String getDocumentType(){ checkNLoad(); return documentType; } /** * Retorna a versรฃo do cartรฃo de cidadรฃo * @return versรฃo do cartรฃo de cidadรฃo */ public String getDocumentVersion(){ checkNLoad(); return documentVersion; } /** * Retorna o gรฉnero * @return gรฉnero */ public String getGender(){ checkNLoad(); return gender; } /** * Retorna os nomes do pai do cidadรฃo * @return nomes do pai do cidadรฃo */ public String getGivenNameFather(){ checkNLoad(); return givenNameFather; } /** * Retorna os nomes da mรฃe do cidadรฃo * @return nomes da mรฃe do cidadรฃo */ public String getGivenNameMother(){ checkNLoad(); return givenNameMother; } /** * Retorna o nรบmero de utente do sistema nacional de saรบde * @return nรบmero de utente do sistema nacional de saรบde */ public String getHealthNo(){ checkNLoad(); return healthNo; } /** * Retorna a altura do cidadรฃo * @return altura do cidadรฃo */ public String getHeigh(){ checkNLoad(); return heigh; } /** * Retorna a entidade emissora do documento * @return entidade emissora do documento */ public String getIssuingEntity(){ checkNLoad(); return issuingEntity; } /** * Retorna o local onde foi efetuado o pedido do documento * @return local onde foi efetuado o pedido do documento */ public String getLocalofRequest(){ checkNLoad(); return localofRequest; } /** * Retorna a primeira linha da Machine Readable Zone (MRZ) * @return primeira linha da Machine Readable Zone (MRZ) */ public String getMrz1(){ checkNLoad(); return mrz1; } /** * Retorna a segunda linha da Machine Readable Zone (MRZ) * @return segunda linha da Machine Readable Zone (MRZ) */ public String getMrz2(){ checkNLoad(); return mrz2; } /** * Retorna a terceira linha da Machine Readable Zone (MRZ) * @return terceira linha da Machine Readable Zone (MRZ) */ public String getMrz3(){ checkNLoad(); return mrz3; } /** * Retorna os nomes do cidadรฃo * @return nomes do cidadรฃo */ public String getName(){ checkNLoad(); return name; } /** * Retorna a nacionalidade do cidadรฃo no formato ISO 3166-1 alpha-3 * @return nacionalidade do cidadรฃo no formato ISO 3166-1 alpha-3 */ public String getNationality(){ checkNLoad(); return nationality; } /** * Retorna o nรบmero de identificaรงรฃo de seguranรงa social * @return nรบmero de identificaรงรฃo de seguranรงa social */ public String getSocialSecurityNo(){ checkNLoad(); return socialSecurityNo; } /** * Retorna os apelidos do cidadรฃo * @return apelidos do cidadรฃo */ public String getSurname(){ checkNLoad(); return surname; } /** * Retorna os apelidos no nome do pai do cidadรฃo * @return apelidos no nome do pai do cidadรฃo */ public String getSurnameFather(){ checkNLoad(); return surnameFather; } /** * Retorna os apelidos no nome da mรฃe do cidadรฃo * @return apelidos no nome da mรฃe do cidadรฃo */ public String getSurnameMother(){ checkNLoad(); return surnameMother; } /** * Retorna o nรบmero de identificaรงรฃo fiscal * @return nรบmero de identificaรงรฃo fiscal */ public String getTaxNo(){ checkNLoad(); return taxNo; } /** * Retorna a data emissรฃo do documento * @return data emissรฃo do documento */ public String getValidityBeginDate(){ checkNLoad(); return validityBeginDate; } /** * Retorna a data de fim de validade * @return data de fim de validade */ public String getValidityEndDate(){ checkNLoad(); return validityEndDate; } /** * Retorna os dados do cidadรฃo tal como lidos do cartรฃo * @return dados do cidadรฃo */ public byte[] getRawData(){ return Arrays.copyOf(data, data.length); } private void checkNLoad(){ if (!isdataLoaded){ parse(data); } } private void parse(byte[] data){ issuingEntity = new String(data, 0, 39, StandardCharsets.UTF_8).trim(); country = new String(data, 40, 80, StandardCharsets.UTF_8).trim(); documentType = new String(data, 120, 34, StandardCharsets.UTF_8).trim(); documentNumber = new String(data, 154, 28, StandardCharsets.UTF_8).trim(); documentNumberPAN = new String(data, 182, 32, StandardCharsets.UTF_8).trim(); documentVersion = new String(data, 214, 16, StandardCharsets.UTF_8).trim(); validityBeginDate = new String(data, 230, 20, StandardCharsets.UTF_8).trim(); localofRequest = new String(data, 250, 60, StandardCharsets.UTF_8).trim(); validityEndDate = new String(data, 310, 20, StandardCharsets.UTF_8).trim(); surname = new String(data, 330, 120, StandardCharsets.UTF_8).trim(); name = new String(data, 450, 120, StandardCharsets.UTF_8).trim(); gender = new String(data, 570, 2, StandardCharsets.UTF_8).trim(); nationality = new String(data, 572, 6, StandardCharsets.UTF_8).trim(); dateOfBirth = new String(data, 578, 20, StandardCharsets.UTF_8).trim(); heigh = new String(data, 598, 8, StandardCharsets.UTF_8).trim(); civilianIdNumber = new String(data, 606, 18, StandardCharsets.UTF_8).trim(); surnameMother = new String(data, 624, 120, StandardCharsets.UTF_8).trim(); givenNameMother = new String(data, 744, 120, StandardCharsets.UTF_8).trim(); surnameFather = new String(data, 864, 120, StandardCharsets.UTF_8).trim(); givenNameFather = new String(data, 984, 120, StandardCharsets.UTF_8).trim(); taxNo = new String(data, 1104, 18, StandardCharsets.UTF_8).trim(); socialSecurityNo = new String(data, 1122, 22, StandardCharsets.UTF_8).trim(); healthNo = new String(data, 1144, 18, StandardCharsets.UTF_8).trim(); accidentalIndications = new String(data, 1162, 120, StandardCharsets.UTF_8).trim(); mrz1 = new String(data, 1282, 30, StandardCharsets.UTF_8).trim(); mrz2 = new String(data, 1312, 30, StandardCharsets.UTF_8).trim(); mrz3 = new String(data, 1342, 30, StandardCharsets.UTF_8).trim(); isdataLoaded = true; } }
[ "pedro.ussman@infosistema.com" ]
pedro.ussman@infosistema.com
eef97e35f5e9622fece38b11040ecd1dc7e666e1
11521e97a8c369630458e6e08888002d379b8c1e
/CarRental/src/test/java/cz/muni/fi/lease/LeaseManagerImplTest.java
a3c65024c9d05c1eaf88358a80193e269be8d166
[]
no_license
RobertTamas/pv168
023ecacff873472d0db032a991c25bbe7f24a309
b5551199a019da67fabc97205c83ddd84ff28ba4
refs/heads/master
2021-01-01T20:14:39.589738
2017-07-30T19:19:11
2017-07-30T19:19:11
98,797,541
0
0
null
null
null
null
UTF-8
Java
false
false
15,685
java
package cz.muni.fi.lease; import cz.muni.fi.car.Car; import cz.muni.fi.car.CarManagerImpl; import cz.muni.fi.customer.Customer; import cz.muni.fi.customer.CustomerManagerImpl; import cz.muni.fi.exceptions.IllegalEntityException; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import java.sql.SQLException; import java.time.Clock; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import static java.time.Month.FEBRUARY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * @author Robert Tamas, Maros Struk */ public class LeaseManagerImplTest { private LeaseManagerImpl manager; private CarManagerImpl carManager; private CustomerManagerImpl customerManager; private EmbeddedDatabase ds; private final static ZonedDateTime NOW = LocalDateTime.of(2016, FEBRUARY, 29, 14, 00).atZone(ZoneId.of("UTC")); @Rule public ExpectedException expectedException = ExpectedException.none(); @Before public void setUp() throws Exception { manager = new LeaseManagerImpl(Clock.fixed(NOW.toInstant(), NOW.getZone())); carManager = new CarManagerImpl(); customerManager = new CustomerManagerImpl(); ds = new EmbeddedDatabaseBuilder().setType( EmbeddedDatabaseType.DERBY).addScript( "createTables.sql").build(); manager.setDataSource(ds); carManager.setDataSource(ds); customerManager.setDataSource(ds); } @After public void tearDown() throws SQLException { ds.shutdown(); } @Test public void createLease() { Customer c = new Customer("Jozef Mrkva", "Bratislavska 1", "1111-90-21-31"); Car car = new Car("ZA1234", "Audi", "A7", 50); Lease lease = new Lease(car, c, 50, LocalDate.of(2014, 10, 10), LocalDate.of(2014, 12, 10), null); carManager.createCar(car); customerManager.createCustomer(c); manager.createLease(lease); Long leaseId = lease.getId(); assertNotNull(leaseId); Lease result = manager.getLeaseById(leaseId); assertNotSame(lease, result); assertDeepEquals(lease, result); } @Test(expected = IllegalArgumentException.class) public void createNullLease() { manager.createLease(null); } @Test(expected = IllegalEntityException.class) public void createLeaseWithExistingId() { Customer c = new Customer("Jozef Mrkva", "Bratislavska 1", "1111-90-21-31"); Car car = new Car("ZA1234", "Audi", "A7", 50); Lease lease = new Lease(car, c, 50, LocalDate.of(2014, 10, 10), LocalDate.of(2014, 12, 10), null); lease.setId(1l); manager.createLease(lease); } @Test public void findAllLeases() { assertTrue(manager.findAllLeases().isEmpty()); Customer c1 = new Customer("Peter Vesely", "Kosicka 4", "1111-32-78-17"); Car car1 = new Car("BA0193", "Skoda", "Superb", 40); Lease lease1 = new Lease(car1, c1, 40, LocalDate.of(2015, 2, 6), LocalDate.of(2015, 3, 8), null); Customer c2 = new Customer("Jozef Mrkva", "Bratislavska 1", "1111-90-21-31"); Car car2 = new Car("ZA1234", "Audi", "A7", 50); Lease lease2 = new Lease(car2, c2, 50, LocalDate.of(2014, 10, 10), LocalDate.of(2014, 12, 10), null); carManager.createCar(car1); customerManager.createCustomer(c1); carManager.createCar(car2); customerManager.createCustomer(c2); manager.createLease(lease1); manager.createLease(lease2); List<Lease> expected = Arrays.asList(lease1, lease2); List<Lease> actual = manager.findAllLeases(); Collections.sort(expected, LEASE_ID_COMPARATOR); Collections.sort(actual, LEASE_ID_COMPARATOR); assertDeepEquals(expected, actual); } @Test public void updateLease() throws Exception { Customer c1 = new Customer("Peter Vesely", "Kosicka 4", "1111-32-78-17"); Car car1 = new Car("BA0193", "Skoda", "Superb", 40); Lease lease1 = new Lease(car1, c1, 40, LocalDate.of(2015, 2, 6), LocalDate.of(2015, 3, 8), null); Customer c2 = new Customer("Jozef Mrkva", "Bratislavska 1", "1111-90-21-31"); Car car2 = new Car("ZA1234", "Audi", "A7", 50); Lease lease2 = new Lease(car2, c2, 50, LocalDate.of(2014, 10, 10), LocalDate.of(2014, 12, 10), null); carManager.createCar(car1); customerManager.createCustomer(c1); carManager.createCar(car2); customerManager.createCustomer(c2); manager.createLease(lease1); manager.createLease(lease2); Long leaseId = c1.getId(); lease1 = manager.getLeaseById(leaseId); Car car3 = new Car("KA2222", "Subaru", "Impreza", 39); carManager.createCar(car3); lease1.setCar(car3); manager.updateLease(lease1); assertDeepEqualsCar(car3, lease1.getCar()); assertDeepEqualsCustomer(c1, lease1.getCustomer()); assertEquals(40, lease1.getPrice()); assertEquals(LocalDate.of(2015, 2, 6), lease1.getStartTime()); assertEquals(LocalDate.of(2015, 3, 8), lease1.getExpectedEndTime()); assertEquals(null, lease1.getRealEndTime()); lease1 = manager.getLeaseById(leaseId); Customer c3 = new Customer("Miroslav Novotny", "Fesakova 69", "0911 222 333 444"); customerManager.createCustomer(c3); lease1.setCustomer(c3); manager.updateLease(lease1); assertDeepEqualsCar(car3, lease1.getCar()); assertDeepEqualsCustomer(c3, lease1.getCustomer()); assertEquals(40, lease1.getPrice()); assertEquals(LocalDate.of(2015, 2, 6), lease1.getStartTime()); assertEquals(LocalDate.of(2015, 3, 8), lease1.getExpectedEndTime()); assertEquals(null, lease1.getRealEndTime()); lease1 = manager.getLeaseById(leaseId); lease1.setPrice(100); manager.updateLease(lease1); assertDeepEqualsCar(car3, lease1.getCar()); assertDeepEqualsCustomer(c3, lease1.getCustomer()); assertEquals(100, lease1.getPrice()); assertEquals(LocalDate.of(2015, 2, 6), lease1.getStartTime()); assertEquals(LocalDate.of(2015, 3, 8), lease1.getExpectedEndTime()); assertEquals(null, lease1.getRealEndTime()); lease1 = manager.getLeaseById(leaseId); lease1.setStartTime(LocalDate.of(2010, 1, 1)); manager.updateLease(lease1); assertDeepEqualsCar(car3, lease1.getCar()); assertDeepEqualsCustomer(c3, lease1.getCustomer()); assertEquals(100, lease1.getPrice()); assertEquals(LocalDate.of(2010, 1, 1), lease1.getStartTime()); assertEquals(LocalDate.of(2015, 3, 8), lease1.getExpectedEndTime()); assertEquals(null, lease1.getRealEndTime()); lease1 = manager.getLeaseById(leaseId); lease1.setExpectedEndTime(LocalDate.of(2011, 12, 12)); manager.updateLease(lease1); assertDeepEqualsCar(car3, lease1.getCar()); assertDeepEqualsCustomer(c3, lease1.getCustomer()); assertEquals(100, lease1.getPrice()); assertEquals(LocalDate.of(2010, 1, 1), lease1.getStartTime()); assertEquals(LocalDate.of(2011, 12, 12), lease1.getExpectedEndTime()); assertEquals(null, lease1.getRealEndTime()); lease1 = manager.getLeaseById(leaseId); lease1.setRealEndTime(LocalDate.of(2020, 2, 13)); manager.updateLease(lease1); assertDeepEqualsCar(car3, lease1.getCar()); assertDeepEqualsCustomer(c3, lease1.getCustomer()); assertEquals(100, lease1.getPrice()); assertEquals(LocalDate.of(2010, 1, 1), lease1.getStartTime()); assertEquals(LocalDate.of(2011, 12, 12), lease1.getExpectedEndTime()); assertEquals(LocalDate.of(2020, 2, 13), lease1.getRealEndTime()); // Check if updates didn't affected other records assertDeepEquals(lease2, manager.getLeaseById(lease2.getId())); } @Test(expected = IllegalEntityException.class) public void updateNullLease() { manager.updateLease(null); } @Test(expected = IllegalEntityException.class) public void updateLeaseWithNullId() { Customer c1 = new Customer("Peter Vesely", "Kosicka 4", "1111-32-78-17"); Car car1 = new Car("BA0193", "Skoda", "Superb", 40); Lease lease = new Lease(car1, c1, 40, LocalDate.of(2015, 2, 6), LocalDate.of(2015, 3, 8), null); carManager.createCar(car1); customerManager.createCustomer(c1); manager.createLease(lease); lease.setId(null); manager.updateLease(lease); } @Test(expected = IllegalEntityException.class) public void updateLeaseWithNonExistingId() { Customer c1 = new Customer("Peter Vesely", "Kosicka 4", "1111-32-78-17"); Car car1 = new Car("BA0193", "Skoda", "Superb", 40); Lease lease = new Lease(car1, c1, 40, LocalDate.of(2015, 2, 6), LocalDate.of(2015, 3, 8), null); carManager.createCar(car1); customerManager.createCustomer(c1); manager.createLease(lease); lease.setId(lease.getId() + 1); manager.updateLease(lease); } @Test public void deleteLease() throws Exception { Customer c1 = new Customer("Peter Vesely", "Kosicka 4", "1111-32-78-17"); Car car1 = new Car("BA0193", "Skoda", "Superb", 40); Lease lease1 = new Lease(car1, c1, 40, LocalDate.of(2015, 2, 6), LocalDate.of(2015, 3, 8), null); Customer c2 = new Customer("Jozef Mrkva", "Bratislavska 1", "1111-90-21-31"); Car car2 = new Car("ZA1234", "Audi", "A7", 50); Lease lease2 = new Lease(car2, c2, 50, LocalDate.of(2014, 10, 10), LocalDate.of(2014, 12, 10), null); carManager.createCar(car1); customerManager.createCustomer(c1); carManager.createCar(car2); customerManager.createCustomer(c2); manager.createLease(lease1); manager.createLease(lease2); assertNotNull(manager.getLeaseById(lease1.getId())); assertNotNull(manager.getLeaseById(lease2.getId())); manager.deleteLease(lease1); assertNull(manager.getLeaseById(lease1.getId())); assertNotNull(manager.getLeaseById(lease2.getId())); } @Test(expected = IllegalArgumentException.class) public void deleteNullLease() { manager.deleteLease(null); } @Test(expected = IllegalEntityException.class) public void deleteLeaseWithNonExistingId() { Customer c1 = new Customer("Peter Vesely", "Kosicka 4", "1111-32-78-17"); Car car1 = new Car("BA0193", "Skoda", "Superb", 40); Lease lease = new Lease(car1, c1, 40, LocalDate.of(2015, 2, 6), LocalDate.of(2015, 3, 8), null); lease.setId(1L); carManager.createCar(car1); customerManager.createCustomer(c1); manager.deleteLease(lease); } @Test public void findAllLeasesForCustomer() throws Exception { Customer c1 = new Customer("Peter Vesely", "Kosicka 4", "1111-32-78-17"); Car car1 = new Car("BA0193", "Skoda", "Superb", 40); Lease lease1 = new Lease(car1, c1, 40, LocalDate.of(2015, 2, 6), LocalDate.of(2015, 3, 8), null); Customer c2 = new Customer("Jozef Mrkva", "Bratislavska 1", "1111-90-21-31"); Car car2 = new Car("ZA1234", "Audi", "A7", 50); Lease lease2 = new Lease(car2, c2, 50, LocalDate.of(2014, 10, 10), LocalDate.of(2014, 12, 10), null); carManager.createCar(car1); customerManager.createCustomer(c1); carManager.createCar(car2); customerManager.createCustomer(c2); manager.createLease(lease1); manager.createLease(lease2); List<Lease> leases = manager.findAllLeasesForCustomer(c1); assertDeepEquals(leases.get(0), lease1); } @Test public void findAllLeasesForCar() throws Exception { Customer c1 = new Customer("Peter Vesely", "Kosicka 4", "1111-32-78-17"); Car car1 = new Car("BA0193", "Skoda", "Superb", 40); Lease lease1 = new Lease(car1, c1, 40, LocalDate.of(2015, 2, 6), LocalDate.of(2015, 3, 8), null); Customer c2 = new Customer("Jozef Mrkva", "Bratislavska 1", "1111-90-21-31"); Car car2 = new Car("ZA1234", "Audi", "A7", 50); Lease lease2 = new Lease(car2, c2, 50, LocalDate.of(2014, 10, 10), LocalDate.of(2014, 12, 10), null); carManager.createCar(car1); customerManager.createCustomer(c1); carManager.createCar(car2); customerManager.createCustomer(c2); manager.createLease(lease1); manager.createLease(lease2); List<Lease> leases = manager.findAllLeasesForCar(car1); assertDeepEquals(leases.get(0), lease1); } private void assertDeepEquals(List<Lease> expectedList, List<Lease> actualList) { for (int i = 0; i < expectedList.size(); i++) { Lease expected = expectedList.get(i); Lease actual = actualList.get(i); assertDeepEquals(expected, actual); } } private void assertDeepEquals(Lease expected, Lease actual) { assertEquals(expected.getId(), actual.getId()); assertDeepEqualsCar(expected.getCar(), actual.getCar()); assertDeepEqualsCustomer(expected.getCustomer(), actual.getCustomer()); assertEquals(expected.getPrice(), actual.getPrice()); assertEquals(expected.getStartTime(), actual.getStartTime()); assertEquals(expected.getExpectedEndTime(), actual.getExpectedEndTime()); assertEquals(expected.getRealEndTime(), actual.getRealEndTime()); } private void assertDeepEqualsCustomer(Customer expected, Customer actual) { assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getFullName(), actual.getFullName()); assertEquals(expected.getAddress(), actual.getAddress()); assertEquals(expected.getPhoneNumber(), actual.getPhoneNumber()); } private void assertDeepEqualsCar(Car expected, Car actual) { assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getLicencePlate(), actual.getLicencePlate()); assertEquals(expected.getBrand(), actual.getBrand()); assertEquals(expected.getModel(), actual.getModel()); assertEquals(expected.getPricePerDay(), actual.getPricePerDay()); } private static final Comparator<Lease> LEASE_ID_COMPARATOR = (l1, l2) -> l1.getId().compareTo(l2.getId()); }
[ "xtamas@fi.muni.cz" ]
xtamas@fi.muni.cz
e859da5e8f19e3428154853fec68f5d5cb6f4608
959b28197fb32ca7259ffafed81f496485a86a71
/src/funcao/Lt01_Func43.java
83e7337098be736801df3fef7690a69c646ddbc1
[]
no_license
CaiqueVidal/LinguagemProgramacao
f11509d3edd030a7d58e66c862a71a8174148120
e9fa4cd3612aad1120c0b4c471aa782319652e23
refs/heads/master
2020-12-22T17:38:25.387721
2020-01-29T01:04:35
2020-01-29T01:04:35
236,877,676
0
0
null
null
null
null
UTF-8
Java
false
false
322
java
package funcao; public class Lt01_Func43 { public static void main(String[] args) { System.out.print(anosNecessarios()); } public static int anosNecessarios() { double ana = 1.10; double maria = 1.50; int ano = 0; while (ana < maria) { ano++; ana += 0.03; maria += 0.02; } return ano; } }
[ "caique.freitas2@fatec.sp.gov.br" ]
caique.freitas2@fatec.sp.gov.br
3b996d5d04b20cbd175c464d1ba97770ead2649e
9972a07cb24612c0220b64643dc98874aeeb144a
/src/main/java/pl/edu/mimuw/javabytecodestaticchecker/detect/NullPointerDetector.java
e08e23efb234dd67c81f6b5c09079dd531f34c98
[]
no_license
mziemba/jbsc
148f764d8b5e6ec53ba9655d64c6c517ddf4ac1e
fa77ddf610157841723356f3138630ec2e6c238d
refs/heads/master
2021-01-17T13:10:33.816577
2012-07-21T12:58:52
2012-07-21T12:58:52
3,074,186
1
0
null
null
null
null
UTF-8
Java
false
false
146
java
package pl.edu.mimuw.javabytecodestaticchecker.detect; /** * * @author M. Ziemba */ public class NullPointerDetector implements Detector { }
[ "ziembal86@gmail.com" ]
ziembal86@gmail.com
bd9e1bcb5be776dcfefe2822ee509a41b84f08db
789ff89a6728160616e5e05d45266360ba99b277
/src/main/java/com/enriquezrene/javaserial/demo/SerialPortCom.java
e106d50118ea10ea7bf814b174b730dd6c5aca76
[]
no_license
enriquezrene/java-serial
746044fba319ef7c54eda14ebac2427109ca2b1b
570ae167490b789662ab64f9e7b451ca6fcc9129
refs/heads/master
2021-01-10T12:37:39.859586
2016-03-22T14:46:21
2016-03-22T14:46:21
54,483,028
0
0
null
null
null
null
UTF-8
Java
false
false
1,351
java
package com.enriquezrene.javaserial.demo; import jssc.SerialPort; import jssc.SerialPortException; import jssc.SerialPortList; /** * Created by rene on 22/03/16. */ public class SerialPortCom { private SerialPort serialPort; public SerialPortCom() { } public void initialize(String serialPortName) throws Exception { serialPort = new SerialPort(serialPortName); // Open serial port serialPort.openPort(); // Set connection params serialPort.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT); // Set a listener to read the ARDUINO output serialPort.addEventListener(new PortReader(serialPort), SerialPort.MASK_RXCHAR); } public void closeConnection() throws Exception { serialPort.closePort(); } public void sendData(String data) { try { serialPort.writeString(data); } catch (SerialPortException e) { e.printStackTrace(); } } public String[] getAvailableSerialPorts() { String[] ports = SerialPortList.getPortNames(); return ports; } }
[ "renriquez@ioet.com" ]
renriquez@ioet.com
14d7406dcf91684f1c0b141e343e0ea89d815aa0
24a32bc2aafcca19cf5e5a72ee13781387be7f0b
/src/framework/tags/gwt-test-utils-parent-0.36/gwt-test-utils/src/test/java/com/octo/gwt/test/MenuBarImagesTest.java
49209124506d020cd5bea5cfe155bbf10db0a5c5
[]
no_license
google-code-export/gwt-test-utils
27d6ee080f039a8b4111e04f32ba03e5396dced5
0391347ea51b3db30c4433566a8985c4e3be240e
refs/heads/master
2016-09-09T17:24:59.969944
2012-11-20T07:13:03
2012-11-20T07:13:03
32,134,062
0
0
null
null
null
null
UTF-8
Java
false
false
2,280
java
package com.octo.gwt.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.AbstractImagePrototype; import com.google.gwt.user.client.ui.AbstractImagePrototype.ImagePrototypeElement; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.MenuBar.MenuBarImages; @SuppressWarnings("deprecation") public class MenuBarImagesTest extends GwtTestTest { private final MenuBarImages menuBarImages = GWT.create(MenuBarImages.class); @Test public void checkToString() { // Arrange AbstractImagePrototype proto = menuBarImages.menuBarSubMenuIcon(); // Act & Assert assertNotNull(proto.toString()); } @Test public void createElement() { // Arrange AbstractImagePrototype proto = menuBarImages.menuBarSubMenuIcon(); // Act ImagePrototypeElement element = proto.createElement(); // Assert assertEquals("IMG", element.getTagName()); assertEquals( "<img onload=\"this.__gwtLastUnhandledEvent=\"load\";\" src=\"http://127.0.0.1:8888/gwt_test_utils_module/clear.cache.gif\" style=\"width: 0px; height: 0px; background:-url(http://127.0.0.1: 8888/gwt_test_utils_module/menuBarSubMenuIcon.gif) no-repeat 0px 0px; \" border=\"0\"></img>", element.toString()); } @Test public void createImage() { // Arrange AbstractImagePrototype proto = menuBarImages.menuBarSubMenuIcon(); // Act Image image = proto.createImage(); // Assert assertEquals( "http://127.0.0.1:8888/gwt_test_utils_module/menuBarSubMenuIcon.gif", image.getUrl()); } @Test public void getHTML() { // Arrange AbstractImagePrototype proto = menuBarImages.menuBarSubMenuIcon(); // Act String html = proto.getHTML(); // Assert assertEquals( "<img onload='this.__gwtLastUnhandledEvent=\"load\";' src='http://127.0.0.1:8888/gwt_test_utils_module/clear.cache.gif' style='width: 0px; height: 0px; background: url(http://127.0.0.1:8888/gwt_test_utils_module/menuBarSubMenuIcon.gif) no-repeat 0px 0px;' border='0'>", html); } }
[ "gael.lazzari@d9eb14d4-a931-11de-b950-3d5b5f4ea0aa" ]
gael.lazzari@d9eb14d4-a931-11de-b950-3d5b5f4ea0aa
82cb08c05c2cfe5c2f4296bad922947f9b5fb09a
2efeb7bf53b0b82244348402ca261cef91a7d14e
/src/raiders/BuyElements/PackMachine.java
ee302c3d306d5335519ccdd34706082f9758f17b
[]
no_license
StephenLeshko/Raiders
ccc2c05da8af478a93b31b44a24d88abee31a1b3
8a0b37b9c766482f966c0159a1a46e89cac775fa
refs/heads/master
2023-04-14T19:45:21.650190
2021-05-07T16:17:55
2021-05-07T16:17:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,956
java
package raiders.BuyElements; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import javax.swing.ImageIcon; import raiders.Player; import raiders.Proximity; import raiders.Weapons; public class PackMachine extends BuyStation { private Weapons weapons; private int weapon; private boolean showMessage = false; //Will create 3 different instances of this class in the Main Class private final Image packMachine = new ImageIcon("/Users/21sleshko/NetBeansProjects/Raiders/packMachine.png").getImage(); //Has all the possible weapons on the ground... public PackMachine(float x, float y, Player player, int price, String name, Weapons weapons, int weapon) { super(x, y, player, price, name); this.weapons = weapons; this.weapon = weapon; } @Override public void update(long timePassed) { if(Proximity.checkProx(player.getX(), player.getY(), this.x, this.y)){ showMessage = true; }else{ showMessage = false; } } @Override public void draw(Graphics g) { g.drawImage(packMachine, (int) x, (int) y, null); if(showMessage && weapons.getWeapon() != weapon){ g.setFont(new Font("Avenir", Font.BOLD, 30)); g.setColor(Color.WHITE); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.drawString("Buy " + name + " for $" + price, 500, 500); } } @Override public void buy(){ if(showMessage && player.getPoints() >= price && weapons.getWeapon() != weapon){ //Audio.playSound("packSound.wav"); player.subtractPoints(price); weapons.packAPunch(); } } }
[ "21sleshko@192.168.1.196" ]
21sleshko@192.168.1.196
e8b9363d96f569d03a2626161e1538846df9068b
d25a353bfbd5dcdf39b1fb5a18dd3eebc0dfbe80
/MovieApp/app/src/main/java/com/kyh/movieapp/viewmodel/MovieDescriptionViewModel.java
81c549f9a1228894969ae400ab986fe1aa88dd53
[]
no_license
YeRyeonHur/AndroidPractice
d592dc8102148d49f4f746be7af7f4b859a96434
d1f9919099622226a9c021dbb09265a49d29cfb0
refs/heads/master
2023-06-11T01:53:59.043651
2021-07-01T14:30:26
2021-07-01T14:30:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,412
java
package com.kyh.movieapp.viewmodel; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import androidx.annotation.RequiresApi; import com.kyh.movieapp.databinding.ActivityMovieDescriptionBinding; import com.kyh.movieapp.model.repositories.RepositoryHome; import com.kyh.movieapp.model.repositories.RepositoryLikeList; import com.kyh.movieapp.model.repositories.RepositoryMovieDescription; import com.kyh.movieapp.util.ImagePutter; public class MovieDescriptionViewModel { private static MovieDescriptionViewModel movieDescriptionViewModel; private ActivityMovieDescriptionBinding binding; private boolean isLiked; private MovieDescriptionViewModel(LayoutInflater inflater, Context context) { this.binding = ActivityMovieDescriptionBinding.inflate(inflater); this.isLiked = RepositoryLikeList.getLikedItems().contains(RepositoryMovieDescription.getItem()); RepositoryHome.addImage(RepositoryMovieDescription.getItem().getImage()); if(isLiked) { binding.movieDescriptionLikeBtn.setColorFilter(Color.parseColor("#FF0000")); } else { binding.movieDescriptionLikeBtn.setColorFilter(Color.parseColor("#000000")); } binding.movieDescriptionTitleText.setText(RepositoryMovieDescription.getItem().getTitle()); binding.movieDescriptionSubtitleText.setText(RepositoryMovieDescription.getItem().getSubtitle()); binding.movieDescriptionPubDateText.setText(RepositoryMovieDescription.getItem().getPubDate()); binding.movieDescriptionDirectorText.setText(RepositoryMovieDescription.getItem().getDirector()); binding.movieDescriptionActorText.setText(RepositoryMovieDescription.getItem().getActor()); binding.movieDescriptionUserRatingText.setText(RepositoryMovieDescription.getItem().getUserRating() + ""); ImagePutter.putImage(context, RepositoryMovieDescription.getItem().getImage(), binding.movieDescriptionImage); binding.movieDescriptionLikeBtn.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void onClick(View v) { if(isLiked) { binding.movieDescriptionLikeBtn.setColorFilter(Color.parseColor("#000000")); } else { binding.movieDescriptionLikeBtn.setColorFilter(Color.parseColor("#FF0000")); } isLiked = !isLiked; } }); } public static MovieDescriptionViewModel getInstance() { return movieDescriptionViewModel; } public static void setMovieDescriptionViewModel(LayoutInflater inflater, Context context) { MovieDescriptionViewModel.movieDescriptionViewModel = new MovieDescriptionViewModel(inflater, context); } public ActivityMovieDescriptionBinding getBinding() { return binding; } public void handleItemToLikeList() { if(isLiked) { if(!RepositoryLikeList.getLikedItems().contains(RepositoryMovieDescription.getItem())) { RepositoryLikeList.addLikedItems(RepositoryMovieDescription.getItem()); } } else { RepositoryLikeList.getLikedItems().remove(RepositoryMovieDescription.getItem()); } } }
[ "kimyoungho0415@gmail.com" ]
kimyoungho0415@gmail.com
a2c34331e1ea2c59929a460070ee4014daef8f55
213a49d646b205a3d417c0f9bb6b2d1c7b5b8094
/Game.java
e534545ba0290044cb8ed8997872f7f90dc7daf6
[]
no_license
mremiasz/JAVA
c6e3d0fa61562b0c9b43911ce8aff0effc3bfb26
6b2c73a7e9cfdc4b524a4d6c82d0fe59c597ab92
refs/heads/master
2020-03-18T04:48:31.844598
2018-12-30T18:21:11
2018-12-30T18:21:11
134,307,411
0
0
null
null
null
null
UTF-8
Java
false
false
1,745
java
import java.util.Random; import java.util.Scanner; public class Game { public static String hashEqualizer(String word){ StringBuilder sb = new StringBuilder(); while (sb.length()< word.length()){ sb.append('*'); } return String.valueOf(sb); } public static void main(String[] args) { String[] words = {"aa", "bbb"}; Scanner scanner = new Scanner(System.in); Random random = new Random(); int fails = 0; int points = 0; String response; while (fails < 3){ String word = words[random.nextInt(words.length)]; String hashWord = word; for (int i = 0; i < points; i+=1) { char randomChar = hashWord.charAt(random.nextInt(hashWord.length())); if (randomChar == '*') { i--; continue; } hashWord = hashWord.replaceFirst(String.valueOf(randomChar), "*"); } if (hashWord.equals(hashEqualizer(hashWord))) { fails = 3; } else { System.out.println("Twoje wylosowane sล‚owo: " + hashWord); System.out.print("Podaj sล‚owo: "); response = scanner.nextLine(); if (word.equalsIgnoreCase(response)) { points++; System.out.println("Gratulacje!! \nTwoje punkty: " + points +"\n"); } else { System.out.println("Podaล‚eล› zล‚e sล‚owo.\n"); fails++; points--; } } } System.out.println("Koniec gry. Twoje punkty: " + (points)); } }
[ "michalremiasz@gmail.com" ]
michalremiasz@gmail.com
c805458431b2ce3f41e868c663a5c83a2307a444
41d7eb02bb5946031193b21b523727be7194e83e
/server/src/main/java/com/xpzheng/server/ServerApplication.java
64bdf93487e9ed9d79f4d996d1c859fa1b209016
[]
no_license
shoppingzh/2019-ncov
e341130b6c70e5d8c02e63edeb7f6b2f57d36c1f
44cce68612ecd9b7402adcbf7cc410df0b75d196
refs/heads/master
2022-07-13T07:51:15.986645
2020-02-12T09:08:30
2020-02-12T09:08:30
238,414,454
0
0
null
2022-06-23T00:14:20
2020-02-05T09:38:33
Vue
UTF-8
Java
false
false
707
java
package com.xpzheng.server; import com.xpzheng.server.filter.CorsFilter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; @SpringBootApplication public class ServerApplication { public static void main(String[] args) { SpringApplication.run(ServerApplication.class, args); } @Bean public FilterRegistrationBean corsFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(new CorsFilter()); registration.addUrlPatterns("/api/*"); return registration; } }
[ "1049262057@qq.com" ]
1049262057@qq.com
24c0e2362f7808b069ea85f38033725ca3d7eaa9
894795383b62c1ed345ae8b0e023908c074f9755
/src/test/java/com/websites/pages/BasePage.java
396d548b9f93341732f35c2c32310d228b40e6a3
[]
no_license
sdet2020/Cucumber6AllureReport
6fd8867db8661fbe9393d92d471b2bb414eccd7d
2044507d2df8d80333f2c9c761f432ea4c43a122
refs/heads/master
2023-03-17T10:56:52.655831
2021-03-10T15:18:42
2021-03-10T15:18:42
346,394,124
0
0
null
null
null
null
UTF-8
Java
false
false
291
java
package com.websites.pages; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.PageFactory; public class BasePage { WebDriver driver; public BasePage(){ PageFactory.initElements(driver, this); } }
[ "cybertek.b20@gmail.com" ]
cybertek.b20@gmail.com
b92efa6a9427ec286980742683cf51e7e6764885
e97ef604a06160f44af53a16c0dfeb5ceaad4d5d
/src/com/hb/entity/system/Department.java
3edbcbbcd87b0938d0e0ff41db4b73cfe9638252
[]
no_license
kevery/ssm
3f6ea6fdb3f6b71c4872e0419b17eacd84c674eb
af54504a5586ef3377c332da999aefe8817579b4
refs/heads/master
2021-01-20T00:34:15.623657
2017-04-23T15:31:31
2017-04-23T15:31:31
88,529,148
0
0
null
null
null
null
UTF-8
Java
false
false
2,790
java
package com.hb.entity.system; import java.util.List; /** * * ็ฑปๅ็งฐ๏ผš็ป„็ป‡ๆœบๆž„ * ็ฑปๆ่ฟฐ๏ผš * @author FH QQ [้’่‹”] * ไฝœ่€…ๅ•ไฝ๏ผš * ่”็ณปๆ–นๅผ๏ผš * ไฟฎๆ”นๆ—ถ้—ด๏ผš2015ๅนด12ๆœˆ16ๆ—ฅ * @version 2.0 */ public class Department { private String NAME; //ๅ็งฐ private String NAME_EN; //่‹ฑๆ–‡ๅ็งฐ private String BIANMA; //็ผ–็  private String PARENT_ID; //ไธŠ็บงID private String HEADMAN; //่ดŸ่ดฃไบบ private String TEL; //็”ต่ฏ private String FUNCTIONS; //้ƒจ้—จ่Œ่ƒฝ private String BZ; //ๅค‡ๆณจ private String ADDRESS; //ๅœฐๅ€ private String DEPARTMENT_ID; //ไธป้”ฎ private String target; private Department department; private List<Department> subDepartment; private boolean hasDepartment = false; private String treeurl; private String icon; public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getNAME() { return NAME; } public void setNAME(String nAME) { NAME = nAME; } public String getNAME_EN() { return NAME_EN; } public void setNAME_EN(String nAME_EN) { NAME_EN = nAME_EN; } public String getBIANMA() { return BIANMA; } public void setBIANMA(String bIANMA) { BIANMA = bIANMA; } public String getPARENT_ID() { return PARENT_ID; } public void setPARENT_ID(String pARENT_ID) { PARENT_ID = pARENT_ID; } public String getHEADMAN() { return HEADMAN; } public void setHEADMAN(String hEADMAN) { HEADMAN = hEADMAN; } public String getTEL() { return TEL; } public void setTEL(String tEL) { TEL = tEL; } public String getFUNCTIONS() { return FUNCTIONS; } public void setFUNCTIONS(String fUNCTIONS) { FUNCTIONS = fUNCTIONS; } public String getBZ() { return BZ; } public void setBZ(String bZ) { BZ = bZ; } public String getADDRESS() { return ADDRESS; } public void setADDRESS(String aDDRESS) { ADDRESS = aDDRESS; } public String getDEPARTMENT_ID() { return DEPARTMENT_ID; } public void setDEPARTMENT_ID(String dEPARTMENT_ID) { DEPARTMENT_ID = dEPARTMENT_ID; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public List<Department> getSubDepartment() { return subDepartment; } public void setSubDepartment(List<Department> subDepartment) { this.subDepartment = subDepartment; } public boolean isHasDepartment() { return hasDepartment; } public void setHasDepartment(boolean hasDepartment) { this.hasDepartment = hasDepartment; } public String getTreeurl() { return treeurl; } public void setTreeurl(String treeurl) { this.treeurl = treeurl; } }
[ "416314413@163.com" ]
416314413@163.com
6cfed460329ec61f11b50dbe779c14fe76eadcad
d0dd3d47cc3e9a13cfb0ca725feda76a83ff6a43
/CS590SWA_DE/Lab03/greetingService/src/main/java/com/miu/greetingservice/controller/BookController.java
00366ace23bd281a95d9f48270c1a73e27da962b
[]
no_license
jij000/homework
cf014ef278ef33b106029707b221426cd8ca613b
e5af2d5e77795154ea4f278801b51f90abef2b1d
refs/heads/master
2022-12-25T14:58:14.821712
2020-09-27T18:55:42
2020-09-27T18:55:42
191,246,144
0
0
null
2022-12-16T00:36:49
2019-06-10T21:10:53
Java
UTF-8
Java
false
false
1,512
java
package com.miu.greetingservice.controller; import java.util.List; import com.miu.greetingservice.domian.Book; import com.miu.greetingservice.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/book") public class BookController { @Autowired BookService bookService; @RequestMapping("/add") public ResponseEntity<?> addBook(@RequestBody Book book) { bookService.addBook(book); return new ResponseEntity<Book>(HttpStatus.OK); } @RequestMapping("/del/{isbn}") public ResponseEntity<?> delBook(@PathVariable("isbn") String isbn) { bookService.deleteBook(isbn); return new ResponseEntity<Book>(HttpStatus.OK); } @RequestMapping("/get/{isbn}") public ResponseEntity<?> getBook(@PathVariable("isbn") String isbn) { Book book = bookService.getBook(isbn); return new ResponseEntity<Book>(book, HttpStatus.OK); } @RequestMapping("/getall") public ResponseEntity<?> getGreeting() { List<Book> books = bookService.getAllBooks(); return new ResponseEntity<List<Book>>(books, HttpStatus.OK); } }
[ "jij000@gmail.com" ]
jij000@gmail.com
1c4bfee92eb05b6d76473779bfb7bfe5333b40a3
52158596884025222abee1ac7472eeffc019ecdd
/AllianzBlink/src/android/io/mariachi/allianzvision/ui/cvision/GraphicOverlay.java
a1873e19ffd112ca097eac099d4a3fea5882e4e3
[]
no_license
Asalmerontkd/pluginApp
956c41782c09accc94fda90b0f4b805aad28e664
81cb1b4281ed4971bf64b8fb22ce4ee02d81b15a
refs/heads/master
2021-01-22T18:58:40.148720
2017-03-16T02:51:52
2017-03-16T02:51:52
85,145,348
0
0
null
null
null
null
UTF-8
Java
false
false
6,381
java
/* * Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mariachi.allianzvision.ui.cvision; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; import com.google.android.gms.vision.CameraSource; import java.util.HashSet; import java.util.Set; /** * A view which renders a series of custom graphics to be overlayed on top of an associated preview * (i.e., the camera preview). The creator can add graphics objects, update the objects, and remove * them, triggering the appropriate drawing and invalidation within the view.<p> * * Supports scaling and mirroring of the graphics relative the camera's preview properties. The * idea is that detection items are expressed in terms of a preview size, but need to be scaled up * to the full view size, and also mirrored in the case of the front-facing camera.<p> * * Associated {@link Graphic} items should use the following methods to convert to view coordinates * for the graphics that are drawn: * <ol> * <li>{@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of the * supplied value from the preview scale to the view scale.</li> * <li>{@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the coordinate * from the preview's coordinate system to the view coordinate system.</li> * </ol> */ public class GraphicOverlay extends View { private final Object mLock = new Object(); private int mPreviewWidth; private float mWidthScaleFactor = 1.0f; private int mPreviewHeight; private float mHeightScaleFactor = 1.0f; private int mFacing = CameraSource.CAMERA_FACING_BACK; private Set<Graphic> mGraphics = new HashSet(); /** * Base class for a custom graphics object to be rendered within the graphic overlay. Subclass * this and implement the {@link Graphic#draw(Canvas)} method to define the * graphics element. Add instances to the overlay using {@link GraphicOverlay#add(Graphic)}. */ public static abstract class Graphic { private GraphicOverlay mOverlay; public Graphic(GraphicOverlay overlay) { mOverlay = overlay; } /** * Draw the graphic on the supplied canvas. Drawing should use the following methods to * convert to view coordinates for the graphics that are drawn: * <ol> * <li>{@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of * the supplied value from the preview scale to the view scale.</li> * <li>{@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the * coordinate from the preview's coordinate system to the view coordinate system.</li> * </ol> * * @param canvas drawing canvas */ public abstract void draw(Canvas canvas); /** * Adjusts a horizontal value of the supplied value from the preview scale to the view * scale. */ public float scaleX(float horizontal) { return horizontal * mOverlay.mWidthScaleFactor; } /** * Adjusts a vertical value of the supplied value from the preview scale to the view scale. */ public float scaleY(float vertical) { return vertical * mOverlay.mHeightScaleFactor; } /** * Adjusts the x coordinate from the preview's coordinate system to the view coordinate * system. */ public float translateX(float x) { if (mOverlay.mFacing == CameraSource.CAMERA_FACING_FRONT) { return mOverlay.getWidth() - scaleX(x); } else { return scaleX(x); } } /** * Adjusts the y coordinate from the preview's coordinate system to the view coordinate * system. */ public float translateY(float y) { return scaleY(y); } public void postInvalidate() { mOverlay.postInvalidate(); } } public GraphicOverlay(Context context, AttributeSet attrs) { super(context, attrs); } /** * Removes all graphics from the overlay. */ public void clear() { synchronized (mLock) { mGraphics.clear(); } postInvalidate(); } /** * Adds a graphic to the overlay. */ public void add(Graphic graphic) { synchronized (mLock) { mGraphics.add(graphic); } postInvalidate(); } /** * Removes a graphic from the overlay. */ public void remove(Graphic graphic) { synchronized (mLock) { mGraphics.remove(graphic); } postInvalidate(); } /** * Sets the camera attributes for size and facing direction, which informs how to transform * image coordinates later. */ public void setCameraInfo(int previewWidth, int previewHeight, int facing) { synchronized (mLock) { mPreviewWidth = previewWidth; mPreviewHeight = previewHeight; mFacing = facing; } postInvalidate(); } /** * Draws the overlay with its associated graphic objects. */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); synchronized (mLock) { if ((mPreviewWidth != 0) && (mPreviewHeight != 0)) { mWidthScaleFactor = (float) canvas.getWidth() / (float) mPreviewWidth; mHeightScaleFactor = (float) canvas.getHeight() / (float) mPreviewHeight; } for (Graphic graphic : mGraphics) { graphic.draw(canvas); } } } }
[ "psrantonio@gmail.com" ]
psrantonio@gmail.com
9451db24aacc8dbd44864353b638b64d3e75898f
83d9c7a3a4bcb1c44ca3249a447f72081d2bd27a
/crypto_eddies/Wallet.java
13293ba73ab01c14b0aa305c767fd8e394f3729d
[ "CC0-1.0" ]
permissive
Tasspazlad/Blockchain_eddies_Java
3d05d5e69a4af41fb508397fe7ea7e362a7a7594
c5b214b90377716e776fe5d895a9601de8ea594c
refs/heads/main
2023-07-03T13:53:25.754511
2021-08-09T10:41:55
2021-08-09T10:41:55
391,950,282
0
0
null
null
null
null
UTF-8
Java
false
false
2,737
java
package crypto_eddies; import java.security.*; import java.security.spec.ECGenParameterSpec; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Wallet { public PrivateKey privateKey; public PublicKey publicKey; public HashMap<String, TransactionOutput> UTXOs = new HashMap<String, TransactionOutput>(); //only UTXOs owned by this wallet. public Wallet(){ generateKeyPair(); } public void generateKeyPair() { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA","BC"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); ECGenParameterSpec ecSpec = new ECGenParameterSpec("prime192v1"); // Initialize the key generator and generate a keyPair keyGen.initialize(ecSpec, random); //256 bytes provides an acceptable security level KeyPair keyPair = keyGen.generateKeyPair(); // set the public and private keys from the keyPair privateKey = keyPair.getPrivate(); publicKey = keyPair.getPublic(); }catch(Exception e) { throw new RuntimeException(); } } //returns balance and stores the UTXO's owned by this wallet in this.UTXOs public float getBalance() { float total = 0; for (Map.Entry<String, TransactionOutput> item: crypto_eddies.UTXOs.entrySet()){ TransactionOutput UTXO = item.getValue(); if(UTXO.isMine(publicKey)) { //if output belongs to me ( if coins belong to me ) UTXOs.put(UTXO.id, UTXO); //add it to our list of unspent transactions. total += UTXO.value ; } } return total; } //Generates and return a new transaction from this wallet. public Transaction sendFunds(PublicKey _recipient,float value ) { if(getBalance() < value) { //gather balance and check funds. System.out.println("#Not Enough funds to send transaction. Transaction Discarded."); return null; } //create array list of inputs ArrayList<TransactionInput> inputs = new ArrayList<TransactionInput>(); float total = 0; for (Map.Entry<String, TransactionOutput> item: UTXOs.entrySet()){ TransactionOutput UTXO = item.getValue(); total += UTXO.value; inputs.add(new TransactionInput(UTXO.id)); if(total > value) break; } Transaction newTransaction = new Transaction(publicKey, _recipient, value, inputs); newTransaction.generateSignature(privateKey); for(TransactionInput input: inputs){ UTXOs.remove(input.transactionOutputId); } return newTransaction; } }
[ "harley.taskis@gmail.com" ]
harley.taskis@gmail.com
c3ec19d382e5217896a55886e9346a9a7ea65557
400a634eb221939d44530d90482f99c1591ada16
/app/src/main/java/com/example/iventorypurilupin/response/response_kacang/response_flake/BarangFlakeItem.java
3080b0e568e64f2bf36126a2d7f01f470235318e
[]
no_license
maling17/IventoryPuriLupin
809744064bea19a7ab26c2b9193acfee162c1783
b4c529de3570f407d306997e16833c4777f6c564
refs/heads/master
2020-05-26T21:44:16.206317
2020-04-14T05:49:22
2020-04-14T05:49:22
188,384,369
0
0
null
null
null
null
UTF-8
Java
false
false
533
java
package com.example.iventorypurilupin.response.response_kacang.response_flake; import com.google.gson.annotations.SerializedName; public class BarangFlakeItem { @SerializedName("stok") private String stok; public String getStok() { return stok; } public void setStok(String stok) { this.stok = stok; } @Override public String toString() { return "BarangFlakeItem{" + "stok = '" + stok + '\'' + "}"; } }
[ "kresnaa09@yahoo.com" ]
kresnaa09@yahoo.com
e98c4d276cf1e5aef0f3d8177582a6fe6d7550ab
162962cf53aa59cd34bdd46fa81cf983556eba6f
/javarepo/common/src/main/java/xdb/summary/common/httputils/HttpUtils.java
950ad521532512e5991f3c7296a1fb8dadf42808
[ "MIT" ]
permissive
xubaodian/summary
8f546d13fa7b0905f3b71026790ddcf3dbaa0d6b
8c96622f423ed01674ffc6019b6a8afa3d17dc76
refs/heads/master
2022-12-17T02:32:04.635395
2020-09-21T14:07:33
2020-09-21T14:07:33
296,628,457
0
0
null
null
null
null
UTF-8
Java
false
false
2,087
java
package xdb.summary.common.httputils; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.charset.Charset; import java.util.Map; public class HttpUtils { private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class); // get ่ฏทๆฑ‚ๆ–นๆณ• public static String get(String url, Map<String, String> headers, int timeout) { CloseableHttpClient httpclient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(timeout) .setConnectTimeout(timeout) .setSocketTimeout(timeout) .build(); HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpGet.addHeader(entry.getKey(), entry.getValue()); } } try { CloseableHttpResponse response = httpclient.execute(httpGet); StringBuffer sb = new StringBuffer(); int code = response.getStatusLine().getStatusCode(); if (code < 200 || code >= 400) { logger.error("remote query failed, response code: " + code); return sb.toString(); } HttpEntity httpEntity = response.getEntity(); return EntityUtils.toString(httpEntity, Charset.forName("UTF-8")); } catch (Exception ex) { logger.error("get remote query failed๏ผŒurl is๏ผš " + url); logger.error("errorStackTrace:", ex.getCause()); return null; } } }
[ "472784995@qq.com" ]
472784995@qq.com
237942d478fff02297dadb834419e70e4c4ddb8f
4fac934b1e78cc8f03d5e55509bfa11ef6c4ab6d
/springboot-redis/src/main/java/com/orange/RedisUtil.java
e46b8eba9c3d05547cf3155f66df94e3e3c7e316
[]
no_license
hunger-c/springboot-everything
ce3eadc3cf2df103c53b233cb34b34672e6df978
df717eefaa5733fa7f64d62ec16b88442c36a14f
refs/heads/master
2020-05-04T10:27:16.751260
2019-04-03T05:47:23
2019-04-03T05:47:23
179,087,760
0
0
null
null
null
null
UTF-8
Java
false
false
995
java
package com.orange; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Repository; import org.springframework.util.StringUtils; import java.util.concurrent.TimeUnit; /** * Created by Z.C.Hemon on 2019/4/2 16:11. */ @Repository public class RedisUtil { @Autowired private RedisTemplate<String,String> redisTemplate; public void add(String key, Long time, Object object){ redisTemplate.opsForValue().set(key,JSON.toJSONString(object),time,TimeUnit.MINUTES); } public Object get(String key){ String result=redisTemplate.opsForValue().get(key); if(!StringUtils.isEmpty(result)){ return JSON.parse(result); } return null; } public void delete(String key){ redisTemplate.opsForValue().getOperations().delete(key); } }
[ "hemon@foxmail.com" ]
hemon@foxmail.com
d1e0e07d32641e9aa287b9e0cb0f9312483fb5ca
4e5aaca603bdfa14c9ce5b54791cd6da13c4138d
/Guia03_POO2_FernandoSantos/src/main/java/com/sv/udb/controlador/TipoGafeCtrl.java
aaea211006881191b3089dc7021814e4d92fd753
[]
no_license
Fernando97Santos/Guia03_POO2_FernandoSantos
a1ea2091edded10c91e0df5646cac844d249853e
7b1cc1c11c26030b2db9212fca116460af595f66
refs/heads/master
2020-09-22T00:59:29.044592
2016-08-25T23:07:27
2016-08-25T23:07:27
65,947,518
0
0
null
null
null
null
UTF-8
Java
false
false
3,382
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sv.udb.controlador; import com.sv.udb.modelo.TipoGafe; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.TypedQuery; /** * * @author ferna */ public class TipoGafeCtrl { public boolean guar(TipoGafe obje) { boolean resp = false; EntityManagerFactory emf = Persistence.createEntityManagerFactory("PooPoolPU"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(obje); tx.commit(); resp = true; } catch(Exception ex) { tx.rollback(); } em.close(); emf.close(); return resp; } public boolean modi(TipoGafe obje) { boolean resp = false; EntityManagerFactory emf = Persistence.createEntityManagerFactory("PooPoolPU"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.merge(obje); tx.commit(); resp = true; } catch(Exception ex) { tx.rollback(); } em.close(); emf.close(); return resp; } public boolean elim(Long empId) { boolean resp = false; EntityManagerFactory emf = Persistence.createEntityManagerFactory("PooPoolPU"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); TipoGafe respo = null; try{ respo = em.find(TipoGafe.class, empId); if(respo != null) { em.remove(respo); tx.commit(); resp = true; } }catch(Exception e){ tx.rollback(); } em.close(); emf.close(); return resp; } public List<TipoGafe> ConsTodo() { List<TipoGafe> resp = new ArrayList<>(); EntityManagerFactory emf = Persistence.createEntityManagerFactory("PooPoolPU"); EntityManager em = emf.createEntityManager(); try { TypedQuery<TipoGafe> query =em.createNamedQuery("TipoGafe.findAll", TipoGafe.class); resp = query.getResultList(); } catch(Exception ex) { } return resp; } public TipoGafe get(Long empId){ EntityManagerFactory emf = Persistence.createEntityManagerFactory("PooPoolPU"); EntityManager em = emf.createEntityManager(); TipoGafe resp = null; try{ resp = em.find(TipoGafe.class, empId); }catch(Exception e){ e.printStackTrace(); } return resp; } }
[ "fernando.97_santos@outlook.com" ]
fernando.97_santos@outlook.com
859b9d89a38c0379cc01268f9b72779d05a91032
45a381de4d2eb499368918485a7e596cd1588325
/len-sys/src/main/java/com/len/service/RoleMenuService.java
0a5bfb8df060e97e2ebe8da1c4dcf33fb4058c47
[ "Apache-2.0" ]
permissive
Yzhao1125/lenosp
008f9838c1d75d4a1bdde7168a8056b8ee374ba8
22441b1f58bdc3256ebac43293010ae6d09888d9
refs/heads/master
2022-10-25T15:43:53.564317
2020-01-07T07:26:21
2020-01-07T07:26:21
191,136,318
1
2
Apache-2.0
2022-10-12T20:27:48
2019-06-10T09:20:38
TSQL
UTF-8
Java
false
false
453
java
package com.len.service; import com.len.base.BaseService; import com.len.entity.SysRoleMenu; import java.util.List; /** * @author zhuxiaomeng * @date 2017/12/28. * @email 154040976@qq.com */ public interface RoleMenuService extends BaseService<SysRoleMenu,String>{ List<SysRoleMenu> selectByCondition(SysRoleMenu sysRoleMenu); int selectCountByCondition(SysRoleMenu sysRoleMenu); int deleteByPrimaryKey(SysRoleMenu sysRoleMenu); }
[ "wing_zyy@163.com" ]
wing_zyy@163.com
9b0eb7a168943b7e3df1e9c94168dcfb2fd276d0
4f12c52540a2518090953f2d67673cb45bb5a9a3
/src/main/java/com/hg/seckill/redis/RedisPoolFactory.java
368b05070672da3baf61fef01e77becbe8e4b009
[]
no_license
WaterRRabbit/seckill
ab0b0da8fe8d272cb9c739363c30fc9c006e326c
d6579e78fdd48d809a654dd3b073b13902f93355
refs/heads/master
2020-05-15T18:14:58.292289
2019-04-28T23:57:42
2019-04-28T23:57:42
182,421,988
1
0
null
null
null
null
UTF-8
Java
false
false
889
java
package com.hg.seckill.redis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * Created by YE * 2019-04-17 23:33 */ @Configuration public class RedisPoolFactory { @Autowired private RedisConfig redisConfig; @Bean public JedisPool jedisPool(){ JedisPoolConfig config = new JedisPoolConfig(); config.setMaxIdle(redisConfig.getPoolMaxIdle()); config.setMaxTotal(redisConfig.getPoolMaxTotal()); config.setMaxWaitMillis(redisConfig.getPoolMaxWait()); JedisPool pool = new JedisPool(config, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getTimeout(), null, 0); return pool; } }
[ "1264118202@qq.com" ]
1264118202@qq.com
4223de8c65ee870f07a177549d9b2797df63848d
e5c9e0ba90a70ca3df8a222b9e48444abdfbe330
/src/chap11/clone/MemberExam.java
6d0ce89e4c2e9f14da5fbeafd124c6f4efec8e2d
[]
no_license
hellojohnwoo/this-is-java-2019
2d73b2e4da8757240f22c2b2399ccd3d4541fa80
5c231c5525569564ba0cd24fd919da898eeedb52
refs/heads/master
2021-08-07T17:37:18.380180
2020-05-17T09:22:23
2020-05-17T09:22:23
178,857,653
0
0
null
null
null
null
UTF-8
Java
false
false
956
java
package chap11.clone; /* public class MemberExam { public static void main(String[] args) { Member original = new Member("blue","Hong","12345",25,true); Member cloned = original.getMember(); cloned.password = "67890"; System.out.println("[๋ณต์ œ ๊ฐ์ฒด์˜ ํ•„๋“œ๊ฐ’]"); System.out.println("id :" + cloned.id); System.out.println("name : " + cloned.name); System.out.println("password : " + cloned.password); System.out.println("age : " + cloned.age); System.out.println("adult : " + cloned.adult); System.out.println(); System.out.println("[์›๋ณธ ๊ฐ์ฒด์˜ ํ•„๋“œ๊ฐ’]"); System.out.println("id :" + original.id); System.out.println("name : " + original.name); System.out.println("password : " + original.password); System.out.println("age : " + original.age); System.out.println("adult : " + original.adult); } } */
[ "hellojohnwoo@gmail.com" ]
hellojohnwoo@gmail.com
4356bbe602d5cc91cb4ce241b976e597f68faef2
ff08f8574a2c91301e0331d99b563502b09371c0
/src/main/resources/metrics/app/guice/MetricsModule.java
55da17ac93c060ee53fba29c6d3f1aecdacc6c4e
[]
no_license
tuantla/play1-metrics
68622ab32a5acb6a47fa61d8fb63b284ebee57ce
8ebf15af5de4adcf78deb387ce20f3af3902bbb3
refs/heads/master
2020-04-05T10:35:59.451705
2018-11-09T03:48:08
2018-11-09T03:56:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
409
java
package guice; import com.google.inject.AbstractModule; import io.prometheus.client.CollectorRegistry; /** * * @author tuan.vu */ public class MetricsModule extends AbstractModule { public void configure() { System.out.println("MetricsModule loaded"); CollectorRegistry registry = CollectorRegistry.defaultRegistry; bind(CollectorRegistry.class).toInstance(registry); } }
[ "robin.github@gmail.com" ]
robin.github@gmail.com
4e0f1000d677a6063791592910860b1677db1036
5da4a85d8e2adf284b3c0daddb6bbe0dd5058db1
/app/src/main/java/com/bignerdranch/android/sovt_app/FragmentActivity.java
0f67a8c06397c857bde218b731b689e2f833227e
[]
no_license
cbratkovics/SOVT_App
e404023f325d952cf51bd04e28037b629207f77c
39ae317ec5ff64fe88a34e9e697a603e5b82c71c
refs/heads/master
2020-03-31T21:51:40.710813
2018-12-05T00:08:57
2018-12-05T00:08:57
152,596,402
0
0
null
null
null
null
UTF-8
Java
false
false
2,526
java
package com.bignerdranch.android.sovt_app; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; //generic superclass creates a fragment //subclasses implement createFragment() to return an instance of //the fragment that the activity is hosting public abstract class FragmentActivity extends AppCompatActivity { private static final String TAG = "FragmentActivity"; protected abstract Fragment createFragment(); @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); Log.i(TAG, "onSaveInstanceState"); } @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate() called"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_fragment); Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar); setSupportActionBar(myToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("SOVT"); //get fragment manager to handle fragments FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_container); //if no fragment, create one & connect it if(fragment == null) { fragment = createFragment(); fm.beginTransaction().add(R.id.fragment_container, fragment).commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.toolbar_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: // User chose the "Settings" item, show the app settings UI... return true; case R.id.go_home: Intent intent = new Intent(FragmentActivity.this, MainMenu.class); startActivity(intent); return true; default: // If we got here, the user's action was not recognized. // Invoke the superclass to handle it. return super.onOptionsItemSelected(item); } } }
[ "ncastle@uvm.edu" ]
ncastle@uvm.edu
915350411f32377b65983a7c16bcc6c765ba8c7c
600bdc179c55006528ba9732a5ee8e467df4756d
/UcViewPager/src/main/java/com/zhejunzhu/ucviewpager/viewobserver/StreamViewChangedObservable.java
c5107d8f3cf625e26726668116fd22a2a4fe1758
[]
no_license
AHuier/UCViewPager
8a5450967412d487e1927b0b374185e44a8ff442
32c6a174b600dbd52cdfff9553687ef58bcb61b3
refs/heads/master
2020-04-08T02:07:02.021051
2016-06-28T02:27:37
2016-06-28T02:27:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
876
java
package com.zhejunzhu.ucviewpager.viewobserver; import com.zhejunzhu.ucviewpager.MainTitleViewContainer; import com.zhejunzhu.ucviewpager.utils.LLog; public class StreamViewChangedObservable extends BaseViewChangedObservable<ProcessViewChangedObserver> { private float mLastProcess; public void onViewScrolled(float distance) { float process = distance / MainTitleViewContainer.sTitleLayoutHeight; if (process > 1f) { process = 1f; } setAnimProcess(process); } public float getLastProcess() { return mLastProcess; } public void setAnimProcess(float process) { LLog.e("StreamViewChangedObservable setAnimProcess : " + process); for (ProcessViewChangedObserver mObserver : mObservers) { mObserver.onProcess(process); } mLastProcess = process; } }
[ "zhuzhejun@gionee.com" ]
zhuzhejun@gionee.com
946d2c3ec789af6d51bb0b9dfa7d8e0712ee2ce6
01a712c7c664def06be0e41d3bf731f0d8a4c928
/demo_03/src/main/java/com/example/demo_03/view/fragment/Fu_AFragment.java
2094624d695e7db735ec496b8be57cabc38a0326
[]
no_license
pfnlovejiafan/day04__groutp9
4f735833fec61d381110c310165821f977a8a9c0
e2acc6b7c0e8dead2f54f7d9c9861a190361deb1
refs/heads/main
2023-02-01T23:22:35.829352
2020-12-18T23:43:20
2020-12-18T23:43:20
322,569,574
0
0
null
null
null
null
UTF-8
Java
false
false
3,071
java
package com.example.demo_03.view.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.demo_03.R; import com.example.demo_03.bean.DataaBean; import com.example.demo_03.model.Apiservice; import java.util.ArrayList; import java.util.List; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * A simple {@link Fragment} subclass. */ public class Fu_AFragment extends Fragment { private RecyclerView mRv; private ArrayList<DataaBean.DataBean.ListBean> list; private RvRvAdapter rvRvAdapter; private int nb; public Fu_AFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View inflate = inflater.inflate(R.layout.fragment_fu__a, container, false); initView(inflate); return inflate; } private void initView(@NonNull final View itemView) { mRv = (RecyclerView) itemView.findViewById(R.id.rv); mRv.setLayoutManager(new LinearLayoutManager(getContext())); list = new ArrayList<>(); Bundle arguments = getArguments(); nb = arguments.getInt("nb"); rvRvAdapter = new RvRvAdapter(getContext(),list); mRv.setAdapter(rvRvAdapter); initData(); } private void initData() { new Retrofit.Builder() .baseUrl(Apiservice.a) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(Apiservice.class) .getData(nb) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<DataaBean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(DataaBean value) { List<DataaBean.DataBean.ListBean> list = value.getData().getList(); list.addAll(list); rvRvAdapter.notifyDataSetChanged(); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } }
[ "32460896231@qq.com" ]
32460896231@qq.com
7328a52dafa6783e27101595f98686d11b884384
6e24160f47ccb28897cb187f9e665833f1ef9aab
/src/main/java/com/xiaoqu/weixin/models/EmployeeLog.java
ed4c0f7b392677c0d4b0261980fd1011a9220a44
[]
no_license
littlefox34/weixin
57522aaefad9330726746e9ad17e04895f266c13
71cc032a5be12c6d5c7d00bb56f690ac9b8b2948
refs/heads/master
2022-06-25T19:23:12.843857
2019-09-05T10:55:44
2019-09-05T10:55:44
206,541,710
0
0
null
2022-06-17T02:25:52
2019-09-05T10:55:28
Java
UTF-8
Java
false
false
3,628
java
package com.xiaoqu.weixin.models; import java.util.Date; public class EmployeeLog { private Integer id; private String empno; private String empname; private String actionlog; private String os; private String browse; private String ip; private Date updatetime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getEmpno() { return empno; } public void setEmpno(String empno) { this.empno = empno == null ? null : empno.trim(); } public String getEmpname() { return empname; } public void setEmpname(String empname) { this.empname = empname == null ? null : empname.trim(); } public String getActionlog() { return actionlog; } public void setActionlog(String actionlog) { this.actionlog = actionlog == null ? null : actionlog.trim(); } public String getOs() { return os; } public void setOs(String os) { this.os = os == null ? null : os.trim(); } public String getBrowse() { return browse; } public void setBrowse(String browse) { this.browse = browse == null ? null : browse.trim(); } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip == null ? null : ip.trim(); } public Date getUpdatetime() { return updatetime; } public void setUpdatetime(Date updatetime) { this.updatetime = updatetime; } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } EmployeeLog other = (EmployeeLog) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getEmpno() == null ? other.getEmpno() == null : this.getEmpno().equals(other.getEmpno())) && (this.getEmpname() == null ? other.getEmpname() == null : this.getEmpname().equals(other.getEmpname())) && (this.getActionlog() == null ? other.getActionlog() == null : this.getActionlog().equals(other.getActionlog())) && (this.getOs() == null ? other.getOs() == null : this.getOs().equals(other.getOs())) && (this.getBrowse() == null ? other.getBrowse() == null : this.getBrowse().equals(other.getBrowse())) && (this.getIp() == null ? other.getIp() == null : this.getIp().equals(other.getIp())) && (this.getUpdatetime() == null ? other.getUpdatetime() == null : this.getUpdatetime().equals(other.getUpdatetime())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getEmpno() == null) ? 0 : getEmpno().hashCode()); result = prime * result + ((getEmpname() == null) ? 0 : getEmpname().hashCode()); result = prime * result + ((getActionlog() == null) ? 0 : getActionlog().hashCode()); result = prime * result + ((getOs() == null) ? 0 : getOs().hashCode()); result = prime * result + ((getBrowse() == null) ? 0 : getBrowse().hashCode()); result = prime * result + ((getIp() == null) ? 0 : getIp().hashCode()); result = prime * result + ((getUpdatetime() == null) ? 0 : getUpdatetime().hashCode()); return result; } }
[ "seed34@163.com" ]
seed34@163.com
2b21495b1e726aa1637785bdbb376147a0dfe036
ba44fb6ccf468b2cd9c3b91964afa39de50140e9
/src/main/java/com/locol/auth/AuthenticatedUser.java
153caba250b231c5f84e50dc0aa557c3a87fbfd7
[]
no_license
dev705370/locol
4758de94d9b269d99215bf7cf85d1658196dbb9b
67d61da25d8bc45d76c4a61197d85169bbc966b9
refs/heads/master
2021-01-23T12:34:32.638524
2017-06-06T14:31:10
2017-06-06T14:31:10
93,175,667
0
0
null
null
null
null
UTF-8
Java
false
false
489
java
package com.locol.auth; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.inject.Qualifier; @Qualifier @Retention(RUNTIME) @Target({ METHOD, FIELD, PARAMETER }) public @interface AuthenticatedUser { }
[ "dev705370@gmail.com" ]
dev705370@gmail.com
c7fcf074fa45c36df0c96a77afb87ce90a4bb9ae
391546ae434d2fd60d78cf97d6e254109580063d
/app/src/main/java/com/example/testingjava/AFragment.java
ac51b3a63501ed977a108d182b0923f55c1dbee5
[]
no_license
SanketPatelHere/TestingJava
265744b289d163d3f9b5da59d14199cd31a501cb
5d49c74599877c385389d165afa80d594412c71d
refs/heads/master
2020-09-06T10:07:28.148656
2019-11-08T05:43:55
2019-11-08T05:43:55
220,395,095
0
0
null
null
null
null
UTF-8
Java
false
false
117
java
package com.example.testingjava; import androidx.fragment.app.Fragment; public class AFragment extends Fragment { }
[ "anilelluminati@gmail.com" ]
anilelluminati@gmail.com
00014dd9edcdb893b16c62048d1c93dd3e6de009
e91825e254281417ebc4e8d5e1dfe7052894e5e0
/src/main/java/com/example/finalproj/repository/RoleRepository.java
b5f850df3335fbad958ed110f4fc03da3c5dc8ab
[]
no_license
Studentfr/finalAjp2
1534cd99ccf93c1c25c762c3ded2e0161835a027
3c9809b4d9799e6d77918e57f9be0b3d7040d81b
refs/heads/main
2023-03-18T20:31:33.225765
2021-03-11T02:44:17
2021-03-11T02:44:17
343,819,696
0
0
null
2021-03-11T02:44:18
2021-03-02T15:25:10
Java
UTF-8
Java
false
false
288
java
package com.example.finalproj.repository; import com.example.finalproj.repository.dto.Role; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface RoleRepository extends JpaRepository<Role, Long> { }
[ "sektor.miras@gmail.com" ]
sektor.miras@gmail.com
b3aecbd99f1c8afe63f9ee10a80598cbb1f43335
c646f5766e70a3eaff49e47a8e4d2392941ca7d5
/app/src/main/java/base/zjl/com/baselibrary/login/bean/ClassEntity.java
56d0d078f58206d902f8cfc04e38029f581358fe
[]
no_license
zhangjilei106787/BaseLibrary
5700860a604459f68ec1d155d739b99237dfc3c1
7291bc9c44f4dd504cf0353c4d4d396bd4c32c99
refs/heads/master
2023-04-12T22:47:34.097202
2023-04-07T05:41:23
2023-04-07T05:41:23
143,843,945
1
0
null
null
null
null
UTF-8
Java
false
false
213
java
package base.zjl.com.baselibrary.login.bean; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "ClassEntity") public class ClassEntity { @PrimaryKey private long id; }
[ "zhangjilei2568@163.com" ]
zhangjilei2568@163.com
76bf3cb8ec9e241ffe37d2c73049d278c0bb1d6b
2e9f34e403028120973d2bf794a3a0b61fae91dd
/app/src/main/java/helper/Word.java
43bdf5c24a2e460935585f5c3c1013d40c696cb4
[]
no_license
enigmaharjan/Dictionarysqllite
7263f3d8557bf565dea9bd1fc35b642d39a883ab
12279d220966ed488584997c28888078100162c5
refs/heads/master
2020-05-18T22:26:54.858454
2019-05-05T04:55:50
2019-05-05T04:55:50
184,691,404
0
0
null
null
null
null
UTF-8
Java
false
false
713
java
package helper; import java.io.PrintStream; public class Word { private int wordId; private String word; private String meaning; public Word(int wordId, String word, String meaning) { this.wordId = wordId; this.word = word; this.meaning = meaning; } public int getWordId() { return wordId; } public void setWordId(int wordId) { this.wordId = wordId; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public String getMeaning() { return meaning; } public void setMeaning(String meaning) { this.meaning = meaning; } }
[ "softwarica@softwarica.com" ]
softwarica@softwarica.com
8218532e04a6756b96d9e182d03cf66cc61af2e7
b826f766d929ceec1b99c34f9e4e6634bd8a4385
/src/main/java/com/cevaris/ag4j/IgnoreUtils.java
401c4716b7c49ae3e940ab334deb989d350a5a24
[]
no_license
cevaris/ag4j
e2d4e4e671facdbf605fd239502463d46cb77d89
ee14ee06e7a624b7d5194777c5701ec7dda417a8
refs/heads/master
2020-03-21T06:49:06.547214
2018-07-08T14:46:54
2018-07-08T14:46:54
138,243,789
0
0
null
null
null
null
UTF-8
Java
false
false
1,281
java
package com.cevaris.ag4j; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.nio.file.Path; import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.Set; public class IgnoreUtils { public Set<String> notIgnoredFiles(File[] files) { FileWalker walker = new FileWalker(); // for each folder // check if this folder is ignored // if we find a ignore file, parse save ignore patterns including parents // add git global ignore patterns to ignore patterns return new HashSet<>(); } public static Set<String> parsePath(Path path) { Set<String> patterns = new HashSet<>(); Scanner scanner = null; try { scanner = new Scanner(new FileReader(path.toFile())); String line; while ((line = scanner.nextLine()) != null) { String candidate = line.trim(); // ignore commented lines if (!candidate.startsWith("#")) { patterns.add(candidate); } } } catch (FileNotFoundException | NoSuchElementException e) { // empty or non-existing file } return patterns; } public static boolean shouldIgnore(Set<String> ignores, Path path) { return false; } }
[ "cevaris@gmail.com" ]
cevaris@gmail.com
3f94e91d0edd879e34d5d0ac4ab111ae1878830e
08ea498cfe34bd69681391aa80fafc829307d64d
/quiz-service/quiz-service-app/src/main/java/app/domain/questions/QuizEntity.java
6c2030eff0d69026e8ded2974992fb2acf94870f
[ "MIT" ]
permissive
achimtimis/L-Project
264fa5458a962de3b2d93144bf1215846b86c7af
46e1cdb8c0fffb6d88c1d94ad7309be694d740d3
refs/heads/master
2021-03-27T19:23:57.051474
2018-05-13T10:28:55
2018-05-13T10:28:55
89,916,152
0
0
null
null
null
null
UTF-8
Java
false
false
1,103
java
package app.domain.questions; import lombok.Data; import lombok.NoArgsConstructor; import models.utils.QuizTypeEnum; import models.utils.TopicEnum; import org.hibernate.annotations.*; import javax.persistence.*; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Table; import java.util.ArrayList; import java.util.List; /** * Created by achy_ on 6/7/2017. */ @Entity @Table(name = "quiz_entity") @Data @NoArgsConstructor public class QuizEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "quiz_id") private Long id; @OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY) @Cascade(org.hibernate.annotations.CascadeType.ALL) @JoinColumn(name = "quiz_question_id") private List<QuestionEntity> quiz_questions = new ArrayList<>(); private TopicEnum topic; private QuizTypeEnum quizType; private int timer; private double minimumScoreToPass; private double totalScore; private String creatorId; private boolean isTimed; private String name; }
[ "achytimis@gmail.com" ]
achytimis@gmail.com
ac661970bb93de3bf4d12e9be4577ce3f39b6ec8
9057337a1d5cf4163b8b054abd303a55771dd36d
/src/main/java/edu/wctc/calculatorlabs/controller/Lab3Controller.java
5b42a7c3f4450ba0c73e81c55705a8482e2fc9ca
[]
no_license
asmith86/CalculatorLabs
e93d73858aa3c6b3c02ce2ca977fc3d31df32f30
1b1e108381a1eb66c5b58558909680df799f6dff
refs/heads/master
2021-06-26T20:56:37.203139
2017-09-14T03:09:19
2017-09-14T03:09:19
103,338,202
0
0
null
null
null
null
UTF-8
Java
false
false
4,002
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 edu.wctc.calculatorlabs.controller; import edu.wctc.calculatorlabs.model.ShapeCalculatorService; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author alexsmith */ @WebServlet(name = "Lab3Controller", urlPatterns = {"/lab3"}) public class Lab3Controller extends HttpServlet { private static final String CALC_MODE = "calcMode"; private static final String TARGET_PAGE = "/lab3.jsp"; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String calcMode = request.getParameter(CALC_MODE); String answer = ""; try { ShapeCalculatorService scs = new ShapeCalculatorService(); if (calcMode.equals("rectangle")) { String length = request.getParameter("rectLength"); String width = request.getParameter("rectWidth"); answer = scs.calculateAreaOfRectangle(width, length); request.setAttribute("rectArea", answer); } else if (calcMode.equals("circle")) { String radius = request.getParameter("radius"); answer = scs.calculateAreaOfCircle(radius); request.setAttribute("circArea", answer); } else if (calcMode.equals("triangle")) { String height = request.getParameter("triHeight"); String width = request.getParameter("triWidth"); answer = scs.getHypotenuseOfTriangle(width, height); request.setAttribute("hypotenuse", answer); } } catch (Exception e) { request.setAttribute("errmsg", e.getMessage()); } RequestDispatcher view = request.getRequestDispatcher(TARGET_PAGE); view.forward(request, response); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
[ "alexsmith@10.30.22.172" ]
alexsmith@10.30.22.172
a05e03a4ab5dc20aa55734751de4b6f5c7b79e20
7399e3ce4fd07774c80a5a33486b06c88ba4af1b
/ges_sol_construccion/src/main/java/com/personalsoft/ges_sol_construccion/persistencia/entidades/Material.java
1a565d711c0674e2008435140806b92cd8fceb91
[]
no_license
rosaguvi/EscenarioSura
edb29b9b7beefcb4489fb4264b338d00bebc35d9
c35beb3788b9d191129c94ae6006f89f5bc67e69
refs/heads/master
2023-05-09T04:49:12.506826
2021-05-24T13:30:08
2021-05-24T13:30:08
370,361,678
0
0
null
null
null
null
UTF-8
Java
false
false
1,462
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.personalsoft.ges_sol_construccion.persistencia.entidades; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; /** * entidad que representa la tabla que guardara la informacion de los materiales a usar en la construccion * @author roagudelo */ @Entity @Table(name = "materiales") public class Material extends EntityBase implements Serializable{ @Column(name = "cod_material") private String codMaterial ; @Column(name = "nom_material") private String nomMaterial ; @Column(name = "cnt_material") private int cntMaterial ; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCodMaterial() { return codMaterial; } public void setCodMaterial(String codMaterial) { this.codMaterial = codMaterial; } public String getNomMaterial() { return nomMaterial; } public void setNomMaterial(String nomMaterial) { this.nomMaterial = nomMaterial; } public int getCntMaterial() { return cntMaterial; } public void setCntMaterial(int cntMaterial) { this.cntMaterial = cntMaterial; } }
[ "roagudelo@personalsoft.com.co" ]
roagudelo@personalsoft.com.co
8e34f3cbdb6934c95dd949ea7399b8d53c5d89bc
78f6bcf8f2771e79c85cf978c4f982f2af8c8f4c
/src/main/java/com/ucsd/globalties/dvs/core/detect/MyopiaDetector.java
383c7f33aedf6b1d7fd3ed46fd38ef248b42dde1
[]
no_license
ucsd-dvs/DVS
c526910fbb826ca64a02072eede7d133895a7bc0
898a6861f540ddb95a0e354d2eb6fd872b057507
refs/heads/master
2020-12-29T02:42:33.934682
2017-03-31T16:39:09
2017-03-31T16:39:09
45,515,308
2
5
null
2015-11-20T21:15:59
2015-11-04T04:30:59
Java
UTF-8
Java
false
false
1,859
java
package com.ucsd.globalties.dvs.core.detect; import com.sun.javafx.binding.StringFormatter; import com.ucsd.globalties.dvs.core.*; import com.ucsd.globalties.dvs.core.model.DiseaseRecord; public class MyopiaDetector implements DiseaseDetector { public void detect(Patient p) { Photo photo = p.getPhotos().get(0); // Use horizontal picture for now. final double MYOPIA_THRESHOLD = -3.25; Crescent_info leftCrescent = photo.getLeftEye().getPupil().getCrescent(); Crescent_info rightCrescent = photo.getRightEye().getPupil().getCrescent(); DiseaseRecord disease = new DiseaseRecord(); disease.setDiseaseName(EyeDisease.MYOPIA); if (leftCrescent.isCrescentIsAtTop() && rightCrescent.isCrescentIsAtTop()) { disease.setStatus("PASS"); } else if (leftCrescent.isCrescentIsAtBot() || rightCrescent.isCrescentIsAtBot()) { disease.setStatus("REFER"); if (leftCrescent.isCrescentIsAtBot()) { double diopter = Pupil.findClosestDiopter(leftCrescent.getCrescentSize()); if (diopter < MYOPIA_THRESHOLD) { disease.setDescription(String.format("Left eye crescent diopter is %.2f when allowed limit is %.2f", diopter, MYOPIA_THRESHOLD)); } } if (rightCrescent.isCrescentIsAtBot()) { double diopter = Pupil.findClosestDiopter(rightCrescent.getCrescentSize()); if (diopter < MYOPIA_THRESHOLD) { disease.setDescription(String.format("Right eye crescent diopter is %.2f when allowed limit is %.2f", diopter, MYOPIA_THRESHOLD)); } } } else { disease.setStatus("REFER"); } p.getDiseaseRecord().add(disease); } }
[ "zarnimng@gmail.com" ]
zarnimng@gmail.com
ff3146d3d2bc98b0881e72263240516078cf53bb
b930d2dc934b10000113c5c9ae3dadcf13345eee
/Internet Banking/build/generated/src/org/apache/jsp/Bankers/AcWithCIF_jsp.java
e43598cdcf23180683e292dac01f21c4b5c6c80a
[]
no_license
suman345/InternetBanking
c5ef2fb1bb8ee15fe512329c78b73d42936b190f
9517b1708bad925ee26702625c78e4892f09bd7b
refs/heads/master
2020-07-25T02:48:12.234766
2020-04-05T14:29:58
2020-04-05T14:29:58
208,139,392
0
0
null
null
null
null
UTF-8
Java
false
false
20,669
java
package org.apache.jsp.Bankers; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class AcWithCIF_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List<String> _jspx_dependants; static { _jspx_dependants = new java.util.ArrayList<String>(2); _jspx_dependants.add("/Bankers/pagefiles/Banker_sidepanel.jsp"); _jspx_dependants.add("/Bankers/pagefiles/Banker_navbar.jsp"); } private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector; public java.util.List<String> getDependants() { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("<!DOCTYPE html>\n"); out.write("<html>\n"); out.write("<head>\n"); out.write(" <meta charset=\"utf-8\">\n"); out.write(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"); out.write(" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"); out.write("\n"); out.write(" <title>Internet Banking</title>\n"); out.write("\n"); out.write(" <!-- Bootstrap CSS CDN -->\n"); out.write(" <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\" integrity=\"sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4\" crossorigin=\"anonymous\">\n"); out.write(" <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css\">\n"); out.write(" <!-- Our Custom CSS -->\n"); out.write(" <link rel=\"stylesheet\" href=\"../Css/Banker_css/BankerHome.css\">\n"); out.write(" <link rel=\"stylesheet\" href=\"../Css/Banker_css/AwithCIF.css\">\n"); out.write(" <!-- Scrollbar Custom CSS -->\n"); out.write(" <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css\">\n"); out.write("\n"); out.write(" <!-- Font Awesome JS -->\n"); out.write(" <script src=\"../Java_Script/Banker_js/AcWithCIF.js\"></script>\n"); out.write(" <script src=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/solid.js\"></script>\n"); out.write(" <script defer src=\"https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js\" integrity=\"sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY\" crossorigin=\"anonymous\"></script>\n"); out.write("</head>\n"); out.write("<body>\n"); out.write(" <div class=\"wrapper\">\n"); out.write(" <!-- Sidebar -->\n"); out.write(" "); out.write("<nav id=\"sidebar\">\n"); out.write(" <div class=\"sidebar-header\">\n"); out.write(" <h3>Banker's Home</h3>\n"); out.write(" </div>\n"); out.write(" <ul class=\"list-unstyled components\">\n"); out.write(" <li class=\"active\">\n"); out.write(" <a href=\"#\">My Profile</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#txnsub\" data-toggle=\"collapse\" aria-expanded=\"false\" class=\"dropdown-toggle\">Consumer Transaction</a>\n"); out.write(" <ul class=\"collapse list-unstyled\" id=\"txnsub\">\n"); out.write(" <li>\n"); out.write(" <a href=\"#acdetails\" data-toggle=\"collapse\" aria-expanded=\"false\" class=\"dropdown-toggle\">Account Deatils</a>\n"); out.write(" <ul class=\"collapse list-unstyled\" id=\"acdetails\">\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">View</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Update</a>\n"); out.write(" </li>\n"); out.write(" </ul>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"Bdeposite.jsp\">Deposite</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"Bwithdrawl.jsp\">Withdrawl</a>\n"); out.write(" </li>\n"); out.write(" </ul>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#capplication\" data-toggle=\"collapse\" aria-expanded=\"false\" class=\"dropdown-toggle\">Consumer Applicaton</a>\n"); out.write(" <ul class=\"collapse list-unstyled\" id=\"capplication\">\n"); out.write(" <li>\n"); out.write(" <a href=\"#nwac\" data-toggle=\"collapse\" aria-expanded=\"false\" class=\"dropdown-toggle\">New Account</a>\n"); out.write(" <ul class=\"collapse list-unstyled\" id=\"nwac\">\n"); out.write(" <li>\n"); out.write(" <a href=\"AcWithCIF.jsp\">Existing User</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"AcForNew_user.jsp\">New User</a>\n"); out.write(" </li>\n"); out.write(" </ul>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Checkbook</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#atm\" data-toggle=\"collapse\" aria-expanded=\"false\" class=\"dropdown-toggle\">Debit Card</a>\n"); out.write(" <ul class=\"collapse list-unstyled\" id=\"atm\">\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Apply For New</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Block</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Generate Pin</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Change Pin</a>\n"); out.write(" </li>\n"); out.write(" </ul>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#credit\" data-toggle=\"collapse\" aria-expanded=\"false\" class=\"dropdown-toggle\">Credit Card</a>\n"); out.write(" <ul class=\"collapse list-unstyled\" id=\"credit\">\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Apply For New</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Block</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Generate Pin</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Change Pin</a>\n"); out.write(" </li>\n"); out.write(" </ul>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#ib\" data-toggle=\"collapse\" aria-expanded=\"false\" class=\"dropdown-toggle\">Internet Banking</a>\n"); out.write(" <ul class=\"collapse list-unstyled\" id=\"ib\">\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Apply as New</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Stop Service</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Password Management</a>\n"); out.write(" </li>\n"); out.write(" </ul>\n"); out.write(" </li>\n"); out.write(" </ul>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Interest Rates</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Services</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Fixed Deposites</a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Loan</a>\n"); out.write(" </li>\n"); out.write(" </ul>\n"); out.write(" <ul class=\"list-unstyled CTAs\">\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">Back to Home</a>\n"); out.write(" </li>\n"); out.write(" </ul>\n"); out.write(" </nav>\n"); out.write("\n"); out.write("\n"); out.write(" <!-- Page Content -->\n"); out.write(" <div id=\"content\">\n"); out.write("\n"); out.write(" "); out.write("\n"); out.write("<nav class=\"navbar navbar-expand-lg navbar-light bg-light\">\n"); out.write(" <div class=\"container-fluid\">\n"); out.write("\n"); out.write(" <button type=\"button\" id=\"sidebarCollapse\" class=\"btn btn-sm btn-sh\">\n"); out.write(" <i class=\"fas fa-align-left\"></i>\n"); out.write(" <span>Shrink me</span>\n"); out.write(" </button>\n"); out.write(" <button class=\"btn btn-dark d-inline-block d-lg-none ml-auto\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n"); out.write(" <i class=\"fas fa-align-justify\"></i>\n"); out.write(" </button>\n"); out.write("\n"); out.write(" <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\">\n"); out.write(" <ul class=\"nav navbar-nav ml-auto\">\n"); out.write(" <li class=\"nav-item active\">\n"); out.write(" <a class=\"nav-link\" href=\"#\"><i class=\"fas fa-envelope-open-text fa-lg\"></i></a>\n"); out.write(" </li>\n"); out.write(" <li class=\"nav-item\">\n"); out.write(" <a class=\"nav-link\" href=\"../Logout.jsp\"><i class=\"fas fa-sign-out-alt fa-lg\"></i></a>\n"); out.write(" </li>\n"); out.write(" </ul>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </nav>"); out.write("\n"); out.write(" \n"); out.write(" <form action=\"#\" style=\"max-width:500px;margin:auto; margin-top: 30px;\" id=\"dform\">\n"); out.write(" <h2 id=\"heading\">CIF Number</h2>\n"); out.write(" <div class=\"input-container\">\n"); out.write(" <input class=\"input-field inp\" type=\"text\" placeholder=\"Enter CIF Number\" id=\"cif\" name=\"cif\">\n"); out.write(" </div>\n"); out.write(" <button type=\"submit\" class=\"btn btn-md\" id=\"DepBtn\" data-target=\"#s\" onclick=\"return cnf_number();\">Find</button>\n"); out.write(" <div class=\"forget_part\"><p id=\"fgttxt\">forgot CIF number?? \n"); out.write(" <button type=\"button\" class=\"btn btn-sm\" data-toggle=\"modal\" data-target=\"#fgt\" id=\"viewBtn\">ClickMe\n"); out.write(" </button>\n"); out.write(" <div class=\"modal fade\" id=\"fgt\">\n"); out.write(" <div class=\"modal-dialog\">\n"); out.write(" <div class=\"modal-content\">\n"); out.write(" <div class=\"modal-header\">\n"); out.write(" <h4 class=\"modal-title\">Search CIF with Account Number</h4>\n"); out.write(" <button type=\"button\" class=\"close\" data-dismiss=\"modal\">&times;</button>\n"); out.write(" </div>\n"); out.write(" <div class=\"modal-body\">\n"); out.write(" <div>\n"); out.write(" <form action=\"#\">\n"); out.write(" <div class=\"input-container\">\n"); out.write(" <input class=\"input-field inp\" type=\"text\" placeholder=\"Enter A/C Number\" id=\"acno\" name=\"acno\">\n"); out.write(" <button type=\"button\" class=\"btn btn-sm\" data-toggle=\"modal\" data-target=\"#srchcif\" id=\"srch\" onclick=\"return ac_number();\">Search</button> \n"); out.write(" </div>\n"); out.write(" </form>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" <div class=\"modal fade\" id=\"srchcif\">\n"); out.write(" <div class=\"modal-dialog\">\n"); out.write(" <div class=\"modal-content\" style=\"background-color: aliceblue;\">\n"); out.write(" <div class=\"modal-header\">\n"); out.write(" <h4 class=\"mdl_title\">Your CIF Number is</h4>\n"); out.write(" <button type=\"button\" class=\"close\" data-dismiss=\"modal\">&times;</button>\n"); out.write(" </div>\n"); out.write(" <div class=\"modal-body\">\n"); out.write(" <p id=\"acnodisplay\">54541646</p>\n"); out.write(" <button type=\"button\" class=\"btn\" onclick=\"copyToClipboard('#acnodisplay')\">Copy CIF</button>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </form>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <!-- jQuery CDN - Slim version (=without AJAX) -->\n"); out.write(" <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script>\n"); out.write(" <!-- Popper.JS -->\n"); out.write(" <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js\" integrity=\"sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ\" crossorigin=\"anonymous\"></script>\n"); out.write(" <!-- Bootstrap JS -->\n"); out.write(" <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\" integrity=\"sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm\" crossorigin=\"anonymous\"></script>\n"); out.write(" <!-- jQuery Custom Scroller CDN -->\n"); out.write(" <script src=\"https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js\"></script>\n"); out.write("\n"); out.write(" <script type=\"text/javascript\">\n"); out.write(" $(document).ready(function () {\n"); out.write(" $(\"#sidebar\").mCustomScrollbar({\n"); out.write(" theme: \"minimal\"\n"); out.write(" });\n"); out.write("\n"); out.write(" $('#sidebarCollapse').on('click', function () {\n"); out.write(" $('#sidebar, #content').toggleClass('active');\n"); out.write(" $('.collapse.in').toggleClass('in');\n"); out.write(" $('a[aria-expanded=true]').attr('aria-expanded', 'false');\n"); out.write(" });\n"); out.write(" });\n"); out.write(" </script>\n"); out.write(" <script type=\"text/javascript\">\n"); out.write(" function copyToClipboard(element) {\n"); out.write(" var $temp = $(\"<input>\");\n"); out.write(" $(\"body\").append($temp);\n"); out.write(" $temp.val($(element).text()).select();\n"); out.write(" document.execCommand(\"copy\");\n"); out.write(" $temp.remove();\n"); out.write("} \n"); out.write(" </script>\n"); out.write("</body>\n"); out.write("\n"); out.write("</html>"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
[ "sumandhara345@gmail.com" ]
sumandhara345@gmail.com
4b804c6b00ac50d849161a69f71856ebfe594bba
aa3ab3cff116e6d2fedcdc31b039ff678023b431
/workspaceJava-EE/TpJSP/src/iit/auth/InscriptionEtud.java
c99559dd01944e4fb1c8e0b9fd7dc3e6b6525bdc
[]
no_license
HassenBenSlima/Mini-Project-Java
623981e9e6196996ec5be0cf1908fea26e64921d
cd5cf3c56229a1660898dce0b929fdbb791010ca
refs/heads/master
2022-12-22T18:39:42.857902
2019-10-08T22:30:26
2019-10-08T22:30:26
133,140,428
0
0
null
2022-12-16T05:46:31
2018-05-12T11:38:47
TSQL
UTF-8
Java
false
false
1,282
java
package iit.auth; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; /** * Servlet implementation class InscriptionEtud */ @WebServlet("/InscriptionEtud") public class InscriptionEtud extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public InscriptionEtud() { super(); // TODO Auto-generated constructor stub } @Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("<h1> Inscription: Cette Etudiant n'est pas inscrit</h1>"); out.println("<form method='post' action='InscriptionControle'> "); out.println("Nom: <input type='text' name='nom'/></br>"); out.println("Prenom: <input type='text' name='prenom'/></br>"); out.println("Login: <input type='text' name='login'/></br>"); out.println("Mot de passe: <input type='text' name='pass'/></br></br>"); out.println("<input value='Inscription' type='submit' />"); out.println("</form>"); } }
[ "Hassen.BenSlima" ]
Hassen.BenSlima
8cb9720d3c5ee9f1ac581c879c245e6134ba6bdd
4592666f931019c19aa08967142ad763b0ad0110
/app/src/main/java/com/applications/pulsus/activity/ui/main/RegistrationsListFragment.java
4df0b9bb66e1209392342b3237c6c1a0cfd5cf24
[]
no_license
AnilWesley/Pulsus
d55188fa6b418ce00fb6c4b2d8e979a02d045949
387eaa68a77ce8b96bea4e49bace1e5c86f0b4cb
refs/heads/master
2023-01-20T13:43:01.596649
2020-11-21T06:30:21
2020-11-21T06:30:21
274,320,197
0
0
null
null
null
null
UTF-8
Java
false
false
4,979
java
package com.applications.pulsus.activity.ui.main; import android.annotation.SuppressLint; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.applications.pulsus.R; import com.applications.pulsus.adapters.RegistrationsListAdapter; import com.applications.pulsus.api.ApiInterface; import com.applications.pulsus.api.RetrofitClient; import com.applications.pulsus.models.RegistrationsListResponse; import com.applications.pulsus.utils.MyAppPrefsManager; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Objects; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * A placeholder fragment containing a simple view. */ public class RegistrationsListFragment extends Fragment { MyAppPrefsManager myAppPrefsManager; String userID; private static final String ARG_SECTION_NUMBER = "section_number"; private static final String TAG = "RESPONSE_DATA"; @BindView(R.id.registrationsRecycler) RecyclerView registrationsRecycler; @BindView(R.id.progressBar) LinearLayout progressBar; @BindView(R.id.constraintLayout) FrameLayout constraintLayout; @BindView(R.id.emptyView) TextView emptyView; public static RegistrationsListFragment newInstance(int index) { RegistrationsListFragment fragment = new RegistrationsListFragment(); Bundle bundle = new Bundle(); bundle.putInt(ARG_SECTION_NUMBER, index); fragment.setArguments(bundle); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int index = 1; if (getArguments() != null) { index = getArguments().getInt(ARG_SECTION_NUMBER); } } @Override public View onCreateView( @NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_registrations_list, container, false); ButterKnife.bind(this, root); myAppPrefsManager = new MyAppPrefsManager(Objects.requireNonNull(getContext())); userID = myAppPrefsManager.getUserId(); registrationsList(); return root; } public void registrationsList() { progressBar.setVisibility(View.VISIBLE); ApiInterface apiInterface = RetrofitClient.getClient(getContext()).create(ApiInterface.class); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("app_user_id", userID); Log.d(TAG, "" + jsonObject); apiInterface.processDataRegistrationsList(jsonObject).enqueue(new Callback<RegistrationsListResponse>() { @SuppressLint("SetTextI18n") @Override public void onResponse(@NotNull Call<RegistrationsListResponse> call, @NotNull Response<RegistrationsListResponse> response) { if (response.isSuccessful()) { Log.d(TAG, "onResponse: "+response.body()); progressBar.setVisibility(View.GONE); RegistrationsListResponse brochureDownload = response.body(); assert brochureDownload != null; if (brochureDownload.isStatus()) { List<RegistrationsListResponse.ResultBean> resultBeans = brochureDownload.getResult(); registrationsRecycler.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false)); RegistrationsListAdapter registrationsListAdapter = new RegistrationsListAdapter(getContext(), resultBeans); registrationsRecycler.setAdapter(registrationsListAdapter); registrationsListAdapter.notifyDataSetChanged(); } else { progressBar.setVisibility(View.GONE); emptyView.setVisibility(View.VISIBLE); registrationsRecycler.setVisibility(View.GONE); //Toast.makeText(getActivity(), "Failed", Toast.LENGTH_SHORT).show(); } } } @Override public void onFailure(@NotNull Call<RegistrationsListResponse> call, @NotNull Throwable t) { progressBar.setVisibility(View.GONE); Toast.makeText(getActivity(), "Failed", Toast.LENGTH_SHORT).show(); } }); } }
[ "anilwesley94@gmail.com" ]
anilwesley94@gmail.com
b9f13966b72b090cb114af470bc926de110aed4a
3db2a80ad323cdf4ad53aa113516c3855963fee1
/app/src/main/java/com/ananthrajsingh/firestoredemo/MainActivity.java
ae0476270e26d32114cea062b643f2e4ef5b48d3
[]
no_license
ananthrajsingh/FirestoreDemo
a018db533b46e853f42f865d812e587e5c3cfebe
123968fe6881b36bcb8710910bb67b92b5f0b0ea
refs/heads/master
2020-03-17T20:39:37.237649
2018-05-18T17:21:28
2018-05-18T17:21:28
133,922,213
0
0
null
null
null
null
UTF-8
Java
false
false
1,420
java
package com.ananthrajsingh.firestoredemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class MainActivity extends AppCompatActivity { TextView nameTextView; DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference mNamesListRef = mRootRef.child("names"); DatabaseReference mNameRef = mNamesListRef.child("name1"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); nameTextView = (TextView) findViewById(R.id.textViewName); } @Override protected void onStart() { super.onStart(); mNameRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String text = dataSnapshot.getValue(String.class); nameTextView.setText(text); } @Override public void onCancelled(DatabaseError databaseError) { } }); } }
[ "ananthraj.singh@gmail.com" ]
ananthraj.singh@gmail.com
93587f2ef28305ab3679b2b18ac440758c9331aa
83110fbb179713c411ddf301c90ef4b814285846
/src/PhysicalNicCdpInfo.java
28e345f33d7d5e9d730615acafdbde35cd09823b
[]
no_license
mikelopez/jvm
f10590edf42b498f2d81dec71b0fee120e381c9a
36a960897062224eabd0c18a1434f7c8961ee81c
refs/heads/master
2021-01-19T05:36:54.710665
2013-06-09T04:36:41
2013-06-09T04:36:41
3,783,647
2
0
null
null
null
null
UTF-8
Java
false
false
13,210
java
package com.vmware.vim25; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for PhysicalNicCdpInfo complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PhysicalNicCdpInfo"> * &lt;complexContent> * &lt;extension base="{urn:vim25}DynamicData"> * &lt;sequence> * &lt;element name="cdpVersion" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="timeout" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="ttl" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="samples" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="devId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="address" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="portId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="deviceCapability" type="{urn:vim25}PhysicalNicCdpDeviceCapability" minOccurs="0"/> * &lt;element name="softwareVersion" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="hardwarePlatform" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ipPrefix" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ipPrefixLen" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="vlan" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="fullDuplex" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="mtu" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="systemName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="systemOID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="mgmtAddr" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="location" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PhysicalNicCdpInfo", propOrder = { "cdpVersion", "timeout", "ttl", "samples", "devId", "address", "portId", "deviceCapability", "softwareVersion", "hardwarePlatform", "ipPrefix", "ipPrefixLen", "vlan", "fullDuplex", "mtu", "systemName", "systemOID", "mgmtAddr", "location" }) public class PhysicalNicCdpInfo extends DynamicData { protected Integer cdpVersion; protected Integer timeout; protected Integer ttl; protected Integer samples; protected String devId; protected String address; protected String portId; protected PhysicalNicCdpDeviceCapability deviceCapability; protected String softwareVersion; protected String hardwarePlatform; protected String ipPrefix; protected Integer ipPrefixLen; protected Integer vlan; protected Boolean fullDuplex; protected Integer mtu; protected String systemName; protected String systemOID; protected String mgmtAddr; protected String location; /** * Gets the value of the cdpVersion property. * * @return * possible object is * {@link Integer } * */ public Integer getCdpVersion() { return cdpVersion; } /** * Sets the value of the cdpVersion property. * * @param value * allowed object is * {@link Integer } * */ public void setCdpVersion(Integer value) { this.cdpVersion = value; } /** * Gets the value of the timeout property. * * @return * possible object is * {@link Integer } * */ public Integer getTimeout() { return timeout; } /** * Sets the value of the timeout property. * * @param value * allowed object is * {@link Integer } * */ public void setTimeout(Integer value) { this.timeout = value; } /** * Gets the value of the ttl property. * * @return * possible object is * {@link Integer } * */ public Integer getTtl() { return ttl; } /** * Sets the value of the ttl property. * * @param value * allowed object is * {@link Integer } * */ public void setTtl(Integer value) { this.ttl = value; } /** * Gets the value of the samples property. * * @return * possible object is * {@link Integer } * */ public Integer getSamples() { return samples; } /** * Sets the value of the samples property. * * @param value * allowed object is * {@link Integer } * */ public void setSamples(Integer value) { this.samples = value; } /** * Gets the value of the devId property. * * @return * possible object is * {@link String } * */ public String getDevId() { return devId; } /** * Sets the value of the devId property. * * @param value * allowed object is * {@link String } * */ public void setDevId(String value) { this.devId = value; } /** * Gets the value of the address property. * * @return * possible object is * {@link String } * */ public String getAddress() { return address; } /** * Sets the value of the address property. * * @param value * allowed object is * {@link String } * */ public void setAddress(String value) { this.address = value; } /** * Gets the value of the portId property. * * @return * possible object is * {@link String } * */ public String getPortId() { return portId; } /** * Sets the value of the portId property. * * @param value * allowed object is * {@link String } * */ public void setPortId(String value) { this.portId = value; } /** * Gets the value of the deviceCapability property. * * @return * possible object is * {@link PhysicalNicCdpDeviceCapability } * */ public PhysicalNicCdpDeviceCapability getDeviceCapability() { return deviceCapability; } /** * Sets the value of the deviceCapability property. * * @param value * allowed object is * {@link PhysicalNicCdpDeviceCapability } * */ public void setDeviceCapability(PhysicalNicCdpDeviceCapability value) { this.deviceCapability = value; } /** * Gets the value of the softwareVersion property. * * @return * possible object is * {@link String } * */ public String getSoftwareVersion() { return softwareVersion; } /** * Sets the value of the softwareVersion property. * * @param value * allowed object is * {@link String } * */ public void setSoftwareVersion(String value) { this.softwareVersion = value; } /** * Gets the value of the hardwarePlatform property. * * @return * possible object is * {@link String } * */ public String getHardwarePlatform() { return hardwarePlatform; } /** * Sets the value of the hardwarePlatform property. * * @param value * allowed object is * {@link String } * */ public void setHardwarePlatform(String value) { this.hardwarePlatform = value; } /** * Gets the value of the ipPrefix property. * * @return * possible object is * {@link String } * */ public String getIpPrefix() { return ipPrefix; } /** * Sets the value of the ipPrefix property. * * @param value * allowed object is * {@link String } * */ public void setIpPrefix(String value) { this.ipPrefix = value; } /** * Gets the value of the ipPrefixLen property. * * @return * possible object is * {@link Integer } * */ public Integer getIpPrefixLen() { return ipPrefixLen; } /** * Sets the value of the ipPrefixLen property. * * @param value * allowed object is * {@link Integer } * */ public void setIpPrefixLen(Integer value) { this.ipPrefixLen = value; } /** * Gets the value of the vlan property. * * @return * possible object is * {@link Integer } * */ public Integer getVlan() { return vlan; } /** * Sets the value of the vlan property. * * @param value * allowed object is * {@link Integer } * */ public void setVlan(Integer value) { this.vlan = value; } /** * Gets the value of the fullDuplex property. * * @return * possible object is * {@link Boolean } * */ public Boolean isFullDuplex() { return fullDuplex; } /** * Sets the value of the fullDuplex property. * * @param value * allowed object is * {@link Boolean } * */ public void setFullDuplex(Boolean value) { this.fullDuplex = value; } /** * Gets the value of the mtu property. * * @return * possible object is * {@link Integer } * */ public Integer getMtu() { return mtu; } /** * Sets the value of the mtu property. * * @param value * allowed object is * {@link Integer } * */ public void setMtu(Integer value) { this.mtu = value; } /** * Gets the value of the systemName property. * * @return * possible object is * {@link String } * */ public String getSystemName() { return systemName; } /** * Sets the value of the systemName property. * * @param value * allowed object is * {@link String } * */ public void setSystemName(String value) { this.systemName = value; } /** * Gets the value of the systemOID property. * * @return * possible object is * {@link String } * */ public String getSystemOID() { return systemOID; } /** * Sets the value of the systemOID property. * * @param value * allowed object is * {@link String } * */ public void setSystemOID(String value) { this.systemOID = value; } /** * Gets the value of the mgmtAddr property. * * @return * possible object is * {@link String } * */ public String getMgmtAddr() { return mgmtAddr; } /** * Sets the value of the mgmtAddr property. * * @param value * allowed object is * {@link String } * */ public void setMgmtAddr(String value) { this.mgmtAddr = value; } /** * Gets the value of the location property. * * @return * possible object is * {@link String } * */ public String getLocation() { return location; } /** * Sets the value of the location property. * * @param value * allowed object is * {@link String } * */ public void setLocation(String value) { this.location = value; } }
[ "dev@scidentify.info" ]
dev@scidentify.info
9d374147f10f134853411acd053b0de55dce2fcf
d504110d2237650b4a445417c80131915f303fe0
/netbeans/gas/main_ui/src/com/gas/main/ui/molpane/sitepanel/primer3/SelectTemplatePanel.java
94a21ed67985d7802d6a822762fe5e94cecd216a
[]
no_license
duncan1201/VF
ab8741163bbff03962818cc1076cc35c1252bb03
095478313d2580925f7417dae6eb083d09636a30
refs/heads/master
2021-03-22T00:26:13.276478
2016-09-08T11:48:01
2016-09-08T11:48:01
32,251,044
0
0
null
null
null
null
UTF-8
Java
false
false
2,777
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.gas.main.ui.molpane.sitepanel.primer3; import com.gas.database.core.primer.service.api.IUserInputService; import com.gas.domain.core.primer3.UserInput; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.lang.ref.WeakReference; import java.util.List; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.openide.DialogDescriptor; import org.openide.NotificationLineSupport; import org.openide.util.Lookup; /** * * @author dq */ public class SelectTemplatePanel extends JPanel { private IUserInputService service = Lookup.getDefault().lookup(IUserInputService.class); private WeakReference<UserInputTable> tableRef; private DialogDescriptor dialogDescriptor; private NotificationLineSupport notificationLineSupport; SelectTemplatePanel() { super(new GridBagLayout()); UserInputTable table = new UserInputTable(); table.setEditable(false); table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { validateInput(); } }); tableRef = new WeakReference<UserInputTable>(table); List<UserInput> userInputs = service.getAll(true); table.setUserInputs(userInputs); GridBagConstraints c = new GridBagConstraints(); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, c); } public void setDialogDescriptor(DialogDescriptor dialogDescriptor) { this.dialogDescriptor = dialogDescriptor; this.notificationLineSupport = dialogDescriptor.createNotificationLineSupport(); } void validateInput(){ UserInput userInput = getSelectedUserInput(); if(userInput == null){ dialogDescriptor.setValid(false); notificationLineSupport.setInformationMessage("Please select a setting"); }else{ dialogDescriptor.setValid(true); notificationLineSupport.clearMessages(); } } public UserInput getSelectedUserInput() { UserInputTable table = tableRef.get(); UserInputTable.UserInputTableModel model = (UserInputTable.UserInputTableModel) table.getModel(); int selected = table.getSelectedRow(); UserInput ret = model.getRow(table.convertRowIndexToModel(selected)); return ret; } }
[ "dunqiang.liao@vectorfriends.com" ]
dunqiang.liao@vectorfriends.com
bf79da99d469024c535e9a2bb3cb1a266f7ed111
8aa09f8aa3b6169cc37387d642a567eb940e0ca9
/coretools-graphics/src/main/java/org/andrill/coretools/graphics/PDFGraphics.java
50a4d8d74578beba4f44d2af9804acfd2da58ac8
[ "Apache-2.0" ]
permissive
laccore/coretools
0f9d23f409580b4667e4f8dcd6b1a3a1c0a8afe3
27ff4ccb8777ff95a7e5ae17d9fd2d088da10926
refs/heads/master
2023-07-21T08:26:56.285352
2023-07-06T19:51:05
2023-07-06T19:51:05
16,624,151
10
0
null
null
null
null
UTF-8
Java
false
false
4,253
java
/* * Copyright (c) Josh Reed, 2009. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andrill.coretools.graphics; import java.awt.Graphics2D; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import org.andrill.coretools.graphics.driver.Java2DDriver; import org.andrill.coretools.graphics.util.Paper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfTemplate; import com.lowagie.text.pdf.PdfWriter; /** * A PDFGraphics renders graphics to a PDF file. * * @author Josh Reed (jareed@andrill.org) */ public class PDFGraphics { private static final Logger LOGGER = LoggerFactory.getLogger(PDFGraphics.class); protected int bottomMargin; protected int height; protected int leftMargin; protected int rightMargin; protected int topMargin; protected int width; protected File file; protected Document document; protected PdfWriter writer; protected PdfContentByte content; // state protected Graphics2D lastGraphics; protected PdfTemplate lastTemplate; protected GraphicsContext lastDriver; /** * Create a new PDFGraphics. * * @param file * the file. * @param width * the width. * @param height * the height. * @param margins * the margins. */ public PDFGraphics(final File file, final int width, final int height, final int margins) { this.width = width; this.height = height; leftMargin = topMargin = rightMargin = bottomMargin = margins; this.file = file; init(); } /** * Create a new PDFGraphics. * * @param file * the file. * @param paper * the specified paper. */ public PDFGraphics(final File file, final Paper paper) { width = paper.getWidth(); height = paper.getHeight(); leftMargin = paper.getPrintableX(); topMargin = paper.getPrintableY(); rightMargin = paper.getWidth() - paper.getPrintableWidth() - paper.getPrintableX(); bottomMargin = paper.getHeight() - paper.getPrintableHeight() - paper.getPrintableY(); this.file = file; init(); } protected void init() { document = new Document(new Rectangle(width, height)); try { writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); } catch (FileNotFoundException e) { LOGGER.error("Unable to create PDF document {}: {}", file.getName(), e.getMessage()); throw new RuntimeException("Unable to create PDF document", e); } catch (DocumentException e) { LOGGER.error("Unable to create PDF document {}: {}", file.getName(), e.getMessage()); throw new RuntimeException("Unable to create PDF document", e); } content = writer.getDirectContent(); } /** * Create a new page. * * @return the new page. */ public GraphicsContext newPage() { if (lastGraphics != null) { lastGraphics.dispose(); } if (lastDriver != null) { lastDriver.dispose(); } if (lastTemplate != null) { content.addTemplate(lastTemplate, 0, 0); document.newPage(); } lastTemplate = content.createTemplate(width, height); lastGraphics = lastTemplate.createGraphics(width, height); lastGraphics.translate(leftMargin, topMargin); lastDriver = new GraphicsContext(new Java2DDriver(lastGraphics)); return lastDriver; } /** * Writes the PDF. */ public void write() { if (lastGraphics != null) { lastGraphics.dispose(); } if (lastDriver != null) { lastDriver.dispose(); } if (lastTemplate != null) { content.addTemplate(lastTemplate, 0, 0); } document.close(); writer.close(); } }
[ "sorghumking@yahoo.com" ]
sorghumking@yahoo.com
f6a1f62427fd1e443714c50655fa499e5acb515a
32d27d0a48dd51ea6b8c785b1bb5e670a22535b8
/challenge-05.java
76497398e8690e37b81bab18f53a6592dfd31427
[]
no_license
bamsrud01/java-challenges
18bb74be7f3c36134e5ba382ceb51e1bed20a0dc
df9ca9945959706c974fd4b55f63ffca3465e4c7
refs/heads/master
2020-04-06T04:42:46.530459
2017-05-20T02:01:34
2017-05-20T02:01:34
82,886,758
0
0
null
null
null
null
UTF-8
Java
false
false
1,129
java
public class main { public static void main(String[] args) { double centimeters = calculateCentimeters(5, 11); double moreCentimeters(100); } // calculateCentimeters() is overloaded public static double calculateCentimeters(double feet, double inches) { // Make sure feet and inches are valid values if ((feet < 0 || inches < 0) || inches > 12) { System.out.println("Invalid values given"); return -1; } double centimeters = (feet * 12) * 2.54; centimeters += inches * 2.54; System.out.println(feet + " feet, " + inches + " inches = " centimeters + "cm"); return centimeters; } // Note that this version of the function calls the one with two arguments public static double calculateCentimeters(double inches) { if (inches < 0) { System.out.println("Invalid value given"); return -1; } double feet = (int) inches / 12; double remainingInches = (int) inches % 12; System.out.println(inches + " inches is equal to " + feet " feet and " + remainingInches + " inches"); return calculateCentimeters(feet, remainingInches); } }
[ "barrettamsrud@gmail.com" ]
barrettamsrud@gmail.com
938a3ace31c9a270a28c227f7f81ee86dda03c23
c253fe38882c51b6898ea7eb3ba9b01a4aea7b1d
/Doodle_Jump_Multiplayer/src/me/eluch/libgdx/DoJuMu/game/GameObjectContainer.java
f52bd9c8236848339d51a69cafe5ac23ca221c2c
[ "Apache-2.0" ]
permissive
Eluch/Doodle-Jump-Multiplayer
21543c01c4e571cb8540a5075d41f5be2fd5c870
305c44f8f0a4c4a711eb7ca93625b71a403314eb
refs/heads/master
2020-05-16T16:39:44.358116
2014-04-27T21:47:31
2014-04-27T21:47:31
18,789,232
1
0
null
null
null
null
UTF-8
Java
false
false
6,354
java
package me.eluch.libgdx.DoJuMu.game; import java.util.ArrayList; import java.util.Random; import me.eluch.libgdx.DoJuMu.Options; import me.eluch.libgdx.DoJuMu.Res; import me.eluch.libgdx.DoJuMu.data.CorePlayer; import me.eluch.libgdx.DoJuMu.data.CorePlayerContainer; import me.eluch.libgdx.DoJuMu.game.active_item.JetpackActive; import me.eluch.libgdx.DoJuMu.game.active_item.PropellerHatActive; import me.eluch.libgdx.DoJuMu.game.active_item.SpringActive; import me.eluch.libgdx.DoJuMu.game.active_item.SpringShoeActive; import me.eluch.libgdx.DoJuMu.game.active_item.TrampolineActive; import me.eluch.libgdx.DoJuMu.game.doodle.DoodleBasic; import me.eluch.libgdx.DoJuMu.game.doodle.DoodleFull; import me.eluch.libgdx.DoJuMu.game.floors.Floor; import me.eluch.libgdx.DoJuMu.game.floors.GreenFloor; import me.eluch.libgdx.DoJuMu.game.item.Item; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Rectangle; public class GameObjectContainer { //Just for degug private boolean running = false; private boolean rPressed = false; private final ArrayList<DoodleBasic> doodles = new ArrayList<>(); //private final ArrayList<Enemy> enemies = new ArrayList<Enemy>(); //private final ArrayList<BlackHole> blackHoles = new ArrayList<>(); private final ArrayList<Floor> floors = new ArrayList<>(); private final ArrayList<Item> items = new ArrayList<>(); private DoodleFull myDoodle; private final Rectangle scrR = new Rectangle(-100, 0, Options.GAME_PLACE_WIDTH + 200, Options.GAME_PLACE_HEIGHT); // Screen Rectangle private float afterDeadDelta = 0; public GameObjectContainer(CorePlayerContainer<?> playerC) { // CONSTRUCTOR DoodleFull myDoodle = new DoodleFull(playerC.getMySelf(), playerC.getMySelf().getName(), new Random().nextInt(Options.ScreenRes.width / 2 - Res._characters.getWidth()), 30, Options.getCharacter(), false); this.myDoodle = myDoodle; playerC.getMySelf().setDoodle(myDoodle); for (CorePlayer p : playerC.getPlayers()) { if (p.getDoodle() == null) { p.setDoodle(new DoodleBasic(p, p.getName(), 10, 30, p.getGenderType(), true)); doodles.add(p.getDoodle()); } } floors.add(new GreenFloor(0, 10)); floors.add(new GreenFloor(80, 10)); floors.add(new GreenFloor(164, 10)); floors.add(new GreenFloor(246, 10)); floors.add(new GreenFloor(328, 10)); floors.add(new GreenFloor(410, 10)); } public DoodleFull getMyDoodle() { return myDoodle; } private void floorCleanup() { ArrayList<Floor> del = null; for (Floor floor : floors) { if (floor.rec.y < getCleanupY() || !floor.need2Show) { if (del == null) del = new ArrayList<>(); del.add(floor); } } if (del != null) floors.removeAll(del); } private void itemCleanup() { ArrayList<Item> del = null; for (Item item : items) { if (item.rec.y < getCleanupY() || !item.need2Show) { if (del == null) del = new ArrayList<>(); del.add(item); } } if (del != null) items.removeAll(del); } public int getPatternSliding() { return (int) (scrR.y % Res._pattern.getHeight()); } public ArrayList<Floor> getFloors() { return floors; } public ArrayList<DoodleBasic> getDoodles() { return doodles; } private float getHighestAliveDoodleY() { float y = -1; for (DoodleBasic doodle : doodles) { if (doodle.getRec().y > y && doodle.isAlive()) y = doodle.getRec().y; } return y; } private float getLowestAliveDoodleY() { float y = -1; boolean found = false; for (DoodleBasic doodle : doodles) { if (!found && doodle.isAlive()) { y = doodle.getRec().y; found = true; } if (doodle.getRec().y < y && doodle.isAlive()) y = doodle.getRec().y; } return y; } private float getCleanupY() { float y = getLowestAliveDoodleY(); if (y == -1 || (y != -1 && y > scrR.y - 100)) y = scrR.y - 100; else y -= 200; return y; } public ArrayList<Item> getItems() { return items; } public Rectangle getScrR() { return scrR; } public void update(float delta) { if (Options.DEBUG) { // Test for DEBUG if (Gdx.input.isKeyPressed(Keys.R) && !rPressed) { rPressed = true; running = !running; } else if (!Gdx.input.isKeyPressed(Keys.R) && rPressed) rPressed = false; } if (running || !Options.DEBUG) { // RUNNING PART floors.forEach(x -> { x.update(scrR, myDoodle.getFootRect(), !myDoodle.isJumping()); if (x.effect == Effect.COMMON_JUMP_CAUSER) { myDoodle.doJump(); x.resetEffect(); } }); items.forEach(x -> { x.update(scrR, myDoodle.getRec(), myDoodle.getFootRect(), !myDoodle.isJumping()); switch (x.getEffect()) { case SHIELD_EQUIPPING: myDoodle.setShielded(true); break; case JETPACK_EQUIPPING: myDoodle.setActiveItem(new JetpackActive(myDoodle)); break; case PROPELLER_HAT_EQUIPPING: myDoodle.setActiveItem(new PropellerHatActive(myDoodle)); break; case SPRING_JUMP: myDoodle.setActiveItem(new SpringActive(myDoodle)); break; case SPRING_SHOE_EQUIPPING: myDoodle.setActiveItem(new SpringShoeActive(myDoodle)); break; case TRAMPOLINE_JUMP: myDoodle.setActiveItem(new TrampolineActive(myDoodle)); break; default: break; } x.resetEffect(); }); myDoodle.update(delta); // Codename: SPECTATOR if (myDoodle.isAlive() && myDoodle.rec.y > (scrR.y + Options.GAME_PLACE_HEIGHT / 2)) { // scrR update scrR.y = myDoodle.rec.y - Options.GAME_PLACE_HEIGHT / 2; } else if (!myDoodle.isAlive()) { if (afterDeadDelta < 2.5f) afterDeadDelta += delta; else { float y = getHighestAliveDoodleY(); if (scrR.y - 100 > y && y != -1) scrR.y = y; if (y != -1) if (y > (scrR.y + Options.GAME_PLACE_HEIGHT / 2)) { // scrR update to highest alive player after dead scrR.y = y - Options.GAME_PLACE_HEIGHT / 2; } } } if (myDoodle.rec.y < scrR.y) { myDoodle.setAlive(false); myDoodle.setXY(myDoodle.getRec().x, myDoodle.getMaxHeight()); } itemCleanup(); floorCleanup(); } } public void render(SpriteBatch batch) { floors.forEach(x -> x.draw(batch, scrR)); items.forEach(x -> x.draw(batch, scrR)); doodles.forEach(x -> x.draw(batch, scrR)); myDoodle.draw(batch, scrR); } }
[ "pkferi@gmail.com" ]
pkferi@gmail.com
d45da743aa7204d75915c677b91ae2132cb1a2d2
d3811f5d2afe584fb3729730549e68981aabfdd4
/src/xue/demo1/Test3.java
20b22bfb6189e41ec05a6a7e60f4fffc32dfb8dc
[]
no_license
xwd627917648/code
9c1b3d347de248a8e710703f118853ad04427e52
cefac8e075fa9652c5b432bee6453c3c35a466b8
refs/heads/master
2020-04-14T21:07:10.805744
2019-01-04T14:34:23
2019-01-04T14:34:23
164,117,993
0
0
null
null
null
null
UTF-8
Java
false
false
780
java
package xue.demo1; public class Test3 { public static void main(String[] args) { System.out.println("sum = " + getSum(10,5)); System.out.println("num = " + getSum1(10.67,5.33)); System.out.println("cir = " + getCircumference(113,25)); System.out.println("area = " + getArea(10,25)); } public static int getSum(int a,int b){ int sum = a + b; return sum; } public static double getSum1(double a, double b){ double num = a + b; return num; } public static int getCircumference(int width,int length){ int cir = (width + length) * 2; return cir; } public static int getArea(int width,int length){ int area = width * length; return area; } }
[ "627917648@qq.com" ]
627917648@qq.com
aa45f9816aaedd3fd60f07fbc0ec91fd0af4c3a2
dbe5a0f4ed5ae354d217d971cdcc1e0eb0bbdc87
/SentimentDemo/src/in/shamit/nlp/sentiment/data/DatasetProcessor.java
e35d8fbe6b79315807d3963eddf517852f322844
[ "Apache-2.0" ]
permissive
shamitv/FastText_TensorFlow_Sentiment
e66a5816e2576e6c832d81ba9c5502391cf68c5f
82d054ac10fa8f41cd3c929c7928c816ed0845de
refs/heads/master
2021-01-01T17:58:33.418639
2017-07-24T15:42:03
2017-07-24T15:42:03
98,206,963
0
0
null
null
null
null
UTF-8
Java
false
false
2,569
java
package in.shamit.nlp.sentiment.data; import java.io.File; import java.nio.charset.Charset; import java.nio.file.Files; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import in.shamit.nlp.sentiment.fasttext.FastTextWrapper; public class DatasetProcessor { private final static Logger LOG = Logger.getLogger("DatasetProcessor"); public static void init(){ FastTextWrapper.init(); } public static void convertToVector(File input, File text, File vector){ try { List<String> inputLines=Files.readAllLines(input.toPath()); List<String> validLines, vectorLines; validLines=new ArrayList<>(); vectorLines=new ArrayList<>(); for (String l : inputLines) { try { double vec[]=FastTextWrapper.getVectors(l); validLines.add(l); String vecLine=getStringForVector(vec); vectorLines.add(vecLine); } catch (Exception e) { LOG.info("No vector for :: "+l); } } Files.write(text.toPath(), validLines, Charset.forName("UTF-8")); Files.write(vector.toPath(), vectorLines, Charset.forName("UTF-8")); } catch (Exception e) { throw new RuntimeException(e); } } private static String getStringForVector(double[] vec) { DecimalFormat df = new DecimalFormat("#.######"); StringBuffer sb=new StringBuffer(); for (double d : vec) { String str=df.format(d); sb.append(str); sb.append(" "); } String ret=sb.toString(); return ret.trim(); } public static void processFile(String name){ LOG.info("Processing input :: "+name); String baseLoc="G:/work/nlp/datasets/finance_sentiment/"; File inputDir=new File(baseLoc,"input"); File textDir=new File(baseLoc,"text"); File vecDir=new File(baseLoc,"vector"); if(!textDir.exists()){ LOG.info("Creating dir :: "+textDir.getAbsolutePath()); textDir.mkdir(); } if(!vecDir.exists()){ LOG.info("Creating dir :: "+vecDir.getAbsolutePath()); vecDir.mkdir(); } File inputFile=new File(inputDir,name+".txt"); LOG.info("Input file :: "+inputFile.getAbsolutePath()); File textFile=new File(textDir,name+".txt"); File vecFile=new File(vecDir,name+".txt"); LOG.info("Output files :: "+textFile.getAbsolutePath()+" :: "+vecFile.getAbsolutePath()); convertToVector(inputFile, textFile, vecFile); } public static void main(String[] args) { init(); processFile("positive"); processFile("negative"); processFile("neutral"); } }
[ "github@shamit.in" ]
github@shamit.in
d59e3f2f1460b8318a1dbd188e78b97e26154570
b8afcdfbe16e8ea8feacf1c4302a01683366e7fa
/basic/src/main/java/com/example/basic/BasicApplication.java
6e992dff5243ee77ce67c136e3d7d5332f0f4809
[]
no_license
jaypatil/spring-cloud
1b8fe81b49d91c3c74f854c160e6aaec383eb303
b95313539e024195912cd175cdbf3fc998fa0bb9
refs/heads/main
2023-08-24T18:52:22.446448
2021-10-27T18:22:59
2021-10-27T18:22:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,309
java
package com.example.basic; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.context.annotation.Bean; @SpringBootApplication public class BasicApplication { public static void main(String[] args) { SpringApplication.run(BasicApplication.class, args); } @Bean RouteLocator gateway(RouteLocatorBuilder routeLocatorBuilder){ return routeLocatorBuilder .routes() .route(routeSpec -> routeSpec .path("/customers") .uri("lb://customers/") ).build(); } /* How to use route @Bean RouteLocator gateway (RouteLocatorBuilder routeLocatorBuilder){ return routeLocatorBuilder .routes() .route(routSpec -> routSpec .path("/hello") // .filters(gatewayFilterSpec -> // gatewayFilterSpec // .setPath("/guides") // ) .uri("https://spring.io/") ) .route("/twitter", routeSpec -> routeSpec .path("/twitter/**") .filters(fs -> fs.rewritePath( "/twitter/(?<handle>.*)", "/${handle}" )) .uri("http://twitter.com/@") ) .build(); } */ }
[ "jaypatil.sonu@gmail.com" ]
jaypatil.sonu@gmail.com
8762b59db4bdf44c10b45bc5096281fced1e1af5
f8da2f0ba6c629872b67cdbe6e48bc828d152e83
/src/main/java/com/capgemini/config/BreachMonitorChecker.java
ba0f07e7777e60d32c901b7e530c4fc89c62be34
[ "MIT" ]
permissive
my3D-Team/light-controller
146089e818357a45467bbb27dc68529a85ebd69a
6862c2cdcdbb66b5bdb3a3c6e065b6c59aff7e64
refs/heads/master
2021-01-10T06:53:47.877271
2015-12-16T16:15:03
2015-12-16T16:15:03
47,127,754
0
0
null
null
null
null
UTF-8
Java
false
false
273
java
package com.capgemini.config; import lombok.Data; import java.util.List; /** * A checker. */ @Data public class BreachMonitorChecker { /** * URI to check */ private String uri; /** * Lights. */ private List<LightBreach> lights; }
[ "corentin.azelart@gmail.com" ]
corentin.azelart@gmail.com
0781972cf5ad62987cb880f0c1e91ad10bae1caf
196e0a64b1c7df40d7206d596da35b2093882c37
/app/build/generated/source/buildConfig/debug/com/camera/surfaceview/BuildConfig.java
1221e3ef397d4eefa65b2bb00a76ea2f786261ff
[]
no_license
NilaxSpaceo/SqaureSurfaceCameraDemo
01aa1acb736ea8df07ce900f9733a8daa67de240
6ced7ec89d3d7593c7af4834b07ac59e756bed6f
refs/heads/master
2020-12-24T06:59:57.719928
2016-11-11T06:51:16
2016-11-11T06:51:16
73,385,345
3
3
null
null
null
null
UTF-8
Java
false
false
472
java
/** * Automatically generated file. DO NOT MODIFY */ package com.camera.surfaceview; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String APPLICATION_ID = "com.javacodegeeks.androidsurfaceviewexample"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = ""; public static final int VERSION_CODE = 1; public static final String VERSION_NAME = "1.0"; }
[ "nilax.spaceo@gmail.com" ]
nilax.spaceo@gmail.com
c9daac218138be11ee064f7e1f13aecf33a49a27
209b998c9289113fda450c8440fd476aefc3a9a6
/src/org/jglrxavpok/glutils/GL_3DS_Importer.java
f3d0457e253f3ff88a3192536cebdf5f53c29114
[ "BSD-2-Clause" ]
permissive
jglrxavpok/jglrxavpok_lwjgl_utils
1efc9bf1e9973ba52d315c530dc365cb6afbd357
5676bbb854e113d79899a783f03712000850db9f
refs/heads/master
2021-01-23T07:04:02.378146
2014-02-24T14:04:29
2014-02-24T14:04:29
17,135,428
0
1
null
null
null
null
UTF-8
Java
false
false
4,533
java
package org.jglrxavpok.glutils; import java.io.*; import java.util.ArrayList; /** * Import a 3DS file into a GL_Model object. */ public class GL_3DS_Importer { // Reads the 3DS files into vertex and face lists private GL_3DS_Reader reader = new GL_3DS_Reader(); // Mesh object will hold the data in a renderable form private GL_Mesh mesh = new GL_Mesh(); public GL_3DS_Importer() { } public GL_Mesh load(String filename) { System.out.println("GL_3DS_Importer.import(): Load object from " + filename); reader = new GL_3DS_Reader(filename); System.out.println("GL_3DS_Importer.importFromStream(): model has " + reader.faces.size() + " faces and " + reader.vertices.size() + " vertices. "); return makeMeshObject(reader.vertices, reader.textureCoords, reader.normals, reader.faces); } /** * Load the 3DS file and store into a mesh. */ public GL_Mesh importFromStream(InputStream inStream) { System.out.println("importFromStream(): Load object from stream..."); reader.load3DSFromStream(inStream); System.out.println("importFromStream(): model has " + reader.faces.size() + " faces and " + reader.vertices.size() + " vertices and " + reader.textureCoords.size() + " txtrcoords."); return makeMeshObject(reader.vertices, reader.textureCoords, reader.normals, reader.faces); } /** * create a GL_Object (mesh object) from the data read by a 3DS_Reader * * @param verts * ArrayList of vertices * @param txtrs * ArrayList of texture coordinates * @param norms * ArrayList of normal * @param faces * ArrayList of Face objects (triangles) * @return */ public GL_Mesh makeMeshObject(ArrayList verts, ArrayList txtrs, ArrayList norms, ArrayList faces) { mesh = new GL_Mesh(); // mesh object mesh.name = "3DS"; // add verts to GL_object for (int i = 0; i < verts.size(); i++) { float[] coords = (float[]) verts.get(i); mesh.addVertex(coords[0], coords[1], coords[2]); } // add triangles to GL_object. 3DS "face" is always a triangle. for (int i = 0; i < faces.size(); i++) { Face face = (Face) faces.get(i); // put verts, normals, texture coords into triangle addTriangle(mesh, face, txtrs, norms); } // optimize the GL_Object and generate normals mesh.rebuild(); // if no normals were loaded, generate some if (norms.size() == 0) { mesh.regenerateNormals(); } return mesh; } /** * Add a new triangle to the GL_Object. This assumes that the vertices have * already been added to the GL_Object, in the same order that they were in * the 3DS. * * @param obj * GL_Object * @param face * a face from the OBJ file * @param txtrs * ArrayList of texture coords from the OBJ file * @param norms * ArrayList of normals from the OBJ file * @param v1 * vertices to use for the triangle (face may have >3 verts) * @param v2 * @param v3 * @return */ public GL_Triangle addTriangle(GL_Mesh obj, Face face, ArrayList txtrs, ArrayList norms) { // An OBJ face may have many vertices (can be a polygon). // Make a new triangle with the specified three verts. GL_Triangle t = new GL_Triangle(obj.vertex(face.vertexIDs[0]), obj.vertex(face.vertexIDs[1]), obj.vertex(face.vertexIDs[2])); // put texture coords into triangle if (txtrs.size() > 0) { // if texture coords were loaded float[] uvw; uvw = (float[]) txtrs.get(face.textureIDs[0]); // txtr coord for // vert 1 t.uvw1 = new GL_Vector(uvw[0], uvw[1], uvw[2]); uvw = (float[]) txtrs.get(face.textureIDs[1]); // txtr coord for // vert 2 t.uvw2 = new GL_Vector(uvw[0], uvw[1], uvw[2]); uvw = (float[]) txtrs.get(face.textureIDs[2]); // txtr coord for // vert 3 t.uvw3 = new GL_Vector(uvw[0], uvw[1], uvw[2]); } // put normals into triangle (NOTE: normalID can be -1!!! could barf // here!!!) if (norms.size() > 0) { // if normals were loaded float[] norm; norm = (float[]) norms.get(face.normalIDs[0]); // normal for vert 1 t.norm1 = new GL_Vector(norm[0], norm[1], norm[2]); norm = (float[]) norms.get(face.normalIDs[1]); // normal for vert 2 t.norm2 = new GL_Vector(norm[0], norm[1], norm[2]); norm = (float[]) norms.get(face.normalIDs[2]); // normal for vert 3 t.norm3 = new GL_Vector(norm[0], norm[1], norm[2]); } // add triangle to GL_object mesh.addTriangle(t); return t; } }
[ "jglrxavpok@gmail.com" ]
jglrxavpok@gmail.com
3506125910a3fa7e2cbf01aebf8256889122039c
641cb853d7892c9b36effb21117835c399c8ffe4
/src/main/java/com/dky/modules/sys/service/impl/GroupServiceImpl.java
aa4db0dc946d140ed09ee4025758c3f77b6d798c
[]
no_license
bowensd/graduation
c2226d7cc12909ba0e3f5121ce6a657eca1c2f6e
1e13c25f09fc766eb3623b84ef425a48ed03170c
refs/heads/master
2020-05-03T00:14:38.132083
2019-04-11T04:23:18
2019-04-11T04:23:18
178,304,432
0
0
null
2019-04-11T04:23:19
2019-03-29T00:44:13
Java
UTF-8
Java
false
false
631
java
package com.dky.modules.sys.service.impl; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.dky.modules.sys.dao.GroupMapper; import com.dky.modules.sys.model.Group; import com.dky.modules.sys.service.GroupService; import org.springframework.stereotype.Service; /** * describe: * * @author bowen * @date 2019/03/28 */ @Service public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements GroupService { @Override public Page<Group> selectList(JSONObject json) { return null; } }
[ "243874370@qq.com" ]
243874370@qq.com
d62f61d490caf090896d2a047d04906b7169e08f
2a4d3219f0d470216a6ab9f04b1769808299298f
/src/test/model/EntryTest.java
2221dfdc55dbb8771636bcb29c2fc27a06239ae6
[]
no_license
terry-yoon1205/lifestyle-tracker
d679f002c83c0bb06506edcdb137ac4db1e594f5
202e2876c53fdc201e025143781b25ad5fecfc3c
refs/heads/main
2023-03-04T04:17:35.362616
2021-02-17T00:08:37
2021-02-17T00:08:37
339,564,897
0
0
null
null
null
null
UTF-8
Java
false
false
1,878
java
package model; import exceptions.DoesNotExistException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public abstract class EntryTest<B extends Entry<T>, T extends SingleUnit> { public B e; public T su1; public T su2; @Test public abstract void testConstructorAndSetter(); @Test public abstract void testGetUnitsFormatted(); @Test public abstract void testToString(); @Test public void testAddUnit() { e.add(su1); assertEquals(1, e.getUnits().size()); assertEquals(su1, e.getUnits().get(0)); e.add(su2); assertEquals(2, e.getUnits().size()); assertEquals(su2, e.getUnits().get(1)); } @Test public void testDeleteUnitEmpty() { assertFalse(e.delete(su1)); assertFalse(e.delete(su2)); } @Test public void testDeleteUnitTypical() { e.add(su1); assertFalse(e.delete(su2)); assertTrue(e.delete(su1)); assertEquals(0, e.getUnits().size()); } @Test public void testDeleteUnitMultiple() { e.add(su1); e.add(su2); assertTrue(e.delete(su1)); assertEquals(1, e.getUnits().size()); assertEquals(su2, e.getUnits().get(0)); assertTrue(e.delete(su2)); assertEquals(0, e.getUnits().size()); } @Test public void testSearchUnitDoesNotExist() { e.add(su1); try { e.search("Test2"); fail(); } catch (DoesNotExistException e) { // pass } } @Test public void testSearchUnitTypical() { e.add(su1); e.add(su2); try { assertEquals(su1, e.search("Test1")); assertEquals(2, e.getUnits().size()); } catch (DoesNotExistException e) { fail(); } } }
[ "noreply@github.com" ]
terry-yoon1205.noreply@github.com
4f76cd291abd953bd13210cdda88006edab64b0a
05a893282046529fdf2335d4a559516d58e83b38
/app/src/main/java/com/xuexiang/templateproject/activity/MainActivity.java
b9d4340d166fa3fbfc9a5aa597d909ced0238836
[ "Apache-2.0" ]
permissive
Vincentlz/TemplateAppProject
6e5ce59882a24d26cff5a82d94ca68ec990156b9
26eaad3f5c8bbfc172712c9508795b823cd99108
refs/heads/master
2023-06-07T15:40:29.246211
2023-05-14T07:18:27
2023-05-14T07:18:27
307,254,867
0
0
Apache-2.0
2023-05-31T07:41:13
2020-10-26T03:46:56
null
UTF-8
Java
false
false
9,817
java
/* * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.xuexiang.templateproject.activity; import android.os.Build; import android.os.Bundle; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.widget.Toolbar; import androidx.viewpager.widget.ViewPager; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.xuexiang.templateproject.R; import com.xuexiang.templateproject.core.BaseActivity; import com.xuexiang.templateproject.core.BaseFragment; import com.xuexiang.templateproject.databinding.ActivityMainBinding; import com.xuexiang.templateproject.fragment.news.NewsFragment; import com.xuexiang.templateproject.fragment.other.AboutFragment; import com.xuexiang.templateproject.fragment.other.SettingsFragment; import com.xuexiang.templateproject.fragment.profile.ProfileFragment; import com.xuexiang.templateproject.fragment.trending.TrendingFragment; import com.xuexiang.templateproject.utils.Utils; import com.xuexiang.templateproject.utils.sdkinit.XUpdateInit; import com.xuexiang.templateproject.widget.GuideTipsDialog; import com.xuexiang.xaop.annotation.SingleClick; import com.xuexiang.xui.adapter.FragmentAdapter; import com.xuexiang.xui.utils.ResUtils; import com.xuexiang.xui.utils.ThemeUtils; import com.xuexiang.xui.utils.WidgetUtils; import com.xuexiang.xui.utils.XToastUtils; import com.xuexiang.xui.widget.imageview.RadiusImageView; import com.xuexiang.xutil.XUtil; import com.xuexiang.xutil.common.ClickUtils; import com.xuexiang.xutil.common.CollectionUtils; import com.xuexiang.xutil.display.Colors; /** * ็จ‹ๅบไธป้กต้ข,ๅชๆ˜ฏไธ€ไธช็ฎ€ๅ•็š„Tabไพ‹ๅญ * * @author xuexiang * @since 2019-07-07 23:53 */ public class MainActivity extends BaseActivity<ActivityMainBinding> implements View.OnClickListener, BottomNavigationView.OnNavigationItemSelectedListener, ClickUtils.OnClick2ExitListener, Toolbar.OnMenuItemClickListener { private String[] mTitles; @Override protected ActivityMainBinding viewBindingInflate(LayoutInflater inflater) { return ActivityMainBinding.inflate(inflater); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initViews(); initData(); initListeners(); } @Override protected boolean isSupportSlideBack() { return false; } private void initViews() { WidgetUtils.clearActivityBackground(this); mTitles = ResUtils.getStringArray(R.array.home_titles); binding.includeMain.toolbar.setTitle(mTitles[0]); binding.includeMain.toolbar.inflateMenu(R.menu.menu_main); binding.includeMain.toolbar.setOnMenuItemClickListener(this); initHeader(); //ไธป้กตๅ†…ๅฎนๅกซๅ…… BaseFragment[] fragments = new BaseFragment[]{ new NewsFragment(), new TrendingFragment(), new ProfileFragment() }; FragmentAdapter<BaseFragment> adapter = new FragmentAdapter<>(getSupportFragmentManager(), fragments); binding.includeMain.viewPager.setOffscreenPageLimit(mTitles.length - 1); binding.includeMain.viewPager.setAdapter(adapter); } private void initData() { GuideTipsDialog.showTips(this); XUpdateInit.checkUpdate(this, false); } private void initHeader() { binding.navView.setItemIconTintList(null); View headerView = binding.navView.getHeaderView(0); LinearLayout navHeader = headerView.findViewById(R.id.nav_header); RadiusImageView ivAvatar = headerView.findViewById(R.id.iv_avatar); TextView tvAvatar = headerView.findViewById(R.id.tv_avatar); TextView tvSign = headerView.findViewById(R.id.tv_sign); if (Utils.isColorDark(ThemeUtils.resolveColor(this, R.attr.colorAccent))) { tvAvatar.setTextColor(Colors.WHITE); tvSign.setTextColor(Colors.WHITE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ivAvatar.setImageTintList(ResUtils.getColors(R.color.xui_config_color_white)); } } else { tvAvatar.setTextColor(ThemeUtils.resolveColor(this, R.attr.xui_config_color_title_text)); tvSign.setTextColor(ThemeUtils.resolveColor(this, R.attr.xui_config_color_explain_text)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ivAvatar.setImageTintList(ResUtils.getColors(R.color.xui_config_color_gray_3)); } } // TODO: 2019-10-09 ๅˆๅง‹ๅŒ–ๆ•ฐๆฎ ivAvatar.setImageResource(R.drawable.ic_default_head); tvAvatar.setText(R.string.app_name); tvSign.setText("่ฟ™ไธชๅฎถไผ™ๅพˆๆ‡’๏ผŒไป€ไนˆไนŸๆฒกๆœ‰็•™ไธ‹๏ฝž๏ฝž"); navHeader.setOnClickListener(this); } protected void initListeners() { ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, binding.drawerLayout, binding.includeMain.toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); binding.drawerLayout.addDrawerListener(toggle); toggle.syncState(); //ไพง่พนๆ ็‚นๅ‡ปไบ‹ไปถ binding.navView.setNavigationItemSelectedListener(menuItem -> { if (menuItem.isCheckable()) { binding.drawerLayout.closeDrawers(); return handleNavigationItemSelected(menuItem); } else { int id = menuItem.getItemId(); if (id == R.id.nav_settings) { openNewPage(SettingsFragment.class); } else if (id == R.id.nav_about) { openNewPage(AboutFragment.class); } else { XToastUtils.toast("็‚นๅ‡ปไบ†:" + menuItem.getTitle()); } } return true; }); //ไธป้กตไบ‹ไปถ็›‘ๅฌ binding.includeMain.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { MenuItem item = binding.includeMain.bottomNavigation.getMenu().getItem(position); binding.includeMain.toolbar.setTitle(item.getTitle()); item.setChecked(true); updateSideNavStatus(item); } @Override public void onPageScrollStateChanged(int state) { } }); binding.includeMain.bottomNavigation.setOnNavigationItemSelectedListener(this); } /** * ๅค„็†ไพง่พนๆ ็‚นๅ‡ปไบ‹ไปถ * * @param menuItem * @return */ private boolean handleNavigationItemSelected(@NonNull MenuItem menuItem) { int index = CollectionUtils.arrayIndexOf(mTitles, menuItem.getTitle()); if (index != -1) { binding.includeMain.toolbar.setTitle(menuItem.getTitle()); binding.includeMain.viewPager.setCurrentItem(index, false); return true; } return false; } @Override public boolean onMenuItemClick(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_privacy) { GuideTipsDialog.showTipsForce(this); } else if (id == R.id.action_about) { openNewPage(AboutFragment.class); } return false; } @SingleClick @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.nav_header) { XToastUtils.toast("็‚นๅ‡ปๅคด้ƒจ๏ผ"); } } //================Navigation================// /** * ๅบ•้ƒจๅฏผ่ˆชๆ ็‚นๅ‡ปไบ‹ไปถ * * @param menuItem * @return */ @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { int index = CollectionUtils.arrayIndexOf(mTitles, menuItem.getTitle()); if (index != -1) { binding.includeMain.toolbar.setTitle(menuItem.getTitle()); binding.includeMain.viewPager.setCurrentItem(index, false); updateSideNavStatus(menuItem); return true; } return false; } /** * ๆ›ดๆ–ฐไพง่พนๆ ่œๅ•้€‰ไธญ็Šถๆ€ * * @param menuItem */ private void updateSideNavStatus(MenuItem menuItem) { MenuItem side = binding.navView.getMenu().findItem(menuItem.getItemId()); if (side != null) { side.setChecked(true); } } /** * ่œๅ•ใ€่ฟ”ๅ›ž้”ฎๅ“ๅบ” */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { ClickUtils.exitBy2Click(2000, this); } return true; } @Override public void onRetry() { XToastUtils.toast("ๅ†ๆŒ‰ไธ€ๆฌก้€€ๅ‡บ็จ‹ๅบ"); } @Override public void onExit() { XUtil.exitApp(); } }
[ "xuexiangjys@163.com" ]
xuexiangjys@163.com
343089e4d050f61c75418edd4b9525e2ba5fbd85
3faa77e55fb707254ce374615cb33864e482ff5a
/src/test/java/proxy/StaticProxyConfiguration.java
8d7e0a3d2260310121476946ea4ca4c00a5696ad
[]
no_license
matekub/restAssuredTutorial
8d684902c920c52903981830dcfa7cd9877d57c3
627cbb923c12e166b709af5553c2ec6191964687
refs/heads/master
2023-05-13T10:16:08.791560
2020-01-06T19:30:50
2020-01-06T19:30:50
232,168,098
0
0
null
2023-05-09T18:37:36
2020-01-06T19:15:05
Java
UTF-8
Java
false
false
654
java
package proxy; import io.restassured.RestAssured; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static io.restassured.RestAssured.given; public class StaticProxyConfiguration { @BeforeClass public static void setup() { RestAssured.baseURI = "http://localhost"; RestAssured.port = 8081; RestAssured.basePath = "/student"; RestAssured.proxy("localhost", 5555); } @Test public void getAllStudentsInformation() { given() .when() .get("/list") .then() .log() .body(); } }
[ "mateusz.kubaszewski@gmail.com" ]
mateusz.kubaszewski@gmail.com
61969a5073cde26451a429285eefc8cea5073e99
eeaccb9302080b7aeec55be14bd66507c97385f3
/app/src/main/java/com/ninefilta/ingnine/portfoliofragment/PortfolioAdaptor.java
23a78c8d8083ea78cd2dec3a7f4022047b9e4fad
[]
no_license
pajh89/ninePjt
ed4201af75c09ea0f61e1d4ef378e258e6b1270c
916cd22fcf9ee7f347f413d9933a5e60019ddb21
refs/heads/master
2021-08-08T10:02:48.973307
2017-11-10T03:28:43
2017-11-10T03:28:43
104,609,005
0
0
null
null
null
null
UTF-8
Java
false
false
2,396
java
package com.ninefilta.ingnine.portfoliofragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ninefilta.ingnine.R; import java.util.ArrayList; /** * Created by pajh8 on 2017-09-17. */ public class PortfolioAdaptor extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private ArrayList<PortfolioItem> portfolioItems; private LinearLayoutManager mLinearLayoutManager; private final int VIEW_ITEM = 1; private final int VIEW_PROG = 0; public PortfolioAdaptor(ArrayList<PortfolioItem> items) { this.portfolioItems = items; portfolioItems = new ArrayList<PortfolioItem>(); } @Override public int getItemViewType(int position) { return portfolioItems.get(position) != null ? VIEW_ITEM : VIEW_PROG; } public void setLinearLayoutManager(LinearLayoutManager linearLayoutManager){ this.mLinearLayoutManager=linearLayoutManager; } public void addAll(ArrayList<PortfolioItem> lst){ portfolioItems.clear(); portfolioItems.addAll(lst); notifyDataSetChanged(); } @Override public int getItemCount() { return portfolioItems.size(); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof PortfolioViowHolder) { PortfolioItem items = (PortfolioItem) portfolioItems.get(position); ((PortfolioViowHolder) holder).mboxNum_Port.setText(items.getBoxNum_Port()); ((PortfolioViowHolder) holder).mtitle_Port.setText(items.getTitle_Port()); }} @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new PortfolioViowHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.portfolio_listitem, parent, false)); } static class PortfolioViowHolder extends RecyclerView.ViewHolder { private TextView mboxNum_Port; private TextView mtitle_Port; public PortfolioViowHolder(View v) { super(v); mboxNum_Port = (TextView) v.findViewById(R.id.boxNum_port); mtitle_Port = (TextView) v.findViewById(R.id.title_Port); } } }
[ "pajh89@naver.com" ]
pajh89@naver.com
d73984a0a9333311ace39667ce064d4d7da381b9
232dedf4a0303b4473902a06e21b0b1b1b411495
/3_Input/src/Main.java
cca3deb23fd66859537494417721c8bf9096dc27
[]
no_license
dongdongkida/JavaPractice
b52aa0e7daf97f147ddcc4f500f7dc4336d5a2b9
dd672b926d7e5d0292615684ec52373787bc2c4f
refs/heads/master
2020-08-17T23:06:18.735178
2019-10-20T02:28:04
2019-10-20T02:28:04
215,721,714
0
0
null
null
null
null
UTF-8
Java
false
false
1,088
java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("What's your name?"); String userName = scanner.nextLine(); System.out.println(userName + " is a nice name!"); System.out.println("\n" + userName + ", how old are you?"); int userAge = scanner.nextInt(); System.out.println("You are " + userAge + " years old."); System.out.println("\nHow tall you are?"); double userHeight = scanner.nextDouble(); System.out.println("You are " + userHeight + " meters tall."); System.out.format("\nI have %d cats, 1 %s, and %.1f apple", 1, "dog",0.87); System.out.println("\nYou have lived " + userAge + " years. In another " + userAge + " years you'll be " + 2*userAge + " old."); System.out.format("\nYou have lived %d years. In another %d years you'll be %d years old.", userAge, userAge, 2*userAge); System.out.format("Your name has %d charaters.", userName.length()); } }
[ "dongdongkida@gmail.com" ]
dongdongkida@gmail.com
ba4f8be7fbccd4852b50072d4c007b36ce96c23f
829b74b88063ffcf62605440fe6a5a5226d1a7fb
/tut16.java
3b737f663b007278200fe80bd485386e19dea0cd
[]
no_license
DSahir/JAVA_learning
44d84cd4f5b9ed5ecc0d8892864523b3d05e8c99
7ecfcc0b58958580c29a9792ee550fcdd9be60c4
refs/heads/master
2022-06-22T08:02:26.744823
2020-05-07T10:56:14
2020-05-07T10:56:14
262,017,566
0
0
null
null
null
null
UTF-8
Java
false
false
1,732
java
public class tut16 { public static void main(String[] args) { //object class : defn - all obj inherits every method of class Object audi = new tut15Vehicle(); //audi as of type Obj--inherit all obj methods ---but cant access vehicle methods //so , typecasting System.out.println(((tut15Vehicle)audi).getspeed()); tut15Vehicle truck = new tut15Vehicle(); // built in equals method System.out.println(audi.equals(truck)); //each obj has unique identifier{hash code} System.out.println(audi.hashCode()); System.out.println(truck.hashCode()); //fianlise -- obj cleaning by java garabage collection when no longer needed in mem System.out.println(audi.getClass()); // samrt tho audi was "Object" System.out.println(audi.getClass().getName()); //only anme of class if(audi.getClass() == truck.getClass()){ System.out.println("SAME"); } System.out.println(audi.getClass().getSuperclass()); System.out.println(audi.toString()); //toString can also be overwritten---so that audi.toSrting is diff from Integer.toString() //CLONING -- LIKE COPYING BUT HAS DIFF HASH I.E AARE DIFF //set vehicle class to clonable truck.setWheel(7); tut15Vehicle truck2 = (tut15Vehicle)truck.clone(); System.out.println(truck.getWheel()); System.out.println(truck2.getWheel()); System.out.println(truck.hashCode()); System.out.println(truck2.hashCode()); /*obj a subobj b then you dont copy / clone subobj b */ } }
[ "dsahir511@gmail.com" ]
dsahir511@gmail.com
bb842338baa4e6955c89580ce626c8a63ba7665e
03303aea1c7f559e6442d3bd400d19ccf52eb60b
/java/src/com/mattrader/common/OrderManagerCom.java
3495a0793c2d8f0a5e76b96e199f18db0c8bf943
[ "BSD-3-Clause" ]
permissive
kalup/MatTrader
d1f206aa6bf0e8f553f4738892c2ab7c1f1f7a8a
f511f48fb2676a18c4bb07a3ad8226076b66c5d8
refs/heads/master
2021-01-10T09:34:22.152698
2016-09-26T22:39:19
2016-09-26T22:39:19
53,906,628
1
1
null
null
null
null
UTF-8
Java
false
false
5,922
java
package com.mattrader.common; import java.util.Collection; import java.util.HashMap; import java.util.Hashtable; import java.util.Locale; import java.util.Set; /** * A manager class for orders. It keep tracks of every order of the client and * it provides a method that will propose new unique orderIds on request. * * @author Luca Poletti * */ public final class OrderManagerCom { private LogCom log; public/*DEBUG private*/ Hashtable<String, OrderCom> orders; //XXX private MTClientBaseCom dcb; private int lastOrdID; /** * Constructor * * @param dcb - the client this order manager belongs to */ OrderManagerCom(MTClientBaseCom dcb) { log = dcb.log(); log.c(this, "constructor"); orders = new Hashtable<String, OrderCom>(); this.dcb = dcb; lastOrdID = 0; } /** * Used to insert a new order in the list of those who are handled by this manager * * @param ticker - the {@link TickerCom} ticker those order refers to * @param operationType - the type of operation performed * @param qty - the amount of stocks required by this order * * @return an {@link OrderCom} order that will be in a not ready state */ synchronized OrderCom insertNewOrder(TickerCom ticker, String operationType, int qty) { log.f(this, "new order insertion: " + operationType + "; " + ticker.tickerCode); String orderId = getNewId(); if(orderId == null) return null; OrderCom newOrder = new OrderCom(orderId, ticker, dcb); newOrder.setOperationType(operationType); newOrder.setQuantity(qty); orders.put(orderId, newOrder); ticker.registerOrder(newOrder); return newOrder; } /** * Used to insert a new order in the list of those who are handled by this manager * * @param ticker - the {@link TickerCom} ticker those order refers to * @param operationType - the type of operation performed * @param price - the price this operation is trying to operate * @param qty - the amount of stocks required by this order * * @return an {@link OrderCom} order that will be in a not ready state */ synchronized OrderCom insertNewOrder(TickerCom ticker, String operationType, double price, int qty) { OrderCom newOrder = insertNewOrder(ticker, operationType, qty); newOrder.setPrice(price); return newOrder; } /** * Used to insert a new order in the list of those who are handled by this manager * * @param ticker - the {@link TickerCom} ticker those order refers to * @param operationType - the type of operation performed * @param qty - the amount of stocks required by this order * @param signal - the price at which the order must be inserted in the market * * @return an {@link OrderCom} order that will be in a not ready state */ synchronized OrderCom insertNewOrder(TickerCom ticker, String operationType, int qty, double signal) { OrderCom newOrder = insertNewOrder(ticker, operationType, qty); newOrder.setPriceSignal(signal); return newOrder; } /** * Used to insert a new order in the list of those who are handled by this manager * * @param ticker - the {@link TickerCom} ticker those order refers to * @param operationType - the type of operation performed * @param price - the price this operation is trying to operate * @param qty - the amount of stocks required by this order * @param signal - the price at which the order must be inserted in the market * * @return an {@link OrderCom} order that will be in a not ready state */ synchronized OrderCom insertNewOrder(TickerCom ticker, String operationType, double price, int qty, double signal) { OrderCom newOrder = insertNewOrder(ticker, operationType, qty, signal); newOrder.setPrice(price); return newOrder; } /** * @return a String representing a new and unique ID for an order */ synchronized private String getNewId() { return "ORD_DM_"+dcb.clientName.toUpperCase(Locale.ENGLISH)+"_"+lastOrdID++; } /** * @param orderId - ID of the order we are seeking * @return the {@link OrderCom} order associated with that orderId */ OrderCom getOrder(String orderId) { return orders.get(orderId); } /** * @return a set of orderIds */ Set<String> getOrderIds() { return orders.keySet(); } /** * @return a collection of orders */ Collection<OrderCom> getOrders() { return orders.values(); } /** * Use this method to notify the manager that a message relative to an order has been * received * * @param message - the {@link MessageCom} received */ void receiveMessage(MessageCom message) { String messType = message.getType(); if(messType.equals(MessageCom.ORDER)) orderListEntry(message.getData()); } /** * Register or update a new order * * @param data - data of the {@link MessageCom} received by the manager */ private void orderListEntry(HashMap<String, String> data) { int id; String ordID = data.get("ordId"); OrderCom order; // TODO check getTicker Empty TickerCom ticker = dcb.getTicker(data.get("ticker"),"none"); if(lastOrdID < (id = Integer.parseInt("0" + ordID.replaceAll("\\D", "")))) lastOrdID = id; if(!orders.containsKey(ordID)) { order = new OrderCom(ordID, ticker, dcb); orders.put(ordID, order); } else order = orders.get(ordID); order.setOperationType(data.get("command")); order.setPrice(Double.parseDouble("0" + data.get("prLim"))); order.setPriceSignal(Double.parseDouble("0" + data.get("prSig"))); order.setQuantity(Integer.parseInt("0" + data.get("qty"))); int status = Integer.parseInt("0" + data.get("orderStatus")); // if(status == 2000 || status == 2002) // status = 3000; // else if(status == 2001) // status = 0; // else if(status == 2003) // status = 3001; // else if(status == 2004) // status = 3002; // else if(status == 2005) // status = 3003; status = OrderCom.convertStausCode(status); order.setStatus(status); ticker.registerOrder(order); } }
[ "luca.poletti.89@gmail.com" ]
luca.poletti.89@gmail.com
e8008fd61e0b484e4a1b2737952e090d98023e9c
1824a3ea8151f56e6d6cbffc7d5c56c1ee04bd2b
/src/main/java/me/Hazz/HazzBot/Variables/MySQLAdapter.java
8492d129353b919df5204a77e692803c5633e9a2
[]
no_license
Hazzaaa43/HazzBot
1652b148d51e55cce87c35ba5df28661ee9cf58b
f23fd9e59f396c59bba85598a7b5c669d4b69fa4
refs/heads/master
2020-12-07T08:01:30.022926
2020-01-08T22:52:02
2020-01-08T23:03:07
232,679,192
0
0
null
null
null
null
UTF-8
Java
false
false
4,181
java
package me.Hazz.HazzBot.Variables; import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource; import java.sql.*; import java.util.Calendar; public class MySQLAdapter { private String DB_NAME; private String DB_USER; private String DB_ADRES; private int DB_PORT; private String DB_PASSWORD; private Connection c; public MySQLAdapter(String server, int port, String databaseUser, String databasePassword, String databaseName) { DB_ADRES = server; DB_USER = databaseUser; DB_PASSWORD = databasePassword; DB_NAME = databaseName; DB_PORT = port; } private Connection createConnection() { try { MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource(); dataSource.setUser(DB_USER); dataSource.setPassword(DB_PASSWORD); dataSource.setServerName(DB_ADRES); dataSource.setPort(DB_PORT); dataSource.setDatabaseName(DB_NAME); dataSource.setZeroDateTimeBehavior("convertToNull"); dataSource.setUseUnicode(true); return dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); System.out.println("Cant connect to db"); try { throw new Exception("Cant connect to db"); } catch (Exception ex) { } } return null; } public Connection getConnection() { if (c == null) { c = createConnection(); } try { if (c.isClosed()) c = createConnection(); } catch (Throwable t) { } return c; } public ResultSet select(String sql, Object... params) throws SQLException { PreparedStatement query; query = getConnection().prepareStatement(sql); resolveParameters(query, params); return query.executeQuery(); } private void resolveParameters(PreparedStatement query, Object... params) throws SQLException { int index = 1; for (Object p : params) { if (p instanceof String) { query.setString(index, (String) p); } else if (p instanceof Integer) { query.setInt(index, (int) p); } else if (p instanceof Long) { query.setLong(index, (Long) p); } else if (p instanceof Double) { query.setDouble(index, (double) p); } else if (p instanceof java.sql.Date) { java.sql.Date d = (java.sql.Date) p; Timestamp ts = new Timestamp(d.getTime()); query.setTimestamp(index, ts); } else if (p instanceof java.util.Date) { java.util.Date d = (java.util.Date) p; Timestamp ts = new Timestamp(d.getTime()); query.setTimestamp(index, ts); } else if (p instanceof Calendar) { Calendar cal = (Calendar) p; Timestamp ts = new Timestamp(cal.getTimeInMillis()); query.setTimestamp(index, ts); } else if (p == null) { query.setNull(index, Types.NULL); } else { try { throw new Exception("Broken fucking database"); } catch (Exception e) { e.printStackTrace(); } } index++; } } public int query(String sql, Object... params) throws SQLException { try (PreparedStatement query = getConnection().prepareStatement(sql)) { resolveParameters(query, params); return query.executeUpdate(); } } public int insert(String sql, Object... params) throws SQLException { try (PreparedStatement query = getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { resolveParameters(query, params); query.executeUpdate(); ResultSet rs = query.getGeneratedKeys(); if (rs.next()) { return rs.getInt(1); } } return -1; } }
[ "unconfigured@null.spigotmc.org" ]
unconfigured@null.spigotmc.org
e1d1c9aa26e6cc0e615412586e69efb4ae1c43a2
011d1419e39568d6f88759de4227314cf75c5cc6
/src/test/java/ppa/marc/reader/RecordToFieldsDividerTest.java
366ac595e1d1d5443e429f2932e8e10f7afe902f
[ "Apache-2.0" ]
permissive
PasiAhopelto/marc-file-access
44c33fd28230ace42cabebb11c7f8eda18a07dd1
ac9d7f9a2294df1080b222e62d6124f08158d967
refs/heads/master
2021-01-10T19:00:39.870001
2014-05-21T16:50:13
2014-05-21T16:50:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,677
java
package ppa.marc.reader; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; public class RecordToFieldsDividerTest extends TestCase { private static final String CONTROL_FIELD = "001 value"; private static final String DATA_FIELD = "101.0_ |a eng"; private static final String MULTILINE_DATA_FIELD = "101.0_ |a eng\n|c ger"; private static final String DATA_FIELD_WITHOUT_VALUE = "101.0_"; RecordToFieldsDivider divider = new RecordToFieldsDivider(); List<String> expectedFields = new ArrayList<String>(); public void testGrantedInputIsEmptyThenThrowsMarcFormatException() throws Exception { assertFailsWithInput("", "contains empty line."); } public void testGrantedInputContainsOnlySpacesThenThrowsMarcFormatException() throws Exception { assertFailsWithInput(" \t", "could not be divided into fields."); } public void testGrantedInputContainsControlFieldThenReturnsItAsString() throws Exception { expectedFields.add(CONTROL_FIELD); assertEquals(expectedFields, divider.divideToFields(CONTROL_FIELD)); } public void testGrantedInputContainsTwoControlFieldsThenReturnsThemAsStrings() throws Exception { expectedFields.add(CONTROL_FIELD); expectedFields.add(CONTROL_FIELD); assertEquals(expectedFields, divider.divideToFields(CONTROL_FIELD + "\n" + CONTROL_FIELD)); } public void testGrantedInputContainsEmptyLineThenThrowsException() throws Exception { assertFailsWithInput(CONTROL_FIELD + "\n\n", "contains empty line."); } public void testGrantedInputContainsSingleDataFieldThenReturnsItAsString() throws Exception { expectedFields.add(DATA_FIELD); assertEquals(expectedFields, divider.divideToFields(DATA_FIELD)); } public void testGrantedInputContainsTwoDataFieldsThenReturnsThemAsStrings() throws Exception { expectedFields.add(DATA_FIELD); expectedFields.add(DATA_FIELD); assertEquals(expectedFields, divider.divideToFields(DATA_FIELD + "\n" + DATA_FIELD)); } public void testGrantedInputContainsMultilineDataFieldThenReturnsItAsString() throws Exception { expectedFields.add(MULTILINE_DATA_FIELD); assertEquals(expectedFields, divider.divideToFields(MULTILINE_DATA_FIELD)); } public void testGrantedInputContainsMultilineDataFieldsThenReturnsThemAsStrings() throws Exception { expectedFields.add(MULTILINE_DATA_FIELD); expectedFields.add(MULTILINE_DATA_FIELD); assertEquals(expectedFields, divider.divideToFields(MULTILINE_DATA_FIELD + "\n" + MULTILINE_DATA_FIELD)); } public void testGrantedInputContainsFieldWithoutValueThenReturnsStringWithFieldIdButNoValue() throws Exception { expectedFields.add(DATA_FIELD_WITHOUT_VALUE); assertEquals(expectedFields, divider.divideToFields(DATA_FIELD_WITHOUT_VALUE)); } public void testGrantedInputContainsFieldsWithoutValueThenReturnsThemAsStringsWithFieldIdsButNoValues() throws Exception { expectedFields.add(DATA_FIELD_WITHOUT_VALUE); expectedFields.add(DATA_FIELD_WITHOUT_VALUE); assertEquals(expectedFields, divider.divideToFields(DATA_FIELD_WITHOUT_VALUE + "\n" + DATA_FIELD_WITHOUT_VALUE)); } public void testGrantedInputContainsAllDifferentFieldTypesThenReturnsThemAsStrings() throws Exception { expectedFields.add(DATA_FIELD); expectedFields.add(CONTROL_FIELD); expectedFields.add(DATA_FIELD_WITHOUT_VALUE); assertEquals(expectedFields, divider.divideToFields(DATA_FIELD + "\n" + CONTROL_FIELD + "\n" + DATA_FIELD_WITHOUT_VALUE)); } private void assertFailsWithInput(String input, String message) { try { divider.divideToFields(input); fail(); } catch(MarcFormatException expected) { assertEquals("Record '" + input + "' " + message, expected.getMessage()); } } }
[ "pahopelt@gmail.com" ]
pahopelt@gmail.com
7b5bf47cca5a2aafa4d1fac7aa26b1cab1cde687
5f4f51fb528b215fa7c8aedd0215649aed704cb0
/MS/src/org/Spectrums/ProteinIDExtractor.java
12d945cf0f776d57c9fb212470df8e3a9af4a69a
[]
no_license
bugouzhi/workspace
4b45b4217dfd26d32f1e97f3f64190d6d73b3c48
f34631dcd49d919bed29e6b5bd3db9f1ee9a90fd
refs/heads/master
2020-05-18T01:50:01.318219
2017-09-21T20:05:41
2017-09-21T20:05:41
14,571,979
1
2
null
null
null
null
UTF-8
Java
false
false
13,703
java
package org.Spectrums; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import Utils.RKLookup; import sequences.*; /** * Given a sequence database and a list of search results from * database search engine: * - Extract list of protein IDs from a list of PSMs * - Mapped the peptide IDs to protein positions * * @author Jian Wang * */ public class ProteinIDExtractor { private String searchResultFile; private String proteinDBFile; private String outputFile; private BufferedWriter out; FastaSequence seqDB; char[] seqArray; String seqStr; Set<String> proteinIDs; Set<String> peptideIDs; RKLookup strMatches; Map<String, List<String>> peptideMap; Map<String, List<String>> proteinMap; Map<String, List<Object>> positionMap; private int pepIDIndex = 1; private int pepIDIndex2 = 1; public Map<String, List<String>> getPeptideMap() { return peptideMap; } public Map<String, List<String>> getProteinMap() { return proteinMap; } public Map<String, List<Object>> getPositionMap() { return positionMap; } public ProteinIDExtractor(String dbFile, String result){ this.proteinDBFile = dbFile; this.searchResultFile = result; System.out.println("resultFile: " + this.searchResultFile); this.outputFile = searchResultFile.split("\\.txt")[0]+".fasta"; System.out.println("out: " + this.outputFile); init(); parseResultFile(); getPeptideProteinMap(); //printProteins(); } public ProteinIDExtractor(String dbFile, String result, int pepInd){ this.proteinDBFile = dbFile; this.searchResultFile = result; this.pepIDIndex = pepInd; System.out.println("resultFile: " + this.searchResultFile); this.outputFile = searchResultFile.split("\\.txt")[0]+".fasta"; System.out.println("out: " + this.outputFile); init(); parseResultFile(); getPeptideProteinMap(); //printProteins(); } public ProteinIDExtractor(List IDs, String dbFile){ this.peptideIDs = new HashSet(); //System.out.println("Protein fasta: " + dbFile); this.proteinDBFile = dbFile; this.seqDB = new FastaSequence(this.proteinDBFile); this.seqStr = seqDB.getSubsequence(0, seqDB.getSize()); System.out.println("resultFile: " + this.searchResultFile); //this.outputFile = searchResultFile.split("\\.txt")[0]+".fasta"; //System.out.println("out: " + this.outputFile); //System.out.println("IDs-list size: " + IDs.size()); for(int i = 0; i < IDs.size(); i++){ Spectrum s = (Spectrum)IDs.get(i); String peptide = s.peptide; //System.out.println("peptide: " + peptide); //peptide = getStrippedSeq(peptide); peptideIDs.add(peptide); } init(); getPeptideProteinMap(); //getPeptideReport(); } public ProteinIDExtractor(Set<String> IDs, String dbFile){ this.peptideIDs = new HashSet(); //System.out.println("Protein fasta: " + dbFile); this.proteinDBFile = dbFile; this.seqDB = new FastaSequence(this.proteinDBFile); this.seqStr = seqDB.getSubsequence(0, seqDB.getSize()); System.out.println("resultFile: " + this.searchResultFile); //this.outputFile = searchResultFile.split("\\.txt")[0]+".fasta"; //System.out.println("out: " + this.outputFile); //System.out.println("IDs-list size: " + IDs.size()); for(Iterator<String> it = IDs.iterator(); it.hasNext();){ String pep = it.next(); //System.out.println("ID is: " + pep); this.peptideIDs.add(pep); } init(); getPeptideProteinMap(); //getPeptideReport(); } public List<String> getProteins(String pep){ if(this.peptideMap.containsKey(pep)){ return this.peptideMap.get(pep); }else{ return new ArrayList<String>(); } } private void init(){ this.seqDB = new FastaSequence(this.proteinDBFile); this.seqStr = seqDB.getSubsequence(0, seqDB.getSize()); this.seqArray = seqStr.toCharArray(); } private String getStrippedSeq(String pep){ return Utils.StringUtils.getStrippedSeq(pep); } private void parseResultFile(){ List<String> results = Utils.FileIOUtils.createListFromFile(this.searchResultFile); this.peptideIDs = new HashSet(); for(int i = 0; i < results.size(); i++){ String line = results.get(i); //System.out.println("line is: " + line); String[] tokens = line.split("\\t"); if(tokens.length < this.pepIDIndex || line.startsWith("#") || line.startsWith("SpectrumFile")){ continue; } String peptide = tokens[pepIDIndex]; if(peptide.contains("!")){ String[] peptides = peptide.split("!"); for(int p = 0; p < peptides.length; p++){ peptide = Utils.StringUtils.getStrippedSeq(peptides[p]); if(peptides.length > 1){ //System.out.println("adding peptide: " + peptide); } peptideIDs.add(peptide); } }else{ peptide = Utils.StringUtils.getStrippedSeq(peptide); //peptide = peptide.substring(1, peptide.length()-1); //System.out.println("IDs is : " + peptide); peptideIDs.add(peptide); //String peptide2 = tokens[pepIDIndex2]; //peptide2 = peptide2.replaceAll("[0-9\\+\\-\\.\\_\\(\\)]", ""); //peptideIDs.add(peptide2); } } //System.out.println("Done parsing results"); } private void getPeptideProteinMap(){ this.peptideMap = new HashMap<String, List<String>>(); this.proteinMap = new HashMap<String, List<String>>(); this.positionMap = new HashMap<String, List<Object>>(); this.proteinIDs = new HashSet(); int counter =0; Map<String, List<String>> modSeqMap = new HashMap<String, List<String>>(); for(Iterator<String> it = this.peptideIDs.iterator(); it.hasNext();){ String pep = it.next(); String stripped = getStrippedSeq(pep); if(modSeqMap.containsKey(stripped)){ modSeqMap.get(stripped).add(pep); }else{ List<String> mods = new ArrayList(); mods.add(pep); modSeqMap.put(stripped, mods); } } //System.out.println(this.peptideIDs.size() + "\t" + modSeqMap.keySet().size()); RKLookup strMatcher = new RKLookup(modSeqMap.keySet(), 5); Map<String, List<Integer>> matches = strMatcher.matches(this.seqStr); for(Iterator<String> it = matches.keySet().iterator(); it.hasNext();){ String pep = it.next(); List<Integer> positions = matches.get(pep); List<String> proteins = new ArrayList<String>(); List<Object> pos = new ArrayList<Object>(); //System.out.println("Peptide: " + pep +"\tmatches: " + positions.size()); for(int i = 0; i < positions.size(); i++){ int ind = positions.get(i); String prot = this.seqDB.getAnnotation(ind); List<String> peps; if(this.proteinMap.containsKey(prot)){ peps = this.proteinMap.get(prot); }else{ peps = new ArrayList<String>(); this.proteinMap.put(prot, peps); } proteins.add(prot); pos.add(prot); pos.add(ind-this.seqDB.getStartPosition(ind-1)); } List<String> modSeq = modSeqMap.get(pep); for(int i = 0; i < modSeq.size(); i++){ for(int j = 0; j < proteins.size(); j++){ this.proteinMap.get(proteins.get(j)).add(modSeq.get(i)); } //System.out.println("putting mod " + modSeq.get(i)); this.peptideMap.put(modSeq.get(i), proteins); this.positionMap.put(modSeq.get(i), pos); } } System.out.println("checking pep2\t" + this.peptideMap.containsKey("+42.011MQNDAGEFVDLYVPR")); System.out.println("After constructing positionmap size: " + this.positionMap.keySet().size()); this.proteinIDs = this.proteinMap.keySet(); } //get a list of peptides not shared by proteins public Set<String> getNonSharedPeps(){ Set<String> nonDegenerate = new HashSet<String>(); System.out.println("size: " + this.peptideMap.keySet().size() + "\t" + this.peptideIDs.size()); for(Iterator<String> it = this.peptideMap.keySet().iterator(); it.hasNext();){ String pep = it.next(); List<String> protIds = this.peptideMap.get(pep); if(protIds.size() == 1){ nonDegenerate.add(pep); } } System.out.println("Total non-degenerate " + nonDegenerate.size()); return nonDegenerate; } public Set<String> getNonSharedPeps(String prot){ Set<String> nonDegenerate = new HashSet<String>(); List<String> peps = this.proteinMap.get(prot); if(peps == null){ return nonDegenerate; } for(Iterator<String> it = peps.iterator(); it.hasNext();){ String pep = it.next(); List<String> protIds = this.peptideMap.get(pep); if(protIds.size() == 1){ nonDegenerate.add(pep); //System.out.println("Protein " + prot +"\tuniq-pep:\t" + pep); } } //System.out.println("Total non-degenerate " + nonDegenerate.size()); return nonDegenerate; } //get a list of proteins do not contain shared peptides public Set<String> getProtWithNoSharePeps(){ Set<String> prots = new HashSet<String>(); Set<String> peps = getNonSharedPeps(); for(Iterator<String> it = peps.iterator(); it.hasNext();){ String pep = it.next(); prots.add(this.peptideMap.get(pep).get(0)); } return prots; } public void printProteins(boolean printDecoy){ try{ this.out = new BufferedWriter(new FileWriter(this.outputFile)); for(Iterator it = proteinIDs.iterator(); it.hasNext();){ String protein = (String)it.next(); String protStr = this.seqDB.getMatchingEntry(protein); if(printDecoy || !protein.startsWith("X_") ){ out.append(">"+protein+"\n"); out.append(protStr +"\n"); } } //print decoy for(Iterator it = proteinIDs.iterator(); it.hasNext();){ String protein = (String)it.next(); String protStr = this.seqDB.getMatchingEntry(protein); if(!protein.startsWith("X_") && printDecoy){ out.append(">X_"+protein +"\n"); out.append(new StringBuffer(protStr).reverse().toString() +"\n"); } } out.flush(); out.close(); }catch(IOException ioe){ System.err.println(ioe.getMessage()); ioe.printStackTrace(); } } public void getPeptideReport(){ String proteinIDPattern = ""; int matchCount = 0; for(Iterator<String> it = this.peptideMap.keySet().iterator(); it.hasNext();){ String peptide = it.next(); //peptide = peptide.substring(1, peptide.length()-1); List<String> proteins = this.peptideMap.get(peptide); System.out.print("ID: " + peptide + "\t"); for(int j = 0; j < proteins.size(); j++){ System.out.print(proteins.get(j) + ";"); } System.out.println(); } } public void getProteinReport(){ for(Iterator<String> it = this.proteinMap.keySet().iterator(); it.hasNext();){ String protID = it.next(); List<String> pepList = this.proteinMap.get(protID); System.out.println("Protein: " + protID + "\tmapped peps:\t" + pepList.size()); } } public void getPeptidePairReport(){ List<String> results = Utils.FileIOUtils.createListFromFile(this.searchResultFile); for(int i = 0; i < results.size(); i++){ String line = results.get(i); String[] tokens = line.split("\\s+"); String peptide1 = tokens[this.pepIDIndex]; String peptide2 = tokens[this.pepIDIndex2]; peptide1 = peptide1.replaceAll("[0-9\\+\\-\\.r]", ""); peptide2 = peptide2.replaceAll("[0-9\\+\\-\\.r]", ""); //peptide = peptide.substring(1, peptide.length()-1); List<String> proteins1 = this.peptideMap.get(peptide1); System.out.print("ID1: " + peptide1 + "\t"); for(int j = 0; j < proteins1.size(); j++){ String prot = proteins1.get(j); //prot = prot.split("\\s+")[0]; System.out.print(prot + ";"); } List<String> proteins2 = this.peptideMap.get(peptide2); System.out.print("\t"); System.out.print("ID2: " + peptide2 + "\t"); for(int j = 0; j < proteins2.size(); j++){ String prot = proteins2.get(j); //prot = prot.split("\\s+")[0]; System.out.print(prot + ";"); } System.out.println(); } } public Map<String, List<Object>> getPositonMap(){ return this.positionMap; } //mapp ID to proteins public static void mapID(String ID, Map<String, List<Integer>> idMap, List<String> seqs){ if(ID.startsWith("r")){ ID = ID.substring(1); } if(idMap.containsKey(ID)){ return; } idMap.put(ID, new ArrayList<Integer>()); List<Integer> positions = idMap.get(ID); for(int j = 0; j < seqs.size(); j++){ String chainSeq = seqs.get(j); //position of peptide in chain int index = chainSeq.indexOf(ID); //System.out.println("chain: " + j + " index: " + index); //linked position, now assume to be first lysine int position = index + ID.indexOf('K'); if(index >=0){ positions.add(j); positions.add(index); positions.add(position); } } } public static void extractProteinsFromResultFiles(String directory){ File dir = new File(directory); File[] files = dir.listFiles(); boolean printDecoy = false; for(int i =0; i < files.length; i++){ File current = files[i]; //System.out.println("file is: " + current.getName()); String name = current.getName(); if(name.matches("Rabbit_proteasome_uniprot_rabbitseqs_M13[0-9]_msgfdbIDs\\.txt")){ System.out.println("file is: " + current.getName()); ProteinIDExtractor IDS = new ProteinIDExtractor("../mixture_linked/database/rabbit_uniprot_allproteins_plusDecoy.fasta" , directory+"/"+current.getName()); IDS.printProteins(printDecoy); } } } public static void main(String[] args){ ProteinIDExtractor IDS = new ProteinIDExtractor("../mixture_linked/database/UPS2.fasta" , "../mixture_linked/18476_REP3_400fmol_UPS2_500ugHumanLysate_peakview - Peptides.txt"); IDS.getPeptideReport(); //IDS.getProteinReport(); //IDS.printProteins(false); //IDS.getPeptidePairReport(); //extractProteinsFromResultFiles("../mixture_linked/"); } }
[ "bugouzhi@gmail.com" ]
bugouzhi@gmail.com