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
3e1380bd3dbbf32b6fc360294404c2b2cf304c50
808
java
Java
flood-dynamic-thread-pool/src/main/java/cn/flood/threadpool/enums/QueueTypeEnum.java
mmdai/flood-dependencies
e95178f7fc71d2dd2a38789abcf3235692cf201f
[ "Apache-2.0" ]
1
2021-08-13T02:53:22.000Z
2021-08-13T02:53:22.000Z
flood-dynamic-thread-pool/src/main/java/cn/flood/threadpool/enums/QueueTypeEnum.java
mmdai/flood-dependencies
e95178f7fc71d2dd2a38789abcf3235692cf201f
[ "Apache-2.0" ]
null
null
null
flood-dynamic-thread-pool/src/main/java/cn/flood/threadpool/enums/QueueTypeEnum.java
mmdai/flood-dependencies
e95178f7fc71d2dd2a38789abcf3235692cf201f
[ "Apache-2.0" ]
null
null
null
22.444444
63
0.642327
8,236
package cn.flood.threadpool.enums; /** * 队列类型 * */ public enum QueueTypeEnum { LINKED_BLOCKING_QUEUE("LinkedBlockingQueue"), SYNCHRONOUS_QUEUE("SynchronousQueue"), ARRAY_BLOCKING_QUEUE("ArrayBlockingQueue"), DELAY_QUEUE("DelayQueue"), LINKED_TRANSFER_DEQUE("LinkedTransferQueue"), LINKED_BLOCKING_DEQUE("LinkedBlockingDeque"), PRIORITY_BLOCKING_QUEUE("PriorityBlockingQueue"); QueueTypeEnum(String type) { this.type = type; }; private String type; public String getType() { return type; } public static boolean exists(String type) { for (QueueTypeEnum typeEnum : QueueTypeEnum.values()) { if (typeEnum.getType().equals(type)) { return true; } } return false; } }
3e13818cfb86fa12e15fc8bafd79febb0bb35ead
1,850
java
Java
security/src/test/java/javacloud/framework/security/jwt/JwtTokenTest.java
javacloud-io/framework
79f1d6ebaff4851722a32e556477f918726b5c6f
[ "Apache-2.0" ]
null
null
null
security/src/test/java/javacloud/framework/security/jwt/JwtTokenTest.java
javacloud-io/framework
79f1d6ebaff4851722a32e556477f918726b5c6f
[ "Apache-2.0" ]
8
2019-11-13T09:13:14.000Z
2021-12-09T19:27:51.000Z
security/src/test/java/javacloud/framework/security/jwt/JwtTokenTest.java
javacloud-io/framework
79f1d6ebaff4851722a32e556477f918726b5c6f
[ "Apache-2.0" ]
null
null
null
29.83871
100
0.714054
8,237
package javacloud.framework.security.jwt; import javacloud.framework.json.impl.JacksonMapper; import javacloud.framework.util.Codecs; import javacloud.framework.util.Objects; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import junit.framework.TestCase; /** * * @author ho * */ public class JwtTokenTest extends TestCase { /** * */ public void testHS256() { JwtCodecs.HS256 hs256 = new JwtCodecs.HS256("a secret key".getBytes()); doTest(hs256, hs256); } /** * @throws NoSuchAlgorithmException * */ public void testRS256() throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair keyPair = keyGen.genKeyPair(); System.out.println("----PUBLIC KEY----"); System.out.println(Codecs.Base64Encoder.apply(keyPair.getPublic().getEncoded(), false, true)); System.out.println("----PRIVATE KEY----"); System.out.println(Codecs.Base64Encoder.apply(keyPair.getPrivate().getEncoded(), false, true)); JwtCodecs.RS256S signer = new JwtCodecs.RS256S(keyPair.getPrivate()); JwtCodecs.RS256V verifier = new JwtCodecs.RS256V(keyPair.getPublic()); doTest(signer, verifier); } /** * * @param jwtSigner * @param jwtVerifier */ private void doTest(JwtSigner jwtSigner, JwtVerifier jwtVerifier) { JwtCodecs jwtCodecs = new JwtCodecs(new JacksonMapper()); JwtToken token = new JwtToken("JWT", Objects.asMap("a", "a", "b", "b")); String stoken = jwtCodecs.encodeJWT(token, jwtSigner); System.out.println(jwtSigner.getAlgorithm() + " JWT: " + stoken); JwtToken tt = jwtCodecs.decodeJWT(stoken, jwtVerifier); assertEquals(token.getType(), tt.getType()); assertEquals(jwtSigner.getAlgorithm(), tt.getAlgorithm()); } }
3e13818fa984a32e9d4a96dcc04240c8e640b8d9
2,745
java
Java
src/main/java/com/github/blombler008/teamspeak3bot/commands/listeners/CommandPlugins.java
blombler008/Teamspeak-3-Bot
5f495ce28643a4ba0ad9e340a94cde54711581f8
[ "MIT" ]
1
2019-04-30T20:29:56.000Z
2019-04-30T20:29:56.000Z
src/main/java/com/github/blombler008/teamspeak3bot/commands/listeners/CommandPlugins.java
blombler008/Teamspeak-3-Bot
5f495ce28643a4ba0ad9e340a94cde54711581f8
[ "MIT" ]
1
2019-04-15T14:45:51.000Z
2019-04-30T19:06:33.000Z
src/main/java/com/github/blombler008/teamspeak3bot/commands/listeners/CommandPlugins.java
blombler008/Teamspeak-3-Bot
5f495ce28643a4ba0ad9e340a94cde54711581f8
[ "MIT" ]
1
2019-04-30T20:31:23.000Z
2019-04-30T20:31:23.000Z
42.230769
147
0.747541
8,238
/* * MIT License * * Copyright (c) 2019 blombler008 * * 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 com.github.blombler008.teamspeak3bot.commands.listeners; import com.github.blombler008.teamspeak3bot.Teamspeak3Bot; import com.github.blombler008.teamspeak3bot.commands.Command; import com.github.blombler008.teamspeak3bot.commands.CommandExecutor; import com.github.blombler008.teamspeak3bot.commands.CommandSender; import com.github.blombler008.teamspeak3bot.commands.ConsoleCommandSender; import com.github.blombler008.teamspeak3bot.plugins.JavaPlugin; import com.github.blombler008.teamspeak3bot.utils.Language; import com.github.theholywaffle.teamspeak3.api.wrapper.ClientInfo; import java.util.List; public class CommandPlugins extends CommandExecutor { @Override public void run(CommandSender source, Command cmd, String commandLabel, String[] args) { int id = cmd.getInvokerId(); ClientInfo sender = source.getInstance().getClient(id); if (source instanceof ConsoleCommandSender || sender.getUniqueIdentifier().equals(source.getInstance().getOwner().getUniqueIdentifier())) { sendPlugins(source, cmd.getChannelId(), id); } else { source.sendMessage(0, id, Language.get("nopermissions")); } } private void sendPlugins(CommandSender source, int ch, int cl) { source.sendMessage(ch, cl, "List of Plugins:"); getPlugins(source.getInstance()).forEach(o -> source.sendMessage(ch, cl, " - " + o.getName())); source.sendMessage(ch, cl, "End of List"); } private List<JavaPlugin> getPlugins(Teamspeak3Bot instance) { return instance.getPluginManager().getPlugins(); } }
3e1382e3953086b3e2dedc47e8d665a24c523774
4,433
java
Java
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/security/web/WeChatMpWebSecurityConfigurerAdapter.java
Hippoom/wechat-mp-starter
1a12d3d5be2788c9913cd8b423b1756bd5a73f2e
[ "MIT" ]
6
2017-08-11T02:50:08.000Z
2018-11-27T06:16:05.000Z
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/security/web/WeChatMpWebSecurityConfigurerAdapter.java
tanbinh123/wechat-mp-starter
1a12d3d5be2788c9913cd8b423b1756bd5a73f2e
[ "MIT" ]
1
2017-07-03T13:43:25.000Z
2017-07-03T14:07:43.000Z
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/security/web/WeChatMpWebSecurityConfigurerAdapter.java
tanbinh123/wechat-mp-starter
1a12d3d5be2788c9913cd8b423b1756bd5a73f2e
[ "MIT" ]
5
2017-07-03T06:51:02.000Z
2022-02-11T03:29:14.000Z
38.885965
109
0.746673
8,239
package com.github.hippoom.wechat.mp.autoconfigure.security.web; import static org.springframework.security.config.http.SessionCreationPolicy.IF_REQUIRED; import com.github.hippoom.wechat.mp.security.web.RestAuthenticationEntryPoint; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationProcessingFilter; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationSuccessHandler; import lombok.Getter; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.mp.api.WxMpService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.CsrfAuthenticationStrategy; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; @RequiredArgsConstructor public class WeChatMpWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Getter @Autowired private WxMpService wxMpService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { } @Override protected void configure(HttpSecurity http) throws Exception { configureAuthorizeRequests(defaultHttp(http)); } /** * subclass should override this to customize protected resources. * * @param httpSecurity see {@link HttpSecurity} * @throws Exception just throw */ protected void configureAuthorizeRequests(HttpSecurity httpSecurity) throws Exception { // @formatter:off httpSecurity .antMatcher("/**").authorizeRequests() .antMatchers("/rel/**/me").authenticated() .anyRequest().permitAll(); // @formatter:on } protected HttpSecurity defaultHttp(HttpSecurity http) throws Exception { // @formatter:off return http.sessionManagement().sessionCreationPolicy(IF_REQUIRED) .and() .csrf().requireCsrfProtectionMatcher(requireCsrfProtectionMatcher()) .csrfTokenRepository(csrfTokenRepository()) .and() .addFilterAfter(weChatMpOAuth2AuthenticationProcessingFilter(wxMpService), CsrfFilter.class) .exceptionHandling() .authenticationEntryPoint(restAuthenticationEntryPoint()) .and(); // @formatter:on } /** * subclass should override this to * customize {@link CsrfConfigurer#requireCsrfProtectionMatcher(RequestMatcher)}. * * @return see {@link RequestMatcher} */ protected RequestMatcher requireCsrfProtectionMatcher() { return new AntPathRequestMatcher("/rel/**/me"); } @Bean protected CsrfTokenRepository csrfTokenRepository() { return CookieCsrfTokenRepository.withHttpOnlyFalse(); } @Bean protected CsrfAuthenticationStrategy sessionAuthenticationStrategy() { return new CsrfAuthenticationStrategy(csrfTokenRepository()); } @Bean protected RestAuthenticationEntryPoint restAuthenticationEntryPoint() { return new RestAuthenticationEntryPoint(); } protected WeChatMpOAuth2AuthenticationProcessingFilter // @formatter:off weChatMpOAuth2AuthenticationProcessingFilter(WxMpService wxMpService) { WeChatMpOAuth2AuthenticationProcessingFilter filter = new WeChatMpOAuth2AuthenticationProcessingFilter("/wechat/oauth/token"); filter.setWxMpService(wxMpService); filter .setAuthenticationSuccessHandler(new WeChatMpOAuth2AuthenticationSuccessHandler()); filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy()); return filter; } // @formatter:on }
3e1384326135692639e6e60a8ba324988438108b
6,055
java
Java
FirstJavaProject/src/com/midnightnoon/pokrocily/strings/StringsAssignment.java
M4t2h3w/Learn2Code
6b06e32d745cc7dc5d6ee1bb91100b116b8a75ec
[ "MIT" ]
null
null
null
FirstJavaProject/src/com/midnightnoon/pokrocily/strings/StringsAssignment.java
M4t2h3w/Learn2Code
6b06e32d745cc7dc5d6ee1bb91100b116b8a75ec
[ "MIT" ]
null
null
null
FirstJavaProject/src/com/midnightnoon/pokrocily/strings/StringsAssignment.java
M4t2h3w/Learn2Code
6b06e32d745cc7dc5d6ee1bb91100b116b8a75ec
[ "MIT" ]
null
null
null
39.575163
113
0.552106
8,240
package com.midnightnoon.pokrocily.strings; public class StringsAssignment { public static void main(String[] args) { String inputString = "This is just a sample text, String, character, array or whatever."; String name = "Ethan Mathew Hunt"; String htmlTags = "[header]Ac mi[/header] massa ac [code]praesent eget[/code], " + "aliquam egestas suscipit, potenti massa, porttitor [link:www.learn2code.sk] " + "gravida quis ac velit facilisi[/link], imperdiet massa rhoncus felis arcu. " + "Ut nullam, mauris vitae, ligula quisque est."; System.out.println("First assignment:\t" + lastLetterUpperCase(inputString)); System.out.println("Second assignment:\t" + aToAt(inputString)); System.out.println("Third assignment:\t" + removeAllAfterLastComma(inputString)); System.out.println("Fourth assignment:\t" + removeTextBetweenCommas(inputString)); System.out.println("Fifth assignment: "); analyzeText(inputString); System.out.println("Sixth assignment:\t" + removeDotsAndCommasSecondLetterUpperCase(inputString)); System.out.println("Seventh assignment:\t" + initials(name)); System.out.println("Eighth assignment:\n" + reformatHTML(htmlTags)); } private static String reformatHTML(String htmlTags) { String result = htmlTags.replace("[code]", "<code>") .replace("[/code]", "</code>") .replace("[header]", "<h1>") .replace("[/header]", "</h1>") .replace("[link:www.learn2code.sk]", "< a href = \"www.learn2code.sk\">") .replace("[/link] ", "</a>"); return result; } private static String initials(String name) { String temp = ""; String result = ""; for (char ch : name.toCharArray()) { if (Character.isUpperCase(ch)) temp += ch; } for (int i = 0; i < temp.length(); i++) { if (i != temp.length()-1) { result += temp.charAt(i) + "."; } else result += temp.charAt(i); } return result; } private static String removeDotsAndCommasSecondLetterUpperCase(String inputString) { String result = ""; int counter = 0; for (int i = 0; i < inputString.length(); i++) { if (inputString.charAt(i) == ',' || inputString.charAt(i) == '.') { //result += inputString.charAt(i); } else if (Character.isLetter(inputString.charAt(i)) && counter % 2 == 0) { counter++; result += inputString.toLowerCase().charAt(i); } else if (Character.isLetter(inputString.charAt(i))) { counter++; result += inputString.toUpperCase().charAt(i); } else result += inputString.charAt(i); } return result; } private static void analyzeText(String inputString) { int wordsCounter = 0; int charCounter = 0; int spaceCounter = 0; int commasCounter = 0; int dotCounter = 0; int upperCaseLettersCounter = 0; for (int i = 0; i < inputString.length(); i++) { if (Character.isLetter(inputString.charAt(i))) charCounter++; else if (inputString.charAt(i) == ' ') spaceCounter++; else if (inputString.charAt(i) == ',') commasCounter++; else if (inputString.charAt(i) == '.') dotCounter++; if (Character.isUpperCase(inputString.charAt(i))) upperCaseLettersCounter++; if (Character.isLetter(inputString.charAt(i)) && i == inputString.length()-1) { wordsCounter++; } else if (Character.isLetter(inputString.charAt(i)) && !Character.isLetter(inputString.charAt(i+1))) { wordsCounter++; } } System.out.println("Input String: " + inputString); System.out.println("\tWords:\t" + wordsCounter); System.out.println("\tChars:\t" + charCounter); System.out.println("\tSpaces:\t" + spaceCounter); System.out.println("\tCommas:\t" + commasCounter); System.out.println("\tDots:\t" + dotCounter); System.out.println("\tCaps:\t" + upperCaseLettersCounter); } private static String removeTextBetweenCommas(String inputString) { String result = ""; int commaCounter = 0; for (int i = 0; i < inputString.length(); i++) { if (inputString.charAt(i) != ',' && (commaCounter == 0 || commaCounter >= 2)) { result += inputString.charAt(i); } else if (inputString.charAt(i) == ',') { commaCounter++; } if (inputString.charAt(i) == ',' && commaCounter > 2) { result += inputString.charAt(i); } } return result; } private static String removeAllAfterLastComma(String inputString) { if (inputString.lastIndexOf(',') != -1) { return inputString.substring(0, inputString.lastIndexOf(',')); } else return inputString; } private static String aToAt(String inputString) { return inputString.replace('a', '@'); } private static String lastLetterUpperCase(String inputString) { String result = ""; for(int i = 0; i < inputString.length();i++) { if(i == inputString.length()-1 && Character.isLetter(inputString.charAt(i))){ result += inputString.toUpperCase().charAt(i); } else if (Character.isLetter(inputString.charAt(i)) && !Character.isLetter(inputString.charAt(i+1))) { result += inputString.toUpperCase().charAt(i); } else result += inputString.toLowerCase().charAt(i); } return result; } }
3e13843dc3a008e26f22bc4ddfecdfb7320723e3
567
java
Java
schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n5/doma/core/container/GeoTouchesConverter.java
nagaikenshin/schemaOrg
4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8
[ "Apache-2.0" ]
1
2020-02-18T01:55:36.000Z
2020-02-18T01:55:36.000Z
schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n5/doma/core/container/GeoTouchesConverter.java
nagaikenshin/schemaOrg
4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8
[ "Apache-2.0" ]
null
null
null
schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n5/doma/core/container/GeoTouchesConverter.java
nagaikenshin/schemaOrg
4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8
[ "Apache-2.0" ]
null
null
null
24.652174
81
0.809524
8,241
package org.kyojo.schemaorg.m3n5.doma.core.container; import org.seasar.doma.ExternalDomain; import org.seasar.doma.jdbc.domain.DomainConverter; import org.kyojo.schemaorg.m3n5.core.impl.GEO_TOUCHES; import org.kyojo.schemaorg.m3n5.core.Container.GeoTouches; @ExternalDomain public class GeoTouchesConverter implements DomainConverter<GeoTouches, String> { @Override public String fromDomainToValue(GeoTouches domain) { return domain.getNativeValue(); } @Override public GeoTouches fromValueToDomain(String value) { return new GEO_TOUCHES(value); } }
3e1384439887c3dbc26163458e14e4bdd48271eb
389
java
Java
sample-activiti7-runtime-bundle/src/test/java/org/activiti/training/sampleactiviti7runtimebundle/SampleActiviti7RuntimeBundleApplicationTests.java
simonjwicks/activiti-test
1e20496bc58178ee47bf0516bbfe6712b9c8fd16
[ "Apache-2.0" ]
null
null
null
sample-activiti7-runtime-bundle/src/test/java/org/activiti/training/sampleactiviti7runtimebundle/SampleActiviti7RuntimeBundleApplicationTests.java
simonjwicks/activiti-test
1e20496bc58178ee47bf0516bbfe6712b9c8fd16
[ "Apache-2.0" ]
null
null
null
sample-activiti7-runtime-bundle/src/test/java/org/activiti/training/sampleactiviti7runtimebundle/SampleActiviti7RuntimeBundleApplicationTests.java
simonjwicks/activiti-test
1e20496bc58178ee47bf0516bbfe6712b9c8fd16
[ "Apache-2.0" ]
null
null
null
22.882353
60
0.832905
8,242
package org.activiti.training.sampleactiviti7runtimebundle; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SampleActiviti7RuntimeBundleApplicationTests { @Test public void contextLoads() { } }
3e138522d34fef925bbe6e18e452471ba8aa31e5
697
java
Java
fakeplayer-nms/1_16_R1/src/main/java/tr/com/infumia/dantero/fakeplayer/nms/v1_16_R1/FakeCreated1_16_R1.java
FurkanDGN/fakeplayer
b810c1b1eb91c8217322dbf1bfb80c1757703273
[ "MIT" ]
null
null
null
fakeplayer-nms/1_16_R1/src/main/java/tr/com/infumia/dantero/fakeplayer/nms/v1_16_R1/FakeCreated1_16_R1.java
FurkanDGN/fakeplayer
b810c1b1eb91c8217322dbf1bfb80c1757703273
[ "MIT" ]
null
null
null
fakeplayer-nms/1_16_R1/src/main/java/tr/com/infumia/dantero/fakeplayer/nms/v1_16_R1/FakeCreated1_16_R1.java
FurkanDGN/fakeplayer
b810c1b1eb91c8217322dbf1bfb80c1757703273
[ "MIT" ]
null
null
null
29.041667
111
0.714491
8,243
package tr.com.infumia.dantero.fakeplayer.nms.v1_16_R1; import tr.com.infumia.dantero.fakeplayer.api.FakeCreated; import tr.com.infumia.dantero.fakeplayer.api.INPC; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.craftbukkit.v1_16_R1.CraftWorld; import org.jetbrains.annotations.NotNull; public final class FakeCreated1_16_R1 implements FakeCreated { @NotNull @Override public INPC create(@NotNull final String name, @NotNull final String tabname, @NotNull final World world) { return new NPC( Bukkit.getServer().getOfflinePlayer(name).getUniqueId(), name, tabname, (CraftWorld) world ); } }
3e1385d0c3b48216ec61ff45d41cfe7aad7b38c2
4,021
java
Java
arrow/src/gen/java/org/bytedeco/arrow_dataset/HivePartitioning.java
oxisto/javacpp-presets
a70841e089cbe4269cd3e1b1e6de2005c3b4aa16
[ "Apache-2.0" ]
2,132
2015-01-14T10:02:38.000Z
2022-03-31T07:51:08.000Z
arrow/src/gen/java/org/bytedeco/arrow_dataset/HivePartitioning.java
oxisto/javacpp-presets
a70841e089cbe4269cd3e1b1e6de2005c3b4aa16
[ "Apache-2.0" ]
1,024
2015-01-11T18:35:03.000Z
2022-03-31T14:52:22.000Z
arrow/src/gen/java/org/bytedeco/arrow_dataset/HivePartitioning.java
oxisto/javacpp-presets
a70841e089cbe4269cd3e1b1e6de2005c3b4aa16
[ "Apache-2.0" ]
759
2015-01-15T08:41:48.000Z
2022-03-29T17:05:57.000Z
61.861538
185
0.722954
8,244
// Targeted by JavaCPP version 1.5.7-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.arrow_dataset; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import org.bytedeco.arrow.*; import static org.bytedeco.arrow.global.arrow.*; import org.bytedeco.parquet.*; import static org.bytedeco.arrow.global.parquet.*; import static org.bytedeco.arrow.global.arrow_dataset.*; /** \brief Multi-level, directory based partitioning * originating from Apache Hive with all data files stored in the * leaf directories. Data is partitioned by static values of a * particular column in the schema. Partition keys are represented in * the form $key=$value in directory names. * Field order is ignored, as are missing or unrecognized field names. * * For example given schema<year:int16, month:int8, day:int8> the path * "/day=321/ignored=3.4/year=2009" parses to ("year"_ == 2009 and "day"_ == 321) */ @Namespace("arrow::dataset") @NoOffset @Properties(inherit = org.bytedeco.arrow.presets.arrow_dataset.class) public class HivePartitioning extends KeyValuePartitioning { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public HivePartitioning(Pointer p) { super(p); } /** If a field in schema is of dictionary type, the corresponding element of * dictionaries must be contain the dictionary of values for that field. */ public HivePartitioning(@SharedPtr @ByVal Schema schema, @ByVal(nullValue = "arrow::ArrayVector{}") ArrayVector dictionaries, @StdString String null_fallback/*=arrow::dataset::kDefaultHiveNullFallback*/) { super((Pointer)null); allocate(schema, dictionaries, null_fallback); } private native void allocate(@SharedPtr @ByVal Schema schema, @ByVal(nullValue = "arrow::ArrayVector{}") ArrayVector dictionaries, @StdString String null_fallback/*=arrow::dataset::kDefaultHiveNullFallback*/); public HivePartitioning(@SharedPtr @ByVal Schema schema) { super((Pointer)null); allocate(schema); } private native void allocate(@SharedPtr @ByVal Schema schema); public HivePartitioning(@SharedPtr @ByVal Schema schema, @ByVal(nullValue = "arrow::ArrayVector{}") ArrayVector dictionaries, @StdString BytePointer null_fallback/*=arrow::dataset::kDefaultHiveNullFallback*/) { super((Pointer)null); allocate(schema, dictionaries, null_fallback); } private native void allocate(@SharedPtr @ByVal Schema schema, @ByVal(nullValue = "arrow::ArrayVector{}") ArrayVector dictionaries, @StdString BytePointer null_fallback/*=arrow::dataset::kDefaultHiveNullFallback*/); public HivePartitioning(@SharedPtr @ByVal Schema schema, @ByVal ArrayVector dictionaries, @ByVal HivePartitioningOptions options) { super((Pointer)null); allocate(schema, dictionaries, options); } private native void allocate(@SharedPtr @ByVal Schema schema, @ByVal ArrayVector dictionaries, @ByVal HivePartitioningOptions options); public native @StdString String type_name(); public native @StdString String null_fallback(); public native @Const @ByRef HivePartitioningOptions options(); public static native @ByVal KeyOptionalResult ParseKey(@StdString String segment, @Const @ByRef HivePartitioningOptions options); public static native @ByVal KeyOptionalResult ParseKey(@StdString BytePointer segment, @Const @ByRef HivePartitioningOptions options); /** \brief Create a factory for a hive partitioning. */ public static native @SharedPtr PartitioningFactory MakeFactory( @ByVal(nullValue = "arrow::dataset::HivePartitioningFactoryOptions{}") HivePartitioningFactoryOptions arg0); public static native @SharedPtr PartitioningFactory MakeFactory(); }
3e1387405f162e296c603a3b7ba32bed4567d0e2
2,352
java
Java
src/sos/base/util/namayangar/sosLayer/fire/EstimateFireSiteBuildings.java
alim1369/sos
098b2922229ec987d3dd7ac28c9c22e67338dda5
[ "Apache-2.0" ]
2
2017-09-27T01:41:30.000Z
2017-11-22T01:43:24.000Z
src/sos/base/util/namayangar/sosLayer/fire/EstimateFireSiteBuildings.java
alim1369/sos
098b2922229ec987d3dd7ac28c9c22e67338dda5
[ "Apache-2.0" ]
1
2019-01-15T15:24:56.000Z
2019-01-15T15:24:56.000Z
src/sos/base/util/namayangar/sosLayer/fire/EstimateFireSiteBuildings.java
alim1369/sos
098b2922229ec987d3dd7ac28c9c22e67338dda5
[ "Apache-2.0" ]
null
null
null
30.947368
248
0.759779
8,245
package sos.base.util.namayangar.sosLayer.fire; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Shape; import java.util.ArrayList; import javax.swing.JComponent; import rescuecore2.misc.Pair; import sos.base.entities.Building; import sos.base.entities.Human; import sos.base.sosFireZone.SOSAbstractFireZone; import sos.base.sosFireZone.SOSEstimatedFireZone; import sos.base.sosFireZone.SOSRealFireZone; import sos.base.util.namayangar.NamayangarUtils; import sos.base.util.namayangar.misc.gui.ScreenTransform; import sos.base.util.namayangar.sosLayer.other.SOSAbstractToolsLayer; import sos.base.util.namayangar.tools.LayerType; public class EstimateFireSiteBuildings extends SOSAbstractToolsLayer<SOSAbstractFireZone> { private Color[] colors = { Color.red, Color.blue, Color.black, Color.cyan, Color.green, Color.orange, Color.yellow }; public EstimateFireSiteBuildings() { super(SOSAbstractFireZone.class); setVisible(false); } @Override public int getZIndex() { return 10; } @Override protected void makeEntities() { ArrayList<Pair<ArrayList<SOSRealFireZone>, SOSEstimatedFireZone>> x = (model()).getFireSites(); ArrayList<SOSAbstractFireZone> sss = new ArrayList<SOSAbstractFireZone>(); for (Pair<ArrayList<SOSRealFireZone>, SOSEstimatedFireZone> paf : x) sss.add(paf.second()); setEntities(sss); } @Override public JComponent getGUIComponent() { return null; } @Override public boolean isValid() { return model().me() instanceof Human; } @Override public ArrayList<Pair<String, String>> sosInspect(SOSAbstractFireZone entity) { return null; } @Override protected Shape render(SOSAbstractFireZone entity, Graphics2D g, ScreenTransform transform) { g.setColor(colors[entity.getIndex() % 6]); for (Building b : (entity).getAllBuildings()) { Shape shape = NamayangarUtils.transformShape(b, transform); g.fill(shape); } g.setColor(Color.yellow); g.drawString("ID = " + entity.getIndex() + " (isDisable=" + entity.isDisable() + "+isEx=" + entity.isExtinguishable() + "isEst=" + entity.isEstimating() + ") ", transform.xToScreen(entity.getCenterX()), transform.yToScreen(entity.getCenterY())); NamayangarUtils.drawShape(entity.getConvex().getShape(), g, transform); return null; } @Override public LayerType getLayerType() { return LayerType.Fire; } }
3e1387cd3cdf6a12297382009db546942e4bc206
3,451
java
Java
venus-biz/src/main/java/com/richur/venus/biz/util/leetcode/L006ZConversion.java
RichurLiu/venus
b87bbb63326c1f43eb4855d040f6e90fbaad5bd5
[ "Apache-2.0" ]
null
null
null
venus-biz/src/main/java/com/richur/venus/biz/util/leetcode/L006ZConversion.java
RichurLiu/venus
b87bbb63326c1f43eb4855d040f6e90fbaad5bd5
[ "Apache-2.0" ]
null
null
null
venus-biz/src/main/java/com/richur/venus/biz/util/leetcode/L006ZConversion.java
RichurLiu/venus
b87bbb63326c1f43eb4855d040f6e90fbaad5bd5
[ "Apache-2.0" ]
null
null
null
31.09009
61
0.363952
8,246
package com.richur.venus.biz.util.leetcode; import java.sql.SQLOutput; import java.util.Arrays; /** * @Author richur * @Date 2019/10/16 8:53 PM * https://leetcode-cn.com/problems/zigzag-conversion/ * 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。 * 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下: * L C I R * E T O E S I I G * E D H N */ public class L006ZConversion { public static void main(String[] args) { String s = "AB"; int numRows = 1; convert(s, numRows); } public static void convert(String s, int numRows) { char[] chars = s.toCharArray(); // char[] newChar = new char[chars.length]; String str = ""; if(numRows == 1 || numRows == 2){ // return s; } if(numRows == 2){ for(int j=0; j<chars.length; j++){ if(2*j >= chars.length){ break; } str +=chars[2*j]; } for(int j=0; j<chars.length; j++){ if(2*j+1 >= chars.length){ break; } str +=chars[2*j+1]; } } // int count = 0; for(int i=0; i< numRows; i++){ int flag = 0; int index = 0; for(int j=0; j<chars.length; j++){ if(i == 0 || i == numRows-1){ index = i + j * 2 * (numRows-1); if(index >= chars.length){ break; } else { // System.out.print(index); // System.out.print(chars[index]); str+=chars[index]; // newChar[count++]= chars[index]; // for(int t=0; t< numRows - 2; t++){ // System.out.print(" "); // } } } else { if(index <= 0){ index = i; } else { flag = 2 * (numRows - 1) - flag; index = flag + index; } if(index >= chars.length){ break; } for(int t = 0; t < flag-numRows +1; t++){ System.out.print(" "); } // System.out.print(chars[index]); // newChar[count++] = chars[index]; str+=chars[index]; // System.out.print(index); if(index < numRows){ flag = 2 * (numRows - i - 1); } else { flag = 2 * (numRows - 1) - flag; } index = flag + index; if(index >= chars.length){ break; } // for(int t=0; t < flag-numRows+1; t++){ // System.out.print(" "); // } // System.out.print(index); // System.out.print(chars[index]); // newChar[count++] = chars[index]; str+=chars[index]; } } // System.out.println(); } // System.out.println(Arrays.toString(newChar)); System.out.println(str); // return; } }
3e13885492a2fcd2a3bc0674db9bf77def577edf
32,611
java
Java
core/src/main/java/com/dtolabs/rundeck/core/plugins/JarPluginProviderLoader.java
yuji901jp/rundeck
22a4454cd3d82181f8ff782058eae958a0c9adf0
[ "Apache-2.0" ]
2
2021-03-03T08:59:35.000Z
2021-03-03T08:59:42.000Z
core/src/main/java/com/dtolabs/rundeck/core/plugins/JarPluginProviderLoader.java
yuji901jp/rundeck
22a4454cd3d82181f8ff782058eae958a0c9adf0
[ "Apache-2.0" ]
null
null
null
core/src/main/java/com/dtolabs/rundeck/core/plugins/JarPluginProviderLoader.java
yuji901jp/rundeck
22a4454cd3d82181f8ff782058eae958a0c9adf0
[ "Apache-2.0" ]
2
2018-03-29T07:58:50.000Z
2018-04-06T08:32:21.000Z
35.727273
130
0.599804
8,247
/* * Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * JarFileProviderLoader.java * * User: Greg Schueler <a href="mailto:lyhxr@example.com">greg@dtosolutions.com</a> * Created: 4/12/11 7:29 PM * */ package com.dtolabs.rundeck.core.plugins; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import org.apache.log4j.Logger; import com.dtolabs.rundeck.core.execution.service.ProviderCreationException; import com.dtolabs.rundeck.core.execution.service.ProviderLoaderException; import com.dtolabs.rundeck.core.utils.FileUtils; import com.dtolabs.rundeck.core.utils.ZipUtil; import com.dtolabs.rundeck.core.utils.cache.FileCache; /** * JarPluginProviderLoader can load jar plugin files as provider instances. * * Calls to load a provider instance should be synchronized as this class will * perform file copy operations. * * @author Greg Schueler <a href="mailto:lyhxr@example.com">greg@dtosolutions.com</a> */ class JarPluginProviderLoader implements ProviderLoader, FileCache.Expireable, PluginResourceLoader, PluginMetadata, Closeable { public static final String RESOURCES_DIR_DEFAULT = "resources"; private static Logger log = Logger.getLogger(JarPluginProviderLoader.class.getName()); public static final String RUNDECK_PLUGIN_ARCHIVE = "Rundeck-Plugin-Archive"; public static final String RUNDECK_PLUGIN_CLASSNAMES = "Rundeck-Plugin-Classnames"; public static final String RUNDECK_PLUGIN_RESOURCES = "Rundeck-Plugin-Resources"; public static final String RUNDECK_PLUGIN_RESOURCES_DIR = "Rundeck-Plugin-Resources-Dir"; public static final String RUNDECK_PLUGIN_LIBS = "Rundeck-Plugin-Libs"; public static final String JAR_PLUGIN_VERSION = "1.1"; public static final String JAR_PLUGIN_VERSION_1_2 = "1.2"; public static final VersionCompare SUPPORTS_RESOURCES_PLUGIN_VERSION = VersionCompare.forString( JAR_PLUGIN_VERSION_1_2); public static final VersionCompare LOWEST_JAR_PLUGIN_VERSION = VersionCompare.forString(JAR_PLUGIN_VERSION); public static final String RUNDECK_PLUGIN_VERSION = "Rundeck-Plugin-Version"; public static final String RUNDECK_PLUGIN_FILE_VERSION = "Rundeck-Plugin-File-Version"; public static final String RUNDECK_PLUGIN_AUTHOR = "Rundeck-Plugin-Author"; public static final String RUNDECK_PLUGIN_URL = "Rundeck-Plugin-URL"; public static final String RUNDECK_PLUGIN_DATE = "Rundeck-Plugin-Date"; public static final String RUNDECK_PLUGIN_LIBS_LOAD_FIRST = "Rundeck-Plugin-Libs-Load-First"; public static final String CACHED_JAR_TIMESTAMP_FORMAT = "yyyyMMddHHmmssSSS"; private final File pluginJar; private final File pluginJarCacheDirectory; private final File cachedir; private final boolean loadLibsFirst; private final DateFormat cachedJarTimestampFormatter = new SimpleDateFormat(CACHED_JAR_TIMESTAMP_FORMAT); @SuppressWarnings("rawtypes") private Map<ProviderIdent, Class> pluginProviderDefs = new HashMap<ProviderIdent, Class>(); private AtomicInteger loadCount = new AtomicInteger(); public JarPluginProviderLoader(final File pluginJar, final File pluginJarCacheDirectory, final File cachedir) { this(pluginJar, pluginJarCacheDirectory, cachedir, true); } public JarPluginProviderLoader(final File pluginJar, final File pluginJarCacheDirectory, final File cachedir, final boolean loadLibsFirst) { if (null == pluginJar) { throw new NullPointerException("Expected non-null plugin jar argument."); } if (!pluginJar.exists()) { throw new IllegalArgumentException("File does not exist: " + pluginJar); } if (!pluginJar.isFile()) { throw new IllegalArgumentException("Not a file: " + pluginJar); } this.pluginJar = pluginJar; this.pluginJarCacheDirectory = pluginJarCacheDirectory; this.cachedir = cachedir; this.loadLibsFirst = loadLibsFirst; } private boolean supportsResources(final String pluginVersion) { return VersionCompare.forString(pluginVersion).atLeast(SUPPORTS_RESOURCES_PLUGIN_VERSION); } @Override public List<String> listResources() throws PluginException, IOException { if (supportsResources(getPluginVersion())) { return getCachedJar().resourcesLoader.listResources(); } return null; } @Override public InputStream openResourceStreamFor(final String path) throws PluginException, IOException { if (supportsResources(getPluginVersion())) { return getCachedJar().resourcesLoader.openResourceStreamFor(path); } return null; } private final Closeable dereferencer = new Closeable() { @Override public void close() throws IOException { removeReference(); } }; @Override public <T> CloseableProvider<T> loadCloseable(final PluggableService<T> service, final String providerName) throws ProviderLoaderException { addReference(); return Closeables.closeableProvider(load(service, providerName), Closeables.closeOnce(dereferencer)); } /** * Load provider instance for the service */ @SuppressWarnings("unchecked") public synchronized <T> T load(final PluggableService<T> service, final String providerName) throws ProviderLoaderException { final ProviderIdent ident = new ProviderIdent(service.getName(), providerName); debug("loadInstance for " + ident + ": " + pluginJar); if (null == pluginProviderDefs.get(ident)) { final String[] strings = getClassnames(); for (final String classname : strings) { final Class<?> cls; try { cls = loadClass(classname); if (matchesProviderDeclaration(ident, cls)) { pluginProviderDefs.put(ident, cls); } } catch (PluginException e) { log.error("Failed to load class from " + pluginJar + ": classname: " + classname + ": " + e.getMessage()); } } } final Class<T> cls = pluginProviderDefs.get(ident); if (null != cls) { try { return createProviderForClass(service, cls); } catch (PluginException e) { throw new ProviderLoaderException(e, service.getName(), providerName); } } return null; } /** * Return true if the ident matches the Plugin annotation for the class */ static boolean matchesProviderDeclaration(final ProviderIdent ident, final Class<?> cls) throws PluginException { final Plugin annotation = getPluginMetadata(cls); return ident.getFirst().equals(annotation.service()) && ident.getSecond().equals(annotation.name()); } /** * Return true if the ident matches the Plugin annotation for the class */ static ProviderIdent getProviderDeclaration(final Class<?> cls) throws PluginException { final Plugin annotation = getPluginMetadata(cls); return new ProviderIdent(annotation.service(), annotation.name()); } Attributes mainAttributes; /** * Get the declared list of provider classnames for the file */ public String[] getClassnames() { final Attributes attributes = getMainAttributes(); if (null == attributes) { return null; } final String value = attributes.getValue(RUNDECK_PLUGIN_CLASSNAMES); if (null == value) { return null; } return value.split(","); } private String getResourcesBasePath() { final Attributes attributes = getMainAttributes(); if (null != attributes) { final String dir = attributes.getValue(RUNDECK_PLUGIN_RESOURCES_DIR); if (null != dir) { //list resources in the dir of the jar return dir; } } return RESOURCES_DIR_DEFAULT; } private List<String> getPluginResourcesList() { final Attributes attributes = getMainAttributes(); if (null != attributes) { final String value = attributes.getValue(RUNDECK_PLUGIN_RESOURCES); if (null != value) { return Arrays.asList(value.split(" *, *")); } } return null; } /** * Get the version of the plugin, not the file version * * @return */ public String getPluginVersion() { Attributes mainAttributes = getMainAttributes(); return mainAttributes.getValue(RUNDECK_PLUGIN_VERSION); } /** * return the main attributes from the jar manifest */ private Attributes getMainAttributes() { if (null == mainAttributes) { mainAttributes = getJarMainAttributes(pluginJar); } return mainAttributes; } /** * Get the main attributes for the jar file */ private static Attributes getJarMainAttributes(final File file) { debug("getJarMainAttributes: " + file); try { try(final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(file))){ return jarInputStream.getManifest().getMainAttributes(); } } catch (IOException e) { return null; } } /** * Attempt to create an instance of thea provider for the given service * * @param cls class * @return created instance */ static <T,X extends T> T createProviderForClass(final PluggableService<T> service, final Class<X> cls) throws PluginException, ProviderCreationException { debug("Try loading provider " + cls.getName()); final Plugin annotation = getPluginMetadata(cls); final String pluginname = annotation.name(); if (!service.isValidProviderClass(cls)) { throw new PluginException("Class " + cls.getName() + " was not a valid plugin class for service: " + service.getName() + ". Expected class " + cls.getName() + ", with a public constructor with no parameter"); } debug("Succeeded loading plugin " + cls.getName() + " for service: " + service.getName()); return service.createProviderInstance(cls, pluginname); } private static void debug(final String s) { if (log.isDebugEnabled()) { log.debug(s); } } /** * Get the Plugin annotation for the class */ static Plugin getPluginMetadata(final Class<?> cls) throws PluginException { // try to get plugin provider name final String pluginname; if (!cls.isAnnotationPresent(Plugin.class)) { throw new PluginException("No Plugin annotation was found for the class: " + cls.getName()); } final Plugin annotation = (Plugin) cls.getAnnotation(Plugin.class); pluginname = annotation.name(); if (null == pluginname || "".equals(pluginname)) { throw new PluginException("Plugin annotation 'name' cannot be empty for the class: " + cls.getName()); } // get service name from annotation final String servicename = annotation.service(); if (null == servicename || "".equals(servicename)) { throw new PluginException("Plugin annotation 'service' cannot be empty for the class: " + cls.getName()); } return annotation; } private Map<String, Class<?>> classCache = new HashMap<String, Class<?>>(); /** * @return true if the other jar is a copy of the pluginJar based on names returned by generateCachedJarName */ protected boolean isEquivalentPluginJar(File other) { return other.getName().replaceFirst("\\d+-\\d+-", "").equals(pluginJar.getName()); } static final AtomicLong counter = new AtomicLong(0); /** * @return a generated name for the pluginJar using the last modified timestamp */ protected String generateCachedJarIdentity() { Date mtime = new Date(pluginJar.lastModified()); return String.format( "%s-%d", cachedJarTimestampFormatter.format(mtime), counter.getAndIncrement() ); } /** * @return a generated name for the pluginJar using the last modified timestamp */ protected String generateCachedJarName(String ident) { return String.format( "%s-%s", ident, pluginJar.getName() ); } /** * @return a generated name for the pluginJar using the last modified timestamp */ protected File generateCachedJarDir(String ident) { File dir = new File(getFileCacheDir(), ident); if (!dir.mkdirs()) { debug("Could not create dir for cachedjar libs: " + dir); } return dir; } /** * Creates a single cached version of the pluginJar located within pluginJarCacheDirectory * deleting all existing versions of pluginJar * @param jarName */ protected File createCachedJar(final File dir, final String jarName) throws PluginException { File cachedJar; try { cachedJar = new File(dir, jarName); cachedJar.deleteOnExit(); FileUtils.fileCopy(pluginJar, cachedJar, true); } catch (IOException e) { throw new PluginException(e); } return cachedJar; } /** * Load a class from the jar file by name */ private Class<?> loadClass(final String classname) throws PluginException { if (null == classname) { throw new IllegalArgumentException("A null java class name was specified."); } if (null != classCache.get(classname)) { return classCache.get(classname); } CachedJar cachedJar1 = getCachedJar(); debug("loadClass! " + classname + ": " + cachedJar1.getCachedJar()); final Class<?> cls; final URLClassLoader urlClassLoader = cachedJar1.getClassLoader(); try { cls = Class.forName(classname, true, urlClassLoader); classCache.put(classname, cls); } catch (ClassNotFoundException e) { throw new PluginException("Class not found: " + classname, e); } catch (Throwable t) { throw new PluginException("Error loading class: " + classname, t); } return cls; } private CachedJar cachedJar; private Date loadedDate = null; private synchronized JarPluginProviderLoader.CachedJar getCachedJar() throws PluginException { if (null == cachedJar) { synchronized (this) { if (null == cachedJar) { this.loadedDate = new Date(); String itemIdent = generateCachedJarIdentity(); String jarName = generateCachedJarName(itemIdent); File dir = generateCachedJarDir(itemIdent); File cachedJar = createCachedJar(dir, jarName); // if jar manifest declares secondary lib deps, expand lib into cachedir, and setup classloader // to use the libs Collection<File> extlibs = null; try { extlibs = extractDependentLibs(dir); } catch (IOException e) { throw new PluginException("Unable to expand plugin libs: " + e.getMessage(), e); } ZipResourceLoader loader = null; if (supportsResources(getPluginVersion())) { loader = new ZipResourceLoader( new File(dir, "resources"), cachedJar, getPluginResourcesList(), getResourcesBasePath() ); try { loader.extractResources(); } catch (IOException e) { throw new PluginException("Unable to expand plugin resources: " + e.getMessage(), e); } } this.cachedJar = new CachedJar(dir, cachedJar, extlibs, loader); } } } return cachedJar; } /** * Extract the dependent libs and return the extracted jar files * * @return the collection of extracted files */ private Collection<File> extractDependentLibs(final File cachedir) throws IOException { final Attributes attributes = getMainAttributes(); if (null == attributes) { debug("no manifest attributes"); return null; } final ArrayList<File> files = new ArrayList<File>(); final String libs = attributes.getValue(RUNDECK_PLUGIN_LIBS); if (null != libs) { debug("jar libs listed: " + libs + " for file: " + pluginJar); if (!cachedir.isDirectory()) { if (!cachedir.mkdirs()) { debug("Failed to create cachedJar dir for dependent libs: " + cachedir); } } final String[] libsarr = libs.split(" "); extractJarContents(libsarr, cachedir); for (final String s : libsarr) { File libFile = new File(cachedir, s); libFile.deleteOnExit(); files.add(libFile); } } else { debug("no jar libs listed in manifest: " + pluginJar); } return files; } /** * Extract specific entries from the jar to a destination directory. Creates the * destination directory if it does not exist * * @param entries * the entries to extract * @param destdir * destination directory */ private void extractJarContents(final String[] entries, final File destdir) throws IOException { if (!destdir.exists()) { if (!destdir.mkdir()) { log.warn("Unable to create cache dir for plugin: " + destdir.getAbsolutePath()); } } debug("extracting lib files from jar: " + pluginJar); for (final String path : entries) { debug("Expand zip " + pluginJar.getAbsolutePath() + " to dir: " + destdir + ", file: " + path); ZipUtil.extractZipFile(pluginJar.getAbsolutePath(), destdir, path); } } /** * Basename of the file */ String getFileBasename() { return basename(pluginJar); } /** * Get basename of a file */ private static String basename(final File file) { final String name = file.getName(); return name.substring(0, name.lastIndexOf(".")); } /** * Get the cache dir for use for this file */ File getFileCacheDir() { return new File(cachedir, getFileBasename()); } /** * Return true if the file has a class that provides the ident. */ public synchronized boolean isLoaderFor(final ProviderIdent ident) { final String[] strings = getClassnames(); for (final String classname : strings) { try { if (matchesProviderDeclaration(ident, loadClass(classname))) { return true; } } catch (PluginException e) { e.printStackTrace(); } } return false; } public synchronized List<ProviderIdent> listProviders() { final ArrayList<ProviderIdent> providerIdents = new ArrayList<ProviderIdent>(); final String[] strings = getClassnames(); for (final String classname : strings) { try { providerIdents.add(getProviderDeclaration(loadClass(classname))); } catch (PluginException e) { e.printStackTrace(); } } return providerIdents; } private synchronized int addReference() { return loadCount.incrementAndGet(); } private synchronized int removeReference() { int i = loadCount.decrementAndGet(); debug(String.format("removeReference for: %s (loadCount: %d)", pluginJar, i)); if (i <= 0) { if (isExpired()) { try { close(); } catch (IOException e) { } } } return i; } /** * Close class loaders and delete cached files * @throws IOException */ @Override public void close() throws IOException { debug(String.format("close jar provider loader for: %s", pluginJar)); synchronized (this) { closed = true; } if (null != cachedJar) { cachedJar.close(); classCache.clear(); cachedJar = null; } } private boolean closed = false; public synchronized boolean isClosed() { return closed; } private boolean expired = false; public synchronized boolean isExpired() { return expired; } /** * Expire the loader cache item */ public void expire() { synchronized (this) { expired = true; } int i = loadCount.get(); debug(String.format("expire jar provider loader for: %s (loadCount: %d)", pluginJar, i)); if (i <= 0) { try { close(); } catch (IOException e) { } } } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final JarPluginProviderLoader that = (JarPluginProviderLoader) o; if (classCache != null ? !classCache.equals(that.classCache) : that.classCache != null) { return false; } if (!pluginJar.equals(that.pluginJar)) { return false; } if (mainAttributes != null ? !mainAttributes.equals(that.mainAttributes) : that.mainAttributes != null) { return false; } if (pluginProviderDefs != null ? !pluginProviderDefs.equals(that.pluginProviderDefs) : that.pluginProviderDefs != null) { return false; } return true; } @Override public int hashCode() { int result = pluginJar.hashCode(); result = 31 * result + (pluginProviderDefs != null ? pluginProviderDefs.hashCode() : 0); result = 31 * result + (mainAttributes != null ? mainAttributes.hashCode() : 0); result = 31 * result + (classCache != null ? classCache.hashCode() : 0); return result; } /** * Return true if the file is a valid jar plugin file */ public static boolean isValidJarPlugin(final File file) { try { try (final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(file))) { final Manifest manifest = jarInputStream.getManifest(); if (null == manifest) { return false; } final Attributes mainAttributes = manifest.getMainAttributes(); validateJarManifest(mainAttributes); } return true; } catch (IOException | InvalidManifestException e) { log.error(file.getAbsolutePath() + ": " + e.getMessage()); return false; } } /** * Validate whether the jar file has a valid manifest, throw exception if invalid */ static void validateJarManifest(final Attributes mainAttributes) throws InvalidManifestException { final String value1 = mainAttributes.getValue(RUNDECK_PLUGIN_ARCHIVE); final String plugvers = mainAttributes.getValue(RUNDECK_PLUGIN_VERSION); final String plugclassnames = mainAttributes.getValue(RUNDECK_PLUGIN_CLASSNAMES); if (null == value1) { throw new InvalidManifestException("Jar plugin manifest attribute missing: " + RUNDECK_PLUGIN_ARCHIVE); } else if (!"true".equals(value1)) { throw new InvalidManifestException(RUNDECK_PLUGIN_ARCHIVE + " was not 'true': " + value1); } if (null == plugvers) { throw new InvalidManifestException("Jar plugin manifest attribute missing: " + RUNDECK_PLUGIN_VERSION); } final VersionCompare pluginVersion = VersionCompare.forString(plugvers); if (!pluginVersion.atLeast(LOWEST_JAR_PLUGIN_VERSION)) { throw new InvalidManifestException("Unsupported plugin version: " + RUNDECK_PLUGIN_VERSION + ": " + plugvers); } if (null == plugclassnames) { throw new InvalidManifestException("Jar plugin manifest attribute missing: " + RUNDECK_PLUGIN_CLASSNAMES); } } static class InvalidManifestException extends Exception { public InvalidManifestException(String s) { super(s); } } /** * Return the version string metadata value for the plugin file, or null if it is not available or could not * loaded * * @param file plugin file * @return version string */ static String getVersionForFile(final File file) { return loadManifestAttribute(file, RUNDECK_PLUGIN_FILE_VERSION); } /** * Return true if the jar attributes declare it should load local dependency classes first. * * @param file plugin file * * @return true if plugin libs load first is set */ static boolean getLoadLocalLibsFirstForFile(final File file) { Attributes attributes = loadMainAttributes(file); if (null == attributes) { return false; } boolean loadFirstDefault=true; String loadFirst = attributes.getValue(RUNDECK_PLUGIN_LIBS_LOAD_FIRST); if(null!=loadFirst){ return Boolean.valueOf(loadFirst); } return loadFirstDefault; } private static Attributes loadMainAttributes(final File file) { Attributes mainAttributes = null; try { try(final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(file))) { final Manifest manifest = jarInputStream.getManifest(); if (null != manifest) { mainAttributes = manifest.getMainAttributes(); } } } catch (IOException e) { e.printStackTrace(System.err); log.warn(e.getMessage() + ": " + file.getAbsolutePath()); } return mainAttributes; } private static String loadManifestAttribute(final File file, final String attribute) { String value = null; final Attributes mainAttributes = loadMainAttributes(file); if(null!=mainAttributes){ value = mainAttributes.getValue(attribute); } return value; } /** * Holds the cached jar file, dir, libs list and class and resource loaders for a jar plugin */ private class CachedJar implements Closeable { private File dir; private File cachedJar; private Collection<File> depLibs; private URLClassLoader classLoader; private PluginResourceLoader resourcesLoader; public File getDir() { return dir; } public File getCachedJar() { return cachedJar; } public CachedJar( File dir, File cachedJar, Collection<File> depLibs, PluginResourceLoader resourcesLoader ) throws PluginException { this.dir = dir; this.cachedJar = cachedJar; this.depLibs = depLibs; this.resourcesLoader = resourcesLoader; } public Collection<File> getDepLibs() { return depLibs; } public URLClassLoader getClassLoader() throws PluginException{ if(null==classLoader){ synchronized (this){ if(null==classLoader){ classLoader = buildClassLoader(); } } } return classLoader; } private URLClassLoader buildClassLoader() throws PluginException { ClassLoader parent = JarPluginProviderLoader.class.getClassLoader(); try { final URL url = getCachedJar().toURI().toURL(); final URL[] urlarray; if (null != getDepLibs() && getDepLibs().size() > 0) { final ArrayList<URL> urls = new ArrayList<URL>(); urls.add(url); for (final File extlib : getDepLibs()) { urls.add(extlib.toURI().toURL()); } urlarray = urls.toArray(new URL[urls.size()]); } else { urlarray = new URL[]{url}; } URLClassLoader loaded = loadLibsFirst ? LocalFirstClassLoader.newInstance(urlarray, parent) : URLClassLoader.newInstance(urlarray, parent); return loaded; } catch (MalformedURLException e) { throw new PluginException("Error creating classloader for " + cachedJar, e); } } @Override public void close() throws IOException { debug(String.format("Jar plugin closing cached jar: %s", cachedJar)); //close loaders if (null != classLoader) { try { debug("expire classLoaders for: " + cachedJar); classLoader.close(); } catch (IOException e) { e.printStackTrace(); } } //remove cache files debug("remove cache dir on exit: " + dir); FileUtils.deleteDir(dir); } } @Override public String getFilename() { return pluginJar.getName(); } @Override public File getFile() { return pluginJar; } @Override public String getPluginAuthor() { Attributes mainAttributes = getMainAttributes(); return mainAttributes.getValue(RUNDECK_PLUGIN_AUTHOR); } @Override public String getPluginFileVersion() { Attributes mainAttributes = getMainAttributes(); return mainAttributes.getValue(RUNDECK_PLUGIN_FILE_VERSION); } @Override public String getPluginUrl() { Attributes mainAttributes = getMainAttributes(); return mainAttributes.getValue(RUNDECK_PLUGIN_URL); } @Override public Date getPluginDate() { Attributes mainAttributes = getMainAttributes(); String value = mainAttributes.getValue(RUNDECK_PLUGIN_DATE); if (null != value) { try { return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX").parse(value); } catch (ParseException e) { } } return null; } @Override public Date getDateLoaded() { return loadedDate; } }
3e1388702882adfd7acf20732822b5ab224365e6
640
java
Java
uniprot-datastore/src/main/java/org/uniprot/store/datastore/uniref/UniRefEntryProcessor.java
ebi-uniprot/uniprot-indexer
6787e2107f60b7a3bb86cac5540c8d4287cfd249
[ "Apache-2.0" ]
1
2019-07-16T00:06:12.000Z
2019-07-16T00:06:12.000Z
uniprot-datastore/src/main/java/org/uniprot/store/datastore/uniref/UniRefEntryProcessor.java
ebi-uniprot/uniprot-store
fca441acb80188d6608acd2bf30bc9746c5644af
[ "Apache-2.0" ]
38
2019-08-22T14:51:19.000Z
2022-01-04T16:57:25.000Z
uniprot-datastore/src/main/java/org/uniprot/store/datastore/uniref/UniRefEntryProcessor.java
ebi-uniprot/uniprot-indexer
6787e2107f60b7a3bb86cac5540c8d4287cfd249
[ "Apache-2.0" ]
null
null
null
26.666667
80
0.751563
8,248
package org.uniprot.store.datastore.uniref; import org.springframework.batch.item.ItemProcessor; import org.uniprot.core.uniref.UniRefEntry; import org.uniprot.core.xml.jaxb.uniref.Entry; import org.uniprot.core.xml.uniref.UniRefEntryConverter; /** * @author jluo * @date: 16 Aug 2019 */ public class UniRefEntryProcessor implements ItemProcessor<Entry, UniRefEntry> { private final UniRefEntryConverter converter; public UniRefEntryProcessor() { converter = new UniRefEntryConverter(); } @Override public UniRefEntry process(Entry item) throws Exception { return converter.fromXml(item); } }
3e13893a3e08bfafe8bfa78eeb928caf372473b9
1,547
java
Java
org/apache/pdfbox/pdmodel/interactive/pagenavigation/PDTransitionDirection.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
2
2021-07-16T10:43:25.000Z
2021-12-15T13:54:10.000Z
org/apache/pdfbox/pdmodel/interactive/pagenavigation/PDTransitionDirection.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
1
2021-10-12T22:24:55.000Z
2021-10-12T22:24:55.000Z
org/apache/pdfbox/pdmodel/interactive/pagenavigation/PDTransitionDirection.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
null
null
null
19.582278
133
0.393665
8,249
/* */ package org.apache.pdfbox.pdmodel.interactive.pagenavigation; /* */ /* */ import org.apache.pdfbox.cos.COSBase; /* */ import org.apache.pdfbox.cos.COSInteger; /* */ import org.apache.pdfbox.cos.COSName; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public enum PDTransitionDirection /* */ { /* 34 */ LEFT_TO_RIGHT(0), /* */ /* */ /* */ /* 38 */ BOTTOM_TO_TOP(90), /* */ /* */ /* */ /* 42 */ RIGHT_TO_LEFT(180), TOP_TO_BOTTOM(270), /* */ /* */ /* */ /* 46 */ TOP_LEFT_TO_BOTTOM_RIGHT(315), /* */ /* */ /* */ /* 50 */ NONE(0) /* */ { /* */ /* */ public COSBase getCOSBase() /* */ { /* 55 */ return (COSBase)COSName.NONE; /* */ } /* */ }; /* */ /* */ /* */ private final int degrees; /* */ /* */ PDTransitionDirection(int degrees) { /* 63 */ this.degrees = degrees; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public COSBase getCOSBase() { /* 71 */ return (COSBase)COSInteger.get(this.degrees); /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/pdfbox/pdmodel/interactive/pagenavigation/PDTransitionDirection.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
3e1389bf2f6d5e76253689b6fd0ce74e21f847c8
687
java
Java
communote/plugins/communote-core-plugin/src/main/java/com/communote/plugins/core/classloader/ClassLoaderAggregatorThreadContextSetter.java
Communote/communote-server
e6a3541054baa7ad26a4eccbbdd7fb8937dead0c
[ "Apache-2.0" ]
26
2016-06-27T09:25:10.000Z
2022-01-24T06:26:56.000Z
communote/plugins/communote-core-plugin/src/main/java/com/communote/plugins/core/classloader/ClassLoaderAggregatorThreadContextSetter.java
Communote/communote-server
e6a3541054baa7ad26a4eccbbdd7fb8937dead0c
[ "Apache-2.0" ]
64
2016-06-28T14:50:46.000Z
2019-05-04T15:10:04.000Z
communote/plugins/communote-core-plugin/src/main/java/com/communote/plugins/core/classloader/ClassLoaderAggregatorThreadContextSetter.java
Communote/communote-server
e6a3541054baa7ad26a4eccbbdd7fb8937dead0c
[ "Apache-2.0" ]
4
2016-10-05T17:30:36.000Z
2019-10-26T15:44:00.000Z
29.869565
94
0.6623
8,250
package com.communote.plugins.core.classloader; /** * @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a> */ public abstract class ClassLoaderAggregatorThreadContextSetter<T extends Exception> { public void execute(final ClassLoader... classLoadersToUse) throws T { ClassLoader current = Thread.currentThread().getContextClassLoader(); try { ClassLoaderAggregator.setAggregatedClassloader(current, classLoadersToUse); run(); } finally { Thread.currentThread().setContextClassLoader(current); } } protected abstract void run() throws T; }
3e1389c6653241f176a5da00388397b75538144d
3,165
java
Java
app/src/main/java/com/qiaojim/bluetoothstudy/DataTransFragment.java
gggggggg1988/BluetoothStudy
8ccff5744f97df4c8b60e8c51c2371f5dbf25f1c
[ "Apache-2.0" ]
48
2017-04-06T01:08:04.000Z
2022-02-05T19:27:26.000Z
app/src/main/java/com/qiaojim/bluetoothstudy/DataTransFragment.java
gggggggg1988/BluetoothStudy
8ccff5744f97df4c8b60e8c51c2371f5dbf25f1c
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/qiaojim/bluetoothstudy/DataTransFragment.java
gggggggg1988/BluetoothStudy
8ccff5744f97df4c8b60e8c51c2371f5dbf25f1c
[ "Apache-2.0" ]
28
2017-04-06T07:24:21.000Z
2020-11-20T07:30:13.000Z
30.142857
123
0.662559
8,251
package com.qiaojim.bluetoothstudy; import android.bluetooth.BluetoothDevice; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; /** * Created by Administrator on 2017/4/4. */ public class DataTransFragment extends Fragment { TextView connectNameTv; ListView showDataLv; EditText inputEt; Button sendBt; ArrayAdapter<String> dataListAdapter; MainActivity mainActivity; Handler uiHandler; BluetoothDevice remoteDevice; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.layout_data_trans, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { connectNameTv = (TextView) view.findViewById(R.id.device_name_tv); showDataLv = (ListView) view.findViewById(R.id.show_data_lv); inputEt = (EditText) view.findViewById(R.id.input_et); sendBt = (Button) view.findViewById(R.id.send_bt); sendBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String msgSend = inputEt.getText().toString(); Message message = new Message(); message.what = Params.MSG_WRITE_DATA; message.obj = msgSend; uiHandler.sendMessage(message); inputEt.setText(""); } }); dataListAdapter = new ArrayAdapter<String>(getContext(), R.layout.layout_item_new_data); showDataLv.setAdapter(dataListAdapter); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mainActivity = (MainActivity) getActivity(); uiHandler = mainActivity.getUiHandler(); } /** * 显示连接远端(客户端)设备 */ public void receiveClient(BluetoothDevice clientDevice) { this.remoteDevice = clientDevice; connectNameTv.setText("连接设备: " + remoteDevice.getName()); } /** * 显示新消息 * * @param newMsg */ public void updateDataView(String newMsg,int role) { if (role == Params.REMOTE) { String remoteName = remoteDevice.getName()==null ? "未命名设备":remoteDevice.getName(); newMsg = remoteName + " : " + newMsg; } else if (role == Params.ME){ newMsg = "我 : " + newMsg; } dataListAdapter.add(newMsg); } /** * 客户端连接服务器端设备后,显示 * * @param serverDevice */ public void connectServer(BluetoothDevice serverDevice) { this.remoteDevice = serverDevice; connectNameTv.setText("连接设备: " + remoteDevice.getName()); } }
3e1389efbd42264f41e7621ad5564892e63d8922
527
java
Java
ecommerce-order-service-api/src/main/java/com/ecommerce/order/order/model/OrderFactory.java
ruperi/ecommerce-order-service
6aeacac2e769421252863361f5f22c92f2c236bb
[ "Apache-2.0" ]
494
2019-09-05T08:24:15.000Z
2022-03-31T06:03:42.000Z
ecommerce-order-service-api/src/main/java/com/ecommerce/order/order/model/OrderFactory.java
ruperi/ecommerce-order-service
6aeacac2e769421252863361f5f22c92f2c236bb
[ "Apache-2.0" ]
5
2019-10-09T11:53:37.000Z
2021-07-08T07:13:31.000Z
ecommerce-order-service-api/src/main/java/com/ecommerce/order/order/model/OrderFactory.java
enjoy-snail/order-backend
5fdfecbf5b915c5d6bb4cefa71ddc27640cf9733
[ "Apache-2.0" ]
186
2019-09-06T04:21:26.000Z
2022-03-31T06:02:56.000Z
25.095238
65
0.740038
8,252
package com.ecommerce.order.order.model; import com.ecommerce.shared.model.Address; import org.springframework.stereotype.Component; import java.util.List; @Component public class OrderFactory { private final OrderIdGenerator idGenerator; public OrderFactory(OrderIdGenerator idGenerator) { this.idGenerator = idGenerator; } public Order create(List<OrderItem> items, Address address) { String orderId = idGenerator.generate(); return Order.create(orderId, items, address); } }
3e138ab81a71dfa39ac59a83616066ee6e6d72a1
1,610
java
Java
src/main/java/com/kwpugh/mining_dims/init/PortalInit.java
JackGlobetrotter/mining_Dimensions-1.17
1a1a537abf42fc6208207e4ab86ab2ea9b0cccdf
[ "CC0-1.0" ]
4
2021-12-14T16:41:37.000Z
2022-01-24T12:51:56.000Z
src/main/java/com/kwpugh/mining_dims/init/PortalInit.java
JackGlobetrotter/mining_Dimensions-1.17
1a1a537abf42fc6208207e4ab86ab2ea9b0cccdf
[ "CC0-1.0" ]
26
2021-06-20T01:41:00.000Z
2022-03-24T02:48:21.000Z
src/main/java/com/kwpugh/mining_dims/init/PortalInit.java
JackGlobetrotter/mining_Dimensions-1.17
1a1a537abf42fc6208207e4ab86ab2ea9b0cccdf
[ "CC0-1.0" ]
9
2021-11-04T19:21:18.000Z
2022-03-11T18:24:34.000Z
26.393443
76
0.702484
8,253
package com.kwpugh.mining_dims.init; import com.kwpugh.mining_dims.MiningDims; import net.kyrptonaught.customportalapi.api.CustomPortalBuilder; import net.minecraft.block.Blocks; import net.minecraft.util.Identifier; public class PortalInit { static boolean mining = MiningDims.CONFIG.GENERAL.enableMiningPortal; static boolean hunting = MiningDims.CONFIG.GENERAL.enableHuntingPortal; static boolean caving = MiningDims.CONFIG.GENERAL.enableCavingPortal; static boolean nethering = MiningDims.CONFIG.GENERAL.enableNetheringPortal; public static void registerPortal() { // 50, 133, 168 = light blue portal color // 13, 130, 21 = green portal // 28, 27, 31 = black portal // 235, 52, 55 = red portal if(mining) { CustomPortalBuilder.beginPortal() .frameBlock(Blocks.COBBLESTONE) .destDimID(new Identifier(MiningDims.MOD_ID, "mining_dim")) .tintColor(50, 133, 168) .registerPortal(); } if(hunting) { CustomPortalBuilder.beginPortal() .frameBlock(Blocks.OAK_LOG) .destDimID(new Identifier(MiningDims.MOD_ID, "hunting_dim")) .tintColor(13, 130, 21) .registerPortal(); } if(caving) { CustomPortalBuilder.beginPortal() .frameBlock(Blocks.DIORITE) .destDimID(new Identifier(MiningDims.MOD_ID, "caving_dim")) .tintColor(28, 27, 31) .registerPortal(); } if(nethering) { CustomPortalBuilder.beginPortal() .frameBlock(Blocks.BASALT) .destDimID(new Identifier(MiningDims.MOD_ID, "nethering_dim")) .tintColor(235, 52, 55) .registerPortal(); } } }
3e138b1ad54ab13a79d6e9dbd79586083e49e4f3
11,088
java
Java
sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareItemInner.java
Manny27nyc/azure-sdk-for-java
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
[ "MIT" ]
1,350
2015-01-17T05:22:05.000Z
2022-03-29T21:00:37.000Z
sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareItemInner.java
Manny27nyc/azure-sdk-for-java
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
[ "MIT" ]
16,834
2015-01-07T02:19:09.000Z
2022-03-31T23:29:10.000Z
sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareItemInner.java
Manny27nyc/azure-sdk-for-java
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
[ "MIT" ]
1,586
2015-01-02T01:50:28.000Z
2022-03-31T11:25:34.000Z
35.652733
120
0.671627
8,254
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.storage.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.storage.models.AzureEntityResource; import com.azure.resourcemanager.storage.models.EnabledProtocols; import com.azure.resourcemanager.storage.models.LeaseDuration; import com.azure.resourcemanager.storage.models.LeaseState; import com.azure.resourcemanager.storage.models.LeaseStatus; import com.azure.resourcemanager.storage.models.RootSquashType; import com.azure.resourcemanager.storage.models.ShareAccessTier; import com.azure.resourcemanager.storage.models.SignedIdentifier; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; import java.util.List; import java.util.Map; /** The file share properties be listed out. */ @Fluent public final class FileShareItemInner extends AzureEntityResource { @JsonIgnore private final ClientLogger logger = new ClientLogger(FileShareItemInner.class); /* * The file share properties be listed out. */ @JsonProperty(value = "properties") private FileShareProperties innerProperties; /** * Get the innerProperties property: The file share properties be listed out. * * @return the innerProperties value. */ private FileShareProperties innerProperties() { return this.innerProperties; } /** * Get the lastModifiedTime property: Returns the date and time the share was last modified. * * @return the lastModifiedTime value. */ public OffsetDateTime lastModifiedTime() { return this.innerProperties() == null ? null : this.innerProperties().lastModifiedTime(); } /** * Get the metadata property: A name-value pair to associate with the share as metadata. * * @return the metadata value. */ public Map<String, String> metadata() { return this.innerProperties() == null ? null : this.innerProperties().metadata(); } /** * Set the metadata property: A name-value pair to associate with the share as metadata. * * @param metadata the metadata value to set. * @return the FileShareItemInner object itself. */ public FileShareItemInner withMetadata(Map<String, String> metadata) { if (this.innerProperties() == null) { this.innerProperties = new FileShareProperties(); } this.innerProperties().withMetadata(metadata); return this; } /** * Get the shareQuota property: The maximum size of the share, in gigabytes. Must be greater than 0, and less than * or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. * * @return the shareQuota value. */ public Integer shareQuota() { return this.innerProperties() == null ? null : this.innerProperties().shareQuota(); } /** * Set the shareQuota property: The maximum size of the share, in gigabytes. Must be greater than 0, and less than * or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. * * @param shareQuota the shareQuota value to set. * @return the FileShareItemInner object itself. */ public FileShareItemInner withShareQuota(Integer shareQuota) { if (this.innerProperties() == null) { this.innerProperties = new FileShareProperties(); } this.innerProperties().withShareQuota(shareQuota); return this; } /** * Get the enabledProtocols property: The authentication protocol that is used for the file share. Can only be * specified when creating a share. * * @return the enabledProtocols value. */ public EnabledProtocols enabledProtocols() { return this.innerProperties() == null ? null : this.innerProperties().enabledProtocols(); } /** * Set the enabledProtocols property: The authentication protocol that is used for the file share. Can only be * specified when creating a share. * * @param enabledProtocols the enabledProtocols value to set. * @return the FileShareItemInner object itself. */ public FileShareItemInner withEnabledProtocols(EnabledProtocols enabledProtocols) { if (this.innerProperties() == null) { this.innerProperties = new FileShareProperties(); } this.innerProperties().withEnabledProtocols(enabledProtocols); return this; } /** * Get the rootSquash property: The property is for NFS share only. The default is NoRootSquash. * * @return the rootSquash value. */ public RootSquashType rootSquash() { return this.innerProperties() == null ? null : this.innerProperties().rootSquash(); } /** * Set the rootSquash property: The property is for NFS share only. The default is NoRootSquash. * * @param rootSquash the rootSquash value to set. * @return the FileShareItemInner object itself. */ public FileShareItemInner withRootSquash(RootSquashType rootSquash) { if (this.innerProperties() == null) { this.innerProperties = new FileShareProperties(); } this.innerProperties().withRootSquash(rootSquash); return this; } /** * Get the version property: The version of the share. * * @return the version value. */ public String version() { return this.innerProperties() == null ? null : this.innerProperties().version(); } /** * Get the deleted property: Indicates whether the share was deleted. * * @return the deleted value. */ public Boolean deleted() { return this.innerProperties() == null ? null : this.innerProperties().deleted(); } /** * Get the deletedTime property: The deleted time if the share was deleted. * * @return the deletedTime value. */ public OffsetDateTime deletedTime() { return this.innerProperties() == null ? null : this.innerProperties().deletedTime(); } /** * Get the remainingRetentionDays property: Remaining retention days for share that was soft deleted. * * @return the remainingRetentionDays value. */ public Integer remainingRetentionDays() { return this.innerProperties() == null ? null : this.innerProperties().remainingRetentionDays(); } /** * Get the accessTier property: Access tier for specific share. GpV2 account can choose between TransactionOptimized * (default), Hot, and Cool. FileStorage account can choose Premium. * * @return the accessTier value. */ public ShareAccessTier accessTier() { return this.innerProperties() == null ? null : this.innerProperties().accessTier(); } /** * Set the accessTier property: Access tier for specific share. GpV2 account can choose between TransactionOptimized * (default), Hot, and Cool. FileStorage account can choose Premium. * * @param accessTier the accessTier value to set. * @return the FileShareItemInner object itself. */ public FileShareItemInner withAccessTier(ShareAccessTier accessTier) { if (this.innerProperties() == null) { this.innerProperties = new FileShareProperties(); } this.innerProperties().withAccessTier(accessTier); return this; } /** * Get the accessTierChangeTime property: Indicates the last modification time for share access tier. * * @return the accessTierChangeTime value. */ public OffsetDateTime accessTierChangeTime() { return this.innerProperties() == null ? null : this.innerProperties().accessTierChangeTime(); } /** * Get the accessTierStatus property: Indicates if there is a pending transition for access tier. * * @return the accessTierStatus value. */ public String accessTierStatus() { return this.innerProperties() == null ? null : this.innerProperties().accessTierStatus(); } /** * Get the shareUsageBytes property: The approximate size of the data stored on the share. Note that this value may * not include all recently created or recently resized files. * * @return the shareUsageBytes value. */ public Long shareUsageBytes() { return this.innerProperties() == null ? null : this.innerProperties().shareUsageBytes(); } /** * Get the leaseStatus property: The lease status of the share. * * @return the leaseStatus value. */ public LeaseStatus leaseStatus() { return this.innerProperties() == null ? null : this.innerProperties().leaseStatus(); } /** * Get the leaseState property: Lease state of the share. * * @return the leaseState value. */ public LeaseState leaseState() { return this.innerProperties() == null ? null : this.innerProperties().leaseState(); } /** * Get the leaseDuration property: Specifies whether the lease on a share is of infinite or fixed duration, only * when the share is leased. * * @return the leaseDuration value. */ public LeaseDuration leaseDuration() { return this.innerProperties() == null ? null : this.innerProperties().leaseDuration(); } /** * Get the signedIdentifiers property: List of stored access policies specified on the share. * * @return the signedIdentifiers value. */ public List<SignedIdentifier> signedIdentifiers() { return this.innerProperties() == null ? null : this.innerProperties().signedIdentifiers(); } /** * Set the signedIdentifiers property: List of stored access policies specified on the share. * * @param signedIdentifiers the signedIdentifiers value to set. * @return the FileShareItemInner object itself. */ public FileShareItemInner withSignedIdentifiers(List<SignedIdentifier> signedIdentifiers) { if (this.innerProperties() == null) { this.innerProperties = new FileShareProperties(); } this.innerProperties().withSignedIdentifiers(signedIdentifiers); return this; } /** * Get the snapshotTime property: Creation time of share snapshot returned in the response of list shares with * expand param "snapshots". * * @return the snapshotTime value. */ public OffsetDateTime snapshotTime() { return this.innerProperties() == null ? null : this.innerProperties().snapshotTime(); } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); if (innerProperties() != null) { innerProperties().validate(); } } }
3e138b40c26854d3f5394379e93b5307fcdd032e
3,089
java
Java
dcm4che-2.0.29/dcm4che-code/src/main/java/org/dcm4che2/code/EchocardiographyAorta.java
ppazos/dicom-waveform
dede548af1ffdb912205a33b9ec0e1ccd7b5ebe0
[ "Apache-2.0" ]
null
null
null
dcm4che-2.0.29/dcm4che-code/src/main/java/org/dcm4che2/code/EchocardiographyAorta.java
ppazos/dicom-waveform
dede548af1ffdb912205a33b9ec0e1ccd7b5ebe0
[ "Apache-2.0" ]
1
2019-09-27T16:07:35.000Z
2019-09-27T16:07:35.000Z
dcm4che-2.0.29/dcm4che-code/src/main/java/org/dcm4che2/code/EchocardiographyAorta.java
ppazos/dicom-waveform
dede548af1ffdb912205a33b9ec0e1ccd7b5ebe0
[ "Apache-2.0" ]
null
null
null
41.756757
103
0.718123
8,255
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), available at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * Agfa HealthCare. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * See listed authors below. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4che2.code; /** * CID 12212 Echocardiography Aorta. * * @author Gunter Zeilinger <envkt@example.com> * @version $Rev: 13502 $ $Date:: 2010-06-09#$ * @since Jun 2, 2010 */ public class EchocardiographyAorta { /** (18011-7, LN, "Aortic Arch Diameter") */ public static final String AorticArchDiameter = "18011-7\\LN"; /** (18014-1, LN, "Aortic Isthmus Diameter") */ public static final String AorticIsthmusDiameter = "18014-1\\LN"; /** (18015-8, LN, "Aortic Root Diameter") */ public static final String AorticRootDiameter = "18015-8\\LN"; /** (18012-5, LN, "Ascending Aortic Diameter") */ public static final String AscendingAorticDiameter = "18012-5\\LN"; /** (18013-3, LN, "Descending Aortic Diameter") */ public static final String DescendingAorticDiameter = "18013-3\\LN"; /** (8867-4, LN, "Heart rate") */ public static final String HeartRate = "8867-4\\LN"; /** (17995-2, LN, "Thoracic Aorta Coarctation Systolic Peak Instantaneous Gradient") */ public static final String ThoracicAortaCoarctationSystolicPeakInstantaneousGradient = "17995-2\\LN"; /** (29460-3, LN, "Thoracic Aorta Coarctation Systolic Peak Velocity") */ public static final String ThoracicAortaCoarctationSystolicPeakVelocity = "29460-3\\LN"; }
3e138c292be27a20253af155b1032c4f1a506204
1,747
java
Java
app/src/main/java/practicaltest01var08/eim/systems/cs/pub/ro/practicaltest01var08/ServiceTest.java
cosmin-ionita/EIM_Exam
19e821cf26e57698d9b01fd4829de48ab09f570a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/practicaltest01var08/eim/systems/cs/pub/ro/practicaltest01var08/ServiceTest.java
cosmin-ionita/EIM_Exam
19e821cf26e57698d9b01fd4829de48ab09f570a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/practicaltest01var08/eim/systems/cs/pub/ro/practicaltest01var08/ServiceTest.java
cosmin-ionita/EIM_Exam
19e821cf26e57698d9b01fd4829de48ab09f570a
[ "Apache-2.0" ]
null
null
null
21.048193
72
0.517459
8,256
package practicaltest01var08.eim.systems.cs.pub.ro.practicaltest01var08; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.widget.Toast; import java.util.Random; public class ServiceTest extends Service { public ServiceTest() { } @Override public void onCreate() { super.onCreate(); } private String getMaskedString(String str) { StringBuilder builder = new StringBuilder(str); Random random = new Random(); int x = random.nextInt(str.length()); for(int i = 0; i < str.length(); i++) { if(i != x) builder.setCharAt(i, '*'); } return builder.toString(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { final String str = intent.getStringExtra("answer"); Thread t = new Thread(new Runnable() { @Override public void run() { while(true) { String str2 = getMaskedString(str); Intent intent = new Intent(); intent.setAction("act"); intent.putExtra("msg", str2); sendBroadcast(intent); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t.start(); return START_REDELIVER_INTENT; } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { super.onDestroy(); } }
3e138de09244f88fead85591f0a895816b70f53e
1,482
java
Java
library/src/main/java/it/unibs/sandroide/lib/BLEEmbeddedEventListener.java
SAndroidEOfficial/framework
5e2f927360fba53a5711646a0313895a00e6add9
[ "MIT" ]
10
2016-12-31T10:34:15.000Z
2018-03-02T19:36:51.000Z
library/src/main/java/it/unibs/sandroide/lib/BLEEmbeddedEventListener.java
SAndroidEOfficial/framework
5e2f927360fba53a5711646a0313895a00e6add9
[ "MIT" ]
53
2016-12-20T14:49:04.000Z
2018-03-07T15:02:01.000Z
library/src/main/java/it/unibs/sandroide/lib/BLEEmbeddedEventListener.java
SAndroidEOfficial/framework
5e2f927360fba53a5711646a0313895a00e6add9
[ "MIT" ]
5
2017-02-20T16:05:13.000Z
2021-07-02T22:16:22.000Z
40.054054
86
0.769231
8,257
/** * Copyright (c) 2016 University of Brescia, Alessandra Flammini, All rights reserved. * * 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 it.unibs.sandroide.lib; import it.unibs.sandroide.lib.item.BLEItem; /** * Event listener interface */ public interface BLEEmbeddedEventListener { public void onBLEEmbeddedEvent(int event); public void onBLEItemDisconnected(BLEItem bleItem); public void onBLEItemConnected(BLEItem bleItem); }
3e138e5316abd4d9db86b454da9704d6e740351b
363
java
Java
sdk/src/main/java/org/zstack/sdk/AddSecurityMachineResult.java
MatheMatrix/zstack
8da3508c624c0bd8f819da91eb28f7ebf34b8cba
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdk/src/main/java/org/zstack/sdk/AddSecurityMachineResult.java
MatheMatrix/zstack
8da3508c624c0bd8f819da91eb28f7ebf34b8cba
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdk/src/main/java/org/zstack/sdk/AddSecurityMachineResult.java
MatheMatrix/zstack
8da3508c624c0bd8f819da91eb28f7ebf34b8cba
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
24.2
66
0.752066
8,258
package org.zstack.sdk; import org.zstack.sdk.SecurityMachineInventory; public class AddSecurityMachineResult { public SecurityMachineInventory inventory; public void setInventory(SecurityMachineInventory inventory) { this.inventory = inventory; } public SecurityMachineInventory getInventory() { return this.inventory; } }
3e138e9e0560192a4217158c5ea6d56a464ff622
435
java
Java
core/src/main/java/com/delmar/core/model/CorePage.java
ldlqdsdcn/wms
0be5e05d65bf76d226e32d7d438f0036e3f47beb
[ "Apache-2.0" ]
20
2016-08-23T08:31:42.000Z
2022-03-14T13:44:57.000Z
core/src/main/java/com/delmar/core/model/CorePage.java
ldlqdsdcn/wms
0be5e05d65bf76d226e32d7d438f0036e3f47beb
[ "Apache-2.0" ]
null
null
null
core/src/main/java/com/delmar/core/model/CorePage.java
ldlqdsdcn/wms
0be5e05d65bf76d226e32d7d438f0036e3f47beb
[ "Apache-2.0" ]
12
2016-08-23T08:31:43.000Z
2019-06-28T08:58:56.000Z
18.913043
41
0.77931
8,259
package com.delmar.core.model; import lombok.Data; /** * table name core_page * Date:2016-08-26 17:08:24 **/ @Data public class CorePage extends CoreModel { private Integer id; private String name; private String descr; private String help; private Integer windowId; private Integer tableId; private Integer filterColumnId; private String isactive; private String showInTab; private Integer seqNo; private String filterSql; }
3e138eb6278d1cb22dd27fd6d75037e01c0ce516
1,282
java
Java
cofpasgers/src/main/java/com/huiketong/cofpasgers/util/SerialGeneratorUtil.java
ZuofeiGithub/javaweb_huiketong
0c2e630fd1be9a0ecf02230acf6b82e9b6bc8b2c
[ "Apache-2.0" ]
null
null
null
cofpasgers/src/main/java/com/huiketong/cofpasgers/util/SerialGeneratorUtil.java
ZuofeiGithub/javaweb_huiketong
0c2e630fd1be9a0ecf02230acf6b82e9b6bc8b2c
[ "Apache-2.0" ]
null
null
null
cofpasgers/src/main/java/com/huiketong/cofpasgers/util/SerialGeneratorUtil.java
ZuofeiGithub/javaweb_huiketong
0c2e630fd1be9a0ecf02230acf6b82e9b6bc8b2c
[ "Apache-2.0" ]
null
null
null
34.648649
88
0.423557
8,260
package com.huiketong.cofpasgers.util; import java.util.Random; public class SerialGeneratorUtil { public static String GetRandomString(int Len) { String[] baseString = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; Random random = new Random(); int length = baseString.length; String randomString = ""; for (int i = 0; i < length; i++) { randomString += baseString[random.nextInt(length)]; } random = new Random(System.currentTimeMillis()); String resultStr = ""; for (int i = 0; i < Len; i++) { resultStr += randomString.charAt(random.nextInt(randomString.length() - 1)); } return resultStr; } public static void main(String[] args) { System.out.println(SerialGeneratorUtil.GetRandomString(32)); } }
3e138f0e54637f86daf142b7c432debb7760af01
382
java
Java
src/main/java/iot/strategy/consume/DummyConsumer.java
Placu95/DingNet
5e52fd2cafdcb2a95c9f34c51bcaa4702faee304
[ "MIT" ]
null
null
null
src/main/java/iot/strategy/consume/DummyConsumer.java
Placu95/DingNet
5e52fd2cafdcb2a95c9f34c51bcaa4702faee304
[ "MIT" ]
null
null
null
src/main/java/iot/strategy/consume/DummyConsumer.java
Placu95/DingNet
5e52fd2cafdcb2a95c9f34c51bcaa4702faee304
[ "MIT" ]
2
2020-03-27T17:26:01.000Z
2020-04-24T10:22:35.000Z
21.222222
65
0.743455
8,261
package iot.strategy.consume; import iot.lora.LoraWanPacket; import iot.networkentity.Mote; import java.util.Arrays; /** * Print the payload of the received packet */ public class DummyConsumer implements ConsumePacketStrategy { @Override public void consume(Mote mote, LoraWanPacket packet) { System.out.println(Arrays.toString(packet.getPayload())); } }
3e138f4661e64d908f1da5e7fedb68ef78a772fa
2,059
java
Java
api/src/java/com/futu/opend/api/impl/QotRegQotPushExec.java
llmyfa/java-for-FutuOpenD
842369ce6b1351b3ff049d446dffd0089d51eb1a
[ "Apache-2.0" ]
15
2018-08-09T08:02:48.000Z
2022-03-07T12:00:15.000Z
api/src/java/com/futu/opend/api/impl/QotRegQotPushExec.java
llmyfa/java-for-FutuOpenD
842369ce6b1351b3ff049d446dffd0089d51eb1a
[ "Apache-2.0" ]
3
2018-08-17T08:16:02.000Z
2019-04-04T13:53:29.000Z
api/src/java/com/futu/opend/api/impl/QotRegQotPushExec.java
llmyfa/java-for-FutuOpenD
842369ce6b1351b3ff049d446dffd0089d51eb1a
[ "Apache-2.0" ]
7
2018-08-06T08:53:41.000Z
2021-03-23T08:29:22.000Z
28.205479
121
0.770763
8,262
package com.futu.opend.api.impl; import com.futu.opend.api.protobuf.QotRegQotPush; import com.futu.opend.api.protobuf.QotCommon.QotMarket; import com.futu.opend.api.protobuf.QotCommon.Security; import com.futu.opend.api.protobuf.QotCommon.SubType; import com.google.protobuf.InvalidProtocolBufferException; class QotRegQotPushExec implements IExecutor{ private QotRegQotPush.Response response; private QotMarket market; private SubType[] subTypes; private String[] symbols; private boolean isRegOrUnReg = true; private boolean isFirstPush = true; public final static int nProtoID = 3002; public QotRegQotPushExec(QotMarket market,String[] symbols,SubType[] subTypes){ this.market = market; this.subTypes = subTypes; this.symbols = symbols; } public QotRegQotPushExec(QotMarket market,String[] symbols,SubType[] subTypes,boolean isFirstPush,boolean isRegOrUnReg){ this.market = market; this.subTypes = subTypes; this.symbols = symbols; this.isFirstPush = isFirstPush; this.isRegOrUnReg = isRegOrUnReg; } @Override public ProtoBufPackage buildPackage() { QotRegQotPush.Request.Builder request = QotRegQotPush.Request.newBuilder(); QotRegQotPush.C2S.Builder c2s = QotRegQotPush.C2S.newBuilder(); for(String symbol : symbols){ Security.Builder security = Security.newBuilder(); security.setMarket(market.getNumber()); security.setCode(symbol); c2s.addSecurityList(security); } for(SubType subType : subTypes) c2s.addSubTypeList(subType.getNumber()); c2s.setIsRegOrUnReg(isRegOrUnReg); c2s.setIsFirstPush(isFirstPush); request.setC2S(c2s); ProtoBufPackage pack = new ProtoBufPackage(); pack.setnProtoID(nProtoID); pack.setBodys(request.build().toByteArray()); return pack; } @Override public void execute(ProtoBufPackage pack) throws InvalidProtocolBufferException { response = QotRegQotPush.Response.parseFrom(pack.getBodys()); } @Override public QotRegQotPush.Response getValue() { return response; } @Override public int getnProtoID() { return nProtoID; } }
3e138f7101892cf7c7ef788f223a4c74ea4a678c
2,725
java
Java
app/src/main/java/jp/ne/hatena/hackugyo/thoughtscalendar/model/DatabaseHelper.java
hackugyo/ThoughtsCalendar_Android
28cb18b15f434960620016cd9c07fc18a1d5d734
[ "Apache-2.0" ]
null
null
null
app/src/main/java/jp/ne/hatena/hackugyo/thoughtscalendar/model/DatabaseHelper.java
hackugyo/ThoughtsCalendar_Android
28cb18b15f434960620016cd9c07fc18a1d5d734
[ "Apache-2.0" ]
null
null
null
app/src/main/java/jp/ne/hatena/hackugyo/thoughtscalendar/model/DatabaseHelper.java
hackugyo/ThoughtsCalendar_Android
28cb18b15f434960620016cd9c07fc18a1d5d734
[ "Apache-2.0" ]
null
null
null
32.058824
127
0.662385
8,263
package jp.ne.hatena.hackugyo.thoughtscalendar.model; import java.io.File; import java.util.concurrent.atomic.AtomicInteger; import jp.ne.hatena.hackugyo.thoughtscalendar.util.LogUtils; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.j256.ormlite.android.apptools.OpenHelperManager; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final String DATABASE_NAME = "philosocial.db"; private static final int DATABASE_VERSION = 1; private File mDatabasePath; private static AtomicInteger sHelperReferenceCount = new AtomicInteger(0); private static volatile DatabaseHelper sHelper; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mDatabasePath = context.getDatabasePath(DATABASE_NAME); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource myConnectionSource) { try { // エンティティを指定してcreate tableします TableUtils.createTable(myConnectionSource, AttendingEvent.class); } catch (java.sql.SQLException e) { LogUtils.e("データベースを作成できませんでした", e); } } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource myConnectionSource, int oldVersion, int newVersion) { // DBのアップグレード処理(今回は割愛) } /*********************************************** * get / release helper * **********************************************/ /** * {@link OpenHelperManager#getHelper(Context, Class)}のラッパです * * @param context * @return DBヘルパ */ public static synchronized DatabaseHelper getHelper(Context context) { if (sHelperReferenceCount.getAndIncrement() == 0) { sHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class); } return sHelper; } /** * DBヘルパを使い終わったら,{@link #close()}のかわりに呼んでください. */ public static synchronized void releaseHelper() { if (sHelperReferenceCount.decrementAndGet() <= 0) { sHelperReferenceCount.set(0); OpenHelperManager.releaseHelper(); } } public static synchronized void destroyHelper() { OpenHelperManager.releaseHelper(); sHelperReferenceCount.set(0); } /** * Close any open connections. * * @deprecated DB更新をAtomicにするため,直接closeせず,<br> * {@link #releaseHelper()}を呼んでください. */ public void close() { super.close(); } }
3e139027280d4b03dc382120c57e7609696948d9
3,106
java
Java
tests/org.jgap/src/test/java/org/jgap/xml/XMLDocumentBuilderTest.java
wwu-pi/midstr
86e09e3b8be113b53c67da8eab871655d5d42e28
[ "Apache-2.0" ]
1
2020-05-26T09:16:25.000Z
2020-05-26T09:16:25.000Z
tests/org.jgap/src/test/java/org/jgap/xml/XMLDocumentBuilderTest.java
vvhof/midstr
2b9949b91712e809399242b767f6f18c435e2640
[ "Apache-2.0" ]
null
null
null
tests/org.jgap/src/test/java/org/jgap/xml/XMLDocumentBuilderTest.java
vvhof/midstr
2b9949b91712e809399242b767f6f18c435e2640
[ "Apache-2.0" ]
1
2020-05-26T09:07:22.000Z
2020-05-26T09:07:22.000Z
35.701149
80
0.675145
8,264
/* * This file is part of JGAP. * * JGAP offers a dual license model containing the LGPL as well as the MPL. * * For licensing information please see the file license.txt included with JGAP * or have a look at the top of class org.jgap.Chromosome which representatively * includes the JGAP license policy applicable for any file delivered with JGAP. */ package org.jgap.xml; import org.jgap.*; import org.jgap.impl.*; import org.jgap.data.*; import junit.framework.*; import org.w3c.dom.*; /** * Tests the XMLDocumentBuilder class. * * @author Klaus Meffert * @since 1.0 */ public class XMLDocumentBuilderTest extends JGAPTestCase { /** String containing the CVS revision. Read out via reflection!*/ private final static String CVS_REVISION = "$Revision: 1.6 $"; private final static String FILENAME_WRITE = "GAtestWrite.xml"; public static Test suite() { TestSuite suite = new TestSuite(XMLDocumentBuilderTest.class); return suite; } /** * @throws Exception * @author Klaus Meffert * @since 2.6 */ public void testBuildDocument_0() throws Exception { XMLDocumentBuilder doc = new XMLDocumentBuilder(); DataTreeBuilder builder = DataTreeBuilder.getInstance(); Chromosome chrom = new Chromosome(conf, new Gene[] { new IntegerGene(conf, 1, 5), new IntegerGene(conf, 1, 10)}); chrom.getGene(0).setAllele(new Integer(1)); chrom.getGene(1).setAllele(new Integer( -3)); IDataCreators doc2 = builder.representChromosomeAsDocument(chrom); Document result = (Document)doc.buildDocument(doc2); assertEquals(null, result.getParentNode()); assertEquals(1, result.getChildNodes().getLength()); Node child = result.getChildNodes().item(0); assertEquals("chromosome", child.getNodeName()); assertEquals(1, child.getChildNodes().getLength()); Node genes = child.getChildNodes().item(0); assertEquals(2, genes.getChildNodes().getLength()); } /** * Artifically create a null node * @throws Exception * @author Klaus Meffert * @since 2.6 */ public void testBuildDocument_1() throws Exception { XMLDocumentBuilder doc = new XMLDocumentBuilder(); DataTreeBuilder builder = DataTreeBuilder.getInstance(); Chromosome chrom = new Chromosome(conf, new Gene[] { new IntegerGene(conf, 1, 5), new IntegerGene(conf, 1, 10)}); chrom.getGene(0).setAllele(new Integer(1)); chrom.getGene(1).setAllele(new Integer( -3)); IDataCreators doc2 = builder.representChromosomeAsDocument(chrom); IDataElement elem = doc2.getTree().item(0); privateAccessor.setField(elem, "m_elements", null); Document result = (Document)doc.buildDocument(doc2); assertEquals(null, result.getParentNode()); assertEquals(1, result.getChildNodes().getLength()); Node child = result.getChildNodes().item(0); assertEquals("chromosome", child.getNodeName()); assertEquals(0, child.getChildNodes().getLength()); } }
3e13905ad3f63cd7517754a7f87c732028a991d8
1,631
java
Java
src/cn/webwheel/setters/AbstractSetter.java
kobe2000/webwheel
68cb81804cbc634a4a5684a98c7dfb7d3518a225
[ "Apache-2.0" ]
2
2017-03-01T01:33:42.000Z
2017-10-12T13:28:50.000Z
src/cn/webwheel/setters/AbstractSetter.java
kobe2000/webwheel
68cb81804cbc634a4a5684a98c7dfb7d3518a225
[ "Apache-2.0" ]
null
null
null
src/cn/webwheel/setters/AbstractSetter.java
kobe2000/webwheel
68cb81804cbc634a4a5684a98c7dfb7d3518a225
[ "Apache-2.0" ]
null
null
null
28.614035
96
0.631514
8,265
/* * Copyright 2017 XueSong Guo. * * 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 cn.webwheel.setters; import cn.webwheel.Setter; import java.lang.reflect.*; import java.util.Map; abstract public class AbstractSetter<T> implements Setter<T> { protected T def; protected void set(Object instance, Member member, T value) { if (member == null) return; try { if (member instanceof Field) { ((Field) member).set(instance, value); } else { ((Method) member).invoke(instance, value); } } catch (IllegalAccessException ignored) { } catch (InvocationTargetException ignored) { } } protected T get(Object param) { return null; } @Override public T set(Object instance, Member member, Map<String, Object> params, String paramName) { if (paramName == null) return def; Object param = params.get(paramName); T t = get(param); if (t != null) { set(instance, member, t); return t; } return def; } }
3e13907f0dabad436e395f4d7748b0a1fa2164d6
426
java
Java
fxiaoke-xjl/src/main/java/com/chylee/fxiaoke/xjl/service/FxkBaoxiaoService.java
chy1ee/fxiaoke
960a0962626636b51a976208bc1cc83a9e4ddac5
[ "MIT" ]
null
null
null
fxiaoke-xjl/src/main/java/com/chylee/fxiaoke/xjl/service/FxkBaoxiaoService.java
chy1ee/fxiaoke
960a0962626636b51a976208bc1cc83a9e4ddac5
[ "MIT" ]
null
null
null
fxiaoke-xjl/src/main/java/com/chylee/fxiaoke/xjl/service/FxkBaoxiaoService.java
chy1ee/fxiaoke
960a0962626636b51a976208bc1cc83a9e4ddac5
[ "MIT" ]
null
null
null
38.727273
81
0.826291
8,266
package com.chylee.fxiaoke.xjl.service; import com.chylee.fxiaoke.xjl.event.data.object.Object_okom1__c; import com.chylee.fxiaoke.common.exception.CrmApiException; import com.chylee.fxiaoke.common.exception.CrmDataException; public interface FxkBaoxiaoService { void update(String dataId, String db, String dh) throws CrmApiException; Object_okom1__c loadById(String id) throws CrmDataException, CrmApiException; }
3e13910ceec015f2c59b8b0aba7c71f37aff5118
3,227
java
Java
src/main/java/io/berndruecker/onboarding/customer/process/DmnJobHandler.java
robert0714/customer-onboarding-camundacloud-springboot-extended
1aaabb4a584f5a6b7b0da6360cb99f4cfa2e8af1
[ "Apache-2.0" ]
5
2021-03-25T15:00:31.000Z
2022-03-24T12:03:14.000Z
src/main/java/io/berndruecker/onboarding/customer/process/DmnJobHandler.java
robert0714/customer-onboarding-camundacloud-springboot-extended
1aaabb4a584f5a6b7b0da6360cb99f4cfa2e8af1
[ "Apache-2.0" ]
2
2021-12-14T18:35:21.000Z
2021-12-14T18:36:45.000Z
src/main/java/io/berndruecker/onboarding/customer/process/DmnJobHandler.java
robert0714/customer-onboarding-camundacloud-springboot-extended
1aaabb4a584f5a6b7b0da6360cb99f4cfa2e8af1
[ "Apache-2.0" ]
3
2021-09-28T22:34:13.000Z
2022-03-24T12:03:15.000Z
39.353659
102
0.643632
8,267
package io.berndruecker.onboarding.customer.process; import io.camunda.zeebe.client.api.response.ActivatedJob; import io.camunda.zeebe.client.api.worker.JobClient; import io.camunda.zeebe.spring.client.annotation.ZeebeWorker; import org.camunda.bpm.dmn.engine.DmnDecision; import org.camunda.bpm.dmn.engine.DmnDecisionResult; import org.camunda.bpm.dmn.engine.DmnEngine; import org.camunda.bpm.model.dmn.Dmn; import org.camunda.bpm.model.dmn.DmnModelInstance; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.Collections; import java.util.HashMap; import java.util.Map; @Component public class DmnJobHandler { private Logger logger = LoggerFactory.getLogger(DmnJobHandler.class); private static final String DECISION_ID_HEADER = "decisionRef"; @Autowired private DmnEngine dmnEngine; @Value("classpath*:*.dmn") private Resource[] resources; private final Map<String, DmnDecision> decisionsById = new HashMap<>(); @ZeebeWorker(type = "DMN") public void handleDecisionTask(JobClient client, ActivatedJob job) { final DmnDecision decision = findDecisionForTask(job); final Map<String, Object> variables = job.getVariablesAsMap(); final DmnDecisionResult decisionResult = dmnEngine.evaluateDecision(decision, variables); client.newCompleteCommand(job.getKey()) // .variables(Collections.singletonMap("result", decisionResult)) // .send(); } private DmnDecision findDecisionForTask(ActivatedJob job) { final String decisionId = job.getCustomHeaders().get(DECISION_ID_HEADER); if (decisionId == null || decisionId.isEmpty()) { throw new RuntimeException("Missing header: '" + DECISION_ID_HEADER + "'"); } final DmnDecision decision = decisionsById.get(decisionId); if (decision == null) { throw new RuntimeException(String.format("No decision found with id: '%s'", decisionId)); } return decision; } @PostConstruct public void readDmnModelsFromClasspath() { logger.info("Load DMN files from classpath: {}", resources); for (Resource dmnResource: resources) { try { DmnModelInstance dmnModel = Dmn.readModelFromStream(dmnResource.getInputStream()); dmnEngine.parseDecisions(dmnModel).forEach( // decision -> { logger.info( "Found decision with id '{}' in file: {}", decision.getKey(), dmnResource); decisionsById.put(decision.getKey(), decision); }); } catch (Throwable t) { logger.warn("Failed to parse decision: {}", dmnResource, t); } } } }
3e13924b326cfd66b4f2060e6b84d0175e4af515
1,984
java
Java
src/game/AttackBehaviour.java
peijiin/apocalypse
2a92de5ea734541d9eb30fe8b3bf9555b1d50cfb
[ "MIT" ]
null
null
null
src/game/AttackBehaviour.java
peijiin/apocalypse
2a92de5ea734541d9eb30fe8b3bf9555b1d50cfb
[ "MIT" ]
null
null
null
src/game/AttackBehaviour.java
peijiin/apocalypse
2a92de5ea734541d9eb30fe8b3bf9555b1d50cfb
[ "MIT" ]
null
null
null
28.342857
86
0.737399
8,268
package game; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import edu.monash.fit2099.engine.Action; import edu.monash.fit2099.engine.Actor; import edu.monash.fit2099.engine.Exit; import edu.monash.fit2099.engine.GameMap; /** * A class that generates an AttackAction if the current Actor is standing * next to an Actor that they can attack. * * @author ram * @author Tan Wei Li * */ public class AttackBehaviour implements Behaviour { /**The team (i.e. ZombieCapability) of the actor's target*/ private ZombieCapability attackableTeam; /** * Constructor. * * Sets the team (i.e. ZombieCapability) that the owner of this * Behaviour is allowed to attack. * * @param attackableTeam Team descriptor for ZombieActors that can be attacked * @throws NullPointerException if attackableTeam argument is null */ public AttackBehaviour(ZombieCapability attackableTeam) throws NullPointerException { Objects.requireNonNull(attackableTeam); this.attackableTeam = attackableTeam; } /** * Returns an AttackAction that attacks an adjacent attackable Actor. * Actors are attackable if their ZombieCapability matches the * "undeadness status" set * * @throws NullPointerException if actor or map argument is null */ @Override public Action getAction(Actor actor, GameMap map) throws NullPointerException { Objects.requireNonNull(actor); Objects.requireNonNull(map); List<Exit> exits = new ArrayList<Exit>(map.locationOf(actor).getExits()); Collections.shuffle(exits); for (Exit e: exits) { if (!(e.getDestination().containsAnActor())) continue; if (e.getDestination().getActor().hasCapability(attackableTeam)) { if (attackableTeam.equals(ZombieCapability.UNDEAD)) { return new HumanAttackAction(e.getDestination().getActor()); } else { return new ZombieAttackAction(e.getDestination().getActor()); } } } return null; } }
3e13926df847ae8a8e7aa90ba18318f0df558e98
974
java
Java
skysail.server.designer.demo.accounts/src-gen/io/skysail/server/designer/demo/accounts/account/AccountsTransactionResource.java
evandor/skysail-framework
480df6f043ab85328ecc6cc38958c501edbc2374
[ "Apache-2.0" ]
1
2016-02-08T08:57:12.000Z
2016-02-08T08:57:12.000Z
skysail.server.designer.demo.accounts/src-gen/io/skysail/server/designer/demo/accounts/account/AccountsTransactionResource.java
evandor/skysail-framework
480df6f043ab85328ecc6cc38958c501edbc2374
[ "Apache-2.0" ]
3
2016-02-15T11:15:06.000Z
2016-03-01T11:57:56.000Z
skysail.server.designer.demo.accounts/src-gen/io/skysail/server/designer/demo/accounts/account/AccountsTransactionResource.java
evandor/skysail-framework
480df6f043ab85328ecc6cc38958c501edbc2374
[ "Apache-2.0" ]
null
null
null
28.647059
113
0.764887
8,269
package io.skysail.server.designer.demo.accounts.account; import java.util.List; import io.skysail.api.links.Link; import io.skysail.api.responses.SkysailResponse; import io.skysail.server.restlet.resources.EntityServerResource; import io.skysail.server.designer.demo.accounts.account.*; import io.skysail.server.designer.demo.accounts.account.resources.*; import io.skysail.server.designer.demo.accounts.transaction.*; import io.skysail.server.designer.demo.accounts.transaction.resources.*; /** * generated from targetRelationResource.stg */ public class AccountsTransactionResource extends EntityServerResource<Transaction> { @Override public SkysailResponse<?> eraseEntity() { return null; } @Override public Transaction getEntity() { return null; } @Override public List<Link> getLinks() { return super.getLinks(AccountsTransactionsResource.class, PostAccountsTransactionRelationResource.class); } }
3e1392c045054cba9c45b4f9b544ba7e4c34d75f
1,245
java
Java
src/test/java/Board/BoardControllerMock.java
ueisd/compteurpoints-jeu-go-java
25ee6e471b076afd39fd4e536434fe63ff4d0cd4
[ "MIT" ]
null
null
null
src/test/java/Board/BoardControllerMock.java
ueisd/compteurpoints-jeu-go-java
25ee6e471b076afd39fd4e536434fe63ff4d0cd4
[ "MIT" ]
null
null
null
src/test/java/Board/BoardControllerMock.java
ueisd/compteurpoints-jeu-go-java
25ee6e471b076afd39fd4e536434fe63ff4d0cd4
[ "MIT" ]
null
null
null
23.490566
71
0.683534
8,270
package Board; import Game.ErrorType; import Player.Color; import Player.Player; public class BoardControllerMock implements IBoardController { Board board; ErrorType currentError; public BoardControllerMock(int size) { this.board = new Board(size); } public Color getOccupationColorAtPosition(Position pos) { return board.getIntersection(pos).getOccupation().orElse(null); } @Override public Board getCurrentBoard() { return board; } @Override public boolean isActionKo(Position pos, Player p) { return currentError == ErrorType.Ko; } @Override public boolean isActionSuicide(Position pos, Player p) { return currentError == ErrorType.Suicide; } @Override public boolean isIntersectionVacant(Position position) { return currentError != ErrorType.IntersectionTaken; } @Override public boolean isPositionValid(Position position) { return currentError != ErrorType.InvalidPosition; } @Override public void putStoneOnBoard(Color color, Position position) { board.putStone(color, position); } public void setCurrentError(ErrorType err) { currentError = err; } }
3e13930f70ffa7136335dfb2d0cfb2efdf858572
110
java
Java
clodhopper-examples/src/main/java/org/battelle/clodhopper/examples/selection/SelectionType.java
hujunxianligong/clodhopper
97e8356f754aa53e805cedf83a6bebe53157b603
[ "Apache-2.0" ]
1
2021-01-03T09:26:40.000Z
2021-01-03T09:26:40.000Z
clodhopper-examples/src/main/java/org/battelle/clodhopper/examples/selection/SelectionType.java
hujunxianligong/clodhopper
97e8356f754aa53e805cedf83a6bebe53157b603
[ "Apache-2.0" ]
null
null
null
clodhopper-examples/src/main/java/org/battelle/clodhopper/examples/selection/SelectionType.java
hujunxianligong/clodhopper
97e8356f754aa53e805cedf83a6bebe53157b603
[ "Apache-2.0" ]
null
null
null
13.75
51
0.781818
8,271
package org.battelle.clodhopper.examples.selection; public enum SelectionType { SELECT, UNSELECT, BOTH }
3e1393b42d2fc05326160de38df310aa0f5f81fd
2,627
java
Java
core/src/test/java/io/grpc/internal/ExponentialBackoffPolicyTest.java
canon0415/grpc1.4
4c683a17b82a886d876c9858caa6c5f51a706098
[ "BSD-3-Clause" ]
null
null
null
core/src/test/java/io/grpc/internal/ExponentialBackoffPolicyTest.java
canon0415/grpc1.4
4c683a17b82a886d876c9858caa6c5f51a706098
[ "BSD-3-Clause" ]
null
null
null
core/src/test/java/io/grpc/internal/ExponentialBackoffPolicyTest.java
canon0415/grpc1.4
4c683a17b82a886d876c9858caa6c5f51a706098
[ "BSD-3-Clause" ]
null
null
null
35.5
86
0.737724
8,272
/* * Copyright 2015, Google Inc. All rights reserved. * * 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.grpc.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Random; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Test for {@link ExponentialBackoffPolicy}. */ @RunWith(JUnit4.class) public class ExponentialBackoffPolicyTest { private ExponentialBackoffPolicy policy = new ExponentialBackoffPolicy(); private Random notRandom = new Random() { @Override public double nextDouble() { return .5; } }; @Test public void maxDelayReached() { long maxBackoffNanos = 120 * 1000; policy.setMaxBackoffNanos(maxBackoffNanos) .setJitter(0) .setRandom(notRandom); for (int i = 0; i < 50; i++) { if (maxBackoffNanos == policy.nextBackoffNanos()) { return; // Success } } assertEquals("max delay not reached", maxBackoffNanos, policy.nextBackoffNanos()); } @Test public void canProvide() { assertNotNull(new ExponentialBackoffPolicy.Provider().get()); } }
3e1393cab0fe0577e25b71d0b0ba2f86c0d24c2a
24,599
java
Java
exec/java-exec/src/main/java/org/apache/drill/exec/work/foreman/Foreman.java
simbatech/incubator-drill
60048be7ff8cde657052dbd26d804d93cd7b0b84
[ "Apache-2.0" ]
null
null
null
exec/java-exec/src/main/java/org/apache/drill/exec/work/foreman/Foreman.java
simbatech/incubator-drill
60048be7ff8cde657052dbd26d804d93cd7b0b84
[ "Apache-2.0" ]
null
null
null
exec/java-exec/src/main/java/org/apache/drill/exec/work/foreman/Foreman.java
simbatech/incubator-drill
60048be7ff8cde657052dbd26d804d93cd7b0b84
[ "Apache-2.0" ]
null
null
null
35.702467
166
0.716127
8,273
/** * 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.drill.exec.work.foreman; import io.netty.buffer.ByteBuf; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.drill.common.config.DrillConfig; import org.apache.drill.common.exceptions.ExecutionSetupException; import org.apache.drill.common.logical.LogicalPlan; import org.apache.drill.common.logical.PlanProperties.Generator.ResultMode; import org.apache.drill.exec.ExecConstants; import org.apache.drill.exec.coord.DistributedSemaphore; import org.apache.drill.exec.coord.DistributedSemaphore.DistributedLease; import org.apache.drill.exec.exception.OptimizerException; import org.apache.drill.exec.ops.FragmentContext; import org.apache.drill.exec.ops.QueryContext; import org.apache.drill.exec.opt.BasicOptimizer; import org.apache.drill.exec.physical.PhysicalPlan; import org.apache.drill.exec.physical.base.FragmentRoot; import org.apache.drill.exec.physical.base.PhysicalOperator; import org.apache.drill.exec.physical.config.ExternalSort; import org.apache.drill.exec.physical.impl.materialize.QueryWritableBatch; import org.apache.drill.exec.planner.fragment.Fragment; import org.apache.drill.exec.planner.fragment.MakeFragmentsVisitor; import org.apache.drill.exec.planner.fragment.PlanningSet; import org.apache.drill.exec.planner.fragment.SimpleParallelizer; import org.apache.drill.exec.planner.fragment.StatsCollector; import org.apache.drill.exec.planner.sql.DirectPlan; import org.apache.drill.exec.planner.sql.DrillSqlWorker; import org.apache.drill.exec.proto.BitControl.InitializeFragments; import org.apache.drill.exec.proto.BitControl.PlanFragment; import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint; import org.apache.drill.exec.proto.ExecProtos.FragmentHandle; import org.apache.drill.exec.proto.GeneralRPCProtos.Ack; import org.apache.drill.exec.proto.UserBitShared.DrillPBError; import org.apache.drill.exec.proto.UserBitShared.QueryId; import org.apache.drill.exec.proto.UserBitShared.QueryResult; import org.apache.drill.exec.proto.UserBitShared.QueryResult.QueryState; import org.apache.drill.exec.proto.UserProtos.RunQuery; import org.apache.drill.exec.proto.helper.QueryIdHelper; import org.apache.drill.exec.rpc.BaseRpcOutcomeListener; import org.apache.drill.exec.rpc.RpcException; import org.apache.drill.exec.rpc.RpcOutcomeListener; import org.apache.drill.exec.rpc.control.Controller; import org.apache.drill.exec.rpc.user.UserServer.UserClientConnection; import org.apache.drill.exec.server.DrillbitContext; import org.apache.drill.exec.util.Pointer; import org.apache.drill.exec.work.EndpointListener; import org.apache.drill.exec.work.ErrorHelper; import org.apache.drill.exec.work.QueryWorkUnit; import org.apache.drill.exec.work.WorkManager.WorkerBee; import org.apache.drill.exec.work.batch.IncomingBuffers; import org.apache.drill.exec.work.fragment.FragmentExecutor; import org.apache.drill.exec.work.fragment.RootFragmentManager; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; /** * Foreman manages all queries where this is the driving/root node. * * The flow is as follows: * - Foreman is submitted as a runnable. * - Runnable does query planning. * - PENDING > RUNNING * - Runnable sends out starting fragments * - Status listener are activated * - Foreman listens for state move messages. * */ public class Foreman implements Runnable, Closeable, Comparable<Object> { static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Foreman.class); private QueryId queryId; private RunQuery queryRequest; private QueryContext context; private QueryManager queryManager; private WorkerBee bee; private UserClientConnection initiatingClient; private volatile QueryState state; private final DistributedSemaphore smallSemaphore; private final DistributedSemaphore largeSemaphore; private final long queueThreshold; private final long queueTimeout; private volatile DistributedLease lease; private final boolean queuingEnabled; private FragmentExecutor rootRunner; private final CountDownLatch acceptExternalEvents = new CountDownLatch(1); private final StateListener stateListener = new StateListener(); private final ResponseSendListener responseListener = new ResponseSendListener(); public Foreman(WorkerBee bee, DrillbitContext dContext, UserClientConnection connection, QueryId queryId, RunQuery queryRequest) { this.queryId = queryId; this.queryRequest = queryRequest; this.context = new QueryContext(connection.getSession(), queryId, dContext); // set up queuing this.queuingEnabled = context.getOptions().getOption(ExecConstants.ENABLE_QUEUE_KEY).bool_val; if (queuingEnabled) { int smallQueue = context.getOptions().getOption(ExecConstants.SMALL_QUEUE_KEY).num_val.intValue(); int largeQueue = context.getOptions().getOption(ExecConstants.LARGE_QUEUE_KEY).num_val.intValue(); this.largeSemaphore = dContext.getClusterCoordinator().getSemaphore("query.large", largeQueue); this.smallSemaphore = dContext.getClusterCoordinator().getSemaphore("query.small", smallQueue); this.queueThreshold = context.getOptions().getOption(ExecConstants.QUEUE_THRESHOLD_KEY).num_val; this.queueTimeout = context.getOptions().getOption(ExecConstants.QUEUE_TIMEOUT_KEY).num_val; } else { this.largeSemaphore = null; this.smallSemaphore = null; this.queueThreshold = 0; this.queueTimeout = 0; } // end queuing setup. this.initiatingClient = connection; this.queryManager = new QueryManager(queryId, queryRequest, bee.getContext().getPersistentStoreProvider(), stateListener, this); this.bee = bee; recordNewState(QueryState.PENDING); } public QueryContext getContext() { return context; } public void cancel() { stateListener.moveToState(QueryState.CANCELED, null); } private void cleanup(QueryResult result) { bee.retireForeman(this); context.getWorkBus().removeFragmentStatusListener(queryId); context.getClusterCoordinator().removeDrillbitStatusListener(queryManager); if(result != null){ initiatingClient.sendResult(responseListener, new QueryWritableBatch(result), true); } releaseLease(); } /** * Called by execution pool to do foreman setup. Actual query execution is a separate phase (and can be scheduled). */ public void run() { final String originalThread = Thread.currentThread().getName(); Thread.currentThread().setName(QueryIdHelper.getQueryId(queryId) + ":foreman"); getStatus().markStart(); // convert a run query request into action try { switch (queryRequest.getType()) { case LOGICAL: parseAndRunLogicalPlan(queryRequest.getPlan()); break; case PHYSICAL: parseAndRunPhysicalPlan(queryRequest.getPlan()); break; case SQL: runSQL(queryRequest.getPlan()); break; default: throw new IllegalStateException(); } } catch (ForemanException e) { moveToState(QueryState.FAILED, e); } catch (AssertionError | Exception ex) { moveToState(QueryState.FAILED, new ForemanException("Unexpected exception during fragment initialization.", ex)); } catch (OutOfMemoryError e) { System.out.println("Out of memory, exiting."); e.printStackTrace(); System.out.flush(); System.exit(-1); } finally { Thread.currentThread().setName(originalThread); } } private void releaseLease() { if (lease != null) { try { lease.close(); } catch (Exception e) { logger.warn("Failure while releasing lease.", e); } ; } } private void parseAndRunLogicalPlan(String json) throws ExecutionSetupException { LogicalPlan logicalPlan; try { logicalPlan = context.getPlanReader().readLogicalPlan(json); } catch (IOException e) { throw new ForemanException("Failure parsing logical plan.", e); } if (logicalPlan.getProperties().resultMode == ResultMode.LOGICAL) { throw new ForemanException( "Failure running plan. You requested a result mode of LOGICAL and submitted a logical plan. In this case you're output mode must be PHYSICAL or EXEC."); } log(logicalPlan); PhysicalPlan physicalPlan = convert(logicalPlan); if (logicalPlan.getProperties().resultMode == ResultMode.PHYSICAL) { returnPhysical(physicalPlan); return; } log(physicalPlan); runPhysicalPlan(physicalPlan); } private void log(LogicalPlan plan) { if (logger.isDebugEnabled()) { logger.debug("Logical {}", plan.unparse(context.getConfig())); } } private void log(PhysicalPlan plan) { if (logger.isDebugEnabled()) { try { String planText = context.getConfig().getMapper().writeValueAsString(plan); logger.debug("Physical {}", planText); } catch (IOException e) { logger.warn("Error while attempting to log physical plan.", e); } } } private void returnPhysical(PhysicalPlan plan) throws ExecutionSetupException { String jsonPlan = plan.unparse(context.getConfig().getMapper().writer()); runPhysicalPlan(DirectPlan.createDirectPlan(context, new PhysicalFromLogicalExplain(jsonPlan))); } public static class PhysicalFromLogicalExplain { public String json; public PhysicalFromLogicalExplain(String json) { super(); this.json = json; } } private void parseAndRunPhysicalPlan(String json) throws ExecutionSetupException { try { PhysicalPlan plan = context.getPlanReader().readPhysicalPlan(json); runPhysicalPlan(plan); } catch (IOException e) { throw new ForemanSetupException("Failure while parsing physical plan.", e); } } private void runPhysicalPlan(PhysicalPlan plan) throws ExecutionSetupException { validatePlan(plan); setupSortMemoryAllocations(plan); acquireQuerySemaphore(plan); final QueryWorkUnit work = getQueryWorkUnit(plan); this.context.getWorkBus().setFragmentStatusListener(work.getRootFragment().getHandle().getQueryId(), queryManager); this.context.getClusterCoordinator().addDrillbitStatusListener(queryManager); logger.debug("Submitting fragments to run."); final PlanFragment rootPlanFragment = work.getRootFragment(); assert queryId == rootPlanFragment.getHandle().getQueryId(); queryManager.setup(rootPlanFragment.getHandle(), context.getCurrentEndpoint(), work.getFragments().size()); // set up the root fragment first so we'll have incoming buffers available. setupRootFragment(rootPlanFragment, initiatingClient, work.getRootOperator()); setupNonRootFragments(work.getFragments()); bee.getContext().getAllocator().resetFragmentLimits(); moveToState(QueryState.RUNNING, null); logger.debug("Fragments running."); } private void validatePlan(PhysicalPlan plan) throws ForemanSetupException{ if (plan.getProperties().resultMode != ResultMode.EXEC) { throw new ForemanSetupException(String.format( "Failure running plan. You requested a result mode of %s and a physical plan can only be output as EXEC", plan.getProperties().resultMode)); } } private void setupSortMemoryAllocations(PhysicalPlan plan){ int sortCount = 0; for (PhysicalOperator op : plan.getSortedOperators()) { if (op instanceof ExternalSort) { sortCount++; } } if (sortCount > 0) { long maxWidthPerNode = context.getOptions().getOption(ExecConstants.MAX_WIDTH_PER_NODE_KEY).num_val; long maxAllocPerNode = Math.min(DrillConfig.getMaxDirectMemory(), context.getConfig().getLong(ExecConstants.TOP_LEVEL_MAX_ALLOC)); maxAllocPerNode = Math.min(maxAllocPerNode, context.getOptions().getOption(ExecConstants.MAX_QUERY_MEMORY_PER_NODE_KEY).num_val); long maxSortAlloc = maxAllocPerNode / (sortCount * maxWidthPerNode); logger.debug("Max sort alloc: {}", maxSortAlloc); for (PhysicalOperator op : plan.getSortedOperators()) { if (op instanceof ExternalSort) { ((ExternalSort) op).setMaxAllocation(maxSortAlloc); } } } } private void acquireQuerySemaphore(PhysicalPlan plan) throws ForemanSetupException { double size = 0; for (PhysicalOperator ops : plan.getSortedOperators()) { size += ops.getCost(); } if (queuingEnabled) { try { if (size > this.queueThreshold) { this.lease = largeSemaphore.acquire(this.queueTimeout, TimeUnit.MILLISECONDS); } else { this.lease = smallSemaphore.acquire(this.queueTimeout, TimeUnit.MILLISECONDS); } } catch (Exception e) { throw new ForemanSetupException("Unable to acquire slot for query.", e); } } } private QueryWorkUnit getQueryWorkUnit(PhysicalPlan plan) throws ExecutionSetupException { PhysicalOperator rootOperator = plan.getSortedOperators(false).iterator().next(); MakeFragmentsVisitor makeFragmentsVisitor = new MakeFragmentsVisitor(); Fragment rootFragment = rootOperator.accept(makeFragmentsVisitor, null); PlanningSet planningSet = StatsCollector.collectStats(rootFragment); SimpleParallelizer parallelizer = new SimpleParallelizer(context); return parallelizer.getFragments(context.getOptions().getOptionList(), context.getCurrentEndpoint(), queryId, context.getActiveEndpoints(), context.getPlanReader(), rootFragment, planningSet, initiatingClient.getSession()); } /** * Tells the foreman to move to a new state. Note that * @param state * @return */ private synchronized boolean moveToState(QueryState newState, Exception exception){ logger.debug("State change requested. {} --> {}", state, newState); outside: switch(state) { case PENDING: // since we're moving out of pending, we can now start accepting other changes in state. // This guarantees that the first state change is driven by the original thread. acceptExternalEvents.countDown(); if(newState == QueryState.RUNNING){ recordNewState(QueryState.RUNNING); return true; } // fall through to running behavior. // case RUNNING: { switch(newState){ case CANCELED: { assert exception == null; recordNewState(QueryState.CANCELED); cancelExecutingFragments(); QueryResult result = QueryResult.newBuilder() // .setQueryId(queryId) // .setQueryState(QueryState.CANCELED) // .setIsLastChunk(true) // .build(); cleanup(result); return true; } case COMPLETED: { assert exception == null; recordNewState(QueryState.COMPLETED); // QueryResult result = QueryResult // // .newBuilder() // // .setIsLastChunk(true) // // .setQueryState(QueryState.COMPLETED) // // .setQueryId(queryId) // // .build(); cleanup(null); return true; } case FAILED: assert exception != null; recordNewState(QueryState.FAILED); cancelExecutingFragments(); DrillPBError error = ErrorHelper.logAndConvertError(context.getCurrentEndpoint(), "Query failed.", exception, logger); QueryResult result = QueryResult // .newBuilder() // .addError(error) // .setIsLastChunk(true) // .setQueryState(QueryState.FAILED) // .setQueryId(queryId) // .build(); cleanup(result); return true; default: break outside; } } case CANCELED: case COMPLETED: case FAILED: { // no op. logger.info("Dropping request to move to {} state as query is already at {} state (which is terminal).", newState, state, exception); return false; } } throw new IllegalStateException(String.format("Failure trying to change states: %s --> %s", state.name(), newState.name())); } private void cancelExecutingFragments(){ // Stop all framgents with a currently active status. List<FragmentData> fragments = getStatus().getFragmentData(); Collections.sort(fragments, new Comparator<FragmentData>() { @Override public int compare(FragmentData o1, FragmentData o2) { return o2.getHandle().getMajorFragmentId() - o1.getHandle().getMajorFragmentId(); } }); for(FragmentData data: fragments){ FragmentHandle handle = data.getStatus().getHandle(); switch(data.getStatus().getProfile().getState()){ case SENDING: case AWAITING_ALLOCATION: case RUNNING: if(data.isLocal()){ rootRunner.cancel(); }else{ bee.getContext().getController().getTunnel(data.getEndpoint()).cancelFragment(new CancelListener(data.getEndpoint(), handle), handle); } break; default: break; } } } private QueryStatus getStatus(){ return queryManager.getStatus(); } private void recordNewState(QueryState newState){ this.state = newState; getStatus().updateQueryStateInStore(newState); } private void runSQL(String sql) throws ExecutionSetupException { DrillSqlWorker sqlWorker = new DrillSqlWorker(context); Pointer<String> textPlan = new Pointer<>(); PhysicalPlan plan = sqlWorker.getPlan(sql, textPlan); getStatus().setPlanText(textPlan.value); runPhysicalPlan(plan); } private PhysicalPlan convert(LogicalPlan plan) throws OptimizerException { if (logger.isDebugEnabled()) { logger.debug("Converting logical plan {}.", plan.toJsonStringSafe(context.getConfig())); } return new BasicOptimizer(DrillConfig.create(), context, initiatingClient).optimize( new BasicOptimizer.BasicOptimizationContext(context), plan); } public QueryId getQueryId() { return queryId; } @Override public void close() throws IOException { } public QueryStatus getQueryStatus() { return this.queryManager.getStatus(); } private void setupRootFragment(PlanFragment rootFragment, UserClientConnection rootClient, FragmentRoot rootOperator) throws ExecutionSetupException { FragmentContext rootContext = new FragmentContext(bee.getContext(), rootFragment, rootClient, bee.getContext() .getFunctionImplementationRegistry()); IncomingBuffers buffers = new IncomingBuffers(rootOperator, rootContext); rootContext.setBuffers(buffers); // add fragment to local node. queryManager.addFragmentStatusTracker(rootFragment, true); this.rootRunner = new FragmentExecutor(rootContext, bee, rootOperator, queryManager.getRootStatusHandler(rootContext, rootFragment)); RootFragmentManager fragmentManager = new RootFragmentManager(rootFragment.getHandle(), buffers, rootRunner); if (buffers.isDone()) { // if we don't have to wait for any incoming data, start the fragment runner. bee.addFragmentRunner(fragmentManager.getRunnable()); } else { // if we do, record the fragment manager in the workBus. bee.getContext().getWorkBus().setFragmentManager(fragmentManager); } } private void setupNonRootFragments(Collection<PlanFragment> fragments) throws ForemanException{ Multimap<DrillbitEndpoint, PlanFragment> leafFragmentMap = ArrayListMultimap.create(); Multimap<DrillbitEndpoint, PlanFragment> intFragmentMap = ArrayListMultimap.create(); // record all fragments for status purposes. for (PlanFragment f : fragments) { // logger.debug("Tracking intermediate remote node {} with data {}", f.getAssignment(), f.getFragmentJson()); queryManager.addFragmentStatusTracker(f, false); if (f.getLeafFragment()) { leafFragmentMap.put(f.getAssignment(), f); } else { intFragmentMap.put(f.getAssignment(), f); } } CountDownLatch latch = new CountDownLatch(intFragmentMap.keySet().size()); // send remote intermediate fragments for (DrillbitEndpoint ep : intFragmentMap.keySet()) { sendRemoteFragments(ep, intFragmentMap.get(ep), latch); } // wait for send complete try { latch.await(); } catch (InterruptedException e) { throw new ForemanException("Interrupted while waiting to complete send of remote fragments.", e); } // send remote (leaf) fragments. for (DrillbitEndpoint ep : leafFragmentMap.keySet()) { sendRemoteFragments(ep, leafFragmentMap.get(ep), null); } } public RpcOutcomeListener<Ack> getSubmitListener(DrillbitEndpoint endpoint, InitializeFragments value, CountDownLatch latch){ return new FragmentSubmitListener(endpoint, value, latch); } private void sendRemoteFragments(DrillbitEndpoint assignment, Collection<PlanFragment> fragments, CountDownLatch latch){ Controller controller = bee.getContext().getController(); InitializeFragments.Builder fb = InitializeFragments.newBuilder(); for(PlanFragment f : fragments){ fb.addFragment(f); } InitializeFragments initFrags = fb.build(); logger.debug("Sending remote fragments to node {} with data {}", assignment, initFrags); FragmentSubmitListener listener = new FragmentSubmitListener(assignment, initFrags, latch); controller.getTunnel(assignment).sendFragments(listener, initFrags); } public QueryState getState(){ return state; } private class FragmentSubmitListener extends EndpointListener<Ack, InitializeFragments>{ private CountDownLatch latch; public FragmentSubmitListener(DrillbitEndpoint endpoint, InitializeFragments value, CountDownLatch latch) { super(endpoint, value); this.latch = latch; } @Override public void success(Ack ack, ByteBuf byteBuf) { if (latch != null) { latch.countDown(); } } @Override public void failed(RpcException ex) { logger.debug("Failure while sending fragment. Stopping query.", ex); moveToState(QueryState.FAILED, ex); } } public class StateListener { public boolean moveToState(QueryState newState, Exception ex){ try{ acceptExternalEvents.await(); }catch(InterruptedException e){ logger.warn("Interrupted while waiting to move state.", e); return false; } return Foreman.this.moveToState(newState, ex); } } @Override public int compareTo(Object o) { return hashCode() - o.hashCode(); } private class ResponseSendListener extends BaseRpcOutcomeListener<Ack> { @Override public void failed(RpcException ex) { logger .info( "Failure while trying communicate query result to initating client. This would happen if a client is disconnected before response notice can be sent.", ex); moveToState(QueryState.FAILED, ex); } } private class CancelListener extends EndpointListener<Ack, FragmentHandle>{ public CancelListener(DrillbitEndpoint endpoint, FragmentHandle handle) { super(endpoint, handle); } @Override public void failed(RpcException ex) { logger.error("Failure while attempting to cancel fragment {} on endpoint {}.", value, endpoint, ex); } @Override public void success(Ack value, ByteBuf buf) { if(!value.getOk()){ logger.warn("Remote node {} responded negative on cancellation request for fragment {}.", endpoint, value); } // do nothing. } } }
3e1394448656966c8f4a867723e1a68e16e8e83b
17,582
java
Java
sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpReceiveLinkProcessor.java
Azure-Fluent/azure-sdk-for-java
c123e88d3e78b3d1b81a977aae0646220457f2c1
[ "MIT" ]
1
2020-10-05T18:51:27.000Z
2020-10-05T18:51:27.000Z
sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpReceiveLinkProcessor.java
Azure-Fluent/azure-sdk-for-java
c123e88d3e78b3d1b81a977aae0646220457f2c1
[ "MIT" ]
24
2020-05-27T05:21:27.000Z
2021-06-25T15:37:42.000Z
sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpReceiveLinkProcessor.java
Azure-Fluent/azure-sdk-for-java
c123e88d3e78b3d1b81a977aae0646220457f2c1
[ "MIT" ]
null
null
null
35.305221
119
0.603003
8,274
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.messaging.eventhubs.implementation; import com.azure.core.amqp.AmqpEndpointState; import com.azure.core.amqp.AmqpRetryPolicy; import com.azure.core.amqp.implementation.AmqpReceiveLink; import com.azure.core.util.logging.ClientLogger; import org.apache.qpid.proton.message.Message; import org.reactivestreams.Subscription; import reactor.core.CoreSubscriber; import reactor.core.Disposable; import reactor.core.Disposables; import reactor.core.Exceptions; import reactor.core.publisher.FluxProcessor; import reactor.core.publisher.Mono; import reactor.core.publisher.Operators; import java.time.Duration; import java.util.Deque; import java.util.Objects; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; /** * Processes AMQP receive links into a stream of AMQP messages. */ public class AmqpReceiveLinkProcessor extends FluxProcessor<AmqpReceiveLink, Message> implements Subscription { private final ClientLogger logger = new ClientLogger(AmqpReceiveLinkProcessor.class); private final Object lock = new Object(); private final AtomicBoolean isTerminated = new AtomicBoolean(); private final AtomicInteger retryAttempts = new AtomicInteger(); private final Deque<Message> messageQueue = new ConcurrentLinkedDeque<>(); private final AtomicBoolean hasFirstLink = new AtomicBoolean(); private final AtomicBoolean linkCreditsAdded = new AtomicBoolean(); private final AtomicReference<CoreSubscriber<? super Message>> downstream = new AtomicReference<>(); private final AtomicInteger wip = new AtomicInteger(); private final int prefetch; private final AmqpRetryPolicy retryPolicy; private final Disposable parentConnection; private volatile Throwable lastError; private volatile boolean isCancelled; private volatile AmqpReceiveLink currentLink; private volatile Disposable currentLinkSubscriptions; private volatile Disposable retrySubscription; // Opting to use AtomicReferenceFieldUpdater because Project Reactor provides utility methods that calculates // backpressure requests, sets the upstream correctly, and reports its state. private volatile Subscription upstream; private static final AtomicReferenceFieldUpdater<AmqpReceiveLinkProcessor, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(AmqpReceiveLinkProcessor.class, Subscription.class, "upstream"); private volatile long requested; private static final AtomicLongFieldUpdater<AmqpReceiveLinkProcessor> REQUESTED = AtomicLongFieldUpdater.newUpdater(AmqpReceiveLinkProcessor.class, "requested"); /** * Creates an instance of {@link AmqpReceiveLinkProcessor}. * * @param prefetch The number if messages to initially fetch. * @param retryPolicy Retry policy to apply when fetching a new AMQP channel. * @param parentConnection Represents the parent connection. * * @throws NullPointerException if {@code retryPolicy} is null. * @throws IllegalArgumentException if {@code prefetch} is less than 0. */ public AmqpReceiveLinkProcessor(int prefetch, AmqpRetryPolicy retryPolicy, Disposable parentConnection) { this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); this.parentConnection = Objects.requireNonNull(parentConnection, "'parentConnection' cannot be null."); if (prefetch < 0) { throw logger.logExceptionAsError(new IllegalArgumentException("'prefetch' cannot be less than 0.")); } this.prefetch = prefetch; } /** * Gets the error associated with this processor. * * @return Error associated with this processor. {@code null} if there is no error. */ @Override public Throwable getError() { return lastError; } /** * Gets whether or not the processor is terminated. * * @return {@code true} if the processor has terminated; false otherwise. */ @Override public boolean isTerminated() { return isTerminated.get() || isCancelled; } /** * When a subscription is obtained from upstream publisher. * * @param subscription Subscription to upstream publisher. */ @Override public void onSubscribe(Subscription subscription) { Objects.requireNonNull(subscription, "'subscription' cannot be null"); if (!Operators.setOnce(UPSTREAM, this, subscription)) { throw logger.logExceptionAsError(new IllegalStateException("Cannot set upstream twice.")); } requestUpstream(); } @Override public int getPrefetch() { return prefetch; } /** * When the next AMQP link is fetched. * * @param next The next AMQP receive link. */ @Override public void onNext(AmqpReceiveLink next) { Objects.requireNonNull(next, "'next' cannot be null."); if (isTerminated()) { logger.warning("linkName[{}] entityPath[{}]. Got another link when we have already terminated processor.", next.getLinkName(), next.getEntityPath()); Operators.onNextDropped(next, currentContext()); return; } final String linkName = next.getLinkName(); final String entityPath = next.getEntityPath(); logger.info("linkName[{}] entityPath[{}]. Setting next AMQP receive link.", linkName, entityPath); final AmqpReceiveLink oldChannel; final Disposable oldSubscription; synchronized (lock) { oldChannel = currentLink; oldSubscription = currentLinkSubscriptions; currentLink = next; // The first time, add the prefetch to the link as credits. if (!hasFirstLink.getAndSet(true)) { linkCreditsAdded.set(true); next.addCredits(prefetch); } next.setEmptyCreditListener(() -> getCreditsToAdd()); currentLinkSubscriptions = Disposables.composite( next.getEndpointStates().subscribe( state -> { // Connection was successfully opened, we can reset the retry interval. if (state == AmqpEndpointState.ACTIVE) { retryAttempts.set(0); } }, error -> { currentLink = null; logger.warning("linkName[{}] entityPath[{}]. Error occurred in link.", linkName, entityPath); onError(error); }, () -> { if (parentConnection.isDisposed() || isTerminated() || upstream == Operators.cancelledSubscription()) { logger.info("Terminal state reached. Disposing of link processor."); dispose(); } else { logger.info("Receive link endpoint states are closed. Requesting another."); final AmqpReceiveLink existing = currentLink; currentLink = null; if (existing != null) { existing.dispose(); } requestUpstream(); } }), next.receive().subscribe(message -> { messageQueue.add(message); drain(); })); } if (oldChannel != null) { oldChannel.dispose(); } if (oldSubscription != null) { oldSubscription.dispose(); } } /** * Sets up the downstream subscriber. * * @param actual The downstream subscriber. * * @throws IllegalStateException if there is already a downstream subscriber. */ @Override public void subscribe(CoreSubscriber<? super Message> actual) { Objects.requireNonNull(actual, "'actual' cannot be null."); final boolean terminateSubscriber = isTerminated() || (currentLink == null && upstream == Operators.cancelledSubscription()); if (isTerminated()) { final AmqpReceiveLink link = currentLink; final String linkName = link != null ? link.getLinkName() : "n/a"; final String entityPath = link != null ? link.getEntityPath() : "n/a"; logger.info("linkName[{}] entityPath[{}]. AmqpReceiveLink is already terminated.", linkName, entityPath); } else if (currentLink == null && upstream == Operators.cancelledSubscription()) { logger.info("There is no current link and upstream is terminated."); } if (terminateSubscriber) { actual.onSubscribe(Operators.emptySubscription()); if (hasError()) { actual.onError(lastError); } else { actual.onComplete(); } return; } if (downstream.compareAndSet(null, actual)) { actual.onSubscribe(this); drain(); } else { Operators.error(actual, logger.logExceptionAsError(new IllegalStateException( "There is already one downstream subscriber.'"))); } } /** * When an error occurs from the upstream publisher. If the {@code throwable} is a transient failure, another AMQP * element is requested if the {@link AmqpRetryPolicy} allows. Otherwise, the processor closes. * * @param throwable Error that occurred in upstream publisher. */ @Override public void onError(Throwable throwable) { Objects.requireNonNull(throwable, "'throwable' is required."); if (isTerminated() || isCancelled) { logger.info("AmqpReceiveLinkProcessor is terminated. Cannot process another error.", throwable); Operators.onErrorDropped(throwable, currentContext()); return; } final int attempt = retryAttempts.incrementAndGet(); final Duration retryInterval = retryPolicy.calculateRetryDelay(throwable, attempt); final AmqpReceiveLink link = currentLink; final String linkName = link != null ? link.getLinkName() : "n/a"; final String entityPath = link != null ? link.getEntityPath() : "n/a"; if (retryInterval != null && !parentConnection.isDisposed() && upstream != Operators.cancelledSubscription()) { logger.warning("linkName[{}] entityPath[{}]. Transient error occurred. Attempt: {}. Retrying after {} ms.", linkName, entityPath, attempt, retryInterval.toMillis(), throwable); retrySubscription = Mono.delay(retryInterval).subscribe(i -> requestUpstream()); return; } if (parentConnection.isDisposed()) { logger.info("Parent connection is disposed. Not reopening on error."); } logger.warning("linkName[{}] entityPath[{}]. Non-retryable error occurred in AMQP receive link.", linkName, entityPath, throwable); lastError = throwable; isTerminated.set(true); final CoreSubscriber<? super Message> subscriber = downstream.get(); if (subscriber != null) { subscriber.onError(throwable); } onDispose(); } /** * When the upstream publisher has no more items to emit. */ @Override public void onComplete() { this.upstream = Operators.cancelledSubscription(); } @Override public void dispose() { if (isTerminated.getAndSet(true)) { return; } drain(); onDispose(); } /** * When downstream subscriber makes a back-pressure request. */ @Override public void request(long request) { if (!Operators.validate(request)) { logger.warning("Invalid request: {}", request); return; } Operators.addCap(REQUESTED, this, request); final AmqpReceiveLink link = currentLink; if (link != null && !linkCreditsAdded.getAndSet(true)) { int credits = getCreditsToAdd(); logger.verbose("Link credits not yet added. Adding: {}", credits); link.addCredits(credits); } drain(); } /** * When downstream subscriber cancels their subscription. */ @Override public void cancel() { if (isCancelled) { return; } isCancelled = true; drain(); } /** * Requests another receive link from upstream. */ private void requestUpstream() { if (isTerminated()) { logger.info("Processor is terminated. Not requesting another link."); return; } else if (upstream == null) { logger.info("There is no upstream. Not requesting another link."); return; } else if (upstream == Operators.cancelledSubscription()) { logger.info("Upstream is cancelled or complete. Not requesting another link."); return; } synchronized (lock) { if (currentLink != null) { logger.info("Current link exists. Not requesting another link."); return; } } logger.info("Requesting a new AmqpReceiveLink from upstream."); upstream.request(1L); } private void onDispose() { if (retrySubscription != null && !retrySubscription.isDisposed()) { retrySubscription.dispose(); } if (currentLink != null) { currentLink.dispose(); } currentLink = null; if (currentLinkSubscriptions != null) { currentLinkSubscriptions.dispose(); } Operators.onDiscardQueueWithClear(messageQueue, currentContext(), null); } private void drain() { // If someone is already in this loop, then we are already clearing the queue. if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { if (wip.decrementAndGet() != 0) { logger.warning("There is another worker in drainLoop. But there should only be 1 worker."); } } } private void drainQueue() { final CoreSubscriber<? super Message> subscriber = downstream.get(); if (subscriber == null || checkAndSetTerminated()) { return; } long numberRequested = requested; boolean isEmpty = messageQueue.isEmpty(); while (numberRequested != 0L && !isEmpty) { if (checkAndSetTerminated()) { break; } long numberEmitted = 0L; while (numberRequested != numberEmitted) { if (isEmpty && checkAndSetTerminated()) { break; } Message message = messageQueue.poll(); if (message == null) { break; } if (isCancelled) { Operators.onDiscard(message, subscriber.currentContext()); Operators.onDiscardQueueWithClear(messageQueue, subscriber.currentContext(), null); return; } try { subscriber.onNext(message); } catch (Exception e) { logger.error("Exception occurred while handling downstream onNext operation.", e); throw logger.logExceptionAsError(Exceptions.propagate( Operators.onOperatorError(upstream, e, message, subscriber.currentContext()))); } numberEmitted++; isEmpty = messageQueue.isEmpty(); } if (requested != Long.MAX_VALUE) { numberRequested = REQUESTED.addAndGet(this, -numberEmitted); } } } private boolean checkAndSetTerminated() { if (!isTerminated()) { return false; } final CoreSubscriber<? super Message> subscriber = downstream.get(); final Throwable error = lastError; if (error != null) { subscriber.onError(error); } else { subscriber.onComplete(); } if (currentLink != null) { currentLink.dispose(); } messageQueue.clear(); return true; } private int getCreditsToAdd() { final CoreSubscriber<? super Message> subscriber = downstream.get(); final long r = requested; if (subscriber == null || r == 0) { logger.verbose("Not adding credits. No downstream subscribers or items requested."); linkCreditsAdded.set(false); return 0; } linkCreditsAdded.set(true); // If there is no back pressure, always add 1. Otherwise, add whatever is requested. return r == Long.MAX_VALUE ? 1 : Long.valueOf(r).intValue(); } }
3e139481c8b084a95f1f88e9862aa6fc86705496
1,793
java
Java
learningNetworkProgrammingWithJava/src/main/java/com/doctor/ch01/Java8EchoClient.java
sdcuike/book-reading
b8bf73d452b1358d9bdc7fdd873ba2891ee3432d
[ "Apache-2.0" ]
2
2017-12-22T02:58:22.000Z
2018-10-25T23:44:37.000Z
learningNetworkProgrammingWithJava/src/main/java/com/doctor/ch01/Java8EchoClient.java
sdcuike/book-reading
b8bf73d452b1358d9bdc7fdd873ba2891ee3432d
[ "Apache-2.0" ]
null
null
null
learningNetworkProgrammingWithJava/src/main/java/com/doctor/ch01/Java8EchoClient.java
sdcuike/book-reading
b8bf73d452b1358d9bdc7fdd873ba2891ee3432d
[ "Apache-2.0" ]
2
2017-08-22T05:06:21.000Z
2018-10-09T05:58:51.000Z
30.389831
130
0.586168
8,275
package com.doctor.ch01; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.util.Scanner; import java.util.function.Supplier; import java.util.stream.Stream; /** * @author sdcuike * * Created on 2016年4月12日 下午9:59:26 */ public class Java8EchoClient { /** * @param args * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException { System.out.println("simple echo client"); InetAddress localHost = InetAddress.getLocalHost(); System.out.println("waiting for connect to server :" + localHost); try (Socket socket = new Socket(localHost, 6666); PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));) { System.out.println("connected to server" + localHost); try (Scanner scanner = new Scanner(System.in)) { Supplier<String> input = () -> scanner.nextLine(); Stream.generate(input).map(s -> { pw.println(s); try { System.out.println("Server response:" + br.readLine()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return s; }).allMatch(s -> !s.equals("q")); } } catch (Exception e) { e.printStackTrace(); } } }
3e13949e8372bdf9bb2500ad78cdcd01f318f949
745
java
Java
src/main/java/nl/esciencecenter/xenon/cli/removejob/RemoveJobCommand.java
xenon-middleware/xenon-cli
6f44874cca0d8497f868d7efa6c16c178d4f3281
[ "Apache-2.0" ]
1
2018-10-10T08:37:40.000Z
2018-10-10T08:37:40.000Z
src/main/java/nl/esciencecenter/xenon/cli/removejob/RemoveJobCommand.java
NLeSC/xenon-cli
6f44874cca0d8497f868d7efa6c16c178d4f3281
[ "Apache-2.0" ]
57
2017-02-10T16:56:26.000Z
2019-02-08T10:28:08.000Z
src/main/java/nl/esciencecenter/xenon/cli/removejob/RemoveJobCommand.java
surf-eds/xenon-cli
6f44874cca0d8497f868d7efa6c16c178d4f3281
[ "Apache-2.0" ]
2
2017-08-11T06:56:32.000Z
2018-01-30T11:07:23.000Z
29.8
71
0.746309
8,276
package nl.esciencecenter.xenon.cli.removejob; import static nl.esciencecenter.xenon.cli.Utils.createScheduler; import net.sourceforge.argparse4j.inf.Namespace; import nl.esciencecenter.xenon.XenonException; import nl.esciencecenter.xenon.cli.XenonCommand; import nl.esciencecenter.xenon.schedulers.Scheduler; /** * Command to remove job from scheduler */ public class RemoveJobCommand extends XenonCommand { @Override public RemoveJobOutput run(Namespace res) throws XenonException { String jobId = res.getString("job_identifier"); try (Scheduler scheduler = createScheduler(res)) { scheduler.cancelJob(jobId); return new RemoveJobOutput(scheduler.getLocation(), jobId); } } }
3e1394a2459da879c69a26f7732ba6f814109999
838
java
Java
app/src/main/java/bookweather/com/bookweather/db/City.java
workofp/BooKWeather
d976459d8594e7890f8ef1782f61481d9a7340c8
[ "Apache-2.0" ]
null
null
null
app/src/main/java/bookweather/com/bookweather/db/City.java
workofp/BooKWeather
d976459d8594e7890f8ef1782f61481d9a7340c8
[ "Apache-2.0" ]
null
null
null
app/src/main/java/bookweather/com/bookweather/db/City.java
workofp/BooKWeather
d976459d8594e7890f8ef1782f61481d9a7340c8
[ "Apache-2.0" ]
null
null
null
17.829787
47
0.614558
8,277
package bookweather.com.bookweather.db; import org.litepal.crud.DataSupport; /** * Created by WP on 2017/8/12. */ 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; } }
3e1394f4c2b72cc6f99be91cb7ece555492a14c9
2,245
java
Java
bval-jsr303/src/main/java/org/apache/bval/jsr303/util/EnumerationConverter.java
tomitribe/bval
eff93b24d23610c7de6c739ad908bff459f3f08c
[ "Apache-2.0" ]
null
null
null
bval-jsr303/src/main/java/org/apache/bval/jsr303/util/EnumerationConverter.java
tomitribe/bval
eff93b24d23610c7de6c739ad908bff459f3f08c
[ "Apache-2.0" ]
6
2020-06-30T23:17:12.000Z
2021-08-25T15:33:57.000Z
bval-jsr303/src/main/java/org/apache/bval/jsr303/util/EnumerationConverter.java
tomitribe/bval
eff93b24d23610c7de6c739ad908bff459f3f08c
[ "Apache-2.0" ]
1
2018-11-23T10:18:00.000Z
2018-11-23T10:18:00.000Z
29.539474
98
0.668151
8,278
/* * 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.bval.jsr303.util; import org.apache.commons.beanutils.Converter; /** * A {@code org.apache.commons.beanutils.Converter} implementation to handle * Enumeration type. * * $Id$ */ public final class EnumerationConverter implements Converter { /** * The static converter instance. */ private static final EnumerationConverter INSTANCE = new EnumerationConverter(); /** * Returns this converter instance. * * @return this converter instance. */ public static EnumerationConverter getInstance() { return INSTANCE; } /** * This class can't be instantiated. */ private EnumerationConverter() { // do nothing } /** * {@inheritDoc} */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Object convert(Class type, Object value) { if (!type.isEnum()) { throw new RuntimeException("Only enum types supported in this version!"); } if (value == null) { throw new RuntimeException("Null values not supported in this version!"); } if (String.class != value.getClass()) { throw new RuntimeException("Only java.lang.String values supported in this version!"); } String stringValue = (String) value; final Class<Enum> enumClass = (Class<Enum>) type; return Enum.valueOf(enumClass, stringValue); } }
3e13950323bc4d4dcd083acf8dba28bf04692ca8
2,422
java
Java
src/test/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java
groupsvkg/algorithms
2eed08cd0de39ce73d445e83e6aa1476741edc51
[ "MIT" ]
12,964
2017-05-12T03:37:24.000Z
2022-03-31T22:30:15.000Z
src/test/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java
JiangnanVL/Algorithms
86661d3daf3063eae2ea9329b069456b87490b62
[ "MIT" ]
230
2017-06-03T00:05:18.000Z
2022-03-29T21:33:00.000Z
src/test/java/com/williamfiset/algorithms/datastructures/hashtable/DoubleHashingTestObject.java
JiangnanVL/Algorithms
86661d3daf3063eae2ea9329b069456b87490b62
[ "MIT" ]
3,708
2017-05-06T11:56:17.000Z
2022-03-31T11:11:02.000Z
24.877551
99
0.657096
8,279
/** * The DoubleHashingTestObject is an object to test the functionality of the hash-table implemented * with double hashing. * * @author William Fiset, envkt@example.com */ package com.williamfiset.algorithms.datastructures.hashtable; import java.util.Random; public class DoubleHashingTestObject implements SecondaryHash { private int hash, hash2; Integer intData = null; int[] vectorData = null; String stringData = null; static long[] randomVector; static Random R = new Random(); static int MAX_VECTOR_SIZE = 100000; static { randomVector = new long[MAX_VECTOR_SIZE]; for (int i = 0; i < MAX_VECTOR_SIZE; i++) { long val = R.nextLong(); while (val % 2 == 0) val = R.nextLong(); randomVector[i] = val; } } public DoubleHashingTestObject(int data) { intData = data; intHash(); computeHash(); } public DoubleHashingTestObject(int[] data) { if (data == null) throw new IllegalArgumentException("Cannot be null"); vectorData = data; vectorHash(); computeHash(); } public DoubleHashingTestObject(String data) { if (data == null) throw new IllegalArgumentException("Cannot be null"); stringData = data; stringHash(); computeHash(); } private void intHash() { hash2 = intData; } private void vectorHash() { for (int i = 0; i < vectorData.length; i++) hash2 += randomVector[i] * vectorData[i]; } private void stringHash() { // Multipicative hash function: final int INITIAL_VALUE = 0; int prime = 17; int power = 1; hash = INITIAL_VALUE; for (int i = 0; i < stringData.length(); i++) { int ch = stringData.charAt(i); hash2 += power * ch; power *= prime; } } private void computeHash() { if (intData != null) hash = intData.hashCode(); else if (stringData != null) hash = stringData.hashCode(); else hash = java.util.Arrays.hashCode(vectorData); } @Override public int hashCode() { return hash; } @Override public int hashCode2() { return hash2; } @Override public boolean equals(Object o) { DoubleHashingTestObject obj = (DoubleHashingTestObject) o; if (hash != obj.hash) return false; if (intData != null) return intData.equals(obj.intData); if (vectorData != null) return java.util.Arrays.equals(vectorData, obj.vectorData); return stringData.equals(obj.stringData); } }
3e139566fece5254a68eab17a9643b5047442e71
1,508
java
Java
tooling/intellij/src/main/java/org/stratos/lang/StratosPluginController.java
Arthur-Kamau/stratos
5afe8aa88ba765498779a6aecea908f2b0d927ef
[ "MIT" ]
8
2020-03-12T06:17:47.000Z
2020-11-06T16:19:47.000Z
tooling/intellij/src/main/java/org/stratos/lang/StratosPluginController.java
Arthur-Kamau/stratos
5afe8aa88ba765498779a6aecea908f2b0d927ef
[ "MIT" ]
null
null
null
tooling/intellij/src/main/java/org/stratos/lang/StratosPluginController.java
Arthur-Kamau/stratos
5afe8aa88ba765498779a6aecea908f2b0d927ef
[ "MIT" ]
null
null
null
28.45283
88
0.769231
8,280
package org.stratos.lang; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManager; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.SystemInfo; import org.jetbrains.annotations.NotNull; public class StratosPluginController implements ProjectComponent { public static final String PLUGIN_ID = "org.antlr.jetbrains.sample"; public static final Logger LOG = Logger.getInstance("SamplePluginController"); public Project project; public boolean projectIsClosed = false; public StratosPluginController(Project project) { this.project = project; } @Override public void projectClosed() { LOG.info("projectClosed " + project.getName()); //synchronized ( shutdownLock ) { // They should be called from EDT only so no lock projectIsClosed = true; project = null; } @Override public void projectOpened() { IdeaPluginDescriptor plugin = PluginManager.getPlugin(PluginId.getId(PLUGIN_ID)); String version = "unknown"; if ( plugin!=null ) { version = plugin.getVersion(); } LOG.info("Sample Plugin version "+version+", Java version "+ SystemInfo.JAVA_VERSION); } @Override public void initComponent() { } @Override public void disposeComponent() { } @NotNull @Override public String getComponentName() { return "sample.ProjectComponent"; } }
3e139567e2ed847a148ade9b60f490e7871cd869
1,625
java
Java
src/test/java/dev/snowdrop/example/KubernetesIT.java
devendra-wanjara/rest-http-example
1be203dd7f44ef214b30bfb067f777be57b11eb8
[ "Apache-2.0" ]
null
null
null
src/test/java/dev/snowdrop/example/KubernetesIT.java
devendra-wanjara/rest-http-example
1be203dd7f44ef214b30bfb067f777be57b11eb8
[ "Apache-2.0" ]
null
null
null
src/test/java/dev/snowdrop/example/KubernetesIT.java
devendra-wanjara/rest-http-example
1be203dd7f44ef214b30bfb067f777be57b11eb8
[ "Apache-2.0" ]
null
null
null
28.017241
88
0.724308
8,281
/* * Copyright 2016-2021 Red Hat, Inc, and individual contributors. * * 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 dev.snowdrop.example; import java.io.IOException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import io.dekorate.testing.annotation.Inject; import io.dekorate.testing.annotation.KubernetesIntegrationTest; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.LocalPortForward; @KubernetesIntegrationTest public class KubernetesIT extends AbstractExampleApplicationTest { @Inject KubernetesClient client; @Inject Pod pod; LocalPortForward appPort; @BeforeEach public void setup() { appPort = client.pods().withName(pod.getMetadata().getName()).portForward(8080); } @AfterEach public void tearDown() throws IOException { if (appPort != null) { appPort.close(); } } @Override public String baseURI() { return "http://localhost:" + appPort.getLocalPort() + "/"; } }
3e13968218759ac9291af78c8d74bc70ead2e2c7
1,755
java
Java
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/protocolPB/StorageContainerDatanodeProtocolPB.java
aswinshakil/ozone
df0489a4ad5ba1f8459a10036524926bef114c18
[ "Apache-2.0" ]
298
2020-10-28T08:58:02.000Z
2022-03-26T03:54:12.000Z
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/protocolPB/StorageContainerDatanodeProtocolPB.java
aswinshakil/ozone
df0489a4ad5ba1f8459a10036524926bef114c18
[ "Apache-2.0" ]
1,428
2020-10-28T02:25:43.000Z
2022-03-31T16:24:20.000Z
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/protocolPB/StorageContainerDatanodeProtocolPB.java
timmylicheng/hadoop-ozone
2e716a0cc374daa8827705494e45c6232f69661d
[ "Apache-2.0" ]
239
2020-11-01T10:49:54.000Z
2022-03-31T21:28:03.000Z
45
124
0.80057
8,282
/** * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.ozone.protocolPB; import org.apache.hadoop.hdds.DFSConfigKeysLegacy; import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageContainerDatanodeProtocolService; import org.apache.hadoop.hdds.scm.ScmConfig; import org.apache.hadoop.ipc.ProtocolInfo; import org.apache.hadoop.security.KerberosInfo; /** * Protocol used from a datanode to StorageContainerManager. This extends * the Protocol Buffers service interface to add Hadoop-specific annotations. */ @ProtocolInfo(protocolName = "org.apache.hadoop.ozone.protocol.StorageContainerDatanodeProtocol", protocolVersion = 1) @KerberosInfo( serverPrincipal = ScmConfig.ConfigStrings.HDDS_SCM_KERBEROS_PRINCIPAL_KEY, clientPrincipal = DFSConfigKeysLegacy.DFS_DATANODE_KERBEROS_PRINCIPAL_KEY) public interface StorageContainerDatanodeProtocolPB extends StorageContainerDatanodeProtocolService.BlockingInterface { }
3e1397c52acb6e08223ca244a5617632ae36b7c4
6,077
java
Java
selenium-capture-core/src/main/java/io/github/mike10004/seleniumcapture/AutoCertificateAndKeySource.java
mike10004/selenium-help
00bf43d4586f6a248b5985106626868a7a6c249d
[ "MIT" ]
1
2020-03-01T11:26:30.000Z
2020-03-01T11:26:30.000Z
selenium-capture-core/src/main/java/io/github/mike10004/seleniumcapture/AutoCertificateAndKeySource.java
mike10004/selenium-capture
00bf43d4586f6a248b5985106626868a7a6c249d
[ "MIT" ]
10
2019-10-23T15:22:14.000Z
2021-10-01T22:57:27.000Z
selenium-capture-core/src/main/java/io/github/mike10004/seleniumcapture/AutoCertificateAndKeySource.java
mike10004/selenium-capture
00bf43d4586f6a248b5985106626868a7a6c249d
[ "MIT" ]
null
null
null
35.747059
140
0.678295
8,283
package io.github.mike10004.seleniumcapture; import com.google.common.annotations.VisibleForTesting; import com.google.common.io.ByteSource; import com.google.common.io.Files; import com.browserup.bup.mitm.CertificateAndKey; import com.browserup.bup.mitm.CertificateAndKeySource; import com.browserup.bup.mitm.RootCertificateGenerator; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.Arrays; import java.util.Base64; import java.util.Objects; import java.util.Random; import static com.google.common.base.Preconditions.checkState; /** * Auto-generating certificate and key source. */ public class AutoCertificateAndKeySource implements CertificateAndKeySource, java.io.Closeable { private static final Logger log = LoggerFactory.getLogger(AutoCertificateAndKeySource.class); private volatile MemoryKeyStoreCertificateSource onDemandSource; private volatile boolean closed; private transient final Object generationLock = new Object(); private final Path scratchDir; private final Random random; @SuppressWarnings("unused") public AutoCertificateAndKeySource(Path scratchDir) { this(scratchDir, new Random()); } @VisibleForTesting public AutoCertificateAndKeySource(Path scratchDir, Random random) { this.scratchDir = scratchDir; this.random = random; } @SuppressWarnings("RedundantThrows") @Override public void close() throws IOException { synchronized (generationLock) { if (onDemandSource != null) { Arrays.fill(onDemandSource.keystoreBytes, (byte) 0); closed = true; onDemandSource = null; } } } protected void keystorePasswordGenerated(String password) { // no op } private void generateIfNecessary() { synchronized (generationLock) { checkState(!closed, "this source is closed"); if (onDemandSource == null) { try { byte[] bytes = new byte[32]; random.nextBytes(bytes); String password = Base64.getEncoder().encodeToString(bytes); keystorePasswordGenerated(password); onDemandSource = generate(password); } catch (IOException e) { throw new CertificateGenerationException(e); } } } } @Override public CertificateAndKey load() { generateIfNecessary(); return onDemandSource.load(); } static class CertificateGenerationException extends RuntimeException { public CertificateGenerationException(String message) { super(message); } @SuppressWarnings("unused") public CertificateGenerationException(String message, Throwable cause) { super(message, cause); } public CertificateGenerationException(Throwable cause) { super(cause); } } private static final String KEYSTORE_TYPE = "PKCS12"; private static final String KEYSTORE_PRIVATE_KEY_ALIAS = "key"; protected static class MemoryKeyStoreCertificateSource extends KeyStoreStreamCertificateSource { public final byte[] keystoreBytes; public final String keystorePassword; public MemoryKeyStoreCertificateSource(String keyStoreType, byte[] keystoreBytes, String privateKeyAlias, String keyStorePassword) { super(keyStoreType, ByteSource.wrap(keystoreBytes), privateKeyAlias, keyStorePassword); this.keystoreBytes = Objects.requireNonNull(keystoreBytes); this.keystorePassword = Objects.requireNonNull(keyStorePassword); } } public static class SerializableForm { public String keystoreBase64; public String password; public SerializableForm(String keystoreBase64, String password) { this.keystoreBase64 = keystoreBase64; this.password = password; } } @SuppressWarnings("RedundantThrows") public SerializableForm createSerializableForm() throws IOException { generateIfNecessary(); return new SerializableForm(Base64.getEncoder().encodeToString(onDemandSource.keystoreBytes), onDemandSource.keystorePassword); } protected void keystoreBytesGenerated(ByteSource byteSource) { // no op; subclasses may override } protected MemoryKeyStoreCertificateSource generate(String keystorePassword) throws IOException { File keystoreFile = File.createTempFile("dynamically-generated-certificate", ".keystore", scratchDir.toFile()); try { // create a dynamic CA root certificate generator using default settings (2048-bit RSA keys) RootCertificateGenerator rootCertificateGenerator = RootCertificateGenerator.builder().build(); rootCertificateGenerator.saveRootCertificateAndKey(KEYSTORE_TYPE, keystoreFile, KEYSTORE_PRIVATE_KEY_ALIAS, keystorePassword); log.debug("saved keystore to {} ({} bytes)%n", keystoreFile, keystoreFile.length()); byte[] keystoreBytes = Files.toByteArray(keystoreFile); keystoreBytesGenerated(ByteSource.wrap(keystoreBytes)); return new MemoryKeyStoreCertificateSource(KEYSTORE_TYPE, keystoreBytes, KEYSTORE_PRIVATE_KEY_ALIAS, keystorePassword); } finally { FileUtils.forceDelete(keystoreFile); } } public KeystoreInput acquireKeystoreInput() { return new KeystoreInput() { @Override public ByteSource getBytes() { generateIfNecessary(); return ByteSource.wrap(onDemandSource.keystoreBytes); } @Override public String getPassword() { generateIfNecessary(); return onDemandSource.keystorePassword; } }; } }
3e1397fc6a76eb6cfa2b2fe04db0ccb25f24650f
483
java
Java
seckilling1/src/main/java/me/zonglun/seckilling/dao/UserDao.java
Allenskoo856/seckilling
b833ee2bffb712c105bf82a722d617b24c6f3395
[ "MIT" ]
null
null
null
seckilling1/src/main/java/me/zonglun/seckilling/dao/UserDao.java
Allenskoo856/seckilling
b833ee2bffb712c105bf82a722d617b24c6f3395
[ "MIT" ]
1
2018-05-06T08:14:47.000Z
2018-05-06T08:14:47.000Z
seckilling1/src/main/java/me/zonglun/seckilling/dao/UserDao.java
Allenskoo856/seckilling
b833ee2bffb712c105bf82a722d617b24c6f3395
[ "MIT" ]
null
null
null
25.421053
60
0.749482
8,284
package me.zonglun.seckilling.dao; import me.zonglun.seckilling.domain.User; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; @Mapper public interface UserDao { @Select("select * from user where id = #{id}") public User getById(@Param("id")int id ); @Insert("insert into user(id, name)values(#{id}, #{name})") public int insert(User user); }
3e13983081373cf33b29c8df1c3cd64bdfb756c4
1,069
java
Java
src/test/java/br/edu/utfpr/jhony/testes/service/PessoaServiceTest.java
Jhonysganzerla/TestMockWithSpringSample
5e829c9ad6e124dc17357e9c9cb14a5f9ab42b42
[ "MIT" ]
null
null
null
src/test/java/br/edu/utfpr/jhony/testes/service/PessoaServiceTest.java
Jhonysganzerla/TestMockWithSpringSample
5e829c9ad6e124dc17357e9c9cb14a5f9ab42b42
[ "MIT" ]
null
null
null
src/test/java/br/edu/utfpr/jhony/testes/service/PessoaServiceTest.java
Jhonysganzerla/TestMockWithSpringSample
5e829c9ad6e124dc17357e9c9cb14a5f9ab42b42
[ "MIT" ]
null
null
null
27.410256
60
0.785781
8,285
package br.edu.utfpr.jhony.testes.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; import br.edu.utfpr.jhony.testes.data.PessoaRepository; import br.edu.utfpr.jhony.testes.model.Pessoa; import br.edu.utfpr.jhony.testes.services.PessoaService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class PessoaServiceTest { @InjectMocks private PessoaService pessoaService; @Mock private PessoaRepository repository; @Test public void pegarTodasPessoas() { when(repository.findAll()).thenReturn(Arrays.asList( new Pessoa(2,"Pessoa2",10,10), new Pessoa(3,"Pessoa3",20,20))); List<Pessoa> pessoas = pessoaService.pegarTodasPessoas(); assertEquals(1000, pessoas.get(0).getPesovezescem()); assertEquals(2000, pessoas.get(1).getPesovezescem()); } }
3e13986fccd9291db43346be90b86568b229bd5c
6,613
java
Java
src/com/sun/jmx/trace/TraceImplementation.java
terminux/jdk1.7.0_80
c2869af7cc5791f7e58894f4c9f5bceea3ed040e
[ "MIT" ]
null
null
null
src/com/sun/jmx/trace/TraceImplementation.java
terminux/jdk1.7.0_80
c2869af7cc5791f7e58894f4c9f5bceea3ed040e
[ "MIT" ]
null
null
null
src/com/sun/jmx/trace/TraceImplementation.java
terminux/jdk1.7.0_80
c2869af7cc5791f7e58894f4c9f5bceea3ed040e
[ "MIT" ]
2
2020-07-12T00:31:07.000Z
2021-05-26T07:38:37.000Z
25.631783
81
0.613791
8,286
/* * * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.sun.jmx.trace; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; /** * Example implementation of the {@link TraceDestination} interface. * <br> * This implementation sends log records to a file (specified by the value of the * <code>com.sun.jmx.trace.file</code> system property) or to the system * console if no file is specified. * <br> * The log level is specified by the value of system property * <code>com.sun.jmx.trace.level</code>, which can be : <code>DEBUG</code>, * <code>TRACE</code>, <code>ERROR</code>. If no trace level is specified, the * default is <code>ERROR</code>. * <br> * Note that this implementation does not provide any filtering based on the log * types. More precisely, the implementation of method {@link #isSelected} only * checks the provided log level. * * @since 1.5 */ @Deprecated public class TraceImplementation implements TraceDestination { // output stream // private PrintWriter out; // log level // private int level; static TraceImplementation newDestination(int level) { try { final TraceImplementation impl = new TraceImplementation(); impl.level = level; return impl; } catch (IOException x) { return null; } } /** * Registers a new instance of class {@link TraceImplementation} as the * trace destination in class {@link Trace}. * * @exception IOException * may be thrown when creating the new log file based on the * value of system property <code>com.sun.jmx.trace.file</code> * @see Trace#setDestination */ public static void init() throws IOException { Trace.setDestination(new TraceImplementation()); } /** * Registers a new instance of class {@link TraceImplementation} as the * trace destination in class {@link Trace}. * * @param level Initial trace level (see {@link TraceTags}) * @exception IOException * may be thrown when creating the new log file based on the * value of system property <code>com.sun.jmx.trace.file</code> * @see Trace#setDestination */ public static void init(int level) throws IOException { final TraceImplementation impl = new TraceImplementation(); impl.level = level; Trace.setDestination(impl); } /** * Constructor. * @exception IOException * may be thrown when creating the new log file based on the * value of system property <code>com.sun.jmx.trace.file</code> */ public TraceImplementation() throws IOException { String filename; if ((filename = System.getProperty("com.sun.jmx.trace.file")) != null) { // Output sent to the specified log file // this.out = new PrintWriter(new FileOutputStream(filename), true); } else { // Output sent to the system console // this.out = new PrintWriter(System.err, true); } String level; if ((level = System.getProperty("com.sun.jmx.trace.level")) != null) { // Read log level from value of system property // if (level.equals("DEBUG")) { this.level = TraceTags.LEVEL_DEBUG; } else if (level.equals("TRACE")) { this.level = TraceTags.LEVEL_TRACE; } else { this.level = TraceTags.LEVEL_ERROR; } } else { // Log level defaults to ERROR // this.level = TraceTags.LEVEL_ERROR; } } /** * Only tests whether the provided log level will generate some output if * used as an argument to {@link #send(int, int, String, String, Throwable)} * or {@link #send(int, int, String, String, String)} * * @see TraceDestination#isSelected */ public boolean isSelected(int level, int type) { return (level <= this.level); } /** * @see TraceDestination#send(int, int, String, String, String) */ public boolean send(int level, int type, String className, String methodName, String info) { if (isSelected(level, type)) { out.println(((className!=null)?"Class: " + className:"")+ ((methodName!=null)?"\nMethod: " + methodName:"") + "\n\tlevel: " + getLevel(level) + "\n\ttype: " + getType(type) + "\n\tmessage: " + info); //out.flush(); return true; } return false; } /** * @see TraceDestination#send(int, int, String, String, Throwable) */ public boolean send(int level, int type, String className, String methodName, Throwable exception) { final boolean result = send(level, type, className, methodName, exception.toString()); if (result) exception.printStackTrace(out); return result; } /** * Not implemented. * * @see TraceDestination#reset **/ public void reset() throws IOException { } /** * Return the string representation of a trace type, as defined in * {@link TraceTags} */ private static String getType(int type) { switch (type) { case TraceTags.INFO_MBEANSERVER: return "INFO_MBEANSERVER"; case TraceTags.INFO_ADAPTOR_SNMP: return "INFO_ADAPTOR_SNMP"; case TraceTags.INFO_SNMP: return "INFO_SNMP"; case TraceTags.INFO_MLET: return "INFO_MLET"; case TraceTags.INFO_MONITOR: return "INFO_MONITOR"; case TraceTags.INFO_TIMER: return "INFO_TIMER"; case TraceTags.INFO_MISC: return "INFO_MISC"; case TraceTags.INFO_NOTIFICATION: return "INFO_NOTIFICATION"; case TraceTags.INFO_RELATION: return "INFO_RELATION"; case TraceTags.INFO_MODELMBEAN: return "INFO_MODELMBEAN"; default: return "UNKNOWN_TRACE_TYPE"; } } /** * Return the string representation of a trace level, as defined in * {@link TraceTags} */ private static String getLevel(int level) { switch (level) { case TraceTags.LEVEL_ERROR: return "LEVEL_ERROR"; case TraceTags.LEVEL_TRACE: return "LEVEL_TRACE"; case TraceTags.LEVEL_DEBUG: return "LEVEL_DEBUG"; default : return "UNKNOWN_TRACE_LEVEL"; } } }
3e13988c518dc7a60154b32635ffa59653722761
6,715
java
Java
src/test/java/io/esoma/khr/dao/ReviewDaoImplTest.java
Kairn/koality-harmonia-rest
291ee7c2a69093b0204a6e4d977316d1ba5bb07d
[ "Apache-2.0" ]
null
null
null
src/test/java/io/esoma/khr/dao/ReviewDaoImplTest.java
Kairn/koality-harmonia-rest
291ee7c2a69093b0204a6e4d977316d1ba5bb07d
[ "Apache-2.0" ]
5
2021-12-14T20:37:21.000Z
2022-01-21T23:23:41.000Z
src/test/java/io/esoma/khr/dao/ReviewDaoImplTest.java
Kairn/koality-harmonia-rest
291ee7c2a69093b0204a6e4d977316d1ba5bb07d
[ "Apache-2.0" ]
null
null
null
23.561404
106
0.758451
8,287
package io.esoma.khr.dao; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.List; import org.hibernate.SessionFactory; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.SqlConfig; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import io.esoma.khr.model.Album; import io.esoma.khr.model.Koalibee; import io.esoma.khr.model.Review; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/spring-context.xml") // Run tests in a fixed order to make sure the SQL script is executed before tests. @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ReviewDaoImplTest { private static boolean isSet; private SessionFactory sessionFactory; private ReviewDao reviewDao; @Autowired @Qualifier(value = "h2DBSessionFactory") public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Autowired @Qualifier(value = "reviewDaoImplBasic") public void setReviewDao(ReviewDao reviewDao) { this.reviewDao = reviewDao; } @BeforeClass public static void setUpBeforeClass() throws Exception { // No content yet. } @AfterClass public static void tearDownAfterClass() throws Exception { // No content yet. } // Set to Use H2 database session factory before executing the SQL script. @Before public void setUp() throws Exception { // Will only run once. if (!isSet) { ((ReviewDaoImpl) this.reviewDao).setSessionFactory(this.sessionFactory); isSet = true; } } // Run Test SQL script. @Test @Sql(scripts = "/kh-h2.sql", config = @SqlConfig(transactionManager = "h2DBHibernateTransactionManager")) public void executeSql() { // Intentionally left blank. assertTrue(true); } @Test public void testGetSessionFactory() throws Exception { assertNotNull(((ReviewDaoImpl) this.reviewDao).getSessionFactory()); } @Test public void testSetSessionFactory() throws Exception { // Intentionally left blank. // This test automatically passes if autowiring succeeds. assertTrue(true); } @Test public void testGetReviewById1() throws Exception { Review review = this.reviewDao.getReviewById(1); assertNotNull(review); assertEquals("Just amazing!", review.getReviewComment()); } @Test public void testGetReviewById2() throws Exception { Review review = this.reviewDao.getReviewById(4); assertNotNull(review); assertEquals(10, review.getRating()); assertEquals("New Album", review.getAlbumName()); assertEquals("Eddy Soma", review.getKoalibeeName()); } @Test public void testGetReviewByIdN() throws Exception { Review review = this.reviewDao.getReviewById(100); assertNull(review); } @Test public void testGetReviewByAlbumAndKoalibee1() throws Exception { Review review = this.reviewDao.getReviewByAlbumAndKoalibee(6, 1); assertNotNull(review); assertEquals(1, review.getRating()); } @Test public void testGetReviewByAlbumAndKoalibee2() throws Exception { Review review = this.reviewDao.getReviewByAlbumAndKoalibee(1, 3); assertEquals(10, review.getRating()); assertEquals("WTFOMG Psyche", review.getReviewComment()); assertNull(review.getAlbumName()); assertNull(review.getKoalibeeName()); } @Test public void testGetReviewByAlbumAndKoalibeeN() throws Exception { Review review = this.reviewDao.getReviewByAlbumAndKoalibee(6, 3); assertNull(review); } @Test public void testAddReview1() throws Exception { final Album album = new Album(4); final Koalibee koalibee = new Koalibee(3); final Review review = new Review(); review.setRating(5); review.setReviewComment("Test comment"); review.setAlbum(album); review.setKoalibee(koalibee); int id = this.reviewDao.addReview(review); assertEquals(11, id); assertEquals("Test comment", this.reviewDao.getReviewById(id).getReviewComment()); } @Test public void testAddReview2() throws Exception { final Album album = new Album(2); final Koalibee koalibee = new Koalibee(2); final Review review = new Review(); review.setRating(9); review.setReviewComment("two to 222"); review.setAlbum(album); review.setKoalibee(koalibee); int id = this.reviewDao.addReview(review); assertNotEquals(0, id); assertEquals(9, this.reviewDao.getReviewById(id).getRating()); assertEquals("Julie Seals", this.reviewDao.getReviewById(id).getKoalibeeName()); } @Test public void testDeleteReview() throws Exception { assertNotNull(this.reviewDao.getReviewById(12)); assertTrue(this.reviewDao.deleteReview(12)); assertNull(this.reviewDao.getReviewById(12)); } @Test public void testGetAllReviews() throws Exception { List<Review> reviewList = this.reviewDao.getAllReviews(); assertFalse(reviewList.isEmpty()); assertTrue(reviewList.contains(new Review(10))); assertTrue(reviewList.contains(new Review(9))); assertTrue(reviewList.contains(new Review(8))); assertTrue(reviewList.contains(new Review(7))); } @Test public void testGetAllReviewsByAlbum() throws Exception { List<Review> reviewList = this.reviewDao.getAllReviewsByAlbum(1); assertEquals(2, reviewList.size()); assertEquals("John Smith", reviewList.get(0).getKoalibeeName()); } @Test public void testGetAllReviewsByAlbumN() throws Exception { List<Review> reviewList = this.reviewDao.getAllReviewsByAlbum(3); assertEquals(0, reviewList.size()); } @Test public void testGetAllReviewsByKoalibee() throws Exception { List<Review> reviewList = this.reviewDao.getAllReviewsByKoalibee(1); assertEquals(4, reviewList.size()); assertTrue(reviewList.contains(new Review(1))); reviewList.removeIf(r -> !r.getAlbum().equals(new Album(1))); assertEquals("Just amazing!", reviewList.get(0).getReviewComment()); assertEquals("Etudes Liszt", reviewList.get(0).getAlbumName()); } @Test public void testGetAllReviewsByKoalibeeN() throws Exception { List<Review> reviewList = this.reviewDao.getAllReviewsByKoalibee(7); assertEquals(0, reviewList.size()); } }
3e1398932ae816cf275723278939ee72d1944d71
2,460
java
Java
U1M6Summative/src/test/java/com/company/U1M6Summative/dao/ItemDaoJdbcImplTest.java
ricksinclair/RestWebServiceGroupProject
8b33552c8e1dfc1841bbe639ab583309fdf00efd
[ "MIT" ]
null
null
null
U1M6Summative/src/test/java/com/company/U1M6Summative/dao/ItemDaoJdbcImplTest.java
ricksinclair/RestWebServiceGroupProject
8b33552c8e1dfc1841bbe639ab583309fdf00efd
[ "MIT" ]
null
null
null
U1M6Summative/src/test/java/com/company/U1M6Summative/dao/ItemDaoJdbcImplTest.java
ricksinclair/RestWebServiceGroupProject
8b33552c8e1dfc1841bbe639ab583309fdf00efd
[ "MIT" ]
null
null
null
28.275862
83
0.661789
8,288
package com.company.U1M6Summative.dao; import com.company.U1M6Summative.model.Item; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.math.BigDecimal; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class ItemDaoJdbcImplTest { @Autowired ItemDao itemDao; @Before public void setUp() throws Exception { List<Item> itemList = itemDao.getAllItems(); itemList.stream().forEach(item -> itemDao.deleteItem(item.getItemId())); } @After public void tearDown() throws Exception { } @Test public void addGetDeleteItem() { Item item = new Item(); item.setName("Free Willy"); item.setDescription("A joyous tale of a boy and a killer whale."); item.setDailyRate(new BigDecimal( "3.34")); item = itemDao.addItem(item); Item item2 = itemDao.getItem(item.getItemId()); assertEquals(item, item2); itemDao.deleteItem(item.getItemId()); item2 = itemDao.getItem(item.getItemId()); assertNull(item2); } @Test public void updateItem() { Item item = new Item(); item.setName("Free Willy"); item.setDescription("A joyous tale of a boy and a killer whale."); item.setDailyRate(new BigDecimal( "3.34")); item = itemDao.addItem(item); item.setDailyRate(new BigDecimal("4.00")); itemDao.updateItem(item); Item item2 = itemDao.getItem(item.getItemId()); assertEquals(item, item2); } @Test public void getAllItems() { Item item = new Item(); item.setName("Free Willy"); item.setDescription("A joyous tale of a boy and a killer whale."); item.setDailyRate(new BigDecimal( "3.34")); itemDao.addItem(item); item.setName("Lion King"); item.setDescription("A joyous tale of a lion who will grow to be a king."); item.setDailyRate(new BigDecimal( "4.50")); itemDao.addItem(item); List<Item> itemList = itemDao.getAllItems(); assertEquals(itemList.size(), 2); } }
3e139965f2ee46c5912c4d678e634427693a41c6
1,896
java
Java
lenskit-core/src/main/java/org/lenskit/data/store/EntityIndex.java
shantanusharma/lenskit
054f4669e2937512ca1e276183ca1a2e8df64d1f
[ "MIT" ]
809
2015-01-02T15:45:31.000Z
2022-03-16T16:38:12.000Z
lenskit-core/src/main/java/org/lenskit/data/store/EntityIndex.java
shantanusharma/lenskit
054f4669e2937512ca1e276183ca1a2e8df64d1f
[ "MIT" ]
321
2015-01-09T00:02:12.000Z
2021-08-23T16:27:45.000Z
lenskit-core/src/main/java/org/lenskit/data/store/EntityIndex.java
shantanusharma/lenskit
054f4669e2937512ca1e276183ca1a2e8df64d1f
[ "MIT" ]
281
2015-01-12T20:26:26.000Z
2022-01-28T16:45:35.000Z
35.773585
73
0.73365
8,289
/* * LensKit, an open-source toolkit for recommender systems. * Copyright 2014-2017 LensKit contributors (see CONTRIBUTORS.md) * Copyright 2010-2014 Regents of the University of Minnesota * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.lenskit.data.store; import org.lenskit.data.entities.Entity; import javax.annotation.Nonnull; import java.util.List; import java.util.Set; /** * An index to look up entities by attribute value. * * @see EntityIndexBuilder */ interface EntityIndex { /** * Get the entities with the associated attribute value. * @param value The attribute value. * @return The list of entities. */ @Nonnull List<Entity> getEntities(@Nonnull Object value); /** * Get the set of entity values in the index. * @return The set of entity values. */ Set<?> getValues(); }
3e1399b6fcc2df7edf83f24ee269cb4fe4fb3312
1,128
java
Java
xs2a-server-api/src/main/java/de/adorsys/psd2/model/DayOfExecution.java
erdincozden/xs2a
f9654f47a13eda78a20d1c8d17366c1f79333a76
[ "Apache-2.0" ]
null
null
null
xs2a-server-api/src/main/java/de/adorsys/psd2/model/DayOfExecution.java
erdincozden/xs2a
f9654f47a13eda78a20d1c8d17366c1f79333a76
[ "Apache-2.0" ]
null
null
null
xs2a-server-api/src/main/java/de/adorsys/psd2/model/DayOfExecution.java
erdincozden/xs2a
f9654f47a13eda78a20d1c8d17366c1f79333a76
[ "Apache-2.0" ]
null
null
null
29.684211
114
0.572695
8,290
package de.adorsys.psd2.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * Day of execution as string in the form DD. Thes string consists always of two characters. 31 is ultimo of the * month. */ public enum DayOfExecution { _01("01"), _02("02"), _03("03"), _04("04"), _05("05"), _06("06"), _07("07"), _08("08"), _09("09"), _10("10"), _11("11"), _12("12"), _13("13"), _14("14"), _15("15"), _16("16"), _17("17"), _18("18"), _19("19"), _20("20"), _21("21"), _22("22"), _23("23"), _24("24"), _25("25"), _26("26"), _27("27"), _28("28"), _29("29"), _30("30"), _31("31"); private String value; DayOfExecution(String value) { this.value = value; } @JsonCreator public static DayOfExecution fromValue(String text) { for (DayOfExecution b : DayOfExecution.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } @Override @JsonValue public String toString() { return String.valueOf(value); } }
3e139a369d1afa464e9f9d11aabec2445d89d65c
6,207
java
Java
src/test/java/serial/connected/TestWriteToXFM.java
arnislektauers/XFM2GUI
225423772996b45c088c5bde26d84d60f1fd2fa7
[ "MIT" ]
3
2020-12-29T08:00:19.000Z
2021-08-28T19:18:04.000Z
src/test/java/serial/connected/TestWriteToXFM.java
arnislektauers/XFM2GUI
225423772996b45c088c5bde26d84d60f1fd2fa7
[ "MIT" ]
null
null
null
src/test/java/serial/connected/TestWriteToXFM.java
arnislektauers/XFM2GUI
225423772996b45c088c5bde26d84d60f1fd2fa7
[ "MIT" ]
2
2021-04-04T10:53:44.000Z
2022-01-31T17:25:40.000Z
35.067797
163
0.665861
8,291
package serial.connected; import jssc.SerialPort; import jssc.SerialPortException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import com.github.steadiestllama.xfm2gui.serial.SerialHandlerBridge; import java.io.IOException; import java.util.Random; import static org.junit.jupiter.api.Assertions.*; public class TestWriteToXFM { static String os = System.getProperty("os.name").toLowerCase(); static SerialPort jsscSerialPort; static com.fazecast.jSerialComm.SerialPort jSerialCommPort; static SerialHandlerBridge serialHandlerBridge = SerialHandlerBridge.getSINGLE_INSTANCE(); Random random = new Random(); @BeforeAll public static void initialise() { // Gets the correct serial port depending on platform // This is tested this way to avoid unnecessary failing tests on different platforms if (os.contains("mac") || os.contains("darwin")) { // Direct reference to the XFM2 device I am using - would need changing on another machine jsscSerialPort = new SerialPort("/dev/tty.usbserial-210328AD3A891"); serialHandlerBridge.setSerialPort(jsscSerialPort); } else if (os.contains("win")){ com.fazecast.jSerialComm.SerialPort[] jSerialComms = com.fazecast.jSerialComm.SerialPort.getCommPorts(); for(com.fazecast.jSerialComm.SerialPort port:jSerialComms){ if(port.getSystemPortName().equals("COM6")){ jSerialCommPort = port; } } serialHandlerBridge.setSerialPort(jSerialCommPort); } else{ // Again, direct reference, although more likely to be correct if only one device is connected... jsscSerialPort = new SerialPort("/dev/ttyUSB1"); serialHandlerBridge.setSerialPort(jsscSerialPort); } } @Test public void SettingParameterValuesIndividuallyToRandomByteValuesThenReadingItWillGetSetValues() throws IOException, SerialPortException, InterruptedException { int[] generatedData = new int[512]; int low = 0; int high = 255; serialHandlerBridge.readProgram(1); byte[] initData = serialHandlerBridge.getAllValues(); for (int i = 0; i < 512; i++) { int gen = random.nextInt(high - low) + low; generatedData[i] = gen; serialHandlerBridge.setIndividualValue(i, gen); } byte[] postWriteData = serialHandlerBridge.getAllValues(); for (int i = 0; i < 512; i++) { assertEquals(generatedData[i], (int) postWriteData[i] & 0xff, "Values should be equal due to being set individually"); } serialHandlerBridge.setAllValues(initData); } @Test public void SettingParameterValuesAllInOneGoToRandomByteValuesThenReadingItWillGetSetValues() throws IOException, SerialPortException { serialHandlerBridge.readProgram(1); byte[] initData = serialHandlerBridge.getAllValues(); byte[] generatedData = new byte[512]; random.nextBytes(generatedData); serialHandlerBridge.setAllValues(generatedData); byte[] postWriteData = serialHandlerBridge.getAllValues(); for (int i = 0; i < 512; i++) { assertEquals(generatedData[i], postWriteData[i], "Values should be equal due to being set in one go"); } } @Test public void SendingLessThan512BytesToBoardChangesNothing() throws IOException, SerialPortException { serialHandlerBridge.readProgram(1); byte[] initData = serialHandlerBridge.getAllValues(); byte[] generatedData = new byte[511]; random.nextBytes(generatedData); serialHandlerBridge.setAllValues(generatedData); byte[] postWriteData = serialHandlerBridge.getAllValues(); boolean differenceFound = false; for (int i = 0; i < 511; i++) { if (generatedData[i] != postWriteData[i]) { differenceFound = true; break; } } assertTrue(differenceFound,"There should be at least one difference between the test arrays"); } @Test public void SendingMoreThan512BytesToBoardChangesNothing() throws IOException, SerialPortException { serialHandlerBridge.readProgram(1); byte[] initData = serialHandlerBridge.getAllValues(); byte[] generatedData = new byte[513]; random.nextBytes(generatedData); serialHandlerBridge.setAllValues(generatedData); byte[] postWriteData = serialHandlerBridge.getAllValues(); boolean differenceFound = false; for (int i = 0; i < 512; i++) { if (generatedData[i] != postWriteData[i]) { differenceFound = true; break; } } assertTrue(differenceFound,"There should be at least one difference between the test arrays"); } @Test public void SendingLettersAsBytesWillSetTheValuesToTheByteValueOfTheLetter() throws IOException, SerialPortException { serialHandlerBridge.readProgram(12); byte[] initData = serialHandlerBridge.getAllValues(); byte[] lettersAsBytes = new byte[512]; for(int i = 0;i<512;i++){ lettersAsBytes[i] = 'f'; } serialHandlerBridge.setAllValues(lettersAsBytes); byte[] postWriteData = serialHandlerBridge.getAllValues(); assertArrayEquals(postWriteData,lettersAsBytes, "Arrays should be equal as the byte value of f is sent"); } @Test public void SendingSpecialCharsAsBytesWillSetTheValuesToTheByteValueOfTheSpecialChar() throws IOException, SerialPortException { serialHandlerBridge.readProgram(12); byte[] initData = serialHandlerBridge.getAllValues(); byte[] lettersAsBytes = new byte[512]; for(int i = 0;i<512;i++){ lettersAsBytes[i] = '\n'; } serialHandlerBridge.setAllValues(lettersAsBytes); byte[] postWriteData = serialHandlerBridge.getAllValues(); assertArrayEquals(postWriteData,lettersAsBytes, "Arrays should be equal as the byte value of f is sent"); } }
3e139ba29ea4023e1f60741a61063b89b401dcdf
14,146
java
Java
gov.nasa.ensemble.core.plan.editor/src/gov/nasa/ensemble/core/plan/editor/lifecycle/PlanOverview.java
mikiec84/OpenSPIFe
71f298821c6003680d46e637462c638a4cee2579
[ "Apache-2.0" ]
87
2015-03-10T04:16:19.000Z
2022-01-19T22:59:12.000Z
gov.nasa.ensemble.core.plan.editor/src/gov/nasa/ensemble/core/plan/editor/lifecycle/PlanOverview.java
mikiec84/OpenSPIFe
71f298821c6003680d46e637462c638a4cee2579
[ "Apache-2.0" ]
1
2020-04-09T08:04:24.000Z
2020-04-09T16:15:17.000Z
gov.nasa.ensemble.core.plan.editor/src/gov/nasa/ensemble/core/plan/editor/lifecycle/PlanOverview.java
mikiec84/OpenSPIFe
71f298821c6003680d46e637462c638a4cee2579
[ "Apache-2.0" ]
59
2015-01-02T08:53:55.000Z
2021-11-18T09:50:17.000Z
31.575893
114
0.724516
8,292
/******************************************************************************* * Copyright 2014 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ /** * */ package gov.nasa.ensemble.core.plan.editor.lifecycle; import gov.nasa.ensemble.common.CommonUtils; import gov.nasa.ensemble.common.logging.LogUtil; import gov.nasa.ensemble.common.type.StringifierRegistry; import gov.nasa.ensemble.common.ui.ICompositeListLabel; import gov.nasa.ensemble.common.ui.WidgetUtils; import gov.nasa.ensemble.common.ui.color.ColorConstants; import gov.nasa.ensemble.common.ui.mission.MissionUIConstants; import gov.nasa.ensemble.core.model.plan.CommonMember; import gov.nasa.ensemble.core.model.plan.EActivity; import gov.nasa.ensemble.core.model.plan.EActivityGroup; import gov.nasa.ensemble.core.model.plan.EPlan; import gov.nasa.ensemble.core.model.plan.EPlanElement; import gov.nasa.ensemble.core.model.plan.activityDictionary.util.ADParameterUtils; import gov.nasa.ensemble.core.model.plan.translator.WrapperUtils; import gov.nasa.ensemble.core.model.plan.util.PlanVisitor; import gov.nasa.ensemble.core.plan.editor.EditorPlugin; import gov.nasa.ensemble.core.plan.editor.PermissionConstants; import gov.nasa.ensemble.dictionary.EActivityDef; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Date; import java.util.LinkedHashSet; import java.util.Set; import org.eclipse.emf.ecore.EObject; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; public class PlanOverview implements ICompositeListLabel, PropertyChangeListener { private final EPlan plan; protected Composite composite; protected Label notesLabel; protected Composite iconRow; protected StyledText objectSummaryText; protected StyleRange objectSummaryBoldStyleRange; protected StyleRange objectSummaryItalicsStyleRange; protected StyleRange objectSummaryNormalStyleRange; /** * Create the GUI elements of the plan overview with the given composite as * its parent. * * @param parent * @param plan */ public PlanOverview(Composite parent, EPlan plan) { this.composite = new Composite(parent, SWT.BORDER | SWT.NO_FOCUS); this.plan = plan; } public void layout() { composite.setBackground(ColorConstants.white); composite.setLayout(new GridLayout()); GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.grabExcessHorizontalSpace = true; composite.setLayoutData(gridData); layoutArea(); for (Control child : composite.getChildren()) { child.setBackground(ColorConstants.white); } } @Override public Composite getComposite() { return composite; } public String getName() { return plan.getName(); } protected void layoutArea() { // build the plan summary section buildSummaryArea(); // build the notes section buildNotesArea(); // build the activity icons and resource summary section buildCategoriesArea(); } protected void setCategoryIcons() { Image image = MissionUIConstants.getInstance().getContainerIcon(""); ImageData imageData = image.getImageData(); iconRow.setLayoutData(new GridData(-1, imageData.height + 2)); final Set<String> categories = getCategorySet(); WidgetUtils.runInDisplayThread(composite, new Runnable() { @Override public void run() { for (String category : categories) { if (category != null) { Image image = MissionUIConstants.getInstance().getIcon(category); addCategoryIcon(image); } } composite.layout(true, true); } }); } protected void buildCategoriesArea() { iconRow = new Composite(composite, SWT.NO_FOCUS); RowLayout rowLayout = new RowLayout(); rowLayout.marginBottom = 0; rowLayout.marginTop = 0; rowLayout.marginLeft = 0; rowLayout.marginRight = 0; rowLayout.wrap = true; rowLayout.pack = true; rowLayout.justify = false; iconRow.setLayout(rowLayout); iconRow.setBackground(composite.getBackground()); setCategoryIcons(); } protected void buildNotesArea() { notesLabel = new Label(composite, SWT.NO_FOCUS); final String notes = getNotes(); WidgetUtils.runInDisplayThread(composite, new Runnable() { @Override public void run() { setNotesText(notes); } }); } protected void buildSummaryArea() { objectSummaryText = new StyledText(composite, SWT.NO_FOCUS); objectSummaryText.setEditable(false); objectSummaryText.setEnabled(false); objectSummaryBoldStyleRange = new StyleRange(); objectSummaryNormalStyleRange = new StyleRange(); objectSummaryItalicsStyleRange = new StyleRange(); setSummaryText(); } protected final void addCategoryIcon(final Image image) { if (image != null) { ImageData imageData = image.getImageData(); Canvas canvas = new Canvas(iconRow, SWT.NO_REDRAW_RESIZE | SWT.NO_FOCUS); canvas.setLayoutData(new RowData(imageData.width, imageData.height)); canvas.setBackground(iconRow.getBackground()); canvas.addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { e.gc.drawImage(image,0,0); } }); } } public void updateObjectName(String name) { updatePlanName(name); } public void updatePlanName(final String planName) { final int activityCount = getActivityCount(); final int activityGroupCount = getActivityGroupCount(); final String custodian = getCustodian(); final String worldPermissions = getWorldPermissions(); final String group = getGroup(); final String lastModified = getLastModified(); WidgetUtils.runInDisplayThread(composite, new Runnable() { @Override public void run() { setPlanSummaryText( activityCount, activityGroupCount, planName, custodian, worldPermissions, group, lastModified); } }); } public void updateWorldPermissions(final String worldPermissions) { final String planName = getName(); final int activityCount = getActivityCount(); final int activityGroupCount = getActivityGroupCount(); final String custodian = getCustodian(); final String group = getGroup(); final String lastModified = getLastModified(); WidgetUtils.runInDisplayThread(composite, new Runnable() { @Override public void run() { setPlanSummaryText( activityCount, activityGroupCount, planName, custodian, worldPermissions, group, lastModified); } }); } protected void setSummaryText() { updatePlanName(getName()); } /** * Set the "plan summary" section of the plan overview. This summary * includes the plan name (bolded) and a brief description of the number of * activity groups and activities (in italics). * @param lastModified * @param name */ protected void setPlanSummaryText( Integer numActivities, Integer numActivityGroups, String planName, String custodian, String worldPermissions, String group, String lastModified ) { // build the plan summary (name plus brief plan description) StringBuilder planSummaryBuilder = new StringBuilder(planName); if (worldPermissions != null) { planSummaryBuilder.append(" ("+worldPermissions+")"); } if (custodian != null) { planSummaryBuilder.append(" ["); planSummaryBuilder.append(custodian); if (group != null) { planSummaryBuilder.append("/"+group); } planSummaryBuilder.append("]"); } planSummaryBuilder.append("\n"); if (numActivities != null && numActivityGroups != null) { planSummaryBuilder.append("("); planSummaryBuilder.append(numActivities); planSummaryBuilder.append(" "); if (numActivities == 1) { planSummaryBuilder.append("activity"); } else { planSummaryBuilder.append("activities"); } planSummaryBuilder.append(" in "); planSummaryBuilder.append(numActivityGroups); planSummaryBuilder.append(" "); if (numActivityGroups == 1) { planSummaryBuilder.append("group"); } else { planSummaryBuilder.append("groups"); } planSummaryBuilder.append(") - Modified: "); planSummaryBuilder.append(lastModified); } String planSummaryString = planSummaryBuilder.toString(); objectSummaryText.setText(planSummaryString); // set the style ranges (bold plan name, and italics plan description) int planNameLength = planName.length(); objectSummaryBoldStyleRange.start = 0; objectSummaryBoldStyleRange.length = planNameLength; objectSummaryBoldStyleRange.fontStyle = SWT.BOLD; objectSummaryText.setStyleRange(objectSummaryBoldStyleRange); int custodianNameLength = 0; if (custodian != null) { custodianNameLength = custodian.length() + 3; } objectSummaryNormalStyleRange.start = planNameLength; objectSummaryNormalStyleRange.length = custodianNameLength; objectSummaryNormalStyleRange.fontStyle = SWT.NONE; objectSummaryText.setStyleRange(objectSummaryNormalStyleRange); objectSummaryItalicsStyleRange.start = custodianNameLength + planNameLength; objectSummaryItalicsStyleRange.length = planSummaryString.length() - planNameLength - custodianNameLength; objectSummaryItalicsStyleRange.fontStyle = SWT.ITALIC; objectSummaryText.setStyleRange(objectSummaryItalicsStyleRange); // tell our parent to re-layout composite.layout(true, true); } /** * Set the "notes" section of the plan overview. If the specified notes * argument is > 75 characters, the display will truncate the notes and set * a tool tip with the complete notes value. * * @param notes */ public void setNotesText(String notes) { if (notes == null) { notes = ""; } if (notes.length() > 75) { notesLabel.setToolTipText(notes); notes = notes.substring(0, 75) + " ..."; } else notesLabel.setToolTipText(null); notesLabel.setText(notes); composite.layout(true, true); } @Override public void propertyChange(PropertyChangeEvent evt) { String name = evt.getPropertyName(); if (EditorPlugin.ATTRIBUTE_NOTES.equals(name)) { setNotesText((String) evt.getNewValue()); } else if (WrapperUtils.ATTRIBUTE_NAME.equals(name)) { updatePlanName((String) evt.getNewValue()); } else if (PermissionConstants.WORLD_PERMISSIONS_KEY.equals(name)) { updateWorldPermissions((String) evt.getNewValue()); } } public int getActivityGroupCount() { class CountingVisitor extends PlanVisitor { int groups = 0; @Override protected void visit(EPlanElement element) { if (element instanceof EActivityGroup) { groups++; } } } CountingVisitor visitor = new CountingVisitor(); visitor.visitAll(plan); return visitor.groups; } public int getActivityCount() { class CountingVisitor extends PlanVisitor { int activities = 0; @Override protected void visit(EPlanElement element) { if (element instanceof EActivity) { activities++; } } } CountingVisitor visitor = new CountingVisitor(); visitor.visitAll(plan); return visitor.activities; } public String getNotes() { return plan.getMember(CommonMember.class).getNotes(); } public String getCustodian() { return WrapperUtils.getAttributeValue(plan, EditorPlugin.ATTRIBUTE_CUSTODIAN); } public String getWorldPermissions() { return WrapperUtils.getAttributeValue(plan, PermissionConstants.WORLD_PERMISSIONS_KEY); } public String getGroup() { return WrapperUtils.getAttributeValue(plan, EditorPlugin.ATTRIBUTE_GROUP); } public String getLastModified() { EObject adapter = CommonUtils.getAdapter(plan, EObject.class); if (adapter != null && adapter.eResource() != null) { long time = adapter.eResource().getTimeStamp(); Date date = new Date(time); return StringifierRegistry.getStringifier(Date.class).getDisplayString(date); } return "Unknown"; } public String getPlanState() { return WrapperUtils.getAttributeValue(plan, EditorPlugin.ATTRIBUTE_PLAN_STATE); } /** * Performs the following query: * select valueString from parameter param, activity a, activityGroup ag, plan p * where p.name = 'name' * and ag.plan = p.id * and a.activityGroup = ag.id * and param.planElement = a.id * and param.name = ATTRIBUTE_TYPE; * @return a list of string representing the categories fo the plan */ public Set<String> getCategorySet() { final Set<String> categories = new LinkedHashSet<String>(); new PlanVisitor() { @Override protected void visit(EPlanElement element) { if (element instanceof EActivity) { EActivity activity = (EActivity) element; EActivityDef def = ADParameterUtils.getActivityDef(activity); if (def == null) { LogUtil.warn("PlanOverviewProvider.getCategorySet(): Activity "+activity.getName()+" has null ActivityDef"); } else { categories.add(def.getCategory()); } } } }.visitAll(plan); return categories; } }
3e139da558efa3a4fe6c9548347a0f60ae32ded4
7,150
java
Java
src/main/java/com/thed/zephyr/jenkins/utils/rest/ServerInfo.java
stacywile/zephyr-for-jira-test-management-plugin
ffec9e014705594ea46f66d27032fe63408680dc
[ "Apache-2.0" ]
8
2016-02-11T23:05:34.000Z
2021-05-21T07:00:13.000Z
src/main/java/com/thed/zephyr/jenkins/utils/rest/ServerInfo.java
stacywile/zephyr-for-jira-test-management-plugin
ffec9e014705594ea46f66d27032fe63408680dc
[ "Apache-2.0" ]
3
2016-02-09T22:45:43.000Z
2020-01-21T12:54:05.000Z
src/main/java/com/thed/zephyr/jenkins/utils/rest/ServerInfo.java
stacywile/zephyr-for-jira-test-management-plugin
ffec9e014705594ea46f66d27032fe63408680dc
[ "Apache-2.0" ]
39
2015-07-31T21:51:07.000Z
2022-02-15T20:51:20.000Z
29.66805
172
0.69972
8,293
package com.thed.zephyr.jenkins.utils.rest; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import com.thed.zephyr.cloud.rest.ZFJCloudRestClient; import com.thed.zephyr.cloud.rest.client.JwtGenerator; public class ServerInfo { private static String URL_GET_PROJECTS = "{SERVER}/rest/api/2/project?expand"; private static String URL_GET_ISSUETYPES = "{SERVER}/rest/api/2/issuetype"; private static String URL_ZCLOUD_GET_GENERAL_INFO = "{SERVER}/public/rest/api/1.0/config/generalinformation"; private static String TEST_ISSSUETYPE_NAME = "Test"; private static long ISSUE_TYPE_ID = 10100L; private static String URL_GET_USERS = "{SERVER}/rest/api/2/user?username="; public static boolean findServerAddressIsValidZephyrURL(RestClient restClient) { boolean status = false; HttpResponse response = null; try { String constructedURL = URL_GET_PROJECTS.replace("{SERVER}", restClient.getUrl()); response = restClient.getHttpclient().execute(new HttpGet(constructedURL)); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); if (string.startsWith("[") && string.endsWith("]") ) return true; } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if (statusCode == 401) { return false; } else if (statusCode == 404) { return false; } else{ try { throw new ClientProtocolException("Unexpected response status: " + statusCode); } catch (ClientProtocolException e) { e.printStackTrace(); } } return status; } public static long findTestIssueTypeId(RestClient restClient) { long status = ISSUE_TYPE_ID; HttpResponse response = null; try { String constructedURL = URL_GET_ISSUETYPES.replace("{SERVER}", restClient.getUrl()); HttpGet getRequest = new HttpGet(constructedURL); getRequest.addHeader("Content-Type", "application/json"); getRequest.addHeader("Accept-Encoding", "gzip, deflate, sdch"); response = restClient.getHttpclient().execute(getRequest, restClient.getContext()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity, "utf-8"); JSONArray jArr = new JSONArray(string); for (int i = 0; i < jArr.length(); i++) { JSONObject jObj = (JSONObject) jArr.getJSONObject(i); if (jObj.getString("name").trim().equals(TEST_ISSSUETYPE_NAME)) { long testIssueTypeId = jObj.getLong("id"); return testIssueTypeId; } } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if (statusCode == 401 || statusCode == 404) { return status; } else{ try { throw new ClientProtocolException("Unexpected response status: " + statusCode); } catch (ClientProtocolException e) { e.printStackTrace(); } } return status; } public static boolean validateCredentials(RestClient restClient) { boolean status = true; HttpResponse response = null; try { String constructedURL = URL_GET_USERS.replace("{SERVER}", restClient.getUrl()) + restClient.getUserName(); response = restClient.getHttpclient().execute(new HttpGet(constructedURL), restClient.getContext()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { status = false; } return status; } public static Map<Boolean, String> findServerAddressIsValidZephyrCloudURL(RestClient restClient) { Map<Boolean, String> statusMap = new HashMap<Boolean, String>(); statusMap.put(false, "Error Validating Zephyr for JIRA Cloud and ZAPI Cloud"); HttpResponse response = null; try { String constructedURL = URL_ZCLOUD_GET_GENERAL_INFO.replace("{SERVER}", restClient.getZephyrCloudURL()); String jwtHeaderValue = generateJWT(restClient, constructedURL, "GET"); HttpGet getRequest = new HttpGet(constructedURL); getRequest.addHeader("Content-Type", "application/json"); getRequest.addHeader("Authorization", jwtHeaderValue); getRequest.addHeader("zapiAccessKey", restClient.getAccessKey()); response = restClient.getHttpclient().execute(getRequest); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); if (string.startsWith("{") && string.endsWith("}") && string.contains("Zephyr")) { statusMap.put(true, "success"); } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // if (string != null) { // statusMap.put(false, string); // } else { // statusMap.put(false, "UnAuthorized"); // } statusMap.put(false, "UnAuthorized. Please ensure accesskey & secretkey are valid."); } else if (statusCode == 404) { statusMap.put(false, "Invalid Zephyr for JIRA Cloud URL"); } else if (statusCode == 200) { HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); if (string.startsWith("{") && string.endsWith("}") && string.contains("Zephyr")) { statusMap.put(true, "success"); } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return statusMap; } static String generateJWT(RestClient restClient, String constructedURL, String requestMethod) { ZFJCloudRestClient client = ZFJCloudRestClient.restBuilder(restClient.getZephyrCloudURL(), restClient.getAccessKey(), restClient.getSecretKey(), restClient.getUserName()) .build(); JwtGenerator jwtGenerator = client.getJwtGenerator(); URI uri = null; try { uri = new URI(constructedURL); } catch (URISyntaxException e) { e.printStackTrace(); } int expirationInSec = 1800; String jwt = jwtGenerator.generateJWT(requestMethod, uri, expirationInSec); return jwt; } }
3e139dedd78ce70a93c503921649abb9e7b6c2ee
1,595
java
Java
src/main/java/app/web/database/DatabaseMigrationServlet.java
project-templates/payara-application
b2becb437c57b322b62ca9e820152208c3f6a1d6
[ "MIT" ]
null
null
null
src/main/java/app/web/database/DatabaseMigrationServlet.java
project-templates/payara-application
b2becb437c57b322b62ca9e820152208c3f6a1d6
[ "MIT" ]
9
2016-12-09T14:31:03.000Z
2017-01-06T14:19:40.000Z
src/main/java/app/web/database/DatabaseMigrationServlet.java
project-templates/payara-application
b2becb437c57b322b62ca9e820152208c3f6a1d6
[ "MIT" ]
null
null
null
33.93617
115
0.670846
8,294
package app.web.database; import lombok.extern.slf4j.Slf4j; import org.flywaydb.core.Flyway; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import java.io.IOException; @Slf4j @WebServlet("/database/migration") public class DatabaseMigrationServlet extends HttpServlet { @Inject private DataSource dataSource; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("/WEB-INF/jsp/database/migration.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Flyway flyway = new Flyway(); flyway.setDataSource(this.dataSource); if (req.getParameter("migrate") != null) { log.info("migrate database"); flyway.migrate(); } else if (req.getParameter("clean") != null) { log.info("clean database"); flyway.clean(); } else if (req.getParameter("cleanMigrate") != null) { log.info("clean database"); flyway.clean(); log.info("migrate database"); flyway.migrate(); } req.getRequestDispatcher("/WEB-INF/jsp/database/migration.jsp").forward(req, resp); } }
3e139ed7455fda321cccd2e05a57447d4858237a
5,870
java
Java
src/ec/Problem.java
tomkren/ecj-playground
3ed511747b3bfce905b331a68342964c136148e5
[ "AFL-3.0" ]
6
2019-05-21T15:03:42.000Z
2022-03-20T14:45:16.000Z
src/ec/Problem.java
tomkren/ecj-playground
3ed511747b3bfce905b331a68342964c136148e5
[ "AFL-3.0" ]
1
2016-12-09T00:17:19.000Z
2016-12-09T00:28:42.000Z
src/ec/Problem.java
tomkren/ecj-playground
3ed511747b3bfce905b331a68342964c136148e5
[ "AFL-3.0" ]
7
2017-04-20T09:46:04.000Z
2022-03-29T03:10:45.000Z
38.874172
138
0.689779
8,295
/* Copyright 2006 by Sean Luke Licensed under the Academic Free License version 3.0 See the file "LICENSE" for more information */ package ec; import ec.util.*; /* * Problem.java * * Created: Fri Oct 15 14:16:17 1999 * By: Sean Luke */ /** * Problem is a prototype which defines the problem against which we will * evaluate individuals in a population. * * <p>Since Problems are Prototypes, you should expect a new Problem class to be * cloned and used, on a per-thread basis, for the evolution of each * chunk of individuals in a new population. If you for some reason * need global Problem information, you will have to provide it * statically, or copy pointers over during the clone() process * (there is likely only one Problem prototype, depending on the * Evaluator class used). * * <p>Note that Problem does not implement a specific evaluation method. * Your particular Problem subclass will need to implement a some kind of * Problem Form (for example, SimpleProblemForm) appropriate to the kind of * evaluation being performed on the Problem. These Problem Forms will provide * the evaluation methods necessary. * * <p>Problem forms will define some kind of <i>evaluation</i> method. This method * may be called in one of two ways by the Evaluator. * * <ul> * <li> The evaluation is called for a series of individuals. This is the old approach, * and it means that each individual must be evaluated and modified as specified by the * Problem Form during the evaluation call. * <li> prepareToEvaluate is called, then a series of individuals is evaluated, and then * finishEvaluating is called. This is the new approach, and in this case the Problem * is free to delay evaluating and modifying the individuals until finishEvaluating has * been called. The Problem may perfectly well evaluate and modify the individuals during * each evaluation call if it likes. It's just given this additional option. * </ul> * * <p>Problems should be prepared for both of the above situations. The easiest way * to handle it is to simply evaluate each individual as his evaluate(...) method is called, * and do nothing during prepareToEvaluate or finishEvaluating. That should be true for * the vast majority of Problem types. * * @author Sean Luke * @version 2.0 */ public abstract class Problem implements Prototype { public static final String P_PROBLEM = "problem"; /** Here's a nice default base for you -- you can change it if you like */ public Parameter defaultBase() { return new Parameter(P_PROBLEM); } // default form does nothing public void setup(final EvolutionState state, final Parameter base) { } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } // never happens } /** May be called by the Evaluator prior to a series of individuals to evaluate, and then ended with a finishEvaluating(...). If this is the case then the Problem is free to delay modifying the individuals or their fitnesses until at finishEvaluating(...). If no prepareToEvaluate(...) is called prior to evaluation, the Problem must complete its modification of the individuals and their fitnesses as they are evaluated as stipulated in the relevant evaluate(...) documentation for SimpleProblemForm or GroupedProblemForm. The default method does nothing. Note that prepareToEvaluate() can be called *multiple times* prior to finishEvaluating() being called -- in this case, the subsequent calls may be ignored. */ public void prepareToEvaluate(final EvolutionState state, final int threadnum) { } /** Will be called by the Evaluator after prepareToEvaluate(...) is called and then a series of individuals are evaluated. However individuals may be evaluated without prepareToEvaluate or finishEvaluating being called at all. See the documentation for prepareToEvaluate for more information. The default method does nothing.*/ public void finishEvaluating(final EvolutionState state, final int threadnum) { } /** Called to set up remote evaluation network contacts when the run is started. By default does nothing. */ public void initializeContacts( EvolutionState state ) { } /** Called to reinitialize remote evaluation network contacts when the run is restarted from checkpoint. By default does nothing. */ public void reinitializeContacts( EvolutionState state ) { } /** Called to shut down remote evaluation network contacts when the run is completed. By default does nothing. */ public void closeContacts(EvolutionState state, int result) { } /** Asynchronous Steady-State EC only: Returns true if the problem is ready to evaluate. In most cases, the default is true. */ public boolean canEvaluate() { return true; } /** Part of SimpleProblemForm. Included here so you don't have to write the default version, which usually does nothing. */ public void describe( final EvolutionState state, final Individual ind, final int subpopulation, final int threadnum, final int log) { return; } /** @deprecated Use the version without verbosity */ public final void describe(final Individual ind, final EvolutionState state, final int subpopulation, final int threadnum, final int log, final int verbosity) { describe(state, ind, subpopulation, threadnum, log); } }
3e139f15a5230a88e43ab00d222dd5ad808fca1b
2,309
java
Java
UPT_AUTO/src/test/java/com/jd/libra/BPT_Auto/PageFactory/Libra_Page_Index.java
MarcusChang/Repo-JETS
a9be89cf8e6dc15d8794ff23e9053806e6ecada4
[ "Apache-2.0" ]
1
2015-07-17T16:08:50.000Z
2015-07-17T16:08:50.000Z
UPT_AUTO/src/test/java/com/jd/libra/BPT_Auto/PageFactory/Libra_Page_Index.java
MarcusChang/Repo-JETS
a9be89cf8e6dc15d8794ff23e9053806e6ecada4
[ "Apache-2.0" ]
null
null
null
UPT_AUTO/src/test/java/com/jd/libra/BPT_Auto/PageFactory/Libra_Page_Index.java
MarcusChang/Repo-JETS
a9be89cf8e6dc15d8794ff23e9053806e6ecada4
[ "Apache-2.0" ]
null
null
null
47.122449
133
0.730619
8,296
package com.jd.libra.BPT_Auto.PageFactory; import Utils.TestUtilFunctions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; /** * Created by changxuliang on 2015/7/15. */ public class Libra_Page_Index extends CommonPageModel { public WebElement Btn_GoTop; //“返回顶部”按钮 public WebElement Banner_tab_left; //首页‘请您帮忙’banner public WebElement Btn_MyTopic; //首页‘我的话题’按钮 public WebElement Btn_MyTopicContainer_Close; //首页‘我的话题’弹出框 public WebElement Btn_UserAsk; //首页‘我要提问’按钮 public WebElement Dlg_PopupAskContainer; //首页弹出‘我要提问’窗口 public WebElement Ipt_AskUrl; //首页弹出‘我要提问’窗口的URL输入栏 public WebElement Ipt_AskTextArea; //首页弹出‘我要提问’窗口的内容输入框 public WebElement Btn_AskSubmit; //首页弹出‘我要提问’窗口的提交按钮 public WebElement Dlg_ActReturns_CreateTopic; //首页创建话题后的返回结果 public WebElement Btn_AskClose; //首页‘我要提问’弹出窗口的关闭按钮 public void getLibraPageIndexElement(WebDriver driver) { Btn_GoTop = getPageElementById(driver, By.id("gotop")); Banner_tab_left = getPageElementById(driver, By.id("tab_left")); Btn_MyTopic = getPageElementById(driver, By.xpath("//span[@id='sidebar_mytopic']")); Btn_MyTopicContainer_Close = getPageElementByXpath(driver, By.xpath("//*[@id=\"dialog_mytopic_container\"]/div[1]/i")); Btn_UserAsk = getPageElementByXpath(driver, By.xpath("//*[@id=\"sidebar_ask_btn\"]")); Dlg_PopupAskContainer = getPageElementByXpath(driver, By.xpath("//*[@id=\"dialog_ask_container\"]")); Ipt_AskUrl = getPageElementByXpath(driver, By.xpath("//form[@id='dialog_ask_form']/div[2]/textarea")); Ipt_AskTextArea = getPageElementByXpath(driver, By.xpath("//*[@id=\"dialog_ask_form_textarea_wrapper\"]/textarea")); Btn_AskSubmit = getPageElementByXpath(driver, By.xpath("//*[@id=\"dialog_ask_form\"]/p/input")); Dlg_ActReturns_CreateTopic = getPageElementByXpath(driver, By.xpath("//*[@id=\"dialog_ask_form_textarea_wrapper\"]/p/span")); Btn_AskClose = getPageElementByXpath(driver, By.xpath("//*[@id=\"dialog_ask_close\"]")); } public void cleanMyTopicContainerAskTextArea(WebDriver driver, TestUtilFunctions testUtil){ testUtil.clearInputs(driver, Ipt_AskTextArea); testUtil.waitForTime(1000); } }
3e139f24dce0b71426cafa79cbff2fd4b5a68e84
8,893
java
Java
myth-core/src/main/java/org/dromara/myth/core/spi/repository/FileCoordinatorRepository.java
Bing-ok/myth
8f9d885a208a71707a57d90c17f57434771d6f69
[ "Apache-2.0" ]
1,501
2017-12-01T06:34:08.000Z
2019-07-22T02:57:06.000Z
myth-core/src/main/java/org/dromara/myth/core/spi/repository/FileCoordinatorRepository.java
Bing-ok/myth
8f9d885a208a71707a57d90c17f57434771d6f69
[ "Apache-2.0" ]
43
2017-12-26T06:12:43.000Z
2019-04-25T06:40:14.000Z
myth-core/src/main/java/org/dromara/myth/core/spi/repository/FileCoordinatorRepository.java
Bing-ok/myth
8f9d885a208a71707a57d90c17f57434771d6f69
[ "Apache-2.0" ]
612
2017-12-11T09:18:38.000Z
2019-07-21T02:58:39.000Z
38.665217
142
0.663668
8,297
/* * 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.dromara.myth.core.spi.repository; import com.google.common.collect.Lists; import org.dromara.myth.annotation.MythSPI; import org.dromara.myth.common.bean.adapter.CoordinatorRepositoryAdapter; import org.dromara.myth.common.bean.entity.MythTransaction; import org.dromara.myth.common.config.MythConfig; import org.dromara.myth.common.constant.CommonConstant; import org.dromara.myth.common.enums.MythStatusEnum; import org.dromara.myth.common.enums.RepositorySupportEnum; import org.dromara.myth.common.exception.MythException; import org.dromara.myth.common.exception.MythRuntimeException; import org.dromara.myth.common.serializer.ObjectSerializer; import org.dromara.myth.common.utils.FileUtils; import org.dromara.myth.common.utils.RepositoryConvertUtils; import org.dromara.myth.common.utils.RepositoryPathUtils; import org.dromara.myth.core.spi.MythCoordinatorRepository; import java.io.File; import java.io.FileInputStream; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; /** * use file save mythTransaction log. * * @author xiaoyu */ @SuppressWarnings("all") @MythSPI("file") public class FileCoordinatorRepository implements MythCoordinatorRepository { private String filePath; private ObjectSerializer serializer; private AtomicBoolean initialized = new AtomicBoolean(false); @Override public void setSerializer(final ObjectSerializer serializer) { this.serializer = serializer; } @Override public int create(final MythTransaction transaction) { writeFile(transaction); return CommonConstant.SUCCESS; } @Override public int remove(final String id) { String fullFileName = RepositoryPathUtils.getFullFileName(filePath, id); File file = new File(fullFileName); return file.exists() && file.delete() ? CommonConstant.SUCCESS : CommonConstant.ERROR; } @Override public int update(final MythTransaction transaction) throws MythRuntimeException { transaction.setLastTime(new Date()); transaction.setVersion(transaction.getVersion() + 1); transaction.setRetriedCount(transaction.getRetriedCount() + 1); writeFile(transaction); return CommonConstant.SUCCESS; } @Override public void updateFailTransaction(final MythTransaction mythTransaction) throws MythRuntimeException { try { final String fullFileName = RepositoryPathUtils.getFullFileName(filePath, mythTransaction.getTransId()); mythTransaction.setLastTime(new Date()); FileUtils.writeFile(fullFileName, RepositoryConvertUtils.convert(mythTransaction, serializer)); } catch (MythException e) { throw new MythRuntimeException("update exception!"); } } @Override public void updateParticipant(final MythTransaction mythTransaction) throws MythRuntimeException { try { final String fullFileName = RepositoryPathUtils.getFullFileName(filePath, mythTransaction.getTransId()); final File file = new File(fullFileName); final CoordinatorRepositoryAdapter adapter = readAdapter(file); if (Objects.nonNull(adapter)) { adapter.setContents(serializer.serialize(mythTransaction.getMythParticipants())); } FileUtils.writeFile(fullFileName, serializer.serialize(adapter)); } catch (Exception e) { throw new MythRuntimeException("update exception!"); } } @Override public int updateStatus(final String id, final Integer status) throws MythRuntimeException { try { final String fullFileName = RepositoryPathUtils.getFullFileName(filePath, id); final File file = new File(fullFileName); final CoordinatorRepositoryAdapter adapter = readAdapter(file); if (Objects.nonNull(adapter)) { adapter.setStatus(status); } FileUtils.writeFile(fullFileName, serializer.serialize(adapter)); return CommonConstant.SUCCESS; } catch (Exception e) { throw new MythRuntimeException("更新数据异常!"); } } @Override public MythTransaction findByTransId(final String transId) { String fullFileName = RepositoryPathUtils.getFullFileName(filePath, transId); File file = new File(fullFileName); try { return readTransaction(file); } catch (Exception e) { e.printStackTrace(); return null; } } @Override public List<MythTransaction> listAllByDelay(final Date date) { final List<MythTransaction> mythTransactionList = listAll(); return mythTransactionList.stream() .filter(tccTransaction -> tccTransaction.getLastTime().compareTo(date) < 0) .filter(mythTransaction -> mythTransaction.getStatus() == MythStatusEnum.BEGIN.getCode()) .collect(Collectors.toList()); } private List<MythTransaction> listAll() { List<MythTransaction> transactionRecoverList = Lists.newArrayList(); File path = new File(filePath); File[] files = path.listFiles(); if (files != null && files.length > 0) { for (File file : files) { try { MythTransaction transaction = readTransaction(file); transactionRecoverList.add(transaction); } catch (Exception e) { e.printStackTrace(); } } } return transactionRecoverList; } @Override public void init(final String modelName, final MythConfig mythConfig) { filePath = RepositoryPathUtils.buildFilePath(modelName); File file = new File(filePath); if (!file.exists()) { file.getParentFile().mkdirs(); file.mkdirs(); } } private MythTransaction readTransaction(final File file) throws Exception { try (FileInputStream fis = new FileInputStream(file)) { byte[] content = new byte[(int) file.length()]; fis.read(content); return RepositoryConvertUtils.transformBean(content, serializer); } } private CoordinatorRepositoryAdapter readAdapter(final File file) throws Exception { try (FileInputStream fis = new FileInputStream(file)) { byte[] content = new byte[(int) file.length()]; fis.read(content); return serializer.deSerialize(content, CoordinatorRepositoryAdapter.class); } } private void writeFile(final MythTransaction transaction) throws MythRuntimeException { for (; ; ) { if (makeDirIfNecessary()) { break; } } try { String fileName = RepositoryPathUtils.getFullFileName(filePath, transaction.getTransId()); FileUtils.writeFile(fileName, RepositoryConvertUtils.convert(transaction, serializer)); } catch (Exception e) { throw new MythRuntimeException("fail to write transaction to local storage", e); } } private boolean makeDirIfNecessary() throws MythRuntimeException { if (!initialized.getAndSet(true)) { File rootDir = new File(filePath); boolean isExist = rootDir.exists(); if (!isExist) { if (rootDir.mkdir()) { return true; } else { throw new MythRuntimeException(String.format("fail to make root directory, path:%s.", filePath)); } } else { if (rootDir.isDirectory()) { return true; } else { throw new MythRuntimeException(String.format("the root path is not a directory, please check again, path:%s.", filePath)); } } } return true;// 已初始化目录,直接返回true } }
3e139f5fd764acb14f924a69245052df72f8886f
103
java
Java
test/sematest/invalid/identifier_system_in_scope5.java
Azegor/mjc
8b7eaca7e2079378d99a2a6fc7f6076976922dab
[ "MIT" ]
3
2019-08-09T00:57:22.000Z
2020-06-18T23:03:05.000Z
test/sematest/invalid/identifier_system_in_scope5.java
Azegor/mjc
8b7eaca7e2079378d99a2a6fc7f6076976922dab
[ "MIT" ]
null
null
null
test/sematest/invalid/identifier_system_in_scope5.java
Azegor/mjc
8b7eaca7e2079378d99a2a6fc7f6076976922dab
[ "MIT" ]
null
null
null
17.166667
42
0.601942
8,298
class A { public int System; public static void main(String[] args) { int a = System + 3; } }
3e139fa610dfe80fd7414b8c903c0c03a0c8d32a
2,390
java
Java
runtime/src/main/java/com/datastax/oss/quarkus/runtime/api/reactive/MutinyReactiveSession.java
kstrempel/cassandra-quarkus
b356d0aea742516c1326254df1f9137095a40adb
[ "Apache-2.0" ]
497
2020-04-15T19:20:16.000Z
2022-03-31T05:01:16.000Z
runtime/src/main/java/com/datastax/oss/quarkus/runtime/api/reactive/MutinyReactiveSession.java
kstrempel/cassandra-quarkus
b356d0aea742516c1326254df1f9137095a40adb
[ "Apache-2.0" ]
154
2020-03-29T17:42:24.000Z
2022-03-18T09:58:29.000Z
runtime/src/main/java/com/datastax/oss/quarkus/runtime/api/reactive/MutinyReactiveSession.java
kstrempel/cassandra-quarkus
b356d0aea742516c1326254df1f9137095a40adb
[ "Apache-2.0" ]
39
2020-04-02T17:55:50.000Z
2022-03-23T18:09:32.000Z
37.936508
97
0.754812
8,299
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.quarkus.runtime.api.reactive; import com.datastax.dse.driver.api.core.cql.reactive.ReactiveSession; import com.datastax.dse.driver.internal.core.cql.reactive.CqlRequestReactiveProcessor; import com.datastax.oss.driver.api.core.cql.SimpleStatement; import com.datastax.oss.driver.api.core.cql.Statement; import com.datastax.oss.quarkus.runtime.internal.reactive.DefaultMutinyReactiveResultSet; import edu.umd.cs.findbugs.annotations.NonNull; import io.smallrye.mutiny.Multi; import java.util.Objects; /** * A specialized {@link ReactiveSession} that supports the Reactive Mutiny API. * * <p>It provides user-friendly methods for executing CQL statements in a reactive way; these * methods all return {@link MutinyReactiveResultSet}, which is a subtype of {@link Multi}. */ public interface MutinyReactiveSession extends ReactiveSession { /** * Returns a {@link Multi} that, once subscribed to, executes the given query and emits all the * results. * * @param query the query to execute. * @return The {@link Multi} that will publish the returned results. */ @NonNull @Override default MutinyReactiveResultSet executeReactive(@NonNull String query) { return executeReactive(SimpleStatement.newInstance(query)); } /** * Returns a {@link Multi} that, once subscribed to, executes the given query and emits all the * results. * * @param statement the statement to execute. * @return The {@link Multi} that will publish the returned results. */ @NonNull @Override default MutinyReactiveResultSet executeReactive(@NonNull Statement<?> statement) { return new DefaultMutinyReactiveResultSet( Objects.requireNonNull( execute(statement, CqlRequestReactiveProcessor.REACTIVE_RESULT_SET))); } }
3e139fc2ca88685973091c79f83a5cf6f97c527a
3,251
java
Java
dhis-2/dhis-support/dhis-support-system/src/test/java/org/hisp/dhis/system/util/TextUtilsTest.java
hispindia/MAHARASHTRA-2.13
f50ec5b3ca2c5fabb43058166fd0c0fbbaa946a9
[ "BSD-3-Clause" ]
null
null
null
dhis-2/dhis-support/dhis-support-system/src/test/java/org/hisp/dhis/system/util/TextUtilsTest.java
hispindia/MAHARASHTRA-2.13
f50ec5b3ca2c5fabb43058166fd0c0fbbaa946a9
[ "BSD-3-Clause" ]
null
null
null
dhis-2/dhis-support/dhis-support-system/src/test/java/org/hisp/dhis/system/util/TextUtilsTest.java
hispindia/MAHARASHTRA-2.13
f50ec5b3ca2c5fabb43058166fd0c0fbbaa946a9
[ "BSD-3-Clause" ]
null
null
null
40.6375
155
0.683482
8,300
package org.hisp.dhis.system.util; /* * Copyright (c) 2004-2013, University of Oslo * All rights reserved. * * 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 the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * 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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import static org.junit.Assert.assertEquals; import static org.hisp.dhis.system.util.TextUtils.subString; import static org.hisp.dhis.system.util.TextUtils.trimEnd; import static org.hisp.dhis.system.util.TextUtils.*; import org.junit.Test; /** * @author Lars Helge Overland * @version $Id $ */ public class TextUtilsTest { private static final String STRING = "abcdefghij"; @Test public void testHtmlLinks() { assertEquals( "<a href=\"http://dhis2.org\">http://dhis2.org</a>", htmlLinks( "http://dhis2.org" ) ); assertEquals( "<a href=\"https://dhis2.org\">https://dhis2.org</a>", htmlLinks( "https://dhis2.org" ) ); assertEquals( "<a href=\"http://www.dhis2.org\">www.dhis2.org</a>", htmlLinks( "www.dhis2.org" ) ); assertEquals( "Navigate to <a href=\"http://dhis2.org\">http://dhis2.org</a> or <a href=\"http://www.dhis2.com\">www.dhis2.com</a> to read more.", htmlLinks( "Navigate to http://dhis2.org or www.dhis2.com to read more." ) ); } @Test public void testSubString() { assertEquals( "abcdefghij", subString( STRING, 0, 10 ) ); assertEquals( "cdef", subString( STRING, 2, 4 ) ); assertEquals( "ghij", subString( STRING, 6, 4 ) ); assertEquals( "ghij", subString( STRING, 6, 6 ) ); assertEquals( "", subString( STRING, 11, 3 ) ); assertEquals( "j", subString( STRING, 9, 1 ) ); assertEquals( "", subString( STRING, 4, 0 ) ); } @Test public void testTrim() { assertEquals( "abcdefgh", trimEnd( "abcdefghijkl", 4 ) ); } }
3e139fce86b30f923ecc15b8355528eb367703bc
1,261
java
Java
src/main/java/com/wexalian/jtrakt/endpoint/people/TraktPerson.java
Wexalian/jtrakt
3bb32a5fa75b406e2cead6832dfb195c8cdc3fce
[ "Unlicense" ]
1
2020-05-16T01:42:59.000Z
2020-05-16T01:42:59.000Z
src/main/java/com/wexalian/jtrakt/endpoint/people/TraktPerson.java
Wexalian/jtrakt
3bb32a5fa75b406e2cead6832dfb195c8cdc3fce
[ "Unlicense" ]
null
null
null
src/main/java/com/wexalian/jtrakt/endpoint/people/TraktPerson.java
Wexalian/jtrakt
3bb32a5fa75b406e2cead6832dfb195c8cdc3fce
[ "Unlicense" ]
null
null
null
19.703125
51
0.603489
8,301
package com.wexalian.jtrakt.endpoint.people; import com.wexalian.jtrakt.endpoint.TraktIds; import java.time.LocalDate; public class TraktPerson { private String name; private TraktIds ids; private Social social_ids; private String biography; private LocalDate birthday; private LocalDate death; private String birthplace; private String homepage; public TraktPerson() {} public TraktPerson(String name, TraktIds ids) { this.name = name; this.ids = ids; } public String getName() { return name; } public TraktIds getIds() { return ids; } public Social getSocialIds() { return social_ids; } public String getBiography() { return biography; } public LocalDate getBirthday() { return birthday; } public LocalDate getDeath() { return death; } public String getBirthplace() { return birthplace; } public String getHomepage() { return homepage; } public static class Social { public String twitter; public String facebook; public String instagram; public String wikipedia; } }
3e13a03db68636cb59003a293070f020cad435c4
854
java
Java
api/src/main/java/com/google/appengine/api/urlfetch/HTTPMethod.java
isopov/appengine-java-standard
e9d2465c2def0a6710d96969b58006835cd792f2
[ "ECL-2.0", "Apache-2.0" ]
125
2020-11-12T16:59:49.000Z
2022-03-29T17:56:28.000Z
api/src/main/java/com/google/appengine/api/urlfetch/HTTPMethod.java
isopov/appengine-java-standard
e9d2465c2def0a6710d96969b58006835cd792f2
[ "ECL-2.0", "Apache-2.0" ]
4
2022-01-27T04:35:11.000Z
2022-03-22T05:54:50.000Z
api/src/main/java/com/google/appengine/api/urlfetch/HTTPMethod.java
isopov/appengine-java-standard
e9d2465c2def0a6710d96969b58006835cd792f2
[ "ECL-2.0", "Apache-2.0" ]
15
2020-11-12T17:00:02.000Z
2022-03-28T09:57:03.000Z
26.6875
75
0.720141
8,302
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.appengine.api.urlfetch; /** * {@code HTTPMethod} is an enumeration of HTTP methods that can be * sent to a remote server via the {@code URLFetchService}. * */ public enum HTTPMethod { GET, POST, HEAD, PUT, DELETE, PATCH }
3e13a0c44241842d01d29270e48ed370528594aa
4,757
java
Java
obridge-main/src/main/java/org/obridge/model/data/Procedure.java
eriksaleksans/obridge
28b057eac8d30698e2a6217eb570d9362fee1157
[ "MIT" ]
24
2015-02-10T10:24:38.000Z
2021-09-14T09:38:57.000Z
obridge-main/src/main/java/org/obridge/model/data/Procedure.java
eriksaleksans/obridge
28b057eac8d30698e2a6217eb570d9362fee1157
[ "MIT" ]
46
2015-02-10T02:11:32.000Z
2022-01-04T16:54:53.000Z
obridge-main/src/main/java/org/obridge/model/data/Procedure.java
hiranp/obridge
28b057eac8d30698e2a6217eb570d9362fee1157
[ "MIT" ]
19
2016-02-29T12:49:32.000Z
2022-01-16T05:52:59.000Z
27.982353
121
0.655035
8,303
/* * The MIT License (MIT) * * Copyright (c) 2016 Ferenc Karsany * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.obridge.model.data; import org.obridge.mappers.builders.CallStringBuilder; import org.obridge.util.StringHelper; import org.obridge.util.TypeMapper; import java.util.List; /** * User: fkarsany Date: 2013.11.18. */ public class Procedure { private String objectName; private String procedureName; private String overload; private String methodType; private List<ProcedureArgument> argumentList; private List<BindParam> bindParams = null; private String callString; private Procedure() { } public List<ProcedureArgument> getArgumentList() { return argumentList; } public void setArgumentList(List<ProcedureArgument> argumentList) { this.argumentList = argumentList; } public String getMethodType() { return methodType; } public void setMethodType(String methodType) { this.methodType = methodType; } public String getObjectName() { return objectName; } public void setObjectName(String objectName) { this.objectName = objectName; } public String getProcedureName() { return procedureName; } public void setProcedureName(String procedureName) { this.procedureName = procedureName; } public String getOverload() { return overload; } public void setOverload(String overload) { this.overload = overload; } public String getJavaProcedureName() { String r = StringHelper.toCamelCaseSmallBegin(this.procedureName + "_" + this.overload); return StringHelper.unJavaKeyword(r); } public String getStoredProcedureClassName() { return StringHelper.toCamelCase(this.getObjectName() + "_" + this.getProcedureName() + "_" + this.getOverload()); } public String getReturnJavaType() { return argumentList.get(0).getJavaDataType(); } public String getCallString() { return this.callString; } public List<BindParam> getBindParams() { return bindParams; } public boolean hasResultSetParam() { for (ProcedureArgument pa : this.argumentList) { if (TypeMapper.JAVA_RESULTSET.equals(pa.getJavaDataType())) { return true; } } return false; } @Override public String toString() { return "Procedure{" + "procedureName='" + procedureName + '\'' + '}'; } public static class Builder { Procedure p = new Procedure(); public Builder objectName(String objectName) { this.p.setObjectName(objectName); return this; } public Builder procedureName(String procedureName) { this.p.setProcedureName(procedureName); return this; } public Builder overload(String overload) { this.p.setOverload(overload); return this; } public Builder methodType(String methodType) { this.p.setMethodType(methodType); return this; } public Builder argumentList(List<ProcedureArgument> argumentList) { this.p.setArgumentList(argumentList); return this; } public Procedure build() { initBindParams(); return p; } private void initBindParams() { CallStringBuilder callStringBuilder = new CallStringBuilder(p); p.callString = callStringBuilder.build(); p.bindParams = callStringBuilder.getBindParams(); } } }
3e13a17cb3bee203261beb9242f02eec077298ea
3,274
java
Java
cnctools/src/main/java/com/rvantwisk/cnctools/opengl/View2D.java
edgarccohen/cnctool
4d1815486878ace8cc7c30a282413cd5b8010f37
[ "BSD-3-Clause" ]
16
2015-10-07T16:36:24.000Z
2021-09-20T07:46:30.000Z
cnctools/src/main/java/com/rvantwisk/cnctools/opengl/View2D.java
edgarccohen/cnctool
4d1815486878ace8cc7c30a282413cd5b8010f37
[ "BSD-3-Clause" ]
null
null
null
cnctools/src/main/java/com/rvantwisk/cnctools/opengl/View2D.java
edgarccohen/cnctool
4d1815486878ace8cc7c30a282413cd5b8010f37
[ "BSD-3-Clause" ]
8
2015-11-13T03:39:25.000Z
2019-06-23T09:51:52.000Z
34.829787
97
0.704643
8,304
/* * Copyright (c) 2014, R. van Twisk * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * 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 the aic-util nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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 THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rvantwisk.cnctools.opengl; import org.lwjgl.opengl.GL11; /** * Created by rvt on 1/10/14. */ public class View2D extends AbstractView { protected float NEAR=-100.0f; protected float FAR=100.0f; @Override public void ui_transform(float length) { GL11.glTranslatef(length, length, 0.0f); GL11.glRotatef(camera.getAzimuth(), 0.0f, 0.0f, 1.0f); } @Override public void begin() { GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPushMatrix(); GL11.glLoadIdentity(); GL11.glOrtho(0, camera.getWidth(), 0, camera.getHeight(), NEAR, FAR); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glLoadIdentity(); } @Override public void end() { GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPopMatrix(); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPopMatrix(); } @Override public void display_transform() { // _center_on_origin GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(-camera.getX(), camera.getX(), -camera.getY(), camera.getY(), NEAR, FAR); GL11.glMatrixMode(GL11.GL_MODELVIEW); // _center_on_origin GL11.glTranslatef(camera.getX(), camera.getY(), camera.getZ()); GL11.glRotatef(camera.getAzimuth(), 0.0f, 0.0f, 1.0f); GL11.glScalef(camera.getZoom_factor(), camera.getZoom_factor(), camera.getZoom_factor()); } }
3e13a196bb426c224958aa024aa640ab93cacff1
386
java
Java
src/main/java/com/sonata/microprofile/sample/microprofilerestservice/rest/HelloWorldEndpoint.java
RakeshKShukla/mprestservice
9c053ad4d30663741e66504ee4790e7a2bcea981
[ "MIT" ]
null
null
null
src/main/java/com/sonata/microprofile/sample/microprofilerestservice/rest/HelloWorldEndpoint.java
RakeshKShukla/mprestservice
9c053ad4d30663741e66504ee4790e7a2bcea981
[ "MIT" ]
null
null
null
src/main/java/com/sonata/microprofile/sample/microprofilerestservice/rest/HelloWorldEndpoint.java
RakeshKShukla/mprestservice
9c053ad4d30663741e66504ee4790e7a2bcea981
[ "MIT" ]
null
null
null
22.705882
68
0.821244
8,305
package com.sonata.microprofile.sample.microprofilerestservice.rest; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.ws.rs.Path; @ApplicationScoped @Path("/sangh") public class HelloWorldEndpoint { @PersistenceContext(unitName = "microprofilepu") private EntityManager em; }
3e13a2111e6877a988eaf5de460f96f114fba49f
3,228
java
Java
qtiworks-jqtiplus/src/main/java/uk/ac/ed/ph/jqtiplus/node/accessibility/companion/LinearUnitUS.java
abrommelhoff/qtiworks
6a4e4353fffb5c35cfa65a7e089386efc4570d97
[ "BSD-3-Clause" ]
1
2015-05-11T12:16:26.000Z
2015-05-11T12:16:26.000Z
qtiworks-jqtiplus/src/main/java/uk/ac/ed/ph/jqtiplus/node/accessibility/companion/LinearUnitUS.java
abrommelhoff/qtiworks
6a4e4353fffb5c35cfa65a7e089386efc4570d97
[ "BSD-3-Clause" ]
null
null
null
qtiworks-jqtiplus/src/main/java/uk/ac/ed/ph/jqtiplus/node/accessibility/companion/LinearUnitUS.java
abrommelhoff/qtiworks
6a4e4353fffb5c35cfa65a7e089386efc4570d97
[ "BSD-3-Clause" ]
null
null
null
35.866667
102
0.724597
8,306
/* Copyright (c) 2012-2013, University of Edinburgh. * All rights reserved. * * 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 the University of Edinburgh nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * This software is derived from (and contains code from) QTITools and MathAssessEngine. * QTITools is (c) 2008, University of Southampton. * MathAssessEngine is (c) 2010, University of Edinburgh. */ package uk.ac.ed.ph.jqtiplus.node.accessibility.companion; import uk.ac.ed.ph.jqtiplus.exception.QtiParseException; import uk.ac.ed.ph.jqtiplus.internal.util.ObjectUtilities; import uk.ac.ed.ph.jqtiplus.types.Stringifiable; import java.util.HashMap; import java.util.Map; /** * Linear unit options in the US system for Rule. * * @author Zack Pierce */ public enum LinearUnitUS implements Stringifiable { INCH("Inch"), FOOT("Foot"), YARD("Yard"), MILE("Mile"); private static final String QTI_CLASS_NAME = "USLinearValue"; private static Map<String, LinearUnitUS> namesToUnits; static { final HashMap<String, LinearUnitUS> hashMap = new HashMap<String, LinearUnitUS>(); for (final LinearUnitUS unit : LinearUnitUS.values()) { hashMap.put(unit.unit, unit); } namesToUnits = ObjectUtilities.unmodifiableMap(hashMap); } private String unit; private LinearUnitUS(final String unit) { this.unit = unit; } @Override public String toQtiString() { return unit; } public static LinearUnitUS parseLinearUnitUS(final String linearUnitUS) throws QtiParseException { final LinearUnitUS result = namesToUnits.get(linearUnitUS); if (result == null) { throw new QtiParseException("Invalid " + QTI_CLASS_NAME + " '" + linearUnitUS + "'."); } return result; } }
3e13a2b26f471575371a01ce6eade0472dfc176e
1,193
java
Java
application/src/main/java/org/mifos/framework/components/customTableTag/HeaderDetails.java
sureshkrishnamoorthy/suresh-mifos
88e7df964688ca3955b38125213090297d4171a4
[ "Apache-2.0" ]
7
2016-06-23T12:50:58.000Z
2020-12-21T18:39:55.000Z
application/src/main/java/org/mifos/framework/components/customTableTag/HeaderDetails.java
sureshkrishnamoorthy/suresh-mifos
88e7df964688ca3955b38125213090297d4171a4
[ "Apache-2.0" ]
8
2019-02-04T14:15:49.000Z
2022-02-01T01:04:00.000Z
application/src/main/java/org/mifos/framework/components/customTableTag/HeaderDetails.java
sureshkrishnamoorthy/suresh-mifos
88e7df964688ca3955b38125213090297d4171a4
[ "Apache-2.0" ]
20
2015-02-11T06:31:19.000Z
2020-03-04T15:24:52.000Z
29.825
70
0.711651
8,307
/* * Copyright (c) 2005-2011 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.framework.components.customTableTag; public class HeaderDetails { private String headerStyle = null; public String getHeaderStyle() { return headerStyle; } public void setHeaderStyle(String headerStyle) { this.headerStyle = headerStyle; } public void getHeaderInfo(StringBuilder tableInfo) { tableInfo.append(" class=\"" + getHeaderStyle() + "\" "); } }
3e13a3a02e6514d5f617d574e0c88fd0abd54dfa
2,522
java
Java
ea-basis-server-layer/auth-basic-server/src/main/java/com/bugjc/ea/auth/service/impl/AppTokenServiceImpl.java
bugjc/quick-ea
aa6885e07d35f3e3b2d7318d8615948b0e5e9d4a
[ "MIT" ]
null
null
null
ea-basis-server-layer/auth-basic-server/src/main/java/com/bugjc/ea/auth/service/impl/AppTokenServiceImpl.java
bugjc/quick-ea
aa6885e07d35f3e3b2d7318d8615948b0e5e9d4a
[ "MIT" ]
11
2019-11-01T04:12:39.000Z
2022-03-15T03:14:58.000Z
ea-basis-server-layer/auth-basic-server/src/main/java/com/bugjc/ea/auth/service/impl/AppTokenServiceImpl.java
bugjc/quick-ea
aa6885e07d35f3e3b2d7318d8615948b0e5e9d4a
[ "MIT" ]
1
2019-04-27T02:05:22.000Z
2019-04-27T02:05:22.000Z
35.521127
138
0.699841
8,308
package com.bugjc.ea.auth.service.impl; import cn.hutool.core.date.DateUtil; import com.bugjc.ea.auth.core.constants.AppTokenConstants; import com.bugjc.ea.auth.core.enums.business.AppTokenStatus; import com.bugjc.ea.auth.core.util.IdWorker; import com.bugjc.ea.auth.mapper.AppTokenMapper; import com.bugjc.ea.auth.model.AppToken; import com.bugjc.ea.auth.service.AppTokenService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Date; /** * 令牌服务 * @author yangqing * @date 2019/7/4 **/ @Service public class AppTokenServiceImpl implements AppTokenService { @Resource private AppTokenMapper appTokenMapper; @Override public AppToken findToken(String appId) { //token生命期内再次获取token会让旧和新token并存一小段段时间 Date date = new Date(); AppToken token = appTokenMapper.selLastByAppId(appId); if (token != null){ //旧的token过期时间小于等于当前时间,则标记token即将过期状态并设置较低的存活时间 if (new Date(DateUtil.offsetSecond(token.getCreateTime(),token.getTokenAvailableTime()).getTime()).compareTo(date) >= 0){ token.setStatus(AppTokenStatus.TokenToBeDestroyed.getStatus()); token.setTokenAvailableTime(AppTokenConstants.TOKEN_TO_BE_DESTROYED_AVAILABLE_TIME); }else{ token.setStatus(AppTokenStatus.DestroyedToken.getStatus()); token.setTokenAvailableTime(AppTokenConstants.DESTROYED_TOKEN_AVAILABLE_TIME); } appTokenMapper.updateByPrimaryKey(token); } //生成新的token AppToken newToken = new AppToken(); newToken.setAccessToken(IdWorker.getNextId()); newToken.setAppId(appId); newToken.setTokenAvailableTime(AppTokenConstants.CURRENT_LATEST_TOKEN_AVAILABLE_TIME); newToken.setCreateTime(date); newToken.setStatus(AppTokenStatus.CurrentLatestToken.getStatus()); appTokenMapper.insert(newToken); return newToken; } @Override public boolean verifyToken(String accessToken) { accessToken = accessToken.replace(AppTokenConstants.BEARER,""); AppToken token = appTokenMapper.selByAccessToken(accessToken); if (token == null){ return false; } if (token.getStatus() == AppTokenStatus.DestroyedToken.getStatus()){ return false; } return new Date(DateUtil.offsetSecond(token.getCreateTime(), token.getTokenAvailableTime()).getTime()).compareTo(new Date()) >= 0; } }
3e13a4b3d33def3d22c18b94ef12f08ef169c6ed
2,608
java
Java
core/src/main/java/org/bitcoinj/net/AddressChecker.java
lavajumper/sexcoinj
f45523931e40f7fb8e3b04cf51de7a36aeedcc0c
[ "Apache-2.0" ]
3
2018-01-08T11:07:05.000Z
2019-04-15T09:36:54.000Z
core/src/main/java/org/bitcoinj/net/AddressChecker.java
lavajumper/sexcoinj
f45523931e40f7fb8e3b04cf51de7a36aeedcc0c
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/bitcoinj/net/AddressChecker.java
lavajumper/sexcoinj
f45523931e40f7fb8e3b04cf51de7a36aeedcc0c
[ "Apache-2.0" ]
null
null
null
36.222222
84
0.653758
8,309
package org.bitcoinj.net; import org.bitcoinj.utils.CIDRUtils; import java.net.InetAddress; /** * Created by danda on 1/12/17. */ public class AddressChecker { private CIDRUtils onionCatNet; private CIDRUtils rfc4193Net; public AddressChecker() { // Note: this is borrowed/ported from btcd (written in go). // btcd has many more rules that are probably important and should be // implemented in this class, but for now we only care about onion // addresses for onioncat (ipv6) encoding/decoding. // onionCatNet defines the IPv6 address block used to support Tor. // bitcoind encodes a .onion address as a 16 byte number by decoding the // address prior to the .onion (i.e. the key hash) base32 into a ten // byte number. It then stores the first 6 bytes of the address as // 0xfd, 0x87, 0xd8, 0x7e, 0xeb, 0x43. // // This is the same range used by OnionCat, which is part part of the // RFC4193 unique local IPv6 range. // // In summary the format is: // { magic 6 bytes, 10 bytes base32 decode of key hash } onionCatNet = new CIDRUtils("fd87:d87e:eb43::", 48); // rfc4193Net specifies the IPv6 unique local address block as defined // by RFC4193 (FC00::/7). rfc4193Net = new CIDRUtils("FC00::", 7); } // IsValid returns whether or not the passed address is valid. The address is // considered invalid under the following circumstances: // IPv4: It is either a zero or all bits set address. // IPv6: It is either a zero or RFC3849 documentation address. public boolean IsValid(InetAddress addr) { // todo: port/implement. // IsUnspecified returns if address is 0, so only all bits set, and // RFC3849 need to be explicitly checked. // return na.IP != nil && !(na.IP.IsUnspecified() || // na.IP.Equal(net.IPv4bcast)) return true; } // IsOnionCatTor returns whether or not the passed address is in the IPv6 range // used by bitcoin to support Tor (fd87:d87e:eb43::/48). Note that this range // is the same range used by OnionCat, which is part of the RFC4193 unique local // IPv6 range. public boolean IsOnionCatTor(InetAddress addr) { return onionCatNet.isInRange(addr); } // IsRFC4193 returns whether or not the passed address is part of the IPv6 // unique local range as defined by RFC4193 (FC00::/7). public boolean IsRFC4193(InetAddress addr) { return rfc4193Net.isInRange(addr); } }
3e13a5b4a76402ded3ccebaf0544730edb1d2098
1,183
java
Java
src/main/java/com/github/msafonov/corporate/bot/Authorization.java
RedheadedGirl/corporate-bot
940a244408f69379a30c8a0739afc1e6b78ee183
[ "MIT" ]
null
null
null
src/main/java/com/github/msafonov/corporate/bot/Authorization.java
RedheadedGirl/corporate-bot
940a244408f69379a30c8a0739afc1e6b78ee183
[ "MIT" ]
null
null
null
src/main/java/com/github/msafonov/corporate/bot/Authorization.java
RedheadedGirl/corporate-bot
940a244408f69379a30c8a0739afc1e6b78ee183
[ "MIT" ]
null
null
null
32.861111
96
0.746407
8,310
package com.github.msafonov.corporate.bot; import com.github.msafonov.corporate.bot.controllers.EntityController; import com.github.msafonov.corporate.bot.entities.AuthorizationCode; import com.github.msafonov.corporate.bot.entities.Employee; public class Authorization { private final EntityController entityController; private final AdminsProperties adminsProperties; public Authorization(EntityController entityController, AdminsProperties adminsProperties) { this.entityController = entityController; this.adminsProperties = adminsProperties; } public void register(Employee employee, AuthorizationCode code) { entityController.save(employee); code.setEmployee(employee); entityController.update(code); } public boolean isRegistered(Employee employee) { //Возможна доп логика return employee != null; } public boolean isAdministrator(String chatId) { return adminsProperties.getChatId().contains(chatId); } public boolean isFreeCode(AuthorizationCode authorizationCode) { return authorizationCode != null && authorizationCode.getUserId() == null; } }
3e13a66a2a699c680b8a05ff0e3e628346079010
348
java
Java
src/main/java/com/mayreh/intellij/plugin/tlaplus/run/ui/errortrace/TextFragment.java
okue/tlaplus-intellij-plugin
2c4d4b2de7066d9053c5474fa4382ab271c29465
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mayreh/intellij/plugin/tlaplus/run/ui/errortrace/TextFragment.java
okue/tlaplus-intellij-plugin
2c4d4b2de7066d9053c5474fa4382ab271c29465
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mayreh/intellij/plugin/tlaplus/run/ui/errortrace/TextFragment.java
okue/tlaplus-intellij-plugin
2c4d4b2de7066d9053c5474fa4382ab271c29465
[ "Apache-2.0" ]
null
null
null
21.75
63
0.798851
8,311
package com.mayreh.intellij.plugin.tlaplus.run.ui.errortrace; import org.jetbrains.annotations.Nullable; import com.mayreh.intellij.plugin.tlaplus.run.ui.ActionFormula; import lombok.Value; import lombok.experimental.Accessors; @Value @Accessors(fluent = true) class TextFragment { String text; @Nullable ActionFormula actionFormula; }
3e13a6f06a2f52d1b5ac50843bc7a92d67837f55
4,956
java
Java
psi25-xml/src/main/java/psidev/psi/mi/xml/converter/impl254/ExperimentalPreparationConverter.java
vibbits/psimi
9baca51cd699a69b3a61533093919ccd614b42b4
[ "CC-BY-4.0" ]
4
2015-07-25T10:56:52.000Z
2022-02-04T12:51:56.000Z
psi25-xml/src/main/java/psidev/psi/mi/xml/converter/impl254/ExperimentalPreparationConverter.java
vibbits/psimi
9baca51cd699a69b3a61533093919ccd614b42b4
[ "CC-BY-4.0" ]
12
2015-12-17T14:52:54.000Z
2021-12-16T16:50:06.000Z
psi25-xml/src/main/java/psidev/psi/mi/xml/converter/impl254/ExperimentalPreparationConverter.java
vibbits/psimi
9baca51cd699a69b3a61533093919ccd614b42b4
[ "CC-BY-4.0" ]
4
2015-06-17T10:40:07.000Z
2021-12-14T13:04:36.000Z
37.55303
114
0.650999
8,312
/* * Copyright (c) 2002 The European Bioinformatics Institute, and others. * All rights reserved. Please see the file LICENSE * in the root directory of this distribution. */ package psidev.psi.mi.xml.converter.impl254; import psidev.psi.mi.xml.converter.ConverterException; import psidev.psi.mi.xml.dao.DAOFactory; import psidev.psi.mi.xml.model.ExperimentDescription; import psidev.psi.mi.xml.model.ExperimentRef; import psidev.psi.mi.xml254.jaxb.ExperimentRefList; /** * Converter to and from JAXB of the class ExperimentalPreparation. * * @author Samuel Kerrien (ychag@example.com) * @version $Id$ * @see psidev.psi.mi.xml.model.ExperimentalPreparation * @see psidev.psi.mi.xml254.jaxb.ExperimentalPreparation * @since <pre>07-Jun-2006</pre> */ public class ExperimentalPreparationConverter { /////////////////////////// // Instance variables private CvTypeConverter cvTypeConverter; /** * Handles DAOs. */ private DAOFactory factory; public ExperimentalPreparationConverter() { cvTypeConverter = new CvTypeConverter(); } /////////////////////////////// // DAO factory stategy /** * Set the DAO Factory that holds required DAOs for resolving ids. * * @param factory the DAO factory */ public void setDAOFactory( DAOFactory factory ) { this.factory = factory; } /** * Checks that the dependencies of that object are fulfilled. * * @throws ConverterException */ private void checkDependencies() throws ConverterException { if ( factory == null ) { throw new ConverterException( "Please set a DAO factory in order to resolve experiment's id." ); } } ///////////////////////////// // Converter methods public psidev.psi.mi.xml.model.ExperimentalPreparation fromJaxb( psidev.psi.mi.xml254.jaxb.ExperimentalPreparation jExperimentalPreparation ) throws ConverterException { if ( jExperimentalPreparation == null ) { throw new IllegalArgumentException( "You must give a non null JAXB Experimental preparation." ); } // Initialise the model reading the Jaxb object // 1. convert the CvType psidev.psi.mi.xml.model.ExperimentalPreparation mExperimentalPreparation = cvTypeConverter.fromJaxb( jExperimentalPreparation, psidev.psi.mi.xml.model.ExperimentalPreparation.class ); // 2. convert remaining components // experiments if ( jExperimentalPreparation.getExperimentRefList() != null ) { for ( Integer jExperimentId : jExperimentalPreparation.getExperimentRefList().getExperimentReves() ) { ExperimentDescription mExperiment = factory.getExperimentDAO().retreive( jExperimentId ); if ( mExperiment == null ) { mExperimentalPreparation.getExperimentRefs().add( new ExperimentRef( jExperimentId ) ); } else { mExperimentalPreparation.getExperiments().add( mExperiment ); } } } return mExperimentalPreparation; } public psidev.psi.mi.xml254.jaxb.ExperimentalPreparation toJaxb( psidev.psi.mi.xml.model.ExperimentalPreparation mExperimentalPreparation ) throws ConverterException { if ( mExperimentalPreparation == null ) { throw new IllegalArgumentException( "You must give a non null model Experimental preparation." ); } // Initialise the JAXB object reading the model // 1. convert the CvType psidev.psi.mi.xml254.jaxb.ExperimentalPreparation jExperimentalPreparation = cvTypeConverter.toJaxb( mExperimentalPreparation, psidev.psi.mi.xml254.jaxb.ExperimentalPreparation.class ); // 2. convert remaining components // experiments if ( mExperimentalPreparation.hasExperiments() ) { if ( jExperimentalPreparation.getExperimentRefList() == null ) { jExperimentalPreparation.setExperimentRefList( new ExperimentRefList() ); } for ( ExperimentDescription mExperiment : mExperimentalPreparation.getExperiments() ) { jExperimentalPreparation.getExperimentRefList().getExperimentReves().add( mExperiment.getId() ); } } else if ( mExperimentalPreparation.hasExperimentRefs() ) { if ( jExperimentalPreparation.getExperimentRefList() == null ) { jExperimentalPreparation.setExperimentRefList( new ExperimentRefList() ); } for ( ExperimentRef mExperiment : mExperimentalPreparation.getExperimentRefs() ) { jExperimentalPreparation.getExperimentRefList().getExperimentReves().add( mExperiment.getRef() ); } } return jExperimentalPreparation; } }
3e13a6f86b705136076914e86e9a1dc7da86323d
4,404
java
Java
digdag-core/src/main/java/io/digdag/core/workflow/SlaCalculator.java
j14159/digdag
dbcd311a380dfdf0b34a6ea5680d3aa2275e05dd
[ "Apache-2.0" ]
1,162
2016-06-15T00:50:20.000Z
2022-03-28T01:33:54.000Z
digdag-core/src/main/java/io/digdag/core/workflow/SlaCalculator.java
j14159/digdag
dbcd311a380dfdf0b34a6ea5680d3aa2275e05dd
[ "Apache-2.0" ]
1,154
2016-06-15T00:54:16.000Z
2022-03-30T08:53:05.000Z
digdag-core/src/main/java/io/digdag/core/workflow/SlaCalculator.java
j14159/digdag
dbcd311a380dfdf0b34a6ea5680d3aa2275e05dd
[ "Apache-2.0" ]
258
2016-06-15T04:40:48.000Z
2022-03-21T09:31:37.000Z
31.234043
117
0.591962
8,313
package io.digdag.core.workflow; import java.time.Duration; import java.util.List; import java.util.Date; import java.util.TimeZone; import java.util.Calendar; import java.time.ZoneId; import java.time.Instant; import java.time.temporal.ChronoUnit; import com.google.common.base.Optional; import com.google.inject.Inject; import io.digdag.client.config.Config; import io.digdag.client.config.ConfigException; import static java.util.Locale.ENGLISH; public class SlaCalculator { @Inject public SlaCalculator() { } public Instant getTriggerTime(Config slaConfig, Instant currentTime, ZoneId timeZone) { TriggerCalculator calc = getCalculator(slaConfig); return calc.calculateTime(currentTime, timeZone); } private TriggerCalculator getCalculator(Config slaConfig) { Optional<String> time = slaConfig.getOptional("time", String.class); Optional<String> duration = slaConfig.getOptional("duration", String.class); if (time.isPresent() == duration.isPresent()) { throw new ConfigException("SLA must be specified using either the 'time' or 'duration' option"); } String option = time.isPresent() ? "time" : "duration"; String value = time.isPresent() ? time.get() : duration.get(); String[] fragments = value.split(":"); Integer hour; Integer minute; Integer second; try { switch (fragments.length) { case 3: hour = Integer.parseInt(fragments[0]); minute = Integer.parseInt(fragments[1]); second = Integer.parseInt(fragments[2]); break; case 2: hour = Integer.parseInt(fragments[0]); minute = Integer.parseInt(fragments[1]); second = 0; break; default: throw new ConfigException("SLA " + option + " option needs to be HH:MM or HH:MM:SS format: " + time); } } catch (NumberFormatException ex) { throw new ConfigException("SLA " + option + " option needs to be HH:MM or HH:MM:SS format: " + time); } if (time.isPresent()) { return new TimeCalculator(hour, minute, second); } else { return new DurationCalculator(hour, minute, second); } } private interface TriggerCalculator { Instant calculateTime(Instant time, ZoneId timeZone); } private static class TimeCalculator implements TriggerCalculator { private final Integer hour; private final Integer minute; private final Integer second; private TimeCalculator(Integer hour, Integer minute, Integer second) { this.hour = hour; this.minute = minute; this.second = second; } @Override public Instant calculateTime(Instant time, ZoneId timeZone) { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(timeZone), ENGLISH); cal.setTime(Date.from(time)); if (hour != null) { cal.set(Calendar.HOUR_OF_DAY, hour); } if (minute != null) { cal.set(Calendar.MINUTE, minute); } if (second != null) { cal.set(Calendar.SECOND, second); } // if the time is already passed, subtract 1 day // TODO this assumes daily SLA Instant result = cal.getTime().toInstant(); if (result.isBefore(time)) { result = result.plus(1, ChronoUnit.DAYS); } return result; } } private static class DurationCalculator implements TriggerCalculator { private final Integer hour; private final Integer minute; private final Integer second; private DurationCalculator(Integer hour, Integer minute, Integer second) { this.hour = hour; this.minute = minute; this.second = second; } @Override public Instant calculateTime(Instant time, ZoneId timeZone) { Duration duration = Duration.ofHours(hour).plusMinutes(minute).plusSeconds(second); Instant deadline = time.plus(duration); return deadline; } } }
3e13a6fd3325353bd017ffc3f1876ee4fce54d36
1,882
java
Java
CISAdminApi7.0.0/src/com/compositesw/services/system/admin/resource/ResourceAttributesList.java
dvbu-test/PDTool
7582131d101f20cf7c66899963a25dcb2ce67ec7
[ "BSD-3-Clause" ]
null
null
null
CISAdminApi7.0.0/src/com/compositesw/services/system/admin/resource/ResourceAttributesList.java
dvbu-test/PDTool
7582131d101f20cf7c66899963a25dcb2ce67ec7
[ "BSD-3-Clause" ]
null
null
null
CISAdminApi7.0.0/src/com/compositesw/services/system/admin/resource/ResourceAttributesList.java
dvbu-test/PDTool
7582131d101f20cf7c66899963a25dcb2ce67ec7
[ "BSD-3-Clause" ]
null
null
null
27.676471
158
0.648247
8,314
package com.compositesw.services.system.admin.resource; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for resourceAttributesList complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="resourceAttributesList"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" type="{http://www.compositesw.com/services/system/admin/resource}resourceAttributes" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "resourceAttributesList", propOrder = { "entry" }) public class ResourceAttributesList { protected List<ResourceAttributes> entry; /** * Gets the value of the entry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the entry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEntry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ResourceAttributes } * * */ public List<ResourceAttributes> getEntry() { if (entry == null) { entry = new ArrayList<ResourceAttributes>(); } return this.entry; } }
3e13a72bcecd76a7d9d527363ffeb1686e9d9bd0
15,401
java
Java
vertx-cloud/vertx-product/src/main/java/in/gopper/ProductVerticle.java
gopperin/vertx-consul-cloud
4e363f580ade0efc89922be792326b977df20748
[ "Apache-2.0" ]
null
null
null
vertx-cloud/vertx-product/src/main/java/in/gopper/ProductVerticle.java
gopperin/vertx-consul-cloud
4e363f580ade0efc89922be792326b977df20748
[ "Apache-2.0" ]
null
null
null
vertx-cloud/vertx-product/src/main/java/in/gopper/ProductVerticle.java
gopperin/vertx-consul-cloud
4e363f580ade0efc89922be792326b977df20748
[ "Apache-2.0" ]
null
null
null
37.290557
138
0.551977
8,315
package in.gopper; import io.vertx.config.ConfigRetriever; import io.vertx.config.ConfigRetrieverOptions; import io.vertx.config.ConfigStoreOptions; import io.vertx.core.*; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.consul.*; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.client.WebClient; import io.vertx.ext.web.client.WebClientOptions; import io.vertx.ext.web.handler.CorsHandler; import io.vertx.mysqlclient.MySQLConnectOptions; import io.vertx.sqlclient.*; import io.vertx.sqlclient.templates.SqlTemplate; import io.vertx.sqlclient.templates.TupleMapper; import java.security.SecureRandom; import java.util.*; /** * vertx product service * * @author eric */ public class ProductVerticle extends AbstractVerticle { static String verticle_deployId; public static void main(String[] args) { Vertx vertx = Vertx.vertx(new VertxOptions().setWorkerPoolSize(40)); vertx.deployVerticle(new ProductVerticle(), new Handler<AsyncResult<String>>() { @Override public void handle(AsyncResult<String> asyncResult) { if (asyncResult.succeeded()) { // khi startFuture.complete() đc gọi System.out.println("asyncResult = DeployId =" + asyncResult.result()); verticle_deployId = asyncResult.result(); } else { //khi startFuture.fail() đc gọi System.out.println("Deployment failed!"); //vì chưa đc cấp id } } }); } private Pool pool; private WebClient webClient; private String serviceId; private ConsulClient consulClient; // private ServiceDiscovery discovery; private HttpServer server; private SqlTemplate<Map<String, Object>, RowSet<JsonObject>> getProductTmpl; private SqlTemplate<JsonObject, SqlResult<Void>> addProductTmpl; @Override public void start(Promise<Void> startPromise) throws Exception { ConfigStoreOptions file = new ConfigStoreOptions().setType("file").setConfig(new JsonObject().put("path", "application.json")); ConfigRetriever retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions().addStore(file)); retriever.getConfig(conf -> { // setup 数据库 JsonObject dbConfig = conf.result().getJsonObject("datasource"); setUpDatabase(dbConfig); // setup WebClient setUpWebClient(); // 注册为consul服务 String serviceAddress = "127.0.0.1"; Integer servicePort = conf.result().getInteger("port"); JsonObject discoveryConfig = conf.result().getJsonObject("discovery"); setUpConsul(serviceAddress, servicePort, discoveryConfig); // 注册router Handler<RoutingContext> getHealthRoute = ProductVerticle.this::handleGetHealth; Handler<RoutingContext> listUsersRoute = ProductVerticle.this::handleListUsers; Handler<RoutingContext> getProductRoute = ProductVerticle.this::handleGetProduct; Handler<RoutingContext> addProductRoute = ProductVerticle.this::handleAddProduct; Handler<RoutingContext> listProductsRoute = ProductVerticle.this::handleListProducts; Router router = Router.router(vertx); router.route().handler(CorsHandler.create("*").allowedHeaders(allowedHeaders()).allowedMethods(allowedMethods())); router.get("/health").handler(getHealthRoute); router.get("/users").handler(listUsersRoute); router.get("/products/:productID").handler(getProductRoute); router.post("/products").handler(addProductRoute); router.get("/products").handler(listProductsRoute); server = vertx.createHttpServer(); server.requestHandler(router); server.listen(conf.result().getInteger("port"), res -> { if (res.succeeded()) { startPromise.complete(); } else { startPromise.fail(res.cause()); } }); }); } @Override public void stop(Promise<Void> stopPromise) throws Exception { if (null != pool) { pool.close(); System.out.println("Pool succcessfully closed"); } if (null != webClient) { webClient.close(); System.out.println("WebClient succcessfully closed"); } System.out.println("ProductVerticle.stop (async):" + serviceId); consulClient.deregisterService(serviceId, res -> { if (res.succeeded()) { System.out.println("Service successfully deregistered"); } else { System.out.println("Service error deregistered"); res.cause().printStackTrace(); } try { super.stop(stopPromise); } catch (Exception e) { e.printStackTrace(); } }); } private void handleGetHealth(RoutingContext routingContext) { HttpServerResponse response = routingContext.response(); String rep = new JsonObject().put("status", "UP").toString(); response .putHeader("content-type", "application/json") .end(rep); } private void handleListUsers(RoutingContext routingContext) { HttpServerResponse response = routingContext.response(); // 使用descovery获取Record // discovery.getRecord(new JsonObject().put("name", "consul-demo-consumer"), ar1 -> { // // if (ar1.succeeded() && ar1.result() != null) { // System.out.println("=============" + ar1.result()); // // // 以get方式请求远程地址 // webClient.get(ar1.result().getLocation().getInteger("port"), ar1.result().getLocation().getString("host"), "/user/list") // .putHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0") // .addQueryParam("username", "admin") // .send(handle -> { // // 处理响应的结果 // if (handle.succeeded()) { // // 这里拿到的结果就是一个HTML文本,直接打印出来 // String body = handle.result().bodyAsString(); // System.out.println(body); // response // .putHeader("content-type", "application/json") // .end(body); // } // }); // } // }); //use consul client get services consulClient.healthServiceNodes("consul-demo-consumer", true, res -> { if (res.succeeded()) { System.out.println("found " + res.result().getList().size() + " services"); System.out.println("consul state index: " + res.result().getIndex()); List<ServiceEntry> lsService = res.result().getList(); if (null == lsService || 0 == lsService.size()) { String rep = new JsonObject().put("status", "UP").toString(); response .putHeader("content-type", "application/json") .end(rep); return; } Random random = new SecureRandom(); int n = random.nextInt(lsService.size()); ServiceEntry entry = lsService.get(n); if (null == entry) { String rep = new JsonObject().put("status", "UP").toString(); response .putHeader("content-type", "application/json") .end(rep); return; } System.out.println("Service node: " + entry.getNode()); System.out.println("Service address: " + entry.getService().getAddress()); System.out.println("Service port: " + entry.getService().getPort()); // 以get方式请求远程地址 webClient.get(entry.getService().getPort(), entry.getService().getAddress(), "/user/list") .putHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0") .addQueryParam("username", "admin") .send(handle -> { // 处理响应的结果 if (handle.succeeded()) { // 这里拿到的结果就是一个HTML文本,直接打印出来 String body = handle.result().bodyAsString(); System.out.println(body); response .putHeader("content-type", "application/json") .end(body); } }); } else { String rep = new JsonObject().put("status", "UP").toString(); response .putHeader("content-type", "application/json") .write(rep); response.end(); } }); } private void handleGetProduct(RoutingContext routingContext) { String productID = routingContext.request().getParam("productID"); HttpServerResponse response = routingContext.response(); if (productID == null) { routingContext.fail(400); } else { getProductTmpl .execute(Collections.singletonMap("id", productID)) .onSuccess(result -> { if (result.size() == 0) { routingContext.fail(404); } else { response .putHeader("content-type", "application/json") .end(result.iterator().next().encode()); } }).onFailure(err -> { routingContext.fail(500); }); } } private void handleAddProduct(RoutingContext routingContext) { HttpServerResponse response = routingContext.response(); JsonObject product = routingContext.getBodyAsJson(); addProductTmpl.execute(product) .onSuccess(res -> response.end()) .onFailure(err -> routingContext.fail(500)); } private void handleListProducts(RoutingContext routingContext) { HttpServerResponse response = routingContext.response(); pool.query("SELECT id, nick_name, price, weight FROM products limit 0,10").execute(query -> { if (query.failed()) { routingContext.fail(500); } else { JsonArray arr = new JsonArray(); query.result().forEach(row -> { arr.add(row.toJson()); }); routingContext.response().putHeader("content-type", "application/json").end(arr.encode()); } }); } /** * setUp database * * @param dbConfig */ private void setUpDatabase(JsonObject dbConfig) { MySQLConnectOptions options = new MySQLConnectOptions() .setPort(dbConfig.getInteger("port")) .setHost(dbConfig.getString("host")) .setDatabase(dbConfig.getString("db_name")) .setUser(dbConfig.getString("user")) .setPassword(dbConfig.getString("password")); pool = Pool.pool(vertx, options, new PoolOptions().setMaxSize(4)); getProductTmpl = SqlTemplate .forQuery(pool, "SELECT id, nick_name, price, weight FROM products where id = #{id} LIMIT 1") .mapTo(Row::toJson); addProductTmpl = SqlTemplate .forUpdate(pool, "INSERT INTO products (nick_name, price, weight) VALUES (#{name}, #{price}, #{weight})") .mapFrom(TupleMapper.jsonObject()); } /** * setUp consul 服务 * * @param serviceAddress * @param servicePort * @param discoveryConfig */ private void setUpConsul(String serviceAddress, Integer servicePort, JsonObject discoveryConfig) { serviceId = discoveryConfig.getString("serviceId"); ConsulClientOptions optConsul = new ConsulClientOptions() .setHost(discoveryConfig.getString("host")) .setPort(discoveryConfig.getInteger("port")); consulClient = ConsulClient.create(vertx, optConsul); CheckOptions optsCheck = new CheckOptions() .setHttp(discoveryConfig.getString("health")) .setInterval("5s"); ServiceOptions opts = new ServiceOptions() .setName(discoveryConfig.getString("serviceName")) .setId(serviceId) .setTags(Arrays.asList("tag", "port" + servicePort)) .setCheckOptions(optsCheck) .setAddress(serviceAddress) .setPort(servicePort); consulClient.registerService(opts, res -> { if (res.succeeded()) { System.out.println("VertxService successfully registered:" + serviceId); } else { res.cause().printStackTrace(); } }); // 使用discovery机制 // discovery = ServiceDiscovery.create(vertx); // discovery.registerServiceImporter(new ConsulServiceImporter(), // new JsonObject() // .put("host", "localhost") // .put("port", 8500) // .put("scan-period", 2000)); } /** * setUp WebClient */ private void setUpWebClient() { // 创建WebClient,用于发送HTTP或者HTTPS请求,ms WebClientOptions webClientOptions = new WebClientOptions() .setConnectTimeout(5000); webClient = WebClient.create(vertx, webClientOptions); } /** * cors allowed headers * * @return */ private Set<String> allowedHeaders() { Set<String> allowedHeaders = new HashSet<>(); allowedHeaders.add("x-requested-with"); allowedHeaders.add("Access-Control-Allow-Origin"); allowedHeaders.add("origin"); allowedHeaders.add("Content-Type"); allowedHeaders.add("accept"); allowedHeaders.add("X-PINGARUNER"); return allowedHeaders; } /** * cors allowed methods * * @return */ private Set<HttpMethod> allowedMethods() { Set<HttpMethod> allowedMethods = new HashSet<>(); allowedMethods.add(HttpMethod.GET); allowedMethods.add(HttpMethod.POST); allowedMethods.add(HttpMethod.OPTIONS); allowedMethods.add(HttpMethod.DELETE); allowedMethods.add(HttpMethod.PATCH); allowedMethods.add(HttpMethod.PUT); return allowedMethods; } }
3e13a776eaed01e2c7c2305436d69ffb1d26df40
3,031
java
Java
src/main/java/miage/skillz/service/CompetenceService.java
GBerenice98/skillZ
bc467b071028ba627fc0791c5e8e86d4cdea8f61
[ "Apache-2.0" ]
null
null
null
src/main/java/miage/skillz/service/CompetenceService.java
GBerenice98/skillZ
bc467b071028ba627fc0791c5e8e86d4cdea8f61
[ "Apache-2.0" ]
null
null
null
src/main/java/miage/skillz/service/CompetenceService.java
GBerenice98/skillZ
bc467b071028ba627fc0791c5e8e86d4cdea8f61
[ "Apache-2.0" ]
null
null
null
30.31
97
0.674035
8,316
package miage.skillz.service; import miage.skillz.repository.CompetenceRepository; import miage.skillz.entity.Competence; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.*; @Service public class CompetenceService { @Autowired CompetenceRepository competenceRepository; // Créer une competence avec un id père public ResponseEntity<Competence> createCompetence(Competence competence) { Competence comp = new Competence(competence.getNom_competence(),competence.getIdPere()); return new ResponseEntity<>(this.competenceRepository.saveAndFlush(comp), HttpStatus.OK); } // Modifier une competence public ResponseEntity<Competence> updateCompetence(Competence comp) { System.out.println("Competence à modifier : " + comp); Optional<Competence> comUpadate = this.competenceRepository.findById(comp.getId()); if(comUpadate.isPresent()) { Competence com = comUpadate.get(); com.setNom_competence(comp.getNom_competence()); com.setIdPere(comp.getIdPere()); System.out.println("Competence trouvé!" + com); return new ResponseEntity<>(this.competenceRepository.saveAndFlush(com),HttpStatus.OK); } else { System.out.println("Error competence pas trouvé!"); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } // Supprimer competence public void deleteCompetence(Long competenceId) { //System.out.println("delete : "+competenceRepository.findById(competenceId).toString()); competenceRepository.deleteById(competenceId); } // Retourne la liste des competences public List<Competence> getAllCompetence() { return competenceRepository.findAll(); } // Compétence by ID public Competence getCompetenceById(Long competenceId) { return this.competenceRepository.findById(competenceId).orElse(null); } // Liste competence by Id père public List<Competence> getCompetenceByIdPere(Long IdPere){ List<Competence> comptences= this.getAllCompetence(); List<Competence> newList= new ArrayList<>(); for (Competence competence : comptences) { long idComp = competence.getIdPere(); if(idComp == IdPere){ newList.add(competence); } } return newList; } public List<Competence> getTreeCompetences () { List<Competence> listComp = this.getAllCompetence(); HashMap<String, Long> listCompetences = new HashMap<>(); for (Competence competence : listComp) { long IdPere = competence.getIdPere(); if(IdPere == 0){ listCompetences.put(competence.getNom_competence(), competence.getIdPere()); } } return listComp; } }
3e13a84d5a3c94c21c7a1309e1e432392f3234de
485
java
Java
src/main/java/com/github/skanukov/reason/core/lang/FileUtils.java
skanukov/reason
99104c947c85ca195cbeb8695e3a35845da28cd9
[ "MIT" ]
null
null
null
src/main/java/com/github/skanukov/reason/core/lang/FileUtils.java
skanukov/reason
99104c947c85ca195cbeb8695e3a35845da28cd9
[ "MIT" ]
null
null
null
src/main/java/com/github/skanukov/reason/core/lang/FileUtils.java
skanukov/reason
99104c947c85ca195cbeb8695e3a35845da28cd9
[ "MIT" ]
null
null
null
26.944444
87
0.750515
8,317
package com.github.skanukov.reason.core.lang; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * Helpers for file handling. */ public final class FileUtils { public static String readAllText(String path) throws IOException { Path settingFilePath = Paths.get(path); return new String(Files.readAllBytes(settingFilePath), StandardCharsets.UTF_8); } }
3e13a8d9481516b7c74feb3fac5be4f684af383f
3,957
java
Java
shadows/framework/src/main/java/org/robolectric/shadows/ShadowMediaController.java
LitterSun/robolectric
caf85b0debc60fbcc03dadebbe115371f4d290bf
[ "Apache-2.0" ]
1
2020-01-30T12:26:08.000Z
2020-01-30T12:26:08.000Z
shadows/framework/src/main/java/org/robolectric/shadows/ShadowMediaController.java
LitterSun/robolectric
caf85b0debc60fbcc03dadebbe115371f4d290bf
[ "Apache-2.0" ]
1
2021-02-02T17:51:20.000Z
2021-02-02T17:51:20.000Z
shadows/framework/src/main/java/org/robolectric/shadows/ShadowMediaController.java
LitterSun/robolectric
caf85b0debc60fbcc03dadebbe115371f4d290bf
[ "Apache-2.0" ]
1
2021-05-05T23:51:50.000Z
2021-05-05T23:51:50.000Z
34.710526
99
0.760677
8,318
package org.robolectric.shadows; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static org.robolectric.shadow.api.Shadow.directlyOn; import android.annotation.NonNull; import android.media.MediaMetadata; import android.media.session.MediaController; import android.media.session.MediaController.Callback; import android.media.session.PlaybackState; import android.os.Bundle; import java.util.ArrayList; import java.util.List; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.ReflectionHelpers.ClassParameter; /** * Implementation of {@link android.media.session.MediaController}. */ @Implements(value = MediaController.class, minSdk = LOLLIPOP) public class ShadowMediaController { @RealObject private MediaController realMediaController; private PlaybackState playbackState; private MediaMetadata mediaMetadata; private final List<Callback> callbacks = new ArrayList<>(); /** Saves the package name for use inside the shadow. */ public void setPackageName(String packageName) { ReflectionHelpers.setField(realMediaController, "mPackageName", packageName); } /** * Saves the playbackState to control the return value of {@link * MediaController#getPlaybackState()}. */ public void setPlaybackState(PlaybackState playbackState) { this.playbackState = playbackState; } /** Gets the playbackState set via {@link #setPlaybackState}. */ @Implementation protected PlaybackState getPlaybackState() { return playbackState; } /** * Saves the mediaMetadata to control the return value of {@link MediaController#getMetadata()}. */ public void setMetadata(MediaMetadata mediaMetadata) { this.mediaMetadata = mediaMetadata; } /** Gets the mediaMetadata set via {@link #setMetadata}. */ @Implementation protected MediaMetadata getMetadata() { return mediaMetadata; } /** * Register callback and store it in the shadow to make it easier to check the state of the * registered callbacks. */ @Implementation protected void registerCallback(@NonNull Callback callback) { callbacks.add(callback); directlyOn(realMediaController, MediaController.class).registerCallback(callback); } /** * Unregister callback and remove it from the shadow to make it easier to check the state of the * registered callbacks. */ @Implementation protected void unregisterCallback(@NonNull Callback callback) { callbacks.remove(callback); directlyOn(realMediaController, MediaController.class).unregisterCallback(callback); } /** Gets the callbacks registered to MediaController. */ public List<Callback> getCallbacks() { return callbacks; } /** Executes all registered onPlaybackStateChanged callbacks. */ public void executeOnPlaybackStateChanged(PlaybackState playbackState) { setPlaybackState(playbackState); int messageId = ReflectionHelpers.getStaticField(MediaController.class, "MSG_UPDATE_PLAYBACK_STATE"); ReflectionHelpers.callInstanceMethod(MediaController.class, realMediaController, "postMessage", ClassParameter.from(int.class, messageId), ClassParameter.from(Object.class, playbackState), ClassParameter.from(Bundle.class, new Bundle())); } /** Executes all registered onMetadataChanged callbacks. */ public void executeOnMetadataChanged(MediaMetadata metadata) { setMetadata(metadata); int messageId = ReflectionHelpers.getStaticField(MediaController.class, "MSG_UPDATE_METADATA"); ReflectionHelpers.callInstanceMethod( MediaController.class, realMediaController, "postMessage", ClassParameter.from(int.class, messageId), ClassParameter.from(Object.class, metadata), ClassParameter.from(Bundle.class, new Bundle())); } }
3e13a97106b4280a0bf0f44540fe0d7661e7668f
241
java
Java
src/main/java/io/vukotic/flightadvisor/error/exception/CityAndCountryAlreadyExistException.java
nkzd/cheap-flights-api
c3f5519f8283988d941a533a8b9c451bc58c7a9e
[ "MIT" ]
null
null
null
src/main/java/io/vukotic/flightadvisor/error/exception/CityAndCountryAlreadyExistException.java
nkzd/cheap-flights-api
c3f5519f8283988d941a533a8b9c451bc58c7a9e
[ "MIT" ]
null
null
null
src/main/java/io/vukotic/flightadvisor/error/exception/CityAndCountryAlreadyExistException.java
nkzd/cheap-flights-api
c3f5519f8283988d941a533a8b9c451bc58c7a9e
[ "MIT" ]
null
null
null
26.777778
75
0.780083
8,319
package io.vukotic.flightadvisor.error.exception; public class CityAndCountryAlreadyExistException extends RuntimeException { public CityAndCountryAlreadyExistException() { super("City in this country already exists"); } }
3e13aa4730eead739c6c9027c8af3b08e41481e8
1,257
java
Java
src/main/java/com/devteam/module/company/service/config/CompanyHRModuleConfig.java
ddthien-coder/iTraining
3210412ac5b6fd3e5017519086503a92b68cce16
[ "MIT" ]
1
2021-12-18T17:06:15.000Z
2021-12-18T17:06:15.000Z
src/main/java/com/devteam/module/company/service/config/CompanyHRModuleConfig.java
ddthien-coder/iTraining
3210412ac5b6fd3e5017519086503a92b68cce16
[ "MIT" ]
1
2022-02-15T03:24:45.000Z
2022-02-15T03:24:45.000Z
src/main/java/com/devteam/module/company/service/config/CompanyHRModuleConfig.java
ddthien-coder/iTraining
3210412ac5b6fd3e5017519086503a92b68cce16
[ "MIT" ]
1
2021-12-18T17:06:00.000Z
2021-12-18T17:06:00.000Z
34.916667
81
0.834527
8,320
package com.devteam.module.company.service.config; import com.devteam.core.module.data.db.repository.BaseRepositoryFactoryBean; import com.devteam.core.module.srpingframework.config.ModuleConfig; import com.devteam.module.account.config.AccountModuleConfig; import com.devteam.module.company.core.config.CompanyModuleConfig; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.transaction.annotation.EnableTransactionManagement; @ModuleConfig( basePackages= { "com.devteam.module.company.service.hr", } ) @Configuration @ComponentScan( basePackages = { "com.devteam.module.company.service.hr" } ) @EnableJpaRepositories( basePackages = { "com.devteam.module.company.service.hr.repository", }, repositoryFactoryBeanClass = BaseRepositoryFactoryBean.class ) @Import({AccountModuleConfig.class, CompanyModuleConfig.class}) @EnableConfigurationProperties @EnableTransactionManagement public class CompanyHRModuleConfig { }
3e13aa815cf65db55977b177e0aacff157b6889b
1,871
java
Java
src/main/java/com/microsoft/graph/requests/extensions/IInferenceClassificationRequestBuilder.java
ashwanikumar04/msgraph-sdk-java
9ed8de320a7b1af7792ba24e0fa0cd010c4e1100
[ "MIT" ]
1
2021-05-17T07:56:01.000Z
2021-05-17T07:56:01.000Z
src/main/java/com/microsoft/graph/requests/extensions/IInferenceClassificationRequestBuilder.java
ashwanikumar04/msgraph-sdk-java
9ed8de320a7b1af7792ba24e0fa0cd010c4e1100
[ "MIT" ]
21
2021-02-01T08:37:29.000Z
2022-03-02T11:07:27.000Z
src/main/java/com/microsoft/graph/requests/extensions/IInferenceClassificationRequestBuilder.java
ashwanikumar04/msgraph-sdk-java
9ed8de320a7b1af7792ba24e0fa0cd010c4e1100
[ "MIT" ]
null
null
null
43.511628
152
0.729556
8,321
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.models.extensions.InferenceClassification; import com.microsoft.graph.requests.extensions.IInferenceClassificationOverrideCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IInferenceClassificationOverrideRequestBuilder; import java.util.Arrays; import java.util.EnumSet; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The interface for the Inference Classification Request Builder. */ public interface IInferenceClassificationRequestBuilder extends IRequestBuilder { /** * Creates the request * * @param requestOptions the options for this request * @return the IInferenceClassificationRequest instance */ IInferenceClassificationRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions); /** * Creates the request with specific options instead of the existing options * * @param requestOptions the options for this request * @return the IInferenceClassificationRequest instance */ IInferenceClassificationRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions); IInferenceClassificationOverrideCollectionRequestBuilder overrides(); IInferenceClassificationOverrideRequestBuilder overrides(final String id); }
3e13ab1fa9c4ff11dfeb643df8d432864f9196ec
3,908
java
Java
hazelcast-hibernate/hazelcast-hibernate4/src/test/java/com/hazelcast/hibernate/serialization/ExpiryMarkerTest.java
asimarslan/hazelcast
de1d731fc6c2cae255a4f00ee30fc5b0f177b66e
[ "Apache-2.0" ]
1
2015-07-27T11:50:58.000Z
2015-07-27T11:50:58.000Z
hazelcast-hibernate/hazelcast-hibernate4/src/test/java/com/hazelcast/hibernate/serialization/ExpiryMarkerTest.java
asimarslan/hazelcast
de1d731fc6c2cae255a4f00ee30fc5b0f177b66e
[ "Apache-2.0" ]
5
2020-02-28T01:19:10.000Z
2021-06-04T01:14:27.000Z
hazelcast-hibernate/hazelcast-hibernate4/src/test/java/com/hazelcast/hibernate/serialization/ExpiryMarkerTest.java
asimarslan/hazelcast
de1d731fc6c2cae255a4f00ee30fc5b0f177b66e
[ "Apache-2.0" ]
null
null
null
44.91954
116
0.717758
8,322
package com.hazelcast.hibernate.serialization; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.hibernate.internal.util.compare.ComparableComparator; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import static org.junit.Assert.*; @RunWith(HazelcastSerialClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class ExpiryMarkerTest { @Test public void testIsReplaceableByTimestampBeforeTimeout() throws Exception { ExpiryMarker marker = new ExpiryMarker(null, 100L, "the-marker-id"); assertFalse("marker is not replaceable when it hasn't timed out", marker.isReplaceableBy(99L, null, null)); } @Test public void testIsReplaceableByTimestampEqualTimeout() throws Exception { ExpiryMarker marker = new ExpiryMarker(null, 100L, "the-marker-id"); assertFalse("marker is not replaceable when it hasn't timed out", marker.isReplaceableBy(100L, null, null)); } @Test public void testIsReplaceableByTimestampAfterTimeout() throws Exception { ExpiryMarker marker = new ExpiryMarker(null, 100L, "the-marker-id"); assertTrue("marker is replaceable when it has timed out", marker.isReplaceableBy(101L, null, null)); } @Test public void testIsReplaceableByTimestampBeforeExpiredTimestamp() throws Exception { ExpiryMarker marker = new ExpiryMarker(null, 150L, "the-marker-id").expire(100L); assertFalse("marker is not replaceable when it when timestamp before expiry", marker.isReplaceableBy(99L, null, null)); } @Test public void testIsReplaceableByTimestampEqualExpiredTimestamp() throws Exception { ExpiryMarker marker = new ExpiryMarker(null, 150L, "the-marker-id").expire(100L); assertFalse("marker is not replaceable when it when timestamp equal to expiry", marker.isReplaceableBy(100L, null, null)); } @Test public void testIsReplaceableByTimestampAfterExpiredTimestamp() throws Exception { ExpiryMarker marker = new ExpiryMarker(null, 150L, "the-marker-id").expire(100L); assertTrue("marker is replaceable when it when timestamp after expiry", marker.isReplaceableBy(101L, null, null)); } @Test public void testIsReplaceableByVersionBefore() throws Exception { ExpiryMarker marker = new ExpiryMarker(10, 150L, "the-marker-id").expire(100L); assertFalse("marker is replaceable when it when version before", marker.isReplaceableBy(101L, 9, ComparableComparator.INSTANCE)); } @Test public void testIsReplaceableByVersionEqual() throws Exception { ExpiryMarker marker = new ExpiryMarker(10, 150L, "the-marker-id").expire(100L); assertFalse("marker is replaceable when it when version equal", marker.isReplaceableBy(101L, 10, ComparableComparator.INSTANCE)); } @Test public void testIsReplaceableByVersionAfter() throws Exception { ExpiryMarker marker = new ExpiryMarker(10, 150L, "the-marker-id").expire(100L); assertTrue("marker is replaceable when it when version after", marker.isReplaceableBy(99L, 11, ComparableComparator.INSTANCE)); } @Test public void testMatchesOnlyUsesMarkerId() throws Exception { ExpiryMarker marker = new ExpiryMarker(10, 150L, "the-marker-id"); assertTrue(marker.matches(marker)); assertTrue(marker.matches(marker.expire(100))); assertTrue(marker.matches(marker.markForExpiration(100L, "some-other-marker-id"))); assertTrue(marker.matches(new ExpiryMarker(9, 100L, "the-marker-id"))); assertFalse(marker.matches(new ExpiryMarker(10, 150L, "some-other-marker-id"))); } }
3e13ab27a607b0a30443ba8363b949ed81ae6367
295
java
Java
JAVA_LAB/LAB_MAN3/P1.java
AmanSarraf/JAVA
a562b30a3ae5d0d4eb23eb7ea281e57dfce83f1c
[ "MIT" ]
null
null
null
JAVA_LAB/LAB_MAN3/P1.java
AmanSarraf/JAVA
a562b30a3ae5d0d4eb23eb7ea281e57dfce83f1c
[ "MIT" ]
null
null
null
JAVA_LAB/LAB_MAN3/P1.java
AmanSarraf/JAVA
a562b30a3ae5d0d4eb23eb7ea281e57dfce83f1c
[ "MIT" ]
null
null
null
21.071429
88
0.620339
8,323
//Program2: WAP in which you declare a character type variable. Assign it a certain char //type value and the post increment it and print its value. public class P1 { public static void main(String arg[]) { char x= 'A'; x = x++; System.out.println(x); } }
3e13ab31de6f3ff8c3a326a02995f72d28e49f93
1,453
java
Java
components/oneapi-validation/src/main/java/com/wso2telco/dep/oneapivalidation/exceptions/ResponseError.java
MilindaLaknath/component-dep
bb1f2ce8ec18e94f3ed2797a3b1983623d98f987
[ "Apache-2.0" ]
3
2017-11-01T20:14:40.000Z
2021-03-23T08:11:08.000Z
components/oneapi-validation/src/main/java/com/wso2telco/dep/oneapivalidation/exceptions/ResponseError.java
MilindaLaknath/component-dep
bb1f2ce8ec18e94f3ed2797a3b1983623d98f987
[ "Apache-2.0" ]
101
2016-11-24T04:21:56.000Z
2022-01-21T23:19:25.000Z
components/oneapi-validation/src/main/java/com/wso2telco/dep/oneapivalidation/exceptions/ResponseError.java
MilindaLaknath/component-dep
bb1f2ce8ec18e94f3ed2797a3b1983623d98f987
[ "Apache-2.0" ]
135
2016-11-23T07:23:20.000Z
2020-12-08T13:36:02.000Z
32.288889
100
0.613902
8,324
/******************************************************************************* * Copyright (c) 2015-2016, WSO2.Telco Inc. (http://www.wso2telco.com) All Rights Reserved. * * WSO2.Telco Inc. licences 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 com.wso2telco.dep.oneapivalidation.exceptions; // TODO: Auto-generated Javadoc /** * The Class ResponseError. */ public class ResponseError { /** The request error. */ private RequestError requestError; /** * Gets the request error. * * @return the request error */ public RequestError getRequestError() { return requestError; } /** * Sets the request error. * * @param requestError the new request error */ public void setRequestError(RequestError requestError) { this.requestError = requestError; } }
3e13abcbb23c05c0276ca961c2142aa382b9e231
12,823
java
Java
molten-core/src/main/java/com/hotels/molten/core/collapser/RequestCollapser.java
szjani/molten
5809b64cdc1fcaec7ef468561702be2320299882
[ "Apache-2.0" ]
12
2020-12-14T17:21:16.000Z
2022-03-25T13:12:12.000Z
molten-core/src/main/java/com/hotels/molten/core/collapser/RequestCollapser.java
szjani/molten
5809b64cdc1fcaec7ef468561702be2320299882
[ "Apache-2.0" ]
110
2020-12-16T15:37:44.000Z
2022-03-28T08:06:37.000Z
molten-core/src/main/java/com/hotels/molten/core/collapser/RequestCollapser.java
szjani/molten
5809b64cdc1fcaec7ef468561702be2320299882
[ "Apache-2.0" ]
6
2020-12-15T07:22:33.000Z
2022-02-08T00:38:20.000Z
41.498382
174
0.661624
8,325
/* * Copyright (c) 2020 Expedia, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hotels.molten.core.collapser; import static com.google.common.base.Preconditions.checkArgument; import static java.time.temporal.ChronoUnit.SECONDS; import static java.util.Objects.requireNonNull; import java.time.Duration; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import io.micrometer.core.instrument.DistributionSummary; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; import com.hotels.molten.core.MoltenCore; import com.hotels.molten.core.metrics.MetricId; /** * A request collapser implementation over functions returning reactive types. * <br> * <img src="doc-files/request_collapser_ttl.png" alt="Request collapser sequence diagram"> * <br> * The wrapped function has the following characteristics: * <ul> * <li>The first call to a specific context will be delegated and cached.</li> * <li>Each subsequent invocations to same context will get the cached one (with single subscription, see {@link Mono#cache()}.</li> * <li>Once the first call emits any event (success, completed, error) that is propagated to each subsequent subscriber with same context.</li> * <li>By default the requests are stored for 10 seconds and last 1000 unique contexts.</li> * </ul> * Please note that calls are cached by {@code context} so it should have proper {@code hashCode} and {@code equals} implementation. * If you need more fine-grained configuration please use the {@link #builder(Function)}. * <p> * When {@link MeterRegistry} is set with {@link Builder#withMetrics(MeterRegistry, MetricId)} then registers the following metrics: * <ul> * <li>{@code [qualifier].pending} - histogram for number of on-going collapsed request</li> * <li>{@code [qualifier].pending.current} - gauge for number on-going collapsed request</li> * </ul> * <h3>Retrying collapsed calls</h3> * Be sure not to {@link Mono#retry()} collapsed invocation as it will always be the same (up to TTL). * If you set {@link Builder#releaseWhenFinished()} then you can retry if you wrap collapsed invocation in a {@link Mono#defer(java.util.function.Supplier)}. * <h3>Timeout</h3> * One can set {@link Builder#timeOutIn(Duration)} to add a timeout to each collapsed call to avoid being stuck if downstream never completes. * * @param <CONTEXT> the context type * @param <VALUE> the value type */ @Slf4j public final class RequestCollapser<CONTEXT, VALUE> implements Function<CONTEXT, Mono<VALUE>> { private final Map<CONTEXT, Mono<VALUE>> onGoingCallsStore; private final Function<CONTEXT, Mono<VALUE>> valueProvider; private final Scheduler scheduler; private final boolean releaseWhenFinished; private final AtomicInteger pendingItemCounter = new AtomicInteger(); private final Duration timeOut; private final Scheduler timeOutScheduler; private DistributionSummary pendingItemsHistogram; private RequestCollapser(Builder<CONTEXT, VALUE> builder) { this.onGoingCallsStore = getOnGoingCallsStore(builder); valueProvider = requireNonNull(builder.valueProvider); scheduler = requireNonNull(builder.scheduler); releaseWhenFinished = builder.releaseWhenFinished; timeOut = builder.timeOut; timeOutScheduler = builder.timeOutScheduler; if (builder.meterRegistry != null) { pendingItemsHistogram = builder.metricId.extendWith("pending_count", "pending") .toDistributionSummary() .description("Number of pending items") .register(builder.meterRegistry); builder.metricId.extendWith("pending_current_count", "pending.current") .toGauge(pendingItemCounter, AtomicInteger::get) .register(builder.meterRegistry); } } @Override public Mono<VALUE> apply(CONTEXT context) { LOG.debug("Collapsing context={}", context); if (pendingItemsHistogram != null) { pendingItemsHistogram.record(pendingItemCounter.incrementAndGet()); } Mono<VALUE> valueMono = onGoingCallsStore.computeIfAbsent(context, this::promiseOf); if (pendingItemsHistogram != null) { valueMono = valueMono.doFinally(i -> pendingItemsHistogram.record(pendingItemCounter.decrementAndGet())); } return valueMono .transform(MoltenCore.propagateContext()); } /** * Creates a {@link RequestCollapser} builder over a value provider. * * @param valueProvider the value provider to collapse calls over * @param <C> the context type * @param <V> the value type * @return the builder */ public static <C, V> Builder<C, V> builder(Function<C, Mono<V>> valueProvider) { return new Builder<>(valueProvider); } /** * Wraps existing provider with one that collapses similar calls. * Uses default configuration of 10 seconds collapse window and 1000 unique calls tracked. * If you need more fine-grained configuration please use {@link #builder(Function)}. * * @param valueProvider the {@link Mono} provider * @param <C> the context type * @param <V> the value type * @return the enhanced provider method */ public static <C, V> RequestCollapser<C, V> collapseCallsOn(Function<C, Mono<V>> valueProvider) { return RequestCollapser.builder(valueProvider).build(); } /** * Gets the current number of on-going calls. * * @return the number of calls */ int getNumberOfOnGoingCalls() { return onGoingCallsStore.size(); } private Map<CONTEXT, Mono<VALUE>> getOnGoingCallsStore(Builder<CONTEXT, VALUE> builder) { Map<CONTEXT, Mono<VALUE>> onGoingCallsStore = builder.onGoingCallsStore; if (onGoingCallsStore == null) { Cache<CONTEXT, Mono<VALUE>> cache = Caffeine.newBuilder() .maximumSize(builder.maxCollapsedCalls) .expireAfterWrite(builder.maxCollapsedTime.toMillis(), TimeUnit.MILLISECONDS) .build(); onGoingCallsStore = cache.asMap(); } return onGoingCallsStore; } private Mono<VALUE> promiseOf(CONTEXT context) { LOG.debug("New collapser for context={}", context); Mono<VALUE> promise; if (releaseWhenFinished) { promise = valueProvider.apply(context) .doFinally(i -> { LOG.debug("Releasing context={}", context); onGoingCallsStore.remove(context); }) .cache() .publishOn(scheduler); } else { promise = valueProvider.apply(context) .cache() .publishOn(scheduler); } if (timeOut != null) { promise = promise.timeout(timeOut, timeOutScheduler); } return promise; } /** * Builder for {@link RequestCollapser}. * * @param <CONTEXT> the context type * @param <VALUE> the value type */ public static final class Builder<CONTEXT, VALUE> { private final Function<CONTEXT, Mono<VALUE>> valueProvider; private Map<CONTEXT, Mono<VALUE>> onGoingCallsStore; private Scheduler scheduler = Schedulers.parallel(); private boolean releaseWhenFinished; private int maxCollapsedCalls = 1000; private Duration maxCollapsedTime = Duration.of(10, SECONDS); private MeterRegistry meterRegistry; private MetricId metricId; private Duration timeOut; private Scheduler timeOutScheduler = Schedulers.parallel(); private Builder(Function<CONTEXT, Mono<VALUE>> valueProvider) { this.valueProvider = requireNonNull(valueProvider); } /** * Sets the scheduler to emit data with. Defaults to {@link Schedulers#parallel()}. * * @param scheduler the scheduler * @return this builder instance */ public Builder<CONTEXT, VALUE> withScheduler(Scheduler scheduler) { this.scheduler = requireNonNull(scheduler); return this; } /** * Sets the maximum number of unique collapsed calls to track at once. * Defaults to 1000 unique elements. * * @param maxCollapsedCalls the maximum number of collapsed calls * @return this builder instance */ public Builder<CONTEXT, VALUE> withMaxCollapsedCalls(int maxCollapsedCalls) { checkArgument(maxCollapsedCalls > 0, "maxCollapsedCalls must be positive"); this.maxCollapsedCalls = maxCollapsedCalls; return this; } /** * Sets the maximum timeframe to collapse similar calls after the initial request. * Defaults to 10 seconds. * * @param maxCollapsedTime the maximum timeframe * @return this builder instance */ public Builder<CONTEXT, VALUE> withMaxCollapsedTime(Duration maxCollapsedTime) { this.maxCollapsedTime = requireNonNull(maxCollapsedTime); return this; } /** * Sets the store for ongoing calls. Usually it is safer to use a cache with TTL to avoid potential leak. * Ignores {@link #withMaxCollapsedCalls(int)} and {@link #withMaxCollapsedTime(Duration)} when set. * * @param onGoingCallsStore the store for ongoing calls. * @return this builder instance */ public Builder<CONTEXT, VALUE> withOnGoingCallsStore(Map<CONTEXT, Mono<VALUE>> onGoingCallsStore) { this.onGoingCallsStore = requireNonNull(onGoingCallsStore); return this; } /** * Sets whether to release collapsed calls as soon as they are complete. * <br> * <img src="doc-files/request_collapser_release.png" alt="Request collapser release when finished sequence diagram"> * * @return this builder instance */ public Builder<CONTEXT, VALUE> releaseWhenFinished() { releaseWhenFinished = true; return this; } /** * Sets whether to add an extra safety by adding timeout to delegated calls. This is a safety net if the collapsed function is not behaving nicely and never complete. * * @param timeOut the timeout to maximum wait for execution * @return this builder instance */ public Builder<CONTEXT, VALUE> timeOutIn(Duration timeOut) { this.timeOut = requireNonNull(timeOut); return this; } /** * Sets the scheduler to be used for timeouts. Defaults to parallel. * * @param timeOutScheduler the scheduler * @return this builder instance */ Builder<CONTEXT, VALUE> withTimeOutScheduler(Scheduler timeOutScheduler) { this.timeOutScheduler = requireNonNull(timeOutScheduler); return this; } /** * Sets the meter registry and metric ID base to record statistics with. * * @param meterRegistry the registry to register metrics with * @param metricId the metric id under which metrics should be registered * @return this builder instance */ public Builder<CONTEXT, VALUE> withMetrics(MeterRegistry meterRegistry, MetricId metricId) { this.meterRegistry = requireNonNull(meterRegistry); this.metricId = requireNonNull(metricId); return this; } /** * Builds the {@link RequestCollapser} instance based on this builder. * * @return the {@link RequestCollapser} instance */ public RequestCollapser<CONTEXT, VALUE> build() { return new RequestCollapser<>(this); } } }
3e13ac07db20a772df7c9ca6eb6f5cbe66fb149e
11,093
java
Java
src/test/java/uk/gov/companieshouse/web/accounts/controller/smallfull/DebtorsControllerTest.java
companieshouse/company-accounts.web.ch.gov.uk
908098ded5647672a2507254e73365050556ac81
[ "MIT" ]
1
2020-01-28T11:28:16.000Z
2020-01-28T11:28:16.000Z
src/test/java/uk/gov/companieshouse/web/accounts/controller/smallfull/DebtorsControllerTest.java
companieshouse/company-accounts.web.ch.gov.uk
908098ded5647672a2507254e73365050556ac81
[ "MIT" ]
100
2018-08-02T13:39:31.000Z
2021-12-21T16:36:11.000Z
src/test/java/uk/gov/companieshouse/web/accounts/controller/smallfull/DebtorsControllerTest.java
companieshouse/company-accounts.web.ch.gov.uk
908098ded5647672a2507254e73365050556ac81
[ "MIT" ]
1
2021-04-10T21:10:05.000Z
2021-04-10T21:10:05.000Z
41.391791
151
0.754169
8,326
package uk.gov.companieshouse.web.accounts.controller.smallfull; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.servlet.view.UrlBasedViewResolver; import uk.gov.companieshouse.web.accounts.enumeration.NoteType; import uk.gov.companieshouse.web.accounts.exception.ServiceException; import uk.gov.companieshouse.web.accounts.model.smallfull.BalanceSheet; import uk.gov.companieshouse.web.accounts.model.smallfull.BalanceSheetHeadings; import uk.gov.companieshouse.web.accounts.model.smallfull.CurrentAssets; import uk.gov.companieshouse.web.accounts.model.smallfull.FixedAssets; import uk.gov.companieshouse.web.accounts.model.smallfull.TangibleAssets; import uk.gov.companieshouse.web.accounts.model.smallfull.notes.debtors.Debtors; import uk.gov.companieshouse.web.accounts.service.NoteService; import uk.gov.companieshouse.web.accounts.service.navigation.NavigatorService; import uk.gov.companieshouse.web.accounts.service.smallfull.BalanceSheetService; import uk.gov.companieshouse.web.accounts.validation.ValidationError; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; @ExtendWith(MockitoExtension.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) class DebtorsControllerTest { private MockMvc mockMvc; @Mock private NoteService<Debtors> mockDebtorsService; @Mock private BalanceSheetService mockBalanceSheetService; @Mock private NavigatorService mockNavigatorService; @InjectMocks private DebtorsController controller; private static final String COMPANY_NUMBER = "companyNumber"; private static final String TRANSACTION_ID = "transactionId"; private static final String COMPANY_ACCOUNTS_ID = "companyAccountsId"; private static final String SMALL_FULL_PATH = "/company/" + COMPANY_NUMBER + "/transaction/" + TRANSACTION_ID + "/company-accounts/" + COMPANY_ACCOUNTS_ID + "/small-full"; private static final String DEBTORS_PATH = SMALL_FULL_PATH + "/debtors"; private static final String DEBTORS_MODEL_ATTR = "debtors"; private static final String BACK_BUTTON_MODEL_ATTR = "backButton"; private static final String TEMPLATE_NAME_MODEL_ATTR = "templateName"; private static final String DEBTORS_VIEW = "smallfull/debtors"; private static final String ERROR_VIEW = "error"; private static final String TEST_PATH = "tradeDebtors.currentTradeDebtors"; private static final String MOCK_CONTROLLER_PATH = UrlBasedViewResolver.REDIRECT_URL_PREFIX + "mockControllerPath"; @BeforeEach private void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); } @Test @DisplayName("Get debtors view success path") void getRequestSuccess() throws Exception { when(mockNavigatorService.getPreviousControllerPath(any(), any())).thenReturn(MOCK_CONTROLLER_PATH); when(mockDebtorsService.get(TRANSACTION_ID, COMPANY_ACCOUNTS_ID, NoteType.SMALL_FULL_DEBTORS)).thenReturn(new Debtors()); this.mockMvc.perform(get(DEBTORS_PATH)) .andExpect(status().isOk()) .andExpect(view().name(DEBTORS_VIEW)) .andExpect(model().attributeExists(DEBTORS_MODEL_ATTR)) .andExpect(model().attributeExists(BACK_BUTTON_MODEL_ATTR)) .andExpect(model().attributeExists(TEMPLATE_NAME_MODEL_ATTR)); verify(mockDebtorsService, times(1)).get(TRANSACTION_ID, COMPANY_ACCOUNTS_ID, NoteType.SMALL_FULL_DEBTORS); } @Test @DisplayName("Get debtors view failure path due to error on debtors retrieval") void getRequestFailureInGetBalanceSheet() throws Exception { when(mockDebtorsService.get(TRANSACTION_ID, COMPANY_ACCOUNTS_ID, NoteType.SMALL_FULL_DEBTORS)).thenThrow(ServiceException.class); this.mockMvc.perform(get(DEBTORS_PATH)) .andExpect(status().isOk()) .andExpect(view().name(ERROR_VIEW)) .andExpect(model().attributeExists(TEMPLATE_NAME_MODEL_ATTR)); } @Test @DisplayName("Post debtors success path") void postRequestSuccess() throws Exception { when(mockNavigatorService.getNextControllerRedirect(any(), ArgumentMatchers.<String>any())).thenReturn(MOCK_CONTROLLER_PATH); when(mockDebtorsService.submit(anyString(), anyString(), any(Debtors.class), eq(NoteType.SMALL_FULL_DEBTORS))).thenReturn(new ArrayList<>()); this.mockMvc.perform(post(DEBTORS_PATH)) .andExpect(status().is3xxRedirection()) .andExpect(view().name(MOCK_CONTROLLER_PATH)); } @Test @DisplayName("Post debtors failure path") void postRequestFailure() throws Exception { doThrow(ServiceException.class) .when(mockDebtorsService).submit(anyString(), anyString(), any(Debtors.class), eq(NoteType.SMALL_FULL_DEBTORS)); this.mockMvc.perform(post(DEBTORS_PATH)) .andExpect(status().isOk()) .andExpect(view().name(ERROR_VIEW)) .andExpect(model().attributeExists(TEMPLATE_NAME_MODEL_ATTR)); } @Test @DisplayName("Post debtors failure path with API validation errors") void postRequestFailureWithApiValidationErrors() throws Exception { ValidationError validationError = new ValidationError(); validationError.setFieldPath(TEST_PATH); validationError.setMessageKey("invalid_character"); List<ValidationError> errors = new ArrayList<>(); errors.add(validationError); when(mockDebtorsService.submit(anyString(), anyString(), any(Debtors.class), eq(NoteType.SMALL_FULL_DEBTORS))).thenReturn(errors); this.mockMvc.perform(post(DEBTORS_PATH)) .andExpect(status().isOk()) .andExpect(view().name(DEBTORS_VIEW)); } @Test @DisplayName("Test will render with Debtors present on balancesheet") void willRenderDebtorsPresent() throws Exception { when(mockBalanceSheetService.getBalanceSheet(TRANSACTION_ID, COMPANY_ACCOUNTS_ID, COMPANY_NUMBER)).thenReturn(getMockBalanceSheet()); boolean renderPage = controller.willRender(COMPANY_NUMBER, TRANSACTION_ID, COMPANY_ACCOUNTS_ID); assertTrue(renderPage); } @Test @DisplayName("Test will render with Debtors not present on balancesheet") void willRenderDebtorsNotPresent() throws Exception { when(mockBalanceSheetService.getBalanceSheet(TRANSACTION_ID, COMPANY_ACCOUNTS_ID, COMPANY_NUMBER)).thenReturn(getMockBalanceSheetNoDebtors()); boolean renderPage = controller.willRender(COMPANY_NUMBER, TRANSACTION_ID, COMPANY_ACCOUNTS_ID); assertFalse(renderPage); } @Test @DisplayName("Test will not render with 0 values in debtors on balance sheet") void willNotRenderDebtorsZeroValues() throws Exception { when(mockBalanceSheetService.getBalanceSheet(TRANSACTION_ID, COMPANY_ACCOUNTS_ID, COMPANY_NUMBER)).thenReturn(getMockBalanceSheetZeroValues()); boolean renderPage = controller.willRender(COMPANY_NUMBER, TRANSACTION_ID, COMPANY_ACCOUNTS_ID); assertFalse(renderPage); } @Test @DisplayName("Post debtors with binding result errors") void postRequestBindingResultErrors() throws Exception { String beanElement = TEST_PATH; // Mock non-numeric input to trigger binding result errors String invalidData = "test"; this.mockMvc.perform(post(DEBTORS_PATH) .param(beanElement, invalidData)) .andExpect(status().isOk()) .andExpect(view().name(DEBTORS_VIEW)) .andExpect(model().attributeExists(TEMPLATE_NAME_MODEL_ATTR)); } private BalanceSheet getMockBalanceSheet() { BalanceSheet balanceSheet = new BalanceSheet(); BalanceSheetHeadings balanceSheetHeadings = new BalanceSheetHeadings(); CurrentAssets currentAssets = new CurrentAssets(); uk.gov.companieshouse.web.accounts.model.smallfull.Debtors debtors = new uk.gov.companieshouse.web.accounts.model.smallfull.Debtors(); debtors.setCurrentAmount(1L); debtors.setPreviousAmount(2L); currentAssets.setDebtors(debtors); balanceSheetHeadings.setCurrentPeriodHeading("currentBalanceSheetHeading"); balanceSheetHeadings.setPreviousPeriodHeading("previousBalanceSheetHeading"); balanceSheet.setCurrentAssets(currentAssets); balanceSheet.setBalanceSheetHeadings(balanceSheetHeadings); return balanceSheet; } private BalanceSheet getMockBalanceSheetNoDebtors() { BalanceSheet balanceSheet = new BalanceSheet(); FixedAssets fixedAssets = new FixedAssets(); TangibleAssets tangibleAssets = new TangibleAssets(); tangibleAssets.setCurrentAmount(1L); tangibleAssets.setPreviousAmount(1L); fixedAssets.setTangibleAssets(tangibleAssets); balanceSheet.setFixedAssets(fixedAssets); return balanceSheet; } private BalanceSheet getMockBalanceSheetZeroValues() { BalanceSheet balanceSheet = new BalanceSheet(); BalanceSheetHeadings balanceSheetHeadings = new BalanceSheetHeadings(); CurrentAssets currentAssets = new CurrentAssets(); uk.gov.companieshouse.web.accounts.model.smallfull.Debtors debtors = new uk.gov.companieshouse.web.accounts.model.smallfull.Debtors(); debtors.setCurrentAmount(0L); debtors.setPreviousAmount(0L); currentAssets.setDebtors(debtors); balanceSheetHeadings.setCurrentPeriodHeading("currentBalanceSheetHeading"); balanceSheetHeadings.setPreviousPeriodHeading("previousBalanceSheetHeading"); balanceSheet.setCurrentAssets(currentAssets); balanceSheet.setBalanceSheetHeadings(balanceSheetHeadings); return balanceSheet; } }
3e13ac51df587866072286dd7f0f51e6fac43335
13,251
java
Java
app/src/main/java/br/com/bittrexanalizer/facade/CompraFacade.java
alimogh/AppBittrexAnalizer
e1b3821debb1cb37ea152f411cf8ed6af4d12556
[ "MIT" ]
2
2020-09-18T14:30:12.000Z
2021-07-05T00:37:44.000Z
app/src/main/java/br/com/bittrexanalizer/facade/CompraFacade.java
legionario07/AppBittrexAnalizer
e1b3821debb1cb37ea152f411cf8ed6af4d12556
[ "MIT" ]
null
null
null
app/src/main/java/br/com/bittrexanalizer/facade/CompraFacade.java
legionario07/AppBittrexAnalizer
e1b3821debb1cb37ea152f411cf8ed6af4d12556
[ "MIT" ]
null
null
null
31.178824
150
0.560411
8,327
package br.com.bittrexanalizer.facade; import android.content.Context; import android.util.Log; import java.math.BigDecimal; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import br.com.bittrexanalizer.analises.AnaliseRobot; import br.com.bittrexanalizer.analises.IAnaliser; import br.com.bittrexanalizer.database.dao.ConfiguracaoDAO; import br.com.bittrexanalizer.database.dao.TickerDAO; import br.com.bittrexanalizer.domain.Balance; import br.com.bittrexanalizer.domain.Candle; import br.com.bittrexanalizer.domain.Configuracao; import br.com.bittrexanalizer.domain.Order; import br.com.bittrexanalizer.domain.Ticker; import br.com.bittrexanalizer.strategy.BalanceStrategy; import br.com.bittrexanalizer.strategy.BuyOrderStrategy; import br.com.bittrexanalizer.utils.CalculoUtil; import br.com.bittrexanalizer.utils.ConstantesUtil; import br.com.bittrexanalizer.utils.EmailUtil; import br.com.bittrexanalizer.utils.SessionUtil; import br.com.bittrexanalizer.utils.WebServiceUtil; /** * Created by PauLinHo on 16/09/2017. */ public class CompraFacade { private TickerDAO tickerDAO; private Context context; public static Map<String, LinkedList<Candle>> mapCandles; private boolean robotLigado = false; private boolean devoParar; private EmailUtil emailUtil; private AnaliseRobot analiseRobot; private BigDecimal valorParaCompraRobot; private final String BTC = "BTC"; private Balance balance; private final String ROBOT_COMPRA = "COMPRA ROBOT "; private final String ROBOT_ERROS = "ERROS ROBOT "; private StringBuilder moedasErros = new StringBuilder(); private LinkedList<Ticker> moedasHabilitadas; private volatile LinkedList<Ticker> tickers; private LinkedList<Ticker> tickersDoBD; private int qtdeTickersPesquisar; private int tempoEsperoThread; public void executar(Context context) { this.context = context; tickerDAO = new TickerDAO(context); getConfiguracoes(); Log.i("Bittrex", "Entrei"); //pegando as variaveis do Sistema robotLigado = Boolean.valueOf(SessionUtil.getInstance().getMapConfiguracao().get(ConstantesUtil.ROBOT_LIGADO)); qtdeTickersPesquisar = Integer.valueOf(SessionUtil.getInstance().getMapConfiguracao().get(ConstantesUtil.QTDE_TICKERS_PESQUISA)); tempoEsperoThread = Integer.valueOf(SessionUtil.getInstance().getMapConfiguracao().get(ConstantesUtil.TEMPO_ESPERA_THREAD)); valorParaCompraRobot = new BigDecimal(SessionUtil.getInstance().getMapConfiguracao().get(ConstantesUtil.VALOR_COMPRA_ROBOT)).setScale(8); SessionUtil.getInstance().setMaxCandleParaPesquisar(0); //iniciando objetos analiseRobot = new AnaliseRobot(); moedasHabilitadas = new LinkedList<>(); emailUtil = new EmailUtil(); moedasErros.append("\r\r"+ROBOT_ERROS); //Verifica se o robot esta ligado if (robotLigado) { try { executarRobot(); } catch (Exception e) { moedasErros.append(e.getMessage() + e.getStackTrace()); } finally { SessionUtil.getInstance().getMsgErros().append(moedasErros.toString()); } } } private void getConfiguracoes() { LinkedList<Configuracao> configuracoes = new LinkedList<>(); configuracoes = new ConfiguracaoDAO(context).all(); Map<String, String> mapConfiguracao = new HashMap<String, String>(); if (configuracoes == null) { SessionUtil.getInstance().setMapConfiguracao(null); return; } for (Configuracao c : configuracoes) { mapConfiguracao.put(c.getPropriedade(), c.getValor()); } SessionUtil.getInstance().setMapConfiguracao(mapConfiguracao); } /** * Realiza o processamento para analisar os valores de todas as moedas */ private void executarRobot() { //atualiza os valores de BTC BalanceStrategy.execute(); //pega o valor da moeda BTC, utilizada para realizar a compra balance = SessionUtil.getInstance().getMapBalances().get(BTC); //valor disponivel em BTC é maior ou igual o valor minimo para compra? if (!temSaldoBTC()) { devoParar = true; moedasErros.append("SEM SALDO"); return; } //pegando todos os tickers do Banco de Dados tickersDoBD = tickerDAO.findAllTickers(); Thread t = new Thread(new Runnable() { @Override public void run() { do { mapCandles = new ConcurrentHashMap<>(new HashMap<String, LinkedList<Candle>>()); getDados(); Set<String> keys = null; if (mapCandles != null) { keys = mapCandles.keySet(); } for (String k : keys) { LinkedList<Candle> lista = mapCandles.get(k); if (lista.size() > 0) { realizarAnalises(k, lista); } } try { if (!devoParar) { Thread.sleep(tempoEsperoThread); } } catch (InterruptedException e) { moedasErros.append("- " + e.getMessage() + " - " + e.getStackTrace()); e.printStackTrace(); } } while (!devoParar); if (!moedasHabilitadas.isEmpty()) { return; } } }); t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public void getDados() { try { Boolean isAllTickers = false; /** * Faz a verificação se foi selecionados todas as moedas * ou se será calculado apenas nas moedas que o usuario esta analizando */ if (SessionUtil.getInstance().getMapConfiguracao().containsKey(ConstantesUtil.ALL_TICKERS)) { isAllTickers = new Boolean(SessionUtil.getInstance().getMapConfiguracao().get(ConstantesUtil.ALL_TICKERS)); if (isAllTickers) { tickers = new LinkedList<>(); Set<String> keys = SessionUtil.getInstance().getNomeExchanges().keySet(); for (String k : keys) { Ticker t = new Ticker(); t.setSigla(k); tickers.add(t); } } else { tickers = SessionUtil.getInstance().getTickers(); } } else { tickers = SessionUtil.getInstance().getTickers(); } ExecutorService executorService = Executors.newCachedThreadPool(); int flagParar = 0; int i = 0; if ((SessionUtil.getInstance().getMaxCandleParaPesquisar() + qtdeTickersPesquisar) > tickers.size()) { i = SessionUtil.getInstance().getMaxCandleParaPesquisar(); flagParar = tickers.size(); SessionUtil.getInstance().setMaxCandleParaPesquisar(Integer.MIN_VALUE); devoParar = true; } else { flagParar = SessionUtil.getInstance().getMaxCandleParaPesquisar() + qtdeTickersPesquisar; i = SessionUtil.getInstance().getMaxCandleParaPesquisar(); } for (; i < tickers.size(); i++) { if (i == flagParar) { SessionUtil.getInstance().setMaxCandleParaPesquisar(SessionUtil.getInstance().getMaxCandleParaPesquisar() + qtdeTickersPesquisar); break; } Candle candle = new Candle(); candle.setSigla(tickers.get(i).getSigla()); executorService.execute(candle); } executorService.shutdown(); while (!executorService.isTerminated()) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (Exception e) { moedasErros.append("Erro: " + e.getMessage()); return; } } public void realizarAnalises(String sigla, LinkedList<Candle> candles) { boolean devoComprar = false; try { int valorOBV = analiseRobot.analizer(candles); if (valorOBV != IAnaliser.IDEAL_PARA_COMPRA) { devoComprar = false; } else { devoComprar = true; } if (devoComprar) { BalanceStrategy.execute(); //atualiza o Balance balance = SessionUtil.getInstance().getMapBalances().get(BTC); //tem saldo? if (!temSaldoBTC()) { devoParar = true; return; } Ticker t = new Ticker(); t.setSigla(sigla); t.setUrlApi(WebServiceUtil.getUrl() + t.getSigla().toLowerCase()); t = localizarValorDoTicker(t); //realiza a compra boolean comprado = comprar(t); if (comprado) { //calcula porcentagem t.setAvisoStopLoss(CalculoUtil.getPorcentagemLoss(t.getBid())); t.setAvisoStopGain(CalculoUtil.getPorcentagemLimit(t.getBid())); t.setBought(true); boolean jaExistia = false; for (Ticker temp : tickersDoBD) { //já existe? if (temp.getSigla().toLowerCase().equals(t.getSigla().toLowerCase())) { t.setId(temp.getId()); t.setNomeExchange(SessionUtil.getInstance().getNomeExchanges().get(t.getSigla())); //atualizado tickerDAO.update(t); jaExistia = true; continue; } } //não existia if (!jaExistia) { t.setNomeExchange(SessionUtil.getInstance().getNomeExchanges().get(t.getSigla())); tickerDAO.create(t); } String mensagem = ROBOT_COMPRA + "Moeda: " + t.getSigla(); mensagem += "\n - Valor: " + t.getAsk(); mensagem += "\n - Valor Limit: " + t.getAvisoStopGain(); mensagem += "\n - Valor Lost: " + t.getAvisoStopLoss(); enviarEmail(mensagem, ROBOT_COMPRA); moedasHabilitadas.add(t); } } } catch (Exception e) { moedasErros.append("\t\r"); moedasErros.append(e.getMessage()); } } private Ticker localizarValorDoTicker(Ticker tic) { LinkedList<Ticker> tickersTemp = new LinkedList<>(); tickersTemp.add(tic); ExecutorService executorService = Executors.newCachedThreadPool(); for (Ticker t : tickersTemp) { executorService.execute(t); } executorService.shutdown(); while (!executorService.isTerminated()) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } return tickersTemp.getFirst(); } private boolean comprar(Ticker ticker) { Order order = new Order(); order.setSigla(ticker.getSigla()); //Calcula a quantidade da moeda que será comprada order.setQuantity(CalculoUtil.getQuantidadeASerComprada(valorParaCompraRobot, ticker.getAsk())); //Pega o valor atual de compra da moeda order.setRate(ticker.getAsk()); boolean retorno = false; Log.i("Bittrex", "Comprar: " + ticker.getSigla() + " - Valor Venda: " + ticker.getAvisoStopGain() + " - Lost: " + ticker.getAvisoStopLoss()); //executa a compra retorno = BuyOrderStrategy.execute(order); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } return retorno; } private boolean temSaldoBTC() { if (balance.getBalance().compareTo(valorParaCompraRobot) == -1) { moedasErros.append("SEM SALDO"); return false; } return true; } private void enviarEmail(final String mensagem, final String operacao) { emailUtil.enviarEmail(context, "COMPRA ROBOT: ", mensagem, operacao); } }
3e13ad0a7b0017cfcaacdb62efdebd1da6c85051
6,567
java
Java
src/main/java/net/sf/reportengine/components/PivotTableBuilder.java
humbletrader/katechaki
c7de760605053ea88e45a8bc938dca01de7280f4
[ "Apache-2.0" ]
3
2016-07-11T12:14:00.000Z
2021-04-30T12:45:34.000Z
src/main/java/net/sf/reportengine/components/PivotTableBuilder.java
humbletrader/katechaki
c7de760605053ea88e45a8bc938dca01de7280f4
[ "Apache-2.0" ]
3
2017-11-23T17:42:05.000Z
2019-03-27T21:05:21.000Z
src/main/java/net/sf/reportengine/components/PivotTableBuilder.java
humbletrader/katechaki
c7de760605053ea88e45a8bc938dca01de7280f4
[ "Apache-2.0" ]
2
2017-11-27T09:53:24.000Z
2021-04-30T16:34:31.000Z
34.229167
99
0.647596
8,328
/** * Copyright (C) 2006 Dragos Balan (hzdkv@example.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.reportengine.components; import static net.sf.reportengine.util.UserProvidedBoolean.FALSE_NOT_PROVIDED_BY_USER; import static net.sf.reportengine.util.UserProvidedBoolean.FALSE_PROVIDED_BY_USER; import static net.sf.reportengine.util.UserProvidedBoolean.TRUE_NOT_PROVIDED_BY_USER; import static net.sf.reportengine.util.UserProvidedBoolean.TRUE_PROVIDED_BY_USER; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.sf.reportengine.config.DataColumn; import net.sf.reportengine.config.DefaultDataColumn; import net.sf.reportengine.config.DefaultGroupColumn; import net.sf.reportengine.config.GroupColumn; import net.sf.reportengine.config.PivotData; import net.sf.reportengine.config.PivotHeaderRow; import net.sf.reportengine.in.TableInput; import net.sf.reportengine.util.UserProvidedBoolean; /** * <p>Builder for a {@link PivotTable} component</p> * <p> * The typical usage is: * <pre> * PivotTable table = new PivotTableBuilder(new TextTableInput("./input/expenses.csv", ",")) * .addDataColumn(new DefaultDataColumn("Month",0)) * .addHeaderRow(new DefaultPivotHeaderRow(1)) * .pivotData(new DefaultPivotData(2)) * .build(); * </pre> * </p> * @author dragos balan * @see PivotTable */ public class PivotTableBuilder { private UserProvidedBoolean showTotals = FALSE_NOT_PROVIDED_BY_USER; private UserProvidedBoolean showGrandTotal = FALSE_NOT_PROVIDED_BY_USER; private boolean showDataRows = true; private boolean valuesSorted = true; private TableInput tableInput = null; private List<DataColumn> dataColumns = new ArrayList<DataColumn>(); private List<GroupColumn> groupColumns = new ArrayList<GroupColumn>(); private List<PivotHeaderRow> headerRows = new ArrayList<PivotHeaderRow>(); private PivotData pivotData = null; /** * constructor for this builder based on the provided input * * @param input * the input for this component */ public PivotTableBuilder(TableInput input) { this.tableInput = input; } public PivotTableBuilder showTotals(boolean show) { this.showTotals = show ? TRUE_PROVIDED_BY_USER : FALSE_PROVIDED_BY_USER; return this; } public PivotTableBuilder showTotals() { return showTotals(true); } public PivotTableBuilder showGrandTotal(boolean show) { this.showGrandTotal = show ? TRUE_PROVIDED_BY_USER : FALSE_PROVIDED_BY_USER; return this; } public PivotTableBuilder showGrandTotal() { return showGrandTotal(true); } public PivotTableBuilder showDataRows(boolean show) { this.showDataRows = show; return this; } public PivotTableBuilder showDataRows() { return showDataRows(true); } public PivotTableBuilder sortValues() { this.valuesSorted = false; return this; } @Deprecated public PivotTableBuilder dataColumns(List<? extends DataColumn> dataCols) { // if(dataCols != null){ for (DataColumn dataColumn : dataCols) { internalAddDataColumn(dataColumn); } // } return this; } private void internalAddDataColumn(DataColumn dataCol) { this.dataColumns.add(dataCol); if (dataCol.getCalculator() != null) { if (!showTotals.isValueProvidedByUser()) { this.showTotals = TRUE_NOT_PROVIDED_BY_USER; } if (!showGrandTotal.isValueProvidedByUser()) { this.showGrandTotal = TRUE_NOT_PROVIDED_BY_USER; } } } public PivotTableBuilder addDataColumn(int columnIndex){ return addDataColumn(new DefaultDataColumn.Builder(columnIndex).build()); } public PivotTableBuilder addDataColumn(int columnIndex, String header){ return addDataColumn(new DefaultDataColumn.Builder(columnIndex).header(header).build()); } public PivotTableBuilder addDataColumn(DataColumn dataCol) { internalAddDataColumn(dataCol); return this; } @Deprecated public PivotTableBuilder groupColumns(List<? extends GroupColumn> groupCols) { for(GroupColumn col: groupCols){ this.groupColumns.add(col); } return this; } public PivotTableBuilder addGroupColumn(int columnIndex){ return addGroupColumn(new DefaultGroupColumn.Builder(columnIndex).build()); } public PivotTableBuilder addGroupColumn(int columnIndex, String header){ return addGroupColumn(new DefaultGroupColumn.Builder(columnIndex).header(header).build()); } public PivotTableBuilder addGroupColumn(GroupColumn groupCol) { this.groupColumns.add(groupCol); return this; } public PivotTableBuilder headerRows(List<PivotHeaderRow> headerRows) { this.headerRows = headerRows; return this; } public PivotTableBuilder addHeaderRow(PivotHeaderRow headerRow) { this.headerRows.add(headerRow); return this; } public PivotTableBuilder pivotData(PivotData data) { this.pivotData = data; return this; } public PivotTable build() { return new DefaultPivotTable(tableInput, dataColumns, groupColumns, pivotData, headerRows, showTotals.getValue(), showGrandTotal.getValue(), showDataRows, valuesSorted); } }
3e13ad7e82c1ef97569abe515ea08fbe15c91725
3,690
java
Java
apps/owl/test/java/org/semanticweb/owlapi/api/test/TestProfile.java
OpenKGC/hypergraphdb
05073f5082df60577e48af283311172dd3f2f847
[ "Apache-2.0" ]
3
2018-10-04T10:37:05.000Z
2020-06-25T16:44:13.000Z
apps/owl/test/java/org/semanticweb/owlapi/api/test/TestProfile.java
OpenKGC/hypergraphdb
05073f5082df60577e48af283311172dd3f2f847
[ "Apache-2.0" ]
8
2015-07-18T05:17:21.000Z
2018-09-12T03:16:49.000Z
apps/owl/test/java/org/semanticweb/owlapi/api/test/TestProfile.java
OpenKGC/hypergraphdb
05073f5082df60577e48af283311172dd3f2f847
[ "Apache-2.0" ]
4
2015-08-07T23:32:26.000Z
2020-06-25T12:58:01.000Z
44.457831
109
0.712737
8,329
/* * This file is part of the OWL API. * * The contents of this file are subject to the LGPL License, Version 3.0. * * Copyright (C) 2011, The University of Manchester * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * * * Alternatively, the contents of this file may be used under the terms of the Apache License, Version 2.0 * in which case, the provisions of the Apache License Version 2.0 are applicable instead of those above. * * Copyright 2011, University of Manchester * * 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.semanticweb.owlapi.api.test; import junit.framework.TestCase; import org.hypergraphdb.app.owl.test.OWLManagerHG; import org.semanticweb.owlapi.io.StringDocumentSource; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.profiles.OWL2RLProfile; import org.semanticweb.owlapi.profiles.OWLProfileReport; import org.semanticweb.owlapi.profiles.OWLProfileViolation; public class TestProfile extends TestCase { public void testOWLEL() throws Exception{ String onto = "<?xml version=\"1.0\"?>\n" + "<!DOCTYPE rdf:RDF [\n" + "<!ENTITY owl \"http://www.w3.org/2002/07/owl#\" >\n" + "<!ENTITY rdfs \"http://www.w3.org/2000/01/rdf-schema#\" >\n" + "<!ENTITY rdf \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >\n" + "]>\n" + "<rdf:RDF xmlns=\"http://xmlns.com/foaf/0.1/\"\n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n" + "xmlns:owl=\"http://www.w3.org/2002/07/owl#\">\n" + "<owl:Ontology rdf:about=\"http://ex.com\"/>\n" + "<rdf:Property rdf:about=\"http://ex.com#p1\">\n" + "<rdf:type rdf:resource=\"http://www.w3.org/2002/07/owl#DatatypeProperty\"/>\n" + "</rdf:Property>\n" + "<rdf:Property rdf:about=\"http://ex.com#p2\">\n" + "<rdf:type rdf:resource=\"http://www.w3.org/2002/07/owl#DatatypeProperty\"/>\n" + "<rdfs:subPropertyOf rdf:resource=\"http://ex.com#p1\"/>\n" + "</rdf:Property>\n" + "</rdf:RDF>"; OWLOntologyManager m= OWLManagerHG.createHGDBOWLOntologyManager(); //OWLManager.createOWLOntologyManager(); OWLOntology o=m.loadOntologyFromOntologyDocument(new StringDocumentSource(onto)); OWL2RLProfile p=new OWL2RLProfile(); OWLProfileReport report=p.checkOntology(o); for(OWLProfileViolation v: report.getViolations()) { System.out.println("TestProfile.testOWLEL() "+v); } assertTrue("unexpected violations! "+report.getViolations(),report.getViolations().size()==0); } }
3e13ada9a999f634839b391f26312927c5630619
347
java
Java
src/main/java/br/eti/qisolucoes/contactcloud/constants/AwsConstants.java
nosered/contact-cloud
9c9d408860d33c87b4f5b00c5d43debccf12c733
[ "MIT" ]
null
null
null
src/main/java/br/eti/qisolucoes/contactcloud/constants/AwsConstants.java
nosered/contact-cloud
9c9d408860d33c87b4f5b00c5d43debccf12c733
[ "MIT" ]
null
null
null
src/main/java/br/eti/qisolucoes/contactcloud/constants/AwsConstants.java
nosered/contact-cloud
9c9d408860d33c87b4f5b00c5d43debccf12c733
[ "MIT" ]
null
null
null
24.785714
97
0.763689
8,330
package br.eti.qisolucoes.contactcloud.constants; public class AwsConstants { public static String S3_PREFIX = "s3://"; public static String BUCKET_NAME = "contactcloudstore"; public static String PUBLIC_FOTO_PATH = "https://s3-sa-east-1.amazonaws.com/contactcloudstore/"; public static String S3_DEFAULT_FILE = "defaultfile.png"; }
3e13ae3dc000a05b572e65c05ad41d3c5db8bc30
1,153
java
Java
components/src/main/java/eu/internetofus/common/components/profile_diversity_manager/Aggregation.java
InternetOfUs/common-models-java
b6312e66aed917fd7efc30bcfd1f1c6526fe8d89
[ "Apache-2.0" ]
null
null
null
components/src/main/java/eu/internetofus/common/components/profile_diversity_manager/Aggregation.java
InternetOfUs/common-models-java
b6312e66aed917fd7efc30bcfd1f1c6526fe8d89
[ "Apache-2.0" ]
null
null
null
components/src/main/java/eu/internetofus/common/components/profile_diversity_manager/Aggregation.java
InternetOfUs/common-models-java
b6312e66aed917fd7efc30bcfd1f1c6526fe8d89
[ "Apache-2.0" ]
null
null
null
25.065217
80
0.580225
8,331
/* * ----------------------------------------------------------------------------- * * Copyright 2019 - 2022 UDT-IA, IIIA-CSIC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ----------------------------------------------------------------------------- */ package eu.internetofus.common.components.profile_diversity_manager; /** * The possible aggregation functions for the similarity. * * @author UDT-IA, IIIA-CSIC */ public enum Aggregation { /** * Use the maximum. */ max, /** * Use the mean. */ mean, /** * Use the quadratic at 75%. */ q75, /** * Use the quadratic at 90%. */ q90; }
3e13ae45a1781760cd3335218e3d0a2ea9d0d507
4,326
java
Java
Figures/src/algs/chapter10/table2/Main.java
inflaton/algorithms-nutshell-2ed
b17f75b067ba7f1cf8bbc0a40ea64c6bd7f73dd8
[ "MIT" ]
522
2016-02-21T18:44:23.000Z
2022-03-31T09:29:04.000Z
Figures/src/algs/chapter10/table2/Main.java
inflaton/algorithms-nutshell-2ed
b17f75b067ba7f1cf8bbc0a40ea64c6bd7f73dd8
[ "MIT" ]
3
2020-04-09T01:52:52.000Z
2022-01-13T08:18:55.000Z
Figures/src/algs/chapter10/table2/Main.java
inflaton/algorithms-nutshell-2ed
b17f75b067ba7f1cf8bbc0a40ea64c6bd7f73dd8
[ "MIT" ]
216
2015-10-16T16:50:10.000Z
2022-02-10T00:57:20.000Z
28.649007
90
0.638696
8,332
package algs.chapter10.table2; /** * Try to show O(n^(1-1/d)+k) behavior where n is the number of elements in the * kd-tree being searched for the range query and k is the number of found * points. * * Test on three setups: * * (a) WHOLE TREE: query will be [-scale*2, scale*2, -scale*2, scale*2] * (b) QUARTER TREE: query will be [ scale*.52, scale, scale*.52, scale] * upper 23% of the tree range * (c) RANGE with no points (or at least, will be a range == a single point) */ import java.text.NumberFormat; import java.util.Random; import algs.model.IMultiPoint; import algs.model.kdtree.DimensionalNode; import algs.model.kdtree.IVisitKDNode; import algs.model.kdtree.KDFactory; import algs.model.kdtree.KDTree; import algs.model.nd.Hypercube; import algs.model.nd.Hyperpoint; import algs.model.problems.rangeQuery.BruteForceRangeQuery; import algs.model.tests.common.TrialSuite; class Counter implements IVisitKDNode { int ct; public void visit(DimensionalNode node) { ct++; } public void drain (DimensionalNode node) { ct++; } } public class Main { // random number generator. static Random rGen; /** * generate array of n d-dimensional points whose coordinates are * values in the range 0 .. scale */ private static IMultiPoint[] randomPoints (int n, int d, int scale) { IMultiPoint points[] = new IMultiPoint[n]; for (int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < d; j++) { sb.append(rGen.nextDouble()*scale); if (j < d-1) { sb.append (","); } } points[i] = new Hyperpoint(sb.toString()); } return points; } public static void main (String []args) { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); nf.setGroupingUsed(false); rGen = new Random(); rGen.setSeed(1); // be consistent across platforms and runs. // dimension for points. int numSearches = 128; int NUM_TRIALS = 100; int maxN = 131072; int maxD = 5; int scale = 4000; System.out.println("n\td=2 RQ\td=3 RQ\td=4 RQ\td=5 RQ\td=2 BF\td=3 BF\td=4 BF\td=5 BF"); for (int n=4096; n <= maxN; n*=2) { double results_RQ[] = new double[maxD+1]; // +1 for easier coding later double results_BF[] = new double[maxD+1]; for (int d = 2; d <= maxD; d++) { TrialSuite kdSearch1 = new TrialSuite(); TrialSuite bfSearch1 = new TrialSuite(); Counter kd_count = new Counter(); Counter bf_count = new Counter(); for (int t = 1; t <= NUM_TRIALS; t++) { long now, done; // create n random points in d dimensions drawn from [0,1] uniformly IMultiPoint[] points = randomPoints (n, d, scale); // Perform a number of searches drawn from same [0,scale] uniformly. System.gc(); // This forms the basis for the kd-tree. These are the points p. Note // that the KDTree generate method will likely shuffle the points. now = System.currentTimeMillis(); KDTree tree = KDFactory.generate(points); done = System.currentTimeMillis(); // space1: Entire tree double lows[] = new double[d], highs[] = new double[d]; for (int k = 0; k < d; k++) { lows[k] = -2*scale; highs[k] = 2*scale; } Hypercube space1 = new Hypercube (lows, highs); System.gc(); now = System.currentTimeMillis(); for (int ns = 0; ns < numSearches; ns++) { /* results1 = */ tree.range(space1, kd_count); } done = System.currentTimeMillis(); kdSearch1.addTrial(n, now, done); BruteForceRangeQuery bfrq = new BruteForceRangeQuery(points); System.gc(); now = System.currentTimeMillis(); for (int ns = 0; ns < numSearches; ns++) { bfrq.search(space1, bf_count); } done = System.currentTimeMillis(); bfSearch1.addTrial(n, now, done); // weak form of comparison if (kd_count.ct != bf_count.ct) { System.err.println("result1 fails"); } } results_RQ[d] = Double.valueOf(kdSearch1.getAverage(n)); results_BF[d] = Double.valueOf(bfSearch1.getAverage(n)); } System.out.print(n + "\t"); for (int d = 2; d <= 5; d++) { System.out.print(nf.format(results_RQ[d]) + "\t"); } for (int d = 2; d <= 5; d++) { System.out.print(nf.format(results_BF[d]) + "\t"); } System.out.println(); } } }
3e13ae6a3425b344546738f94f0a0e9789fa4331
2,824
java
Java
core/src/com/tacktic/inbudget/Resources.java
lauraluiz/in-budget
545661cd03afc01cee03dc8e6934cc85a5a0439a
[ "MIT" ]
null
null
null
core/src/com/tacktic/inbudget/Resources.java
lauraluiz/in-budget
545661cd03afc01cee03dc8e6934cc85a5a0439a
[ "MIT" ]
null
null
null
core/src/com/tacktic/inbudget/Resources.java
lauraluiz/in-budget
545661cd03afc01cee03dc8e6934cc85a5a0439a
[ "MIT" ]
null
null
null
30.042553
89
0.660765
8,333
package com.tacktic.inbudget; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture; import java.util.HashMap; import java.util.Map; public class Resources { private final Texture backgroundImage; private final Texture topMenuImage; private final Texture bottomMenuImage; private final Texture girlImage; private final Map<String, Texture> itemTextures; private final Texture priceTagImage; private final Sound dropSound; private final Music pianoMusic; private final Texture blankImage; private Texture resultBackgroundImage; public Resources() { itemTextures = new HashMap<String, Texture>(); for (FileHandle file : Gdx.files.internal("items").list()) { itemTextures.put(file.nameWithoutExtension(), new Texture(file)); } blankImage = new Texture(Gdx.files.internal("none.png")); backgroundImage = new Texture(Gdx.files.internal("background-layer1.png")); topMenuImage = new Texture(Gdx.files.internal("background-layer3.png")); bottomMenuImage = new Texture(Gdx.files.internal("background-layer2.png")); resultBackgroundImage = new Texture(Gdx.files.internal("background-layer4.png")); girlImage = new Texture(Gdx.files.internal("girl.png")); priceTagImage = new Texture(Gdx.files.internal("tag.png")); dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav")); pianoMusic = Gdx.audio.newMusic(Gdx.files.internal("music.wav")); pianoMusic.setLooping(true); } public Texture itemImage(String itemId) { if (itemTextures.containsKey(itemId)) { return itemTextures.get(itemId); } else { return blankImage; } } public Texture girlImage() { return girlImage; } public Texture backgroundImage() { return backgroundImage; } public Texture resultBackgroundImage() { return resultBackgroundImage; } public Texture topMenuImage() { return topMenuImage; } public Texture bottomMenuImage() { return bottomMenuImage; } public Texture priceTagImage() { return priceTagImage; } public Sound dropSound() { return dropSound; } public Music gameMusic() { return pianoMusic; } public void dispose() { for (Texture texture : itemTextures.values()) { texture.dispose(); } itemTextures.clear(); backgroundImage.dispose(); resultBackgroundImage.dispose(); topMenuImage.dispose(); bottomMenuImage.dispose(); dropSound.dispose(); pianoMusic.dispose(); } }
3e13b0f8f6d935700af9ecd9789e17c8f1f3fd60
310
java
Java
backend/src/main/java/my/sample/util/Constants.java
sabob/springboot-angular-starter
0ac472cdde08ae5b31d9943ecf4029132adabf0b
[ "MIT" ]
null
null
null
backend/src/main/java/my/sample/util/Constants.java
sabob/springboot-angular-starter
0ac472cdde08ae5b31d9943ecf4029132adabf0b
[ "MIT" ]
null
null
null
backend/src/main/java/my/sample/util/Constants.java
sabob/springboot-angular-starter
0ac472cdde08ae5b31d9943ecf4029132adabf0b
[ "MIT" ]
null
null
null
20.666667
69
0.758065
8,334
package my.sample.util; public class Constants { public static final int CONNECT_TIMEOUT_IN_SECONDS = 10; public static final int READ_TIMEOUT_IN_MINUTES = 5; public static final String APP_COOKIE_NAME = "sampleToken"; public static final String JSESSIONID_COOKIE_NAME = "JSESSIONID"; }
3e13b11423736580818a21be7496dab24169357f
7,005
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/AltHoloDrive.java
NerdsOfAFeather/FtcRobotController
4c1a168a96effa1ea9d9c44f1aac6f704dca4fd4
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/AltHoloDrive.java
NerdsOfAFeather/FtcRobotController
4c1a168a96effa1ea9d9c44f1aac6f704dca4fd4
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/AltHoloDrive.java
NerdsOfAFeather/FtcRobotController
4c1a168a96effa1ea9d9c44f1aac6f704dca4fd4
[ "MIT" ]
null
null
null
36.675393
159
0.615846
8,335
package org.firstinspires.ftc.teamcode; import android.net.wifi.aware.WifiAwareManager; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; @TeleOp(name="AltHoloDrive", group="Pushbot") public class AltHoloDrive extends ConceptTensorFlowObjectDetectionWebcam{ float rotate_angle = 0; double reset_angle = 0; public DcMotor frontRight; public DcMotor backRight; public DcMotor backLeft; public DcMotor frontLeft; BNO055IMU imu; public void initDriveHardware(){ // init the motors frontRight = hardwareMap.dcMotor.get("fr"); backRight = hardwareMap.dcMotor.get("br"); frontLeft = hardwareMap.dcMotor.get("fl"); backLeft = hardwareMap.dcMotor.get("bl"); // set wheel direction (If a motor is put on backwards the direction may need to be reversed) frontLeft.setDirection(DcMotorSimple.Direction.FORWARD); backLeft.setDirection(DcMotorSimple.Direction.FORWARD); frontRight.setDirection(DcMotorSimple.Direction.REVERSE); backRight.setDirection(DcMotorSimple.Direction.REVERSE); //set stop method frontLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); backLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); frontRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); backRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); //imu stuff imu = hardwareMap.get(BNO055IMU.class, "imu"); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.mode = BNO055IMU.SensorMode.IMU; parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; parameters.loggingEnabled = false; imu.initialize(parameters); } @Override public void runOpMode() { } public void driveSimple(){ double power = 1; if(gamepad1.dpad_up){ //Forward frontLeft.setPower(-power); backLeft.setPower(-power); backRight.setPower(-power); frontRight.setPower(-power); } else if(gamepad1.dpad_left){ //Left frontLeft.setPower(power); backLeft.setPower(-power); backRight.setPower(power); frontRight.setPower(-power); } else if(gamepad1.dpad_down){ //Back frontLeft.setPower(power); backLeft.setPower(power); backRight.setPower(power); frontRight.setPower(power); } else if(gamepad1.dpad_right){ //Right frontLeft.setPower(-power); backLeft.setPower(power); backRight.setPower(-power); frontRight.setPower(power); } else if(Math.abs(gamepad1.right_stick_x) > 0){ //Rotation frontLeft.setPower(-gamepad1.right_stick_x); backLeft.setPower(-gamepad1.right_stick_x); backRight.setPower(gamepad1.right_stick_x); frontRight.setPower(gamepad1.right_stick_x); } else{ frontLeft.setPower(0); backLeft.setPower(0); backRight.setPower(0); frontRight.setPower(0); } } public void drive() { double rotate = gamepad1.right_stick_x/4; double stick_x = gamepad1.left_stick_x * Math.sqrt(Math.pow(1-Math.abs(rotate), 2)/2); //Accounts for rrotate when limiting magnitude to be less than 1 double stick_y = gamepad1.left_stick_y * Math.sqrt(Math.pow(1-Math.abs(rotate), 2)/2); double theta = 0; double Px = 0; double Py = 0; double gyroAngle = getHeading() * Math.PI / 180; //Converts gyroAngle into radians if (gyroAngle <= 0) { gyroAngle = gyroAngle + (Math.PI / 2); } else if (0 < gyroAngle && gyroAngle < Math.PI / 2) { gyroAngle = gyroAngle + (Math.PI / 2); } else if (Math.PI / 2 <= gyroAngle) { gyroAngle = gyroAngle - (3 * Math.PI / 2); } gyroAngle = -1 * gyroAngle; if(gamepad1.right_bumper){ //Disables gyro, sets to -Math.PI/2 so front is defined correctly. gyroAngle = -Math.PI/2; } //Linear directions in case you want to do straight lines. if(gamepad1.dpad_right){ stick_x = -1; if (gamepad1.left_bumper){ stick_x = -.5; } } else if(gamepad1.dpad_left){ stick_x = 1; if (gamepad1.left_bumper){ stick_x = .5; } } if(gamepad1.dpad_up){ stick_y = 1; if (gamepad1.left_bumper){ stick_y = .5; } } else if(gamepad1.dpad_down){ stick_y = -1; if (gamepad1.left_bumper){ stick_y = -.5; } } //MOVEMENT theta = Math.atan2(stick_y, stick_x) - gyroAngle - (Math.PI / 2); Px = Math.sqrt(Math.pow(stick_x, 2) + Math.pow(stick_y, 2)) * (Math.sin(theta + Math.PI / 4)); Py = Math.sqrt(Math.pow(stick_x, 2) + Math.pow(stick_y, 2)) * (Math.sin(theta - Math.PI / 4)); telemetry.addData("Stick_X", stick_x); telemetry.addData("Stick_Y", stick_y); telemetry.addData("Magnitude", Math.sqrt(Math.pow(stick_x, 2) + Math.pow(stick_y, 2))); telemetry.addData("Front Left", Py - rotate); telemetry.addData("Back Left", Px - rotate); telemetry.addData("Back Right", Py + rotate); telemetry.addData("Front Right", Px + rotate); frontLeft.setPower(-(Py - rotate)); backLeft.setPower(-(Px - rotate)); backRight.setPower(-(Py + rotate)); frontRight.setPower(-(Px + rotate)); } public void resetAngle(){ if(gamepad1.a){ reset_angle = getHeading() + reset_angle; } } public double getHeading(){ Orientation angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); double heading = angles.firstAngle; if(heading < -180) { heading = heading + 360; } else if(heading > 180){ heading = heading - 360; } heading = heading - reset_angle; return heading; } }