hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e0a2f9f556035b99df55aae206af3cda8638e69 | 3,758 | java | Java | zabbix-wrapper/monitoring-pillar-domain/src/main/java/it/reply/monitoringpillar/domain/dsl/monitoring/pillar/wrapper/paas/MonitoringPillarEventCallbackResponse.java | damian1976/Monitoring | 8db17c5b2028882c2d658ac5257acd1c7173c3c4 | [
"Apache-2.0"
] | 4 | 2016-10-04T10:38:08.000Z | 2021-05-04T18:49:27.000Z | zabbix-wrapper/monitoring-pillar-domain/src/main/java/it/reply/monitoringpillar/domain/dsl/monitoring/pillar/wrapper/paas/MonitoringPillarEventCallbackResponse.java | damian1976/Monitoring | 8db17c5b2028882c2d658ac5257acd1c7173c3c4 | [
"Apache-2.0"
] | 37 | 2016-07-15T16:30:59.000Z | 2021-12-14T21:07:09.000Z | zabbix-wrapper/monitoring-pillar-domain/src/main/java/it/reply/monitoringpillar/domain/dsl/monitoring/pillar/wrapper/paas/MonitoringPillarEventCallbackResponse.java | damian1976/Monitoring | 8db17c5b2028882c2d658ac5257acd1c7173c3c4 | [
"Apache-2.0"
] | 3 | 2019-01-24T03:05:20.000Z | 2019-10-29T15:25:38.000Z | 22.775758 | 87 | 0.722991 | 4,319 | package it.reply.monitoringpillar.domain.dsl.monitoring.pillar.wrapper.paas;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({ "serviceId", "status", "vmuuid", "vmName", "tenant", "ip", "time",
"description" })
public class MonitoringPillarEventCallbackResponse implements Serializable {
private static final long serialVersionUID = -8425673865503069848L;
@JsonProperty("serviceId")
private String serviceId;
@JsonProperty("status")
private String status;
@JsonProperty("vmuuid")
private String vmuuid;
@JsonProperty("vmName")
private String vmName;
@JsonProperty("tenant")
private String tenant;
@JsonProperty("ip")
private String ip;
@JsonProperty("metricName")
private String metricName;
@JsonProperty("triggerName")
private String triggerName;
@JsonProperty("description")
private String description;
@JsonProperty("time")
private Long time;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("serviceId")
public String getServiceId() {
return serviceId;
}
@JsonProperty("serviceId")
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
@JsonProperty("status")
public String getStatus() {
return status;
}
@JsonProperty("status")
public void setStatus(String status) {
this.status = status;
}
@JsonProperty("vmuuid")
public String getVmuuid() {
return vmuuid;
}
@JsonProperty("vmuuid")
public void setVmuuid(String vmuuid) {
this.vmuuid = vmuuid;
}
@JsonProperty("vmName")
public String getVmName() {
return vmName;
}
@JsonProperty("vmName")
public void setVmName(String vmName) {
this.vmName = vmName;
}
@JsonProperty("tenant")
public String getTenant() {
return tenant;
}
@JsonProperty("tenant")
public void setTenant(String tenant) {
this.tenant = tenant;
}
@JsonProperty("ip")
public String getIp() {
return ip;
}
@JsonProperty("ip")
public void setIp(String ip) {
this.ip = ip;
}
@JsonProperty("metricName")
public String getMetricName() {
return metricName;
}
@JsonProperty("metricName")
public void setMetricName(String metricName) {
this.metricName = metricName;
}
@JsonProperty("triggerName")
public String geTriggerName() {
return triggerName;
}
@JsonProperty("triggerName")
public void setTriggerName(String triggerName) {
this.triggerName = triggerName;
}
@JsonProperty("description")
public String getDescription() {
return description;
}
@JsonProperty("description")
public void setDescription(String description) {
this.description = description;
}
@JsonProperty("time")
public Long getTime() {
return time;
}
@JsonProperty("time")
public void setTime(Long time) {
this.time = time;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
3e0a31407be836cc60cc1b76f45969a6aa71e5aa | 1,657 | java | Java | app/src/main/java/pl/karoldabrowski/newsapp/ArticleAdapter.java | karol-dabrowski/news-app | 9de3c79469b3e63ccc51ce9d2328828a2afdf4b4 | [
"MIT"
] | null | null | null | app/src/main/java/pl/karoldabrowski/newsapp/ArticleAdapter.java | karol-dabrowski/news-app | 9de3c79469b3e63ccc51ce9d2328828a2afdf4b4 | [
"MIT"
] | null | null | null | app/src/main/java/pl/karoldabrowski/newsapp/ArticleAdapter.java | karol-dabrowski/news-app | 9de3c79469b3e63ccc51ce9d2328828a2afdf4b4 | [
"MIT"
] | null | null | null | 33.14 | 94 | 0.697043 | 4,320 | package pl.karoldabrowski.newsapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class ArticleAdapter extends ArrayAdapter<Article> {
public ArticleAdapter(@NonNull Context context, List<Article> articles) {
super(context, 0, articles);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Article currentArticle = getItem(position);
TextView articleTitle = listItemView.findViewById(R.id.article_title);
articleTitle.setText(currentArticle.getTitle());
if(currentArticle.hasAuthor()) {
TextView articleAuthor = listItemView.findViewById(R.id.article_author);
articleAuthor.setText(currentArticle.getAuthor());
}
TextView articleSection = listItemView.findViewById(R.id.article_section);
articleSection.setText(currentArticle.getSection());
if(currentArticle.hasDate()) {
TextView articleDate = listItemView.findViewById(R.id.article_date);
articleDate.setText(currentArticle.getDate().replace('T', ' ').replace("Z", ""));
}
return listItemView;
}
}
|
3e0a316fee6754e6b2e6bc1aeb883d7b13b8ea63 | 239 | java | Java | src/com/aaron/strategy/Plus.java | cdcdec/DesignPatterns | b2a0dfd98f256db13654de30556a47858568e81b | [
"Apache-2.0"
] | null | null | null | src/com/aaron/strategy/Plus.java | cdcdec/DesignPatterns | b2a0dfd98f256db13654de30556a47858568e81b | [
"Apache-2.0"
] | null | null | null | src/com/aaron/strategy/Plus.java | cdcdec/DesignPatterns | b2a0dfd98f256db13654de30556a47858568e81b | [
"Apache-2.0"
] | null | null | null | 18.384615 | 69 | 0.690377 | 4,321 | package com.aaron.strategy;
/** 实现类 **/
public class Plus extends AbstractCalculator implements ICalculator {
@Override
public int calculate(String exp) {
int arrayInt[] = split(exp, "\\+");
return arrayInt[0] + arrayInt[1];
}
}
|
3e0a3377ace879f5d9fe8aab1d6d924a025fb867 | 933 | java | Java | app/src/main/java/com/example/bearapp/hostlive/HostControlState.java | zhengwanshi/BearApp | 6508281d67b5df0e1ae2530b450545c8e7e4c329 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/bearapp/hostlive/HostControlState.java | zhengwanshi/BearApp | 6508281d67b5df0e1ae2530b450545c8e7e4c329 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/bearapp/hostlive/HostControlState.java | zhengwanshi/BearApp | 6508281d67b5df0e1ae2530b450545c8e7e4c329 | [
"Apache-2.0"
] | null | null | null | 20.282609 | 55 | 0.646302 | 4,322 | package com.example.bearapp.hostlive;
import com.tencent.ilivesdk.ILiveConstants;
/**
* Created by zhengyg on 2018/3/24.
*/
public class HostControlState {
private boolean isBeautyOn = false;
private boolean isFlashOn = false;
private boolean isVoiceOn = true;
private int cameraid = ILiveConstants.FRONT_CAMERA;
public boolean isBeautyOn() {
return isBeautyOn;
}
public void setBeautyOn(boolean beautyOn) {
isBeautyOn = beautyOn;
}
public boolean isFlashOn() {
return isFlashOn;
}
public void setFlashOn(boolean flashOn) {
isFlashOn = flashOn;
}
public boolean isVoiceOn() {
return isVoiceOn;
}
public void setVoiceOn(boolean voiceOn) {
isVoiceOn = voiceOn;
}
public int getCameraid() {
return cameraid;
}
public void setCameraid(int cameraid) {
this.cameraid = cameraid;
}
}
|
3e0a33cbb4dde6d51158f8e6254a61d125549f30 | 1,841 | java | Java | src/main/java/de/uniks/networkparser/logic/IdFilterElements.java | fujaba/NetworkParser | d690c9bf664358e249897a226f595585736b4a35 | [
"MIT"
] | 9 | 2015-06-28T20:12:07.000Z | 2019-03-27T13:11:14.000Z | src/main/java/de/uniks/networkparser/logic/IdFilterElements.java | fujaba/NetworkParser | d690c9bf664358e249897a226f595585736b4a35 | [
"MIT"
] | 15 | 2015-07-01T06:51:41.000Z | 2019-10-18T05:46:58.000Z | src/main/java/de/uniks/networkparser/logic/IdFilterElements.java | fujaba/NetworkParser | d690c9bf664358e249897a226f595585736b4a35 | [
"MIT"
] | 6 | 2016-06-10T20:32:50.000Z | 2019-09-30T05:42:49.000Z | 35.403846 | 84 | 0.789245 | 4,323 | package de.uniks.networkparser.logic;
/*
NetworkParser
The MIT License
Copyright (c) 2010-2016 Stefan Lindel https://www.github.com/fujaba/NetworkParser/
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.
*/
import java.beans.PropertyChangeEvent;
import de.uniks.networkparser.interfaces.ObjectCondition;
import de.uniks.networkparser.list.SimpleSet;
public class IdFilterElements extends SimpleSet<Object> implements ObjectCondition {
private ObjectCondition condition;
public IdFilterElements(ObjectCondition condition) {
this.condition = condition;
}
public IdFilterElements(Class<?> clazzConditon) {
this.condition = InstanceOf.create(clazzConditon);
}
@Override
public boolean update(Object evt) {
if (condition != null) {
if (condition.update(evt)) {
return add(((PropertyChangeEvent) evt).getNewValue());
}
}
return false;
}
}
|
3e0a34955e0252493c21eed6efda7d748d428ca4 | 14,850 | java | Java | web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java | CangYaCommunity2022/spring-security | 4c5d404c46167f1c8660dd38324a6a8b8d43cfd3 | [
"Apache-2.0"
] | 2 | 2019-09-02T05:12:19.000Z | 2019-12-13T07:53:44.000Z | web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java | CangYaCommunity2022/spring-security | 4c5d404c46167f1c8660dd38324a6a8b8d43cfd3 | [
"Apache-2.0"
] | null | null | null | web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java | CangYaCommunity2022/spring-security | 4c5d404c46167f1c8660dd38324a6a8b8d43cfd3 | [
"Apache-2.0"
] | null | null | null | 50.510204 | 116 | 0.8167 | 4,324 | /*
* Copyright 2002-2019 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
*
* 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 org.springframework.security.web.authentication;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationManagerResolver;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
/**
* @author Sergey Bespalov
* @since 5.2.0
*/
@ExtendWith(MockitoExtension.class)
public class AuthenticationFilterTests {
@Mock
private AuthenticationSuccessHandler successHandler;
@Mock
private AuthenticationConverter authenticationConverter;
@Mock
private AuthenticationManager authenticationManager;
@Mock
private AuthenticationFailureHandler failureHandler;
@Mock
private AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver;
@Mock
private RequestMatcher requestMatcher;
private void givenResolveWillReturnAuthenticationManager() {
given(this.authenticationManagerResolver.resolve(any())).willReturn(this.authenticationManager);
}
@AfterEach
public void clearContext() {
SecurityContextHolder.clearContext();
}
@Test
public void filterWhenDefaultsAndNoAuthenticationThenContinues() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verifyZeroInteractions(this.authenticationManager);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void filterWhenAuthenticationManagerResolverDefaultsAndNoAuthenticationThenContinues() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verifyZeroInteractions(this.authenticationManagerResolver);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void filterWhenDefaultsAndAuthenticationSuccessThenContinues() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(this.authenticationManager).authenticate(any(Authentication.class));
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
}
@Test
public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationSuccessThenContinues()
throws Exception {
givenResolveWillReturnAuthenticationManager();
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(this.authenticationManager).authenticate(any(Authentication.class));
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
}
@Test
public void filterWhenDefaultsAndAuthenticationFailThenUnauthorized() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willThrow(new BadCredentialsException("failed"));
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationFailThenUnauthorized()
throws Exception {
givenResolveWillReturnAuthenticationManager();
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willThrow(new BadCredentialsException("failed"));
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void filterWhenConvertEmptyThenOk() throws Exception {
given(this.authenticationConverter.convert(any())).willReturn(null);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, new MockHttpServletResponse(), chain);
verifyZeroInteractions(this.authenticationManagerResolver);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void filterWhenConvertAndAuthenticationSuccessThenSuccess() throws Exception {
givenResolveWillReturnAuthenticationManager();
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
filter.setSuccessHandler(this.successHandler);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(this.successHandler).onAuthenticationSuccess(any(), any(), any(), eq(authentication));
verifyZeroInteractions(this.failureHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
}
@Test
public void filterWhenConvertAndAuthenticationEmptyThenServerError() throws Exception {
givenResolveWillReturnAuthenticationManager();
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(null);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
filter.setSuccessHandler(this.successHandler);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
assertThatExceptionOfType(ServletException.class).isThrownBy(() -> filter.doFilter(request, response, chain));
verifyZeroInteractions(this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void filterWhenNotMatchAndConvertAndAuthenticationSuccessThenContinues() throws Exception {
given(this.requestMatcher.matches(any())).willReturn(false);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
filter.setRequestMatcher(this.requestMatcher);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verifyZeroInteractions(this.authenticationConverter, this.authenticationManagerResolver, this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
// gh-7446
@Test
public void filterWhenSuccessfulAuthenticationThenSessionIdChanges() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
MockHttpSession session = new MockHttpSession();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain();
String sessionId = session.getId();
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
filter.doFilter(request, response, chain);
assertThat(session.getId()).isNotEqualTo(sessionId);
}
@Test
public void filterWhenSuccessfulAuthenticationThenNoSessionCreated() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain();
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
filter.doFilter(request, response, chain);
assertThat(request.getSession(false)).isNull();
}
@Test
public void filterWhenCustomSecurityContextRepositoryAndSuccessfulAuthenticationRepositoryUsed() throws Exception {
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
ArgumentCaptor<SecurityContext> securityContextArg = ArgumentCaptor.forClass(SecurityContext.class);
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain();
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
filter.setSecurityContextRepository(securityContextRepository);
filter.doFilter(request, response, chain);
verify(securityContextRepository).saveContext(securityContextArg.capture(), eq(request), eq(response));
assertThat(securityContextArg.getValue().getAuthentication()).isEqualTo(authentication);
}
}
|
3e0a34e7d507a762c1d3a9bb1425524f39d7c261 | 368 | java | Java | sample/src/androidTest/java/de/timfreiheit/mathjax/android/sample/ApplicationTest.java | timfreiheit/MathJaxAndroid | ad49902b2e1d57dca1956ce22e72cec05a55563f | [
"MIT"
] | 20 | 2015-12-17T19:23:00.000Z | 2021-10-12T05:00:01.000Z | sample/src/androidTest/java/de/timfreiheit/mathjax/android/sample/ApplicationTest.java | timfreiheit/MathJaxAndroid | ad49902b2e1d57dca1956ce22e72cec05a55563f | [
"MIT"
] | 5 | 2016-08-27T04:22:19.000Z | 2017-08-19T14:14:33.000Z | sample/src/androidTest/java/de/timfreiheit/mathjax/android/sample/ApplicationTest.java | timfreiheit/MathJaxAndroid | ad49902b2e1d57dca1956ce22e72cec05a55563f | [
"MIT"
] | 4 | 2017-04-19T10:12:21.000Z | 2021-07-01T19:15:28.000Z | 28.307692 | 93 | 0.758152 | 4,325 | package de.timfreiheit.mathjax.android.sample;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} |
3e0a35bae04b5fb5264b1462763100a9330a5e3d | 6,785 | java | Java | corpus/class/eclipse.jdt.core/4249.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 15 | 2018-07-10T09:38:31.000Z | 2021-11-29T08:28:07.000Z | corpus/class/eclipse.jdt.core/4249.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 3 | 2018-11-16T02:58:59.000Z | 2021-01-20T16:03:51.000Z | corpus/class/eclipse.jdt.core/4249.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 6 | 2018-06-27T20:19:00.000Z | 2022-02-19T02:29:53.000Z | 41.613497 | 161 | 0.717087 | 4,326 | /*******************************************************************************
* Copyright (c) 2007, 2015 BEA Systems, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* ychag@example.com - initial API and implementation
*
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.apt.dispatch;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jdt.internal.compiler.AbstractAnnotationProcessorManager;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
/**
* This class is the central dispatch point for Java 6 annotation processing.
* This is created and configured by the JDT core; specifics depend on how
* compilation is being performed, ie from the command line, via the Tool
* interface, or within the IDE. This class manages the discovery of annotation
* processors and other information spanning multiple rounds of processing;
* context that is valid only within a single round is managed by
* {@link RoundDispatcher}. There may be multiple instances of this class;
* there is in general one of these for every Compiler that has annotation
* processing enabled. Within the IDE there will typically be one for every
* Java project, because each project potentially has a separate processor path.
*
* TODO: do something useful with _supportedOptions and _supportedAnnotationTypes.
*/
public abstract class BaseAnnotationProcessorManager extends AbstractAnnotationProcessorManager implements IProcessorProvider {
protected PrintWriter _out;
protected PrintWriter _err;
protected BaseProcessingEnvImpl _processingEnv;
protected boolean _isFirstRound = true;
/**
* The list of processors that have been loaded so far. A processor on this
* list has been initialized, but may not yet have been called to process().
*/
protected List<ProcessorInfo> _processors = new ArrayList();
// Tracing
protected boolean _printProcessorInfo = false;
protected boolean _printRounds = false;
protected int _round;
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.AbstractAnnotationProcessorManager#configure(org.eclipse.jdt.internal.compiler.batch.Main, java.lang.String[])
*/
@Override
public void configure(Object batchCompiler, String[] options) {
// Implemented by BatchAnnotationProcessorManager.
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.AbstractAnnotationProcessorManager#configureFromPlatform(org.eclipse.jdt.internal.compiler.Compiler, java.lang.Object)
*/
@Override
public void configureFromPlatform(Compiler compiler, Object compilationUnitLocator, Object javaProject) {
// Implemented by IdeAnnotationProcessorManager.
throw new UnsupportedOperationException();
}
@Override
public List<ProcessorInfo> getDiscoveredProcessors() {
return _processors;
}
@Override
public ICompilationUnit[] getDeletedUnits() {
return _processingEnv.getDeletedUnits();
}
@Override
public ICompilationUnit[] getNewUnits() {
return _processingEnv.getNewUnits();
}
@Override
public ReferenceBinding[] getNewClassFiles() {
return _processingEnv.getNewClassFiles();
}
@Override
public void reset() {
_processingEnv.reset();
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.AbstractAnnotationProcessorManager#setErr(java.io.PrintWriter)
*/
@Override
public void setErr(PrintWriter err) {
_err = err;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.AbstractAnnotationProcessorManager#setOut(java.io.PrintWriter)
*/
@Override
public void setOut(PrintWriter out) {
_out = out;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.AbstractAnnotationProcessorManager#setProcessors(java.lang.Object[])
*/
@Override
public void setProcessors(Object[] processors) {
// Only meaningful in batch mode.
throw new UnsupportedOperationException();
}
/**
* A single "round" of processing, in the sense implied in
* {@link javax.annotation.processing.Processor}.
* <p>
* The Java 6 Processor spec contains ambiguities about how processors that support "*" are
* handled. Eclipse tries to match Sun's implementation in javac. What that actually does is
* analogous to inspecting the set of annotions found in the root units and adding an
* "imaginary" annotation if the set is empty. Processors are then called in order of discovery;
* for each processor, the intersection between the set of root annotations and the set of
* annotations the processor supports is calculated, and if it is non-empty, the processor is
* called. If the processor returns <code>true</code> then the intersection (including the
* imaginary annotation if one exists) is removed from the set of root annotations and the loop
* continues, until the set is empty. Of course, the imaginary annotation is not actually
* included in the set of annotations passed in to the processor. A processor's process() method
* is not called until its intersection set is non-empty, but thereafter it is called on every
* round. Note that even if a processor is not called in the first round, if it is called in
* subsequent rounds, it will be called in the order in which the processors were discovered,
* rather than being added to the end of the list.
*/
@Override
public void processAnnotations(CompilationUnitDeclaration[] units, ReferenceBinding[] referenceBindings, boolean isLastRound) {
RoundEnvImpl roundEnv = new RoundEnvImpl(units, referenceBindings, isLastRound, _processingEnv);
if (_isFirstRound) {
_isFirstRound = false;
}
PrintWriter traceProcessorInfo = _printProcessorInfo ? _out : null;
PrintWriter traceRounds = _printRounds ? _out : null;
if (traceRounds != null) {
//$NON-NLS-1$
traceRounds.println("Round " + ++_round + ':');
}
RoundDispatcher dispatcher = new RoundDispatcher(this, roundEnv, roundEnv.getRootAnnotations(), traceProcessorInfo, traceRounds);
dispatcher.round();
}
}
|
3e0a35e18f5777e0de5587ffd7e9ed86ec21228c | 1,109 | java | Java | dragonshard-dynamic-datasource-starter/src/main/java/net/dragonshard/dsf/dynamic/datasource/strategy/DynamicDataSourceStrategy.java | mayee/dragonshard | f1a15b0d99c670a80a573bc04c0c7247ef2dbd40 | [
"Apache-2.0"
] | 15 | 2019-07-24T05:34:34.000Z | 2021-01-13T09:17:36.000Z | dragonshard-dynamic-datasource-starter/src/main/java/net/dragonshard/dsf/dynamic/datasource/strategy/DynamicDataSourceStrategy.java | mayee/dragonshard | f1a15b0d99c670a80a573bc04c0c7247ef2dbd40 | [
"Apache-2.0"
] | 3 | 2019-08-13T12:10:34.000Z | 2020-01-12T07:38:39.000Z | dragonshard-dynamic-datasource-starter/src/main/java/net/dragonshard/dsf/dynamic/datasource/strategy/DynamicDataSourceStrategy.java | mayee/dragonshard | f1a15b0d99c670a80a573bc04c0c7247ef2dbd40 | [
"Apache-2.0"
] | 8 | 2019-08-13T06:07:24.000Z | 2022-02-11T02:21:10.000Z | 30.805556 | 77 | 0.735798 | 4,327 | /*
* Copyright 1999-2018 dragonshard.net.
* 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.dragonshard.dsf.dynamic.datasource.strategy;
import java.util.List;
import javax.sql.DataSource;
/**
* 多数据源选择策略接口 一般默认为负载均衡策略,默认提供了一个随机策略
*
* @author TaoYu Kanyuxia
* @see RandomDynamicDataSourceStrategy
* @see LoadBalanceDynamicDataSourceStrategy
* @since 1.0.0
*/
public interface DynamicDataSourceStrategy {
/**
* 决定当前数据源
*
* @param dataSources 数据源选择库
* @return dataSource 所选择的数据源
*/
DataSource determineDataSource(List<DataSource> dataSources);
}
|
3e0a3640b32c0a3a1fbff1c27fd733dc89555b02 | 1,540 | java | Java | activityresult/src/main/java/com/hss01248/activityresult/EmptyFragment.java | hss01248/StartActivityResult | 05f19491eb2e3f15e0c5bdcedd7118552b8e3686 | [
"Apache-2.0"
] | null | null | null | activityresult/src/main/java/com/hss01248/activityresult/EmptyFragment.java | hss01248/StartActivityResult | 05f19491eb2e3f15e0c5bdcedd7118552b8e3686 | [
"Apache-2.0"
] | null | null | null | activityresult/src/main/java/com/hss01248/activityresult/EmptyFragment.java | hss01248/StartActivityResult | 05f19491eb2e3f15e0c5bdcedd7118552b8e3686 | [
"Apache-2.0"
] | null | null | null | 32.083333 | 87 | 0.672727 | 4,328 | package com.hss01248.activityresult;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
/*
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.contract.ActivityResultContract;*/
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.hss01248.transfrag.BaseTransFragment;
public class EmptyFragment extends BaseTransFragment<Intent> {
ActivityResultListener listener;
public EmptyFragment(FragmentActivity activity, Intent o) {
super(activity, o);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* registerForActivityResult(new ActivityResultContract<Object, Intent>() {
@NonNull
@Override
public Intent createIntent(@NonNull Context context, Object input) {
return bean;
}
@Override
public Intent parseResult(int resultCode, @Nullable Intent intent) {
listener.onActivityResult(0,resultCode,intent);
finish();
return intent;
}
}, new ActivityResultCallback<Intent>() {
@Override
public void onActivityResult(Intent result) {
//Toast.makeText(activity,result.toString(),Toast.LENGTH_SHORT).show();
}
}).launch("");*/
}
}
|
3e0a367e2630d400547fc2723586979aa61bac87 | 6,194 | java | Java | hydra-main/src/main/java/com/addthis/hydra/job/SpawnMesh.java | worrel/hydra | d22953070b1a6c84d875d2d42e6fa6998f0eb789 | [
"Apache-2.0"
] | null | null | null | hydra-main/src/main/java/com/addthis/hydra/job/SpawnMesh.java | worrel/hydra | d22953070b1a6c84d875d2d42e6fa6998f0eb789 | [
"Apache-2.0"
] | null | null | null | hydra-main/src/main/java/com/addthis/hydra/job/SpawnMesh.java | worrel/hydra | d22953070b1a6c84d875d2d42e6fa6998f0eb789 | [
"Apache-2.0"
] | null | null | null | 33.301075 | 116 | 0.590249 | 4,329 | /*
* 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.addthis.hydra.job;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import com.addthis.basis.util.Bytes;
import com.addthis.basis.util.Parameter;
import com.addthis.codec.Codec;
import com.addthis.codec.CodecJSON;
import com.addthis.hydra.job.mq.CommandTaskKick;
import com.addthis.meshy.MeshyClient;
import com.addthis.meshy.MeshyClientConnector;
import com.addthis.meshy.service.message.MessageFileProvider;
import com.addthis.meshy.service.message.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Date: 10/22/12
* Time: 5:23 PM
* <p/>
* Attach Spawn to Mesh and present an API / Filesystem for Minions and others
*/
public class SpawnMesh implements MessageListener {
private static Logger log = LoggerFactory.getLogger(SpawnMesh.class);
private static Codec codec = new CodecJSON();
private static final String meshHost = Parameter.value("mesh.host", "localhost");
private static final int meshPort = Parameter.intValue("mesh.port", 0);
private static final int meshRetryTimeout = Parameter.intValue("mesh.retry.timeout", 5000);
private static boolean meshQueue = Parameter.boolValue("queue.mesh", false);
private final Spawn spawn;
private final String meshPrefix;
private MeshyClientConnector meshClient;
private MessageFileProvider provider;
private AtomicBoolean linkUp = new AtomicBoolean(false);
SpawnMesh(final Spawn spawn) {
this.spawn = spawn;
this.meshPrefix = "/spawn/" + spawn.getUuid();
if (meshPort == 0) {
if (!meshQueue) return;
throw new RuntimeException("invalid mesh port 0");
}
meshClient = new MeshyClientConnector(meshHost, meshPort, 1000, meshRetryTimeout) {
@Override
public void linkUp(MeshyClient client) {
log.warn("connected to mesh on " + client);
provider = new MessageFileProvider(client);
provider.setListener(meshPrefix + "/status", SpawnMesh.this);
provider.setListener(meshPrefix + "/shutdown", SpawnMesh.this);
provider.setListener(meshPrefix + "/task/get.config", SpawnMesh.this);
linkUp.set(true);
synchronized (this) { this.notifyAll(); }
}
@Override
public void linkDown(MeshyClient client) {
log.warn("disconnected from mesh on " + client);
linkUp.set(false);
}
};
}
public void waitLinkUp() {
while (!linkUp.get()) {
synchronized (meshClient) {
try {
meshClient.wait(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
public MeshyClient getClient() {
return meshClient.getClient();
}
private String getString(Map<String, String> map, String key, String defVal) {
try {
String v = map.get(key);
return v != null ? v : defVal;
} catch (Exception ex) {
return defVal;
}
}
private int getInt(Map<String, String> map, String key, int defVal) {
try {
return Integer.parseInt(map.get(key));
} catch (Exception ex) {
return defVal;
}
}
@Override
public void requestContents(String fileName, Map<String, String> options, OutputStream out) throws IOException {
if (fileName.endsWith("/status")) {
send(out, spawn);
} else if (fileName.endsWith("/shutdown")) {
if (options != null && options.containsKey("yes")) {
send(out, "shutting down");
System.exit(1);
} else {
send(out, "ignored. send yes=1 to initiate shutdown");
}
} else if (fileName.endsWith("/job/list")) {
// TODO
send(out, "TODO");
} else if (fileName.endsWith("/task/get.config")) {
if (options != null && options.containsKey("job") && options.containsKey("task")) {
Job job = spawn.getJob(options.get("job"));
JobTask task = spawn.getTask(job.getId(), getInt(options, "task", -1));
CommandTaskKick kick = spawn.getCommandTaskKick(job, task);
if (kick == null) {
send(out, "{error:'no such job or task'}");
} else {
send(out, kick);
}
} else {
send(out, "{error:'missing job and/or task parameters'}");
}
}
}
private void send(OutputStream out, String msg) {
try {
out.write(Bytes.toBytes(msg));
out.write('\n');
out.close();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private void send(OutputStream out, Codec.Codable msg) {
try {
out.write(codec.encode(msg));
out.write('\n');
out.close();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private void send(OutputStream out, byte msg[]) {
try {
out.write(msg);
out.close();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static String getMeshHost() {
return meshHost;
}
public static int getMeshPort() {
return meshPort;
}
}
|
3e0a36e841f32bf0304fcd182ad17a0e8559c98b | 413 | java | Java | src/main/java/com/xcyg/project/entity/SysUserRole.java | Doooogh/questionnaire | 9821ecb696d726dc8d8f61cece34541ab5874247 | [
"MIT"
] | null | null | null | src/main/java/com/xcyg/project/entity/SysUserRole.java | Doooogh/questionnaire | 9821ecb696d726dc8d8f61cece34541ab5874247 | [
"MIT"
] | 1 | 2022-02-09T22:26:09.000Z | 2022-02-09T22:26:09.000Z | src/main/java/com/xcyg/project/entity/SysUserRole.java | Doooogh/questionnaire | 9821ecb696d726dc8d8f61cece34541ab5874247 | [
"MIT"
] | null | null | null | 18.772727 | 51 | 0.767554 | 4,330 | package com.xcyg.project.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class SysUserRole implements Serializable {
@TableId(type = IdType.UUID)
private String id;
private String userId;
private String roleId;
private Date createTime;
} |
3e0a381f01248479496f17601ce3991c75ea2dea | 607 | java | Java | BASCore/src/main/java/com/photo/bas/core/vo/common/TagStatusReportOption.java | yufeng1982/PGMS | c05e9ce62c2706632a4e0723e94150e575bef0ac | [
"MIT"
] | null | null | null | BASCore/src/main/java/com/photo/bas/core/vo/common/TagStatusReportOption.java | yufeng1982/PGMS | c05e9ce62c2706632a4e0723e94150e575bef0ac | [
"MIT"
] | 4 | 2019-11-14T13:09:23.000Z | 2022-01-21T23:25:58.000Z | BASCore/src/main/java/com/photo/bas/core/vo/common/TagStatusReportOption.java | yufeng1982/PGMS | c05e9ce62c2706632a4e0723e94150e575bef0ac | [
"MIT"
] | null | null | null | 23.346154 | 70 | 0.714992 | 4,331 | package com.photo.bas.core.vo.common;
import java.util.EnumSet;
import com.photo.bas.core.model.entity.IEnum;
import com.photo.bas.core.utils.ResourceUtils;
public enum TagStatusReportOption implements IEnum {
Open, Closed;
public String getKey() {
return new StringBuffer().append("Com.").append(name()).toString();
}
@Override
public String getName() {
return name();
}
public static EnumSet<TagStatusReportOption> getOptionList() {
return EnumSet.allOf(TagStatusReportOption.class);
}
public String getText() {
return ResourceUtils.getText(getKey());
}
}
|
3e0a3a3cde662629448d39a4ef2f3678b5224c77 | 31,353 | java | Java | JavaSourceLearn/javafx-src/javafx/scene/control/TableCell.java | likuisuper/Java-Notes | e6cad954387c1fa9cef0ffb8f2f2aa9f7a857e99 | [
"Apache-2.0"
] | 1 | 2021-01-30T13:44:33.000Z | 2021-01-30T13:44:33.000Z | javafx-src/javafx/scene/control/TableCell.java | songningbo/jdk8source | 7458e994df5fc9519004e60d280b728b6736a978 | [
"Apache-2.0"
] | null | null | null | javafx-src/javafx/scene/control/TableCell.java | songningbo/jdk8source | 7458e994df5fc9519004e60d280b728b6736a978 | [
"Apache-2.0"
] | 1 | 2022-01-13T06:59:10.000Z | 2022-01-13T06:59:10.000Z | 38.422794 | 125 | 0.535355 | 4,332 | /*
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javafx.scene.control;
import javafx.css.PseudoClass;
import javafx.beans.InvalidationListener;
import javafx.beans.WeakInvalidationListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.event.Event;
import javafx.scene.AccessibleAction;
import javafx.scene.AccessibleAttribute;
import javafx.scene.AccessibleRole;
import javafx.scene.control.TableView.TableViewFocusModel;
import com.sun.javafx.scene.control.skin.TableCellSkin;
import javafx.collections.WeakListChangeListener;
import java.lang.ref.WeakReference;
import java.util.List;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.scene.control.TableColumn.CellEditEvent;
/**
* Represents a single row/column intersection in a {@link TableView}. To
* represent this intersection, a TableCell contains an
* {@link #indexProperty() index} property, as well as a
* {@link #tableColumnProperty() tableColumn} property. In addition, a TableCell
* instance knows what {@link TableRow} it exists in.
*
* <p><strong>A note about selection:</strong> A TableCell visually shows it is
* selected when two conditions are met:
* <ol>
* <li>The {@link TableSelectionModel#isSelected(int, TableColumnBase)} method
* returns true for the row / column that this cell represents, and</li>
* <li>The {@link javafx.scene.control.TableSelectionModel#cellSelectionEnabledProperty() cell selection mode}
* property is set to true (to represent that it is allowable to select
* individual cells (and not just rows of cells)).</li>
* </ol>
* </p>
*
* @see TableView
* @see TableColumn
* @see Cell
* @see IndexedCell
* @see TableRow
* @param <S> The type of the TableView generic type (i.e. S == TableView<S>).
* This should also match with the first generic type in TableColumn.
* @param <T> The type of the item contained within the Cell.
* @since JavaFX 2.0
*/
public class TableCell<S,T> extends IndexedCell<T> {
/***************************************************************************
* *
* Constructors *
* *
**************************************************************************/
/**
* Constructs a default TableCell instance with a style class of 'table-cell'
*/
public TableCell() {
getStyleClass().addAll(DEFAULT_STYLE_CLASS);
setAccessibleRole(AccessibleRole.TABLE_CELL);
updateColumnIndex();
}
/***************************************************************************
* *
* Private fields *
* *
**************************************************************************/
// package for testing
boolean lockItemOnEdit = false;
/***************************************************************************
* *
* Callbacks and Events *
* *
**************************************************************************/
private boolean itemDirty = false;
/*
* This is the list observer we use to keep an eye on the SelectedCells
* ObservableList in the table view. Because it is possible that the table can
* be mutated, we create this observer here, and add/remove it from the
* storeTableView method.
*/
private ListChangeListener<TablePosition> selectedListener = c -> {
while (c.next()) {
if (c.wasAdded() || c.wasRemoved()) {
updateSelection();
}
}
};
// same as above, but for focus
private final InvalidationListener focusedListener = value -> {
updateFocus();
};
// same as above, but for for changes to the properties on TableRow
private final InvalidationListener tableRowUpdateObserver = value -> {
itemDirty = true;
requestLayout();
};
private final InvalidationListener editingListener = value -> {
updateEditing();
};
private ListChangeListener<TableColumn<S,?>> visibleLeafColumnsListener = c -> {
updateColumnIndex();
};
private ListChangeListener<String> columnStyleClassListener = c -> {
while (c.next()) {
if (c.wasRemoved()) {
getStyleClass().removeAll(c.getRemoved());
}
if (c.wasAdded()) {
getStyleClass().addAll(c.getAddedSubList());
}
}
};
private final InvalidationListener columnStyleListener = value -> {
if (getTableColumn() != null) {
possiblySetStyle(getTableColumn().getStyle());
}
};
private final InvalidationListener columnIdListener = value -> {
if (getTableColumn() != null) {
possiblySetId(getTableColumn().getId());
}
};
private final WeakListChangeListener<TablePosition> weakSelectedListener =
new WeakListChangeListener<>(selectedListener);
private final WeakInvalidationListener weakFocusedListener =
new WeakInvalidationListener(focusedListener);
private final WeakInvalidationListener weaktableRowUpdateObserver =
new WeakInvalidationListener(tableRowUpdateObserver);
private final WeakInvalidationListener weakEditingListener =
new WeakInvalidationListener(editingListener);
private final WeakInvalidationListener weakColumnStyleListener =
new WeakInvalidationListener(columnStyleListener);
private final WeakInvalidationListener weakColumnIdListener =
new WeakInvalidationListener(columnIdListener);
private final WeakListChangeListener<TableColumn<S,?>> weakVisibleLeafColumnsListener =
new WeakListChangeListener<>(visibleLeafColumnsListener);
private final WeakListChangeListener<String> weakColumnStyleClassListener =
new WeakListChangeListener<String>(columnStyleClassListener);
/***************************************************************************
* *
* Properties *
* *
**************************************************************************/
// --- TableColumn
private ReadOnlyObjectWrapper<TableColumn<S,T>> tableColumn = new ReadOnlyObjectWrapper<TableColumn<S,T>>() {
@Override protected void invalidated() {
updateColumnIndex();
}
@Override public Object getBean() {
return TableCell.this;
}
@Override public String getName() {
return "tableColumn";
}
};
/**
* The TableColumn instance that backs this TableCell.
*/
public final ReadOnlyObjectProperty<TableColumn<S,T>> tableColumnProperty() { return tableColumn.getReadOnlyProperty(); }
private void setTableColumn(TableColumn<S,T> value) { tableColumn.set(value); }
public final TableColumn<S,T> getTableColumn() { return tableColumn.get(); }
// --- TableView
private ReadOnlyObjectWrapper<TableView<S>> tableView;
private void setTableView(TableView<S> value) {
tableViewPropertyImpl().set(value);
}
public final TableView<S> getTableView() {
return tableView == null ? null : tableView.get();
}
/**
* The TableView associated with this TableCell.
*/
public final ReadOnlyObjectProperty<TableView<S>> tableViewProperty() {
return tableViewPropertyImpl().getReadOnlyProperty();
}
private ReadOnlyObjectWrapper<TableView<S>> tableViewPropertyImpl() {
if (tableView == null) {
tableView = new ReadOnlyObjectWrapper<TableView<S>>() {
private WeakReference<TableView<S>> weakTableViewRef;
@Override protected void invalidated() {
TableView.TableViewSelectionModel<S> sm;
TableViewFocusModel<S> fm;
if (weakTableViewRef != null) {
cleanUpTableViewListeners(weakTableViewRef.get());
}
if (get() != null) {
sm = get().getSelectionModel();
if (sm != null) {
sm.getSelectedCells().addListener(weakSelectedListener);
}
fm = get().getFocusModel();
if (fm != null) {
fm.focusedCellProperty().addListener(weakFocusedListener);
}
get().editingCellProperty().addListener(weakEditingListener);
get().getVisibleLeafColumns().addListener(weakVisibleLeafColumnsListener);
weakTableViewRef = new WeakReference<TableView<S>>(get());
}
updateColumnIndex();
}
@Override public Object getBean() {
return TableCell.this;
}
@Override public String getName() {
return "tableView";
}
};
}
return tableView;
}
// --- TableRow
/**
* The TableRow that this TableCell currently finds itself placed within.
* The TableRow may be null early in the TableCell lifecycle, in the period
* between the TableCell being instantiated and being set into an owner
* TableRow.
*/
private ReadOnlyObjectWrapper<TableRow> tableRow = new ReadOnlyObjectWrapper<TableRow>(this, "tableRow");
private void setTableRow(TableRow value) { tableRow.set(value); }
public final TableRow getTableRow() { return tableRow.get(); }
public final ReadOnlyObjectProperty<TableRow> tableRowProperty() { return tableRow; }
/***************************************************************************
* *
* Editing API *
* *
**************************************************************************/
/** {@inheritDoc} */
@Override public void startEdit() {
final TableView<S> table = getTableView();
final TableColumn<S,T> column = getTableColumn();
if (! isEditable() ||
(table != null && ! table.isEditable()) ||
(column != null && ! getTableColumn().isEditable())) {
return;
}
// We check the boolean lockItemOnEdit field here, as whilst we want to
// updateItem normally, when it comes to unit tests we can't have the
// item change in all circumstances.
if (! lockItemOnEdit) {
updateItem(-1);
}
// it makes sense to get the cell into its editing state before firing
// the event to listeners below, so that's what we're doing here
// by calling super.startEdit().
super.startEdit();
if (column != null) {
CellEditEvent<S,?> editEvent = new CellEditEvent<>(
table,
table.getEditingCell(),
TableColumn.editStartEvent(),
null
);
Event.fireEvent(column, editEvent);
}
}
/** {@inheritDoc} */
@Override public void commitEdit(T newValue) {
if (! isEditing()) return;
final TableView<S> table = getTableView();
if (table != null) {
// Inform the TableView of the edit being ready to be committed.
CellEditEvent editEvent = new CellEditEvent(
table,
table.getEditingCell(),
TableColumn.editCommitEvent(),
newValue
);
Event.fireEvent(getTableColumn(), editEvent);
}
// inform parent classes of the commit, so that they can switch us
// out of the editing state.
// This MUST come before the updateItem call below, otherwise it will
// call cancelEdit(), resulting in both commit and cancel events being
// fired (as identified in RT-29650)
super.commitEdit(newValue);
// update the item within this cell, so that it represents the new value
updateItem(newValue, false);
if (table != null) {
// reset the editing cell on the TableView
table.edit(-1, null);
// request focus back onto the table, only if the current focus
// owner has the table as a parent (otherwise the user might have
// clicked out of the table entirely and given focus to something else.
// It would be rude of us to request it back again.
ControlUtils.requestFocusOnControlOnlyIfCurrentFocusOwnerIsChild(table);
}
}
/** {@inheritDoc} */
@Override public void cancelEdit() {
if (! isEditing()) return;
final TableView<S> table = getTableView();
super.cancelEdit();
// reset the editing index on the TableView
if (table != null) {
TablePosition<S,?> editingCell = table.getEditingCell();
if (updateEditingIndex) table.edit(-1, null);
// request focus back onto the table, only if the current focus
// owner has the table as a parent (otherwise the user might have
// clicked out of the table entirely and given focus to something else.
// It would be rude of us to request it back again.
ControlUtils.requestFocusOnControlOnlyIfCurrentFocusOwnerIsChild(table);
CellEditEvent<S,?> editEvent = new CellEditEvent<>(
table,
editingCell,
TableColumn.editCancelEvent(),
null
);
Event.fireEvent(getTableColumn(), editEvent);
}
}
/* *************************************************************************
* *
* Overriding methods *
* *
**************************************************************************/
/** {@inheritDoc} */
@Override public void updateSelected(boolean selected) {
// copied from Cell, with the first conditional clause below commented
// out, as it is valid for an empty TableCell to be selected, as long
// as the parent TableRow is not empty (see RT-15529).
/*if (selected && isEmpty()) return;*/
if (getTableRow() == null || getTableRow().isEmpty()) return;
setSelected(selected);
}
/** {@inheritDoc} */
@Override protected Skin<?> createDefaultSkin() {
return new TableCellSkin<S,T>(this);
}
// @Override public void dispose() {
// cleanUpTableViewListeners(getTableView());
//
// if (currentObservableValue != null) {
// currentObservableValue.removeListener(weaktableRowUpdateObserver);
// }
//
// super.dispose();
// }
/* *************************************************************************
* *
* Private Implementation *
* *
**************************************************************************/
private void cleanUpTableViewListeners(TableView<S> tableView) {
if (tableView != null) {
TableView.TableViewSelectionModel<S> sm = tableView.getSelectionModel();
if (sm != null) {
sm.getSelectedCells().removeListener(weakSelectedListener);
}
TableViewFocusModel<S> fm = tableView.getFocusModel();
if (fm != null) {
fm.focusedCellProperty().removeListener(weakFocusedListener);
}
tableView.editingCellProperty().removeListener(weakEditingListener);
tableView.getVisibleLeafColumns().removeListener(weakVisibleLeafColumnsListener);
}
}
@Override void indexChanged(int oldIndex, int newIndex) {
super.indexChanged(oldIndex, newIndex);
// Ideally we would just use the following two lines of code, rather
// than the updateItem() call beneath, but if we do this we end up with
// RT-22428 where all the columns are collapsed.
// itemDirty = true;
// requestLayout();
updateItem(oldIndex);
updateSelection();
updateFocus();
}
private boolean isLastVisibleColumn = false;
private int columnIndex = -1;
private void updateColumnIndex() {
TableView<S> tv = getTableView();
TableColumn<S,T> tc = getTableColumn();
columnIndex = tv == null || tc == null ? -1 : tv.getVisibleLeafIndex(tc);
// update the pseudo class state regarding whether this is the last
// visible cell (i.e. the right-most).
isLastVisibleColumn = getTableColumn() != null &&
columnIndex != -1 &&
columnIndex == getTableView().getVisibleLeafColumns().size() - 1;
pseudoClassStateChanged(PSEUDO_CLASS_LAST_VISIBLE, isLastVisibleColumn);
}
private void updateSelection() {
/*
* This cell should be selected if the selection mode of the table
* is cell-based, and if the row and column that this cell represents
* is selected.
*
* If the selection mode is not cell-based, then the listener in the
* TableRow class might pick up the need to set an entire row to be
* selected.
*/
if (isEmpty()) return;
final boolean isSelected = isSelected();
if (! isInCellSelectionMode()) {
if (isSelected) {
updateSelected(false);
}
return;
}
final TableView<S> tableView = getTableView();
if (getIndex() == -1 || tableView == null) return;
TableSelectionModel<S> sm = tableView.getSelectionModel();
if (sm == null) {
updateSelected(false);
return;
}
boolean isSelectedNow = sm.isSelected(getIndex(), getTableColumn());
if (isSelected == isSelectedNow) return;
updateSelected(isSelectedNow);
}
private void updateFocus() {
final boolean isFocused = isFocused();
if (! isInCellSelectionMode()) {
if (isFocused) {
setFocused(false);
}
return;
}
final TableView<S> tableView = getTableView();
final TableRow<S> tableRow = getTableRow();
final int index = getIndex();
if (index == -1 || tableView == null || tableRow == null) return;
final TableViewFocusModel<S> fm = tableView.getFocusModel();
if (fm == null) {
setFocused(false);
return;
}
boolean isFocusedNow = fm != null && fm.isFocused(index, getTableColumn());
setFocused(isFocusedNow);
}
private void updateEditing() {
if (getIndex() == -1 || getTableView() == null) return;
TablePosition<S,?> editCell = getTableView().getEditingCell();
boolean match = match(editCell);
if (match && ! isEditing()) {
startEdit();
} else if (! match && isEditing()) {
// If my index is not the one being edited then I need to cancel
// the edit. The tricky thing here is that as part of this call
// I cannot end up calling list.edit(-1) the way that the standard
// cancelEdit method would do. Yet, I need to call cancelEdit
// so that subclasses which override cancelEdit can execute. So,
// I have to use a kind of hacky flag workaround.
updateEditingIndex = false;
cancelEdit();
updateEditingIndex = true;
}
}
private boolean updateEditingIndex = true;
private boolean match(TablePosition<S,?> pos) {
return pos != null && pos.getRow() == getIndex() && pos.getTableColumn() == getTableColumn();
}
private boolean isInCellSelectionMode() {
TableView<S> tableView = getTableView();
if (tableView == null) return false;
TableSelectionModel<S> sm = tableView.getSelectionModel();
return sm != null && sm.isCellSelectionEnabled();
}
/*
* This was brought in to fix the issue in RT-22077, namely that the
* ObservableValue was being GC'd, meaning that changes to the value were
* no longer being delivered. By extracting this value out of the method,
* it is now referred to from TableCell and will therefore no longer be
* GC'd.
*/
private ObservableValue<T> currentObservableValue = null;
private boolean isFirstRun = true;
private WeakReference<S> oldRowItemRef;
/*
* This is called when we think that the data within this TableCell may have
* changed. You'll note that this is a private function - it is only called
* when one of the triggers above call it.
*/
private void updateItem(int oldIndex) {
if (currentObservableValue != null) {
currentObservableValue.removeListener(weaktableRowUpdateObserver);
}
// get the total number of items in the data model
final TableView<S> tableView = getTableView();
final List<S> items = tableView == null ? FXCollections.<S>emptyObservableList() : tableView.getItems();
final TableColumn<S,T> tableColumn = getTableColumn();
final int itemCount = items == null ? -1 : items.size();
final int index = getIndex();
final boolean isEmpty = isEmpty();
final T oldValue = getItem();
final TableRow<S> tableRow = getTableRow();
final S rowItem = tableRow == null ? null : tableRow.getItem();
final boolean indexExceedsItemCount = index >= itemCount;
// there is a whole heap of reasons why we should just punt...
outer: if (indexExceedsItemCount ||
index < 0 ||
columnIndex < 0 ||
!isVisible() ||
tableColumn == null ||
!tableColumn.isVisible()) {
// RT-30484 We need to allow a first run to be special-cased to allow
// for the updateItem method to be called at least once to allow for
// the correct visual state to be set up. In particular, in RT-30484
// refer to Ensemble8PopUpTree.png - in this case the arrows are being
// shown as the new cells are instantiated with the arrows in the
// children list, and are only hidden in updateItem.
// RT-32621: There are circumstances where we need to updateItem,
// even when the index is greater than the itemCount. For example,
// RT-32621 identifies issues where a TreeTableView collapses a
// TreeItem but the custom cells remain visible. This is now
// resolved with the check for indexExceedsItemCount.
if ((!isEmpty && oldValue != null) || isFirstRun || indexExceedsItemCount) {
updateItem(null, true);
isFirstRun = false;
}
return;
} else {
currentObservableValue = tableColumn.getCellObservableValue(index);
final T newValue = currentObservableValue == null ? null : currentObservableValue.getValue();
// RT-35864 - if the index didn't change, then avoid calling updateItem
// unless the item has changed.
if (oldIndex == index) {
if (!isItemChanged(oldValue, newValue)) {
// RT-36670: we need to check the row item here to prevent
// the issue where the cell value and index doesn't change,
// but the backing row object does.
S oldRowItem = oldRowItemRef != null ? oldRowItemRef.get() : null;
if (oldRowItem != null && oldRowItem.equals(rowItem)) {
// RT-37054: we break out of the if/else code here and
// proceed with the code following this, so that we may
// still update references, listeners, etc as required//.
break outer;
}
}
}
updateItem(newValue, false);
}
oldRowItemRef = new WeakReference<>(rowItem);
if (currentObservableValue == null) {
return;
}
// add property change listeners to this item
currentObservableValue.addListener(weaktableRowUpdateObserver);
}
@Override protected void layoutChildren() {
if (itemDirty) {
updateItem(-1);
itemDirty = false;
}
super.layoutChildren();
}
/***************************************************************************
* *
* Expert API *
* *
**************************************************************************/
/**
* Updates the TableView associated with this TableCell. This is typically
* only done once when the TableCell is first added to the TableView.
*
* @expert This function is intended to be used by experts, primarily
* by those implementing new Skins. It is not common
* for developers or designers to access this function directly.
*/
public final void updateTableView(TableView tv) {
setTableView(tv);
}
/**
* Updates the TableRow associated with this TableCell.
*
* @expert This function is intended to be used by experts, primarily
* by those implementing new Skins. It is not common
* for developers or designers to access this function directly.
*/
public final void updateTableRow(TableRow tableRow) {
this.setTableRow(tableRow);
}
/**
* Updates the TableColumn associated with this TableCell.
*
* @expert This function is intended to be used by experts, primarily
* by those implementing new Skins. It is not common
* for developers or designers to access this function directly.
*/
public final void updateTableColumn(TableColumn col) {
// remove style class of existing table column, if it is non-null
TableColumn<S,T> oldCol = getTableColumn();
if (oldCol != null) {
oldCol.getStyleClass().removeListener(weakColumnStyleClassListener);
getStyleClass().removeAll(oldCol.getStyleClass());
oldCol.idProperty().removeListener(weakColumnIdListener);
oldCol.styleProperty().removeListener(weakColumnStyleListener);
String id = getId();
String style = getStyle();
if (id != null && id.equals(oldCol.getId())) {
setId(null);
}
if (style != null && style.equals(oldCol.getStyle())) {
setStyle("");
}
}
setTableColumn(col);
if (col != null) {
getStyleClass().addAll(col.getStyleClass());
col.getStyleClass().addListener(weakColumnStyleClassListener);
col.idProperty().addListener(weakColumnIdListener);
col.styleProperty().addListener(weakColumnStyleListener);
possiblySetId(col.getId());
possiblySetStyle(col.getStyle());
}
}
/***************************************************************************
* *
* Stylesheet Handling *
* *
**************************************************************************/
private static final String DEFAULT_STYLE_CLASS = "table-cell";
private static final PseudoClass PSEUDO_CLASS_LAST_VISIBLE =
PseudoClass.getPseudoClass("last-visible");
private void possiblySetId(String idCandidate) {
if (getId() == null || getId().isEmpty()) {
setId(idCandidate);
}
}
private void possiblySetStyle(String styleCandidate) {
if (getStyle() == null || getStyle().isEmpty()) {
setStyle(styleCandidate);
}
}
/***************************************************************************
* *
* Accessibility handling *
* *
**************************************************************************/
@Override
public Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters) {
switch (attribute) {
case ROW_INDEX: return getIndex();
case COLUMN_INDEX: return columnIndex;
case SELECTED: return isInCellSelectionMode() ? isSelected() : getTableRow().isSelected();
default: return super.queryAccessibleAttribute(attribute, parameters);
}
}
@Override
public void executeAccessibleAction(AccessibleAction action, Object... parameters) {
switch (action) {
case REQUEST_FOCUS: {
TableView<S> tableView = getTableView();
if (tableView != null) {
TableViewFocusModel<S> fm = tableView.getFocusModel();
if (fm != null) {
fm.focus(getIndex(), getTableColumn());
}
}
break;
}
default: super.executeAccessibleAction(action, parameters);
}
}
}
|
3e0a3bd25a279fc769f40b0680941a4b98be8008 | 521 | java | Java | src/top.chenqwwq/leetcode/hot100/_621/SolutionTest.java | CheNbXxx/_leetcode | d49786b376d7cf17e099af7dcda1a47866f7e194 | [
"Apache-2.0"
] | null | null | null | src/top.chenqwwq/leetcode/hot100/_621/SolutionTest.java | CheNbXxx/_leetcode | d49786b376d7cf17e099af7dcda1a47866f7e194 | [
"Apache-2.0"
] | null | null | null | src/top.chenqwwq/leetcode/hot100/_621/SolutionTest.java | CheNbXxx/_leetcode | d49786b376d7cf17e099af7dcda1a47866f7e194 | [
"Apache-2.0"
] | null | null | null | 26.05 | 116 | 0.667946 | 4,333 | package top.chenqwwq.leetcode.hot100._621;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author chen
* @date 2021-08-31
**/
class SolutionTest {
@Test
void leastInterval() {
Solution solution = new Solution();
Assertions.assertEquals(16,solution.leastInterval(new char[]{'A','A','A','A','A','A','B','C','D','E','F','G'},2));
Assertions.assertEquals(8,solution.leastInterval(new char[]{'A','A','A','B','B','B'},2));
}
} |
3e0a3c2a7ca9ac59dd9ef79a3826a25c1209f618 | 843 | java | Java | app/src/main/java/android/coolweather/com/coolweather/db/City.java | Hanlishanda/coolweather | 3a295ff3af56f90714257fea4fcfef41ebdff4f5 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/android/coolweather/com/coolweather/db/City.java | Hanlishanda/coolweather | 3a295ff3af56f90714257fea4fcfef41ebdff4f5 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/android/coolweather/com/coolweather/db/City.java | Hanlishanda/coolweather | 3a295ff3af56f90714257fea4fcfef41ebdff4f5 | [
"Apache-2.0"
] | null | null | null | 21.615385 | 47 | 0.635824 | 4,334 | package android.coolweather.com.coolweather.db;
import org.litepal.crud.DataSupport;
/**
* Created by Administrator on 2019/1/21/021.
*/
public class City extends DataSupport {
private int id;
private String cityName;
private int cityCode;
private int provinceId;
public int getId(){
return id;
}
public void setId(int id){
this.id =id;
}
public String getCityName(){
return cityName;
}
public void setCityName(String cityName){
this.cityName =cityName;
}
public int getCityCode(){
return cityCode;
}
public void setCityCode(int cityCode){
this.cityCode = cityCode;
}
public int getProvinceId(){
return provinceId;
}
public void setProvinceId(int provinceId){
this.provinceId = provinceId;
}
}
|
3e0a3d0b6087721c38818ca4cf7b51f16c1fabcd | 2,015 | java | Java | src/main/java/com/snow/postgis/NamedLocation.java | AngryLionQaz1/postgis | 2c5b67a545570c78b7fc6f4720e6208b54d864fa | [
"Apache-2.0"
] | null | null | null | src/main/java/com/snow/postgis/NamedLocation.java | AngryLionQaz1/postgis | 2c5b67a545570c78b7fc6f4720e6208b54d864fa | [
"Apache-2.0"
] | null | null | null | src/main/java/com/snow/postgis/NamedLocation.java | AngryLionQaz1/postgis | 2c5b67a545570c78b7fc6f4720e6208b54d864fa | [
"Apache-2.0"
] | null | null | null | 23.430233 | 116 | 0.595037 | 4,335 | package com.snow.postgis;
import com.vividsolutions.jts.geom.Point;
import org.hibernate.annotations.*;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* Created by Nikolaj Schaldemose Reibke on 4/30/17.
*/
@Entity
@NamedNativeQueries({
@NamedNativeQuery(name = "NamedLocation.findNearest",
query = "SELECT id, name, point\n" +
"FROM NamedLocation\n" +
"ORDER BY ST_Distance(point, ST_MakePoint(:lat, :lon)) ASC LIMIT 1")
})
public class NamedLocation {
/**
* Automatic ID generator, also primary key as stated by @Id
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
/**
* Hibernate dont put qoutes around names, causing errors
*/
@Column(name = "\"name\"")
private String name;
/**
* jts_geometry will map the point type to a Geometry of the postgis type for a postgresql database with postgis
*/
@Column(name = "\"point\"")
@Type(type = "jts_geometry")
private Point point;
public NamedLocation(String name, Point point) {
this.name = name;
this.point = point;
}
public NamedLocation() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
@Override
public String toString() {
return "NamedLocation{" +
"id=" + id +
", name='" + name + '\'' +
", point=" + point +
'}';
}
} |
3e0a3d1ff49deaa168dd4a0dc6d6515b7c83e86f | 12,463 | java | Java | src/common/src/be/ac/ulb/crashcoin/common/BlockChain.java | StanIsAdmin/CrashCoin | fddce88306da49b5810d3b0be0bb98c76914f9a8 | [
"Unlicense"
] | 4 | 2017-12-18T13:25:57.000Z | 2020-06-07T16:13:00.000Z | src/common/src/be/ac/ulb/crashcoin/common/BlockChain.java | StanIsAdmin/CrashCoin | fddce88306da49b5810d3b0be0bb98c76914f9a8 | [
"Unlicense"
] | null | null | null | src/common/src/be/ac/ulb/crashcoin/common/BlockChain.java | StanIsAdmin/CrashCoin | fddce88306da49b5810d3b0be0bb98c76914f9a8 | [
"Unlicense"
] | 1 | 2021-08-16T14:36:17.000Z | 2021-08-16T14:36:17.000Z | 40.073955 | 117 | 0.634197 | 4,336 | package be.ac.ulb.crashcoin.common;
import be.ac.ulb.crashcoin.common.utils.Cryptography;
import java.security.PublicKey;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Represents the CrashCoin BlockChain as a list of Block instances.
* Manage the BlockChain. Initialises it and valids mined blocks.
*
* The add method has been overridden to verify the block to add and
* each of its transactions.
*
* (Note that: In CrashCoin, there is a central trusted node)
*/
public class BlockChain extends ArrayList<Block> implements JSONable {
/** Maps inputs available for transactions to the Address they belong to */
private final Map<byte[], TransactionOutput> availableInputs;
/** Maps a new block's used inputs from their hashes */
private final Map<byte[], TransactionOutput> tempUsedInputs;
/** Maps a new block's generated available inputs from their hashes */
private final Map<byte[], TransactionOutput> tempAvailableInputs;
/**
* Creates a BlockChain which contains only the genesis block.
*
* The genesis block is created through the createGenesisBlock() method.
* @see #createGenesisBlock
*/
public BlockChain() {
this.availableInputs = new HashMap<>();
this.tempUsedInputs = new HashMap<>();
this.tempAvailableInputs = new HashMap<>();
final Block genesis = createGenesisBlock();
addAvailableTransactionOutputs(genesis.get(0)); // add first transaction to the available inputs
super.add(genesis); // call to super does not perform validity check
}
/**
* Creates a BlockChain instance from its JSON representation.
*
* Used by the Master to send the BlockChain the relays.
*
* @param json the JSON representation of the BlockChain, compatible with
* the result of BlockChain.toJSON()
* @see #toJSON
*/
public BlockChain(final JSONObject json) {
this(); // Creates BC containing genesis bloc
final JSONArray blockArray = json.getJSONArray("blockArray");
for (int i = 0; i < blockArray.length(); ++i) {
final Object type = blockArray.get(i);
if (type instanceof JSONObject) {
this.add(new Block((JSONObject) type));
} else {
throw new IllegalArgumentException("Unknow object in blockArray ! " + type);
}
}
}
public Block getLastBlock() {
return this.get(this.size() - 1);
}
private byte[] getLastBlockToBytes() {
return Cryptography.hashBytes(get(this.size() - 1).headerToBytes());
}
/**
* Verifies the block, add it to the end of the blockChain if it is valid
* and update the set of transactions available as inputs.
*
* @param block
* @return whether the block was added to the blockchain.
*/
@Override
public final boolean add(final Block block) {
final boolean valid = isValidNextBlock(block, Parameters.MINING_DIFFICULTY);
if (valid) {
super.add(block);
} else {
// Remove the block's available inputs, put back the ones it used
revertAvailbleInputs();
Logger.getLogger(BlockChain.class.getName()).log(Level.WARNING, "Invalid block discarded");
}
return valid;
}
/**
* Performs checks one the given block and returns whether it may be
* appended to the Blockchain.
*
* - The proof of work realised must correspond to the difficulty indicated
* in the block
* - The difficulty indicated must correspond to the required difficulty
* - The block must indicate the current last block as previous block
*
* @param block The block to check
* @param difficulty the difficulty required
* @return wether the block may validly appended to the blockchain.
*/
protected boolean isValidNextBlock(final Block block, final int difficulty) {
boolean result = block.isHashValid(); // check that the hash corresponds the indicated difficulty
if(result) {
// check that the indicated difficulty corresponds to the required difficulty
result &= (difficulty == block.getDifficulty());
if(result) {
// Previous hash block is valid
result &= Arrays.equals(block.getPreviousBlock(), this.getLastBlockToBytes()) ;
if(result) {
result &= (getBadTransactions(block).isEmpty()); // Check the transaction
if(!result) {
Logger.getLogger(getClass().getName()).warning("The transaction of the block is not valid");
}
} else {
Logger.getLogger(getClass().getName()).warning("Block not reference last block of blockchain");
}
} else {
Logger.getLogger(getClass().getName()).warning("Difficulty of block not valid");
}
} else {
Logger.getLogger(getClass().getName()).warning("Hash of block is invalid");
}
return result;
}
/**
* Gets the first bad transaction that it finds in a block, otherwise returns null.
* A transaction is considered bad if isValidTransaction(transaction) returns false.
*
* @param block Block that needs to be added to the blockchain
* @return First bad transaction found if there is one, null otherwise
*/
public HashSet<Transaction> getBadTransactions(final Block block) {
final HashSet<Transaction> badTransactions = new HashSet<>();
tempUsedInputs.clear();
tempAvailableInputs.clear();
for (final Transaction transaction : block) {
final boolean isReward = (transaction == block.get(block.size()-1));
if (! isValidTransaction(transaction, isReward)) {
badTransactions.add(transaction);
}
}
return badTransactions;
}
/**
* Returns true if transaction is valid, false otherwise.
* The validity check depends on whether the transaction is meant to be
* a reward or not.
* For a reward transaction to be valid, it has to meet all of these conditions :<br>
* - transaction.isValidReward() == true<br>
* <br>
* For a non-reward transaction to be valid, it has to meet all of these conditions :<br>
* - transaction.isValidNonReward() == true<br>
*
*
* @see Transaction#isValidNonReward()
* @see Transaction#isValidReward()
* @param transaction
* @return true if the transaction is valid as defined, false otherwise
*/
private boolean isValidTransaction(final Transaction transaction, final boolean isReward) {
// Verify the transaction is valid as a reward
if (isReward) {
return transaction.isValidReward();
}
// Verify the transaction is valid as a non-reward
if (! transaction.isValidNonReward()) {
return false;
}
// Verify that each input is available and belongs to the sender
for (final TransactionInput input: transaction.getInputs()) {
// Temporarily remove the input so that it can't be used again
final byte[] inputHash = input.getHashBytes();
TransactionOutput referencedOutput = null;
// Must use loop because "byte[]".equals juste test instance and not value
for(final byte[] addressAvailable : availableInputs.keySet()) {
if(Arrays.equals(addressAvailable, inputHash)) {
referencedOutput = availableInputs.remove(addressAvailable);
break;
}
}
if (referencedOutput == null) {
return false;
}
// Keep a copy of the discarded input, to put back if the block is invalid
tempUsedInputs.put(inputHash, referencedOutput);
// verify that the destination address of the referenced output corrponds to
// the address of the payer (i.e. destination addess of the change output)
if(!referencedOutput.getDestinationAddress().equals(transaction.getSrcAddress()))
return false;
}
// Temporarily add the the outputs to the set of available inputs
this.addAvailableTransactionOutputs(transaction);
// All verifications having passed, the transaction is valid
return true;
}
/**
* Adds a transaction's outputs to the set of available inputs.
*
* @param transaction the transaction to (temporarily) validate.
*/
private void addAvailableTransactionOutputs(final Transaction transaction) {
// Add the transactino output
final TransactionOutput transactionOutput = transaction.getTransactionOutput();
final byte[] transactionHash = transactionOutput.getHashBytes();
this.availableInputs.put(transactionHash, transactionOutput);
this.tempAvailableInputs.put(transactionHash, transactionOutput);
// Add the change output, only if it exists and has a strictly positive amount
// (this avoids keeping useless transactions in memory)
final TransactionOutput changeOutput = transaction.getChangeOutput();
if (! transaction.isReward() && changeOutput.getAmount() > 0) {
final byte[] changeHash = changeOutput.getHashBytes();
this.availableInputs.put(changeHash, changeOutput);
this.tempAvailableInputs.put(changeHash, changeOutput);
}
}
/**
* Updates the internal representation of transactions available as inputs,
* after a block has been discarded.
*
* While a block is verified, the inputs it uses are removed from the set
* of available inputs, and the outputs it generates are added to that set.
* This function reverts the process thanks to temporary sets of
*/
private synchronized void revertAvailbleInputs() {
this.availableInputs.keySet().removeAll(this.tempAvailableInputs.keySet());
this.availableInputs.putAll(this.tempUsedInputs);
}
@Override
public JSONObject toJSON() {
final JSONObject json = JSONable.super.toJSON();
try {
final JSONArray jArray = new JSONArray();
// Add every block except for the genesis block
for (final Block block : this.subList(1, this.size())) {
jArray.put(block.toJSON());
}
json.put("blockArray", jArray);
} catch (JSONException jse) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, jse);
}
return json;
}
@Override
public boolean equals(final Object equalsObject) {
boolean result = false;
if(this == equalsObject) {
result = true;
} else if(equalsObject instanceof BlockChain) {
final BlockChain equalsBlockChain = (BlockChain) equalsObject;
if(equalsBlockChain.size() == this.size()) {
result = containsAll(equalsBlockChain) && equalsBlockChain.containsAll(this);
}
}
return result;
}
/**
* Create a block designed to be the first block of the blockchain and
* returns it.
*
* @return a block designed to be the first block of the blockchain
*/
protected static Block createGenesisBlock() {
final Block genesisBlock = new Block(new byte[0], 0);
final PublicKey masterPublicKey = Cryptography.createPublicKeyFromBytes(Parameters.MASTER_WALLET_PUBLIC_KEY);
final Address masterWallet = new Address(masterPublicKey);
final Timestamp genesisTime = new Timestamp(0L);
final Transaction reward = new Transaction(masterWallet, genesisTime);
reward.setSignature(Parameters.GENESIS_SIGNATURE);
genesisBlock.add(reward);
return genesisBlock;
}
}
|
3e0a3e500f3ce84868d30f8fb150fa587268013a | 3,912 | java | Java | Service/src/org/celebino/persistence/controller/GardenStatusController.java | MrH3nry/Celebino | d1f55122c42f15a4ced76c77164977b5086f4538 | [
"MIT"
] | 2 | 2017-09-04T03:00:52.000Z | 2017-09-04T11:58:48.000Z | Service/src/org/celebino/persistence/controller/GardenStatusController.java | mrh3nry/Celebino | d1f55122c42f15a4ced76c77164977b5086f4538 | [
"MIT"
] | 1 | 2021-12-18T18:16:42.000Z | 2021-12-18T18:16:42.000Z | Service/src/org/celebino/persistence/controller/GardenStatusController.java | henry-ns/celebino | 6806212e5a979fce41f738d80e8eda781f7e6b48 | [
"MIT"
] | null | null | null | 23.011765 | 91 | 0.728783 | 4,337 | package org.celebino.persistence.controller;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.security.PermitAll;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.celebino.persistence.dao.AirConditioningDao;
import org.celebino.persistence.dao.GardenDao;
import org.celebino.persistence.dao.GardenStatusDao;
import org.celebino.persistence.dao.LitersMinuteDao;
import org.celebino.persistence.model.AirConditioning;
import org.celebino.persistence.model.Garden;
import org.celebino.persistence.model.GardenStatus;
@Path("gardenstatus")
public class GardenStatusController {
/**
* Cadastra GardenStatus
*
* @param GardenStatus
* @return Response
*/
@PermitAll
@POST
@Path("/")
@Consumes("application/json")
@Produces("application/json")
public Response insert(GardenStatus gardenstatus) {
ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
builder.expires(new Date());
Timestamp time = new Timestamp(System.currentTimeMillis());
gardenstatus.setTime(time);
try {
Garden garden = GardenDao.getInstance().getById(gardenstatus.getGarden().getId());
if (garden.getId().equals(null)) {
GardenDao.getInstance().insertU(gardenstatus.getGarden());
} else {
gardenstatus.setGarden(garden);
}
Long id = GardenStatusDao.getInstance().insertU(gardenstatus);
gardenstatus.setId(id);
System.out.println(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(time.getTime()));
System.out.println(time.getTime());
builder.status(Response.Status.OK).entity(gardenstatus);
} catch (SQLException e) {
builder.status(Response.Status.INTERNAL_SERVER_ERROR);
}
return builder.build();
}
/**
* retorna todos os gardenstatus.
*
* @return Response
*/
@PermitAll
@GET
@Path("/")
@Produces("application/json")
public List<GardenStatus> getAll() {
List<GardenStatus> gardenstatus = new ArrayList<GardenStatus>();
try {
gardenstatus = GardenStatusDao.getInstance().getAll();
} catch (SQLException e) {
// TRATAR EXCECAO
}
return gardenstatus;
}
/**
* Retorna gardenstatus atraves do Id
*
* @param idGardenStatus
* @return Response
*/
@PermitAll
@GET
@Path("/{id}")
@Produces("application/json")
public Response getGardenStatusById(@PathParam("id") Long idGardenStatus) {
ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
builder.expires(new Date());
try {
GardenStatus gardenStatus = GardenStatusDao.getInstance().getById(idGardenStatus);
if (gardenStatus != null) {
builder.status(Response.Status.OK);
builder.entity(gardenStatus);
} else {
builder.status(Response.Status.NOT_FOUND);
}
} catch (SQLException exception) {
builder.status(Response.Status.INTERNAL_SERVER_ERROR);
}
return builder.build();
}
/**
* Get garden status by garden's id
*
* @param gardenId
* @return
*/
@PermitAll
@GET
@Path("/garden/{gardenId}")
@Produces("application/json")
public Response getGardensByGardenId(@PathParam("gardenId") Long gardenId) {
ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
builder.expires(new Date());
try {
List<GardenStatus> gardenStatus = GardenStatusDao.getInstance().getByGardenId(gardenId);
if (gardenStatus != null) {
builder.status(Response.Status.OK);
builder.entity(gardenStatus);
} else {
builder.status(Response.Status.NOT_FOUND);
}
} catch (SQLException exception) {
builder.status(Response.Status.INTERNAL_SERVER_ERROR);
}
return builder.build();
}
}
|
3e0a3f17d58f4a60351f48c65c5c733efe7e0808 | 15,175 | java | Java | src/net/sourceforge/docfetcher/gui/ResultPanel.java | docfetcher/DocFetcher | 42f2accd840edc5059060447ed3536aa4d54b5d3 | [
"Apache-2.0"
] | 24 | 2018-07-22T13:02:53.000Z | 2022-02-02T16:45:29.000Z | src/net/sourceforge/docfetcher/gui/ResultPanel.java | docfetcher/DocFetcher | 42f2accd840edc5059060447ed3536aa4d54b5d3 | [
"Apache-2.0"
] | null | null | null | src/net/sourceforge/docfetcher/gui/ResultPanel.java | docfetcher/DocFetcher | 42f2accd840edc5059060447ed3536aa4d54b5d3 | [
"Apache-2.0"
] | 5 | 2018-12-29T10:38:03.000Z | 2021-02-06T15:29:03.000Z | 32.564378 | 140 | 0.713015 | 4,338 | /*******************************************************************************
* Copyright (c) 2011 Tran Nam Quang.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tran Nam Quang - initial API and implementation
*******************************************************************************/
package net.sourceforge.docfetcher.gui;
import java.io.File;
import java.io.FileNotFoundException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.sourceforge.docfetcher.enums.Img;
import net.sourceforge.docfetcher.enums.Msg;
import net.sourceforge.docfetcher.enums.SettingsConf;
import net.sourceforge.docfetcher.model.FileResource;
import net.sourceforge.docfetcher.model.Path;
import net.sourceforge.docfetcher.model.Path.PathParts;
import net.sourceforge.docfetcher.model.parse.ParseException;
import net.sourceforge.docfetcher.model.search.ResultDocument;
import net.sourceforge.docfetcher.util.AppUtil;
import net.sourceforge.docfetcher.util.Event;
import net.sourceforge.docfetcher.util.Util;
import net.sourceforge.docfetcher.util.annotations.MutableCopy;
import net.sourceforge.docfetcher.util.annotations.NotNull;
import net.sourceforge.docfetcher.util.annotations.Nullable;
import net.sourceforge.docfetcher.util.collect.AlphanumComparator;
import net.sourceforge.docfetcher.util.gui.ContextMenuManager;
import net.sourceforge.docfetcher.util.gui.FileIconCache;
import net.sourceforge.docfetcher.util.gui.MenuAction;
import net.sourceforge.docfetcher.util.gui.viewer.VirtualTableViewer;
import net.sourceforge.docfetcher.util.gui.viewer.VirtualTableViewer.Column;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import com.google.common.primitives.Longs;
/**
* @author Tran Nam Quang
*/
public final class ResultPanel {
// TODO post-release-1.1: show an additional icon if an email has attachments
// TODO post-release-1.1: show some helpful overlay message if a search yielded no results
// TODO post-release-1.1: implement context menu: copy paths to clipboard, including Mod1+C shortcut (also: Mod1+A for selecting all items)
public enum HeaderMode {
FILES { protected void setLabel(VariableHeaderColumn<?> column) {
column.setLabel(column.fileHeader);
} },
EMAILS { protected void setLabel(VariableHeaderColumn<?> column) {
column.setLabel(column.emailHeader);
} },
FILES_AND_EMAILS { protected void setLabel(VariableHeaderColumn<?> column) {
column.setLabel(column.combinedHeader);
} },
;
protected abstract void setLabel(@NotNull VariableHeaderColumn<?> column);
@NotNull
public static HeaderMode getInstance(boolean filesFound, boolean emailsFound) {
final HeaderMode mode;
if (filesFound)
mode = emailsFound ? HeaderMode.FILES_AND_EMAILS : HeaderMode.FILES;
else
mode = HeaderMode.EMAILS;
return mode;
}
}
private static final DateFormat dateFormat = new SimpleDateFormat();
public final Event<List<ResultDocument>> evtSelection = new Event<List<ResultDocument>> ();
public final Event<Void> evtHideInSystemTray = new Event<Void>();
private final VirtualTableViewer<ResultDocument> viewer;
private final FileIconCache iconCache;
private HeaderMode presetHeaderMode = HeaderMode.FILES; // externally suggested header mode
private HeaderMode actualHeaderMode = HeaderMode.FILES; // header mode after examining each visible element
public ResultPanel(@NotNull Composite parent) {
iconCache = new FileIconCache(parent);
int treeStyle = SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER;
viewer = new VirtualTableViewer<ResultDocument> (parent, treeStyle) {
@SuppressWarnings("unchecked")
protected List<ResultDocument> getElements(Object rootElement) {
return (List<ResultDocument>) rootElement;
}
};
// Open result document on double-click
final Table table = viewer.getControl();
table.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent e) {
launchSelection();
}
});
table.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (Util.isEnterKey(e.keyCode))
launchSelection();
else if (e.stateMask == SWT.MOD1 && e.keyCode == 'c')
copyToClipboard();
else if (e.stateMask == SWT.MOD1 && e.keyCode == 'a')
table.selectAll();
}
});
viewer.setSortingEnabled(true);
initContextMenu();
table.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
evtSelection.fire(viewer.getSelection());
}
});
viewer.addColumn(new VariableHeaderColumn<ResultDocument>(Msg.title.get(), Msg.subject.get()) {
protected String getLabel(ResultDocument element) {
return element.getTitle();
}
protected Image getImage(ResultDocument element) {
if (element.isEmail())
return Img.EMAIL.get();
return iconCache.getIcon(element.getFilename(), Img.FILE.get());
}
protected int compare(ResultDocument e1, ResultDocument e2) {
return compareAlphanum(e1.getTitle(), e2.getTitle());
}
});
viewer.addColumn(new Column<ResultDocument>(Msg.score.get(), SWT.RIGHT) {
protected String getLabel(ResultDocument element) {
return String.valueOf(element.getScore());
}
protected int compare(ResultDocument e1, ResultDocument e2) {
return -1 * Float.compare(e1.getScore(), e2.getScore());
}
});
viewer.addColumn(new Column<ResultDocument>(Msg.size.get(), SWT.RIGHT) {
protected String getLabel(ResultDocument element) {
return String.format("%,d KB", element.getSizeInKB());
}
protected int compare(ResultDocument e1, ResultDocument e2) {
return -1 * Longs.compare(e1.getSizeInKB(), e2.getSizeInKB());
}
});
viewer.addColumn(new VariableHeaderColumn<ResultDocument>(Msg.filename.get(), Msg.sender.get()) {
protected String getLabel(ResultDocument element) {
if (element.isEmail())
return element.getSender();
return element.getFilename();
}
protected int compare(ResultDocument e1, ResultDocument e2) {
return compareAlphanum(getLabel(e1), getLabel(e2));
}
});
viewer.addColumn(new Column<ResultDocument>(Msg.type.get()) {
protected String getLabel(ResultDocument element) {
return element.getType();
}
protected int compare(ResultDocument e1, ResultDocument e2) {
return compareAlphanum(e1.getType(), e2.getType());
}
});
viewer.addColumn(new Column<ResultDocument>(Msg.path.get()) {
protected String getLabel(ResultDocument element) {
return element.getPath().getPath();
}
protected int compare(ResultDocument e1, ResultDocument e2) {
return compareAlphanum(getLabel(e1), getLabel(e2));
}
});
viewer.addColumn(new VariableHeaderColumn<ResultDocument>(Msg.authors.get(), Msg.sender.get()) {
protected String getLabel(ResultDocument element) {
return element.getAuthors();
}
protected int compare(ResultDocument e1, ResultDocument e2) {
return compareAlphanum(e1.getAuthors(), e2.getAuthors());
}
});
viewer.addColumn(new VariableHeaderColumn<ResultDocument>(Msg.last_modified.get(), Msg.send_date.get()) {
protected String getLabel(ResultDocument element) {
Date date = getDate(element);
return date == null ? "" : dateFormat.format(date);
}
protected int compare(ResultDocument e1, ResultDocument e2) {
Date date1 = getDate(e1);
Date date2 = getDate(e2);
if (date1 == null) // Place null dates before non-null dates
return date2 == null ? 0 : -1;
else if (date2 == null)
return 1;
return date1.compareTo(date2);
}
@Nullable
private Date getDate(ResultDocument element) {
if (element.isEmail())
return element.getDate();
return element.getLastModified();
}
});
SettingsConf.ColumnWidths.ResultPanel.bind(table);
SettingsConf.ColumnOrder.ResultPanelColumnOrder.bind(table);
}
private void launchSelection() {
List<ResultDocument> selection = viewer.getSelection();
if (selection.isEmpty())
return;
ResultDocument doc = selection.get(0);
if (!doc.isEmail())
launchFiles(Collections.singletonList(doc));
}
private static int compareAlphanum(@NotNull String s1, @NotNull String s2) {
return AlphanumComparator.ignoreCaseInstance.compare(s1, s2);
}
private void initContextMenu() {
ContextMenuManager menuManager = new ContextMenuManager(viewer.getControl());
menuManager.add(new MenuAction(Msg.open.get()) {
public boolean isEnabled() {
List<ResultDocument> sel = viewer.getSelection();
if (sel.isEmpty())
return false;
for (ResultDocument doc : sel)
if (doc.isEmail())
return false;
return true;
}
public void run() {
launchFiles(viewer.getSelection());
}
public boolean isDefaultItem() {
return true;
}
});
menuManager.add(new MenuAction(Msg.open_parent.get()) {
public boolean isEnabled() {
return !viewer.getSelection().isEmpty();
}
public void run() {
MultiFileLauncher launcher = new MultiFileLauncher();
for (ResultDocument doc : viewer.getSelection()) {
Path path = doc.getPath();
try {
launcher.addFile(getParent(path));
}
catch (FileNotFoundException e) {
launcher.addMissing(path.getCanonicalPath());
}
}
if (launcher.launch() && SettingsConf.Bool.HideOnOpen.get())
evtHideInSystemTray.fire(null);
}
@NotNull
private File getParent(@NotNull Path path)
throws FileNotFoundException {
/*
* The possible cases:
* - Path points to an ordinary file
* - Path points to an archive entry
* - Path points to an item in a PST file
*
* In each case, the target may or may not exist.
*/
PathParts pathParts = path.splitAtExistingFile();
if (pathParts.getRight().isEmpty()) // Existing ordinary file
return Util.getParentFile(path.getCanonicalFile());
File leftFile = pathParts.getLeft().getCanonicalFile();
if (leftFile.isDirectory())
// File, archive entry or PST item does not exist
throw new FileNotFoundException();
// Existing PST item
if (Util.hasExtension(pathParts.getLeft().getName(), "pst"))
return Util.getParentFile(leftFile);
// Existing archive entry -> return the archive
return leftFile;
}
});
menuManager.addSeparator();
menuManager.add(new MenuAction(Msg.copy.get()) {
public boolean isEnabled() {
return !viewer.getSelection().isEmpty();
}
public void run() {
copyToClipboard();
}
});
}
private void copyToClipboard() {
List<ResultDocument> docs = getSelection();
if (docs.isEmpty())
return;
List<File> files = new ArrayList<File>(docs.size());
for (ResultDocument doc : docs)
files.add(doc.getPath().getCanonicalFile());
Util.setClipboard(files);
}
@NotNull
public Table getControl() {
return viewer.getControl();
}
public int getItemCount() {
return viewer.getControl().getItemCount();
}
@MutableCopy
@NotNull
public List<ResultDocument> getSelection() {
return viewer.getSelection();
}
// header mode: auto-detect for "files + emails", no auto-detect for files and emails mode
public void setResults( @NotNull List<ResultDocument> results,
@NotNull HeaderMode headerMode) {
Util.checkNotNull(results, headerMode);
if (this.presetHeaderMode != headerMode) {
if (headerMode != HeaderMode.FILES_AND_EMAILS)
updateColumnHeaders(headerMode);
this.presetHeaderMode = headerMode;
}
setActualHeaderMode(results); // TODO post-release-1.1: needs some refactoring
viewer.setRoot(results);
viewer.scrollToTop();
}
private void setActualHeaderMode(List<ResultDocument> elements) {
if (presetHeaderMode != HeaderMode.FILES_AND_EMAILS) {
actualHeaderMode = presetHeaderMode;
return;
}
boolean filesFound = false;
boolean emailsFound = false;
for (ResultDocument element : elements) {
if (element.isEmail())
emailsFound = true;
else
filesFound = true;
}
actualHeaderMode = HeaderMode.getInstance(filesFound, emailsFound);
updateColumnHeaders(actualHeaderMode);
}
private void updateColumnHeaders(HeaderMode headerMode) {
for (Column<ResultDocument> column : viewer.getColumns()) {
if (! (column instanceof VariableHeaderColumn)) continue;
headerMode.setLabel((VariableHeaderColumn<?>) column);
}
}
// sign of given index specifies direction of sorting
// zero and out-of-range values will be ignored
// column numbering starts at 1
// the index points at the column in visual order, not in creation order
public void sortByColumn(int columnIndex) {
if (columnIndex == 0)
return;
/*
* Note: The column to sort by must be specified as an index, since the
* column names may change.
*/
try {
int index = Math.abs(columnIndex) - 1;
List<Column<ResultDocument>> columns = viewer.getColumnsVisualOrder();
if (index >= columns.size())
return;
boolean up = Math.signum(columnIndex) > 0;
viewer.sortByColumn(columns.get(index), up);
}
catch (NumberFormatException e) {
return;
}
}
// Should not be called with emails
private void launchFiles(@NotNull List<ResultDocument> docs) {
assert !docs.isEmpty();
MultiFileLauncher launcher = new MultiFileLauncher();
Set<FileResource> resources = new HashSet<FileResource>();
try {
for (ResultDocument doc : docs) {
try {
FileResource fileResource = doc.getFileResource();
resources.add(fileResource);
launcher.addFile(fileResource.getFile());
}
catch (FileNotFoundException e) {
launcher.addMissing(doc.getPath().getCanonicalPath());
}
catch (ParseException e) {
AppUtil.showError(e.getMessage(), true, false);
return;
}
}
if (launcher.launch() && SettingsConf.Bool.HideOnOpen.get())
evtHideInSystemTray.fire(null);
}
finally {
for (FileResource fileResource : resources)
fileResource.dispose();
}
}
private static abstract class VariableHeaderColumn<T> extends Column<T> {
private final String fileHeader;
private final String emailHeader;
private final String combinedHeader;
public VariableHeaderColumn(@NotNull String fileHeader,
@NotNull String emailHeader) {
super(fileHeader);
Util.checkNotNull(fileHeader, emailHeader);
this.fileHeader = fileHeader;
this.emailHeader = emailHeader;
combinedHeader = fileHeader + " / " + emailHeader;
}
}
}
|
3e0a3f21789c8c0f4292c195310f5ddde5b07d63 | 482 | java | Java | gomint-server/src/main/java/io/gomint/server/inventory/item/ItemFlowerPot.java | WhiteGrouse/GoMint | 2a77f9ae9d2e98b9982fd89816b577941b01239e | [
"BSD-3-Clause"
] | null | null | null | gomint-server/src/main/java/io/gomint/server/inventory/item/ItemFlowerPot.java | WhiteGrouse/GoMint | 2a77f9ae9d2e98b9982fd89816b577941b01239e | [
"BSD-3-Clause"
] | null | null | null | gomint-server/src/main/java/io/gomint/server/inventory/item/ItemFlowerPot.java | WhiteGrouse/GoMint | 2a77f9ae9d2e98b9982fd89816b577941b01239e | [
"BSD-3-Clause"
] | null | null | null | 20.083333 | 96 | 0.70332 | 4,339 | package io.gomint.server.inventory.item;
import io.gomint.inventory.item.ItemType;
import io.gomint.server.registry.RegisterInfo;
/**
* @author geNAZt
* @version 1.0
*/
@RegisterInfo( id = 390 )
public class ItemFlowerPot extends ItemStack implements io.gomint.inventory.item.ItemFlowerPot {
@Override
public String getBlockId() {
return "minecraft:flower_pot";
}
@Override
public ItemType getType() {
return ItemType.FLOWER_POT;
}
}
|
3e0a3f807614dd002fc947e5ccc5cb696f96f1fe | 729 | java | Java | src/main/java/com/tlh/entity/Department.java | tlhhup/tlh | 07a0fa243ac67d8f94edfaf75e4c204cf455a2e3 | [
"Apache-2.0"
] | 5 | 2016-09-28T04:21:30.000Z | 2019-11-09T09:23:41.000Z | src/main/java/com/tlh/entity/Department.java | tlhhup/tlh | 07a0fa243ac67d8f94edfaf75e4c204cf455a2e3 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/tlh/entity/Department.java | tlhhup/tlh | 07a0fa243ac67d8f94edfaf75e4c204cf455a2e3 | [
"Apache-2.0"
] | 2 | 2016-09-30T03:33:25.000Z | 2018-08-07T08:36:25.000Z | 18.225 | 50 | 0.698217 | 4,340 | package com.tlh.entity;
import com.tlh.system.annotation.Id;
import com.tlh.system.annotation.Table;
@Table(tableName="sys_department")
public class Department extends BaseEntity
{
private static final long serialVersionUID = 1L;
@Id(name="id",isAotu=false)
private String id;
private String name;
private String description;
public String getId()
{
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
} |
3e0a3fc580b0372b7104ccfd55c7b0ea266f1a6d | 336 | java | Java | src/main/java/org/txazo/jvm/classloader/ClassInit.java | txazo/java | d3e9b20ee98c890bfaa464140554961d9850a06d | [
"Apache-2.0"
] | null | null | null | src/main/java/org/txazo/jvm/classloader/ClassInit.java | txazo/java | d3e9b20ee98c890bfaa464140554961d9850a06d | [
"Apache-2.0"
] | 2 | 2021-07-02T18:51:34.000Z | 2021-08-09T20:59:24.000Z | src/main/java/org/txazo/jvm/classloader/ClassInit.java | txazo/java | d3e9b20ee98c890bfaa464140554961d9850a06d | [
"Apache-2.0"
] | 1 | 2016-08-15T15:05:32.000Z | 2016-08-15T15:05:32.000Z | 17.684211 | 56 | 0.636905 | 4,341 | package org.txazo.jvm.classloader;
public class ClassInit extends ClassInitSuper {
private static ClassInit instance = new ClassInit();
private int status = 1;
static {
System.out.println("ClassInit 静态代码块");
}
public ClassInit() {
super();
System.out.println("ClassInit 构造函数");
}
}
|
3e0a409fd50d77f714c17a1bccf7b74c6c41708d | 297 | java | Java | src/main/java/org/cryptimeleon/craco/commitment/CommitmentKey.java | Colamaleon/craco | e34bddb90c2ad381a7d02954bae9446a11fc7e7c | [
"Apache-2.0"
] | null | null | null | src/main/java/org/cryptimeleon/craco/commitment/CommitmentKey.java | Colamaleon/craco | e34bddb90c2ad381a7d02954bae9446a11fc7e7c | [
"Apache-2.0"
] | 6 | 2022-02-16T12:04:16.000Z | 2022-03-21T12:11:42.000Z | src/main/java/org/cryptimeleon/craco/commitment/CommitmentKey.java | Colamaleon/craco | e34bddb90c2ad381a7d02954bae9446a11fc7e7c | [
"Apache-2.0"
] | null | null | null | 27 | 79 | 0.828283 | 4,342 | package org.cryptimeleon.craco.commitment;
import org.cryptimeleon.math.hash.UniqueByteRepresentable;
import org.cryptimeleon.math.serialization.Representable;
/**
* Commitment key used to commit to messages
*/
public interface CommitmentKey extends Representable, UniqueByteRepresentable {
}
|
3e0a40a78f0c4b0ade2bf9010be50850238f1304 | 1,948 | java | Java | src/main/java/com/rymcu/forest/answer/AnswerController.java | acaterpillar/forest | d6904d84d123421884e628e8231e63492b733e6b | [
"MIT"
] | 5 | 2021-01-25T09:02:31.000Z | 2022-03-04T09:11:24.000Z | src/main/java/com/rymcu/forest/answer/AnswerController.java | acaterpillar/forest | d6904d84d123421884e628e8231e63492b733e6b | [
"MIT"
] | 16 | 2021-01-25T09:13:47.000Z | 2022-01-08T13:27:43.000Z | src/main/java/com/rymcu/forest/answer/AnswerController.java | acaterpillar/forest | d6904d84d123421884e628e8231e63492b733e6b | [
"MIT"
] | 7 | 2021-01-26T00:32:14.000Z | 2022-01-27T06:02:55.000Z | 38.196078 | 97 | 0.738193 | 4,343 | package com.rymcu.forest.answer;
import com.alibaba.fastjson.JSONObject;
import com.rymcu.forest.core.result.GlobalResult;
import com.rymcu.forest.core.service.log.annotation.TransactionLogger;
import com.rymcu.forest.dto.AnswerDTO;
import com.rymcu.forest.entity.User;
import com.rymcu.forest.enumerate.TransactionEnum;
import com.rymcu.forest.util.HttpUtils;
import com.rymcu.forest.util.UserUtils;
import com.rymcu.forest.web.api.exception.BaseApiException;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author ronger
*/
@RestController
@RequestMapping("/api/v1/answer")
public class AnswerController {
private final static String ANSWER_API_URL = "http://1.116.175.112:8089/question";
@GetMapping("/today")
public GlobalResult today() throws BaseApiException {
User user = UserUtils.getCurrentUserByToken();
String result = HttpUtils.sendGet(ANSWER_API_URL + "/record/" + user.getIdUser() );
return JSONObject.parseObject(result, GlobalResult.class);
}
@PostMapping("/answer")
@TransactionLogger(transactionType = TransactionEnum.Answer)
public GlobalResult answer(@RequestBody AnswerDTO answerDTO) throws BaseApiException {
User user = UserUtils.getCurrentUserByToken();
Map params = new HashMap<>(3);
params.put("userId", user.getIdUser());
params.put("answer", answerDTO.getAnswer());
params.put("subjectQuestionId", answerDTO.getIdSubjectQuestion());
String result = HttpUtils.sendPost(ANSWER_API_URL + "/answer/everyday", params);
return JSONObject.parseObject(result, GlobalResult.class);
}
@GetMapping("/get-answer")
public GlobalResult getAnswer(Integer idSubjectQuestion) {
String result = HttpUtils.sendGet(ANSWER_API_URL + "/show-answer/" + idSubjectQuestion );
return JSONObject.parseObject(result, GlobalResult.class);
}
}
|
3e0a418a1901fc540b6446ab42cd80946460c923 | 1,621 | java | Java | src/main/java/io/jmnarloch/spring/boot/rxjava/async/SingleDeferredResult.java | jmnarloch/rxjava-spring-cloud-starter | b1abbd9ae7abc13e5d806de3115f671d88ab6da9 | [
"Apache-2.0"
] | 193 | 2016-01-25T07:49:27.000Z | 2022-03-31T15:02:17.000Z | src/main/java/io/jmnarloch/spring/boot/rxjava/async/SingleDeferredResult.java | yakup/rxjava-spring-boot-starter | b1abbd9ae7abc13e5d806de3115f671d88ab6da9 | [
"Apache-2.0"
] | 12 | 2016-02-20T12:52:54.000Z | 2020-03-31T02:55:06.000Z | src/main/java/io/jmnarloch/spring/boot/rxjava/async/SingleDeferredResult.java | yakup/rxjava-spring-boot-starter | b1abbd9ae7abc13e5d806de3115f671d88ab6da9 | [
"Apache-2.0"
] | 58 | 2016-01-31T12:25:45.000Z | 2021-04-06T03:53:40.000Z | 33.081633 | 87 | 0.73103 | 4,344 | /**
* Copyright (c) 2015-2016 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jmnarloch.spring.boot.rxjava.async;
import org.springframework.util.Assert;
import org.springframework.web.context.request.async.DeferredResult;
import io.reactivex.Single;
/**
* A specialized {@link DeferredResult} that handles {@link Single} return type.
*
* @author Jakub Narloch
* @see DeferredResult
*/
public class SingleDeferredResult<T> extends DeferredResult<T> {
private static final Object EMPTY_RESULT = new Object();
private final DeferredResultObserver<T> observer;
public SingleDeferredResult(Single<T> single) {
this(null, EMPTY_RESULT, single);
}
public SingleDeferredResult(long timeout, Single<T> single) {
this(timeout, EMPTY_RESULT, single);
}
public SingleDeferredResult(Long timeout, Object timeoutResult, Single<T> single) {
super(timeout, timeoutResult);
Assert.notNull(single, "single can not be null");
observer = new DeferredResultObserver<T>(single.toObservable(), this);
}
}
|
3e0a4213f6c2ff26fabe53f625237497c73adffe | 591 | java | Java | spring-boot-web/spring-boot-rest/src/main/java/org/luvx/common/throwable/assertion/LicenceAssert.java | LuVx21/spring-boot | 5ec19d3a44b2ac29be5a743eda4f1bc0df9d97bf | [
"MIT"
] | 1 | 2019-10-22T03:17:05.000Z | 2019-10-22T03:17:05.000Z | spring-boot-web/spring-boot-rest/src/main/java/org/luvx/common/throwable/assertion/LicenceAssert.java | LuVx21/spring-boot | 5ec19d3a44b2ac29be5a743eda4f1bc0df9d97bf | [
"MIT"
] | 12 | 2020-06-15T20:06:14.000Z | 2022-02-09T22:56:29.000Z | spring-boot-web/spring-boot-rest/src/main/java/org/luvx/common/throwable/assertion/LicenceAssert.java | LuVx21/spring-boot | 5ec19d3a44b2ac29be5a743eda4f1bc0df9d97bf | [
"MIT"
] | 2 | 2019-01-16T09:13:49.000Z | 2019-10-22T03:17:22.000Z | 19.064516 | 62 | 0.642978 | 4,345 | package org.luvx.common.throwable.assertion;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.luvx.common.throwable.base.BusinessExceptionAssert;
/**
* @author: Ren, Xie
* @desc:
*/
@Getter
@AllArgsConstructor
public enum LicenceAssert implements BusinessExceptionAssert {
/**
* Bad licence type
*/
BAD_LICENCE_TYPE("7001", "Bad licence type."),
/**
* Licence not found
*/
LICENCE_NOT_FOUND("7002", "Licence not found.");
/**
* 返回码
*/
private String code;
/**
* 返回消息
*/
private String message;
} |
3e0a42dbc98e995e9519d2657357ab0999c59799 | 695 | java | Java | src/main/java/uk/gov/justice/digital/delius/jpa/standard/repository/ReferralDocumentRepository.java | ollietreend/community-api | 9431b03e93d7540bba2a3b1dfafc5983750d68f1 | [
"MIT"
] | 4 | 2019-08-30T11:08:35.000Z | 2022-03-04T10:17:20.000Z | src/main/java/uk/gov/justice/digital/delius/jpa/standard/repository/ReferralDocumentRepository.java | ollietreend/community-api | 9431b03e93d7540bba2a3b1dfafc5983750d68f1 | [
"MIT"
] | 39 | 2019-06-26T08:44:06.000Z | 2022-03-29T16:22:50.000Z | src/main/java/uk/gov/justice/digital/delius/jpa/standard/repository/ReferralDocumentRepository.java | ollietreend/community-api | 9431b03e93d7540bba2a3b1dfafc5983750d68f1 | [
"MIT"
] | 6 | 2019-05-22T14:23:46.000Z | 2021-11-08T14:27:23.000Z | 49.642857 | 181 | 0.827338 | 4,346 | package uk.gov.justice.digital.delius.jpa.standard.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import uk.gov.justice.digital.delius.jpa.standard.entity.ReferralDocument;
import java.util.List;
public interface ReferralDocumentRepository extends JpaRepository<ReferralDocument, Long> {
@Query("select document from ReferralDocument document, Referral entity where document.referral = entity and document.offenderId = :offenderId and document.softDeleted = false")
List<ReferralDocument> findByOffenderId(@Param("offenderId") Long offenderId);
}
|
3e0a431dd5e5faefbb8cf7b01facc579fd343d89 | 3,927 | java | Java | src/ch/hesso/master/sweetcity/database/entity/Report.java | Chavjoh/SweetCityWeb | 9b8084587ba5b28348fe513fe496f119b9173fe9 | [
"Apache-2.0"
] | null | null | null | src/ch/hesso/master/sweetcity/database/entity/Report.java | Chavjoh/SweetCityWeb | 9b8084587ba5b28348fe513fe496f119b9173fe9 | [
"Apache-2.0"
] | null | null | null | src/ch/hesso/master/sweetcity/database/entity/Report.java | Chavjoh/SweetCityWeb | 9b8084587ba5b28348fe513fe496f119b9173fe9 | [
"Apache-2.0"
] | null | null | null | 18.43662 | 96 | 0.676598 | 4,347 | package ch.hesso.master.sweetcity.database.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import ch.hesso.master.sweetcity.database.tools.Deref;
import ch.hesso.master.sweetcity.utils.DateUtils;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
@Entity
public class Report implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
@Index
private Ref<Account> user;
private String image;
private List<Ref<Tag>> listTag;
private Integer vote;
private Float latitude;
private Float longitude;
private Date submitDate;
private Date validationDate;
public Report() {
listTag = new ArrayList<Ref<Tag>>();
}
public Report(Account user, String image, Float latitude, Float longitude) {
this();
setUser(user);
setImage(image);
setLatitude(latitude);
setLongitude(longitude);
resetDefault();
}
public Report(Account user, String image, List<Tag> listTag, Float latitude, Float longitude) {
this(user, image, latitude, longitude);
setListTag(listTag);
}
public void resetDefault() {
setVote(0);
setSubmitDate(DateUtils.now());
setValidationDate(null);
}
@Override
public boolean equals(Object object) {
if (object == this) { return true; }
if (object == null || object.getClass() != this.getClass()) { return false; }
Report report = (Report)object;
return id.equals(report.getId());
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @return the user
*/
public Account getUser() {
return Deref.deref(user);
}
/**
* @param user the user to set
*/
public void setUser(Account user) {
this.user = Ref.create(user);
}
/**
* @return the image
*/
public String getImage() {
return image;
}
/**
* @param image the image to set
*/
public void setImage(String image) {
this.image = image;
}
/**
* @return the listTag
*/
public List<Tag> getListTag() {
List<Tag> derefList = Deref.deref(this.listTag);
derefList.removeAll(Collections.singleton(null));
return derefList;
}
/**
* @param listTag the listTag to set
*/
public void setListTag(List<Tag> listTag) {
this.listTag.clear();
for (Tag tag:listTag) {
addTag(tag);
}
}
/**
* @param tag the tag to delete
*/
public void removeTag(Tag tag) {
this.listTag.remove(Ref.create(tag));
}
/**
* @param tag the tag to add
*/
public void addTag(Tag tag) {
this.listTag.add(Ref.create(tag));
}
/**
* @return the vote
*/
public Integer getVote() {
return vote;
}
/**
* @param vote the vote to set
*/
public void setVote(Integer vote) {
this.vote = vote;
}
/**
* @return the latitude
*/
public Float getLatitude() {
return latitude;
}
/**
* @param latitude the latitude to set
*/
public void setLatitude(Float latitude) {
this.latitude = latitude;
}
/**
* @return the longitude
*/
public Float getLongitude() {
return longitude;
}
/**
* @param longitude the longitude to set
*/
public void setLongitude(Float longitude) {
this.longitude = longitude;
}
/**
* @return the submitDate
*/
public Date getSubmitDate() {
return submitDate;
}
/**
* @param submitDate the submitDate to set
*/
private void setSubmitDate(Date submitDate) {
this.submitDate = submitDate;
}
/**
* @return the validationDate
*/
public Date getValidationDate() {
return validationDate;
}
/**
* @param validationDate the validationDate to set
*/
public void setValidationDate(Date validationDate) {
this.validationDate = validationDate;
}
/**
* @return true if the report is validated
*/
public boolean isValidated() {
return validationDate != null;
}
}
|
3e0a435103de5425f92cecae4a3a1a55c595d629 | 58,874 | java | Java | src/erp/mfin/form/SFormMoneyOutCheck.java | alphalapz/siie | 43743d6df51525c49230805a2e85eb8d28516301 | [
"MIT"
] | null | null | null | src/erp/mfin/form/SFormMoneyOutCheck.java | alphalapz/siie | 43743d6df51525c49230805a2e85eb8d28516301 | [
"MIT"
] | null | null | null | src/erp/mfin/form/SFormMoneyOutCheck.java | alphalapz/siie | 43743d6df51525c49230805a2e85eb8d28516301 | [
"MIT"
] | 2 | 2017-01-14T17:20:25.000Z | 2018-07-19T14:41:16.000Z | 43.257899 | 203 | 0.674797 | 4,348 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* SFormMoneyOutCheck.java
*
* Created on 21/10/2010, 03:30:20 PM
*/
package erp.mfin.form;
import erp.data.SDataConstants;
import erp.data.SDataConstantsSys;
import erp.data.SDataReadDescriptions;
import erp.data.SDataUtilities;
import erp.data.SProcConstants;
import erp.lib.SLibConstants;
import erp.lib.SLibUtilities;
import erp.lib.form.SFormField;
import erp.lib.form.SFormUtilities;
import erp.lib.form.SFormValidation;
import erp.mbps.data.SDataBizPartnerBranch;
import erp.mcfg.data.SDataCurrency;
import erp.mfin.data.SDataCheck;
import erp.mfin.data.SDataCheckWallet;
import erp.mfin.data.SDataRecord;
import erp.mfin.data.SDataRecordEntry;
import erp.mod.SModSysConsts;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
/**
*
* @author Alfonso Flores
*/
public class SFormMoneyOutCheck extends javax.swing.JDialog implements erp.lib.form.SFormInterface, java.awt.event.ActionListener, java.awt.event.FocusListener {
private int mnFormType;
private int mnFormResult;
private int mnFormStatus;
private boolean mbFirstTime;
private boolean mbResetingForm;
private java.util.Vector<erp.lib.form.SFormField> mvFields;
private erp.client.SClientInterface miClient;
private erp.mfin.data.SDataCheck moCheck;
private erp.lib.form.SFormField moFieldConcept;
private erp.lib.form.SFormField moFieldPkCheckWalletId;
private erp.lib.form.SFormField moFieldNumber;
private erp.lib.form.SFormField moFieldDate;
private erp.lib.form.SFormField moFieldBeneficiary;
private erp.lib.form.SFormField moFieldFkBizPartnerBranchId;
private erp.lib.form.SFormField moFieldFkBizPartnerBankAccountId;
private erp.lib.form.SFormField moFieldBeneficiaryUser;
private erp.lib.form.SFormField moFieldValueCy;
private erp.lib.form.SFormField moFieldExchangeRateSystem;
private erp.lib.form.SFormField moFieldValue;
private erp.lib.form.SFormField moFieldExchangeRate;
private erp.lib.form.SFormField moFieldIsForBeneficiaryAccount;
private Vector<erp.mfin.data.SDataCheck> mvParamCheckVector;
private erp.mfin.data.SDataRecord moParamRecord;
private erp.mfin.data.SDataRecordEntry moRecordEntry;
private erp.mcfg.data.SDataCurrency moCurrency;
private int mnFkUser;
/** Creates new form SFormMoneyOutCheck */
public SFormMoneyOutCheck(erp.client.SClientInterface client) {
super(client.getFrame(), true);
miClient = client;
initComponents();
initComponentsExtra();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jbOk = new javax.swing.JButton();
jbCancel = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jlAccountCash = new javax.swing.JLabel();
jtfCompanyBranch = new javax.swing.JTextField();
jtfAccountCash = new javax.swing.JTextField();
jtfCode = new javax.swing.JTextField();
jPanel6 = new javax.swing.JPanel();
jlPkCheckWalletId = new javax.swing.JLabel();
jcbPkCheckWalletId = new javax.swing.JComboBox();
jPanel7 = new javax.swing.JPanel();
jlDate = new javax.swing.JLabel();
jftDate = new javax.swing.JFormattedTextField();
jbDate = new javax.swing.JButton();
jPanel8 = new javax.swing.JPanel();
jlNumber = new javax.swing.JLabel();
jtfNumber = new javax.swing.JTextField();
jPanel9 = new javax.swing.JPanel();
jrbIsBeneficiarySelected = new javax.swing.JRadioButton();
jrbIsBeneficiaryByUser = new javax.swing.JRadioButton();
jPanel10 = new javax.swing.JPanel();
jlBeneficiary = new javax.swing.JLabel();
jcbBeneficiary = new javax.swing.JComboBox();
jbBeneficiary = new javax.swing.JButton();
jPanel16 = new javax.swing.JPanel();
jlFkBizPartnerBranchId = new javax.swing.JLabel();
jcbFkBizPartnerBranchId = new javax.swing.JComboBox();
jPanel15 = new javax.swing.JPanel();
jlFkBizPartnerBankAccountId = new javax.swing.JLabel();
jcbFkBizPartnerBankAccountId = new javax.swing.JComboBox();
jPanel11 = new javax.swing.JPanel();
jlBeneficiaryUser = new javax.swing.JLabel();
jtfBeneficiaryUser = new javax.swing.JTextField();
jPanel12 = new javax.swing.JPanel();
jlCurrency = new javax.swing.JLabel();
jtfCurrency = new javax.swing.JTextField();
jPanel13 = new javax.swing.JPanel();
jlValueCy = new javax.swing.JLabel();
jtfValueCy = new javax.swing.JTextField();
jbValueCy = new javax.swing.JButton();
jlExchangeRateSystem = new javax.swing.JLabel();
jtfExchangeRateSystem = new javax.swing.JTextField();
jbExchangeRateSystem = new javax.swing.JButton();
jbExchangeRateAccountCashView = new javax.swing.JButton();
jPanel14 = new javax.swing.JPanel();
jlValue = new javax.swing.JLabel();
jtfValue = new javax.swing.JTextField();
jbValue = new javax.swing.JButton();
jlExchangeRate = new javax.swing.JLabel();
jtfExchangeRate = new javax.swing.JTextField();
jbExchangeRate = new javax.swing.JButton();
jbExchangeRateAccountCash = new javax.swing.JButton();
jckIsForBeneficiayAccount = new javax.swing.JCheckBox();
jPanel5 = new javax.swing.JPanel();
jlConcept = new javax.swing.JLabel();
jtfConcept = new javax.swing.JTextField();
jbConcept = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Egreso de efectivo con cheque");
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
});
jPanel1.setPreferredSize(new java.awt.Dimension(492, 33));
jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));
jbOk.setText("Aceptar");
jbOk.setToolTipText("[Ctrl + Enter]");
jbOk.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel1.add(jbOk);
jbCancel.setText("Cancelar");
jbCancel.setToolTipText("[Escape]");
jPanel1.add(jbCancel);
getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del registro:"));
jPanel2.setLayout(new java.awt.BorderLayout());
jPanel3.setLayout(new java.awt.GridLayout(14, 1, 0, 1));
jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
jlAccountCash.setText("Cuenta de efectivo: ");
jlAccountCash.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel4.add(jlAccountCash);
jtfCompanyBranch.setEditable(false);
jtfCompanyBranch.setText("COMPANY BRANCH");
jtfCompanyBranch.setFocusable(false);
jtfCompanyBranch.setPreferredSize(new java.awt.Dimension(150, 23));
jPanel4.add(jtfCompanyBranch);
jtfAccountCash.setEditable(false);
jtfAccountCash.setText("ACCOUNT CASH");
jtfAccountCash.setFocusable(false);
jtfAccountCash.setPreferredSize(new java.awt.Dimension(170, 23));
jPanel4.add(jtfAccountCash);
jtfCode.setEditable(false);
jtfCode.setText("CODE");
jtfCode.setFocusable(false);
jtfCode.setPreferredSize(new java.awt.Dimension(73, 23));
jPanel4.add(jtfCode);
jPanel3.add(jPanel4);
jPanel6.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
jlPkCheckWalletId.setForeground(java.awt.Color.blue);
jlPkCheckWalletId.setText("Chequera: *");
jlPkCheckWalletId.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel6.add(jlPkCheckWalletId);
jcbPkCheckWalletId.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbPkCheckWalletId.setPreferredSize(new java.awt.Dimension(397, 23));
jcbPkCheckWalletId.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jcbPkCheckWalletIdItemStateChanged(evt);
}
});
jPanel6.add(jcbPkCheckWalletId);
jPanel3.add(jPanel6);
jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
jlDate.setText("Fecha: *");
jlDate.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel7.add(jlDate);
jftDate.setText("dd/mm/yyyy");
jftDate.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel7.add(jftDate);
jbDate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/cal_date_day.gif"))); // NOI18N
jbDate.setToolTipText("Seleccionar fecha");
jbDate.setFocusable(false);
jbDate.setPreferredSize(new java.awt.Dimension(23, 23));
jPanel7.add(jbDate);
jPanel3.add(jPanel7);
jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
jlNumber.setText("Número: *");
jlNumber.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel8.add(jlNumber);
jtfNumber.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
jtfNumber.setText("NUMBER");
jtfNumber.setPreferredSize(new java.awt.Dimension(75, 23));
jPanel8.add(jtfNumber);
jPanel3.add(jPanel8);
jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
buttonGroup1.add(jrbIsBeneficiarySelected);
jrbIsBeneficiarySelected.setText("Seleccionar beneficiario");
jrbIsBeneficiarySelected.setPreferredSize(new java.awt.Dimension(300, 23));
jrbIsBeneficiarySelected.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jrbIsBeneficiarySelectedItemStateChanged(evt);
}
});
jPanel9.add(jrbIsBeneficiarySelected);
buttonGroup1.add(jrbIsBeneficiaryByUser);
jrbIsBeneficiaryByUser.setText("Ingresar beneficiario");
jrbIsBeneficiaryByUser.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jrbIsBeneficiaryByUserItemStateChanged(evt);
}
});
jPanel9.add(jrbIsBeneficiaryByUser);
jPanel3.add(jPanel9);
jPanel10.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
jlBeneficiary.setText("Beneficario: *");
jlBeneficiary.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel10.add(jlBeneficiary);
jcbBeneficiary.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbBeneficiary.setPreferredSize(new java.awt.Dimension(372, 23));
jcbBeneficiary.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jcbBeneficiaryItemStateChanged(evt);
}
});
jcbBeneficiary.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
jcbBeneficiaryFocusLost(evt);
}
});
jPanel10.add(jcbBeneficiary);
jbBeneficiary.setText("jButton1");
jbBeneficiary.setToolTipText("Seleccionar beneficiario");
jbBeneficiary.setFocusable(false);
jbBeneficiary.setPreferredSize(new java.awt.Dimension(23, 23));
jPanel10.add(jbBeneficiary);
jPanel3.add(jPanel10);
jPanel16.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
jlFkBizPartnerBranchId.setText("Sucursal beneficario:");
jlFkBizPartnerBranchId.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel16.add(jlFkBizPartnerBranchId);
jcbFkBizPartnerBranchId.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbFkBizPartnerBranchId.setPreferredSize(new java.awt.Dimension(397, 23));
jcbFkBizPartnerBranchId.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jcbFkBizPartnerBranchIdItemStateChanged(evt);
}
});
jPanel16.add(jcbFkBizPartnerBranchId);
jPanel3.add(jPanel16);
jPanel15.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
jlFkBizPartnerBankAccountId.setText("Cuenta bancaria beneficiario:");
jlFkBizPartnerBankAccountId.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel15.add(jlFkBizPartnerBankAccountId);
jcbFkBizPartnerBankAccountId.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbFkBizPartnerBankAccountId.setPreferredSize(new java.awt.Dimension(397, 23));
jPanel15.add(jcbFkBizPartnerBankAccountId);
jPanel3.add(jPanel15);
jPanel11.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
jlBeneficiaryUser.setText("Beneficiario (manual): *");
jlBeneficiaryUser.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel11.add(jlBeneficiaryUser);
jtfBeneficiaryUser.setText("BENEFICARY");
jtfBeneficiaryUser.setPreferredSize(new java.awt.Dimension(397, 23));
jPanel11.add(jtfBeneficiaryUser);
jPanel3.add(jPanel11);
jPanel12.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
jlCurrency.setText("Moneda:");
jlCurrency.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel12.add(jlCurrency);
jtfCurrency.setEditable(false);
jtfCurrency.setText("CURRENCY");
jtfCurrency.setFocusable(false);
jtfCurrency.setPreferredSize(new java.awt.Dimension(150, 23));
jPanel12.add(jtfCurrency);
jPanel3.add(jPanel12);
jPanel13.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
jlValueCy.setText("Monto: *");
jlValueCy.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel13.add(jlValueCy);
jtfValueCy.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
jtfValueCy.setText("1,000,000,000.00");
jtfValueCy.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel13.add(jtfValueCy);
jbValueCy.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_std_action.gif"))); // NOI18N
jbValueCy.setToolTipText("Calcular monto");
jbValueCy.setFocusable(false);
jbValueCy.setPreferredSize(new java.awt.Dimension(23, 23));
jPanel13.add(jbValueCy);
jlExchangeRateSystem.setText("Tipo de cambio sistema:");
jlExchangeRateSystem.setPreferredSize(new java.awt.Dimension(118, 23));
jPanel13.add(jlExchangeRateSystem);
jtfExchangeRateSystem.setEditable(false);
jtfExchangeRateSystem.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
jtfExchangeRateSystem.setText("1,000,000,000.00");
jtfExchangeRateSystem.setFocusable(false);
jtfExchangeRateSystem.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel13.add(jtfExchangeRateSystem);
jbExchangeRateSystem.setText("jButton5");
jbExchangeRateSystem.setToolTipText("Seleccionar tipo de cambio sistema");
jbExchangeRateSystem.setFocusable(false);
jbExchangeRateSystem.setPreferredSize(new java.awt.Dimension(23, 23));
jPanel13.add(jbExchangeRateSystem);
jbExchangeRateAccountCashView.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_std_look.gif"))); // NOI18N
jbExchangeRateAccountCashView.setToolTipText("Ver tipo de cambio acumulado");
jbExchangeRateAccountCashView.setFocusable(false);
jbExchangeRateAccountCashView.setPreferredSize(new java.awt.Dimension(23, 23));
jPanel13.add(jbExchangeRateAccountCashView);
jPanel3.add(jPanel13);
jPanel14.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
jlValue.setText("Monto moneda local (ML): *");
jlValue.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel14.add(jlValue);
jtfValue.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
jtfValue.setText("1,000,000,000.00");
jtfValue.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel14.add(jtfValue);
jbValue.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_std_action.gif"))); // NOI18N
jbValue.setToolTipText("Calcular monto moneda local");
jbValue.setFocusable(false);
jbValue.setPreferredSize(new java.awt.Dimension(23, 23));
jPanel14.add(jbValue);
jlExchangeRate.setText("Tipo de cambio: *");
jlExchangeRate.setPreferredSize(new java.awt.Dimension(118, 23));
jPanel14.add(jlExchangeRate);
jtfExchangeRate.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
jtfExchangeRate.setText("1,000,000,000.00");
jtfExchangeRate.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel14.add(jtfExchangeRate);
jbExchangeRate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_std_action.gif"))); // NOI18N
jbExchangeRate.setToolTipText("Calcular tipo de cambio");
jbExchangeRate.setFocusable(false);
jbExchangeRate.setPreferredSize(new java.awt.Dimension(23, 23));
jPanel14.add(jbExchangeRate);
jbExchangeRateAccountCash.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_std_money.gif"))); // NOI18N
jbExchangeRateAccountCash.setToolTipText("Asignar tipo de cambio acumulado");
jbExchangeRateAccountCash.setFocusable(false);
jbExchangeRateAccountCash.setPreferredSize(new java.awt.Dimension(23, 23));
jPanel14.add(jbExchangeRateAccountCash);
jPanel3.add(jPanel14);
jckIsForBeneficiayAccount.setText("Para abono en cuenta del beneficiario");
jPanel3.add(jckIsForBeneficiayAccount);
jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0));
jlConcept.setText("Concepto de la partida: *");
jlConcept.setPreferredSize(new java.awt.Dimension(175, 23));
jPanel5.add(jlConcept);
jtfConcept.setText("CONCEPT");
jtfConcept.setPreferredSize(new java.awt.Dimension(372, 23));
jPanel5.add(jtfConcept);
jbConcept.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_std_action.gif"))); // NOI18N
jbConcept.setToolTipText("Crear concepto");
jbConcept.setFocusable(false);
jbConcept.setPreferredSize(new java.awt.Dimension(23, 23));
jPanel5.add(jbConcept);
jPanel3.add(jPanel5);
jPanel2.add(jPanel3, java.awt.BorderLayout.PAGE_START);
getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-600)/2, (screenSize.height-450)/2, 600, 450);
}// </editor-fold>//GEN-END:initComponents
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
windowActivated();
}//GEN-LAST:event_formWindowActivated
private void jcbPkCheckWalletIdItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbPkCheckWalletIdItemStateChanged
if (!mbResetingForm) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
itemStateChangedPkCheckWalletId();
}
}
}//GEN-LAST:event_jcbPkCheckWalletIdItemStateChanged
private void jrbIsBeneficiarySelectedItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jrbIsBeneficiarySelectedItemStateChanged
if (!mbResetingForm) {
itemStateChangedIsBeneficiarySelected();
}
}//GEN-LAST:event_jrbIsBeneficiarySelectedItemStateChanged
private void jrbIsBeneficiaryByUserItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jrbIsBeneficiaryByUserItemStateChanged
if (!mbResetingForm) {
itemStateChangedIsBeneficiaryByUser();
}
}//GEN-LAST:event_jrbIsBeneficiaryByUserItemStateChanged
private void jcbBeneficiaryFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jcbBeneficiaryFocusLost
focusLostBeneficiary();
}//GEN-LAST:event_jcbBeneficiaryFocusLost
private void jcbBeneficiaryItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbBeneficiaryItemStateChanged
if (!mbResetingForm) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
itemStateChangedBeneficiary();
}
}
}//GEN-LAST:event_jcbBeneficiaryItemStateChanged
private void jcbFkBizPartnerBranchIdItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbFkBizPartnerBranchIdItemStateChanged
if (!mbResetingForm) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
itemStateChangedBizPartnerBranch();
}
}
}//GEN-LAST:event_jcbFkBizPartnerBranchIdItemStateChanged
private void initComponentsExtra() {
mvFields = new Vector<SFormField>();
moFieldConcept = new SFormField(miClient, SLibConstants.DATA_TYPE_STRING, true, jtfConcept, jlConcept);
moFieldConcept.setLengthMax(100);
moFieldPkCheckWalletId = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, true, jcbPkCheckWalletId, jlPkCheckWalletId);
moFieldNumber = new SFormField(miClient, SLibConstants.DATA_TYPE_INTEGER, true, jtfNumber, jlNumber);
moFieldDate = new SFormField(miClient, SLibConstants.DATA_TYPE_DATE, true, jftDate, jlDate);
moFieldDate.setPickerButton(jbDate);
moFieldBeneficiary = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbBeneficiary, jlBeneficiary);
moFieldBeneficiary.setPickerButton(jbBeneficiary);
moFieldFkBizPartnerBranchId = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbFkBizPartnerBranchId, jlFkBizPartnerBranchId);
moFieldFkBizPartnerBankAccountId = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbFkBizPartnerBankAccountId, jlFkBizPartnerBankAccountId);
moFieldBeneficiaryUser = new SFormField(miClient, SLibConstants.DATA_TYPE_STRING, false, jtfBeneficiaryUser, jlBeneficiaryUser);
moFieldBeneficiaryUser.setLengthMax(202);
moFieldValueCy = new SFormField(miClient, SLibConstants.DATA_TYPE_DOUBLE, true, jtfValueCy, jlValueCy);
moFieldValueCy.setDecimalFormat(miClient.getSessionXXX().getFormatters().getDecimalsValueFormat());
moFieldExchangeRateSystem = new SFormField(miClient, SLibConstants.DATA_TYPE_DOUBLE, false, jtfExchangeRateSystem, jlExchangeRateSystem);
moFieldExchangeRateSystem.setDecimalFormat(miClient.getSessionXXX().getFormatters().getDecimalsExchangeRateFormat());
moFieldValue = new SFormField(miClient, SLibConstants.DATA_TYPE_DOUBLE, true, jtfValue, jlValue);
moFieldValue.setDecimalFormat(miClient.getSessionXXX().getFormatters().getDecimalsValueFormat());
moFieldExchangeRate = new SFormField(miClient, SLibConstants.DATA_TYPE_DOUBLE, true, jtfExchangeRate, jlExchangeRate);
moFieldExchangeRate.setDecimalFormat(miClient.getSessionXXX().getFormatters().getDecimalsExchangeRateFormat());
moFieldIsForBeneficiaryAccount = new SFormField(miClient, SLibConstants.DATA_TYPE_BOOLEAN, false, jckIsForBeneficiayAccount);
mvFields.add(moFieldConcept);
mvFields.add(moFieldPkCheckWalletId);
mvFields.add(moFieldNumber);
mvFields.add(moFieldDate);
mvFields.add(moFieldBeneficiary);
mvFields.add(moFieldFkBizPartnerBranchId);
mvFields.add(moFieldFkBizPartnerBankAccountId);
mvFields.add(moFieldBeneficiaryUser);
mvFields.add(moFieldValueCy);
mvFields.add(moFieldValue);
mvFields.add(moFieldExchangeRateSystem);
mvFields.add(moFieldExchangeRate);
mvFields.add(moFieldIsForBeneficiaryAccount);
jbOk.addActionListener(this);
jbCancel.addActionListener(this);
jbDate.addActionListener(this);
jbExchangeRate.addActionListener(this);
jbExchangeRateSystem.addActionListener(this);
jbValueCy.addActionListener(this);
jbValue.addActionListener(this);
jbExchangeRateAccountCash.addActionListener(this);
jbExchangeRateAccountCashView.addActionListener(this);
jbBeneficiary.addActionListener(this);
jbConcept.addActionListener(this);
jtfValueCy.addFocusListener(this);
jtfValue.addFocusListener(this);
jtfExchangeRate.addFocusListener(this);
jtfNumber.addFocusListener(this);
jtfBeneficiaryUser.addFocusListener(this);
moParamRecord = null;
mvParamCheckVector = new Vector<SDataCheck>();
mvParamCheckVector.clear();
mnFkUser = 0;
AbstractAction actionOk = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) { actionOk(); }
};
SFormUtilities.putActionMap(getRootPane(), actionOk, "ok", KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK);
AbstractAction action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) { actionCancel(); }
};
SFormUtilities.putActionMap(getRootPane(), action, "cancel", KeyEvent.VK_ESCAPE, 0);
}
private void windowActivated() {
if (mbFirstTime) {
mbFirstTime = false;
if (moCheck != null) {
jftDate.requestFocus();
}
else {
jcbPkCheckWalletId.requestFocus();
}
}
renderCurrencySettings();
}
private void actionOk() {
SFormValidation validation = formValidate();
jbOk.requestFocus(); // this forces all pending focus lost function to be called
if (validation.getIsError()) {
if (validation.getComponent() != null) {
validation.getComponent().requestFocus();
}
if (validation.getMessage().length() > 0) {
miClient.showMsgBoxWarning(validation.getMessage());
}
}
else {
mnFormResult = SLibConstants.FORM_RESULT_OK;
setVisible(false);
}
}
private void actionCancel() {
mnFormResult = SLibConstants.FORM_RESULT_CANCEL;
setVisible(false);
}
private void actionSetDate() {
miClient.getGuiDatePickerXXX().formReset();
miClient.getGuiDatePickerXXX().setDate(moFieldDate.getDate());
miClient.getGuiDatePickerXXX().setVisible(true);
if (miClient.getGuiDatePickerXXX().getFormResult() == SLibConstants.FORM_RESULT_OK) {
moFieldDate.setFieldValue(miClient.getGuiDatePickerXXX().getGuiDate());
jftDate.requestFocus();
}
}
private double obtainExchangeRateAccountCash() {
double rate = 0;
double[] balance = null;
try {
balance = obtainCurrentAccountCashBalance();
rate = balance[0] == 0d ? 0d : balance[0] / balance[1];
}
catch (Exception e) {
SLibUtilities.printOutException(this, e);
}
return rate;
}
private double[] obtainCurrentAccountCashBalance() {
double[] balance = new double[2];
try {
balance = SDataUtilities.obtainAccountCashBalanceUpdated(miClient,
moParamRecord.getDbmsDataAccountCash().getFkCurrencyId(), moFieldDate.getDate(),
moParamRecord.getDbmsDataAccountCash().getPrimaryKey(),
moParamRecord.getDbmsDataAccountCash().getFkAccountCashCategoryId() == SDataConstantsSys.FINS_CT_ACC_CASH_CASH ?
SDataConstantsSys.FINS_TP_SYS_MOV_CASH_CASH : SDataConstantsSys.FINS_TP_SYS_MOV_CASH_BANK,
moParamRecord, moRecordEntry);
}
catch (Exception e) {
SLibUtilities.printOutException(this, e);
}
return balance;
}
private void renderCurrencySettings() {
SDataBizPartnerBranch oBranch = null;
oBranch = (SDataBizPartnerBranch) SDataUtilities.readRegistry(miClient,
SDataConstants.BPSU_BPB, new int[] { moParamRecord.getDbmsDataAccountCash().getPkCompanyBranchId() }, SLibConstants.EXEC_MODE_SILENT);
moCurrency = (SDataCurrency) SDataUtilities.readRegistry(miClient,
SDataConstants.CFGU_CUR, new int[] { moParamRecord.getDbmsDataAccountCash().getFkCurrencyId() }, SLibConstants.EXEC_MODE_SILENT);
jtfCompanyBranch.setText(oBranch.getBizPartnerBranch());
jtfAccountCash.setText(moParamRecord.getDbmsDataAccountCash().getDbmsCompanyBranchEntity().getEntity());
jtfCode.setText(moParamRecord.getDbmsDataAccountCash().getDbmsCompanyBranchEntity().getCode());
jtfCurrency.setText(moCurrency.getCurrency());
if (moParamRecord.getDbmsDataAccountCash().getFkCurrencyId() != miClient.getSessionXXX().getParamsErp().getFkCurrencyId()) {
jtfValue.setEnabled(true);
jbValue.setEnabled(true);
jtfExchangeRate.setEnabled(true);
jbExchangeRate.setEnabled(true);
jbExchangeRateSystem.setEnabled(true);
jbExchangeRateAccountCashView.setEnabled(true);
jbExchangeRateAccountCash.setEnabled(true);
if (moCheck == null) {
moFieldExchangeRate.setFieldValue(obtainExchangeRateAccountCash());
}
}
else {
jtfValue.setEnabled(false);
jbValue.setEnabled(false);
jtfExchangeRate.setEnabled(false);
jbExchangeRateSystem.setEnabled(false);
jbExchangeRate.setEnabled(false);
jbExchangeRateAccountCashView.setEnabled(false);
jbExchangeRateAccountCash.setEnabled(false);
moFieldExchangeRateSystem.setFieldValue(1);
moFieldExchangeRate.setFieldValue(1);
}
}
private void renderBeneficiarySettings(boolean b) {
jcbBeneficiary.setEnabled(b);
jtfBeneficiaryUser.setEnabled(!b);
jbBeneficiary.setEnabled(b);
renderBankAccountSettings(b);
}
private void renderBankAccountSettings(boolean b) {
if (b) {
if (moFieldBeneficiary.getKeyAsIntArray()[0] > 0) {
jcbFkBizPartnerBranchId.setEnabled(true);
}
if (moFieldFkBizPartnerBranchId.getKeyAsIntArray() != null) {
if (moFieldFkBizPartnerBranchId.getKeyAsIntArray()[0] > 0) {
jcbFkBizPartnerBankAccountId.setEnabled(true);
}
}
}
else {
jcbFkBizPartnerBranchId.setEnabled(false);
jcbFkBizPartnerBankAccountId.setEnabled(false);
}
}
private void itemStateChangedPkCheckWalletId() {
int number = 0;
if (moFieldNumber.getInteger() == 0 || moCheck == null) {
Vector<Object> params = new Vector<Object>();
params.add(moFieldPkCheckWalletId.getKeyAsIntArray()[0]);
params = SDataUtilities.callProcedure(miClient, SProcConstants.FIN_GET_CHECK_NEXT_NUM, params, SLibConstants.EXEC_MODE_SILENT);
number = (Integer) params.get(0);
for (int i = 0; i < mvParamCheckVector.size(); i++) {
if (number <= mvParamCheckVector.get(i).getNumber()) {
number += 1;
}
}
moFieldNumber.setFieldValue(number);
}
}
private void itemStateChangedIsBeneficiarySelected() {
renderBeneficiarySettings(true);
}
private void itemStateChangedIsBeneficiaryByUser() {
renderBeneficiarySettings(false);
}
private void itemStateChangedBeneficiary() {
if (moFieldBeneficiary.getKeyAsIntArray()[0] > 0) {
populateComboBoxBizPartnerBranch();
jcbFkBizPartnerBranchId.setEnabled(true);
}
else {
jcbFkBizPartnerBankAccountId.removeAllItems();
jcbFkBizPartnerBranchId.setEnabled(false);
}
}
private void itemStateChangedBizPartnerBranch() {
if (moFieldFkBizPartnerBranchId.getKeyAsIntArray()[0] > 0) {
jcbFkBizPartnerBankAccountId.setEnabled(true);
populateComboBoxBizPartnerBankAccount();
}
else {
jcbFkBizPartnerBankAccountId.setEnabled(false);
jcbFkBizPartnerBankAccountId.removeAllItems();
}
}
private void actionExchangeRateSystem() {
double rate = miClient.pickExchangeRate(moParamRecord.getDbmsDataAccountCash().getFkCurrencyId(), miClient.getSessionXXX().getWorkingDate());
if (rate != 0d) {
moFieldExchangeRateSystem.setFieldValue(rate);
if (moFieldExchangeRate.getDouble() == 0) {
moFieldExchangeRate.setFieldValue(rate);
}
jtfExchangeRate.requestFocus();
}
}
private void actionValueCy() {
if (moFieldExchangeRate.getDouble() == 0) {
jtfExchangeRate.requestFocus();
}
else {
moFieldValueCy.setFieldValue(SLibUtilities.round(moFieldValue.getDouble() / moFieldExchangeRate.getDouble(),
miClient.getSessionXXX().getParamsErp().getDecimalsValue()));
jtfValueCy.requestFocus();
}
}
private void actionValue() {
if (moFieldExchangeRate.getDouble() == 0) {
jtfExchangeRate.requestFocus();
}
else {
moFieldValue.setFieldValue(SLibUtilities.round(moFieldValueCy.getDouble() * moFieldExchangeRate.getDouble(),
miClient.getSessionXXX().getParamsErp().getDecimalsValue()));
jtfValue.requestFocus();
}
}
private void actionExchangeRate() {
if (moFieldValueCy.getDouble() != 0) {
if (moFieldValue.getDouble() == 0) {
jtfValueCy.requestFocus();
}
else {
moFieldExchangeRate.setFieldValue(moFieldValue.getDouble() / moFieldValueCy.getDouble());
jtfExchangeRate.requestFocus();
}
}
else if (moFieldValue.getDouble() != 0) {
jtfValue.requestFocus();
}
else {
jtfExchangeRate.requestFocus();
}
}
private void actionExchangeRateAccountCash() {
moFieldExchangeRate.setFieldValue(obtainExchangeRateAccountCash());
jtfExchangeRate.requestFocus();
}
private void actionExchangeRateAccountCashView() {
double[] balance = null;
try {
balance = obtainCurrentAccountCashBalance();
miClient.showMsgBoxInformation(
"Tipo de cambio acumulado al día: " + miClient.getSessionXXX().getFormatters().getDateFormat().format(moFieldDate.getDate()) + "\n" +
"Saldo " + miClient.getSessionXXX().getParamsErp().getDbmsDataCurrency().getKey() + ": $ " +
miClient.getSessionXXX().getFormatters().getDecimalsValueFormat().format(balance[0]) + ".\n" +
"Saldo " + moCurrency.getKey() + ": $ " +
miClient.getSessionXXX().getFormatters().getDecimalsValueFormat().format(balance[1]) + ".\n" +
"Tipo de cambio acumulado: " + miClient.getSessionXXX().getFormatters().getDecimalsExchangeRateFormat().format(balance[1] == 0d ? 0d : balance[0] / balance[1]) + ".");
}
catch (Exception e) {
SLibUtilities.renderException(this, e);
}
}
private void focusLostValueCy() {
if (moFieldValueCy.getDouble() != 0) {
if (!jtfValue.isEnabled() || moFieldValue.getDouble() == 0) {
moFieldValue.setFieldValue(SLibUtilities.round(moFieldValueCy.getDouble() * moFieldExchangeRate.getDouble(),
miClient.getSessionXXX().getParamsErp().getDecimalsValue()));
}
else if (moFieldExchangeRate.getDouble() == 0) {
moFieldExchangeRate.setFieldValue(SLibUtilities.round(moFieldValue.getDouble() / moFieldValueCy.getDouble(),
miClient.getSessionXXX().getParamsErp().getDecimalsExchangeRate()));
}
}
}
private void focusLostValue() {
if (moFieldValue.getDouble() != 0) {
if (moFieldValueCy.getDouble() == 0 && moFieldExchangeRate.getDouble() != 0) {
moFieldValueCy.setFieldValue(SLibUtilities.round(moFieldValue.getDouble() / moFieldExchangeRate.getDouble(),
miClient.getSessionXXX().getParamsErp().getDecimalsValue()));
}
else if (moFieldValueCy.getDouble() != 0 && moFieldExchangeRate.getDouble() == 0) {
moFieldExchangeRate.setFieldValue(SLibUtilities.round(moFieldValue.getDouble() / moFieldValueCy.getDouble(),
miClient.getSessionXXX().getParamsErp().getDecimalsExchangeRate()));
}
}
}
private void focusLostExchangeRate() {
if (moFieldValueCy.getDouble() != 0 && moFieldValue.getDouble() == 0) {
moFieldValue.setFieldValue(SLibUtilities.round(moFieldValueCy.getDouble() * moFieldExchangeRate.getDouble(),
miClient.getSessionXXX().getParamsErp().getDecimalsValue()));
}
}
private void focusLostNumber() {
if (jtfConcept.getText().length() == 0) {
createConcept();
}
}
private void focusLostBeneficiary() {
if (jtfConcept.getText().length() == 0) {
createConcept();
}
}
private void focusLostBeneficiaryUser() {
if (jtfConcept.getText().length() == 0) {
createConcept();
}
}
private void actionBeneficiary() {
miClient.pickOption(SDataConstants.BPSU_BP, moFieldBeneficiary, null);
}
private void populateComboBoxCheckWallet() {
SFormUtilities.populateComboBox(miClient, jcbPkCheckWalletId, SDataConstants.FIN_CHECK_WAL, new int[]
{ moParamRecord.getDbmsDataAccountCash().getPkCompanyBranchId(), moParamRecord.getDbmsDataAccountCash().getPkAccountCashId() });
}
private void populateComboBoxBizPartnerBranch() {
SFormUtilities.populateComboBox(miClient, jcbFkBizPartnerBranchId, SDataConstants.BPSU_BPB, moFieldBeneficiary.getKeyAsIntArray());
}
private void populateComboBoxBizPartnerBankAccount() {
SFormUtilities.populateComboBox(miClient, jcbFkBizPartnerBankAccountId, SDataConstants.BPSU_BANK_ACC, moFieldFkBizPartnerBranchId.getKeyAsIntArray());
}
private erp.mfin.data.SDataRecordEntry prepareRecordEntry() {
SDataRecordEntry oEntry = new SDataRecordEntry();
if (moRecordEntry != null) {
oEntry.setPkEntryId(moRecordEntry.getPkEntryId());
}
oEntry.setConcept(moFieldConcept.getString());
oEntry.setDebit(0);
oEntry.setCredit(moFieldValue.getDouble());
oEntry.setExchangeRate(moFieldExchangeRate.getDouble());
oEntry.setExchangeRateSystem(moFieldExchangeRateSystem.getDouble());
oEntry.setDebitCy(0);
oEntry.setCreditCy(moFieldValueCy.getDouble());
oEntry.setFkAccountIdXXX(moParamRecord.getDbmsDataAccountCash().getFkAccountId());
oEntry.setFkAccountingMoveTypeId(SDataConstantsSys.FINS_CLS_ACC_MOV_JOURNAL[0]);
oEntry.setFkAccountingMoveClassId(SDataConstantsSys.FINS_CLS_ACC_MOV_JOURNAL[1]);
oEntry.setFkAccountingMoveSubclassId(SDataConstantsSys.FINS_CLS_ACC_MOV_JOURNAL[2]);
oEntry.setFkSystemMoveClassId(SModSysConsts.FINS_TP_SYS_MOV_MO_SUP_PAY[0]);
oEntry.setFkSystemMoveTypeId(SModSysConsts.FINS_TP_SYS_MOV_MO_SUP_PAY[1]);
if (moParamRecord.getDbmsDataAccountCash().getFkAccountCashCategoryId() == SDataConstantsSys.FINS_CT_ACC_CASH_CASH) {
oEntry.setFkSystemAccountClassId(SModSysConsts.FINS_TP_SYS_ACC_ENT_CSH_CSH[0]);
oEntry.setFkSystemAccountTypeId(SModSysConsts.FINS_TP_SYS_ACC_ENT_CSH_CSH[1]);
oEntry.setFkSystemMoveCategoryIdXXX(SDataConstantsSys.FINS_TP_SYS_MOV_CASH_CASH[0]);
oEntry.setFkSystemMoveTypeIdXXX(SDataConstantsSys.FINS_TP_SYS_MOV_CASH_CASH[1]);
}
else {
oEntry.setFkSystemAccountClassId(SModSysConsts.FINS_TP_SYS_ACC_ENT_CSH_BNK[0]);
oEntry.setFkSystemAccountTypeId(SModSysConsts.FINS_TP_SYS_ACC_ENT_CSH_BNK[1]);
oEntry.setFkSystemMoveCategoryIdXXX(SDataConstantsSys.FINS_TP_SYS_MOV_CASH_BANK[0]);
oEntry.setFkSystemMoveTypeIdXXX(SDataConstantsSys.FINS_TP_SYS_MOV_CASH_BANK[1]);
}
oEntry.setFkCurrencyId(moParamRecord.getDbmsDataAccountCash().getFkCurrencyId());
oEntry.setFkCompanyBranchId_n(moParamRecord.getDbmsDataAccountCash().getPkCompanyBranchId());
oEntry.setFkEntityId_n(moParamRecord.getDbmsDataAccountCash().getPkAccountCashId());
oEntry.setDbmsAccount(SDataReadDescriptions.getCatalogueDescription(miClient, SDataConstants.FIN_ACC, new Object[] { oEntry.getFkAccountIdXXX() }));
oEntry.setDbmsAccountComplement(moParamRecord.getDbmsDataAccountCash().getAuxEntity());
oEntry.setDbmsAccountingMoveSubclass(SDataReadDescriptions.getCatalogueDescription(miClient, SDataConstants.FINS_CLS_ACC_MOV, SDataConstantsSys.FINS_CLS_ACC_MOV_JOURNAL));
oEntry.setDbmsCurrencyKey(moCurrency.getKey());
oEntry.setAuxCheckNumber(moCheck.getNumber());
oEntry.setFkUserNewId(miClient.getSession().getUser().getPkUserId());
oEntry.setFkUserEditId(mnFkUser > 0 ? miClient.getSession().getUser().getPkUserId() : SDataConstantsSys.USRX_USER_NA);
return oEntry;
}
/*private void searchBeneficiary() { //XXX
boolean bIsSelected = false;
for (int i = 0; i < jcbBeneficiary.getItemCount(); i++) {
if (moCheck.getBeneficiary().compareTo(jcbBeneficiary.getItemAt(i).toString()) == 0) {
bIsSelected = true;
moFieldBeneficiary.setKey(((SFormComponentItem) jcbBeneficiary.getItemAt(i)).getPrimaryKey());
jrbIsBeneficiarySelected.setSelected(true);
break;
}
}
if (!bIsSelected) {
moFieldBeneficiaryUser.setFieldValue(moCheck.getBeneficiary());
jrbIsBeneficiaryByUser.setSelected(true);
}
}*/
private void createConcept() {
if (moFieldNumber.getString().length() > 0 &&
(jrbIsBeneficiarySelected.isSelected() ? moFieldBeneficiary.getKeyAsIntArray()[0] > 0 : moFieldBeneficiaryUser.getString().length() > 0)) {
jtfConcept.setText("CH " + moFieldNumber.getString().replace(",", "") + "; " + (jrbIsBeneficiarySelected.isSelected() ? moFieldBeneficiary.getString() : moFieldBeneficiaryUser.getString()));
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel14;
private javax.swing.JPanel jPanel15;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JButton jbBeneficiary;
private javax.swing.JButton jbCancel;
private javax.swing.JButton jbConcept;
private javax.swing.JButton jbDate;
private javax.swing.JButton jbExchangeRate;
private javax.swing.JButton jbExchangeRateAccountCash;
private javax.swing.JButton jbExchangeRateAccountCashView;
private javax.swing.JButton jbExchangeRateSystem;
private javax.swing.JButton jbOk;
private javax.swing.JButton jbValue;
private javax.swing.JButton jbValueCy;
private javax.swing.JComboBox jcbBeneficiary;
private javax.swing.JComboBox jcbFkBizPartnerBankAccountId;
private javax.swing.JComboBox jcbFkBizPartnerBranchId;
private javax.swing.JComboBox jcbPkCheckWalletId;
private javax.swing.JCheckBox jckIsForBeneficiayAccount;
private javax.swing.JFormattedTextField jftDate;
private javax.swing.JLabel jlAccountCash;
private javax.swing.JLabel jlBeneficiary;
private javax.swing.JLabel jlBeneficiaryUser;
private javax.swing.JLabel jlConcept;
private javax.swing.JLabel jlCurrency;
private javax.swing.JLabel jlDate;
private javax.swing.JLabel jlExchangeRate;
private javax.swing.JLabel jlExchangeRateSystem;
private javax.swing.JLabel jlFkBizPartnerBankAccountId;
private javax.swing.JLabel jlFkBizPartnerBranchId;
private javax.swing.JLabel jlNumber;
private javax.swing.JLabel jlPkCheckWalletId;
private javax.swing.JLabel jlValue;
private javax.swing.JLabel jlValueCy;
private javax.swing.JRadioButton jrbIsBeneficiaryByUser;
private javax.swing.JRadioButton jrbIsBeneficiarySelected;
private javax.swing.JTextField jtfAccountCash;
private javax.swing.JTextField jtfBeneficiaryUser;
private javax.swing.JTextField jtfCode;
private javax.swing.JTextField jtfCompanyBranch;
private javax.swing.JTextField jtfConcept;
private javax.swing.JTextField jtfCurrency;
private javax.swing.JTextField jtfExchangeRate;
private javax.swing.JTextField jtfExchangeRateSystem;
private javax.swing.JTextField jtfNumber;
private javax.swing.JTextField jtfValue;
private javax.swing.JTextField jtfValueCy;
// End of variables declaration//GEN-END:variables
@Override
public void formClearRegistry() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void formReset() {
mnFormResult = SLibConstants.UNDEFINED;
mnFormStatus = SLibConstants.UNDEFINED;
mbFirstTime = true;
moCheck = null;
moRecordEntry = null;
for (int i = 0; i < mvFields.size(); i++) {
((erp.lib.form.SFormField) mvFields.get(i)).resetField();
}
moFieldDate.setFieldValue(moParamRecord == null ? miClient.getSessionXXX().getWorkingDate() : moParamRecord.getDate());
jcbFkBizPartnerBranchId.setEnabled(false);
jcbFkBizPartnerBankAccountId.setEnabled(false);
jcbFkBizPartnerBranchId.removeAllItems();
jcbFkBizPartnerBankAccountId.removeAllItems();
jcbPkCheckWalletId.setEnabled(true);
jckIsForBeneficiayAccount.setSelected(true);
jrbIsBeneficiarySelected.setSelected(true);
itemStateChangedIsBeneficiarySelected();
mbResetingForm = false;
}
@Override
public void formRefreshCatalogues() {
mbResetingForm = true;
SFormUtilities.populateComboBox(miClient, jcbBeneficiary, SDataConstants.BPSU_BP);
}
@Override
public erp.lib.form.SFormValidation formValidate() {
String message = "";
SFormValidation validation = new SFormValidation();
SDataCheckWallet oWallet = null;
for (int i = 0; i < mvFields.size(); i++) {
if (!((erp.lib.form.SFormField) mvFields.get(i)).validateField()) {
validation.setIsError(true);
validation.setComponent(((erp.lib.form.SFormField) mvFields.get(i)).getComponent());
break;
}
}
if (!validation.getIsError()) {
Object[] oParamsIn = new Object[] { moFieldPkCheckWalletId.getKeyAsIntArray()[0], moCheck == null ? 0 : moCheck.getPkCheckId(),
moFieldNumber.getInteger() };
oWallet = (SDataCheckWallet) SDataUtilities.readRegistry(miClient, SDataConstants.FIN_CHECK_WAL, moFieldPkCheckWalletId.getKeyAsIntArray(), SLibConstants.EXEC_MODE_SILENT);
if (SDataUtilities.callProcedureVal(miClient, SProcConstants.FIN_CHECK_NUM_VAL, oParamsIn, SLibConstants.EXEC_MODE_VERBOSE) > 0) {
validation.setMessage("El valor del campo '" + jlNumber.getText() + "' ya existe.");
validation.setComponent(jtfNumber);
}
else if (moFieldNumber.getInteger() < oWallet.getNumberStart() || oWallet.getNumberEnd_n() > 0 && moFieldNumber.getInteger() > oWallet.getNumberEnd_n()) {
validation.setMessage("El valor del campo '" + jlNumber.getText() + "' esta fuera del rango de folios valido.");
validation.setComponent(jtfNumber);
}
else if (jrbIsBeneficiarySelected.isSelected() && moFieldBeneficiary.getKeyAsIntArray()[0] == 0) {
validation.setMessage("Se debe ingresar un valor para el campo '" + jlBeneficiary.getText() + "'.");
validation.setComponent(jcbBeneficiary);
}
else if (jrbIsBeneficiaryByUser.isSelected() && moFieldBeneficiaryUser.getString().length() == 0) {
validation.setMessage("Se debe ingresar un valor para el campo '" + jlBeneficiaryUser.getText() + "'.");
validation.setComponent(jtfBeneficiaryUser);
}
else if (!SDataUtilities.isPeriodOpen(miClient, moFieldDate.getDate())) {
validation.setMessage(SLibConstants.MSG_ERR_GUI_PER_CLOSE);
validation.setComponent(jftDate);
}
else {
message = SDataUtilities.validateExchangeRate(miClient, moFieldValueCy.getDouble(), moFieldExchangeRate.getDouble(), moFieldValue.getDouble(), jlValueCy.getText());
if (message.length() > 0) {
if (miClient.showMsgBoxConfirm(message + "\n" + SLibConstants.MSG_CNF_MSG_CONT) != JOptionPane.YES_OPTION) {
validation.setMessage(SLibConstants.MSG_ERR_GUI_FIELD_VALUE_DIF + "'" + jlValueCy.getText() + "'.");
validation.setComponent(jtfValueCy);
}
}
}
}
if (!validation.getIsError()) {
if (jrbIsBeneficiarySelected.isSelected()) {
if (moFieldFkBizPartnerBranchId.getKeyAsIntArray()[0] > 0 && moFieldFkBizPartnerBankAccountId.getKeyAsIntArray()[1] == 0 ) {
validation.setMessage("Se debe seleccionar un valor para el campo '" + jlFkBizPartnerBankAccountId.getText() + "'.");
validation.setComponent(jcbFkBizPartnerBankAccountId);
}
}
}
return validation;
}
@Override
public void setFormStatus(int status) {
mnFormStatus = status;
}
@Override
public void setFormVisible(boolean visible) {
setVisible(visible);
}
@Override
public int getFormStatus() {
return mnFormStatus;
}
@Override
public int getFormResult() {
return mnFormResult;
}
@Override
public void setRegistry(erp.lib.data.SDataRegistry registry) {
moRecordEntry = (SDataRecordEntry) registry;
moCheck = moRecordEntry.getDbmsCheck();
moFieldConcept.setFieldValue(moRecordEntry.getConcept());
moFieldPkCheckWalletId.setFieldValue(new int[] { moCheck.getPkCheckWalletId() });
moFieldNumber.setFieldValue(moCheck.getNumber());
moFieldDate.setFieldValue(moCheck.getDate());
if (moCheck.getFkBizPartnerId_nr() > 0) {
moFieldBeneficiary.setKey(new int[] { moCheck.getFkBizPartnerId_nr() });
moFieldFkBizPartnerBranchId.setKey(new int[] { moCheck.getFkBizPartnerBranchId() });
moFieldFkBizPartnerBankAccountId.setKey(new int[] { moCheck.getFkBizPartnerBranchId(), moCheck.getFkBankAccountId() });
jcbFkBizPartnerBranchId.setEnabled(true);
jcbFkBizPartnerBankAccountId.setEnabled(moCheck.getFkBankAccountId() > 0);
jrbIsBeneficiarySelected.setSelected(true);
}
else {
moFieldBeneficiaryUser.setFieldValue(moCheck.getBeneficiary());
jcbFkBizPartnerBranchId.setEnabled(false);
jcbFkBizPartnerBankAccountId.setEnabled(false);
jrbIsBeneficiaryByUser.setSelected(true);
}
moFieldValueCy.setFieldValue(moCheck.getValue());
moFieldValue.setFieldValue(moRecordEntry.getCredit());
moFieldExchangeRateSystem.setFieldValue(moRecordEntry.getExchangeRateSystem());
moFieldExchangeRate.setFieldValue(moRecordEntry.getExchangeRate());
moFieldIsForBeneficiaryAccount.setFieldValue(moCheck.getIsForBeneficiaryAccount());
//searchBeneficiary();
mnFkUser = moRecordEntry.getFkUserNewId();
jcbPkCheckWalletId.setEnabled(false);
}
@Override
public erp.lib.data.SDataRegistry getRegistry() {
if (moCheck == null) {
moCheck = new SDataCheck();
moCheck.setFkUserNewId(miClient.getSession().getUser().getPkUserId());
}
else {
moCheck.setFkUserEditId(miClient.getSession().getUser().getPkUserId());
}
moCheck.setPkCheckWalletId(moFieldPkCheckWalletId.getKeyAsIntArray()[0]);
moCheck.setNumber(moFieldNumber.getInteger());
moCheck.setDate(moFieldDate.getDate());
moCheck.setBeneficiary(jrbIsBeneficiarySelected.isSelected() ? moFieldBeneficiary.getString() : moFieldBeneficiaryUser.getString());
if (jrbIsBeneficiarySelected.isSelected()) {
moCheck.setFkBizPartnerId_nr(moFieldBeneficiary.getKeyAsIntArray()[0] > 0 ? moFieldBeneficiary.getKeyAsIntArray()[0] : 0);
moCheck.setFkBizPartnerBranchId(moFieldFkBizPartnerBranchId.getKeyAsIntArray() != null ? moFieldFkBizPartnerBranchId.getKeyAsIntArray()[0] : 0);
moCheck.setFkBankAccountId(moFieldFkBizPartnerBankAccountId.getKeyAsIntArray() != null ? moFieldFkBizPartnerBankAccountId.getKeyAsIntArray()[1] : 0);
}
else if (jrbIsBeneficiaryByUser.isSelected()) {
moCheck.setFkBizPartnerId_nr(0);
moCheck.setFkBizPartnerBranchId(0);
moCheck.setFkBankAccountId(0);
}
moCheck.setValue(moFieldValueCy.getDouble());
moCheck.setIsForBeneficiaryAccount(moFieldIsForBeneficiaryAccount.getBoolean());
moCheck.setFkCheckStatusId(SDataConstantsSys.TRNS_ST_DPS_EMITED);
moCheck.seAuxCurrencyId(moCurrency.getPkCurrencyId());
moRecordEntry = prepareRecordEntry();
moRecordEntry.setDbmsCheck(moCheck);
return moRecordEntry;
}
@Override
@SuppressWarnings("unchecked")
public void setValue(int type, java.lang.Object value) {
if (type == SDataConstants.FIN_REC) {
moParamRecord = (SDataRecord) value;
populateComboBoxCheckWallet();
}
else if (type == SDataConstants.FIN_CHECK) {
mvParamCheckVector = (Vector<SDataCheck>) value;
}
}
@Override
public java.lang.Object getValue(int type) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public javax.swing.JLabel getTimeoutLabel() {
return null;
}
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
if (e.getSource() instanceof javax.swing.JButton) {
javax.swing.JButton button = (javax.swing.JButton) e.getSource();
if (button == jbOk) {
actionOk();
}
else if (button == jbCancel) {
actionCancel();
}
else if (button == jbDate) {
actionSetDate();
}
else if (button == jbValueCy) {
actionValueCy();
}
else if (button == jbValue) {
actionValue();
}
else if (button == jbExchangeRateSystem) {
actionExchangeRateSystem();
}
else if (button == jbExchangeRate) {
actionExchangeRate();
}
else if (button == jbExchangeRateAccountCash) {
actionExchangeRateAccountCash();
}
else if (button == jbExchangeRateAccountCashView) {
actionExchangeRateAccountCashView();
}
else if (button == jbBeneficiary) {
actionBeneficiary();
}
else if (button == jbConcept) {
createConcept();
}
}
}
@Override
public void focusGained(java.awt.event.FocusEvent e) {
}
@Override
public void focusLost(java.awt.event.FocusEvent e) {
if (e.getSource() instanceof javax.swing.JTextField) {
JTextField textField = (JTextField) e.getSource();
if (textField == jtfValueCy) {
focusLostValueCy();
}
else if (textField == jtfValue) {
focusLostValue();
}
else if (textField == jtfExchangeRate) {
focusLostExchangeRate();
}
else if (textField == jtfNumber) {
focusLostNumber();
}
else if (textField == jtfBeneficiaryUser) {
focusLostBeneficiaryUser();
}
}
}
}
|
3e0a438687eadd2e117fcfb1167848655981689a | 2,160 | java | Java | gradle-require-dependency-compliance-plugin/src/main/java/de/acetous/dependencycompliance/export/DependencyExportTask.java | acetous/gradle-enforce-dependency-compliance | 7b094f224c93f200bb5eb3f1437dc9511b938317 | [
"Apache-2.0"
] | 2 | 2019-06-09T04:06:40.000Z | 2019-06-28T11:26:11.000Z | gradle-require-dependency-compliance-plugin/src/main/java/de/acetous/dependencycompliance/export/DependencyExportTask.java | acetous/gradle-enforce-dependency-compliance | 7b094f224c93f200bb5eb3f1437dc9511b938317 | [
"Apache-2.0"
] | 8 | 2018-08-27T04:29:04.000Z | 2021-07-09T14:28:59.000Z | gradle-require-dependency-compliance-plugin/src/main/java/de/acetous/dependencycompliance/export/DependencyExportTask.java | acetous/gradle-enforce-dependency-compliance | 7b094f224c93f200bb5eb3f1437dc9511b938317 | [
"Apache-2.0"
] | 3 | 2020-06-23T11:48:47.000Z | 2022-02-24T20:41:26.000Z | 33.75 | 131 | 0.684722 | 4,349 | package de.acetous.dependencycompliance.export;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import de.acetous.dependencycompliance.DependencyTask;
import org.gradle.api.tasks.TaskAction;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Set;
/**
* Task to export all dependencies and repositories to the {@code outputFile}.
*/
public class DependencyExportTask extends DependencyTask {
private Gson gson = new GsonBuilder().setPrettyPrinting().create();
@TaskAction
void writeDependencies() {
Set<DependencyIdentifier> dependencyFilter = loadDependencyFilter();
if (!dependencyFilter.isEmpty()) {
logDependencyFilter(dependencyFilter);
}
List<DependencyIdentifier> dependencies = resolveDependencies();
List<DependencyIdentifier> buildDependencies = resolveBuildDependencies();
Set<RepositoryIdentifier> repositories = resolveRepositories();
Set<RepositoryIdentifier> buildRepositories = resolveBuildRepositories();
DependencyExport dependencyExport = new DependencyExport(dependencies, buildDependencies, repositories, buildRepositories);
String exportJson = gson.toJson(dependencyExport);
Path path = outputFile.getAsFile().get().toPath();
createFile(path);
try {
Files.write(path, exportJson.getBytes(CHARSET), StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException e) {
throw new IllegalStateException("Cannot write file: " + path);
}
}
/**
* Create a file if not present. Created intermediate directories.
*
* @param path The path to the file.
*/
private void createFile(Path path) {
Path parent = path.getParent();
try {
Files.createDirectories(parent);
if (!Files.isRegularFile(path)) {
Files.createFile(path);
}
} catch (IOException e) {
throw new IllegalStateException("Cannot create file: " + path);
}
}
}
|
3e0a440cd7551589792e2083cec72521591c6154 | 3,453 | java | Java | common/junit-platform-native/src/main/java/org/graalvm/junit/platform/NativeImageConfigurationImpl.java | hannesd/native-build-tools | e08907fba8e05aa6d1c436c05467ce10928a4937 | [
"UPL-1.0",
"Apache-2.0"
] | 138 | 2021-06-14T14:46:24.000Z | 2022-03-31T18:22:48.000Z | common/junit-platform-native/src/main/java/org/graalvm/junit/platform/NativeImageConfigurationImpl.java | hannesd/native-build-tools | e08907fba8e05aa6d1c436c05467ce10928a4937 | [
"UPL-1.0",
"Apache-2.0"
] | 135 | 2021-06-14T16:33:19.000Z | 2022-03-31T20:50:21.000Z | common/junit-platform-native/src/main/java/org/graalvm/junit/platform/NativeImageConfigurationImpl.java | hannesd/native-build-tools | e08907fba8e05aa6d1c436c05467ce10928a4937 | [
"UPL-1.0",
"Apache-2.0"
] | 20 | 2021-06-21T07:54:15.000Z | 2022-03-12T05:38:58.000Z | 40.151163 | 159 | 0.727773 | 4,350 | /*
* Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must 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.graalvm.junit.platform;
import org.graalvm.junit.platform.config.core.NativeImageConfiguration;
import org.graalvm.nativeimage.hosted.RuntimeClassInitialization;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
class NativeImageConfigurationImpl implements NativeImageConfiguration {
@Override
public void registerForReflection(Class<?>... classes) {
RuntimeReflection.register(classes);
}
@Override
public void registerForReflection(Executable... methods) {
RuntimeReflection.register(methods);
}
@Override
public void registerForReflection(Field... fields) {
RuntimeReflection.register(fields);
}
@Override
public void initializeAtBuildTime(String... classNames) {
for (String className : classNames) {
Class<?> clazz;
try {
clazz = Class.forName(className);
initializeAtBuildTime(clazz);
} catch (ClassNotFoundException e) {
JUnitPlatformFeature.debug("[Native Image Configuration] Failed to register class for build time initialization: %s Reason: %s", className, e);
}
}
}
@Override
public void initializeAtBuildTime(Class<?>... classes) {
RuntimeClassInitialization.initializeAtBuildTime(classes);
}
}
|
3e0a44f551c44a9fb751c859b9d5e5ea7072e6b6 | 1,242 | java | Java | org.jpat.scuba.core/src/main/java/org/jpat/scuba/core/command/system/ScubaControllerCreator.java | JPAT-ROSEMARY/SCUBA | 0d7dcee9e62e724af8dc006e1399d5c3e7b77dd1 | [
"MIT"
] | 2 | 2015-08-06T02:39:53.000Z | 2015-08-06T02:41:13.000Z | org.jpat.scuba.core/src/main/java/org/jpat/scuba/core/command/system/ScubaControllerCreator.java | JPAT-ROSEMARY/SCUBA | 0d7dcee9e62e724af8dc006e1399d5c3e7b77dd1 | [
"MIT"
] | 2 | 2019-04-23T19:18:03.000Z | 2022-01-21T23:25:48.000Z | org.jpat.scuba.core/src/main/java/org/jpat/scuba/core/command/system/ScubaControllerCreator.java | JPAT-ROSEMARY/SCUBA | 0d7dcee9e62e724af8dc006e1399d5c3e7b77dd1 | [
"MIT"
] | 1 | 2016-03-09T21:25:10.000Z | 2016-03-09T21:25:10.000Z | 37.636364 | 140 | 0.743961 | 4,351 | package org.jpat.scuba.core.command.system;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jpat.scuba.core.controller.AnalysisProvider;
import org.jpat.scuba.core.controller.ScubaController;
import org.jpat.scuba.core.model.IAnalysisProvider;
import org.jpat.scuba.core.model.IScubaController;
public final class ScubaControllerCreator
{
public ScubaControllerCreator()
{
super();
}
public static IScubaController create(final List<IAnalysisProvider> analysisProviders)
{
assert null != analysisProviders : "Parameter 'analysisProviders' of method 'create' must not be null";
assert !analysisProviders.isEmpty() : "Parameter 'analysisProviders' of method 'create' must not be empty";
final Set<AnalysisProvider> concreteAnalysisProviders = new HashSet<>(analysisProviders.size());
analysisProviders.forEach(nextAnalysisProvider -> {
assert nextAnalysisProvider instanceof AnalysisProvider : "Not an analysis provider: '" + nextAnalysisProvider.getClass() + "'";
concreteAnalysisProviders.add((AnalysisProvider) nextAnalysisProvider);
});
return new ScubaController(concreteAnalysisProviders);
}
}
|
3e0a45b861349ceeee6c5cea16639ce5d978a3d1 | 460 | java | Java | application/service/src/main/java/com/batis/application/service/system/StorageService.java | yanweixin/Batis | d2555d6ef097084ea19450ecc1015140c445bb56 | [
"MIT"
] | null | null | null | application/service/src/main/java/com/batis/application/service/system/StorageService.java | yanweixin/Batis | d2555d6ef097084ea19450ecc1015140c445bb56 | [
"MIT"
] | null | null | null | application/service/src/main/java/com/batis/application/service/system/StorageService.java | yanweixin/Batis | d2555d6ef097084ea19450ecc1015140c445bb56 | [
"MIT"
] | null | null | null | 19.166667 | 55 | 0.745652 | 4,352 | package com.batis.application.service.system;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Path;
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path getRootLocation();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
|
3e0a469271acabea1af2c4ea789023be1dcdc616 | 2,486 | java | Java | src/model2/Model2.java | Nourhann/GP | f61313daeecc8f58c2839196fd4bab0cfc1189cd | [
"BSD-3-Clause"
] | null | null | null | src/model2/Model2.java | Nourhann/GP | f61313daeecc8f58c2839196fd4bab0cfc1189cd | [
"BSD-3-Clause"
] | null | null | null | src/model2/Model2.java | Nourhann/GP | f61313daeecc8f58c2839196fd4bab0cfc1189cd | [
"BSD-3-Clause"
] | null | null | null | 28.25 | 83 | 0.638777 | 4,353 | /*
* 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 model2;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.scene.layout.HBox;
import javafx.scene.control.Button;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
/**
*
* @author norhan
*/
public class Model2 extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
// stage.setResizable(false);
//stage.initStyle(StageStyle.values());
stage.initStyle(StageStyle.UNDECORATED);
BorderPane borderPane = new BorderPane();
//borderPane.setStyle("-fx-background-color: green;");
ToolBar toolBar = new ToolBar();
int height = 25;
toolBar.setPrefHeight(height);
toolBar.setMinHeight(height);
toolBar.setMaxHeight(height);
toolBar.setStyle("-fx-background-color: #010b17;");
WindowButtons button = new WindowButtons();
button.setAlignment(Pos.CENTER_RIGHT);
button.setStyle("-fx-background-color: red;");
//button.setAlignment(Pos.valueOf());
toolBar.getItems().add(button);
borderPane.setTop(toolBar);
borderPane.setBottom(root);
stage.setScene(new Scene(borderPane));
stage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
class WindowButtons extends HBox {
public WindowButtons() {
Button closeBtn = new Button("X");
closeBtn.setStyle("-fx-background-color: red;");
closeBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
Platform.exit();
}
});
this.getChildren().add(closeBtn);
}
}
}
|
3e0a46f7de75dac1fc6a0d3b959802b281ab50a4 | 2,248 | java | Java | src/main/java/com/xuzp/insuredxmltool/core/insurance/plan/filter/CoverageFilter.java | xuziping/InsuredProductXmlGenerator | e94a19cf4be93ca8811cf3722ac8c16e7e135327 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/xuzp/insuredxmltool/core/insurance/plan/filter/CoverageFilter.java | xuziping/InsuredProductXmlGenerator | e94a19cf4be93ca8811cf3722ac8c16e7e135327 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/xuzp/insuredxmltool/core/insurance/plan/filter/CoverageFilter.java | xuziping/InsuredProductXmlGenerator | e94a19cf4be93ca8811cf3722ac8c16e7e135327 | [
"Apache-2.0"
] | null | null | null | 28.820513 | 92 | 0.733096 | 4,354 | /**
* 保险责任
* 除了旧版本支持的文字段落排版外,额外添加的功能有:
* 1.可以插入图片。
* 2.可以插入表格。
* 3.可以通过插入变量或公式来表示一段可变的文字或数字。
*/
package com.xuzp.insuredxmltool.core.insurance.plan.filter;
import com.xuzp.insuredxmltool.core.insurance.plan.Commodity;
import com.xuzp.insuredxmltool.core.insurance.plan.filter.table.Table;
import com.xuzp.insuredxmltool.core.insurance.plan.filter.table.TableFilter;
import com.xuzp.insuredxmltool.core.insurance.product.Insurance;
import com.xuzp.insuredxmltool.core.insurance.product.attachment.coverage.Coverage;
import com.xuzp.insuredxmltool.core.insurance.product.attachment.coverage.CoverageParagraph;
import com.xuzp.insuredxmltool.core.insurance.product.attachment.table.TableDef;
import com.xuzp.insuredxmltool.core.tool.formula.Factors;
import com.xuzp.insuredxmltool.core.tool.formula.Formula;
import com.xuzp.insuredxmltool.core.tool.formula.Value;
public class CoverageFilter implements FilterCommodity
{
private static final long serialVersionUID = 1L;
public CoverageFilter()
{
}
@Override
public Object filtrate(Commodity p, String attachmentName)
{
Insurance ins = p.getProduct();
Coverage coverage = (Coverage)(ins.getAttachment(attachmentName));
int c = coverage.getParagraphCount();
Coverage result = new Coverage();
for (int i = 0; i < c; i++)
{
CoverageParagraph cp = coverage.getParagraph(i);
if (cp.getCondition() == null || Value.booleanOf(cp.getCondition(), p.getFactors()))
result.addParagrpah(compileParagraph(cp, p.getFactors()));
}
return result;
}
private CoverageParagraph compileParagraph(CoverageParagraph cp, Factors factors)
{
CoverageParagraph r = new CoverageParagraph();
r.setTitle(cp.getTitle());
for (int i=0;i<cp.size();i++)
{
int type = cp.getType(i);
Object o = cp.getContent(i);
if (type == CoverageParagraph.TEXT)
{
r.addContent(type, o);
}
else if (type == CoverageParagraph.FORMULA)
{
Object value = ((Formula)o).run(factors);
r.addContent(CoverageParagraph.TEXT, value == null ? null : value.toString());
}
else if (type == CoverageParagraph.TABLE)
{
Table table = TableFilter.filterTable((TableDef)o, factors, null);
r.addContent(type, table);
}
}
return r;
}
}
|
3e0a4a2a2a39eaf9a671d2255ee7b4c8c5479638 | 1,293 | java | Java | src/main/java/com/zos/generate/dto/WorkflowTemplateDTO.java | zostudio/zos | 62aa4144249e82ffc9cc00ee68997533a8614926 | [
"MIT"
] | 1 | 2019-09-19T03:42:59.000Z | 2019-09-19T03:42:59.000Z | src/main/java/com/zos/generate/dto/WorkflowTemplateDTO.java | zostudio/zos | 62aa4144249e82ffc9cc00ee68997533a8614926 | [
"MIT"
] | null | null | null | src/main/java/com/zos/generate/dto/WorkflowTemplateDTO.java | zostudio/zos | 62aa4144249e82ffc9cc00ee68997533a8614926 | [
"MIT"
] | null | null | null | 21.915254 | 57 | 0.689869 | 4,356 | package com.zos.generate.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* 暂无表注释
*
* @author 01Studio
*/
@ApiModel(description = "暂无表注释")
public class WorkflowTemplateDTO {
@ApiModelProperty(value = "流程模版主键", example = "0")
private java.lang.Long templateId;
@ApiModelProperty(value = "流程唯一标识", example = "String")
private java.lang.String processKey;
@ApiModelProperty(value = "流程唯一代码", example = "String")
private java.lang.String objType;
@ApiModelProperty(value = "流程唯一名称", example = "String")
private java.lang.String processName;
public void setTemplateId(java.lang.Long value) {
this.templateId = value;
}
public java.lang.Long getTemplateId() {
return this.templateId;
}
public java.lang.String getProcessKey() {
return this.processKey;
}
public void setProcessKey(java.lang.String value) {
this.processKey = value;
}
public java.lang.String getObjType() {
return this.objType;
}
public void setObjType(java.lang.String value) {
this.objType = value;
}
public java.lang.String getProcessName() {
return this.processName;
}
public void setProcessName(java.lang.String value) {
this.processName = value;
}
}
|
3e0a4a69c054f1b53d515cc5291f3da3a572efc4 | 2,060 | java | Java | spring-social-weibo/src/main/java/com/georges/social/weibo/api/impl/WeiboTemplate.java | alexzuo/spring-social-weibo | a0860b17d5827fc1a95aba59dd85fa2269172f44 | [
"Apache-2.0"
] | 1 | 2016-07-22T07:52:44.000Z | 2016-07-22T07:52:44.000Z | spring-social-weibo/src/main/java/com/georges/social/weibo/api/impl/WeiboTemplate.java | alexzuo/spring-social-weibo | a0860b17d5827fc1a95aba59dd85fa2269172f44 | [
"Apache-2.0"
] | null | null | null | spring-social-weibo/src/main/java/com/georges/social/weibo/api/impl/WeiboTemplate.java | alexzuo/spring-social-weibo | a0860b17d5827fc1a95aba59dd85fa2269172f44 | [
"Apache-2.0"
] | null | null | null | 26.410256 | 99 | 0.780583 | 4,357 | /**
*
*/
package com.georges.social.weibo.api.impl;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import com.georges.social.weibo.api.UserOperations;
import com.georges.social.weibo.api.Weibo;
import com.georges.social.weibo.api.impl.json.WeiboModule;
import com.georges.social.weibo.connect.WeiboRequestInterceptor;
/**
* @author alexzuo
*
*/
public class WeiboTemplate extends AbstractOAuth2ApiBinding implements Weibo {
private UserOperations userOperations;
private ObjectMapper objectMapper;
/**
*
*/
public WeiboTemplate() {
super();
initialize();
}
/**
* @param consumerKey
* @param consumerSecret
* @param accessToken
* @param accessTokenSecret
*/
public WeiboTemplate(String accessToken) {
super(accessToken);
List<ClientHttpRequestInterceptor> interceptors = new LinkedList<ClientHttpRequestInterceptor>();
interceptors.add(new WeiboRequestInterceptor(accessToken));
getRestTemplate().setInterceptors(interceptors);
initialize();
}
private void initialize() {
userOperations = new UserTemplate(this, getRestTemplate(),
isAuthorized());
}
/**
* @return the userOperations
*/
public UserOperations userOperations() {
return userOperations;
}
protected MappingJacksonHttpMessageConverter getJsonMessageConverter() {
MappingJacksonHttpMessageConverter converter = super
.getJsonMessageConverter();
List<MediaType> list = new ArrayList<MediaType>();
list.addAll(converter.getSupportedMediaTypes());
list.add(MediaType.TEXT_PLAIN);
converter.setSupportedMediaTypes(list);
objectMapper = new ObjectMapper();
objectMapper.registerModule(new WeiboModule());
converter.setObjectMapper(objectMapper);
return converter;
}
}
|
3e0a4aee0ca5bfa8dc9219371e42ccc134efcf72 | 22,793 | java | Java | src/main/java/org/dasein/persist/RelationalCache.java | greese/dasein-persist | 1104621ad1670a45488b093b984ec1db4c7be781 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/dasein/persist/RelationalCache.java | greese/dasein-persist | 1104621ad1670a45488b093b984ec1db4c7be781 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/dasein/persist/RelationalCache.java | greese/dasein-persist | 1104621ad1670a45488b093b984ec1db4c7be781 | [
"Apache-2.0"
] | 1 | 2019-04-23T03:31:40.000Z | 2019-04-23T03:31:40.000Z | 35.558502 | 149 | 0.53999 | 4,358 | /**
* Copyright (C) 1998-2011 enStratusNetworks 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
*
* 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.dasein.persist;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.log4j.Logger;
import org.dasein.persist.jdbc.AutomatedSql.Operator;
import org.dasein.persist.jdbc.AutomatedSql.TranslationMethod;
import org.dasein.persist.jdbc.Counter;
import org.dasein.persist.jdbc.Creator;
import org.dasein.persist.jdbc.Deleter;
import org.dasein.persist.jdbc.Loader;
import org.dasein.persist.jdbc.Updater;
import org.dasein.util.CacheLoader;
import org.dasein.util.CacheManagementException;
import org.dasein.util.CachedItem;
import org.dasein.util.DaseinUtilTasks;
import org.dasein.util.JitCollection;
import org.dasein.util.Jiterator;
import org.dasein.util.JiteratorFilter;
public final class RelationalCache<T extends CachedItem> extends PersistentCache<T> {
static public final Logger logger = Logger.getLogger(RelationalCache.class);
static public class OrderedColumn {
public String column;
public boolean descending = false;
}
private String readDataSource = null;
private TranslationMethod translationMethod = TranslationMethod.NONE;
private String writeDataSource = null;
private ConcurrentHashMap<String,ConcurrentHashMap<String,T>> secondaryCache = null;
public RelationalCache() { }
/**
* Constructs a new persistent factory for objects of the specified class with
* the named unique identifier attributes.
* @param cls the class of objects managed by this factory
* @param keys a list of unique identifiers for instances of the specified class
*/
protected void init(Class<T> cls, Key ... keys) {
readDataSource = Execution.getDataSourceName(cls.getName(), true);
writeDataSource = Execution.getDataSourceName(cls.getName(), false);
if( readDataSource == null ) {
readDataSource = writeDataSource;
}
if( writeDataSource == null ) {
writeDataSource = readDataSource;
}
if (keys != null && keys.length > 0) {
secondaryCache = new ConcurrentHashMap<String,ConcurrentHashMap<String,T>>(keys.length);
for (Key k : keys) {
secondaryCache.put(k.toString(), new ConcurrentHashMap<String,T>(0));
}
}
}
public void setTranslationMethod(TranslationMethod translationMethod) {
this.translationMethod = translationMethod;
}
private Counter getCounter(SearchTerm[] whereTerms) {
final SearchTerm[] terms = whereTerms;
final RelationalCache<T> self = this;
Counter counter = new Counter() {
public void init() {
setTarget(self.getEntityClassName());
if( terms != null && terms.length > 0 ) {
ArrayList<Criterion> criteria = new ArrayList<Criterion>(terms.length);
for( SearchTerm term : terms ) {
criteria.add(new Criterion(term.getColumn(), term.getOperator()));
}
setCriteria(criteria.toArray(new Criterion[criteria.size()]));
}
}
public boolean isReadOnly() {
return true;
}
};
return counter;
}
private Creator getCreator() {
final RelationalCache<T> self = this;
Creator creator = new Creator() {
public void init() {
setTarget(self.getEntityClassName());
switch (translationMethod) {
case CUSTOM: setCustomTranslating(); break;
case STANDARD: setTranslating(true); break;
case NONE: setTranslating(false); break;
}
}
public boolean isReadOnly() {
return false;
}
};
return creator;
}
private Deleter getDeleter(SearchTerm ... terms) {
final SearchTerm[] killTerms = terms;
final RelationalCache<T> self = this;
Deleter deleter = new Deleter() {
public void init() {
setTarget(self.getEntityClassName());
if( killTerms != null && killTerms.length > 0 ) {
ArrayList<Criterion> criteria = new ArrayList<Criterion>(killTerms.length);
for( SearchTerm term : killTerms ) {
criteria.add(new Criterion(term.getJoinEntity(), term.getColumn(), term.getOperator()));
}
setCriteria(criteria.toArray(new Criterion[criteria.size()]));
}
else {
setCriteria(self.getPrimaryKey().getFields());
}
switch (translationMethod) {
case CUSTOM: setCustomTranslating(); break;
case STANDARD: setTranslating(true); break;
case NONE: setTranslating(false); break;
}
}
public boolean isReadOnly() {
return false;
}
};
return deleter;
}
private Loader getLoader(SearchTerm[] whereTerms, OrderedColumn[] orderBy) {
final SearchTerm[] terms = whereTerms;
final OrderedColumn[] order = orderBy;
final RelationalCache<T> self = this;
Loader loader = new Loader() {
public void init() {
setTarget(self.getEntityClassName());
setEntityJoins(getJoins());
if( terms != null && terms.length > 0 ) {
ArrayList<Criterion> criteria = new ArrayList<Criterion>(terms.length);
for( SearchTerm term : terms ) {
criteria.add(new Criterion(term.getJoinEntity(), term.getColumn(), term.getOperator()));
}
setCriteria(criteria.toArray(new Criterion[criteria.size()]));
}
if( order != null && order.length > 0 ) {
ArrayList<String> cols = new ArrayList<String>(order.length);
boolean desc = order[0].descending;
for( OrderedColumn col : order ) {
cols.add(col.column);
}
setOrder(desc, cols.toArray(new String[cols.size()]));
}
switch (translationMethod) {
case CUSTOM: setCustomTranslating(); break;
case STANDARD: setTranslating(true); break;
case NONE: setTranslating(false); break;
}
}
public boolean isReadOnly() {
return true;
}
};
return loader;
}
private Updater getUpdater() {
final RelationalCache<T> self = this;
Updater updater = new Updater() {
public void init() {
setTarget(self.getEntityClassName());
setCriteria(self.getPrimaryKey().getFields());
switch (translationMethod) {
case CUSTOM: setCustomTranslating(); break;
case STANDARD: setTranslating(true); break;
case NONE: setTranslating(false); break;
}
}
public boolean isReadOnly() {
return false;
}
};
return updater;
}
/**
* Counts the total number of objects governed by this factory in the database.
* @return the number of objects in the database
* @throws PersistenceException an error occurred counting the elements in the database
*/
@Override
public long count() throws PersistenceException {
logger.debug("enter - count()");
try {
Transaction xaction = Transaction.getInstance(true);
Counter counter = getCounter(null);
try {
Map<String,Object> results;
long count;
results = xaction.execute(counter, new HashMap<String,Object>(0), readDataSource);
count = ((Number)results.get("count")).longValue();
xaction.commit();
return count;
}
finally {
xaction.rollback();
}
}
finally {
logger.debug("exit - count()");
}
}
@Override
public long count(SearchTerm ... terms) throws PersistenceException {
logger.debug("enter - count(SearchTerm...)");
try {
Transaction xaction = Transaction.getInstance(true);
Counter counter = getCounter(terms);
try {
Map<String,Object> params = toParams(terms);
Map<String,Object> results;
long count;
results = xaction.execute(counter, params, readDataSource);
count = ((Number)results.get("count")).longValue();
xaction.commit();
return count;
}
finally {
xaction.rollback();
}
}
finally {
logger.debug("exit - count(SearchTerm...)");
}
}
/**
* Creates the specified object with the data provided in the specified state under
* the governance of the specified transaction.
* @param xaction the transaction governing this event
* @param state the new state for the new object
* @throws PersistenceException an error occurred talking to the data store, or
* creates are not supported
*/
@Override
public T create(Transaction xaction, Map<String,Object> state) throws PersistenceException {
state.put("--key--", getPrimaryKey().getFields()[0]);
xaction.execute(getCreator(), state, writeDataSource);
return getCache().find(state);
}
@Override
public T get(SearchTerm... terms) throws PersistenceException {
if (logger.isDebugEnabled()) {
logger.debug("get(SearchTerm... terms) - enter");
}
try {
Key k = matchKeys(terms);
if (logger.isDebugEnabled()) {
logger.debug("Key: " + k);
}
if (k != null) {
if (logger.isDebugEnabled()) {
logger.debug("Executing cache find...");
}
try {
ConcurrentHashMap<String,T> cache = secondaryCache.get(k.toString());
if (logger.isDebugEnabled()) {
logger.debug("Found cache...");
}
String itemKey = getKeyValue(terms, k);
if (logger.isDebugEnabled()) {
logger.debug("Generated key value..." + itemKey);
}
T t = cache.get(itemKey);
if (logger.isDebugEnabled()) {
logger.debug("Hit cache..." + t);
}
if (t == null || t instanceof CachedItem && !((CachedItem) t).isValidForCache()) {
if (logger.isDebugEnabled()) {
logger.debug("Loading from RelationalCache...");
}
Collection<T> list = find(terms);
if (list != null && !list.isEmpty()) {
t = list.iterator().next();
cache.put(itemKey, t);
}
}
return t;
} catch (RuntimeException e) {
Throwable t = e.getCause();
if (t != null && t instanceof PersistenceException) {
throw (PersistenceException) t;
}
if (logger.isDebugEnabled()) {
logger.error(e.getMessage(), e);
}
throw new PersistenceException(e);
}
}
return null;
} finally {
if (logger.isDebugEnabled()) {
logger.debug("get(SearchTerm... terms) - exit");
}
}
}
@Override
public Collection<T> find(SearchTerm[] terms, JiteratorFilter<T> filter, Boolean orderDesc, String ... orderFields) throws PersistenceException {
logger.debug("enter - find(SearchTerm[], JiteratorFilter, Boolean, String)");
try {
OrderedColumn[] order;
if( orderFields == null ) {
order = new OrderedColumn[0];
}
else {
int i = 0;
order = new OrderedColumn[orderFields.length];
for( String field : orderFields ) {
order[i] = new OrderedColumn();
order[i].column = field;
order[i].descending = (orderDesc != null && orderDesc);
i++;
}
}
return this.load(getLoader(terms, order), filter, toParams(terms));
}
finally {
logger.debug("exit - find(SearchTerm[], JiteratorFilter, Boolean, String...)");
}
}
/**
* Retrieves the object uniquely identified by the value for the specified ID field.
* @param primaryKeyValue the ID field identifying the object
* @return the object matching the query criterion
* @throws PersistenceException an error occurred talking to the data store
*/
@Override
public T get(Object primaryKeyValue) throws PersistenceException {
try {
CacheLoader<T> loader;
loader = new CacheLoader<T>() {
public T load(Object ... args) {
SearchTerm[] terms = new SearchTerm[1];
Collection<T> list;
terms[0] = new SearchTerm((String)args[0], Operator.EQUALS, args[1]);
try {
list = RelationalCache.this.load(getLoader(terms, null), null, toParams(terms));
}
catch( PersistenceException e ) {
try {
try { Thread.sleep(1000L); }
catch( InterruptedException ignore ) { }
list = RelationalCache.this.load(getLoader(terms, null), null, toParams(terms));
}
catch( Throwable forgetIt ) {
logger.error(forgetIt.getMessage(), forgetIt);
throw new RuntimeException(e);
}
}
if( list.isEmpty() ) {
return null;
}
return list.iterator().next();
}
};
logger.debug("Executing cache find...");
try {
return getCache().find(getPrimaryKeyField(), primaryKeyValue, loader, getPrimaryKeyField(), primaryKeyValue);
}
catch( CacheManagementException e ) {
throw new PersistenceException(e);
}
catch( RuntimeException e ) {
Throwable t = e.getCause();
if( t != null && t instanceof PersistenceException ) {
throw (PersistenceException)t;
}
if( logger.isDebugEnabled() ) {
logger.error(e.getMessage(), e);
}
throw new PersistenceException(e);
}
finally {
logger.debug("Executed.");
}
}
finally {
logger.debug("exit - get(String,Object)");
}
}
@Override
public String getSchema() throws PersistenceException {
StringBuilder schema = new StringBuilder();
schema.append("CREATE TABLE ");
schema.append(getSqlNameForClassName(getEntityClassName()));
schema.append(" (");
schema.append(");");
return schema.toString();
}
protected String getSqlName(String nom) {
StringBuilder sql = new StringBuilder();
for(int i=0; i<nom.length(); i++) {
char c = nom.charAt(i);
if( Character.isLetter(c) && !Character.isLowerCase(c) ) {
if( i != 0 ) {
sql.append("_");
}
sql.append(Character.toLowerCase(c));
}
else {
sql.append(c);
}
}
return sql.toString();
}
protected String getSqlNameForClassName(String cname) {
String[] parts = cname.split("\\.");
int i;
if( parts != null && parts.length > 1 ) {
cname = parts[parts.length-1];
}
i = cname.lastIndexOf("$");
if( i != -1 ) {
cname = cname.substring(i+1);
}
return getSqlName(cname);
}
/**
* Loads all elements of this class from the data store. Use this method only when you know
* exactly what you are doing. Otherwise, you will pull a lot of data.
* @return all objects from the database
* @throws PersistenceException an error occurred executing the query
*/
@Override
public Collection<T> list() throws PersistenceException {
logger.debug("enter - list()");
try {
return find(null, null, false);
}
finally {
logger.debug("exit - list()");
}
}
private Map<String,Object> toParams(SearchTerm ... searchTerms) {
HashMap<String,Object> params = null;
if( searchTerms != null ) {
params = new HashMap<String,Object>(searchTerms.length);
for( SearchTerm term : searchTerms ) {
params.put(term.getColumn(), term.getValue());
}
} else {
params = new HashMap<String,Object>(0);
}
return params;
}
private class RelationalCacheTask implements Runnable {
private final Jiterator<T> it;
private final Map<String,Object> results;
private RelationalCacheTask(Jiterator<T> it, Map<String,Object> results) {
this.it = it;
this.results = results;
}
@Override
public void run() {
try {
for( Map<String,Object> map: (Collection<Map<String,Object>>)this.results.get(Loader.LISTING) ) {
for( String fieldName : map.keySet() ) {
LookupDelegate delegate = getLookupDelegate(fieldName);
if( delegate != null && !delegate.validate((String)map.get(fieldName)) ) {
throw new PersistenceException("Unable to validate " + fieldName + " value of " + map.get(fieldName));
}
}
this.it.push(getCache().find(map));
}
this.it.complete();
}
catch( Exception e ) {
this.it.setLoadException(e);
}
catch( Throwable t ) {
this.it.setLoadException(new RuntimeException(t));
}
}
}
@SuppressWarnings("unchecked")
private Collection<T> load(Loader loader, JiteratorFilter<T> filter, Map<String,Object> params) throws PersistenceException {
logger.debug("enter - load(Class,SearchTerm...)");
try {
Transaction xaction = Transaction.getInstance(true);
final Jiterator<T> it = new Jiterator<T>(filter);
params.put("--key--", getPrimaryKey().getFields()[0]);
try {
final Map<String,Object> results;
results = xaction.execute(loader, params, readDataSource);
xaction.commit();
DaseinUtilTasks.submit(new RelationalCacheTask(it, results));
return new JitCollection<T>(it, getEntityClassName());
}
catch( PersistenceException e ) {
it.setLoadException(e);
throw e;
}
catch( RuntimeException e ) {
it.setLoadException(e);
throw e;
}
catch( Throwable t ) {
RuntimeException e = new RuntimeException(t);
it.setLoadException(e);
throw e;
}
finally {
xaction.rollback();
}
}
finally {
logger.debug("exit - load(Class,Map)");
}
}
/**
* Removes the specified item from the system permanently.
* @param xaction the transaction under which this event is occurring
* @param item the item to be removed
* @throws PersistenceException an error occurred talking to the data store or
* removal of these objects is prohibited
*/
@Override
public void remove(Transaction xaction, T item) throws PersistenceException {
xaction.execute(getDeleter(), getCache().getKeys(item), writeDataSource);
getCache().release(item);
}
@Override
public void remove(Transaction xaction, SearchTerm ... terms) throws PersistenceException {
xaction.execute(getDeleter(terms), toParams(terms), writeDataSource);
}
public String toString() {
return getCache().toString();
}
/**
* Updates the specified object with the data provided in the specified state under
* the governance of the specified transaction.
* @param xaction the transaction governing this event
* @param item the item to be updated
* @param state the new state for the updated object
* @throws PersistenceException an error occurred talking to the data store, or
* updates are not supported
*/
@Override
public void update(Transaction xaction, T item, Map<String,Object> state) throws PersistenceException {
state.put("--key--", getPrimaryKey().getFields()[0]);
xaction.execute(getUpdater(), state, writeDataSource);
}
}
|
3e0a4b60759dd545fac243de4b5220192650515b | 10,256 | java | Java | Project/src/DFS.java | meghanakiran/Data-Structure | b994a7a77eaf9aa465d1b57d6c741a82056ff0f4 | [
"MIT"
] | null | null | null | Project/src/DFS.java | meghanakiran/Data-Structure | b994a7a77eaf9aa465d1b57d6c741a82056ff0f4 | [
"MIT"
] | null | null | null | Project/src/DFS.java | meghanakiran/Data-Structure | b994a7a77eaf9aa465d1b57d6c741a82056ff0f4 | [
"MIT"
] | null | null | null | 25.323457 | 94 | 0.560257 | 4,359 | /*@author-MEGHANA KIRAN*/
/*Depth First Search -Question 1 */
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;
public class DFS {
static String[] node;
static int[][] vertexValue;
static int[][] nodeValue;
static String[][] vertex;
static String[] oneline;
static ArrayList<ArrayList<Integer>> adjList;
static ArrayList<ArrayList<Integer>> adjLists;
private static Scanner scanner;
public static int[][] readfile(String readFile) {
ArrayList<String> arrlist = new ArrayList<String>();
try {
/* System.out.println("entered"); */
/* System.out.println(readFile); */
File file = new File(readFile /* "input" */);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
arrlist.add(line);
/* System.out.println(line); */
}
fileReader.close();
node = arrlist.get(0).trim().split(" ");
/* System.out.println("node length = " + node.length); */
vertex = new String[node.length][node.length + 1];
vertexValue = new int[node.length][node.length];
for (int i = 1; i < arrlist.size(); i++) {
oneline = arrlist.get(i).split(" ");
/* System.out.println("oneline"+ oneline.length); */
for (int k = 0; k < oneline.length; k++) {
vertex[i - 1][k] = oneline[k];
}
}
/*
* System.out.println("vertex.length = " + vertex.length);
* System.out.println("vertex [0] length = " + vertex[0].length);
*/
for (int i = 0; i < vertex.length; i++) {
for (int j = 1; j < vertex[0].length; j++) {
vertexValue[i][j - 1] = Integer.parseInt(vertex[i][j]);
}
}
/*
* for (int i = 0; i < node.length; i++) {
* System.out.println("node loop"); System.out.println(node[i]); }
*/
/*
* System.out.println("printing vertex "); for (int i = 0; i <
* vertex.length; i++) { for (int j = 0; j < vertex[0].length; j++)
* { System.out.print(vertex[i][j] + " "); } System.out.println(); }
* System.out.println();
* System.out.println("printing vertexValue "); for (int i = 0; i <
* vertexValue.length; i++) { for (int j = 0; j <
* vertexValue.length; j++) { System.out.print(vertexValue[i][j] +
* " "); } System.out.println(); } System.out.println();
*/
}
catch (IOException e) {
e.printStackTrace();
}
return vertexValue;
}
public static int[][] VertexChange(int[][] vertexValue) {
for (int i = 0; i < vertexValue.length; i++) {
for (int j = 0; j < vertexValue.length; j++) {
if (vertexValue[i][j] == 1) {
vertexValue[i][j] = j + 1;
}
}
}
/*
* System.out.println("Vertex changed "); for (int i = 0; i <
* vertexValue.length; i++) { for (int j = 0; j < vertexValue.length;
* j++) { System.out.print(vertexValue[i][j] + " "); }
* System.out.println(); }
*/
return vertexValue;
}
public static ArrayList<ArrayList<Integer>> createList(int[][] nodeValue) {
adjList = new ArrayList<ArrayList<Integer>>();
for (int v = 0; v < nodeValue.length; v++) {
adjList.add(new ArrayList<Integer>());
}
for (int i = 0; i < vertexValue.length; i++) {
for (int j = 0; j < vertexValue[0].length; j++) {
if (vertexValue[i][j] != 0) {
adjList.get(i).add(vertexValue[i][j] - 1);
}
}
}
/*
* for(int i = 0; i < adjList.size(); i++) System.out.println(i + "->"+
* adjList.get(i)+" ");
*/
return adjList;
}
public static void main(String[] args) {
scanner = new Scanner(System.in);
System.out.print("Enter filename: ");
String filename = scanner.nextLine();
vertexValue = readfile(filename/* "input" */);
nodeValue = new int[node.length][node.length];
nodeValue = VertexChange(vertexValue);
adjLists = new ArrayList<ArrayList<Integer>>();
adjLists = createList(nodeValue);
DFSGraph dfsGraph = new DFSGraph(adjLists);
dfsGraph.DFS();
dfsGraph.printarrList();
dfsGraph.plot();
}
}
/* DFSGraph class */
class DFSGraph {
public static class Vertex {
public int vertex;
/* color of vertex */
public Color color;
/* to find the parent */
public Vertex parent;
/* visit time */
public int discoverTime;
/* finish time */
public int finishTime;
/* to know the path */
public int join;
public Vertex(int v) {
vertex = v;
parent = null;
join = 0;
color = Color.WHITE;
discoverTime = Integer.MAX_VALUE;
finishTime = Integer.MAX_VALUE;
}
}
public enum Color {
WHITE, GRAY, BLACK
}
/* Number of vertex */
private int n;
private ArrayList<ArrayList<Integer>> graph;
private Vertex[] vertices;
private ArrayList<Vertex> res;
private int timer;
private ArrayList<Vertex> stack = new ArrayList<Vertex>();
private LinkedList<Integer> adj[];
private int V;
static int[][] multi;
static int[][] multi3;
public DFSGraph(ArrayList<ArrayList<Integer>> graph) {
this.n = graph.size();
/* System.out.println("graph size" + graph.size()); */
this.graph = graph;
this.vertices = new Vertex[n];
MatrixCreation(graph.size());
this.res = new ArrayList<Vertex>();
this.timer = 0;
}
public void DFS() {
int i = 0;
for (i = 0; i < n; i++) {
vertices[i] = new Vertex(i);
/* System.out.println("vertices" + vertices[i]); */
}
for (i = 0; i < n; i++) {
Vertex u = vertices[i];
if (u.color == Color.WHITE) {
visitDFS(u);
/* visit DFS Iteratively */
}
}
}
/* insert traversal into arraylist */
public ArrayList<Vertex> getRes() {
return res;
}
private void visitDFS(Vertex u) {
res.add(u);
u.color = Color.GRAY;
timer++;
u.discoverTime = timer;
ArrayList<Integer> adjList = graph.get(u.vertex);
/*
* System.out.println("adjlist size in dfsGraph " + adjList.size());
* System.out.println(adjList);
*/
/* System.out.println(vertices); */
for (int i = 0; i < adjList.size(); i++) {
Vertex v = vertices[adjList.get(i)];
if (v.color == Color.WHITE) {
v.parent = u;
v.join = 1;
addEdge(v.vertex, u.vertex);
visitDFS(v);
}
}
u.color = Color.BLACK;
timer++;
u.finishTime = timer;
}
private void addEdge(int v, int u) {
adj[v].add(u);
}
private void MatrixCreation(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
public void printarrList() {
System.out.println("Question 1: DFS Algorithm - OUTPUT ");
System.out.println("Traversal path : ");
for (int i = 0; i < n; i++) {
Vertex v = res.get(i);
String node = DFS.node[v.vertex];
System.out.print(node + " ");
}
System.out.println();
System.out.println("Vertex:Discover time/Finish time");
for (int i = 0; i < n; i++) {
Vertex v = res.get(i);
String node = DFS.node[v.vertex];
System.out.println(node + " : " + v.discoverTime + " / "
+ v.finishTime);
}
}
public void plot() {
System.out.println();
System.out.println("Final Output Matrix:");
multi = new int[n][n];
System.out.print(" ");
for (int i = 0; i < n; i++) {
String node1 = DFS.node[i];
System.out.print(node1 + " ");
// System.out.printf("%6s",node1);
}
System.out.println();
/*
* for (int k = 0; k < n; k++) { for (int j = 0; j < n; j++) {
*
* System.out.print(multi[k][j] + " "); } System.out.println(); }
*/
for (int i = 0; i < n; i++) {
Vertex u = res.get(i);
plotDFS(u);
/* visit plotDFS(u) iteratively */
}
for (int k = 0; k < n; k++) {
String node2 = DFS.node[k];
System.out.print(node2 + " ");
for (int j = 0; j < n; j++) {
System.out.print(multi[k][j] + " ");
}
System.out.println();
}
changematrix(multi);
}
private void plotDFS(Vertex u) {
ArrayList<Integer> adjList = graph.get(u.vertex);
/*
* System.out.println("adjlist size in dfsGraph " + adjList.size());
* System.out.println(adjList);
*/
/* System.out.println(vertices); */
for (int i = 0; i < adjList.size(); i++) {
Vertex v = vertices[adjList.get(i)];
if (v.join == 1 && v.parent == u) {
/* add 1 to that place */
multi[u.vertex][v.vertex] = 1;
plotDFS(v);
}
}
}
private void changematrix(int[][] multi2) {
System.out.println();
System.out.println("Final Output Matrix with Discover time/Finish time on the diagonal :");
System.out.print(" ");
for (int i = 0; i < n; i++) {
String node1 = DFS.node[i];
System.out.print(" " + node1 + " ");
/* System.out.printf("%6s",node1); */
}
System.out.println();
/*
* multi3= new int[n][n]; multi3 = changeDiagonal(multi2);
*/
for (int k = 0; k < n; k++) {
int findApproNode = 0;
Vertex u = res.get(k);/* getvertex(k); */
/* System.out.println("before "+u.vertex); */
while (u.vertex != k && findApproNode < n - 1) {
findApproNode++;
u = res.get(findApproNode);
}
/* System.out.println("after "+u.vertex); */
String node2 = DFS.node[u.vertex];
System.out.print(node2 + " ");
/* for(int l =0;l<n;l++){ */
for (int j = 0; j < n; j++) {
if (/* u.vertex == j && u.vertex == k */k == j) {
/* v= res.get(k);Vertex */
System.out.print(u.discoverTime + "/" + u.finishTime + " ");
/*
* System.out.printf("%1s%s%2s ",u.discoverTime+"/",u.finishTime
* ," ");
*/
} else {
System.out.print(multi2[k][j] + " ");
/* System.out.printf("%2s%5s", multi2[k][j]," "); */
}
}
System.out.println();
}
/* System.out.println(); */
}
private Vertex getvertex(int k) {
System.out.println(k);
/* for(int l =0;l<n;l++){ */
Vertex u = res.get(k);
for (int j = 0; j < n; j++) {
/* System.out.println(u.vertex); */
if (u.vertex == j && u.vertex == k) {
return u;
}
}
return null;
}
}
|
3e0a4bffa6a9ba1cd34531dd64094955b72d6213 | 1,447 | java | Java | core/src/main/java/com/huawei/openstack4j/openstack/storage/block/domain/VBSVolumeBackupScheduledPolicy.java | huaweicloudsdk/openstack4j | c802f800ee5488083378d2bec0e99949a50aa3c3 | [
"Apache-2.0"
] | 16 | 2018-01-25T05:32:40.000Z | 2019-03-14T03:48:14.000Z | core/src/main/java/com/huawei/openstack4j/openstack/storage/block/domain/VBSVolumeBackupScheduledPolicy.java | huaweicloudsdk/openstack4j | c802f800ee5488083378d2bec0e99949a50aa3c3 | [
"Apache-2.0"
] | 3 | 2018-05-03T15:31:50.000Z | 2018-08-29T04:27:13.000Z | core/src/main/java/com/huawei/openstack4j/openstack/storage/block/domain/VBSVolumeBackupScheduledPolicy.java | huaweicloudsdk/openstack4j | c802f800ee5488083378d2bec0e99949a50aa3c3 | [
"Apache-2.0"
] | 20 | 2018-02-06T03:08:56.000Z | 2019-02-19T07:24:45.000Z | 30.787234 | 98 | 0.811334 | 4,360 | package com.huawei.openstack4j.openstack.storage.block.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.huawei.openstack4j.model.common.serializer.YNBooleanDeserializer;
import com.huawei.openstack4j.model.common.serializer.YNBooleanSerializer;
import com.huawei.openstack4j.model.storage.block.VolumeBackupPolicy.VolumeBackupPolicyStatus;
import com.huawei.openstack4j.model.storage.block.VolumeBackupPolicy.VolumeBackupScheduledPolicy;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
*
* @author QianBiao.NG
* @date 2017-06-29 16:13:25
*/
@Getter
@ToString
@Builder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor
public class VBSVolumeBackupScheduledPolicy implements VolumeBackupScheduledPolicy {
private static final long serialVersionUID = -5660930519824771L;
@JsonProperty("rentention_num")
Integer maxBackupAmount;
Integer frequency;
@JsonSerialize(using = YNBooleanSerializer.class)
@JsonDeserialize(using = YNBooleanDeserializer.class)
@JsonProperty("remain_first_backup_of_curMonth")
Boolean retainFirstBackupOfCurrentMonth;
@JsonProperty("start_time")
String startTime;
VolumeBackupPolicyStatus status;
}
|
3e0a4ccb28e2510c398c2eaf8353f580050f39ef | 8,595 | java | Java | EngineerMode/src/com/mediatek/engineermode/settingsfontsize/SettingsFontSize.java | bulkin042/android_device_wileyfox_porridge | 8ac55a7ff1ab05c04412655e48d64722b8c1fc06 | [
"Apache-2.0"
] | 4 | 2018-08-03T17:34:48.000Z | 2018-10-14T05:43:15.000Z | EngineerMode/src/com/mediatek/engineermode/settingsfontsize/SettingsFontSize.java | bulkin042/android_device_wileyfox_porridge | 8ac55a7ff1ab05c04412655e48d64722b8c1fc06 | [
"Apache-2.0"
] | 1 | 2022-03-06T06:19:47.000Z | 2022-03-06T06:19:47.000Z | EngineerMode/src/com/mediatek/engineermode/settingsfontsize/SettingsFontSize.java | bulkin042/android_device_wileyfox_porridge | 8ac55a7ff1ab05c04412655e48d64722b8c1fc06 | [
"Apache-2.0"
] | 2 | 2019-06-09T15:05:23.000Z | 2019-09-11T07:42:21.000Z | 43.852041 | 84 | 0.568819 | 4,361 | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
package com.mediatek.engineermode.settingsfontsize;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.mediatek.engineermode.Elog;
import com.mediatek.engineermode.R;
public class SettingsFontSize extends Activity {
private static final String TAG = "EM_SetFontSize";
private static final String SMALL = "settings_fontsize_small";
private static final String LARGE = "settings_fontsize_large";
private static final String EXTRALARGE = "settings_fontsize_extralarge";
private EditText mEditSmall;
private EditText mEditLarge;
private EditText mEditExtraLarge;
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_fontsize);
mEditSmall = (EditText) findViewById(R.id.settings_fs_small_edit);
mEditLarge = (EditText) findViewById(R.id.settings_fs_large_edit);
mEditExtraLarge = (EditText) findViewById(R.id.settings_fs_extralarge_edit);
mButton = (Button) findViewById(R.id.settings_fs_ok);
float readSmall = Settings.System.getFloat(getContentResolver(), SMALL,
-1);
float readLarge = Settings.System.getFloat(getContentResolver(), LARGE,
-1);
float readExtra = Settings.System.getFloat(getContentResolver(),
EXTRALARGE, -1);
if (readSmall != -1) {
mEditSmall.setText(readSmall + "");
}
if (readLarge != -1) {
mEditLarge.setText(readLarge + "");
}
if (readExtra != -1) {
mEditExtraLarge.setText(readExtra + "");
}
mEditSmall.setSelection(mEditSmall.getText().length());
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float smallValue = 1;
float largeValue = 1;
float extraLargeValue = 1;
String small = mEditSmall.getText().toString().trim();
String large = mEditLarge.getText().toString().trim();
String extralarge = mEditExtraLarge.getText().toString().trim();
if (small.equals("") && large.equals("")
&& extralarge.equals("")) {
return;
}
if (!small.equals("")) {
try {
smallValue = Float.valueOf(small);
Elog.e(TAG, "small : " + small);
} catch (NumberFormatException e) {
// Dialog
new AlertDialog.Builder(SettingsFontSize.this)
.setTitle("Warning").setMessage(
"Please input right value!")
.setPositiveButton("OK", null).create().show();
Elog.e(TAG, "--NumberFormatException");
return;
}
}
if (!large.equals("")) {
try {
largeValue = Float.valueOf(large);
} catch (NumberFormatException e) {
// Dialog
new AlertDialog.Builder(SettingsFontSize.this)
.setTitle("Warning").setMessage(
"Please input right value!")
.setPositiveButton("OK", null).create().show();
Elog.e(TAG, "--NumberFormatException");
return;
}
}
if (!extralarge.equals("")) {
try {
extraLargeValue = Float.valueOf(extralarge);
} catch (NumberFormatException e) {
// Dialog
new AlertDialog.Builder(SettingsFontSize.this)
.setTitle("Warning").setMessage(
"Please input right value!")
.setPositiveButton("OK", null).create().show();
Elog.e(TAG, "--NumberFormatException");
return;
}
}
if (smallValue <= 0 || largeValue <= 0 || extraLargeValue <= 0) {
new AlertDialog.Builder(SettingsFontSize.this).setTitle(
"Warning").setMessage("Please input right value!")
.setPositiveButton("OK", null).create().show();
return;
}
boolean isSuccessSm;
boolean isSuccessLa;
boolean isSuccessEx;
if (!small.equals("")) {
isSuccessSm = Settings.System.putFloat(
getContentResolver(), SMALL, smallValue);
} else {
isSuccessSm = true;
}
if (!large.equals("")) {
isSuccessLa = Settings.System.putFloat(
getContentResolver(), LARGE, largeValue);
} else {
isSuccessLa = true;
}
if (!extralarge.equals("")) {
isSuccessEx = Settings.System.putFloat(
getContentResolver(), EXTRALARGE, extraLargeValue);
} else {
isSuccessEx = true;
}
Elog.d(TAG, " Set font size -- SMALL :" + smallValue
+ "LARGE :" + largeValue + "EXTRALARGE :"
+ extraLargeValue);
if (isSuccessSm && isSuccessLa && isSuccessEx) {
Toast.makeText(SettingsFontSize.this, "Success!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(SettingsFontSize.this, "Fail!",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
|
3e0a4e4e2969342fbda9cf5167ecea783a0d9cdc | 1,534 | java | Java | src/application/Main.java | fredden87/2dv603-project | fc79c6009dcf2735e3ee256ca107f0cabc1bb7f7 | [
"MIT"
] | 2 | 2018-09-04T14:31:11.000Z | 2018-10-16T11:41:51.000Z | src/application/Main.java | brocahontaz/1dv603-project | fc79c6009dcf2735e3ee256ca107f0cabc1bb7f7 | [
"MIT"
] | 8 | 2018-03-27T15:35:25.000Z | 2018-04-25T15:04:05.000Z | src/application/Main.java | brocahontaz/1dv603-project | fc79c6009dcf2735e3ee256ca107f0cabc1bb7f7 | [
"MIT"
] | 1 | 2018-09-04T14:30:45.000Z | 2018-09-04T14:30:45.000Z | 26.448276 | 96 | 0.73794 | 4,362 | package application;
import controller.Controller;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.fxml.FXMLLoader;
/**
* Main class for the application
*
* @author Johan Andersson, Fredrik Norrman, David Larsson
*
*/
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
setupMainStage(primaryStage);
}
public static void main(String[] args) {
launch(args);
}
private void setupMainStage(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/ViewConfig.fxml"));
BorderPane root = (BorderPane) loader.load();
Scene scene = new Scene(root, 800, 600);
scene.getStylesheets().add(getClass().getResource("/view/bootstrap3.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.setMaximized(true);
primaryStage.setMinHeight(600);
primaryStage.setMinWidth(800);
primaryStage.setMaxHeight(1080);
primaryStage.setMaxWidth(1920);
primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/view/apeemoji.png")));
primaryStage.setTitle("HotelFX");
loader.<Controller>getController().setStage(primaryStage);
// Completely closes the application and all threads.
primaryStage.setOnCloseRequest(e -> {
Platform.exit();
System.exit(0);
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
3e0a4f7a3a8d3ea69ebf5c5bf21dcfe478e7ce95 | 2,976 | java | Java | instrumentation/jaxrs/jaxrs-2.0/src/main/java/io/opentelemetry/instrumentation/auto/jaxrs/v2_0/DefaultRequestContextInstrumentation.java | mabdinur/opentelemetry-java-instrumentation | e20cba57c2b8218cddec6e63046be1d5a7885cd0 | [
"Apache-2.0"
] | null | null | null | instrumentation/jaxrs/jaxrs-2.0/src/main/java/io/opentelemetry/instrumentation/auto/jaxrs/v2_0/DefaultRequestContextInstrumentation.java | mabdinur/opentelemetry-java-instrumentation | e20cba57c2b8218cddec6e63046be1d5a7885cd0 | [
"Apache-2.0"
] | 30 | 2020-09-03T08:10:47.000Z | 2022-03-01T18:03:20.000Z | instrumentation/jaxrs/jaxrs-2.0/src/main/java/io/opentelemetry/instrumentation/auto/jaxrs/v2_0/DefaultRequestContextInstrumentation.java | mabdinur/opentelemetry-java-instrumentation | e20cba57c2b8218cddec6e63046be1d5a7885cd0 | [
"Apache-2.0"
] | null | null | null | 36.740741 | 99 | 0.736895 | 4,363 | /*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.opentelemetry.instrumentation.auto.jaxrs.v2_0;
import static io.opentelemetry.instrumentation.auto.jaxrs.v2_0.JaxRsAnnotationsTracer.TRACER;
import static io.opentelemetry.trace.TracingContextUtils.currentContextWith;
import com.google.auto.service.AutoService;
import io.opentelemetry.instrumentation.auto.api.SpanWithScope;
import io.opentelemetry.javaagent.tooling.Instrumenter;
import io.opentelemetry.trace.Span;
import java.lang.reflect.Method;
import javax.ws.rs.container.ContainerRequestContext;
import net.bytebuddy.asm.Advice;
/**
* Default context instrumentation.
*
* <p>JAX-RS does not define a way to get the matched resource method from the <code>
* ContainerRequestContext</code>
*
* <p>This default instrumentation uses the class name of the filter to create the span. More
* specific instrumentations may override this value.
*/
@AutoService(Instrumenter.class)
public class DefaultRequestContextInstrumentation extends AbstractRequestContextInstrumentation {
public static class ContainerRequestContextAdvice {
@Advice.OnMethodEnter(suppress = Throwable.class)
public static SpanWithScope createGenericSpan(@Advice.This ContainerRequestContext context) {
if (context.getProperty(JaxRsAnnotationsTracer.ABORT_HANDLED) == null) {
Class filterClass = (Class) context.getProperty(JaxRsAnnotationsTracer.ABORT_FILTER_CLASS);
Method method = null;
try {
method = filterClass.getMethod("filter", ContainerRequestContext.class);
} catch (NoSuchMethodException e) {
// Unable to find the filter method. This should not be reachable because the context
// can only be aborted inside the filter method
}
Span span = TRACER.startSpan(filterClass, method);
return new SpanWithScope(span, currentContextWith(span));
}
return null;
}
@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
public static void stopSpan(
@Advice.Enter SpanWithScope spanWithScope, @Advice.Thrown Throwable throwable) {
if (spanWithScope == null) {
return;
}
Span span = spanWithScope.getSpan();
if (throwable != null) {
TRACER.endExceptionally(span, throwable);
} else {
TRACER.end(span);
}
spanWithScope.closeScope();
}
}
}
|
3e0a4fb311699cb745a62e0dbc16fb77cc223609 | 17,181 | java | Java | src/main/java/gov/nasa/pds/tracking/tracking/db/ProductDao.java | NASA-PDS/tracking-service | 1fba608a9b692901385ff225bd3323f77cbb198b | [
"Apache-2.0"
] | null | null | null | src/main/java/gov/nasa/pds/tracking/tracking/db/ProductDao.java | NASA-PDS/tracking-service | 1fba608a9b692901385ff225bd3323f77cbb198b | [
"Apache-2.0"
] | 14 | 2020-10-29T21:47:14.000Z | 2021-09-08T13:38:26.000Z | src/main/java/gov/nasa/pds/tracking/tracking/db/ProductDao.java | NASA-PDS/pds-tracking-service | 1fba608a9b692901385ff225bd3323f77cbb198b | [
"Apache-2.0"
] | 1 | 2020-12-21T22:19:02.000Z | 2020-12-21T22:19:02.000Z | 31.016245 | 124 | 0.679683 | 4,364 | /**
* Copyright 2010-2017, by the California Institute of Technology.
*
* The object class represents Product table.
*
*/
package gov.nasa.pds.tracking.tracking.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
/**
* @author danyu nnheo@example.com
*
*/
public class ProductDao extends DBConnector {
public static Logger logger = Logger.getLogger(ProductDao.class);
private static final String TABLENAME = "product";
private static final String DELIVERYTABLENAME = "delivery";
public static final String IDENTIFIERCOLUMN = "logical_identifier";
public static final String VERSIONCOLUMN = "version_id";
public static final String TITLECOLUMN = "title";
public static final String TYPECOLUMN = "type";
public static final String ALTERNATECOLUMN = "alternate_id";
public static final String INVESTREFCOLUMN = "investigation_reference";
public static final String INVESTTITLECOLUMN = "investigation_title";
public static final String INSTREFCOLUMN = "instrument_reference";
public static final String INSTTITLECOLUMN = "instrument_title";
public static final String NODEREFCOLUMN = "node_reference";
public static final String NODETITLECOLUMN = "node_title";
private ResultSet resultSet = null;
public ProductDao() throws ClassNotFoundException, SQLException {
// TODO Auto-generated constructor stub
}
/**
* Product Query - Query the product table for a list of products by type.
*
* @param type
* (can be null)
* @return a list of all products by type (optional) order by title
*/
@SuppressWarnings("finally")
public List<Product> getProducts(String type) {
Connection connect = null;
Statement statement = null;
List<Product> prodObjs = new ArrayList<Product>();
Product prod = null;
try {
// Setup the connection with the DB
connect = getConnection();
statement = connect.createStatement();
if (type != null && type.length() > 0) {
resultSet = statement.executeQuery("select * from " + TABLENAME + " where " + TYPECOLUMN + " = '" + type
+ "' order by " + TITLECOLUMN);
} else {
resultSet = statement.executeQuery("select * from " + TABLENAME + " order by " + TITLECOLUMN);
}
while (resultSet.next()) {
prod = new Product();
prod.setIdentifier(resultSet.getString(IDENTIFIERCOLUMN));
prod.setVersion(resultSet.getString(VERSIONCOLUMN));
prod.setTitle(resultSet.getString(TITLECOLUMN));
prod.setType(resultSet.getString(TYPECOLUMN));
prod.setAlternate(resultSet.getString(ALTERNATECOLUMN));
prodObjs.add(prod);
}
} catch (Exception e) {
logger.error(e);
} finally {
close(connect, statement);
return prodObjs;
}
}
/**
* @return a list of all products order by title
*/
@SuppressWarnings("finally")
public List<Product> getProductsOrderByTitle() {
Connection connect = null;
Statement statement = null;
List<Product> prodObjs = new ArrayList<Product>();
Product prod = null;
try {
// Setup the connection with the DB
connect = getConnection();
statement = connect.createStatement();
resultSet = statement.executeQuery("select * from " + TABLENAME + " order by " + TITLECOLUMN);
while (resultSet.next()) {
prod = new Product();
prod.setIdentifier(resultSet.getString(IDENTIFIERCOLUMN));
prod.setVersion(resultSet.getString(VERSIONCOLUMN));
prod.setTitle(resultSet.getString(TITLECOLUMN));
prod.setType(resultSet.getString(TYPECOLUMN));
prod.setAlternate(resultSet.getString(ALTERNATECOLUMN));
prodObjs.add(prod);
}
} catch (Exception e) {
logger.error(e);
} finally {
close(connect, statement);
return prodObjs;
}
}
/**
* Product Delivery Query - Query the product, delivery and *_reference
* tables for a list of products that have associated deliveries.
*
* @return a list of all products that have associated deliveries order by
* title
*/
@SuppressWarnings("finally")
public List<Product> getProductsAssociatedDeliveriesOrderByTitle(String instRef, String investRef) {
Connection connect = null;
Statement statement = null;
List<Product> prodObjs = new ArrayList<Product>();
Product prod = null;
try {
// Setup the connection with the DB
connect = getConnection();
statement = connect.createStatement();
String defaultQueryPartOne = "select DISTINCT p.*, ivr.reference AS investigation_reference, "
+ "ivr.title AS investigation_title, " + "isr.reference AS instrument_reference, "
+ "isr.title AS instrument_title, " + "nr.reference AS node_reference, " + "nr.title AS node_title "
+ "from " + TABLENAME + " p, " + DELIVERYTABLENAME + " d, " + ReferenceDao.INVES_TABLENAME + " ivr,"
+ ReferenceDao.INST_TABLENAME + " isr," + ReferenceDao.NODE_TABLENAME + " nr " + "where p."
+ IDENTIFIERCOLUMN + " = d." + IDENTIFIERCOLUMN + " and p." + VERSIONCOLUMN + " = d."
+ VERSIONCOLUMN + " and p." + IDENTIFIERCOLUMN + " = ivr." + IDENTIFIERCOLUMN + " and p."
+ IDENTIFIERCOLUMN + " = isr." + IDENTIFIERCOLUMN + " and p." + IDENTIFIERCOLUMN + " = nr."
+ IDENTIFIERCOLUMN;
String defaultQueryOrder = " order by " + TITLECOLUMN;
String queryInstRefPart = "";
String queryInveRefPart = "";
if (instRef != null && !instRef.equalsIgnoreCase("null") && instRef.length() > 0)
queryInstRefPart = " and isr." + ReferenceDao.REFERENCECOLUMN + " = '" + instRef + "'";
if (investRef != null && !investRef.equalsIgnoreCase("null") && investRef.length() > 0)
queryInveRefPart = " and ivr." + ReferenceDao.REFERENCECOLUMN + " = '" + investRef + "'";
String query = defaultQueryPartOne + queryInstRefPart + queryInveRefPart + defaultQueryOrder;
logger.debug(query);
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
prod = new Product();
prod.setIdentifier(resultSet.getString(IDENTIFIERCOLUMN));
prod.setVersion(resultSet.getString(VERSIONCOLUMN));
prod.setTitle(resultSet.getString(TITLECOLUMN));
prod.setType(resultSet.getString(TYPECOLUMN));
prod.setAlternate(resultSet.getString(ALTERNATECOLUMN));
prod.setInstRef(resultSet.getString(INSTREFCOLUMN));
prod.setInstTitle(resultSet.getString(INSTTITLECOLUMN));
prod.setInveRef(resultSet.getString(INVESTREFCOLUMN));
prod.setInveTitle(resultSet.getString(INVESTTITLECOLUMN));
prod.setNodeRef(resultSet.getString(NODEREFCOLUMN));
prod.setNodeTitle(resultSet.getString(NODETITLECOLUMN));
prodObjs.add(prod);
}
} catch (Exception e) {
logger.error(e);
} finally {
close(connect, statement);
return prodObjs;
}
}
/**
* @param logical
* identifier
* @param version
* @return a product with logical identifier and version
*/
@SuppressWarnings("finally")
public Product getProduct(String idf, String ver) {
Connection connect = null;
Statement statement = null;
Product prodObj = null;
try {
// Setup the connection with the DB
connect = getConnection();
String query = "select * from " + TABLENAME + " where " + IDENTIFIERCOLUMN + " = '" + idf + "' AND "
+ VERSIONCOLUMN + " = '" + ver + "'";
statement = connect.createStatement();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
prodObj = new Product();
prodObj.setIdentifier(resultSet.getString(IDENTIFIERCOLUMN));
prodObj.setVersion(resultSet.getString(VERSIONCOLUMN));
prodObj.setTitle(resultSet.getString(TITLECOLUMN));
prodObj.setType(resultSet.getString(TYPECOLUMN));
prodObj.setAlternate(resultSet.getString(ALTERNATECOLUMN));
}
} catch (Exception e) {
logger.error(e);
} finally {
close(connect, statement);
return prodObj;
}
}
@SuppressWarnings("finally")
public List<Product> getProductsAssociatedAllTypeReferencesOrderByTitle(String instRef, String investRef, String nodeRef) {
Connection connect = null;
Statement statement = null;
List<Product> prodObjs = new ArrayList<Product>();
Product prod = null;
try {
// Setup the connection with the DB
connect = getConnection();
statement = connect.createStatement();
String defaultQueryPartOne = "select DISTINCT p.*, ivr.reference AS investigation_reference, "
+ "ivr.title AS investigation_title, " + "isr.reference AS instrument_reference, "
+ "isr.title AS instrument_title, " + "nr.reference AS node_reference, " + "nr.title AS node_title "
+ "from " + TABLENAME + " p, " + ReferenceDao.INVES_TABLENAME + " ivr,"
+ ReferenceDao.INST_TABLENAME + " isr," + ReferenceDao.NODE_TABLENAME + " nr " + "where p."
+ IDENTIFIERCOLUMN + " = ivr." + IDENTIFIERCOLUMN + " and p." + IDENTIFIERCOLUMN + " = isr."
+ IDENTIFIERCOLUMN + " and p." + IDENTIFIERCOLUMN + " = nr." + IDENTIFIERCOLUMN;
String defaultQueryOrder = " order by " + TITLECOLUMN;
String queryInstRefPart = "";
String queryInveRefPart = "";
String queryNodeRefPart = "";
if (instRef != null && !instRef.equalsIgnoreCase("null") && instRef.length() > 0)
queryInstRefPart = " and isr." + ReferenceDao.REFERENCECOLUMN + " = '" + instRef + "'";
if (investRef != null && !investRef.equalsIgnoreCase("null") && investRef.length() > 0)
queryInveRefPart = " and ivr." + ReferenceDao.REFERENCECOLUMN + " = '" + investRef + "'";
if (nodeRef != null && !nodeRef.equalsIgnoreCase("null") && nodeRef.length() > 0)
queryNodeRefPart = " and nr." + ReferenceDao.REFERENCECOLUMN + " = '" + nodeRef + "'";
String query = defaultQueryPartOne + queryInstRefPart + queryInveRefPart + queryNodeRefPart + defaultQueryOrder;
logger.debug(query);
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
prod = new Product();
prod.setIdentifier(resultSet.getString(IDENTIFIERCOLUMN));
prod.setVersion(resultSet.getString(VERSIONCOLUMN));
prod.setTitle(resultSet.getString(TITLECOLUMN));
prod.setType(resultSet.getString(TYPECOLUMN));
prod.setAlternate(resultSet.getString(ALTERNATECOLUMN));
prod.setInstRef(resultSet.getString(INSTREFCOLUMN));
prod.setInstTitle(resultSet.getString(INSTTITLECOLUMN));
prod.setInveRef(resultSet.getString(INVESTREFCOLUMN));
prod.setInveTitle(resultSet.getString(INVESTTITLECOLUMN));
prod.setNodeRef(resultSet.getString(NODEREFCOLUMN));
prod.setNodeTitle(resultSet.getString(NODETITLECOLUMN));
prodObjs.add(prod);
}
} catch (Exception e) {
logger.error(e);
} finally {
close(connect, statement);
return prodObjs;
}
}
/**
* @param stm
*/
private void close(Connection connect, Statement stm) {
try {
if (resultSet != null) {
resultSet.close();
}
if (stm != null) {
stm.close();
}
if (connect != null) {
connect.setAutoCommit(true);
connect.close();
}
} catch (Exception e) {
logger.error(e);
}
}
/**
* @param prod
* - an object of product
*/
public int insertProduct(Product prod) {
int success = 0;
Connection connect = null;
PreparedStatement prepareStm = null;
try {
// Setup the connection with the DB
connect = getConnection();
connect.setAutoCommit(false);
prepareStm = connect
.prepareStatement("INSERT INTO " + TABLENAME + " (" + IDENTIFIERCOLUMN + ", " + VERSIONCOLUMN + ", "
+ TITLECOLUMN + ", " + TYPECOLUMN + ", " + ALTERNATECOLUMN + ") VALUES (?, ?, ?, ?, ?)");
prepareStm.setString(1, prod.getIdentifier());
prepareStm.setString(2, prod.getVersion());
prepareStm.setString(3, prod.getTitle());
prepareStm.setString(4, prod.getType());
prepareStm.setString(5, prod.getAlternate());
prepareStm.executeUpdate();
connect.commit();
logger.info("The product " + prod.getTitle() + " with the type: " + prod.getType() + ", has been added.");
success = 1;
} catch (Exception e) {
logger.error(e);
if (connect != null) {
try {
logger.error("Transaction is being rolled back");
connect.rollback();
} catch (SQLException excep) {
logger.error(excep);
}
}
success = 0;
} finally {
close(connect, prepareStm);
}
return success;
}
/**
* @param prod
* - an object of product
*/
public Product updateProduct(Product prod) {
Product prodUpdated = null;
Connection connect = null;
PreparedStatement prepareStm = null;
try {
// Setup the connection with the DB
connect = getConnection();
connect.setAutoCommit(false);
boolean hasAlternate = false;
String setAlternate = "";
if (prod.getAlternate() != null && prod.getAlternate().length() > 0) {
hasAlternate = true;
setAlternate = ", " + ALTERNATECOLUMN + " = ? ";
}
prepareStm = connect.prepareStatement("UPDATE " + TABLENAME + " SET " + TITLECOLUMN + " = ?, " + TYPECOLUMN
+ " = ?" + setAlternate + " WHERE " + IDENTIFIERCOLUMN + " = ? " + "AND " + VERSIONCOLUMN + " = ?");
prepareStm.setString(1, prod.getTitle());
prepareStm.setString(2, prod.getType());
if (hasAlternate)
prepareStm.setString(3, prod.getAlternate());
prepareStm.setString(hasAlternate ? 4 : 3, prod.getIdentifier());
prepareStm.setString(hasAlternate ? 5 : 4, prod.getVersion());
prepareStm.executeUpdate();
connect.commit();
logger.info("The product " + prod.getTitle() + " with the type: " + prod.getType() + ", has been updated.");
prodUpdated = getProduct(prod.getIdentifier(), prod.getVersion());
} catch (Exception e) {
logger.error(e);
if (connect != null) {
try {
logger.error("Transaction is being rolled back");
connect.rollback();
} catch (SQLException excep) {
logger.error(excep);
}
}
} finally {
close(connect, prepareStm);
}
return prodUpdated;
}
/**
* @return a list of all products with latest three types of status order by
* title
*/
public List<Product> getProductsWithStatus() {
List<Product> prodObjs = new ArrayList<Product>();
try {
prodObjs = getProductsOrderByTitle();
if (prodObjs != null && prodObjs.size() > 0) {
for (int i = 0; i < prodObjs.size(); i++) {
getStatuses(prodObjs.get(i));
// logger.debug("AStatus 1: " +
// prodObjs.get(i).getAStatus());
}
}
} catch (Exception e) {
logger.error(e);
}
return prodObjs;
}
private void getStatuses(Product prod) {
try {
String aStatusValue = "";
String cStatusValue = "";
String nssdcaValue = "";
ArchiveStatusDao aStatusDao = new ArchiveStatusDao();
ArchiveStatus aStatus = aStatusDao.getLatestArchiveStatus(prod.getIdentifier(), prod.getVersion());
if (aStatus != null && aStatus.getStatus() != null) {
aStatusValue = aStatus.getStatus();
}
prod.setAStatus(aStatusValue);
CertificationStatusDao cStatusDao = new CertificationStatusDao();
CertificationStatus cStatus = cStatusDao.getLatestCertificationStatus(prod.getIdentifier(),
prod.getVersion());
if (cStatus != null && cStatus.getStatus() != null) {
cStatusValue = cStatus.getStatus();
}
prod.setCStatus(cStatusValue);
NssdcaStatusDao nStatusDao = new NssdcaStatusDao();
List<NssdcaStatus> nStatusList = nStatusDao.getNssdcaStatusList(prod.getIdentifier(), prod.getVersion());
if (nStatusList != null && nStatusList.size() > 0) {
NssdcaStatus nStatus = nStatusList.get(0);
if (nStatus != null && nStatus.getNssdca() != null) {
nssdcaValue = nStatus.getNssdca();
}
}
prod.setNssdca(nssdcaValue);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* @return a list of all products with latest releases and associated all types of references order by title
*/
public List<Product> getProductsWithLatestReleases(String instRef, String investRef, String nodeRef) {
List<Product> prodObjs = new ArrayList<Product>();
try {
prodObjs = getProductsAssociatedAllTypeReferencesOrderByTitle(instRef, investRef, nodeRef);
if (prodObjs != null && prodObjs.size() > 0) {
for (int i = 0; i < prodObjs.size(); i++) {
getLatestReleases(prodObjs.get(i));
// logger.debug("Latest Releases: " +
// prodObjs.get(i).getLatestReleases());
}
}
} catch (Exception e) {
logger.error(e);
}
return prodObjs;
}
private void getLatestReleases(Product prod) {
try {
String name = "";
Timestamp release_date = null;
String description = "";
ReleasesDao releasesDao = new ReleasesDao();
Releases releases = releasesDao.getLatestReleases(prod.getIdentifier(), prod.getVersion());
if (releases != null && releases.getName() != null) {
name = releases.getName();
release_date = releases.getDate();
description = releases.getDescription();
}
prod.setReleasesName(name);
prod.setReleasesDate(release_date);
prod.setReleasesDescription(description);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
3e0a516c0ea9a0d40a6e8a548b6e40599aa0f4dc | 1,285 | java | Java | common/rest-api/src/main/java/org/apache/syncope/common/rest/api/beans/AnySearchQuery.java | feuhaps/syncope | b13e9fe4dd226d7ef48b249447289e3a4451c84b | [
"Apache-2.0"
] | null | null | null | common/rest-api/src/main/java/org/apache/syncope/common/rest/api/beans/AnySearchQuery.java | feuhaps/syncope | b13e9fe4dd226d7ef48b249447289e3a4451c84b | [
"Apache-2.0"
] | 36 | 2015-10-05T12:21:18.000Z | 2015-10-29T17:13:10.000Z | common/rest-api/src/main/java/org/apache/syncope/common/rest/api/beans/AnySearchQuery.java | feuhaps/syncope | b13e9fe4dd226d7ef48b249447289e3a4451c84b | [
"Apache-2.0"
] | null | null | null | 32.125 | 71 | 0.740078 | 4,365 | /*
* 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.syncope.common.rest.api.beans;
import javax.ws.rs.QueryParam;
import org.apache.syncope.common.rest.api.service.JAXRSService;
public class AnySearchQuery extends AnyListQuery {
private static final long serialVersionUID = -6736562952418964707L;
private String fiql;
public String getFiql() {
return fiql;
}
@QueryParam(JAXRSService.PARAM_FIQL)
public void setFiql(final String fiql) {
this.fiql = fiql;
}
}
|
3e0a51768321b03f9906261b966e9b3c63ba47c9 | 10,230 | java | Java | gosu-xml/src/main/java/gw/internal/schema/gw/xsd/w3c/wsdl/anonymous/elements/TDefinitions_PortType.java | vakuum/gosu-lang-old | 48c598458abd412aa9f2d21b8088120e8aa9de00 | [
"Apache-2.0"
] | 1 | 2019-09-11T14:08:50.000Z | 2019-09-11T14:08:50.000Z | gosu-xml/src/main/java/gw/internal/schema/gw/xsd/w3c/wsdl/anonymous/elements/TDefinitions_PortType.java | gosu-lang/old-gosu-repo | 48c598458abd412aa9f2d21b8088120e8aa9de00 | [
"Apache-2.0"
] | null | null | null | gosu-xml/src/main/java/gw/internal/schema/gw/xsd/w3c/wsdl/anonymous/elements/TDefinitions_PortType.java | gosu-lang/old-gosu-repo | 48c598458abd412aa9f2d21b8088120e8aa9de00 | [
"Apache-2.0"
] | 2 | 2019-06-11T04:34:07.000Z | 2020-01-21T02:58:10.000Z | 73.071429 | 345 | 0.744966 | 4,366 | package gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements;
/***************************************************************************/
/* THIS IS AUTOGENERATED CODE - DO NOT MODIFY OR YOUR CHANGES WILL BE LOST */
/* THIS CODE CAN BE REGENERATED USING 'xsd-codegen' */
/***************************************************************************/
public class TDefinitions_PortType extends gw.xml.XmlElement implements gw.internal.xml.IXmlGeneratedClass {
public static final javax.xml.namespace.QName $ATTRIBUTE_QNAME_Name = new javax.xml.namespace.QName( "", "name", "" );
public static final javax.xml.namespace.QName $ELEMENT_QNAME_Documentation = new javax.xml.namespace.QName( "http://schemas.xmlsoap.org/wsdl/", "documentation", "wsdl" );
public static final javax.xml.namespace.QName $ELEMENT_QNAME_Operation = new javax.xml.namespace.QName( "http://schemas.xmlsoap.org/wsdl/", "operation", "wsdl" );
public static final javax.xml.namespace.QName $QNAME = new javax.xml.namespace.QName( "http://schemas.xmlsoap.org/wsdl/", "portType", "wsdl" );
public static final gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType> TYPE = new gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType>( gw.lang.reflect.TypeSystem.getGlobalLock() ) {
@Override
protected gw.lang.reflect.IType init() {
return gw.lang.reflect.TypeSystem.getByFullName( "gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType" );
}
};
private static final gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType> TYPEINSTANCETYPE = new gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType>( gw.lang.reflect.TypeSystem.getGlobalLock() ) {
@Override
protected gw.lang.reflect.IType init() {
return gw.lang.reflect.TypeSystem.getByFullName( "gw.xsd.w3c.wsdl.types.complex.TPortType" );
}
};
public TDefinitions_PortType() {
this( new gw.internal.schema.gw.xsd.w3c.wsdl.types.complex.TPortType() );
}
public TDefinitions_PortType( gw.internal.schema.gw.xsd.w3c.wsdl.types.complex.TPortType typeInstance ) {
super( $QNAME, TYPE.get(), TYPEINSTANCETYPE.get(), typeInstance );
}
protected TDefinitions_PortType( javax.xml.namespace.QName qname, gw.lang.reflect.IType type, gw.lang.reflect.IType schemaDefinedTypeInstanceType, gw.internal.schema.gw.xsd.w3c.xmlschema.types.complex.AnyType typeInstance ) {
super( qname, type, schemaDefinedTypeInstanceType, typeInstance );
}
public gw.internal.schema.gw.xsd.w3c.wsdl.types.complex.TPortType getTypeInstance() {
//noinspection RedundantCast
return (gw.internal.schema.gw.xsd.w3c.wsdl.types.complex.TPortType) super.getTypeInstance();
}
public void setTypeInstance( gw.internal.schema.gw.xsd.w3c.wsdl.types.complex.TPortType param ) {
super.setTypeInstance( param );
}
public gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDocumented_Documentation Documentation() {
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDocumented_Documentation) TYPE.get().getTypeInfo().getProperty( "Documentation" ).getAccessor().getValue( this );
}
public void setDocumentation$( gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDocumented_Documentation param ) {
TYPE.get().getTypeInfo().getProperty( "Documentation" ).getAccessor().setValue( this, param );
}
public java.lang.String Name() {
return (java.lang.String) TYPE.get().getTypeInfo().getProperty( "Name" ).getAccessor().getValue( this );
}
public void setName$( java.lang.String param ) {
TYPE.get().getTypeInfo().getProperty( "Name" ).getAccessor().setValue( this, param );
}
public java.util.List<gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TPortType_Operation> Operation() {
//noinspection unchecked
return (java.util.List<gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TPortType_Operation>) TYPE.get().getTypeInfo().getProperty( "Operation" ).getAccessor().getValue( this );
}
public void setOperation$( java.util.List<gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TPortType_Operation> param ) {
TYPE.get().getTypeInfo().getProperty( "Operation" ).getAccessor().setValue( this, param );
}
public static gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType parse( byte[] byteArray ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( byte[].class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { byteArray } );
}
public static gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType parse( byte[] byteArray, gw.xml.XmlParseOptions options ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( byte[].class ), gw.lang.reflect.TypeSystem.get( gw.xml.XmlParseOptions.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { byteArray, options } );
}
public static gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType parse( java.io.File file ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.io.File.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { file } );
}
public static gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType parse( java.io.File file, gw.xml.XmlParseOptions options ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.io.File.class ), gw.lang.reflect.TypeSystem.get( gw.xml.XmlParseOptions.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { file, options } );
}
public static gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType parse( java.io.InputStream inputStream ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.io.InputStream.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { inputStream } );
}
public static gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType parse( java.io.InputStream inputStream, gw.xml.XmlParseOptions options ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.io.InputStream.class ), gw.lang.reflect.TypeSystem.get( gw.xml.XmlParseOptions.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { inputStream, options } );
}
public static gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType parse( java.io.Reader reader ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.io.Reader.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { reader } );
}
public static gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType parse( java.io.Reader reader, gw.xml.XmlParseOptions options ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.io.Reader.class ), gw.lang.reflect.TypeSystem.get( gw.xml.XmlParseOptions.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { reader, options } );
}
public static gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType parse( java.lang.String xmlString ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.lang.String.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { xmlString } );
}
public static gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType parse( java.lang.String xmlString, gw.xml.XmlParseOptions options ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.lang.String.class ), gw.lang.reflect.TypeSystem.get( gw.xml.XmlParseOptions.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { xmlString, options } );
}
public static gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType parse( java.net.URL url ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.net.URL.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { url } );
}
public static gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType parse( java.net.URL url, gw.xml.XmlParseOptions options ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.wsdl.anonymous.elements.TDefinitions_PortType) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.net.URL.class ), gw.lang.reflect.TypeSystem.get( gw.xml.XmlParseOptions.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { url, options } );
}
@SuppressWarnings( {"UnusedDeclaration"} )
private static final long FINGERPRINT = 3737049672341785483L;
}
|
3e0a51953981c5d8b40c7bb5cfbe5a3e0e5bf39f | 3,834 | java | Java | platform/core-impl/src/com/intellij/ide/plugins/PluginLoadingError.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | platform/core-impl/src/com/intellij/ide/plugins/PluginLoadingError.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | null | null | null | platform/core-impl/src/com/intellij/ide/plugins/PluginLoadingError.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | null | null | null | 39.525773 | 140 | 0.708399 | 4,367 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.plugins;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.function.Supplier;
public final class PluginLoadingError {
private final @NotNull IdeaPluginDescriptor myPlugin;
private final Supplier<@NlsContexts.DetailedDescription String> myDetailedMessage;
private final Supplier<@NlsContexts.Label String> myShortMessage;
private final boolean myNotifyUser;
private PluginId myDisabledDependency;
static PluginLoadingError create(@NotNull IdeaPluginDescriptor plugin,
@NotNull Supplier<@NlsContexts.DetailedDescription String> detailedMessage,
@NotNull Supplier<@NlsContexts.Label @NotNull String> shortMessage) {
return new PluginLoadingError(plugin, detailedMessage, shortMessage, true);
}
static PluginLoadingError create(@NotNull IdeaPluginDescriptor plugin,
@NotNull Supplier<@NlsContexts.DetailedDescription @NotNull String> detailedMessage,
@NotNull Supplier<@NlsContexts.Label @NotNull String> shortMessage,
boolean notifyUser) {
return new PluginLoadingError(plugin, detailedMessage, shortMessage, notifyUser);
}
static PluginLoadingError createWithoutNotification(@NotNull IdeaPluginDescriptor plugin,
@NotNull Supplier<@NlsContexts.Label @NotNull String> shortMessage) {
return new PluginLoadingError(plugin, null, shortMessage, false);
}
private PluginLoadingError(@NotNull IdeaPluginDescriptor plugin,
Supplier<String> detailedMessage,
Supplier<String> shortMessage,
boolean notifyUser) {
myPlugin = plugin;
myDetailedMessage = detailedMessage;
myShortMessage = shortMessage;
myNotifyUser = notifyUser;
}
void setDisabledDependency(PluginId disabledDependency) {
myDisabledDependency = disabledDependency;
}
@NlsContexts.DetailedDescription
public String getDetailedMessage() {
return myDetailedMessage.get();
}
PluginId getDisabledDependency() {
return myDisabledDependency;
}
boolean isNotifyUser() {
return myNotifyUser;
}
void register(Map<PluginId, PluginLoadingError> errorsMap) {
errorsMap.put(myPlugin.getPluginId(), this);
}
@Override
public @NotNull String toString() {
return getInternalMessage();
}
@NotNull
public @NonNls String getInternalMessage() {
return formatErrorMessage(myPlugin, (myDetailedMessage == null ? myShortMessage : myDetailedMessage).get());
}
public @NlsContexts.Label String getShortMessage() {
return myShortMessage.get();
}
@NonNls @NotNull
static String formatErrorMessage(IdeaPluginDescriptor descriptor, @NotNull String message) {
String path = descriptor.getPluginPath().toString();
StringBuilder builder = new StringBuilder();
builder.append("The ").append(descriptor.getName()).append(" (id=").append(descriptor.getPluginId()).append(", path=");
builder.append(FileUtil.getLocationRelativeToUserHome(path, false));
String version = descriptor.getVersion();
if (version != null && !descriptor.isBundled() && !version.equals(PluginManagerCore.getBuildNumber().asString())) {
builder.append(", version=").append(version);
}
builder.append(") plugin ").append(message);
return builder.toString();
}
}
|
3e0a530659f7708f9645d26ef1f591bbda9caeb4 | 1,403 | java | Java | spring-boot-learn/src/main/java/com/zengdw/learn/redis/listener/RedisKeyExpirationListener.java | zengdw/study-project | d4e205cf17fe078a1fea977f9d548ab6b162570d | [
"Apache-2.0"
] | null | null | null | spring-boot-learn/src/main/java/com/zengdw/learn/redis/listener/RedisKeyExpirationListener.java | zengdw/study-project | d4e205cf17fe078a1fea977f9d548ab6b162570d | [
"Apache-2.0"
] | null | null | null | spring-boot-learn/src/main/java/com/zengdw/learn/redis/listener/RedisKeyExpirationListener.java | zengdw/study-project | d4e205cf17fe078a1fea977f9d548ab6b162570d | [
"Apache-2.0"
] | null | null | null | 34.219512 | 100 | 0.764077 | 4,368 | package com.zengdw.learn.redis.listener;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
/**
* @author : zengd
* @date : Created in 2021/1/19 14:07
* @description: 监听redis key过期事件
* @version: 1.0
*/
@Component
public class RedisKeyExpirationListener implements MessageListener, DisposableBean {
private static final Topic KEYEVENT_EXPIRED_TOPIC = new PatternTopic("__keyevent@*__:expired");
private final RedisMessageListenerContainer container;
public RedisKeyExpirationListener(RedisMessageListenerContainer container){
this.container = container;
container.addMessageListener(this, KEYEVENT_EXPIRED_TOPIC);
}
@Override
public void destroy() {
container.removeMessageListener(this);
}
@Override
public void onMessage(Message message, byte[] bytes) {
if (!ObjectUtils.isEmpty(message.getChannel()) && !ObjectUtils.isEmpty(message.getBody())) {
System.out.println(message);
}
}
}
|
3e0a53793054362d5c257ba23d3f274f9d325be4 | 2,628 | java | Java | app/src/main/java/com/paulliu/zhihudaily/entity/CommentEntity.java | LevineLiu/ZhihuDaily | b181baffc8457d873c6ea4a62eba47bbb5c4da96 | [
"Apache-2.0"
] | 2 | 2017-02-27T13:02:27.000Z | 2017-02-27T13:02:30.000Z | app/src/main/java/com/paulliu/zhihudaily/entity/CommentEntity.java | LevineLiu/ZhihuDaily | b181baffc8457d873c6ea4a62eba47bbb5c4da96 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/paulliu/zhihudaily/entity/CommentEntity.java | LevineLiu/ZhihuDaily | b181baffc8457d873c6ea4a62eba47bbb5c4da96 | [
"Apache-2.0"
] | null | null | null | 20.215385 | 128 | 0.555936 | 4,369 | package com.paulliu.zhihudaily.entity;
/**
* Created on 2017/2/3
*
* @author LLW
*/
public class CommentEntity {
/**
* author : TuoTuo的亲爹
* content : 第一次也是吃了牛肉…吃完以后,人家很客气的问我还需要么…我也很客气地再来了一盒鸡肉的。。。。可惜后来专门坐那个航班,居然换成茄子饭了?
* avatar : http://pic1.zhimg.com/8949bb2f30ed5789857accd489644234_im.jpg
* time : 1413859600
* reply_to : {"content":"我每次都不假思索选了牛肉,然后就深深的后悔没有试过一次鸡肉,到下一次又情不自禁选了牛肉,周而复始循环往复-_-#","status":0,"id":551969,"author":"怒放的腋毛"}
* id : 552762
* likes : 0
*/
private String author;
private String content;
private String avatar;
private int time;
private ReplyToBean reply_to;
private int id;
private int likes;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public ReplyToBean getReply_to() {
return reply_to;
}
public void setReply_to(ReplyToBean reply_to) {
this.reply_to = reply_to;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public static class ReplyToBean {
/**
* content : 我每次都不假思索选了牛肉,然后就深深的后悔没有试过一次鸡肉,到下一次又情不自禁选了牛肉,周而复始循环往复-_-#
* status : 0
* id : 551969
* author : 怒放的腋毛
*/
private String content;
private int status;
private int id;
private String author;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
}
|
3e0a53b734d6d1562d8d31574efffbf92f60a612 | 1,389 | java | Java | codeForces/round736/GregorAndPawnGame.java | YaduAhuja/CP-Repo | 2113ab02c430c6b92c1b372d847e22f126f75246 | [
"MIT"
] | 3 | 2021-04-13T17:34:28.000Z | 2021-05-24T19:45:07.000Z | codeForces/round736/GregorAndPawnGame.java | YaduAhuja/CP-Repo | 2113ab02c430c6b92c1b372d847e22f126f75246 | [
"MIT"
] | null | null | null | codeForces/round736/GregorAndPawnGame.java | YaduAhuja/CP-Repo | 2113ab02c430c6b92c1b372d847e22f126f75246 | [
"MIT"
] | 6 | 2021-04-14T10:09:40.000Z | 2021-12-14T13:39:49.000Z | 30.866667 | 86 | 0.480202 | 4,370 | /**
* Problem Link : https://codeforces.com/contest/1549/problem/B
* Runtime: 0.202s
*/
package codeForces.round736;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class GregorAndPawnGame {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
var sb = new StringBuilder();
for (int i = 0; i < t; i++) {
int n = Integer.parseInt(br.readLine().trim());
char[][] board = new char[2][n];
for (int j = 0; j < 2; j++) board[j] = br.readLine().trim().toCharArray();
sb.append(getPawnsOptimized(board)).append("\n");
}
br.close();
System.out.println(sb);
}
private static int getPawnsOptimized(char[][] board) {
int ret = 0;
for (int i = 0; i < board[0].length; i++) {
if (board[1][i] == '1') {
if (board[0][i] == '0') ret++;
else if (i > 0 && board[0][i - 1] == '1') {
ret++;
board[0][i - 1] = '2';
} else if (i + 1 < board[0].length && board[0][i + 1] == '1') {
ret++;
board[0][i + 1] = '2';
}
}
}
return ret;
}
}
|
3e0a544c7c3d6a939f29071e4cb6d6d2268c9f40 | 131 | java | Java | app/src/main/java/com/dsource/idc/jellowintl/packageUpdate/UpdateTaskStage.java | anr007/Jellow-Arch | 75e7cd53820e75cfa9376a4fd706114e526c330d | [
"BSD-3-Clause"
] | null | null | null | app/src/main/java/com/dsource/idc/jellowintl/packageUpdate/UpdateTaskStage.java | anr007/Jellow-Arch | 75e7cd53820e75cfa9376a4fd706114e526c330d | [
"BSD-3-Clause"
] | null | null | null | app/src/main/java/com/dsource/idc/jellowintl/packageUpdate/UpdateTaskStage.java | anr007/Jellow-Arch | 75e7cd53820e75cfa9376a4fd706114e526c330d | [
"BSD-3-Clause"
] | null | null | null | 21.833333 | 49 | 0.78626 | 4,371 | package com.dsource.idc.jellowintl.packageUpdate;
public enum UpdateTaskStage {
STAGE_1, STAGE_2, STAGE_3, STAGE_4, STAGE_5
}
|
3e0a5558eae5774c6135dc56888d1f9e75beaac7 | 4,770 | java | Java | src/main/java/br/ufscar/hclga/classes/CountRules.java | geantrindade/HC-LGA | b2ce56d66e5aca33f0b696d2d03da1e059528486 | [
"MIT"
] | 2 | 2020-09-19T17:18:37.000Z | 2021-06-01T07:31:20.000Z | src/main/java/br/ufscar/hclga/classes/CountRules.java | geantrindade/HC-LGA | b2ce56d66e5aca33f0b696d2d03da1e059528486 | [
"MIT"
] | null | null | null | src/main/java/br/ufscar/hclga/classes/CountRules.java | geantrindade/HC-LGA | b2ce56d66e5aca33f0b696d2d03da1e059528486 | [
"MIT"
] | 1 | 2018-09-04T18:16:18.000Z | 2018-09-04T18:16:18.000Z | 30.660256 | 96 | 0.573908 | 4,372 | package br.ufscar.hclga.classes;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* @author Gean Trindade <ychag@example.com / lyhxr@example.com>
*/
public class CountRules {
public ArrayList<String> readRulesFile(String rulesFile) {
ArrayList<String> result = new ArrayList<>();
try {
FileReader reader = new FileReader(rulesFile);
BufferedReader buffReader = new BufferedReader(reader);
String line = null;
while ((line = buffReader.readLine()) != null) {
if (!line.isEmpty()) {
result.add(line);
}
}
buffReader.close();
reader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return result;
}
public ArrayList<String> readRulesFileClus(String rulesFile) {
ArrayList<String> result = new ArrayList<>();
String wholeRule = "";
try {
FileReader reader = new FileReader(rulesFile);
BufferedReader buffReader = new BufferedReader(reader);
String line = null;
while ((line = buffReader.readLine()) != null) {
if (!line.isEmpty()) {
wholeRule += line;
if (line.contains("THEN")) {
result.add(wholeRule);
wholeRule = "";
}
}
}
buffReader.close();
reader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
for (int i = 0; i < result.size(); i++) {
String aux = result.get(i);
aux = aux.replaceAll("=", "");
aux = aux.replace(":", "=");
aux = aux.replace("IF", "");
aux = aux.replace("[", "");
int index = aux.indexOf("]");
aux = aux.substring(0, index);
aux = aux.trim();
result.remove(i);
result.add(i, aux);
}
return result;
}
public int countTestsInRules(ArrayList<String> rulesFile) {
int cont = 0;
int ini;
while (!rulesFile.isEmpty()) {
String line = rulesFile.remove(0).trim();
if (!line.isEmpty()) {
ini = 0;
if (line.indexOf("AND") == -1) {
cont++;
} else {
cont++;
while ((ini = line.indexOf("AND", ini)) != -1) {
cont++;
ini += 3;
}
}
}
}
return cont;
}
public void run(String pathRules, String dataset, int folds, int numberOfTrainIntances) {
double meanNumberOfRules = 0, meanTestsInRules = 0;
double meanAverageTestPerRule = 0, meanAverageCoveragePerRule = 0;
System.out.println("=====================================================");
System.out.println("dataset: " + dataset);
for (int i = 1; i <= folds; i++) {
// ArrayList<String> rules = readRulesFileClus(pathRules + dataset + i + "Rules.txt");
ArrayList<String> rules = readRulesFile(pathRules + dataset + i + "Rules.txt");
int numberOfRules = rules.size();
meanNumberOfRules += numberOfRules;
int testsInRules = countTestsInRules(rules);
meanTestsInRules += testsInRules;
Double averageTestPerRule = (double) testsInRules / (double) numberOfRules;
meanAverageTestPerRule += averageTestPerRule;
Double averageCoveragePerRule = (double) numberOfTrainIntances / (double) numberOfRules;
meanAverageCoveragePerRule += averageCoveragePerRule;
System.out.println("fold " + i);
System.out.println("numberOfRules: " + numberOfRules);
System.out.println("numberOfActiveTests: " + testsInRules);
System.out.println("averageTestPerRule: " + averageTestPerRule);
System.out.println("averageCoveragePerRule: " + averageCoveragePerRule + "\n");
}
System.out.println("\nmeanNumberOfRules: " + meanNumberOfRules / folds);
System.out.println("meanNumberOfActiveTests: " + meanTestsInRules / folds);
System.out.println("meanAverageTestPerRule: " + meanAverageTestPerRule / folds);
System.out.println("meanAverageCoveragePerRule: " + meanAverageCoveragePerRule / folds);
System.out.println("=====================================================\n\n");
}
public static void main(String[] args) {
CountRules c = new CountRules();
// c.run("C:\\Users\\gean_\\Dropbox\\posGrad\\GACerriMaven\\src\\main\\java\\"
// + "hmc_ga\\mips\\finalTestMipsAVGConfig3_e2m2c8pt4\\fold10\\",
// "mips", 10, 16805);
c.run("C:\\Users\\gean_\\Dropbox\\posGrad\\GACerriMaven\\src\\main\\java\\"
+ "hmc_ga\\repbase\\testRepbaseAVGPConfig12_config8\\fold10\\",
"repbase", 10, 31091);
}
}
|
3e0a55a039f9912e20eee986ca7c6ac2979937ec | 934 | java | Java | src/main/java/com/example/demo/domain/Log.java | DEVOPS-PROJECTS-ORGANIZATION/Servers-0.2.0 | 9987fb2819de604f6b35f26eb2128c424ba76c34 | [
"MIT"
] | null | null | null | src/main/java/com/example/demo/domain/Log.java | DEVOPS-PROJECTS-ORGANIZATION/Servers-0.2.0 | 9987fb2819de604f6b35f26eb2128c424ba76c34 | [
"MIT"
] | null | null | null | src/main/java/com/example/demo/domain/Log.java | DEVOPS-PROJECTS-ORGANIZATION/Servers-0.2.0 | 9987fb2819de604f6b35f26eb2128c424ba76c34 | [
"MIT"
] | null | null | null | 25.944444 | 98 | 0.728051 | 4,373 | package com.example.demo.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class Log {
private static final String DELIMITER = "|";
private static final String FORMAT = "%s" + DELIMITER + "%s" + DELIMITER + "%s";
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
private LocalDateTime timestamp;
private String service;
private String content;
public Log(String service, String content) {
this.timestamp = LocalDateTime.now();
this.service = service;
this.content = content;
}
@Override
public String toString() {
return String.format(FORMAT, DATE_FORMATTER.format(timestamp), service, content);
}
}
|
3e0a569f8d43277e3d844208f7551299393e3517 | 20,139 | java | Java | controlsfx/src/main/java/org/controlsfx/control/WorldMapView.java | fmichel/controlsfx | 2aa218c58db495e0230e2e8ebed593c6049974a0 | [
"BSD-3-Clause"
] | 1,197 | 2018-12-28T20:20:46.000Z | 2022-03-30T23:58:31.000Z | controlsfx/src/main/java/org/controlsfx/control/WorldMapView.java | fmichel/controlsfx | 2aa218c58db495e0230e2e8ebed593c6049974a0 | [
"BSD-3-Clause"
] | 351 | 2018-12-29T11:32:51.000Z | 2022-03-21T05:00:21.000Z | controlsfx/src/main/java/org/controlsfx/control/WorldMapView.java | fmichel/controlsfx | 2aa218c58db495e0230e2e8ebed593c6049974a0 | [
"BSD-3-Clause"
] | 278 | 2018-12-30T11:18:33.000Z | 2022-03-29T17:14:32.000Z | 27.178138 | 154 | 0.606435 | 4,374 | /**
* Copyright (c) 2016, ControlsFX
* All rights reserved.
* <p>
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of ControlsFX, any associated website, nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
* <p>
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CONTROLSFX BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.controlsfx.control;
import impl.org.controlsfx.worldmap.WorldMapViewSkin;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.Skin;
import javafx.scene.control.Tooltip;
import javafx.scene.shape.Circle;
import javafx.scene.shape.SVGPath;
import javafx.util.Callback;
import java.util.Locale;
import java.util.Objects;
/**
* A simple map view showing either the entire world or a list of countries. The view
* is not capable of displaying detailed map information. The view is based on simple SVG data found in a
* properties file of the ControlsFX distribution. A big advantage of this approach is the fact that the view
* can be run without a network connection. In addition to showing countries or the world the view can also
* show locations. The map can be customized by specifying custom factories for the country and
* location views.
* <h2>Example: Country View Factory</h2>
* The code snippet below shows how a custom country view factory can be used to assign individual styles
* to all countries. In this example the style is used to color the countries differently.
* <code>
* worldMapView.setCountryViewFactory(country -> {
* CountryView view = new CountryView(country);
* if (showColorsProperty.get()) {
* view.getStyleClass().add("country" + ((country.ordinal() % 8) + 1));
* }
* return view;
* });
* </code>
* <h2>Example: Location View Factory</h2>
* Each location can be visualized with its own node. The default location view factory creates a simple circle
* shape.
* <p>
* <code>
* worldMapView.setLocationViewFactory(location -> {
* Circle circle = new Circle();
* circle.getStyleClass().add("location");
* circle.setRadius(4);
* circle.setTranslateX(-4); // translate to center node on location
* circle.setTranslateY(-4); // translate to center node on location
* return circle;
* });
* </code>
* Shown below is a screenshot of the world map view:
* <br>
* <center>
* <img src="world-map.png" alt="Screenshot of WorldMapView">
* </center>
*/
public class WorldMapView extends ControlsFXControl {
private static final String DEFAULT_STYLE_CLASS = "world-map";
// A shared tooltip instance to save memory
private Tooltip tooltip = new Tooltip();
/**
* Constructs a new map view with an initially empty list of countries which will
* result in the entire world to be shown.
*/
public WorldMapView() {
getStyleClass().add(DEFAULT_STYLE_CLASS);
setCountryViewFactory(country -> {
CountryView view = new CountryView(country);
view.setOnMouseEntered(evt -> tooltip.setText(country.getLocale().getDisplayCountry()));
Tooltip.install(view, tooltip);
return view;
});
setLocationViewFactory(location -> {
Circle circle = new Circle();
circle.setRadius(4);
circle.setTranslateX(-4);
circle.setTranslateY(-4);
circle.setOnMouseEntered(evt -> tooltip.setText(location.getName()));
Tooltip.install(circle, tooltip);
return circle;
});
}
@Override
protected Skin<?> createDefaultSkin() {
return new WorldMapViewSkin(this);
}
@Override
public String getUserAgentStylesheet() {
return getUserAgentStylesheet(WorldMapView.class, "world.css");
}
/**
* The selection modes supported by the view.
*
* @see WorldMapView#setCountrySelectionMode(SelectionMode)
* @see WorldMapView#setLocationSelectionMode(SelectionMode)
* @see WorldMapView#getSelectedCountries()
* @see WorldMapView#getSelectedLocations()
*/
public enum SelectionMode {
/**
* The single selection mode allows the user to always only select one country and one location
* at a time.
*/
SINGLE,
/**
* The multiple selection mode allows the user to select several countries and locations at the
* same time.
*/
MULTIPLE
}
// country selection support
private final ObjectProperty<SelectionMode> countrySelectionMode = new SimpleObjectProperty<>(this, "countrySelectionMode", SelectionMode.MULTIPLE);
/**
* A property used to store the selection mode that will be applied for the selection
* of countries.
*
* @return the country selection mode property
*/
public final ObjectProperty<SelectionMode> countrySelectionModeProperty() {
return countrySelectionMode;
}
/**
* Returns the value of {@link #countrySelectionModeProperty()}
*
* @return the country selection mode
*/
public final SelectionMode getCountrySelectionMode() {
return countrySelectionMode.get();
}
/**
* Sets the value of {@link #countrySelectionModeProperty()}.
*
* @param mode the country selection mode
*/
public final void setCountrySelectionMode(SelectionMode mode) {
this.countrySelectionMode.set(mode);
}
// location selection support
private final ObjectProperty<SelectionMode> locationSelectionMode = new SimpleObjectProperty<>(this, "locationSelectionMode", SelectionMode.MULTIPLE);
/**
* A property used to store the selection mode that will be applied for the selection
* of locations.
*
* @return the location selection mode property
*/
public final ObjectProperty<SelectionMode> locationSelectionModeProperty() {
return locationSelectionMode;
}
/**
* Returns the value of {@link #locationSelectionModeProperty()}
*
* @return the location selection mode
*/
public final SelectionMode getLocationSelectionMode() {
return locationSelectionMode.get();
}
/**
* Sets the value of {@link #locationSelectionModeProperty()}.
*
* @param mode the location selection mode
*/
public final void setLocationSelectionMode(SelectionMode mode) {
this.locationSelectionMode.set(mode);
}
// zoom support
private final DoubleProperty zoomFactor = new SimpleDoubleProperty(this, "zoomFactor", 1) {
@Override
public void set(double newValue) {
super.set(Math.max(1, Math.min(10, newValue)));
}
};
/**
* A property used to store the current zoom factor, a value between 1 and 10.
*
* @return the zoom factor
*/
public final DoubleProperty zoomFactorProperty() {
return zoomFactor;
}
/**
* Returns the value of {@link #zoomFactorProperty()}.
*
* @return the zoom factor
*/
public final double getZoomFactor() {
return zoomFactor.get();
}
/**
* Sets the value of {@link #zoomFactorProperty()}.
*
* @param factor the zoom factor
*/
public final void setZoomFactor(double factor) {
this.zoomFactor.set(factor);
}
private final ListProperty<Country> selectedCountries = new SimpleListProperty<>(this, "selectedCountries", FXCollections.observableArrayList());
/**
* A property used for storing the list of selected countries (aka "the selection model").
*
* @return the selected countries property
*/
public final ListProperty<Country> selectedCountriesProperty() {
return selectedCountries;
}
/**
* Returns the list of currently selected countries.
*
* @return the list of selected countries
*/
public final ObservableList<Country> getSelectedCountries() {
return selectedCountries.get();
}
/**
* Sets the list of currently selected countries.
*
* @param countries the selected countries
*/
public final void setSelectedCountries(ObservableList<Country> countries) {
this.selectedCountries.set(countries);
}
private final ListProperty<Location> selectedLocations = new SimpleListProperty<>(this, "selectedLocations", FXCollections.observableArrayList());
/**
* A property used for storing the list of selected locations (aka "the selection model").
*
* @return the selected locations property
*/
public final ListProperty<Location> selectedLocationsProperty() {
return selectedLocations;
}
/**
* Returns the list of currently selected locations.
*
* @return the list of selected locations
*/
public final ObservableList<Location> getSelectedLocations() {
return selectedLocations.get();
}
/**
* Sets the list of currently selected locations.
*
* @param locations the selected locations
*/
public final void setSelectedLocations(ObservableList<Location> locations) {
this.selectedLocations.set(locations);
}
// Visible countries support.
private final ListProperty<Country> countries = new SimpleListProperty<>(this, "countries", FXCollections.observableArrayList());
/**
* A property used to store the list of countries that should be shown by the map. If this
* list is empty then the view will show the entire world.
*
* @return the list of countries shown by the map
*/
public final ListProperty<Country> countriesProperty() {
return countries;
}
/**
* Returns the list of countries that will be shown by the map.
*
* @return the list of countries shown by the map
*/
public final ObservableList<Country> getCountries() {
return countries.get();
}
/**
* Sets the list of countries that will be shown by the map.
*
* @param countries the list of countries shown by the map
*/
public final void setCountries(ObservableList<Country> countries) {
this.countries.set(countries);
}
private final ListProperty<Location> locations = new SimpleListProperty<>(this, "locations", FXCollections.observableArrayList());
/**
* A property used to store the list of locations shown by the map.
*/
public final ListProperty<Location> locationsProperty() {
return locations;
}
/**
* Returns the list of locations shown by the map.
*
* @return the list of locations
*/
public final ObservableList<Location> getLocations() {
return locations.get();
}
/**
* Sets the list of locations shown by the map.
*
* @param locations the list of locations
*/
public final void setLocations(ObservableList<Location> locations) {
this.locations.set(locations);
}
private final BooleanProperty showLocations = new SimpleBooleanProperty(this, "showLocations", true);
/**
* A property used to control whether locations will be shown by the map or not.
*
* @return a property to control the visibility of locations
*/
public final BooleanProperty showLocationsProperty() {
return showLocations;
}
/**
* Returns the value of {@link #showLocationsProperty()}.
*
* @return true if locations are shown
*/
public final boolean isShowLocations() {
return showLocations.get();
}
/**
* Sets the value of {@link #showLocationsProperty()}.
*
* @param show if true then locations are shown
*/
public final void setShowLocations(boolean show) {
this.showLocations.set(show);
}
// Location view factory.
private final ObjectProperty<Callback<Location, Node>> locationViewFactory = new SimpleObjectProperty<>(this, "locationViewFactory");
/**
* A property used to store a factory callback for creating new location views (nodes).
*
* @return the location view factory property
*/
public final ObjectProperty<Callback<Location, Node>> locationViewFactoryProperty() {
return locationViewFactory;
}
/**
* Returns the value of {@link #locationViewFactoryProperty()}.
*
* @return the location view factory
*/
public final Callback<Location, Node> getLocationViewFactory() {
return locationViewFactory.get();
}
/**
* Sets the value of {@link #locationViewFactoryProperty()}.
*
* @param factory the location view factory
*/
public final void setLocationViewFactory(Callback<Location, Node> factory) {
this.locationViewFactory.set(factory);
}
// Country view factory.
private final ObjectProperty<Callback<Country, CountryView>> countryViewFactory = new SimpleObjectProperty(this, "countryViewFactory");
/**
* A property used to store a factory callback for creating new country views.
*
* @return the country view factory property
*/
public final ObjectProperty<Callback<Country, CountryView>> countryViewFactoryProperty() {
return countryViewFactory;
}
/**
* Returns the value of {@link #countryViewFactoryProperty()}.
*
* @return the country view factory
*/
public final Callback<Country, CountryView> getCountryViewFactory() {
return countryViewFactory.get();
}
/**
* Sets the value of {@link #countryViewFactoryProperty()}.
*
* @param factory the country view factory
*/
public final void setCountryViewFactory(Callback<Country, CountryView> factory) {
this.countryViewFactory.set(factory);
}
/**
* A view used to visualize the bounds of a country via SVG. The SVG information
* will be set on the view as part of the skin implementation of the map view. Applications
* can provide subclasses of this view in order to install their own event handling or
* tooltips.
*
* @see WorldMapView#setCountryViewFactory(Callback)
*/
public static class CountryView extends SVGPath {
private final Country country;
public CountryView(Country country) {
super();
this.country = Objects.requireNonNull(country);
}
public final Country getCountry() {
return country;
}
public String getName() {
return country.name();
}
}
/**
* An enumerator listing all countries of the world.
*
* @see WorldMapView#setLocationViewFactory(Callback)
* @see WorldMapView#getCountries()
*/
public enum Country {
AE,
AO,
AR,
AT,
AU,
AZ,
BA,
BD,
BE,
BF,
BG,
BI,
BJ,
BN,
BO,
BR,
BS,
BT,
BW,
BY,
BZ,
CA,
CD,
CF,
CG,
CH,
CI,
CL,
CM,
CN,
CO,
CR,
CU,
CY,
CZ,
DE,
DJ,
DK,
DO,
DZ,
EC,
EE,
EG,
EH,
ER,
ES,
ET,
FK,
FI,
FJ,
FR,
GA,
GB,
GE,
GF,
GH,
GL,
GM,
GN,
GQ,
GR,
GT,
GW,
GY,
HN,
HR,
HT,
HU,
ID,
IE,
IL,
IN,
IQ,
IR,
IS,
IT,
JM,
JO,
JP,
KE,
KG,
KH,
KP,
KR,
XK,
KW,
KZ,
LA,
LB,
LK,
LR,
LS,
LT,
LU,
LV,
LY,
MA,
MD,
ME,
MG,
MK,
ML,
MM,
MN,
MR,
MW,
MX,
MY,
MZ,
NA,
NC,
NE,
NG,
NI,
NL,
NO,
NP,
NZ,
OM,
PA,
PE,
PG,
PH,
PL,
PK,
PR,
PS,
PT,
PY,
QA,
RO,
RS,
RU,
RW,
SA,
SB,
SD,
SE,
SI,
SJ,
SK,
SL,
SN,
SO,
SR,
SS,
SV,
SY,
SZ,
TD,
TF,
TG,
TH,
TJ,
TL,
TM,
TN,
TR,
TT,
TW,
TZ,
UA,
UG,
US,
UY,
UZ,
VE,
VN,
VU,
YE,
ZA,
ZM,
ZW;
private final Locale locale;
Country(final String... p) {
this.locale = new Locale("", name());
}
/**
* Returns the locale for the given country. The locale can be used to lookup
* the display name of the country.
*
* @return the locale matching the country
*/
public Locale getLocale() {
return locale;
}
}
/**
* An object using latitude and longitude information to specify a location
* in the real world.
*
* @see WorldMapView#setLocationViewFactory(Callback)
*/
public static class Location {
private String name;
private double latitude;
private double longitude;
/**
* Constructs a new location.
*
* @param latitude the latitude data
* @param longitude the longitude data
*/
public Location(double latitude, double longitude) {
this("", latitude, longitude);
}
/**
* Constructs a new location.
*
* @param name the name of the location (e.g. "Zurich")
* @param latitude the latitude data
* @param longitude the longitude data
*/
public Location(String name, double latitude, double longitude) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
}
/**
* Returns the name of the location.
*
* @return the location's name
*/
public final String getName() {
return name;
}
/**
* Returns the latitude of the location.
*
* @return the latitude
*/
public final double getLatitude() {
return latitude;
}
/**
* Returns the longitude of the location.
*
* @return the longitude
*/
public final double getLongitude() {
return longitude;
}
}
} |
3e0a57e453379fad25758cb349313073d3cf2386 | 2,730 | java | Java | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/ServicePlugin.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/ServicePlugin.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/ServicePlugin.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | 28.14433 | 814 | 0.78022 | 4,375 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.util
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|util
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|Closeable
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceAudience
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceStability
import|;
end_import
begin_comment
comment|/** * Service plug-in interface. * * Service plug-ins may be used to expose functionality of datanodes or * namenodes using arbitrary RPC protocols. Plug-ins are instantiated by the * service instance, and are notified of service life-cycle events using the * methods defined by this class. * * Service plug-ins are started after the service instance is started, and * stopped before the service instance is stopped. */
end_comment
begin_interface
annotation|@
name|InterfaceAudience
operator|.
name|Private
annotation|@
name|InterfaceStability
operator|.
name|Unstable
DECL|interface|ServicePlugin
specifier|public
interface|interface
name|ServicePlugin
extends|extends
name|Closeable
block|{
comment|/** * This method is invoked when the service instance has been started. * * @param service The service instance invoking this method */
DECL|method|start (Object service)
name|void
name|start
parameter_list|(
name|Object
name|service
parameter_list|)
function_decl|;
comment|/** * This method is invoked when the service instance is about to be shut down. */
DECL|method|stop ()
name|void
name|stop
parameter_list|()
function_decl|;
block|}
end_interface
end_unit
|
3e0a58d8325a070dc329cbe52917aa12f625063d | 1,480 | java | Java | src/main/java/org/trustedanalytics/servicebroker/gearpump/service/file/FileReaderService.java | trustedanalytics-ng/gearpump-broker | 749e85bc6c9e184c1eec82f512d98071e62fe952 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2017-04-28T07:52:29.000Z | 2017-04-28T07:52:29.000Z | src/main/java/org/trustedanalytics/servicebroker/gearpump/service/file/FileReaderService.java | trustedanalytics-ng/gearpump-broker | 749e85bc6c9e184c1eec82f512d98071e62fe952 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/main/java/org/trustedanalytics/servicebroker/gearpump/service/file/FileReaderService.java | trustedanalytics-ng/gearpump-broker | 749e85bc6c9e184c1eec82f512d98071e62fe952 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2016-12-29T12:43:13.000Z | 2020-01-22T18:41:44.000Z | 29.019608 | 87 | 0.687838 | 4,376 | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.servicebroker.gearpump.service.file;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.*;
@Service
public class FileReaderService {
@Autowired
private FileService fileService;
private String readData(BufferedReader input) throws IOException {
StringBuilder sb = new StringBuilder();
String line;
while ((line = input.readLine()) != null) {
if (!line.trim().startsWith("#")) {
sb.append(line);
}
}
return sb.toString();
}
public String read(String filePath) throws IOException {
fileService.setFilePath(filePath);
try (BufferedReader reader = new BufferedReader(fileService.getFileReader())) {
return readData(reader);
}
}
}
|
3e0a594c15242a393cb0eda0fbc3f453b8639996 | 852 | java | Java | src/main/java/org/ralasafe/db/sql/ValuesOfIn.java | donkeycart/-ralasafe | 8f53fbce5e9c28c0c98aa45466b1f6b88b976382 | [
"Apache-2.0"
] | 36 | 2015-01-26T07:32:36.000Z | 2020-06-06T07:28:46.000Z | src/main/java/org/ralasafe/db/sql/ValuesOfIn.java | donkeycart/-ralasafe | 8f53fbce5e9c28c0c98aa45466b1f6b88b976382 | [
"Apache-2.0"
] | 1 | 2019-04-26T08:09:23.000Z | 2019-04-26T08:09:23.000Z | src/main/java/org/ralasafe/db/sql/ValuesOfIn.java | donkeycart/-ralasafe | 8f53fbce5e9c28c0c98aa45466b1f6b88b976382 | [
"Apache-2.0"
] | 49 | 2015-01-26T04:59:17.000Z | 2021-08-10T08:25:53.000Z | 23.027027 | 85 | 0.66784 | 4,377 | /**
* Copyright (c) 2004-2011 Wang Jinbao(Julian Wong), http://www.ralasafe.com
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
package org.ralasafe.db.sql;
import java.util.ArrayList;
import java.util.Iterator;
public class ValuesOfIn implements RightOfIn {
private ArrayList values=new ArrayList();
public String toSQL() {
StringBuffer buf=new StringBuffer();
buf.append( " (" );
if( values.size()>0 ) {
Iterator itr=values.iterator();
Value value=(Value) itr.next();
buf.append( value.toSQL() );
while( itr.hasNext() ) {
value=(Value) itr.next();
buf.append( "," ).append( value.toSQL() );
}
}
buf.append( ") " );
return buf.toString();
}
public ArrayList getValues() {
return values;
}
public void setValues( ArrayList values ) {
this.values=values;
}
}
|
3e0a59911652787c975173a37896ffe2a26a2f2f | 789 | java | Java | src/shiyiyue11/Nov_22/leetcode_300.java | iceswordhs/AlgorithmsStudy | 5f87d7a45bdcd08a637744cd5572d05f1af21bce | [
"Apache-2.0"
] | null | null | null | src/shiyiyue11/Nov_22/leetcode_300.java | iceswordhs/AlgorithmsStudy | 5f87d7a45bdcd08a637744cd5572d05f1af21bce | [
"Apache-2.0"
] | null | null | null | src/shiyiyue11/Nov_22/leetcode_300.java | iceswordhs/AlgorithmsStudy | 5f87d7a45bdcd08a637744cd5572d05f1af21bce | [
"Apache-2.0"
] | null | null | null | 21.916667 | 82 | 0.485425 | 4,378 | package shiyiyue11.Nov_22;
/**
* @author Hs
* @Date 2021/11/22 20:51
*/
/**
* 给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
*
* 子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。
*
* 思路:动态规划 dp[i]表示以第i个节点为结尾的递增序列长度,注意:第i个元素一定要选
* 如果第i个元素大于前一个元素,dp[i]=dp[i-1]
* 否则dp[i]=1
*/
public class leetcode_300 {
public int lengthOfLIS(int[] nums) {
int len=nums.length;
if(len==0) return 0;
int[] dp=new int[len];
dp[0]=1;
int max=1;
for(int i=1;i<len;i++){
dp[i]=1;
for(int j=0;j<i;j++){
if(nums[i]>nums[j]){
dp[i]=Math.max(dp[i],dp[j]+1);
}
}
max=Math.max(max,dp[i]);
}
return max;
}
}
|
3e0a5a7f934f7d052adfe9348574766590ec0a57 | 1,172 | java | Java | src/main/java/org/cloudfoundry/credhub/generator/RsaGenerator.java | Acidburn0zzz/credhub | 7e4f439c4bd5a2f140b0f34020945965a10dae8f | [
"Apache-2.0"
] | 1 | 2018-10-30T10:08:00.000Z | 2018-10-30T10:08:00.000Z | src/main/java/org/cloudfoundry/credhub/generator/RsaGenerator.java | Acidburn0zzz/credhub | 7e4f439c4bd5a2f140b0f34020945965a10dae8f | [
"Apache-2.0"
] | null | null | null | src/main/java/org/cloudfoundry/credhub/generator/RsaGenerator.java | Acidburn0zzz/credhub | 7e4f439c4bd5a2f140b0f34020945965a10dae8f | [
"Apache-2.0"
] | null | null | null | 34.470588 | 84 | 0.804608 | 4,379 | package org.cloudfoundry.credhub.generator;
import org.cloudfoundry.credhub.credential.RsaCredentialValue;
import org.cloudfoundry.credhub.request.GenerationParameters;
import org.cloudfoundry.credhub.request.RsaGenerationParameters;
import org.cloudfoundry.credhub.util.CertificateFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.security.KeyPair;
@Component
public class RsaGenerator implements CredentialGenerator<RsaCredentialValue> {
private final LibcryptoRsaKeyPairGenerator keyGenerator;
@Autowired
RsaGenerator(LibcryptoRsaKeyPairGenerator keyGenerator) {
this.keyGenerator = keyGenerator;
}
@Override
public RsaCredentialValue generateCredential(GenerationParameters p) {
RsaGenerationParameters params = (RsaGenerationParameters) p;
try {
final KeyPair keyPair = keyGenerator.generateKeyPair(params.getKeyLength());
return new RsaCredentialValue(CertificateFormatter.pemOf(keyPair.getPublic()),
CertificateFormatter.pemOf(keyPair.getPrivate()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
3e0a5bc28adb68a2ad8e1a523c28608bbe21f1b6 | 1,564 | java | Java | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/runtime/properties/IPropertySourceMulti.java | halitanildonmez/dbeaver | f9b42d9cedaff1208f0088635acb5142b599b13e | [
"Apache-2.0"
] | 2 | 2020-10-19T03:34:04.000Z | 2020-10-19T03:34:31.000Z | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/runtime/properties/IPropertySourceMulti.java | halitanildonmez/dbeaver | f9b42d9cedaff1208f0088635acb5142b599b13e | [
"Apache-2.0"
] | 1 | 2020-05-29T09:11:40.000Z | 2020-05-29T09:11:40.000Z | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/runtime/properties/IPropertySourceMulti.java | halitanildonmez/dbeaver | f9b42d9cedaff1208f0088635acb5142b599b13e | [
"Apache-2.0"
] | 2 | 2019-04-18T14:56:22.000Z | 2021-05-18T09:38:43.000Z | 38.146341 | 133 | 0.786445 | 4,380 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2020 DBeaver Corp and others
*
* 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.jkiss.dbeaver.runtime.properties;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.model.preferences.DBPPropertySource;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
/**
* Property source which allows editing of multiple objects.
*/
public interface IPropertySourceMulti extends DBPPropertySource {
boolean isPropertySet(Object object, ObjectPropertyDescriptor id);
Object getPropertyValue(@Nullable DBRProgressMonitor monitor, Object object, ObjectPropertyDescriptor prop, boolean formatValue);
boolean isPropertyResettable(Object object, ObjectPropertyDescriptor prop);
void resetPropertyValue(@Nullable DBRProgressMonitor monitor, Object object, ObjectPropertyDescriptor prop);
void setPropertyValue(@Nullable DBRProgressMonitor monitor, Object object, ObjectPropertyDescriptor prop, Object value)
throws IllegalArgumentException;
}
|
3e0a5caf37e0e0a4b4aafc8a7878bbe2487a98eb | 514 | java | Java | gmall-common/src/main/java/org/sirius/common/to/mq/SeckillOrderTo.java | david606/gmall | 895c9ee6417c3d0e8fc2a6f96f969153514d38f3 | [
"Apache-2.0"
] | null | null | null | gmall-common/src/main/java/org/sirius/common/to/mq/SeckillOrderTo.java | david606/gmall | 895c9ee6417c3d0e8fc2a6f96f969153514d38f3 | [
"Apache-2.0"
] | null | null | null | gmall-common/src/main/java/org/sirius/common/to/mq/SeckillOrderTo.java | david606/gmall | 895c9ee6417c3d0e8fc2a6f96f969153514d38f3 | [
"Apache-2.0"
] | null | null | null | 11.422222 | 36 | 0.519455 | 4,381 | package org.sirius.common.to.mq;
import lombok.Data;
import java.math.BigDecimal;
/**
* 秒杀订单To
*
* @author david
*/
@Data
public class SeckillOrderTo {
/**
* 订单号
*/
private String orderSn;
/**
* 活动场次id
*/
private Long promotionSessionId;
/**
* 商品id
*/
private Long skuId;
/**
* 秒杀价格
*/
private BigDecimal seckillPrice;
/**
* 购买数量
*/
private Integer num;
/**
* 会员ID
*/
private Long memberId;
}
|
3e0a5d8c9a45e43d74ddc9bdb04ce8ddf3293780 | 3,193 | java | Java | java/src/main/java/io/cucumber/java/Invoker.java | kenpritchard/cucumber-jvm | b65240aa1e5a01739a4575d9021897bd0a6c69ac | [
"MIT"
] | 1,799 | 2015-01-02T10:22:05.000Z | 2022-03-31T19:48:49.000Z | java/src/main/java/io/cucumber/java/Invoker.java | kenpritchard/cucumber-jvm | b65240aa1e5a01739a4575d9021897bd0a6c69ac | [
"MIT"
] | 1,781 | 2015-01-01T19:29:08.000Z | 2022-03-30T16:21:04.000Z | java/src/main/java/io/cucumber/java/Invoker.java | kenpritchard/cucumber-jvm | b65240aa1e5a01739a4575d9021897bd0a6c69ac | [
"MIT"
] | 1,682 | 2015-01-03T05:45:54.000Z | 2022-03-25T10:07:05.000Z | 38.011905 | 104 | 0.646727 | 4,382 | package io.cucumber.java;
import io.cucumber.core.backend.CucumberBackendException;
import io.cucumber.core.backend.CucumberInvocationTargetException;
import io.cucumber.core.backend.Located;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
final class Invoker {
private Invoker() {
}
static Object invoke(Annotation annotation, Method expressionMethod) {
return invoke(null, annotation, expressionMethod);
}
static Object invoke(Located located, Object target, Method method, Object... args) {
Method targetMethod = targetMethod(target, method);
return doInvoke(located, target, targetMethod, args);
}
private static Method targetMethod(Object target, Method method) {
Class<?> targetClass = target.getClass();
Class<?> declaringClass = method.getDeclaringClass();
// Immediately return the provided method if the class loaders are the
// same.
if (targetClass.getClassLoader().equals(declaringClass.getClassLoader())) {
return method;
}
try {
// Check if the method is publicly accessible. Note that methods
// from interfaces are always public.
if (Modifier.isPublic(method.getModifiers())) {
return targetClass.getMethod(method.getName(), method.getParameterTypes());
}
// Loop through all the super classes until the declared method is
// found.
Class<?> currentClass = targetClass;
while (currentClass != Object.class) {
try {
return currentClass.getDeclaredMethod(method.getName(), method.getParameterTypes());
} catch (NoSuchMethodException e) {
currentClass = currentClass.getSuperclass();
}
}
// The method does not exist in the class hierarchy.
throw new NoSuchMethodException(String.valueOf(method));
} catch (NoSuchMethodException e) {
throw new CucumberBackendException("Could not find target method", e);
}
}
private static Object doInvoke(Located located, Object target, Method targetMethod, Object[] args) {
boolean accessible = targetMethod.isAccessible();
try {
targetMethod.setAccessible(true);
return targetMethod.invoke(target, args);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new CucumberBackendException("Failed to invoke " + targetMethod, e);
} catch (InvocationTargetException e) {
if (located == null) { // Reflecting into annotations
throw new CucumberBackendException("Failed to invoke " + targetMethod, e);
}
throw new CucumberInvocationTargetException(located, e);
} finally {
targetMethod.setAccessible(accessible);
}
}
static Object invokeStatic(Located located, Method method, Object... args) {
return doInvoke(located, null, method, args);
}
}
|
3e0a5df22505825e3e37671fefa7cc38a0266424 | 555 | java | Java | BankingAPI/src/Handlers.java | thomasvt1/BankAPI | 9285d42dc521f93fe036352fdfdbcc32b64df4b3 | [
"Apache-2.0"
] | null | null | null | BankingAPI/src/Handlers.java | thomasvt1/BankAPI | 9285d42dc521f93fe036352fdfdbcc32b64df4b3 | [
"Apache-2.0"
] | null | null | null | BankingAPI/src/Handlers.java | thomasvt1/BankAPI | 9285d42dc521f93fe036352fdfdbcc32b64df4b3 | [
"Apache-2.0"
] | null | null | null | 25.227273 | 58 | 0.758559 | 4,383 | import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
public class Handlers {
public static class RootHandler implements HttpHandler {
@Override
public void handle(HttpExchange he) throws IOException {
String response = "BANK ONLINE";
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
} |
3e0a5f1c5a7cc5af94f5b144cb20af588c382537 | 1,877 | java | Java | app/src/main/java/com/evrencoskun/tableviewsample/tableview/holder/CellViewHolder.java | MaTriXy/TableView | 02daf0bd7d32e6bd34c8483228d58c20b6ea82eb | [
"MIT"
] | 1 | 2020-12-14T06:25:33.000Z | 2020-12-14T06:25:33.000Z | app/src/main/java/com/evrencoskun/tableviewsample/tableview/holder/CellViewHolder.java | MaTriXy/TableView | 02daf0bd7d32e6bd34c8483228d58c20b6ea82eb | [
"MIT"
] | null | null | null | app/src/main/java/com/evrencoskun/tableviewsample/tableview/holder/CellViewHolder.java | MaTriXy/TableView | 02daf0bd7d32e6bd34c8483228d58c20b6ea82eb | [
"MIT"
] | 1 | 2019-11-26T11:34:47.000Z | 2019-11-26T11:34:47.000Z | 34.127273 | 88 | 0.731486 | 4,384 | /*
* Copyright (c) 2018. Evren Coşkun
*
* 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.evrencoskun.tableviewsample.tableview.holder;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.evrencoskun.tableview.adapter.recyclerview.holder.AbstractViewHolder;
import com.evrencoskun.tableviewsample.R;
import com.evrencoskun.tableviewsample.tableview.model.Cell;
/**
* Created by evrencoskun on 23/10/2017.
*/
public class CellViewHolder extends AbstractViewHolder {
public final TextView cell_textview;
public final LinearLayout cell_container;
private Cell cell;
public CellViewHolder(View itemView) {
super(itemView);
cell_textview = (TextView) itemView.findViewById(R.id.cell_data);
cell_container = (LinearLayout) itemView.findViewById(R.id.cell_container);
}
public void setCell(Cell cell) {
this.cell = cell;
cell_textview.setText(String.valueOf(cell.getData()));
// If your TableView should have auto resize for cells & columns.
// Then you should consider the below lines. Otherwise, you can ignore them.
// It is necessary to remeasure itself.
cell_container.getLayoutParams().width = LinearLayout.LayoutParams.WRAP_CONTENT;
cell_textview.requestLayout();
}
} |
3e0a5f468a093c01a66b73bbb5a1bfbeb37ad471 | 1,840 | java | Java | components/bps-tools/plugins/org.eclipse.bpel.common.model/src/org/eclipse/bpel/common/extension/model/adapters/ExtendedObjectAdapter.java | chanikag/integration-studio | 860542074068146e95960889e281d9dbdeeaeaba | [
"Apache-2.0"
] | 23 | 2020-12-09T09:52:23.000Z | 2022-03-23T03:59:39.000Z | components/bps-tools/plugins/org.eclipse.bpel.common.model/src/org/eclipse/bpel/common/extension/model/adapters/ExtendedObjectAdapter.java | sajithaliyanage/integration-studio | 3329da9fa47e75028edf51f79264b6816bc4e333 | [
"Apache-2.0"
] | 751 | 2020-12-16T12:30:50.000Z | 2022-03-31T07:53:21.000Z | components/bps-tools/plugins/org.eclipse.bpel.common.model/src/org/eclipse/bpel/common/extension/model/adapters/ExtendedObjectAdapter.java | sajithaliyanage/integration-studio | 3329da9fa47e75028edf51f79264b6816bc4e333 | [
"Apache-2.0"
] | 25 | 2020-12-09T09:52:29.000Z | 2022-03-16T06:18:08.000Z | 29.677419 | 81 | 0.677174 | 4,385 | /*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.bpel.common.extension.model.adapters;
import org.eclipse.bpel.common.extension.model.Extension;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.ecore.EObject;
/**
* This adapter provides an easy way to get to an Extension object. It is
* created when an EObject is extended or its Extension is retrieved from the
* ExtensionMap.
* @custom
*/
public interface ExtendedObjectAdapter extends Adapter {
/**
* Returns the compExtension.
* Gets the Extension object extending the adapted EObject.
* @return ComponentExtension
*/
Extension getExtension();
/**
* Returns the extension object.
* @return ComponentExtension
*/
EObject getExtensionObject();
/**
* Sets the compExtension.
* Sets the Extension object extending the adapted EObject.
* @param compExtension The compExtension to set
*/
void setExtension(Extension extension);
/**
* Method getNamespace
* Returns the namesapce of the ExtensionMap that associated this adapter.
* @return String
*/
String getNamespace();
/**
* Method setNamespace.
* Sets the namescpase for this adapter (which should correspond to the
* namespace of the ExtensionMap that associated this adapter).
* @param namespace
*/
void setNamespace(String namespace);
}
|
3e0a5fde894728ffefc3b5c165b8268e7c4fbdb8 | 6,776 | java | Java | src/main/java/it/marteEngine/resource/ResourceManager.java | Gornova/MarteEngine | 89756429c3856e48b3b390de45da2e749d47f761 | [
"MIT"
] | 13 | 2015-01-28T01:23:57.000Z | 2021-07-10T18:40:52.000Z | src/main/java/it/marteEngine/resource/ResourceManager.java | Gornova/MarteEngine | 89756429c3856e48b3b390de45da2e749d47f761 | [
"MIT"
] | 11 | 2015-12-19T15:33:23.000Z | 2018-10-13T09:55:33.000Z | src/main/java/it/marteEngine/resource/ResourceManager.java | Gornova/MarteEngine | 89756429c3856e48b3b390de45da2e749d47f761 | [
"MIT"
] | 8 | 2015-08-30T01:37:38.000Z | 2021-12-31T06:07:52.000Z | 29.982301 | 98 | 0.670307 | 4,386 | package it.marteEngine.resource;
import org.newdawn.slick.*;
import org.newdawn.slick.tiled.TiledMap;
import org.newdawn.slick.util.ResourceLoader;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* Provides convenient access to all game resources. Each of these resources is
* mapped to a key eg "SELECT_SOUND" -> Sound object.
* <p>
* If an attempt is made to overwrite an existing resource an
* IllegalArgumentException is thrown.This is true for all resources except the
* parameters, the parameter values can be overwritten.
*/
public final class ResourceManager {
private static final Map<String, Music> songs = new HashMap<String, Music>();
private static final Map<String, Sound> sounds = new HashMap<String, Sound>();
private static final Map<String, Image> images = new HashMap<String, Image>();
private static final Map<String, SpriteSheet> sheets = new HashMap<String, SpriteSheet>();
private static final Map<String, Animation> animations = new HashMap<String, Animation>();
private static final Map<String, Font> fonts = new HashMap<String, Font>();
private static final Map<String, String> parameters = new HashMap<String, String>();
private static final Map<String, TiledMap> tiledMaps = new HashMap<String, TiledMap>();
/**
* This constructor is intentionally made private. Use the static methods.
*/
private ResourceManager() {
}
/**
* @param ref The path to the resource file
* @throws SlickException If the resources could not be loaded
* @see XMLResourceLoader
*/
public static void loadResources(String ref) throws SlickException {
loadResources(ResourceLoader.getResourceAsStream(ref));
}
/**
* @param in The stream to the resource file
* @throws SlickException If the resources could not be loaded
* @see XMLResourceLoader
*/
public static void loadResources(InputStream in) throws SlickException {
try {
XMLResourceLoader resourceLoader = new XMLResourceLoader();
resourceLoader.load(in);
} catch (IOException e) {
throw new SlickException("Resource loading failed: "
+ e.getMessage());
}
}
public static void addImage(String key, Image image) {
if (hasImage(key)) {
throw new IllegalArgumentException("Image for key " + key
+ " already exist!");
}
images.put(key, image);
}
public static void addSpriteSheet(String key, SpriteSheet sheet) {
if (hasSpriteSheet(key)) {
throw new IllegalArgumentException("SpriteSheet for key " + key
+ " already exist!");
}
sheets.put(key, sheet);
}
public static void addAnimation(String key, Animation anim) {
if (hasAnimation(key)) {
throw new IllegalArgumentException("Animation for key " + key
+ " already exist!");
}
animations.put(key, anim);
}
public static void addFont(String key, Font font) {
if (hasFont(key)) {
throw new IllegalArgumentException("Font for key " + key
+ " already exist!");
}
fonts.put(key, font);
}
public static void addMusic(String key, Music music) {
if (hasMusic(key)) {
throw new IllegalArgumentException("Music for key " + key
+ " already exist!");
}
songs.put(key, music);
}
public static void addSound(String key, Sound sound) {
if (hasSound(key)) {
throw new IllegalArgumentException("Sound for key " + key
+ " already exist!");
}
sounds.put(key, sound);
}
public static void setParameter(String key, String value) {
parameters.put(key, value);
}
public static void addTiledMap(String key, TiledMap map) {
if (hasTiledMap(key)) {
throw new IllegalArgumentException("TiledMap for key " + key
+ " already exist!");
}
tiledMaps.put(key, map);
}
public static boolean hasImage(String key) {
return images.containsKey(key);
}
public static boolean hasSpriteSheet(String key) {
return sheets.containsKey(key);
}
public static boolean hasAnimation(String key) {
return animations.containsKey(key);
}
public static boolean hasFont(String key) {
return fonts.containsKey(key);
}
public static boolean hasMusic(String key) {
return songs.containsKey(key);
}
public static boolean hasSound(String key) {
return sounds.containsKey(key);
}
public static boolean hasParameter(String key) {
return parameters.containsKey(key);
}
public static boolean hasTiledMap(String key) {
return tiledMaps.containsKey(key);
}
public static Image getImage(String key) {
Image image = images.get(key);
if (image == null)
throw new IllegalArgumentException("No image for key " + key + " "
+ images.keySet());
return image;
}
public static SpriteSheet getSpriteSheet(String key) {
SpriteSheet spriteSheet = sheets.get(key);
if (spriteSheet == null)
throw new IllegalArgumentException("No spriteSheet for key " + key
+ " " + sheets.keySet());
return spriteSheet;
}
public static Animation getAnimation(String key) {
Animation anim = animations.get(key);
if (anim == null)
throw new IllegalArgumentException("No Animation for key " + key
+ " " + animations.keySet());
return anim;
}
public static Font getFont(String key) {
Font font = fonts.get(key);
if (font == null)
throw new IllegalArgumentException("No font for key " + key + " "
+ fonts.keySet());
return font;
}
public static Music getMusic(String key) {
Music music = songs.get(key);
if (music == null)
throw new IllegalArgumentException("No music for key " + key + " "
+ songs.keySet());
return music;
}
public static Sound getSound(String key) {
Sound sound = sounds.get(key);
if (sound == null)
throw new IllegalArgumentException("No sound for key " + key + " "
+ sounds.keySet());
return sound;
}
public static int getInt(String key) {
return Integer.parseInt(getParameter(key));
}
public static double getDouble(String key) {
return Double.parseDouble(getParameter(key));
}
public static float getFloat(String key) {
return Float.parseFloat(getParameter(key));
}
public static String getParameter(String key) {
String val = parameters.get(key);
if (val == null)
throw new IllegalArgumentException("No parameter for key " + key
+ " " + parameters.keySet());
return val;
}
public static TiledMap getMap(String key) {
TiledMap map = tiledMaps.get(key);
if (map == null)
throw new IllegalArgumentException("No tiledmap for key " + key + " " + tiledMaps.keySet());
return map;
}
} |
3e0a6056146b5000ad5900ccf285035531508796 | 1,416 | java | Java | hdw-upms-web/src/main/java/com/hdw/upms/shiro/cas/ShiroCasJWTConfig.java | tianxiongfang/hdws | 96f463a1c492515e5df6ff34f6fc8eb3649de12e | [
"Apache-2.0"
] | 4 | 2018-11-20T01:30:58.000Z | 2019-06-20T04:41:06.000Z | hdw-upms-web/src/main/java/com/hdw/upms/shiro/cas/ShiroCasJWTConfig.java | tianxiongfang/hdws | 96f463a1c492515e5df6ff34f6fc8eb3649de12e | [
"Apache-2.0"
] | null | null | null | hdw-upms-web/src/main/java/com/hdw/upms/shiro/cas/ShiroCasJWTConfig.java | tianxiongfang/hdws | 96f463a1c492515e5df6ff34f6fc8eb3649de12e | [
"Apache-2.0"
] | 4 | 2018-11-29T10:43:14.000Z | 2019-08-27T12:38:40.000Z | 29.5 | 113 | 0.747175 | 4,387 | package com.hdw.upms.shiro.cas;
import org.pac4j.jwt.config.encryption.SecretEncryptionConfiguration;
import org.pac4j.jwt.config.signature.SecretSignatureConfiguration;
import org.pac4j.jwt.credentials.authenticator.JwtAuthenticator;
import org.pac4j.jwt.profile.JwtGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author TuMinglong
* @version v1.0.0
* @description CAS JWT配置
* @date 2018年4月25日上午10:15:50
*/
@Configuration
public class ShiroCasJWTConfig {
@Value("${jwt.salt}")
private String salt;
/**
* JWT Token 生成器,对CommonProfile生成然后每次携带token访问
*
* @return
*/
@SuppressWarnings("rawtypes")
@Bean
protected JwtGenerator jwtGenerator() {
return new JwtGenerator(new SecretSignatureConfiguration(salt), new SecretEncryptionConfiguration(salt));
}
/**
* JWT校验器,也就是目前设置的ParameterClient进行的校验器,是rest/或者前后端分离的核心校验器
*
* @return
*/
@Bean
protected JwtAuthenticator jwtAuthenticator() {
JwtAuthenticator jwtAuthenticator = new JwtAuthenticator();
jwtAuthenticator.addSignatureConfiguration(new SecretSignatureConfiguration(salt));
jwtAuthenticator.addEncryptionConfiguration(new SecretEncryptionConfiguration(salt));
return jwtAuthenticator;
}
}
|
3e0a60c691061e8970e8b2080b954f0a5d5fdbbe | 1,356 | java | Java | wordy/logic/compile/structure/ForLoopBlock.java | TypeMonkey/Wordy | f58f3a615c1e1cbc697273524aadb6f625718352 | [
"MIT"
] | null | null | null | wordy/logic/compile/structure/ForLoopBlock.java | TypeMonkey/Wordy | f58f3a615c1e1cbc697273524aadb6f625718352 | [
"MIT"
] | null | null | null | wordy/logic/compile/structure/ForLoopBlock.java | TypeMonkey/Wordy | f58f3a615c1e1cbc697273524aadb6f625718352 | [
"MIT"
] | null | null | null | 22.983051 | 96 | 0.722714 | 4,388 | package wordy.logic.compile.structure;
import java.util.ArrayList;
import java.util.List;
import wordy.logic.compile.nodes.ASTNode;
public class ForLoopBlock extends StatementBlock{
private Statement initialization;
private Statement checkStatement;
private Statement changeStatement;
public ForLoopBlock(Statement init, Statement check, Statement change) {
super(BlockType.FOR);
this.initialization = init;
this.checkStatement = check;
this.changeStatement = change;
}
public ForLoopBlock(Statement init) {
this(init, null, null);
}
public void setInitialization(Statement checkStatement) {
this.checkStatement = checkStatement;
}
public void setCheckStatement(Statement checkStatement) {
this.checkStatement = checkStatement;
}
public void setChangeStatement(Statement changeStatement) {
this.changeStatement = changeStatement;
}
public Statement getInitialization() {
return initialization;
}
public Statement getCheckStatement() {
return checkStatement;
}
public Statement getChangeStatement() {
return changeStatement;
}
public Object execute() {
return null;
}
public String toString() {
String x = "INIT: "+initialization+" | COMP: "+checkStatement+" | CHANGE: "+changeStatement;
x += super.toString();
return x;
}
}
|
3e0a60f3a13a08e2312dcc81937c66c85a52a3a0 | 1,663 | java | Java | icloudmoo-common/src/main/java/com/icloudmoo/common/vo/CodeDesc.java | liyong7686/Icloudmoo | c5d7f76c80689a10cbd2a9155cf9aca818f9b1a9 | [
"Artistic-2.0"
] | 2 | 2016-04-16T13:53:38.000Z | 2019-01-08T10:10:28.000Z | icloudmoo-common/src/main/java/com/icloudmoo/common/vo/CodeDesc.java | liyong7686/Icloudmoo | c5d7f76c80689a10cbd2a9155cf9aca818f9b1a9 | [
"Artistic-2.0"
] | null | null | null | icloudmoo-common/src/main/java/com/icloudmoo/common/vo/CodeDesc.java | liyong7686/Icloudmoo | c5d7f76c80689a10cbd2a9155cf9aca818f9b1a9 | [
"Artistic-2.0"
] | null | null | null | 18.274725 | 91 | 0.611545 | 4,389 | /**
* copywrite 2015-2020 金地物业
* 不能修改和删除上面的版权声明
* 此代码属于数据与信息中心部门编写,在未经允许的情况下不得传播复制
* ValidStatus.java
* @Date 2015年10月15日 下午5:17:46
* guguihe
*/
package com.icloudmoo.common.vo;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* TODO: 数据验证状态
*
* @author guguihe
* @Date 2015年10月15日 下午5:17:46
*/
public class CodeDesc extends ValueObject {
/**
*
*/
private static final long serialVersionUID = -9043254667494875088L;
private int code;
private String desc;
private String name;
private String businessCode;
private Integer userId;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public int getCode() {
return code;
}
public String getBusinessCode() {
return businessCode;
}
public void setBusinessCode(String businessCode) {
this.businessCode = businessCode;
}
public void setCode(int code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public void setValues(int code, String desc) {
this.setCode(code);
this.setDesc(desc);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringBuilder.getDefaultStyle());
}
}
|
3e0a61e754e300ac30926f2754c87ab38b84d43b | 301 | java | Java | modules/analysis/src/main/java/com/haoxuer/adminstore/analysis/list/IntegerList.java | cng1985/adminstore | 2e9b590d7a763c68c74c6528280231cfc85b813e | [
"Apache-2.0"
] | 15 | 2018-03-02T07:38:48.000Z | 2021-06-11T07:15:09.000Z | modules/analysis/src/main/java/com/haoxuer/adminstore/analysis/list/IntegerList.java | cng1985/adminstore | 2e9b590d7a763c68c74c6528280231cfc85b813e | [
"Apache-2.0"
] | null | null | null | modules/analysis/src/main/java/com/haoxuer/adminstore/analysis/list/IntegerList.java | cng1985/adminstore | 2e9b590d7a763c68c74c6528280231cfc85b813e | [
"Apache-2.0"
] | 10 | 2018-03-11T07:43:57.000Z | 2021-05-12T09:57:02.000Z | 20.066667 | 60 | 0.79402 | 4,390 | package com.haoxuer.adminstore.analysis.list;
import com.haoxuer.adminstore.analysis.simple.IntegerName;
import com.haoxuer.discover.rest.base.ResponseList;
import lombok.Data;
@Data
public class IntegerList extends ResponseList<IntegerName> {
private Long total;
private String name;
}
|
3e0a62b63a1d6d49895acaa9cedc409af2ec7f7c | 10,991 | java | Java | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/CleanerTask.java | yellowflash/hadoop | aa9cdf2af6fd84aa24ec5a19da4f955472a8d5bd | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 14,425 | 2015-01-01T15:34:43.000Z | 2022-03-31T15:28:37.000Z | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/CleanerTask.java | yellowflash/hadoop | aa9cdf2af6fd84aa24ec5a19da4f955472a8d5bd | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 3,805 | 2015-03-20T15:58:53.000Z | 2022-03-31T23:58:37.000Z | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/CleanerTask.java | yellowflash/hadoop | aa9cdf2af6fd84aa24ec5a19da4f955472a8d5bd | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 9,521 | 2015-01-01T19:12:52.000Z | 2022-03-31T03:07:51.000Z | 35.454839 | 84 | 0.65499 | 4,391 | /**
* 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.hadoop.yarn.server.sharedcachemanager;
import java.io.IOException;
import java.util.concurrent.locks.Lock;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Evolving;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.server.sharedcache.SharedCacheUtil;
import org.apache.hadoop.yarn.server.sharedcachemanager.metrics.CleanerMetrics;
import org.apache.hadoop.yarn.server.sharedcachemanager.store.SCMStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The task that runs and cleans up the shared cache area for stale entries and
* orphaned files. It is expected that only one cleaner task runs at any given
* point in time.
*/
@Private
@Evolving
class CleanerTask implements Runnable {
private static final String RENAMED_SUFFIX = "-renamed";
private static final Logger LOG =
LoggerFactory.getLogger(CleanerTask.class);
private final String location;
private final long sleepTime;
private final int nestedLevel;
private final Path root;
private final FileSystem fs;
private final SCMStore store;
private final CleanerMetrics metrics;
private final Lock cleanerTaskLock;
/**
* Creates a cleaner task based on the configuration. This is provided for
* convenience.
*
* @param conf
* @param store
* @param metrics
* @param cleanerTaskLock lock that ensures a serial execution of cleaner
* task
* @return an instance of a CleanerTask
*/
public static CleanerTask create(Configuration conf, SCMStore store,
CleanerMetrics metrics, Lock cleanerTaskLock) {
try {
// get the root directory for the shared cache
String location =
conf.get(YarnConfiguration.SHARED_CACHE_ROOT,
YarnConfiguration.DEFAULT_SHARED_CACHE_ROOT);
long sleepTime =
conf.getLong(YarnConfiguration.SCM_CLEANER_RESOURCE_SLEEP_MS,
YarnConfiguration.DEFAULT_SCM_CLEANER_RESOURCE_SLEEP_MS);
int nestedLevel = SharedCacheUtil.getCacheDepth(conf);
FileSystem fs = FileSystem.get(conf);
return new CleanerTask(location, sleepTime, nestedLevel, fs, store,
metrics, cleanerTaskLock);
} catch (IOException e) {
LOG.error("Unable to obtain the filesystem for the cleaner service", e);
throw new ExceptionInInitializerError(e);
}
}
/**
* Creates a cleaner task based on the root directory location and the
* filesystem.
*/
CleanerTask(String location, long sleepTime, int nestedLevel, FileSystem fs,
SCMStore store, CleanerMetrics metrics, Lock cleanerTaskLock) {
this.location = location;
this.sleepTime = sleepTime;
this.nestedLevel = nestedLevel;
this.root = new Path(location);
this.fs = fs;
this.store = store;
this.metrics = metrics;
this.cleanerTaskLock = cleanerTaskLock;
}
@Override
public void run() {
if (!this.cleanerTaskLock.tryLock()) {
// there is already another task running
LOG.warn("A cleaner task is already running. "
+ "This scheduled cleaner task will do nothing.");
return;
}
try {
if (!fs.exists(root)) {
LOG.error("The shared cache root " + location + " was not found. "
+ "The cleaner task will do nothing.");
return;
}
// we're now ready to process the shared cache area
process();
} catch (Throwable e) {
LOG.error("Unexpected exception while initializing the cleaner task. "
+ "This task will do nothing,", e);
} finally {
// this is set to false regardless of if it is a scheduled or on-demand
// task
this.cleanerTaskLock.unlock();
}
}
/**
* Sweeps and processes the shared cache area to clean up stale and orphaned
* files.
*/
void process() {
// mark the beginning of the run in the metrics
metrics.reportCleaningStart();
try {
// now traverse individual directories and process them
// the directory structure is specified by the nested level parameter
// (e.g. 9/c/d/<checksum>)
String pattern = SharedCacheUtil.getCacheEntryGlobPattern(nestedLevel);
FileStatus[] resources =
fs.globStatus(new Path(root, pattern));
int numResources = resources == null ? 0 : resources.length;
LOG.info("Processing " + numResources + " resources in the shared cache");
long beginMs = System.currentTimeMillis();
if (resources != null) {
for (FileStatus resource : resources) {
// check for interruption so it can abort in a timely manner in case
// of shutdown
if (Thread.currentThread().isInterrupted()) {
LOG.warn("The cleaner task was interrupted. Aborting.");
break;
}
if (resource.isDirectory()) {
processSingleResource(resource);
} else {
LOG.warn("Invalid file at path " + resource.getPath().toString()
+
" when a directory was expected");
}
// add sleep time between cleaning each directory if it is non-zero
if (sleepTime > 0) {
Thread.sleep(sleepTime);
}
}
}
long endMs = System.currentTimeMillis();
long durationMs = endMs - beginMs;
LOG.info("Processed " + numResources + " resource(s) in " + durationMs +
" ms.");
} catch (IOException e1) {
LOG.error("Unable to complete the cleaner task", e1);
} catch (InterruptedException e2) {
Thread.currentThread().interrupt(); // restore the interrupt
}
}
/**
* Returns a path for the root directory for the shared cache.
*/
Path getRootPath() {
return root;
}
/**
* Processes a single shared cache resource directory.
*/
void processSingleResource(FileStatus resource) {
Path path = resource.getPath();
// indicates the processing status of the resource
ResourceStatus resourceStatus = ResourceStatus.INIT;
// first, if the path ends with the renamed suffix, it indicates the
// directory was moved (as stale) but somehow not deleted (probably due to
// SCM failure); delete the directory
if (path.toString().endsWith(RENAMED_SUFFIX)) {
LOG.info("Found a renamed directory that was left undeleted at " +
path.toString() + ". Deleting.");
try {
if (fs.delete(path, true)) {
resourceStatus = ResourceStatus.DELETED;
}
} catch (IOException e) {
LOG.error("Error while processing a shared cache resource: " + path, e);
}
} else {
// this is the path to the cache resource directory
// the directory name is the resource key (i.e. a unique identifier)
String key = path.getName();
try {
store.cleanResourceReferences(key);
} catch (YarnException e) {
LOG.error("Exception thrown while removing dead appIds.", e);
}
if (store.isResourceEvictable(key, resource)) {
try {
/*
* TODO See YARN-2663: There is a race condition between
* store.removeResource(key) and
* removeResourceFromCacheFileSystem(path) operations because they do
* not happen atomically and resources can be uploaded with different
* file names by the node managers.
*/
// remove the resource from scm (checks for appIds as well)
if (store.removeResource(key)) {
// remove the resource from the file system
boolean deleted = removeResourceFromCacheFileSystem(path);
if (deleted) {
resourceStatus = ResourceStatus.DELETED;
} else {
LOG.error("Failed to remove path from the file system."
+ " Skipping this resource: " + path);
resourceStatus = ResourceStatus.ERROR;
}
} else {
// we did not delete the resource because it contained application
// ids
resourceStatus = ResourceStatus.PROCESSED;
}
} catch (IOException e) {
LOG.error(
"Failed to remove path from the file system. Skipping this resource: "
+ path, e);
resourceStatus = ResourceStatus.ERROR;
}
} else {
resourceStatus = ResourceStatus.PROCESSED;
}
}
// record the processing
switch (resourceStatus) {
case DELETED:
metrics.reportAFileDelete();
break;
case PROCESSED:
metrics.reportAFileProcess();
break;
case ERROR:
metrics.reportAFileError();
break;
default:
LOG.error("Cleaner encountered an invalid status (" + resourceStatus
+ ") while processing resource: " + path.getName());
}
}
private boolean removeResourceFromCacheFileSystem(Path path)
throws IOException {
// rename the directory to make the delete atomic
Path renamedPath = new Path(path.toString() + RENAMED_SUFFIX);
if (fs.rename(path, renamedPath)) {
// the directory can be removed safely now
// log the original path
LOG.info("Deleting " + path.toString());
return fs.delete(renamedPath, true);
} else {
// we were unable to remove it for some reason: it's best to leave
// it at that
LOG.error("We were not able to rename the directory to "
+ renamedPath.toString() + ". We will leave it intact.");
}
return false;
}
/**
* A status indicating what happened with the processing of a given cache
* resource.
*/
private enum ResourceStatus {
INIT,
/** Resource was successfully processed, but not deleted **/
PROCESSED,
/** Resource was successfully deleted **/
DELETED,
/** The cleaner task ran into an error while processing the resource **/
ERROR
}
}
|
3e0a63db4d3d0c91e2d209e9ea853e8344e8cf01 | 217 | java | Java | spring/spring-flux-demo/src/test/java/com/kuroha/springdemo/SpringDemoApplicationTests.java | kurohayan/dataStructureAndAlgorithm | 57213e0b352232d51320b7262c47c70aa42ca8d5 | [
"Apache-2.0"
] | null | null | null | spring/spring-flux-demo/src/test/java/com/kuroha/springdemo/SpringDemoApplicationTests.java | kurohayan/dataStructureAndAlgorithm | 57213e0b352232d51320b7262c47c70aa42ca8d5 | [
"Apache-2.0"
] | 2 | 2020-08-07T10:24:54.000Z | 2021-12-31T07:37:20.000Z | spring/spring-flux-demo/src/test/java/com/kuroha/springdemo/SpringDemoApplicationTests.java | kurohayan/kuroha-study | 57213e0b352232d51320b7262c47c70aa42ca8d5 | [
"Apache-2.0"
] | null | null | null | 15.5 | 60 | 0.792627 | 4,392 | package com.kuroha.springdemo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringDemoApplicationTests {
@Test
void contextLoads() {
}
}
|
3e0a63e6cb2ed4e05b9088ead11a6da6acf63097 | 4,620 | java | Java | src/main/java/com/snowplowanalytics/snowplow/tracker/http/OkHttpClientAdapter.java | snowplow/snowplow-java-tracker | 117995a1a5b551abcdbed015425282b30f4c79ea | [
"Apache-2.0"
] | 18 | 2015-03-20T13:17:00.000Z | 2022-03-29T16:48:06.000Z | src/main/java/com/snowplowanalytics/snowplow/tracker/http/OkHttpClientAdapter.java | snowplow/snowplow-java-tracker | 117995a1a5b551abcdbed015425282b30f4c79ea | [
"Apache-2.0"
] | 202 | 2015-01-02T09:42:58.000Z | 2022-03-25T09:51:48.000Z | src/main/java/com/snowplowanalytics/snowplow/tracker/http/OkHttpClientAdapter.java | snowplow/snowplow-java-tracker | 117995a1a5b551abcdbed015425282b30f4c79ea | [
"Apache-2.0"
] | 28 | 2015-02-03T19:38:02.000Z | 2022-02-04T19:57:18.000Z | 31.216216 | 114 | 0.642424 | 4,393 | /*
* Copyright (c) 2014-2021 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker.http;
// Java
import java.io.IOException;
// Google
import com.google.common.base.Preconditions;
// SquareUp
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.RequestBody;
// Slf4j
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// This library
import com.snowplowanalytics.snowplow.tracker.constants.Constants;
/**
* A HttpClient built using OkHttp to send events via
* GET or POST requests.
*/
public class OkHttpClientAdapter extends AbstractHttpClientAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpClientAdapter.class);
private final MediaType JSON = MediaType.get(Constants.POST_CONTENT_TYPE);
private OkHttpClient httpClient;
public static abstract class Builder<T extends Builder<T>> extends AbstractHttpClientAdapter.Builder<T> {
private OkHttpClient httpClient; // Required
/**
* @param httpClient The Apache HTTP Client to use
* @return itself
*/
public T httpClient(OkHttpClient httpClient) {
this.httpClient = httpClient;
return self();
}
public OkHttpClientAdapter build() {
return new OkHttpClientAdapter(this);
}
}
private static class Builder2 extends Builder<Builder2> {
@Override
protected Builder2 self() {
return this;
}
}
public static Builder<?> builder() {
return new Builder2();
}
protected OkHttpClientAdapter(Builder<?> builder) {
super(builder);
// Precondition checks
Preconditions.checkNotNull(builder.httpClient);
this.httpClient = builder.httpClient;
}
/**
* Returns the HttpClient in use; it is up to the developer
* to cast it back to its original class.
*
* @return the http client
*/
public Object getHttpClient() {
return this.httpClient;
}
/**
* Attempts to send a group of payloads with a
* GET request to the configured endpoint.
*
* @param url the URL send
* @return the HttpResponse code for the Request or -1 if exception is caught
*/
public int doGet(String url) {
int returnValue = -1;
Request request = new Request.Builder().url(url).build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
LOGGER.error("OkHttpClient GET Request failed: {}", response);
} else {
returnValue = response.code();
}
} catch (IOException e) {
LOGGER.error("OkHttpClient GET Request failed: {}", e.getMessage());
}
return returnValue;
}
/**
* Attempts to send a group of payloads with a
* POST request to the configured endpoint.
*
* @param url the URL to send to
* @param payload the payload to send
* @return the HttpResponse code for the Request or -1 if exception is caught
*/
public int doPost(String url, String payload) {
int returnValue = -1;
RequestBody body = RequestBody.create(payload, JSON);
Request request = new Request.Builder()
.url(url)
.addHeader("Content-Type", Constants.POST_CONTENT_TYPE)
.post(body)
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
LOGGER.error("OkHttpClient POST Request failed: {}", response);
} else {
returnValue = response.code();
}
} catch (IOException e) {
LOGGER.error("OkHttpClient POST Request failed: {}", e.getMessage());
}
return returnValue;
}
} |
3e0a64271a6c701e37edeb5135df3a382878b1f6 | 881 | java | Java | src/test/java/com/basaki/example/config/SwaggerConfigurationTest.java | indrabasak/spring-functional-example | bf419cd0266c240cbef35503be52f741807024dd | [
"Apache-2.0"
] | null | null | null | src/test/java/com/basaki/example/config/SwaggerConfigurationTest.java | indrabasak/spring-functional-example | bf419cd0266c240cbef35503be52f741807024dd | [
"Apache-2.0"
] | null | null | null | src/test/java/com/basaki/example/config/SwaggerConfigurationTest.java | indrabasak/spring-functional-example | bf419cd0266c240cbef35503be52f741807024dd | [
"Apache-2.0"
] | null | null | null | 23.810811 | 62 | 0.708286 | 4,394 | package com.basaki.example.config;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.context.ActiveProfiles;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import static org.junit.Assert.assertEquals;
/**
* {@code SwaggerConfigurationTest} unit test class for {@link
* SwaggerConfiguration}.
* <p/>
*
* @author Indra Basak
* @since 6/3/17
*/
@ActiveProfiles("test")
public class SwaggerConfigurationTest {
private SwaggerConfiguration config;
@Before
public void startUp() {
config = new SwaggerConfiguration();
}
@Test
public void testApi() {
Docket docket = config.api();
assertEquals("book", docket.getGroupName());
assertEquals(DocumentationType.SWAGGER_2,
docket.getDocumentationType());
}
}
|
3e0a642c1415b6b16fc587875aa3003a6aec0d6c | 9,366 | java | Java | WEB-INF/src/com/krishagni/catissueplus/core/administrative/repository/impl/DistributionOrderDaoImpl.java | marwahan/test-os | 8673696fa13c848c8dfe118d30ff0475f1e8bf77 | [
"BSD-3-Clause"
] | null | null | null | WEB-INF/src/com/krishagni/catissueplus/core/administrative/repository/impl/DistributionOrderDaoImpl.java | marwahan/test-os | 8673696fa13c848c8dfe118d30ff0475f1e8bf77 | [
"BSD-3-Clause"
] | null | null | null | WEB-INF/src/com/krishagni/catissueplus/core/administrative/repository/impl/DistributionOrderDaoImpl.java | marwahan/test-os | 8673696fa13c848c8dfe118d30ff0475f1e8bf77 | [
"BSD-3-Clause"
] | null | null | null | 35.748092 | 111 | 0.748238 | 4,395 | package com.krishagni.catissueplus.core.administrative.repository.impl;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import com.krishagni.catissueplus.core.administrative.domain.DistributionOrder;
import com.krishagni.catissueplus.core.administrative.domain.DistributionOrderItem;
import com.krishagni.catissueplus.core.administrative.events.DistributionOrderListCriteria;
import com.krishagni.catissueplus.core.administrative.events.DistributionOrderSummary;
import com.krishagni.catissueplus.core.administrative.events.DistributionProtocolDetail;
import com.krishagni.catissueplus.core.administrative.repository.DistributionOrderDao;
import com.krishagni.catissueplus.core.common.events.UserSummary;
import com.krishagni.catissueplus.core.common.repository.AbstractDao;
public class DistributionOrderDaoImpl extends AbstractDao<DistributionOrder> implements DistributionOrderDao {
@SuppressWarnings("unchecked")
@Override
public List<DistributionOrderSummary> getOrders(DistributionOrderListCriteria listCrit) {
List<Object[]> rows = getOrderList(listCrit);
List<DistributionOrderSummary> result = new ArrayList<DistributionOrderSummary>();
Map<Long, DistributionOrderSummary> doMap = new HashMap<Long, DistributionOrderSummary>();
for (Object[] row : rows) {
DistributionOrderSummary order = getDoSummary(row);
result.add(order);
if (listCrit.includeStat()) {
doMap.put(order.getId(), order);
}
}
if (listCrit.includeStat() && !doMap.isEmpty()) {
rows = getSessionFactory().getCurrentSession()
.getNamedQuery(GET_SPEC_CNT_BY_ORDER)
.setParameterList("orderIds", doMap.keySet())
.list();
for (Object[] row : rows) {
DistributionOrderSummary order = doMap.get((Long)row[0]);
order.setSpecimenCnt((Long)row[1]);
}
}
return result;
}
@Override
@SuppressWarnings("unchecked")
public DistributionOrder getOrder(String name) {
List<DistributionOrder> result = getOrders(Collections.singletonList(name));
return result.isEmpty() ? null : result.iterator().next();
}
@Override
public List<DistributionOrder> getOrders(List<String> names) {
return getSessionFactory().getCurrentSession()
.getNamedQuery(GET_ORDERS_BY_NAME)
.setParameterList("names", names)
.list();
}
@Override
public List<DistributionOrderItem> getDistributedOrderItems(List<String> specimenLabels) {
return getSessionFactory().getCurrentSession()
.getNamedQuery(GET_DISTRIBUTED_ITEMS_BY_LABELS)
.setParameterList("labels", specimenLabels)
.list();
}
@Override
public Class<DistributionOrder> getType() {
return DistributionOrder.class;
}
@Override
public Map<String, Object> getOrderIds(String key, Object value) {
return getObjectIds("orderId", key, value);
}
@SuppressWarnings("unchecked")
private List<Object[]> getOrderList(DistributionOrderListCriteria crit) {
Criteria query = sessionFactory.getCurrentSession()
.createCriteria(DistributionOrder.class)
.createAlias("distributionProtocol", "dp")
.createAlias("requester", "user")
.createAlias("site", "site", JoinType.LEFT_OUTER_JOIN)
.setFirstResult(crit.startAt() < 0 ? 0 : crit.startAt())
.setMaxResults(crit.maxResults() < 0 || crit.maxResults() > 100 ? 100 : crit.maxResults())
.addOrder(Order.desc("id"));
//
// Restrict by distributing sites
//
if (CollectionUtils.isNotEmpty(crit.siteIds())) {
query.createAlias("dp.distributingSites", "distSites")
.createAlias("distSites.site", "distSite", JoinType.LEFT_OUTER_JOIN)
.createAlias("distSites.institute", "distInst")
.createAlias("distInst.sites", "instSite")
.add(Restrictions.or(
Restrictions.and(Restrictions.isNull("distSites.site"), Restrictions.in("instSite.id", crit.siteIds())),
Restrictions.and(Restrictions.isNotNull("distSites.site"),Restrictions.in("distSite.id", crit.siteIds()))
));
}
//
// Add search restrictions
//
MatchMode matchMode = crit.exactMatch() ? MatchMode.EXACT : MatchMode.ANYWHERE;
addNameRestriction(query, crit, matchMode);
addDpRestriction(query, crit, matchMode);
addRequestorRestriction(query, crit, matchMode);
addExecutionDtRestriction(query, crit);
addReceivingSiteRestriction(query, crit, matchMode);
addReceivingInstRestriction(query, crit, matchMode);
addProjections(query, CollectionUtils.isNotEmpty(crit.siteIds()));
return query.list();
}
private void addNameRestriction(Criteria query, DistributionOrderListCriteria crit, MatchMode mode) {
if (StringUtils.isBlank(crit.query())) {
return;
}
query.add(Restrictions.ilike("name", crit.query(), mode));
}
private void addDpRestriction(Criteria query, DistributionOrderListCriteria crit, MatchMode mode) {
if (crit.dpId() != null) {
query.add(Restrictions.eq("dp.id", crit.dpId()));
} else if (StringUtils.isNotBlank(crit.dpShortTitle())) {
query.add(Restrictions.ilike("dp.shortTitle", crit.dpShortTitle(), mode));
}
}
private void addRequestorRestriction(Criteria query, DistributionOrderListCriteria crit, MatchMode mode) {
if (crit.requestorId() != null) {
query.add(Restrictions.eq("user.id", crit.requestorId()));
} else if (StringUtils.isNotBlank(crit.requestor())) {
query.add(
Restrictions.disjunction()
.add(Restrictions.ilike("user.firstName", crit.requestor(), mode))
.add(Restrictions.ilike("user.lastName", crit.requestor(), mode))
);
}
}
private void addExecutionDtRestriction(Criteria query, DistributionOrderListCriteria crit) {
if (crit.executionDate() == null) {
return;
}
Calendar from = Calendar.getInstance();
from.setTime(crit.executionDate());
from.set(Calendar.HOUR_OF_DAY, 0);
from.set(Calendar.MINUTE, 0);
from.set(Calendar.SECOND, 0);
from.set(Calendar.MILLISECOND, 0);
Calendar to = Calendar.getInstance();
to.setTime(crit.executionDate());
to.set(Calendar.HOUR_OF_DAY, 23);
to.set(Calendar.MINUTE, 59);
to.set(Calendar.SECOND, 59);
to.set(Calendar.MILLISECOND, 999);
query.add(Restrictions.between("executionDate", from.getTime(), to.getTime()));
}
private void addReceivingSiteRestriction(Criteria query, DistributionOrderListCriteria crit, MatchMode mode) {
if (StringUtils.isBlank(crit.receivingSite())) {
return;
}
query.add(Restrictions.ilike("site.name", crit.receivingSite(), mode));
}
private void addReceivingInstRestriction(Criteria query, DistributionOrderListCriteria crit, MatchMode mode) {
if (StringUtils.isBlank(crit.receivingInstitute())) {
return;
}
query.createAlias("site.institute", "institute")
.add(Restrictions.ilike("institute.name", crit.receivingInstitute(), mode));
}
private void addProjections(Criteria query, boolean isDistinct) {
ProjectionList projs = Projections.projectionList();
if (isDistinct) {
//added as duplicate entries come due to distributing site lists
query.setProjection(Projections.distinct(projs));
} else {
query.setProjection(projs);
}
projs.add(Projections.property("id"));
projs.add(Projections.property("name"));
projs.add(Projections.property("creationDate"));
projs.add(Projections.property("executionDate"));
projs.add(Projections.property("status"));
projs.add(Projections.property("dp.id"));
projs.add(Projections.property("dp.shortTitle"));
projs.add(Projections.property("site.id"));
projs.add(Projections.property("site.name"));
projs.add(Projections.property("user.id"));
projs.add(Projections.property("user.firstName"));
projs.add(Projections.property("user.lastName"));
projs.add(Projections.property("user.emailAddress"));
}
private DistributionOrderSummary getDoSummary(Object[] row) {
DistributionOrderSummary result = new DistributionOrderSummary();
result.setId((Long)row[0]);
result.setName((String)row[1]);
result.setCreationDate((Date)row[2]);
result.setExecutionDate((Date)row[3]);
result.setStatus(((DistributionOrder.Status)row[4]).name());
DistributionProtocolDetail dp = new DistributionProtocolDetail();
dp.setId((Long)row[5]);
dp.setShortTitle((String)row[6]);
result.setDistributionProtocol(dp);
result.setSiteId((Long)row[7]);
result.setSiteName((String)row[8]);
UserSummary requester = new UserSummary();
requester.setId((Long)row[9]);
requester.setFirstName((String)row[10]);
requester.setLastName((String)row[11]);
requester.setEmailAddress((String)row[12]);
result.setRequester(requester);
return result;
}
public static final String FQN = DistributionOrder.class.getName();
private static final String GET_ORDERS_BY_NAME = FQN + ".getOrdersByName";
private static final String GET_DISTRIBUTED_ITEMS_BY_LABELS = FQN + ".getDistributedItemsByLabels";
private static final String GET_SPEC_CNT_BY_ORDER = FQN + ".getSpecimenCountByOrder";
}
|
3e0a653a3449459538d14e3583e6d8eba9d26efa | 2,906 | java | Java | 1-evosuite-fuzzer/client/src/main/java/org/evosuite/symbolic/solver/SolverResult.java | mitchellolsthoorn/ASE-NIER-2020-Replication | d921c324d95346b2d962d913c21b993fa5a51d18 | [
"MIT"
] | null | null | null | 1-evosuite-fuzzer/client/src/main/java/org/evosuite/symbolic/solver/SolverResult.java | mitchellolsthoorn/ASE-NIER-2020-Replication | d921c324d95346b2d962d913c21b993fa5a51d18 | [
"MIT"
] | 3 | 2020-11-16T20:45:46.000Z | 2021-03-23T00:28:18.000Z | 1-evosuite-fuzzer/client/src/main/java/org/evosuite/symbolic/solver/SolverResult.java | mitchellolsthoorn/ASE-NIER-2020-Replication | d921c324d95346b2d962d913c21b993fa5a51d18 | [
"MIT"
] | null | null | null | 27.942308 | 93 | 0.71989 | 4,396 | /**
* Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.symbolic.solver;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class SolverResult implements Serializable {
/**
*
*/
private static final long serialVersionUID = -930589471876011035L;
private enum SolverResultType {
SAT, UNSAT, UNKNOWN
};
private final SolverResultType resultType;
private final Map<String, Object> model;
private SolverResult(SolverResultType t, Map<String, Object> model) {
this.resultType = t;
this.model = model;
}
public static SolverResult newUNSAT() {
return new SolverResult(SolverResultType.UNSAT, null);
}
public static SolverResult newUnknown() {
return new SolverResult(SolverResultType.UNKNOWN, null);
}
public static SolverResult newSAT(Map<String, Object> values) {
return new SolverResult(SolverResultType.SAT, values);
}
public boolean isSAT() {
return resultType.equals(SolverResultType.SAT);
}
public boolean containsVariable(String var_name) {
if (!resultType.equals(SolverResultType.SAT)) {
throw new IllegalStateException("This method should not be called with a non-SAT result");
}
return model.containsKey(var_name);
}
public Object getValue(String var_name) {
if (!resultType.equals(SolverResultType.SAT)) {
throw new IllegalStateException("This method should not be called with a non-SAT result");
}
return model.get(var_name);
}
public Map<String, Object> getModel() {
HashMap<String, Object> newModel = model == null ? new HashMap<>() : new HashMap<>(model);
return newModel;
}
public boolean isUNSAT() {
return resultType.equals(SolverResultType.UNSAT);
}
public String toString() {
StringBuffer buff = new StringBuffer();
buff.append(resultType + "\n");
if (resultType.equals(SolverResultType.SAT)) {
buff.append("--------------------" + "\n");
for (String varName : this.model.keySet()) {
Object value = this.model.get(varName);
buff.append(varName + "->" + value + "\n");
}
}
return buff.toString();
}
public boolean isUnknown() {
return resultType.equals(SolverResultType.UNKNOWN);
}
}
|
3e0a664154355480d1d310d665ac479a0d4e7645 | 1,470 | java | Java | Others/TouchEvent Demo/src/main/java/com/example/len/toucheventexample/activity/MainActivity.java | KoizumiSinya/DemoProject | 01aae447bdc02b38b73b2af085e3e28e662764be | [
"Apache-2.0"
] | null | null | null | Others/TouchEvent Demo/src/main/java/com/example/len/toucheventexample/activity/MainActivity.java | KoizumiSinya/DemoProject | 01aae447bdc02b38b73b2af085e3e28e662764be | [
"Apache-2.0"
] | null | null | null | Others/TouchEvent Demo/src/main/java/com/example/len/toucheventexample/activity/MainActivity.java | KoizumiSinya/DemoProject | 01aae447bdc02b38b73b2af085e3e28e662764be | [
"Apache-2.0"
] | null | null | null | 30 | 85 | 0.669388 | 4,397 | package com.example.len.toucheventexample.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.example.len.toucheventexample.R;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt_normal_view = (Button) findViewById(R.id.bt_normal_view);
bt_normal_view.setOnClickListener(this);
Button bt_button = (Button) findViewById(R.id.bt_button);
bt_button.setOnClickListener(this);
Button bt_scroll_View = (Button) findViewById(R.id.bt_scroll_View);
bt_scroll_View.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_normal_view:
startActivity(TestNormalViewActivity.class);
break;
case R.id.bt_button:
startActivity(TestButtonActivity.class);
break;
case R.id.bt_scroll_View:
startActivity(TestScrollViewActivity.class);
break;
}
}
void startActivity(Class<?> cls){
Intent intent = new Intent(MainActivity.this, cls);
startActivity(intent);
}
}
|
3e0a6685db36db03cbc2ab70b08a725a22c3f85f | 6,296 | java | Java | app/src/main/java/com/shhatrat/bikerun2/presenter/activity/MenuActivityPresenter.java | Shhatrat/BikeRun2 | d384a8266e9783f723491cf67174f4fbb01b3ef9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/shhatrat/bikerun2/presenter/activity/MenuActivityPresenter.java | Shhatrat/BikeRun2 | d384a8266e9783f723491cf67174f4fbb01b3ef9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/shhatrat/bikerun2/presenter/activity/MenuActivityPresenter.java | Shhatrat/BikeRun2 | d384a8266e9783f723491cf67174f4fbb01b3ef9 | [
"Apache-2.0"
] | null | null | null | 41.973333 | 211 | 0.71601 | 4,398 | package com.shhatrat.bikerun2.presenter.activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.shhatrat.bikerun2.R;
import com.shhatrat.bikerun2.di.NetImpl;
import com.shhatrat.bikerun2.di.UtilImpl;
import com.shhatrat.bikerun2.model.AthleteDataToStats;
import com.shhatrat.bikerun2.model.StaticFields;
import com.shhatrat.bikerun2.presenter.activity.models.IMenuActivityPresenter;
import com.shhatrat.bikerun2.presenter.activity.models.IStravaStatsPresenter;
import com.shhatrat.bikerun2.view.activity.BaseActivity;
import com.shhatrat.bikerun2.view.activity.StravaStatsActivity;
import com.shhatrat.bikerun2.view.activity.models.IMenuActivityView;
import com.sweetzpot.stravazpot.athlete.model.Athlete;
import com.sweetzpot.stravazpot.athlete.model.Stats;
import com.sweetzpot.stravazpot.authenticaton.api.AccessScope;
import com.sweetzpot.stravazpot.authenticaton.api.ApprovalPrompt;
import com.sweetzpot.stravazpot.authenticaton.api.StravaLogin;
import com.sweetzpot.stravazpot.authenticaton.model.LoginResult;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;
import org.parceler.Parcels;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observable;
/**
* Created by szymon on 4/3/17.
*/
public class MenuActivityPresenter implements IMenuActivityPresenter {
private BaseActivity baseActivity;
private IMenuActivityView menuActivityView;
private UtilImpl util;
private NetImpl net;
private String error;
public MenuActivityPresenter(BaseActivity baseActivity, IMenuActivityView menuActivityView, UtilImpl util, NetImpl net) {
this.menuActivityView = menuActivityView;
this.net = net;
this.util = util;
this.baseActivity = baseActivity;
this.error = baseActivity.getString(R.string.LOG_ERROR);
}
@Override
public void refreshImages() {
if(util.getAppSettings().getAccountSaved())
{
menuActivityView.setLoggedIcon(util.getAppSettings().getName());
downloadAthlete();
}
else
menuActivityView.setOfflineIcon();
}
private void downloadAthlete() {
Observable<Athlete> athleteSingle = net.getCurrentAthlete();
athleteSingle
.compose(RxLifecycleAndroid.bindActivity(baseActivity.lifecycle()))
.subscribe(this::downloadStatsAndsaveAthlete, e-> Log.d(error, e.getMessage()));
}
private void downloadStatsAndsaveAthlete(Athlete athlete)
{
StaticFields.athlete = athlete;
net.getAthleteStats(athlete.getID())
.compose(RxLifecycleAndroid.bindActivity(baseActivity.lifecycle()))
.subscribe(e -> StaticFields.stats = e, e-> Log.d(error, e.getMessage()));
}
@Override
public void loginResultCode(String code) {
Observable<LoginResult> resultLogin = net.getResultLogin(code);
resultLogin
.compose(RxLifecycleAndroid.bindActivity(baseActivity.lifecycle()))
.subscribe(this::setUp, e -> menuActivityView.showErrorSnacky(e));
}
private void setUp(LoginResult loginResult){
util.getAppSettings().setToken(loginResult.getToken().toString());
util.getAppSettings().setAccountSaved(true);
util.getAppSettings().setName(loginResult.getAthlete().getFirstName());
util.getAppSettings().setUserId(loginResult.getAthlete().getID());
StaticFields.athlete = loginResult.getAthlete();
refreshImages();
}
@Override
public void logUser() {
Intent intent = StravaLogin.withContext(baseActivity)
.withClientID(baseActivity.getResources().getInteger(R.integer.strava_key))
.withRedirectURI(baseActivity.getString(R.string.strava_redirect_page))
.withApprovalPrompt(ApprovalPrompt.AUTO)
.withAccessScope(AccessScope.VIEW_PRIVATE_WRITE)
.makeIntent();
baseActivity.startActivityForResult(intent, baseActivity.getResources().getInteger(R.integer.strava_request_login));
}
@Override
public void isStravaReady() {
if(StaticFields.stats!=null){
List<AthleteDataToStats.AthleteData> data = prepareList(StaticFields.stats, StaticFields.athlete);
startStatsActivity(data);
}
else
{
menuActivityView.showInfoSnacky(baseActivity.getString(R.string.downloading__));
downloadAllDataForUserRequest();
}
}
private void startStatsActivity(List<AthleteDataToStats.AthleteData> data)
{
AthleteDataToStats athleteDataToStats = new AthleteDataToStats();
athleteDataToStats.setListdata(data);
Bundle bundle = new Bundle();
bundle.putParcelable(IStravaStatsPresenter.PARCEL_LIST, Parcels.wrap(athleteDataToStats));
Intent i = new Intent(baseActivity, StravaStatsActivity.class);
i.putExtras(bundle);
baseActivity.startActivity(i);
}
private void downloadAllDataForUserRequest()
{
Observable<Athlete> singleAthlete = net.getCurrentAthlete()
.compose(RxLifecycleAndroid.bindActivity(baseActivity.lifecycle()));
net.getAthleteStats(util.getAppSettings().getUserId())
.zipWith(singleAthlete, this::prepareList)
.subscribe(this::startStatsActivity, e -> menuActivityView.showErrorSnacky(e));
}
private List<AthleteDataToStats.AthleteData> prepareList(Stats s, Athlete a)
{
//// TODO: 16.04.17 Fix this list
List<AthleteDataToStats.AthleteData> list = new ArrayList<>();
list.add(new AthleteDataToStats.AthleteData(baseActivity.getString(R.string.user), a.getFirstName()+ " " + a.getLastName()));
list.add(new AthleteDataToStats.AthleteData(baseActivity.getString(R.string.friends_count), a.getFriendCount()+""));
list.add(new AthleteDataToStats.AthleteData(baseActivity.getString(R.string.followers_count), a.getFollowerCount()+""));
list.add(new AthleteDataToStats.AthleteData(baseActivity.getString(R.string.rides), s.getAllRideTotals().getCount()+ baseActivity.getString(R.string.rides__distance)+s.getAllRideTotals().getDistance()));
return list;
}
} |
3e0a668f533a4b5323eca5e766a81a227e7f5246 | 2,133 | java | Java | src/main/java/scc/io/OutputMappingsFormat.java | ernestojimenezruiz/logmap-conservativity | e9ced7048c14a373154d4dcca6a1ed3974cbbd73 | [
"Apache-2.0"
] | null | null | null | src/main/java/scc/io/OutputMappingsFormat.java | ernestojimenezruiz/logmap-conservativity | e9ced7048c14a373154d4dcca6a1ed3974cbbd73 | [
"Apache-2.0"
] | null | null | null | src/main/java/scc/io/OutputMappingsFormat.java | ernestojimenezruiz/logmap-conservativity | e9ced7048c14a373154d4dcca6a1ed3974cbbd73 | [
"Apache-2.0"
] | null | null | null | 41.019231 | 132 | 0.701828 | 4,399 | /*******************************************************************************
* Copyright 2016 by the Department of Computer Science (University of Genova and University of Oxford)
*
* This file is part of LogMapC an extension of LogMap matcher for conservativity principle.
*
* LogMapC is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LogMapC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LogMapC. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package scc.io;
public abstract class OutputMappingsFormat {
protected String output_file;
protected OutputMappingsFormat(String output_file_str){
output_file=output_file_str;
}
protected abstract void setOutput() throws Exception;
protected abstract void addClassMapping2Output(String iri_str1, String iri_str2, int dir_mapping, double conf) throws Exception;
protected abstract void addDataPropMapping2Output(String iri_str1, String iri_str2, int dir_mapping, double conf) throws Exception;
protected abstract void addObjPropMapping2Output(String iri_str1, String iri_str2, int dir_mapping, double conf) throws Exception;
protected abstract void addInstanceMapping2Output(String iri_str1, String iri_str2, double conf) throws Exception;
protected abstract void saveOutputFile() throws Exception;
/**
* Rounded and shifted to [0-1] interval
* @param conf
* @return
*/
protected double getRoundConfidence(double conf){
//return (double)Math.round(conf*10.0)/1000.0;
return (double)Math.round(conf*100.0)/100.0; //two decimals
}
} |
3e0a66fa43278ae53d8d39826db7bb4b2c3587b8 | 335 | java | Java | SpringCloud/chapter20/ms-zuul/src/main/java/com/spring/cloud/ms/zuul/dao/UserDao.java | idealcountry/practice | 5215a220166a51e5f22f63bc6765c5de031660e6 | [
"Apache-2.0"
] | null | null | null | SpringCloud/chapter20/ms-zuul/src/main/java/com/spring/cloud/ms/zuul/dao/UserDao.java | idealcountry/practice | 5215a220166a51e5f22f63bc6765c5de031660e6 | [
"Apache-2.0"
] | null | null | null | SpringCloud/chapter20/ms-zuul/src/main/java/com/spring/cloud/ms/zuul/dao/UserDao.java | idealcountry/practice | 5215a220166a51e5f22f63bc6765c5de031660e6 | [
"Apache-2.0"
] | null | null | null | 23.928571 | 72 | 0.767164 | 4,400 | package com.spring.cloud.ms.zuul.dao;
import com.spring.cloud.ms.zuul.pojo.UserPo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserDao {
public UserPo getUser(@Param("id") Long id);
public UserPo getUserByUserName(@Param("userName") String userName);
}
|
3e0a6737d63fbea3cab4d32d3756510964a4579c | 194 | java | Java | implementation/customer/java/customer-management-ms/src/main/java/com/trivadis/ms/sample/person/model/EmailAddressDO.java | TrivadisPF/data-mesh-demo | 4c1a22f8f1f4b876666c9ba5b7a06e13f186617a | [
"Apache-2.0"
] | 1 | 2022-02-10T08:05:56.000Z | 2022-02-10T08:05:56.000Z | implementation/customer/java/customer-management-ms/src/main/java/com/trivadis/ms/sample/person/model/EmailAddressDO.java | TrivadisPF/data-mesh-demo | 4c1a22f8f1f4b876666c9ba5b7a06e13f186617a | [
"Apache-2.0"
] | null | null | null | implementation/customer/java/customer-management-ms/src/main/java/com/trivadis/ms/sample/person/model/EmailAddressDO.java | TrivadisPF/data-mesh-demo | 4c1a22f8f1f4b876666c9ba5b7a06e13f186617a | [
"Apache-2.0"
] | 8 | 2022-02-10T09:30:12.000Z | 2022-02-10T16:28:46.000Z | 14.923077 | 44 | 0.762887 | 4,401 | package com.trivadis.ms.sample.person.model;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class EmailAddressDO {
private Long id;
private String emailAddress;
}
|
3e0a689d340281eebdad14c445f098fcfabec928 | 2,174 | java | Java | Resources/Code/Eclipse-SW360antenna/antenna/modules/p2/p2-product/bundles/antenna-p2-repository-manager/src/main/java/org/eclipse/sw360/antenna/p2/P2Artifact.java | briancabbott/xtrax | 3bfcbe1c2f5c355b886d8171481a604cca7f4f16 | [
"MIT"
] | 2 | 2020-02-07T17:32:14.000Z | 2022-02-08T09:14:01.000Z | Resources/Code/Eclipse-SW360antenna/antenna/modules/p2/p2-product/bundles/antenna-p2-repository-manager/src/main/java/org/eclipse/sw360/antenna/p2/P2Artifact.java | briancabbott/xtrax | 3bfcbe1c2f5c355b886d8171481a604cca7f4f16 | [
"MIT"
] | null | null | null | Resources/Code/Eclipse-SW360antenna/antenna/modules/p2/p2-product/bundles/antenna-p2-repository-manager/src/main/java/org/eclipse/sw360/antenna/p2/P2Artifact.java | briancabbott/xtrax | 3bfcbe1c2f5c355b886d8171481a604cca7f4f16 | [
"MIT"
] | null | null | null | 26.839506 | 81 | 0.654554 | 4,402 | /*
* Copyright (c) Bosch Software Innovations GmbH 2019.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v20.html
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.sw360.antenna.p2;
import org.eclipse.equinox.p2.metadata.Version;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Optional;
public class P2Artifact {
private final String bundleCoordinates;
private final Version version;
private Optional<Path> jarPath = Optional.empty();
private Optional<Path> sourcePath = Optional.empty();
public P2Artifact(String bundleCoordinates, Version version) {
this.bundleCoordinates = bundleCoordinates;
this.version = version;
}
public String getBundleSymbolicName() {
return bundleCoordinates;
}
public Version getVersion() {
return version;
}
public Optional<Path> getJarPath() {
return jarPath;
}
public void setJarPath(Path jarPath) {
this.jarPath = Optional.of(jarPath);
}
public Optional<Path> getSourcePath() {
return sourcePath;
}
public void setSourcePath(Path sourcePath) {
this.sourcePath = Optional.of(sourcePath);
}
@Override
public String toString() {
return bundleCoordinates + "," + version.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
P2Artifact p2Artifact = (P2Artifact) o;
return Objects.equals(bundleCoordinates, p2Artifact.bundleCoordinates) &&
Objects.equals(version, p2Artifact.version) &&
Objects.equals(jarPath, p2Artifact.jarPath) &&
Objects.equals(sourcePath, p2Artifact.sourcePath);
}
@Override
public int hashCode() {
return Objects.hash(bundleCoordinates, version, jarPath, sourcePath);
}
}
|
3e0a68a4a537a875a1f60a30b483e07c2a180391 | 18,422 | java | Java | opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/adaptors/VariantQueryParam.java | lawrencegripper/opencga | a7f39d82a5b21be7887ac16479eb76f2e340626b | [
"Apache-2.0"
] | null | null | null | opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/adaptors/VariantQueryParam.java | lawrencegripper/opencga | a7f39d82a5b21be7887ac16479eb76f2e340626b | [
"Apache-2.0"
] | null | null | null | opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/adaptors/VariantQueryParam.java | lawrencegripper/opencga | a7f39d82a5b21be7887ac16479eb76f2e340626b | [
"Apache-2.0"
] | null | null | null | 53.708455 | 140 | 0.715666 | 4,403 | /*
* Copyright 2015-2017 OpenCB
*
* 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.opencb.opencga.storage.core.variant.adaptors;
import org.opencb.commons.datastore.core.QueryParam;
import java.util.*;
import static org.opencb.commons.datastore.core.QueryParam.Type.*;
import static org.opencb.opencga.storage.core.variant.adaptors.VariantQueryUtils.*;
/**
* Created on 30/03/17.
*
* @author Jacobo Coll <jacobo167@gmail.com>
*/
public final class VariantQueryParam implements QueryParam {
private final String key;
private final Type type;
private final String description;
private static final List<VariantQueryParam> VALUES = new ArrayList<>();
private static final Map<String, VariantQueryParam> VALUES_MAP = new HashMap<>();
private static final String ACCEPTS_ALL_NONE = "Accepts '" + ALL + "' and '" + NONE + "'.";
private static final String ACCEPTS_AND_OR = "Accepts AND (" + AND + ") and OR (" + OR + ") operators.";
public static final String ID_DESCR
= "List of IDs, these can be rs IDs (dbSNP) or variants in the format chrom:start:ref:alt, e.g. rs116600158,19:7177679:C:T";
public static final VariantQueryParam ID = new VariantQueryParam("id", TEXT_ARRAY, ID_DESCR);
public static final String REGION_DESCR
= "List of regions, these can be just a single chromosome name or regions in the format chr:start-end, e.g.: 2,3:100000-200000";
public static final VariantQueryParam REGION = new VariantQueryParam("region", TEXT_ARRAY, REGION_DESCR);
@Deprecated
public static final String CHROMOSOME_DESCR
= "List of chromosomes, this is an alias of 'region' parameter with just the chromosome names";
public static final String REFERENCE_DESCR
= "Reference allele";
public static final VariantQueryParam REFERENCE = new VariantQueryParam("reference", TEXT_ARRAY, REFERENCE_DESCR);
public static final String ALTERNATE_DESCR
= "Main alternate allele";
public static final VariantQueryParam ALTERNATE = new VariantQueryParam("alternate", TEXT_ARRAY, ALTERNATE_DESCR);
public static final String TYPE_DESCR
= "List of types, accepted values are SNV, MNV, INDEL, SV, CNV, INSERTION, DELETION, e.g. SNV,INDEL";
public static final VariantQueryParam TYPE = new VariantQueryParam("type", TEXT_ARRAY, TYPE_DESCR);
public static final String STUDY_DESCR
= "Filter variants from the given studies, these can be either the numeric ID or the alias with the format user@project:study";
public static final VariantQueryParam STUDY = new VariantQueryParam("study", TEXT_ARRAY, STUDY_DESCR);
public static final String INCLUDE_STUDY_DESCR
= "List of studies to include in the result. "
+ ACCEPTS_ALL_NONE;
public static final VariantQueryParam INCLUDE_STUDY = new VariantQueryParam("includeStudy", TEXT_ARRAY, INCLUDE_STUDY_DESCR);
//SAMPLES_DESCR = "Filter variants where ALL the provided samples are mutated (not HOM_REF or missing)";
public static final String SAMPLE_DESCR
= "Filter variants where the samples contain the variant (HET or HOM_ALT). "
+ ACCEPTS_AND_OR + ' '
+ "This will automatically set 'includeSample' parameter when not provided";
public static final VariantQueryParam SAMPLE = new VariantQueryParam("sample", TEXT_ARRAY, SAMPLE_DESCR);
public static final String GENOTYPE_DESCR
= "Samples with a specific genotype: {samp_1}:{gt_1}(,{gt_n})*(;{samp_n}:{gt_1}(,{gt_n})*)*"
+ " e.g. HG0097:0/0;HG0098:0/1,1/1. "
+ "Genotype aliases accepted: HOM_REF, HOM_ALT, HET, HET_REF, HET_ALT and MISS "
+ " e.g. HG0097:HOM_REF;HG0098:HET_REF,HOM_ALT. "
+ "This will automatically set 'includeSample' parameter when not provided";
public static final VariantQueryParam GENOTYPE = new VariantQueryParam("genotype", TEXT_ARRAY, GENOTYPE_DESCR);
public static final String FORMAT_DESCR
= "Filter by any FORMAT field from samples. [{sample}:]{key}{op}{value}[,;]* . "
+ "If no sample is specified, will use all samples from \"sample\" or \"genotype\" filter. "
+ "e.g. DP>200 or HG0097:DP>200,HG0098:DP<10 . "
+ "Many FORMAT fields can be combined. e.g. HG0097:DP>200;GT=1/1,0/1,HG0098:DP<10";
public static final VariantQueryParam FORMAT = new VariantQueryParam("format", TEXT_ARRAY, FORMAT_DESCR);
public static final String INCLUDE_SAMPLE_DESCR
= "List of samples to be included in the result. "
+ ACCEPTS_ALL_NONE;
public static final VariantQueryParam INCLUDE_SAMPLE = new VariantQueryParam("includeSample", TEXT_ARRAY, INCLUDE_SAMPLE_DESCR);
public static final String SAMPLE_METADATA_DESCR
= "Return the samples metadata group by study. Sample names will appear in the same order as their corresponding genotypes.";
public static final VariantQueryParam SAMPLE_METADATA = new VariantQueryParam("sampleMetadata", TEXT_ARRAY, SAMPLE_METADATA_DESCR);
public static final String INCLUDE_FORMAT_DESCR
= "List of FORMAT names from Samples Data to include in the output. e.g: DP,AD. "
+ ACCEPTS_ALL_NONE;
public static final VariantQueryParam INCLUDE_FORMAT = new VariantQueryParam("includeFormat", TEXT_ARRAY, INCLUDE_FORMAT_DESCR);
public static final String INCLUDE_GENOTYPE_DESCR
= "Include genotypes, apart of other formats defined with includeFormat";
public static final VariantQueryParam INCLUDE_GENOTYPE = new VariantQueryParam("includeGenotype", BOOLEAN, INCLUDE_GENOTYPE_DESCR);
public static final String FILE_DESCR
= "Filter variants from the files specified. This will set includeFile parameter when not provided";
public static final VariantQueryParam FILE = new VariantQueryParam("file", TEXT_ARRAY, FILE_DESCR);
public static final String INFO_DESCR
= "Filter by INFO attributes from file. [{file}:]{key}{op}{value}[,;]* . "
+ "If no file is specified, will use all files from \"file\" filter. "
+ "e.g. AN>200 or file_1.vcf:AN>200;file_2.vcf:AN<10 . "
+ "Many INFO fields can be combined. e.g. file_1.vcf:AN>200;DB=true;file_2.vcf:AN<10";
public static final VariantQueryParam INFO = new VariantQueryParam("info", TEXT_ARRAY, INFO_DESCR);
public static final String FILTER_DESCR
= "Specify the FILTER for any of the files. If 'file' filter is provided, will match the file and the filter. "
+ "e.g.: PASS,LowGQX";
public static final VariantQueryParam FILTER = new VariantQueryParam("filter", TEXT_ARRAY, FILTER_DESCR);
public static final String QUAL_DESCR
= "Specify the QUAL for any of the files. If 'file' filter is provided, will match the file and the qual. "
+ "e.g.: >123.4";
public static final VariantQueryParam QUAL = new VariantQueryParam("qual", DECIMAL_ARRAY, QUAL_DESCR);
public static final String INCLUDE_FILE_DESCR
= "List of files to be returned. "
+ ACCEPTS_ALL_NONE;
public static final VariantQueryParam INCLUDE_FILE = new VariantQueryParam("includeFile", TEXT_ARRAY, INCLUDE_FILE_DESCR);
public static final String COHORT_DESCR
= "Select variants with calculated stats for the selected cohorts";
public static final VariantQueryParam COHORT = new VariantQueryParam("cohort", TEXT_ARRAY, COHORT_DESCR);
public static final String STATS_MAF_DESCR
= "Minor Allele Frequency: [{study:}]{cohort}[<|>|<=|>=]{number}. e.g. ALL<=0.4";
public static final VariantQueryParam STATS_MAF = new VariantQueryParam("maf", TEXT_ARRAY, STATS_MAF_DESCR);
public static final String STATS_MGF_DESCR
= "Minor Genotype Frequency: [{study:}]{cohort}[<|>|<=|>=]{number}. e.g. ALL<=0.4";
public static final VariantQueryParam STATS_MGF = new VariantQueryParam("mgf", TEXT_ARRAY, STATS_MGF_DESCR);
public static final String MISSING_ALLELES_DESCR
= "Number of missing alleles: [{study:}]{cohort}[<|>|<=|>=]{number}";
public static final VariantQueryParam MISSING_ALLELES = new VariantQueryParam("missingAlleles", TEXT_ARRAY, MISSING_ALLELES_DESCR);
public static final String MISSING_GENOTYPES_DESCR
= "Number of missing genotypes: [{study:}]{cohort}[<|>|<=|>=]{number}";
public static final VariantQueryParam MISSING_GENOTYPES
= new VariantQueryParam("missingGenotypes", TEXT_ARRAY, MISSING_GENOTYPES_DESCR);
public static final String ANNOT_EXISTS_DESCR
= "Return only annotated variants";
public static final VariantQueryParam ANNOTATION_EXISTS = new VariantQueryParam("annotationExists", BOOLEAN, ANNOT_EXISTS_DESCR);
public static final String ANNOT_XREF_DESCR
= "List of any external reference, these can be genes, proteins or variants. "
+ "Accepted IDs include HGNC, Ensembl genes, dbSNP, ClinVar, HPO, Cosmic, ...";
public static final VariantQueryParam ANNOT_XREF = new VariantQueryParam("xref", TEXT_ARRAY, ANNOT_XREF_DESCR);
public static final String GENE_DESCR
= "List of genes, most gene IDs are accepted (HGNC, Ensembl gene, ...). This is an alias to 'xref' parameter";
public static final VariantQueryParam GENE = new VariantQueryParam("gene", TEXT_ARRAY, GENE_DESCR);
public static final String ANNOT_BIOTYPE_DESCR
= "List of biotypes, e.g. protein_coding";
public static final VariantQueryParam ANNOT_BIOTYPE = new VariantQueryParam("biotype", TEXT_ARRAY, ANNOT_BIOTYPE_DESCR);
public static final String ANNOT_CONSEQUENCE_TYPE_DESCR
= "List of SO consequence types, e.g. missense_variant,stop_lost or SO:0001583,SO:0001578";
public static final VariantQueryParam ANNOT_CONSEQUENCE_TYPE = new VariantQueryParam("ct", TEXT_ARRAY, ANNOT_CONSEQUENCE_TYPE_DESCR);
@Deprecated
public static final String ANNOT_POLYPHEN_DESCR
= "Polyphen, protein substitution score. [<|>|<=|>=]{number} or [~=|=|]{description} e.g. <=0.9 , =benign";
@Deprecated
public static final VariantQueryParam ANNOT_POLYPHEN
= new VariantQueryParam("polyphen", TEXT_ARRAY, ANNOT_POLYPHEN_DESCR);
@Deprecated
public static final String ANNOT_SIFT_DESCR
= "Sift, protein substitution score. [<|>|<=|>=]{number} or [~=|=|]{description} e.g. >0.1 , ~=tolerant";
@Deprecated
public static final VariantQueryParam ANNOT_SIFT
= new VariantQueryParam("sift", TEXT_ARRAY, ANNOT_SIFT_DESCR);
public static final String ANNOT_PROTEIN_SUBSTITUTION_DESCR
= "Protein substitution scores include SIFT and PolyPhen. You can query using the score {protein_score}[<|>|<=|>=]{number}"
+ " or the description {protein_score}[~=|=]{description} e.g. polyphen>0.1,sift=tolerant";
public static final VariantQueryParam ANNOT_PROTEIN_SUBSTITUTION
= new VariantQueryParam("proteinSubstitution", TEXT_ARRAY, ANNOT_PROTEIN_SUBSTITUTION_DESCR);
public static final String ANNOT_CONSERVATION_DESCR
= "Filter by conservation score: {conservation_score}[<|>|<=|>=]{number} e.g. phastCons>0.5,phylop<0.1,gerp>0.1";
public static final VariantQueryParam ANNOT_CONSERVATION
= new VariantQueryParam("conservation", TEXT_ARRAY, ANNOT_CONSERVATION_DESCR);
public static final String ANNOT_POPULATION_ALTERNATE_FREQUENCY_DESCR
= "Alternate Population Frequency: {study}:{population}[<|>|<=|>=]{number}. e.g. 1kG_phase3:ALL<0.01";
public static final VariantQueryParam ANNOT_POPULATION_ALTERNATE_FREQUENCY
= new VariantQueryParam("populationFrequencyAlt", TEXT_ARRAY, ANNOT_POPULATION_ALTERNATE_FREQUENCY_DESCR);
public static final String ANNOT_POPULATION_REFERENCE_FREQUENCY_DESCR
= "Reference Population Frequency: {study}:{population}[<|>|<=|>=]{number}. e.g. 1kG_phase3:ALL<0.01";
public static final VariantQueryParam ANNOT_POPULATION_REFERENCE_FREQUENCY
= new VariantQueryParam("populationFrequencyRef", TEXT_ARRAY, ANNOT_POPULATION_REFERENCE_FREQUENCY_DESCR);
public static final String ANNOT_POPULATION_MINOR_ALLELE_FREQUENCY_DESCR
= "Population minor allele frequency: {study}:{population}[<|>|<=|>=]{number}. e.g. 1kG_phase3:ALL<0.01";
public static final VariantQueryParam ANNOT_POPULATION_MINOR_ALLELE_FREQUENCY
= new VariantQueryParam("populationFrequencyMaf", TEXT_ARRAY, ANNOT_POPULATION_MINOR_ALLELE_FREQUENCY_DESCR);
public static final String ANNOT_TRANSCRIPTION_FLAG_DESCR
= "List of transcript annotation flags. e.g. CCDS, basic, cds_end_NF, mRNA_end_NF, cds_start_NF, mRNA_start_NF, seleno";
public static final VariantQueryParam ANNOT_TRANSCRIPTION_FLAG
= new VariantQueryParam("transcriptionFlag", TEXT_ARRAY, ANNOT_TRANSCRIPTION_FLAG_DESCR);
public static final String ANNOT_GENE_TRAIT_ID_DESCR
= "List of gene trait association id. e.g. \"umls:C0007222\" , \"OMIM:269600\"";
public static final VariantQueryParam ANNOT_GENE_TRAIT_ID
= new VariantQueryParam("geneTraitId", TEXT_ARRAY, ANNOT_GENE_TRAIT_ID_DESCR);
@Deprecated
public static final String ANNOT_GENE_TRAIT_NAME_DESCR
= "List of gene trait association names. e.g. Cardiovascular Diseases";
@Deprecated
public static final VariantQueryParam ANNOT_GENE_TRAIT_NAME
= new VariantQueryParam("geneTraitName", TEXT_ARRAY, ANNOT_GENE_TRAIT_NAME_DESCR);
public static final String ANNOT_TRAIT_DESCR
= "List of traits, based on ClinVar, HPO, COSMIC, i.e.: IDs, histologies, descriptions,...";
public static final VariantQueryParam ANNOT_TRAIT = new VariantQueryParam("trait", TEXT_ARRAY, ANNOT_TRAIT_DESCR);
public static final String ANNOT_CLINICAL_SIGNIFICANCE_DESCR
= "Clinical significance: benign, likely_benign, likely_pathogenic, pathogenic";
public static final VariantQueryParam ANNOT_CLINICAL_SIGNIFICANCE =
new VariantQueryParam("clinicalSignificance", TEXT_ARRAY, ANNOT_CLINICAL_SIGNIFICANCE_DESCR);
@Deprecated
public static final String ANNOT_CLINVAR_DESCR
= "List of ClinVar accessions";
@Deprecated
public static final VariantQueryParam ANNOT_CLINVAR = new VariantQueryParam("clinvar", TEXT_ARRAY, ANNOT_CLINVAR_DESCR);
@Deprecated
public static final String ANNOT_COSMIC_DESCR
= "List of COSMIC mutation IDs.";
@Deprecated
public static final VariantQueryParam ANNOT_COSMIC = new VariantQueryParam("cosmic", TEXT_ARRAY, ANNOT_COSMIC_DESCR);
@Deprecated
public static final String ANNOT_HPO_DESCR
= "List of HPO terms. e.g. \"HP:0000545,HP:0002812\"";
@Deprecated
public static final VariantQueryParam ANNOT_HPO = new VariantQueryParam("hpo", TEXT_ARRAY, ANNOT_HPO_DESCR);
public static final String ANNOT_GO_DESCR
= "List of GO (Gene Ontology) terms. e.g. \"GO:0002020\"";
public static final VariantQueryParam ANNOT_GO = new VariantQueryParam("go", TEXT_ARRAY, ANNOT_GO_DESCR);
public static final String ANNOT_EXPRESSION_DESCR
= "List of tissues of interest. e.g. \"lung\"";
public static final VariantQueryParam ANNOT_EXPRESSION = new VariantQueryParam("expression", TEXT_ARRAY, ANNOT_EXPRESSION_DESCR);
public static final String ANNOT_PROTEIN_KEYWORD_DESCR
= "List of Uniprot protein variant annotation keywords";
public static final VariantQueryParam ANNOT_PROTEIN_KEYWORD
= new VariantQueryParam("proteinKeyword", TEXT_ARRAY, ANNOT_PROTEIN_KEYWORD_DESCR);
public static final String ANNOT_DRUG_DESCR
= "List of drug names";
public static final VariantQueryParam ANNOT_DRUG = new VariantQueryParam("drug", TEXT_ARRAY, ANNOT_DRUG_DESCR);
public static final String ANNOT_FUNCTIONAL_SCORE_DESCR
= "Functional score: {functional_score}[<|>|<=|>=]{number} e.g. cadd_scaled>5.2 , cadd_raw<=0.3";
public static final VariantQueryParam ANNOT_FUNCTIONAL_SCORE
= new VariantQueryParam("functionalScore", TEXT_ARRAY, ANNOT_FUNCTIONAL_SCORE_DESCR);
public static final String CUSTOM_ANNOTATION_DESCR
= "Custom annotation: {key}[<|>|<=|>=]{number} or {key}[~=|=]{text}";
public static final VariantQueryParam CUSTOM_ANNOTATION
= new VariantQueryParam("customAnnotation", TEXT_ARRAY, CUSTOM_ANNOTATION_DESCR);
public static final String UNKNOWN_GENOTYPE_DESCR
= "Returned genotype for unknown genotypes. Common values: [0/0, 0|0, ./.]";
public static final VariantQueryParam UNKNOWN_GENOTYPE = new VariantQueryParam("unknownGenotype", TEXT, UNKNOWN_GENOTYPE_DESCR);
public static final String RELEASE_DESCR
= "";
public static final VariantQueryParam RELEASE
= new VariantQueryParam("release", INTEGER, RELEASE_DESCR);
private VariantQueryParam(String key, Type type, String description) {
this.key = key;
this.type = type;
this.description = description;
VALUES.add(this);
VALUES_MAP.put(key, this);
}
@Override
public String key() {
return key;
}
@Override
public String description() {
return description;
}
@Override
public Type type() {
return type;
}
@Override
public String toString() {
return key() + " [" + type() + "] : " + description();
}
public static List<VariantQueryParam> values() {
return Collections.unmodifiableList(VALUES);
}
public static VariantQueryParam valueOf(String param) {
return VALUES_MAP.get(param);
}
}
|
3e0a68ba4b7766254301fbbdba2b3ec42ea2749e | 3,734 | java | Java | src/test/java/com/firstrowria/pushnotificationtester/MockHttpServletResponse.java | bbindreiter/PushNotificationTester_Web | 999aa19c5e00f6141d79ee533ca8289084eaf217 | [
"Apache-2.0"
] | 6 | 2016-02-24T23:27:05.000Z | 2021-07-11T17:30:40.000Z | src/test/java/com/firstrowria/pushnotificationtester/MockHttpServletResponse.java | berndfinal/PushNotificationTester_Web | 999aa19c5e00f6141d79ee533ca8289084eaf217 | [
"Apache-2.0"
] | 1 | 2020-04-26T08:39:09.000Z | 2020-04-26T08:39:09.000Z | src/test/java/com/firstrowria/pushnotificationtester/MockHttpServletResponse.java | bbindreiter/PushNotificationTester_Web | 999aa19c5e00f6141d79ee533ca8289084eaf217 | [
"Apache-2.0"
] | 7 | 2016-02-24T23:27:11.000Z | 2021-05-14T17:40:05.000Z | 18.954315 | 76 | 0.706481 | 4,404 | package com.firstrowria.pushnotificationtester;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Locale;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
/**
* This mock class is created to enable basic unit testing of the
* {@link HelloAppEngine} class. Only methods used in the unit test
* have a non-trivial implementation.
*
* Feel free to change this class or replace it using other ways for testing
* {@link HttpServlet}s, e.g. Spring MVC Test or Mockito to suit your needs.
*/
public class MockHttpServletResponse implements HttpServletResponse {
private String contentType;
private String encoding;
private StringWriter writerContent = new StringWriter();
private PrintWriter writer = new PrintWriter(writerContent);
@Override
public void setContentType(String contentType) {
this.contentType = contentType;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public PrintWriter getWriter() throws IOException {
return writer;
}
public StringWriter getWriterContent() {
return writerContent;
}
// anything below is the default generated implementation
@Override
public void flushBuffer() throws IOException {
}
@Override
public int getBufferSize() {
return 0;
}
@Override
public String getCharacterEncoding() {
return encoding;
}
@Override
public Locale getLocale() {
return null;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return null;
}
@Override
public boolean isCommitted() {
return false;
}
@Override
public void reset() {
}
@Override
public void resetBuffer() {
}
@Override
public void setBufferSize(int arg0) {
}
@Override
public void setCharacterEncoding(String encoding) {
this.encoding = encoding;
}
@Override
public void setContentLength(int arg0) {
}
@Override
public void setLocale(Locale arg0) {
}
@Override
public void addCookie(Cookie arg0) {
}
@Override
public void addDateHeader(String arg0, long arg1) {
}
@Override
public void addHeader(String arg0, String arg1) {
}
@Override
public void addIntHeader(String arg0, int arg1) {
}
@Override
public boolean containsHeader(String arg0) {
return false;
}
@Override
public String encodeRedirectURL(String arg0) {
return null;
}
@Override
public String encodeRedirectUrl(String arg0) {
return null;
}
@Override
public String encodeURL(String arg0) {
return null;
}
@Override
public String encodeUrl(String arg0) {
return null;
}
@Override
public void sendError(int arg0) throws IOException {
}
@Override
public void sendError(int arg0, String arg1) throws IOException {
}
@Override
public void sendRedirect(String arg0) throws IOException {
}
@Override
public void setDateHeader(String arg0, long arg1) {
}
@Override
public void setHeader(String arg0, String arg1) {
}
@Override
public void setIntHeader(String arg0, int arg1) {
}
@Override
public void setStatus(int arg0) {
}
@Override
public void setStatus(int arg0, String arg1) {
}
// Servlet API 3.0 and 3.1 methods
public void setContentLengthLong(long length) {
}
public int getStatus() {
return 0;
}
public String getHeader(String name) {
return null;
}
public Collection<String> getHeaders(String name) {
return null;
}
public Collection<String> getHeaderNames() {
return null;
}
}
|
3e0a6935ab6965f627809854b56007f3a810861b | 855 | java | Java | app/src/main/java/com/example/shubhraj/dealskart/FullScreenActitvity.java | Shubhraaaj/Dealskart | 31feb174623468a1b7fae4c204001724e0182e79 | [
"Apache-2.0"
] | 2 | 2019-05-02T04:35:39.000Z | 2020-09-09T17:14:27.000Z | app/src/main/java/com/example/shubhraj/dealskart/FullScreenActitvity.java | Shubhraaaj/Dealskart | 31feb174623468a1b7fae4c204001724e0182e79 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/shubhraj/dealskart/FullScreenActitvity.java | Shubhraaaj/Dealskart | 31feb174623468a1b7fae4c204001724e0182e79 | [
"Apache-2.0"
] | null | null | null | 29.482759 | 81 | 0.661988 | 4,405 | package com.example.shubhraj.dealskart;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class FullScreenActitvity extends AppCompatActivity
{
private String status;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen_actitvity);
status = getIntent().getStringExtra("STATUS");
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("STATUS", status);
startActivity(intent);
}
}, 1000L);
}
}
|
3e0a693c19cd6099e4456196ab4ddc1ea786ab4f | 2,503 | java | Java | backend/src/main/java/br/com/srsali/srsali/controllers/HorarioController.java | rafaelgude/SrSali | 0df6fdef2faad2d4612f6f3db1dcfbf59848cd34 | [
"Apache-2.0"
] | 1 | 2019-09-05T01:44:42.000Z | 2019-09-05T01:44:42.000Z | backend/src/main/java/br/com/srsali/srsali/controllers/HorarioController.java | rafaelgude/SrSali | 0df6fdef2faad2d4612f6f3db1dcfbf59848cd34 | [
"Apache-2.0"
] | 5 | 2020-09-07T09:42:02.000Z | 2022-02-10T17:28:54.000Z | backend/src/main/java/br/com/srsali/srsali/controllers/HorarioController.java | rafaelgude/SrSali | 0df6fdef2faad2d4612f6f3db1dcfbf59848cd34 | [
"Apache-2.0"
] | null | null | null | 41.032787 | 123 | 0.728726 | 4,406 | package br.com.srsali.srsali.controllers;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import br.com.srsali.srsali.models.Horario;
import br.com.srsali.srsali.services.HorarioService;
@RestController
@RequestMapping("/horarios")
public class HorarioController {
@Autowired HorarioService horarioService;
@GetMapping
public ResponseEntity<Page<Horario>> findAll(@RequestParam(value="page", defaultValue="0") int page,
@RequestParam(value="linesPerPage", defaultValue="24") int linesPerPage,
@RequestParam(value="orderBy", defaultValue="turno,nome") String orderBy,
@RequestParam(value="direction", defaultValue="ASC") String direction) {
return ResponseEntity.ok().body(horarioService.findAll(page, linesPerPage, orderBy, direction));
}
@GetMapping("/{id}")
public ResponseEntity<Horario> find(@PathVariable int id) {
return ResponseEntity.ok().body(horarioService.find(id));
}
@PostMapping
public ResponseEntity<Void> insert(@RequestBody List<Horario> horarios) {
horarios.forEach(horarioService::insert);
return ResponseEntity.created(null).build();
}
@PutMapping("/{id}")
public ResponseEntity<Void> update(@PathVariable int id, @RequestBody Horario horario) {
var newHorario = horarioService.find(id);
BeanUtils.copyProperties(horario, newHorario, "id", "instituicao");
horarioService.update(newHorario);
return ResponseEntity.noContent().build();
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable int id) {
horarioService.delete(id);
return ResponseEntity.noContent().build();
}
} |
3e0a6a546c4cf82202ef7c01e797b639094d1eef | 2,180 | java | Java | nepxion-swing/src/com/nepxion/swing/chart/pie/PiePlotRotator.java | Nepxion/Marvel | 51bb477ccbff64067981bd92efcdb9b7b01c6f5f | [
"Apache-2.0"
] | 10 | 2016-11-28T11:16:42.000Z | 2021-08-22T04:03:21.000Z | nepxion-swing/src/com/nepxion/swing/chart/pie/PiePlotRotator.java | Nepxion/Marvel | 51bb477ccbff64067981bd92efcdb9b7b01c6f5f | [
"Apache-2.0"
] | null | null | null | nepxion-swing/src/com/nepxion/swing/chart/pie/PiePlotRotator.java | Nepxion/Marvel | 51bb477ccbff64067981bd92efcdb9b7b01c6f5f | [
"Apache-2.0"
] | 2 | 2021-01-14T09:41:50.000Z | 2021-07-01T14:17:51.000Z | 20.537736 | 84 | 0.686725 | 4,407 | package com.nepxion.swing.chart.pie;
/**
* <p>Title: Nepxion Swing</p>
* <p>Description: Nepxion Swing Repository</p>
* <p>Copyright: Copyright (c) 2010</p>
* <p>Company: Nepxion</p>
* @author Neptune
* @email lyhxr@example.com
* @version 1.0
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import org.jfree.chart.plot.PiePlot;
import com.nepxion.swing.chart.JChartPanel;
public class PiePlotRotator
extends Timer implements ActionListener
{
/**
* The instance of PiePlot.
*/
private PiePlot piePlot;
/**
* The rotation angle value.
*/
private int angle;
/**
* Constructs with the specified initial chartPanel and isClickingStarted.
* @param chartPanel the instance of JChartPanel
* @param isClickingStarted the boolean value of isClickingStarted
*/
public PiePlotRotator(JChartPanel chartPanel, boolean isClickingStarted)
{
this(chartPanel, 100, isClickingStarted);
}
/**
* Constructs with the specified initial chartPanel, delay and isClickingStarted.
* @param chartPanel the instance of JChartPanel
* @param delay the delay value
* @param isClickingStarted the boolean value of isClickingStarted
*/
public PiePlotRotator(JChartPanel chartPanel, int delay, boolean isClickingStarted)
{
super(delay, null);
this.angle = 270;
this.piePlot = (PiePlot) chartPanel.getChart().getPlot();
if (isClickingStarted)
{
chartPanel.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 1)
{
execute();
}
}
}
);
}
addActionListener(this);
}
/**
* Invoked when an action occurs.
* @param e the instance of ActionEvent
*/
public void actionPerformed(ActionEvent e)
{
piePlot.setStartAngle(angle);
angle = angle + 1;
if (angle == 360)
{
angle = 0;
}
}
/**
* Executes the timer.
*/
public void execute()
{
if (!isRunning())
{
start();
}
else
{
stop();
}
}
} |
3e0a6a7aed5e143969a3de131e19dad8866c6383 | 2,351 | java | Java | three-sum/src/Solution.java | bunnyc1986/leetcode | ba854a8f085ef626230d8392a3c937699d397250 | [
"MIT"
] | 1 | 2018-05-21T10:31:09.000Z | 2018-05-21T10:31:09.000Z | three-sum/src/Solution.java | bunnyc1986/leetcode | ba854a8f085ef626230d8392a3c937699d397250 | [
"MIT"
] | null | null | null | three-sum/src/Solution.java | bunnyc1986/leetcode | ba854a8f085ef626230d8392a3c937699d397250 | [
"MIT"
] | null | null | null | 36.169231 | 113 | 0.433007 | 4,408 | import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static junit.framework.Assert.assertEquals;
/**
* https://leetcode.com/problems/3sum/
*/
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
if (nums.length < 3) {
return results;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length && nums[i] <= 0; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int target = 0 - nums[i];
int j = i + 1, k = nums.length - 1;
while (j < k) {
if (nums[j] + nums[k] == target) {
results.add(Arrays.asList(nums[i], nums[j], nums[k]));
while (j < k && nums[j] == nums[++j]) ;
while (j < k && nums[k] == nums[--k]) ;
} else if (nums[j] + nums[k] < target) {
while (j < k && nums[j] == nums[++j]) ;
} else {
while (j < k && nums[k] == nums[--k]) ;
}
}
}
return results;
}
@Test
public void test1() {
List<List<Integer>> output = threeSum(new int[]{-1, 0, 1, 2, -1, -4});
assertEquals(2, output.size());
assertEquals("[-1, -1, 2]", output.get(0).toString());
assertEquals("[-1, 0, 1]", output.get(1).toString());
}
@Test
public void test2() {
List<List<Integer>> output = threeSum(new int[]{0, 0, 0, 0, 0, 0, 0});
assertEquals(1, output.size());
assertEquals("[0, 0, 0]", output.get(0).toString());
}
@Test
public void test3() {
List<List<Integer>> output = threeSum(new int[]{7, -1, 14, -12, -8, 7, 2, -15, 8, 8, -8, -14, -4, -5, 7,
9, 11, -4, -15, -6, 1, -14, 4, 3, 10, -5, 2, 1, 6, 11, 2, -2, -5, -7, -6, 2, -15, 11, -6, 8, -4,
2, 1, -1, 4, -6, -15, 1, 5, -15, 10, 14, 9, -8, -6, 4, -6, 11, 12, -15, 7, -1, -9, 9, -1, 0, -4,
-1, -12, -2, 14, -9, 7, 0, -3, -4, 1, -2, 12, 14, -10, 0, 5, 14, -1, 14, 3, 8, 10, -8, 8, -5, -2,
6, -11, 12, 13, -7, -12, 8, 6, -13, 14, -2, -5, -11, 1, 3, -6});
assertEquals(119, output.size());
}
}
|
3e0a6ab1e3227131c5035be2f1440f1515581d2c | 3,149 | java | Java | serenity-core/src/main/java/net/thucydides/core/reports/html/TagFilter.java | raulfandinoolaya/serenity-core | 89183101d2a058f62b8ae30e6bd995f23425186b | [
"Apache-2.0"
] | null | null | null | serenity-core/src/main/java/net/thucydides/core/reports/html/TagFilter.java | raulfandinoolaya/serenity-core | 89183101d2a058f62b8ae30e6bd995f23425186b | [
"Apache-2.0"
] | null | null | null | serenity-core/src/main/java/net/thucydides/core/reports/html/TagFilter.java | raulfandinoolaya/serenity-core | 89183101d2a058f62b8ae30e6bd995f23425186b | [
"Apache-2.0"
] | 1 | 2016-11-03T22:08:24.000Z | 2016-11-03T22:08:24.000Z | 31.178218 | 112 | 0.639886 | 4,409 | package net.thucydides.core.reports.html;
import com.google.common.base.Splitter;
import net.thucydides.core.ThucydidesSystemProperty;
import net.thucydides.core.model.TestTag;
import net.thucydides.core.util.EnvironmentVariables;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
public class TagFilter {
private final EnvironmentVariables environmentVariables;
public TagFilter(EnvironmentVariables environmentVariables) {
this.environmentVariables = environmentVariables;
}
public List<String> filteredTagTypes(List<String> tagTypes) {
List<String> filteredTags = new ArrayList<>(tagTypes);
List<String> displayedTags = includedTagTypes();
if (!displayedTags.isEmpty()) {
filteredTags = onlyKeepAllowedTypes(filteredTags, displayedTags);
}
List<String> excludedTags = excludedTagTypes();
if (!excludedTags.isEmpty()) {
filteredTags = removeUnwantedTags(filteredTags, excludedTags);
}
return filteredTags;
}
public Set<TestTag> removeTagsOfType(Set<TestTag> tags, String... redundantTagTypes) {
Set<TestTag> filteredTags = new HashSet();
List<String> maskedTagTypes = Arrays.asList(redundantTagTypes);
for (TestTag tag : tags) {
if (!maskedTagTypes.contains(tag.getType())) {
filteredTags.add(tag);
}
}
return filteredTags;
}
public Set<TestTag> removeTagsWithName(Set<TestTag> tags, String name) {
Set<TestTag> filteredTags = new HashSet();
for (TestTag tag : tags) {
if (!tag.getShortName().equalsIgnoreCase(name)) {
filteredTags.add(tag);
}
}
return filteredTags;
}
private List<String> onlyKeepAllowedTypes(List<String> tags, List<String> displayedTags) {
List<String> allowedTags = new ArrayList<>();
for (String tag : tags) {
if (displayedTags.contains(tag.toLowerCase())) {
allowedTags.add(tag);
}
}
return allowedTags;
}
private List<String> removeUnwantedTags(List<String> tags, List<String> unwantedTags) {
for (String tag : unwantedTags) {
if (tags.contains(tag.toLowerCase())) {
tags.remove(tag.toLowerCase());
}
if (tags.contains(tag.toUpperCase())) {
tags.remove(tag.toUpperCase());
}
}
return tags;
}
private List<String> includedTagTypes() {
return asLowercaseList(ThucydidesSystemProperty.DASHBOARD_TAG_LIST.from(environmentVariables));
}
private List<String> excludedTagTypes() {
return asLowercaseList(ThucydidesSystemProperty.DASHBOARD_EXCLUDED_TAG_LIST.from(environmentVariables));
}
private List<String> asLowercaseList(String displayTags) {
if (StringUtils.isNotEmpty(displayTags)) {
return Splitter.on(",").omitEmptyStrings().trimResults().splitToList(displayTags.toLowerCase());
} else {
return new ArrayList<>();
}
}
}
|
3e0a6af7e132bfac7f2df399503681ae44cb755e | 10,062 | java | Java | BlinkIDSample/BlinkID-TemplatingSample/src/main/java/com/microblink/blinkid/MainActivity.java | AsimKhan2019/Blink-ID | bfa8bf2c795833be7bbf7fdc41820954e5684143 | [
"Intel"
] | null | null | null | BlinkIDSample/BlinkID-TemplatingSample/src/main/java/com/microblink/blinkid/MainActivity.java | AsimKhan2019/Blink-ID | bfa8bf2c795833be7bbf7fdc41820954e5684143 | [
"Intel"
] | null | null | null | BlinkIDSample/BlinkID-TemplatingSample/src/main/java/com/microblink/blinkid/MainActivity.java | AsimKhan2019/Blink-ID | bfa8bf2c795833be7bbf7fdc41820954e5684143 | [
"Intel"
] | null | null | null | 43.184549 | 130 | 0.717253 | 4,410 | package com.microblink.blinkid;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.widget.Toast;
import com.microblink.BaseMenuActivity;
import com.microblink.MenuListItem;
import com.microblink.activity.DocumentScanActivity;
import com.microblink.entities.recognizers.Recognizer;
import com.microblink.entities.recognizers.RecognizerBundle;
import com.microblink.entities.recognizers.blinkid.mrtd.MrtdRecognizer;
import com.microblink.entities.recognizers.blinkid.mrtd.MrzResult;
import com.microblink.entities.recognizers.detector.DetectorRecognizer;
import com.microblink.entities.recognizers.successframe.SuccessFrameGrabberRecognizer;
import com.microblink.image.Image;
import com.microblink.results.date.Date;
import com.microblink.util.RecognizerCompatibility;
import com.microblink.util.RecognizerCompatibilityStatus;
import com.microblink.util.templating.CroatianIDBackSideTemplatingUtil;
import com.microblink.util.templating.CroatianIDFrontSideTemplatingUtil;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends BaseMenuActivity {
private static final int SCAN_FRONT_REQ_CODE = 234;
private static final int SCAN_BACK_REQ_CODE = 432;
/**
* Prepares all parsers and templating recognizer for scanning front side of
* the Croatian ID front side and holds parsers references which are used later for
* obtaining scan results.
*/
private CroatianIDFrontSideTemplatingUtil mFrontSideTemplatingUtil;
private CroatianIDBackSideTemplatingUtil mBackSideTemplatingUtil;
private DetectorRecognizer mFrontSideTemplatingRecognizer;
private MrtdRecognizer mBackSideTemplatingRecognizer;
private SuccessFrameGrabberRecognizer mSuccessFrameGrabberRecognizer;
private RecognizerBundle mRecognizerBundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFrontSideTemplatingUtil = new CroatianIDFrontSideTemplatingUtil();
mBackSideTemplatingUtil = new CroatianIDBackSideTemplatingUtil();
// check if BlinkInput is supported on the device
RecognizerCompatibilityStatus supportStatus = RecognizerCompatibility.getRecognizerCompatibilityStatus(this);
if (supportStatus != RecognizerCompatibilityStatus.RECOGNIZER_SUPPORTED) {
Toast.makeText(this, "BlinkInput is not supported! Reason: " + supportStatus.name(), Toast.LENGTH_LONG).show();
}
}
@Override
protected List<MenuListItem> createMenuListItems() {
List<MenuListItem> items = new ArrayList<>();
items.add(new MenuListItem(getString(R.string.scan_croatian_id_front), new Runnable() {
@Override
public void run() {
mFrontSideTemplatingRecognizer = mFrontSideTemplatingUtil.getDetectorRecognizer();
//wrapping into SuccessFrameGrabberRecognizer because we want to show successful scan image
mSuccessFrameGrabberRecognizer = new SuccessFrameGrabberRecognizer(mFrontSideTemplatingRecognizer);
startScanActivity(SCAN_FRONT_REQ_CODE);
}
}));
items.add(new MenuListItem(getString(R.string.scan_croatian_id_back), new Runnable() {
@Override
public void run() {
mBackSideTemplatingRecognizer = mBackSideTemplatingUtil.getMRTDRecognizer();
mSuccessFrameGrabberRecognizer = new SuccessFrameGrabberRecognizer(mBackSideTemplatingRecognizer);
startScanActivity(SCAN_BACK_REQ_CODE);
}
}));
return items;
}
@Override
protected String getTitleText() {
return getString(R.string.app_name);
}
private void startScanActivity(int requestCode) {
mRecognizerBundle = new RecognizerBundle(mSuccessFrameGrabberRecognizer);
mRecognizerBundle.setNumMsBeforeTimeout(10_000);
Intent intent = new Intent(MainActivity.this, DocumentScanActivity.class);
mRecognizerBundle.saveToIntent(intent);
startActivityForResult(intent, requestCode);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != DocumentScanActivity.RESULT_OK || data == null) {
return;
}
if (requestCode == SCAN_FRONT_REQ_CODE) {
showFrontScanResults(data);
} else if (requestCode == SCAN_BACK_REQ_CODE) {
showBackScanResults(data);
}
}
private void showFrontScanResults(Intent data) {
// now we can load bundle with scan results, after loading, results will be available
// through recognizer instances
mRecognizerBundle.loadFromIntent(data);
String successFramePath = storeImageToFile(mSuccessFrameGrabberRecognizer.getResult().getSuccessFrame(),
"successFrame.jpg");
String fullDocumentPath = storeImageToFile(mFrontSideTemplatingUtil.getFullDocumentImage().getResult().getRawImage(),
"fullDocument.jpg");
String facePath = storeImageToFile(mFrontSideTemplatingUtil.getFaceImage().getResult().getRawImage(),
"face.jpg");
String resultText = extractFrontSideData();
if (mFrontSideTemplatingRecognizer.getResult().getResultState() == Recognizer.Result.State.Valid) {
startActivity(ResultsActivity.buildIntent(this, resultText, successFramePath, fullDocumentPath, facePath));
}
}
private void showBackScanResults(Intent data) {
mRecognizerBundle.loadFromIntent(data);
String successFramePath = storeImageToFile(mSuccessFrameGrabberRecognizer.getResult().getSuccessFrame(),
"successFrame.jpg");
String fullDocumentPath = storeImageToFile(mBackSideTemplatingUtil.getMRTDRecognizer().getResult().getFullDocumentImage(),
"fullDocument.jpg");
String resultText = extractBackSideData();
if (mBackSideTemplatingRecognizer.getResult().getResultState() == Recognizer.Result.State.Valid) {
startActivity(ResultsActivity.buildIntent(this, resultText, successFramePath, fullDocumentPath, ""));
}
}
//returns absolute file path
private String storeImageToFile(Image image, String filename) {
String filePath;
try {
Bitmap bitmap = image.convertToBitmap();
File imageFile = new File(getFilesDir(), filename);
OutputStream os = new BufferedOutputStream(new FileOutputStream(imageFile));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
filePath = imageFile.getAbsolutePath();
os.close();
} catch (Exception e) {
filePath = null;
}
return filePath;
}
private String extractFrontSideData() {
StringBuilder sb = new StringBuilder();
addEntry(sb, R.string.result_key_first_name,
mFrontSideTemplatingUtil.getFirstNameParser().getResult().toString());
addEntry(sb, R.string.result_key_last_name,
mFrontSideTemplatingUtil.getLastNameParser().getResult().toString());
// either new or old document number parser contains valid result (depends on the scanned document type)
int documentNumberKeyResourceId = R.string.result_key_old_document_number;
String documentNumber = mFrontSideTemplatingUtil.getOldDocumentNumberParser().getResult().toString();
if (documentNumber.isEmpty()) {
documentNumber = mFrontSideTemplatingUtil.getNewDocumentNumberParser().getResult().toString();
documentNumberKeyResourceId = R.string.result_key_new_document_number;
}
addEntry(sb, documentNumberKeyResourceId, documentNumber);
addEntry(sb, R.string.result_key_sex,
mFrontSideTemplatingUtil.getSexParser().getResult().toString());
addEntry(sb, R.string.result_key_citizenship,
mFrontSideTemplatingUtil.getCitizenshipParser().getResult().toString());
Date dateOfBirth = mFrontSideTemplatingUtil.getDateOfBirthParser().getResult().getDate().getDate();
if (dateOfBirth != null) {
addEntry(sb, R.string.result_key_date_of_birth, formatDate(dateOfBirth));
}
return sb.toString();
}
private String extractBackSideData() {
StringBuilder sb = new StringBuilder();
addEntry(sb, R.string.PPAddress, mBackSideTemplatingUtil.getAddressParser().getResult().toString());
Date issueDate = mBackSideTemplatingUtil.getDateOfIssueParser().getResult().getDate().getDate();
if (issueDate != null) {
addEntry(sb, R.string.PPIssueDate, formatDate(issueDate));
}
addEntry(sb, R.string.PPIssuedBy, mBackSideTemplatingUtil.getIssuedByParser().getResult().toString());
//extract everything else from mrz result
MrzResult mrzResult = mBackSideTemplatingRecognizer.getResult().getMrzResult();
addEntry(sb, R.string.PPPrimaryId, mrzResult.getPrimaryId());
addEntry(sb, R.string.PPSecondaryId, mrzResult.getSecondaryId());
addEntry(sb, R.string.PPSex, mrzResult.getGender());
addEntry(sb, R.string.PPNationality, mrzResult.getNationality());
return sb.toString();
}
private void addEntry(StringBuilder stringBuilder, @StringRes int entryKeyResourceId, @NonNull String value) {
stringBuilder.append(getString(entryKeyResourceId)).append(": ").append(value).append("\n");
}
private String formatDate(@NonNull Date date) {
return String.format(Locale.US, "%02d.%02d.%d.", date.getDay(), date.getMonth(), date.getYear());
}
}
|
3e0a6c2a210176de8472ca16232827af5de9a890 | 5,315 | java | Java | clients/google-api-services-deploymentmanager/v2beta/1.29.2/com/google/api/services/deploymentmanager/model/GlobalSetPolicyRequest.java | yoshi-code-bot/google-api-java-client-services | 9f5e3b6073c822db4078d638c980b11a0effc686 | [
"Apache-2.0"
] | 372 | 2018-09-05T21:06:51.000Z | 2022-03-31T09:22:03.000Z | clients/google-api-services-deploymentmanager/v2beta/1.29.2/com/google/api/services/deploymentmanager/model/GlobalSetPolicyRequest.java | yoshi-code-bot/google-api-java-client-services | 9f5e3b6073c822db4078d638c980b11a0effc686 | [
"Apache-2.0"
] | 1,351 | 2018-10-12T23:07:12.000Z | 2022-03-05T09:25:29.000Z | clients/google-api-services-deploymentmanager/v2beta/1.29.2/com/google/api/services/deploymentmanager/model/GlobalSetPolicyRequest.java | yoshi-code-bot/google-api-java-client-services | 9f5e3b6073c822db4078d638c980b11a0effc686 | [
"Apache-2.0"
] | 307 | 2018-09-04T20:15:31.000Z | 2022-03-31T09:42:39.000Z | 32.408537 | 182 | 0.697272 | 4,411 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.deploymentmanager.model;
/**
* Model definition for GlobalSetPolicyRequest.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Google Cloud Deployment Manager API V2Beta Methods.
* For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GlobalSetPolicyRequest extends com.google.api.client.json.GenericJson {
/**
* Flatten Policy to create a backward compatible wire-format. Deprecated. Use 'policy' to specify
* bindings.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Binding> bindings;
static {
// hack to force ProGuard to consider Binding used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(Binding.class);
}
/**
* Flatten Policy to create a backward compatible wire-format. Deprecated. Use 'policy' to specify
* the etag.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String etag;
/**
* REQUIRED: The complete policy to be applied to the 'resource'. The size of the policy is
* limited to a few 10s of KB. An empty policy is in general a valid policy but certain services
* (like Projects) might reject them.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Policy policy;
/**
* Flatten Policy to create a backward compatible wire-format. Deprecated. Use 'policy' to specify
* bindings.
* @return value or {@code null} for none
*/
public java.util.List<Binding> getBindings() {
return bindings;
}
/**
* Flatten Policy to create a backward compatible wire-format. Deprecated. Use 'policy' to specify
* bindings.
* @param bindings bindings or {@code null} for none
*/
public GlobalSetPolicyRequest setBindings(java.util.List<Binding> bindings) {
this.bindings = bindings;
return this;
}
/**
* Flatten Policy to create a backward compatible wire-format. Deprecated. Use 'policy' to specify
* the etag.
* @see #decodeEtag()
* @return value or {@code null} for none
*/
public java.lang.String getEtag() {
return etag;
}
/**
* Flatten Policy to create a backward compatible wire-format. Deprecated. Use 'policy' to specify
* the etag.
* @see #getEtag()
* @return Base64 decoded value or {@code null} for none
*
* @since 1.14
*/
public byte[] decodeEtag() {
return com.google.api.client.util.Base64.decodeBase64(etag);
}
/**
* Flatten Policy to create a backward compatible wire-format. Deprecated. Use 'policy' to specify
* the etag.
* @see #encodeEtag()
* @param etag etag or {@code null} for none
*/
public GlobalSetPolicyRequest setEtag(java.lang.String etag) {
this.etag = etag;
return this;
}
/**
* Flatten Policy to create a backward compatible wire-format. Deprecated. Use 'policy' to specify
* the etag.
* @see #setEtag()
*
* <p>
* The value is encoded Base64 or {@code null} for none.
* </p>
*
* @since 1.14
*/
public GlobalSetPolicyRequest encodeEtag(byte[] etag) {
this.etag = com.google.api.client.util.Base64.encodeBase64URLSafeString(etag);
return this;
}
/**
* REQUIRED: The complete policy to be applied to the 'resource'. The size of the policy is
* limited to a few 10s of KB. An empty policy is in general a valid policy but certain services
* (like Projects) might reject them.
* @return value or {@code null} for none
*/
public Policy getPolicy() {
return policy;
}
/**
* REQUIRED: The complete policy to be applied to the 'resource'. The size of the policy is
* limited to a few 10s of KB. An empty policy is in general a valid policy but certain services
* (like Projects) might reject them.
* @param policy policy or {@code null} for none
*/
public GlobalSetPolicyRequest setPolicy(Policy policy) {
this.policy = policy;
return this;
}
@Override
public GlobalSetPolicyRequest set(String fieldName, Object value) {
return (GlobalSetPolicyRequest) super.set(fieldName, value);
}
@Override
public GlobalSetPolicyRequest clone() {
return (GlobalSetPolicyRequest) super.clone();
}
}
|
3e0a6ca9d50dca3ce74eacc52ea32b30dbe5a542 | 6,938 | java | Java | test/src/main/java/org/apache/accumulo/test/GetFileInfoBulkIT.java | isabella232/accumulo | 6fac8cbce9a0b180b8d21f3a20282ee2586e859e | [
"Apache-2.0"
] | 1 | 2019-02-27T13:15:14.000Z | 2019-02-27T13:15:14.000Z | test/src/main/java/org/apache/accumulo/test/GetFileInfoBulkIT.java | cloudera/accumulo | 6fac8cbce9a0b180b8d21f3a20282ee2586e859e | [
"Apache-2.0"
] | 1 | 2021-02-23T22:07:41.000Z | 2021-02-23T22:07:41.000Z | test/src/main/java/org/apache/accumulo/test/GetFileInfoBulkIT.java | dorateq/accumulo | c03d770d771e7a9f7d868a9525f275b9a1b80c46 | [
"Apache-2.0"
] | 3 | 2017-09-30T02:48:32.000Z | 2020-12-12T10:29:54.000Z | 40.337209 | 100 | 0.698616 | 4,412 | /*
* 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.accumulo.test;
import static org.apache.accumulo.fate.util.UtilWaitThread.sleepUninterruptibly;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.file.FileOperations;
import org.apache.accumulo.core.file.FileSKVWriter;
import org.apache.accumulo.core.file.rfile.RFile;
import org.apache.accumulo.core.master.thrift.MasterMonitorInfo;
import org.apache.accumulo.core.util.CachedConfiguration;
import org.apache.accumulo.core.util.Pair;
import org.apache.accumulo.minicluster.ServerType;
import org.apache.accumulo.minicluster.impl.MiniAccumuloConfigImpl;
import org.apache.accumulo.test.functional.ConfigurableMacBase;
import org.apache.accumulo.test.functional.FunctionalTestUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.junit.Test;
import com.google.gson.Gson;
// ACCUMULO-3949, ACCUMULO-3953
public class GetFileInfoBulkIT extends ConfigurableMacBase {
@Override
protected void configure(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
cfg.setNumTservers(1);
cfg.useMiniDFS(true);
cfg.setProperty(Property.GC_FILE_ARCHIVE, "false");
}
@SuppressWarnings("unchecked")
long getOpts() throws Exception {
String uri = getCluster().getMiniDfs().getHttpUri(0);
URL url = new URL(uri + "/jmx");
log.debug("Fetching web page " + url);
String jsonString = FunctionalTestUtils.readAll(url.openStream());
Gson gson = new Gson();
Map<Object,Object> jsonObject = (Map<Object,Object>) gson.fromJson(jsonString, Object.class);
List<Object> beans = (List<Object>) jsonObject.get("beans");
for (Object bean : beans) {
Map<Object,Object> map = (Map<Object,Object>) bean;
if (map.get("name").toString().equals("Hadoop:service=NameNode,name=NameNodeActivity")) {
return (long) Double.parseDouble(map.get("FileInfoOps").toString());
}
}
return 0;
}
@Test
public void test() throws Exception {
final Connector c = getConnector();
getCluster().getClusterControl().kill(ServerType.GARBAGE_COLLECTOR, "localhost");
final String tableName = getUniqueNames(1)[0];
c.tableOperations().create(tableName);
// turn off compactions
c.tableOperations().setProperty(tableName, Property.TABLE_MAJC_RATIO.getKey(), "2000");
c.tableOperations().setProperty(tableName, Property.TABLE_FILE_MAX.getKey(), "2000");
// splits to slow down bulk import
SortedSet<Text> splits = new TreeSet<>();
for (int i = 1; i < 0xf; i++) {
splits.add(new Text(Integer.toHexString(i)));
}
c.tableOperations().addSplits(tableName, splits);
MasterMonitorInfo stats = getCluster().getMasterMonitorInfo();
assertEquals(1, stats.tServerInfo.size());
log.info("Creating lots of bulk import files");
final FileSystem fs = getCluster().getFileSystem();
final Path basePath = getCluster().getTemporaryPath();
CachedConfiguration.setInstance(fs.getConf());
final Path base = new Path(basePath, "testBulkLoad" + tableName);
fs.delete(base, true);
fs.mkdirs(base);
ExecutorService es = Executors.newFixedThreadPool(5);
List<Future<Pair<String,String>>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final int which = i;
futures.add(es.submit(new Callable<Pair<String,String>>() {
@Override
public Pair<String,String> call() throws Exception {
Path bulkFailures = new Path(base, "failures" + which);
Path files = new Path(base, "files" + which);
fs.mkdirs(bulkFailures);
fs.mkdirs(files);
for (int i = 0; i < 100; i++) {
FileSKVWriter writer = FileOperations.getInstance().newWriterBuilder()
.forFile(files.toString() + "/bulk_" + i + "." + RFile.EXTENSION, fs, fs.getConf())
.withTableConfiguration(AccumuloConfiguration.getDefaultConfiguration()).build();
writer.startDefaultLocalityGroup();
for (int j = 0x100; j < 0xfff; j += 3) {
writer.append(new Key(Integer.toHexString(j)), new Value(new byte[0]));
}
writer.close();
}
return new Pair<>(files.toString(), bulkFailures.toString());
}
}));
}
List<Pair<String,String>> dirs = new ArrayList<>();
for (Future<Pair<String,String>> f : futures) {
dirs.add(f.get());
}
log.info("Importing");
long startOps = getOpts();
long now = System.currentTimeMillis();
List<Future<Object>> errs = new ArrayList<>();
for (Pair<String,String> entry : dirs) {
final String dir = entry.getFirst();
final String err = entry.getSecond();
errs.add(es.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
c.tableOperations().importDirectory(tableName, dir, err, false);
return null;
}
}));
}
for (Future<Object> err : errs) {
err.get();
}
es.shutdown();
es.awaitTermination(2, TimeUnit.MINUTES);
log.info(
String.format("Completed in %.2f seconds", (System.currentTimeMillis() - now) / 1000.));
sleepUninterruptibly(30, TimeUnit.SECONDS);
long getFileInfoOpts = getOpts() - startOps;
log.info("# opts: {}", getFileInfoOpts);
assertTrue("unexpected number of getFileOps", getFileInfoOpts < 2100 && getFileInfoOpts > 1000);
}
}
|
3e0a6d42bfd83541202019123812e7203cad8a2d | 891 | java | Java | IHMCHumanoidBehaviors/src/us/ihmc/humanoidBehaviors/behaviors/simpleBehaviors/SimpleDoNothingBehavior.java | wxmerkt/ihmc-open-robotics-software | 2c47c9a9bd999e7811038e99c3888683f9973a2a | [
"Apache-2.0"
] | null | null | null | IHMCHumanoidBehaviors/src/us/ihmc/humanoidBehaviors/behaviors/simpleBehaviors/SimpleDoNothingBehavior.java | wxmerkt/ihmc-open-robotics-software | 2c47c9a9bd999e7811038e99c3888683f9973a2a | [
"Apache-2.0"
] | null | null | null | IHMCHumanoidBehaviors/src/us/ihmc/humanoidBehaviors/behaviors/simpleBehaviors/SimpleDoNothingBehavior.java | wxmerkt/ihmc-open-robotics-software | 2c47c9a9bd999e7811038e99c3888683f9973a2a | [
"Apache-2.0"
] | null | null | null | 16.5 | 91 | 0.702581 | 4,413 | package us.ihmc.humanoidBehaviors.behaviors.simpleBehaviors;
import us.ihmc.humanoidBehaviors.behaviors.AbstractBehavior;
import us.ihmc.humanoidBehaviors.communication.CommunicationBridgeInterface;
public class SimpleDoNothingBehavior extends AbstractBehavior
{
public SimpleDoNothingBehavior(CommunicationBridgeInterface outgoingCommunicationBridge)
{
super(outgoingCommunicationBridge);
}
@Override
public void doControl()
{
}
@Override
public boolean isDone()
{
return true;
}
public boolean hasInputBeenSet()
{
return true;
}
@Override
public void onBehaviorEntered()
{
}
@Override
public void onBehaviorAborted()
{
}
@Override
public void onBehaviorPaused()
{
}
@Override
public void onBehaviorResumed()
{
}
@Override
public void onBehaviorExited()
{
}
}
|
3e0a6f59b4e1a0ffcbbbff35458e9700c00337a3 | 6,697 | java | Java | server/src/main/java/org/opensearch/common/lucene/search/function/CombineFunction.java | korpx-z/OpenSearch | dd9622fec64805141848537c0cf5265e8650ffb9 | [
"Apache-2.0"
] | 4,822 | 2021-04-12T15:03:57.000Z | 2022-03-31T23:37:49.000Z | server/src/main/java/org/opensearch/common/lucene/search/function/CombineFunction.java | korpx-z/OpenSearch | dd9622fec64805141848537c0cf5265e8650ffb9 | [
"Apache-2.0"
] | 2,146 | 2021-04-12T14:10:48.000Z | 2022-03-31T23:58:34.000Z | server/src/main/java/org/opensearch/common/lucene/search/function/CombineFunction.java | dlvenable/OpenSearch | 17e7a4962da9e85f30c16f552dafea00fd921649 | [
"Apache-2.0"
] | 593 | 2021-04-12T16:26:05.000Z | 2022-03-31T11:33:45.000Z | 36.2 | 138 | 0.620875 | 4,414 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.lucene.search.function;
import org.apache.lucene.search.Explanation;
import org.opensearch.common.io.stream.StreamInput;
import org.opensearch.common.io.stream.StreamOutput;
import org.opensearch.common.io.stream.Writeable;
import java.io.IOException;
import java.util.Locale;
public enum CombineFunction implements Writeable {
MULTIPLY {
@Override
public float combine(double queryScore, double funcScore, double maxBoost) {
return (float) (queryScore * Math.min(funcScore, maxBoost));
}
@Override
public Explanation explain(Explanation queryExpl, Explanation funcExpl, float maxBoost) {
Explanation boostExpl = Explanation.match(maxBoost, "maxBoost");
Explanation minExpl = Explanation.match(Math.min(funcExpl.getValue().floatValue(), maxBoost), "min of:", funcExpl, boostExpl);
return Explanation.match(
queryExpl.getValue().floatValue() * minExpl.getValue().floatValue(),
"function score, product of:",
queryExpl,
minExpl
);
}
},
REPLACE {
@Override
public float combine(double queryScore, double funcScore, double maxBoost) {
return (float) (Math.min(funcScore, maxBoost));
}
@Override
public Explanation explain(Explanation queryExpl, Explanation funcExpl, float maxBoost) {
Explanation boostExpl = Explanation.match(maxBoost, "maxBoost");
return Explanation.match(Math.min(funcExpl.getValue().floatValue(), maxBoost), "min of:", funcExpl, boostExpl);
}
},
SUM {
@Override
public float combine(double queryScore, double funcScore, double maxBoost) {
return (float) (queryScore + Math.min(funcScore, maxBoost));
}
@Override
public Explanation explain(Explanation queryExpl, Explanation funcExpl, float maxBoost) {
Explanation minExpl = Explanation.match(
Math.min(funcExpl.getValue().floatValue(), maxBoost),
"min of:",
funcExpl,
Explanation.match(maxBoost, "maxBoost")
);
return Explanation.match(
Math.min(funcExpl.getValue().floatValue(), maxBoost) + queryExpl.getValue().floatValue(),
"sum of",
queryExpl,
minExpl
);
}
},
AVG {
@Override
public float combine(double queryScore, double funcScore, double maxBoost) {
return (float) ((Math.min(funcScore, maxBoost) + queryScore) / 2.0);
}
@Override
public Explanation explain(Explanation queryExpl, Explanation funcExpl, float maxBoost) {
Explanation minExpl = Explanation.match(
Math.min(funcExpl.getValue().floatValue(), maxBoost),
"min of:",
funcExpl,
Explanation.match(maxBoost, "maxBoost")
);
return Explanation.match(
(float) ((Math.min(funcExpl.getValue().floatValue(), maxBoost) + queryExpl.getValue().floatValue()) / 2.0),
"avg of",
queryExpl,
minExpl
);
}
},
MIN {
@Override
public float combine(double queryScore, double funcScore, double maxBoost) {
return (float) (Math.min(queryScore, Math.min(funcScore, maxBoost)));
}
@Override
public Explanation explain(Explanation queryExpl, Explanation funcExpl, float maxBoost) {
Explanation innerMinExpl = Explanation.match(
Math.min(funcExpl.getValue().floatValue(), maxBoost),
"min of:",
funcExpl,
Explanation.match(maxBoost, "maxBoost")
);
return Explanation.match(
Math.min(Math.min(funcExpl.getValue().floatValue(), maxBoost), queryExpl.getValue().floatValue()),
"min of",
queryExpl,
innerMinExpl
);
}
},
MAX {
@Override
public float combine(double queryScore, double funcScore, double maxBoost) {
return (float) (Math.max(queryScore, Math.min(funcScore, maxBoost)));
}
@Override
public Explanation explain(Explanation queryExpl, Explanation funcExpl, float maxBoost) {
Explanation innerMinExpl = Explanation.match(
Math.min(funcExpl.getValue().floatValue(), maxBoost),
"min of:",
funcExpl,
Explanation.match(maxBoost, "maxBoost")
);
return Explanation.match(
Math.max(Math.min(funcExpl.getValue().floatValue(), maxBoost), queryExpl.getValue().floatValue()),
"max of:",
queryExpl,
innerMinExpl
);
}
};
public abstract float combine(double queryScore, double funcScore, double maxBoost);
public abstract Explanation explain(Explanation queryExpl, Explanation funcExpl, float maxBoost);
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeEnum(this);
}
public static CombineFunction readFromStream(StreamInput in) throws IOException {
return in.readEnum(CombineFunction.class);
}
public static CombineFunction fromString(String combineFunction) {
return valueOf(combineFunction.toUpperCase(Locale.ROOT));
}
}
|
3e0a7036ab13ea5665da6f643d93b93f1fb3fc24 | 2,165 | java | Java | src/game/entities/concrete/BishopEntity.java | danielricci/Chess | 5d3fd5939ad04c44104be321ea885c65cc72485e | [
"MIT"
] | 2 | 2019-06-24T23:20:55.000Z | 2020-03-02T13:18:09.000Z | src/game/entities/concrete/BishopEntity.java | danielricci/chess | 5d3fd5939ad04c44104be321ea885c65cc72485e | [
"MIT"
] | 84 | 2017-02-02T19:12:55.000Z | 2020-05-11T17:27:15.000Z | src/game/entities/concrete/BishopEntity.java | danielricci/Chess | 5d3fd5939ad04c44104be321ea885c65cc72485e | [
"MIT"
] | 1 | 2017-05-02T02:48:27.000Z | 2017-05-02T02:48:27.000Z | 36.79661 | 87 | 0.727775 | 4,415 | /**
* Daniel Ricci <hzdkv@example.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 game.entities.concrete;
import java.util.ArrayList;
import java.util.List;
import game.components.MovementComponent.EntityMovements;
import generated.DataLookup.DataLayerName;
/**
* This class represents a bishop in the chess game
*
* @author Daniel Ricci {@literal <hzdkv@example.com>}
*/
class BishopEntity extends AbstractChessEntity {
/**
* Constructs a new instance of this class type
*/
public BishopEntity() {
super(DataLayerName.BISHOP);
}
@Override public List<EntityMovements[]> getMovements() {
return new ArrayList<EntityMovements[]>() {{
add(new EntityMovements[] { EntityMovements.UP, EntityMovements.LEFT});
add(new EntityMovements[] { EntityMovements.UP, EntityMovements.RIGHT });
add(new EntityMovements[] { EntityMovements.DOWN, EntityMovements.LEFT });
add(new EntityMovements[] { EntityMovements.DOWN, EntityMovements.RIGHT });
}};
}
@Override public boolean isMovementContinuous() {
return true;
}
} |
3e0a70a3465722889a3aead733771eb8de66b827 | 921 | java | Java | src/main/java/com/hivemq/extensions/executor/task/PluginInTaskContext.java | ATAKing1023/hivemq-community-edition | 257d1b0f40b3df3d6982c3978bb39239b2e93024 | [
"Apache-2.0"
] | 776 | 2019-04-16T11:51:51.000Z | 2022-03-28T10:43:26.000Z | src/main/java/com/hivemq/extensions/executor/task/PluginInTaskContext.java | ATAKing1023/hivemq-community-edition | 257d1b0f40b3df3d6982c3978bb39239b2e93024 | [
"Apache-2.0"
] | 142 | 2019-04-17T01:31:13.000Z | 2022-03-16T02:08:10.000Z | src/main/java/com/hivemq/extensions/executor/task/PluginInTaskContext.java | ATAKing1023/hivemq-community-edition | 257d1b0f40b3df3d6982c3978bb39239b2e93024 | [
"Apache-2.0"
] | 230 | 2019-04-16T17:34:04.000Z | 2022-03-30T02:01:34.000Z | 31.758621 | 77 | 0.747014 | 4,416 | /*
* Copyright 2019-present HiveMQ GmbH
*
* 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.hivemq.extensions.executor.task;
import com.hivemq.extension.sdk.api.annotations.NotNull;
/**
* @author Georg Held
*/
public abstract class PluginInTaskContext extends AbstractPluginTaskContext {
protected PluginInTaskContext(final @NotNull String identifier) {
super(identifier);
}
}
|
3e0a715313d03d3c97ba6cee970c15e00192fb90 | 10,752 | java | Java | Studio/plugins/com.wizzer.mle.studio.framework/src/com/wizzer/mle/studio/framework/PathUtil.java | magic-lantern-studio/mle-studio | e962ecf8bc64a854fcd997196be1857d078a2781 | [
"MIT"
] | null | null | null | Studio/plugins/com.wizzer.mle.studio.framework/src/com/wizzer/mle/studio/framework/PathUtil.java | magic-lantern-studio/mle-studio | e962ecf8bc64a854fcd997196be1857d078a2781 | [
"MIT"
] | 28 | 2020-06-24T16:47:07.000Z | 2020-08-06T05:15:59.000Z | Studio/plugins/com.wizzer.mle.studio.framework/src/com/wizzer/mle/studio/framework/PathUtil.java | magic-lantern-studio/mle-studio | e962ecf8bc64a854fcd997196be1857d078a2781 | [
"MIT"
] | null | null | null | 27.569231 | 95 | 0.652437 | 4,417 | // COPYRIGHT_BEGIN
//
// The MIT License (MIT)
//
// Copyright (c) 2000-2020 Wizzer Works
//
// 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.
//
// COPYRIGHT_END
// Declare package.
package com.wizzer.mle.studio.framework;
// Import standard java packages.
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Hashtable;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
* This class provides some useful utility for managing directory path names.
*
* @author Mark S. Millard
*/
public class PathUtil
{
/*
* Various constants that might be found in pathnames.
*/
static private char TILDE = '~';
static private char SLASH = '/';
static private char DOLLAR = '$';
static private char NIL = '\0';
static private char PERCENT = '%';
static private String SPECIALS = "_";
static private char LBRACE = '{';
static private char RBRACE = '}';
/* The regex for one or more spaces. */
static final private String ONE_OR_MORE_SPACES = "\\s+";
// Some predefined, known environment variables.
static private Hashtable m_knownEnvVars = new Hashtable();
// A convenience value for appending paths with incremental values.
static private int m_filenameIndex = 0;
// Register the known environment variables.
static
{
String var = new String("MLE_HOME");
String value = new String("MleDefaultHomePath");
m_knownEnvVars.put(var,value);
}
static public String filenameExpand(String filename)
{
StringBuffer path = new StringBuffer(filename);
StringBuffer userName = null;
StringBuffer tildeName = null;
char curPtr;
StringBuffer varName, val;
int curIndex = 0;
int newIndex = 0;
StringBuffer retString = new StringBuffer(filename.length());
int retIndex = 0;
// Return an empty String if nothing to expand.
if (filename == null)
{
return new String("");
}
// Quick check for no work; if path doesn't start with '~' or contain a '$' or '%' character.
if ((filename.charAt(0) != TILDE) &&
(filename.indexOf(DOLLAR) == -1) &&
(filename.indexOf(PERCENT) == -1))
{
return new String(filename);
}
// If the first character is a tilde, process it. Note that embedded
// tildes are not allowed, as per C-shell semantics.
curPtr = path.charAt(curIndex);
if (curPtr == TILDE)
{
curIndex++;
if (curIndex < path.length())
{
curPtr = path.charAt(curIndex);
}
if ((curIndex == path.length()) || curPtr == SLASH)
{
tildeName = getHomeOfMe();
} else
{
if ((newIndex = path.toString().indexOf(SLASH)) == -1)
{
newIndex = path.length();
}
userName = new StringBuffer(path.substring(curIndex,newIndex));
tildeName = getHomeOfName(userName);
curIndex = newIndex;
}
retString.insert(retIndex,tildeName.toString());
retIndex += tildeName.toString().length();
//retString.insert(retIndex,SLASH);
//retIndex++;
}
// curIndex now points to the current scan point in the remaining input.
// Check for environment variables.
while (curIndex < path.length())
{
// Get the next character.
curPtr = path.charAt(curIndex);
if (curPtr == DOLLAR)
{
varName = new StringBuffer(path.length() - curIndex);
curIndex++;
curPtr = path.charAt(curIndex);
if (curPtr == LBRACE)
{
newIndex = 0;
curIndex++;
curPtr = path.charAt(curIndex);
while ((curPtr != NIL) && (curPtr != RBRACE))
{
varName.insert(newIndex,curPtr);
newIndex++;
curIndex++;
curPtr = path.charAt(curIndex);
}
if (curPtr != NIL)
{
curIndex++;
}
} else
{
newIndex = 0;
while ((curIndex < path.length()) && (isAlnum(curPtr) ||
(SPECIALS.indexOf(curPtr) != -1)))
{
curPtr = path.charAt(curIndex);
varName.insert(newIndex,curPtr);
newIndex++;
curIndex++;
}
}
// Terminate the variable name.
//varName.insert(newIndex,NIL);
// Get the system environment variable.
if ((val = getEnv(varName)) == null)
{
// If the undefined environment variable is in the known table,
// substitute the default value.
if (m_knownEnvVars.containsKey(varName.toString()))
{
val = new StringBuffer((String)m_knownEnvVars.get(varName.toString()));
retString.insert(retIndex,val.toString());
retIndex += val.toString().length();
//retString.insert(retIndex,SLASH);
//retIndex++;
}
} else
{
retString.insert(retIndex,val.toString());
retIndex += val.toString().length();
//retString.insert(retIndex,SLASH);
//retIndex++;
}
} else if ( curPtr == PERCENT )
{
char[] fmt = new char[3];
String buf;
curPtr = path.charAt(curIndex);
fmt[0] = curPtr; curIndex++;
curPtr = path.charAt(curIndex);
fmt[1] = curPtr; curIndex++;
fmt[2] = 0;
if ( fmt[1] == 'n' )
{
String value = String.valueOf(m_filenameIndex);
buf = new String(value);
} else
{
GregorianCalendar clock = new GregorianCalendar();
String timestamp = new String(
new Integer(clock.get(Calendar.DAY_OF_MONTH)).toString() +
new Integer(clock.get(Calendar.MONTH)).toString() +
new Integer(clock.get(Calendar.YEAR)).toString() +
new Integer(clock.get(Calendar.HOUR)).toString() +
new Integer(clock.get(Calendar.MINUTE)).toString() +
new Integer(clock.get(Calendar.SECOND)).toString()
);
buf = new String(timestamp);
}
retString.insert(retIndex,buf);
retIndex += buf.length();
} else
{
retString.insert(retIndex,curPtr);
retIndex++;
curIndex++;
}
}
// Terminate the return string.
//retString.insert(retIndex,NIL);
// Return the expanded file name.
return retString.toString();
}
// Get the system environment variable.
static private StringBuffer getEnv(StringBuffer var)
{
String varName = new String(var);
String value = System.getProperty(varName);
if (value != null)
return new StringBuffer(value);
else
return null;
}
// Get the home path for the user.
static private StringBuffer getHomeOfMe()
{
String home = System.getProperty("HOME");
if (home != null)
return new StringBuffer(home);
StringBuffer path = new StringBuffer(1);
path.insert(0,TILDE);
return path;
}
// Get the home path for the specified user.
// XXX - not yet supported.
static private StringBuffer getHomeOfName(StringBuffer user)
{
int len = 1 + user.length() + 1;
StringBuffer path = new StringBuffer(len);
path.insert(0,TILDE);
path.insert(1,user);
return path;
}
static public boolean isAlpha(char ch)
{
return Character.isLetter(ch);
}
static public boolean isAlnum(char ch)
{
return Character.isLetterOrDigit(ch);
}
static public boolean isLowerCase(char ch)
{
return Character.isLowerCase(ch);
}
static public char toLowerCase(char ch)
{
return (isUpperCase(ch) ? Character.toLowerCase(ch) : ch);
}
static public boolean isUpperCase(char ch)
{
return Character.isUpperCase(ch);
}
static public char toUpperCase(char ch)
{
return (isLowerCase(ch) ? Character.toUpperCase(ch) : ch);
}
static public boolean isSpace(char ch)
{
return Character.isSpace(ch);
}
static public boolean isDigit(char ch)
{
return Character.isDigit(ch);
}
static public void setFilenameIndexSet(int x)
{
m_filenameIndex = x;
}
static void incFilenameIndex()
{
m_filenameIndex++;
}
/**
* Converts a url to a file object.
*
* @param url The url of the resource.
* @return The corresponding file.
*/
static public File urlToFile(URL url)
{
final String noSpaces = url.toString().replaceAll(ONE_OR_MORE_SPACES, "%20");
File result = null;
try {
final URI uri = new URI(noSpaces);
result = new File(uri);
} catch (final URISyntaxException e) {
e.printStackTrace();
}
return result;
}
static public void main(String[] args)
{
// Test 1: simple path.
String filename = "C:/Users/msm/test/for/filename/expansion.txt";
String result = PathUtil.filenameExpand(filename);
System.out.println("Test 1: " + result);
// Test 2: expand tilde with path.
filename = "~/test/for/filename/expansion.txt";
result = PathUtil.filenameExpand(filename);
System.out.println("Test 2: " + result);
// Test 3: expand just environemnt variable.
filename = "$HOME";
result = PathUtil.filenameExpand(filename);
System.out.println("Test 3: " + result);
// Test 4: expand environemnt variable with path.
filename = "${HOME}/test/for/filename/expansion.txt";
result = PathUtil.filenameExpand(filename);
System.out.println("Test 4: " + result);
// Test 5: expand just tilde.
filename = "~";
result = PathUtil.filenameExpand(filename);
System.out.println("Test 5: " + result);
// Test 6: test for known default values.
filename = "$MLE_HOME";
result = PathUtil.filenameExpand(filename);
System.out.println("Test 6: " + result);
// Test 7: test for incremental filename generation.
for (int i = 0; i < 10; i++)
{
PathUtil.incFilenameIndex();
filename = "${MLE_HOME}/animation/file%n";
result = PathUtil.filenameExpand(filename);
System.out.println("Test 7: " + result);
}
// Test 8: test for timestamp filename generation.
filename = "${HOME}/animation/file%d";
result = PathUtil.filenameExpand(filename);
System.out.println("Test 8: " + result);
}
}
|
3e0a7170d8250ce425e6fa4360fc44f3ff5ad36d | 865 | java | Java | clover-core/src/main/java/com/atlassian/clover/api/optimization/package-info.java | andyglick/atlassian-clover-oss | d19472bdccb449537ba7d17ad7faea6c8df8f7f4 | [
"Apache-2.0"
] | 33 | 2019-11-19T10:18:02.000Z | 2022-03-08T03:43:51.000Z | clover-core/src/main/java/com/atlassian/clover/api/optimization/package-info.java | andyglick/atlassian-clover-oss | d19472bdccb449537ba7d17ad7faea6c8df8f7f4 | [
"Apache-2.0"
] | 150 | 2019-12-15T19:37:19.000Z | 2022-03-28T19:07:47.000Z | clover-core/src/main/java/com/atlassian/clover/api/optimization/package-info.java | andyglick/atlassian-clover-oss | d19472bdccb449537ba7d17ad7faea6c8df8f7f4 | [
"Apache-2.0"
] | 11 | 2020-02-04T02:33:25.000Z | 2022-03-31T12:24:32.000Z | 43.25 | 108 | 0.753757 | 4,418 | /**
* Provides classes to optimize a set of Tests programatically using Clover's Test Optimzation.
*
* A {@link com.atlassian.clover.api.optimization.TestOptimizer} takes an instance of
* {@link com.atlassian.clover.api.optimization.OptimizationOptions}.
*
* {@link com.atlassian.clover.api.optimization.OptimizationOptions} are built and configured using an
* {@link com.atlassian.clover.api.optimization.OptimizationOptions.Builder}.
*
* <h2> Example </h2>
* <pre>
* final Options options = new Options.Builder().snapshot(new File(".clover/clover.snapshot")).build();
* final Collection<Class> optimizedClasses = new TestOptimizer(options).optimize(unoptimizedClasses);
* // optimizedClasses will only contain those tests that cover code that has been modified.
* </pre>
*
*
* @since 2.6.0
*/
package com.atlassian.clover.api.optimization; |
3e0a7207ecdc8c1fcc75904855b0f932cc3945f8 | 154 | java | Java | src/Acquaintance/IOffer.java | jolluguy/GSEProjectF18 | 25a97b28eefa551889096e3a1edee549ce730d5c | [
"MIT"
] | 1 | 2018-05-21T12:26:19.000Z | 2018-05-21T12:26:19.000Z | src/Acquaintance/IOffer.java | jolluguy/GSEProjectF18 | 25a97b28eefa551889096e3a1edee549ce730d5c | [
"MIT"
] | 1 | 2018-05-24T12:54:22.000Z | 2018-05-24T12:54:22.000Z | src/Acquaintance/IOffer.java | jolluguy/GSEProjectF18 | 25a97b28eefa551889096e3a1edee549ce730d5c | [
"MIT"
] | 1 | 2018-05-17T13:03:34.000Z | 2018-05-17T13:03:34.000Z | 14 | 40 | 0.662338 | 4,419 | package Acquaintance;
/**
*
* @author Rasmus
*/
public interface IOffer {
public int getOfferID();
public String getOfferDescription();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.