blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
b4739ac7510b74a3b4e3de5aaf1b2bd8046a457e
Java
tmdgusya/roach-web-server
/src/main/java/core/response/HttpResponseBuilder.java
UTF-8
1,795
2.71875
3
[]
no_license
package core.response; import core.Cookie; import core.Header; import java.util.Map; public class HttpResponseBuilder { private Header header; private Cookie cookie; private Map<String, String> parameters; private Map<String, String> responseBody; public HttpResponseBuilder setHeader(Header header) { this.header = header; return this; } public HttpResponseBuilder addHeader(String key, String value) { this.header.addHeader(key, value); return this; } public HttpResponseBuilder setCookie(Cookie cookie) { this.cookie = cookie; return this; } public HttpResponseBuilder addCookie(String key, String value) { this.cookie.addCookie(key, value); return this; } public HttpResponseBuilder setParameters(Map<String, String> parameters) { this.parameters = parameters; return this; } public HttpResponseBuilder addParameters(String key, String value) { if(parameters.containsKey(key)) { throw new IllegalArgumentException("Parameter 에 해당 Key 가 이미 존재합니다."); } parameters.put(key, value); return this; } public HttpResponseBuilder setResponseBody(Map<String, String> responseBody) { this.responseBody = responseBody; return this; } public HttpResponseBuilder addResponseBody(String key, String value) { if(responseBody.containsKey(key)) { throw new IllegalArgumentException("Response Body 에 해당 Key 가 이미 존재합니다."); } responseBody.put(key, value); return this; } public HttpResponse build() { return new HttpResponse(header, cookie, parameters, responseBody); } }
true
5f89fd04e34e9959b50dc483485d16f4f9bb636e
Java
ybark/Spring2020B18_Java
/src/REPLIT/_Assesment_1_4_Calorie_Burn.java
UTF-8
625
3.125
3
[]
no_license
package REPLIT; import java.util.Scanner; public class _Assesment_1_4_Calorie_Burn { public static void main(String[] args) { Scanner scan = new Scanner(System.in); double weight = 0; double cal = 0; System.out.println("Enter weight in pounds:"); weight = scan.nextDouble(); weight = weight/2.2; double runs = (0.0175 * (6*60) * weight); double basket = (0.0175 * (8*60) * weight); double sleep = (0.0175 * 60 * weight); int result = (int) (runs + basket + sleep); System.out.println("Calories Burned: "+result); } }
true
42008dda165f79d5aaf7a22a14aeef8074577c22
Java
LaraMou/my-app-keycloak
/src/main/java/com/example/application/views/admin/AdminView.java
UTF-8
1,658
2.125
2
[ "Unlicense" ]
permissive
package com.example.application.views.admin; import com.example.application.services.ClientService; import com.vaadin.flow.component.html.Anchor; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.H1; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.router.Route; import org.keycloak.KeycloakPrincipal; import org.keycloak.KeycloakSecurityContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; @Route("admin") public class AdminView extends Div { public AdminView(@Autowired ClientService clientService){ String adminPage= clientService.getAdminPage(); add(new H1(adminPage)); if(!SecurityContextHolder.getContext() .getAuthentication().getPrincipal().equals("anonymousUser")) { KeycloakPrincipal principal = (KeycloakPrincipal) SecurityContextHolder.getContext() .getAuthentication().getPrincipal(); KeycloakSecurityContext keycloakSecurityContext = principal.getKeycloakSecurityContext(); String preferredUsername = keycloakSecurityContext.getIdToken().getPreferredUsername(); Anchor logout = new Anchor("http://localhost:9991/auth/realms/Demo/protocol/openid-connect/logout?redirect_uri=" + "http://localhost:8080/", "Logout"); add(new HorizontalLayout(new Span(preferredUsername), logout)); } else{ add(new Span("No Logged in User")); } } }
true
347d286a335e7e95afc1ad422c142a1aeb7be14c
Java
eviatarc/OOP-java-verifier
/main/SMethod.java
UTF-8
3,035
3.546875
4
[]
no_license
package oop.ex6.main; import oop.ex6.Sexcepsion.CalledToUnfamilierMethod; import oop.ex6.Sexcepsion.MethodCallWithInvalidParameters; import java.util.ArrayList; /** * a class that represent a method class and also might be used as scoop object like a loop of a condition * but first of all it works as a class of methods than a condition for example is a private case * of a method */ public class SMethod { ArrayList<SVariable> allVariables; ArrayList<SVariable> myCallVariables; String nameMethod; ArrayList<SVariable> knownVariabels; ArrayList<SVariable> localVariables; /** * constructor * @param nameMethod - the name of the method */ public SMethod(String nameMethod){ this.nameMethod = nameMethod; this.knownVariabels = new ArrayList<>(); this.myCallVariables = new ArrayList<>(); this.localVariables = new ArrayList<>(); this.allVariables = new ArrayList<>(); } /** * help function for ourselfs to check the method object * @return a method represented as a string */ @Override public String toString() { return this.nameMethod +" this VARIABLES " + this.knownVariabels; } /** * a check function for the method object that checks if the given variable is known * @param varThatIWantToUse - the variable that want to check if the method knows * @return true if the method know this variable */ public boolean doIKnowThisVar(SVariable varThatIWantToUse){ String relName = varThatIWantToUse.name; for(int eachVarIndex = 0; eachVarIndex<knownVariabels.size(); eachVarIndex++){ if(knownVariabels.get(eachVarIndex).name.equals(varThatIWantToUse.name)){ return true; } } return false; } /** * @param methodsArray - the array of the collected methods * @param nameMethod - the method that is called * @param typesArray - the array that holds all the types of the vars * that the method called with * @return - boolean that is never used but good for ourself to check * @throws MethodCallWithInvalidParameters * @throws CalledToUnfamilierMethod */ public static boolean checkValidCall(ArrayList<SMethod> methodsArray,String nameMethod, ArrayList<String> typesArray)throws MethodCallWithInvalidParameters, CalledToUnfamilierMethod { for(int h=0; h<methodsArray.size();h++){ SMethod cuurToCheck = methodsArray.get(h); if(nameMethod.equals(cuurToCheck.nameMethod)){ for(int p=0;p<cuurToCheck.myCallVariables.size();p++){ if(!cuurToCheck.myCallVariables.get(p).type.equals(typesArray.get(p))){ throw new MethodCallWithInvalidParameters(); } } return true; } } throw new CalledToUnfamilierMethod(); } }
true
61f8115613df0ae76a887102b657d5ab707e3532
Java
TNG/keycloak-mock
/mock/src/test/java/com/tngtech/keycloakmock/impl/UrlConfigurationTest.java
UTF-8
10,042
2
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.tngtech.keycloakmock.impl; import static com.tngtech.keycloakmock.api.ServerConfig.aServerConfig; import static org.assertj.core.api.Assertions.assertThat; import com.tngtech.keycloakmock.api.ServerConfig; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; class UrlConfigurationTest { private static final String DEFAULT_HOSTNAME = "defaultHost"; private static final String DEFAULT_REALM = "defaultRealm"; private static final String REQUEST_HOST = "requestHost"; private static final String REQUEST_HOST_NO_CONTEXT_PATH = "requestHostNoContextPath"; private static final String REQUEST_HOST_CUSTOM_CONTEXT_PATH = "requestHostCustomContextPath"; private static final String REQUEST_REALM = "requestRealm"; private UrlConfiguration urlConfiguration; private static Stream<Arguments> server_config_and_expected_base_url() { return Stream.of( Arguments.of(aServerConfig().build(), "http://localhost:8000"), Arguments.of( aServerConfig().withDefaultHostname(DEFAULT_HOSTNAME).build(), "http://defaultHost:8000"), Arguments.of(aServerConfig().withPort(80).build(), "http://localhost"), Arguments.of(aServerConfig().withPort(443).build(), "http://localhost:443"), Arguments.of(aServerConfig().withTls(true).withPort(80).build(), "https://localhost:80"), Arguments.of(aServerConfig().withTls(true).withPort(443).build(), "https://localhost")); } private static Stream<Arguments> server_config_and_expected_issuer_url() { return Stream.of( Arguments.of(aServerConfig().build(), "http://localhost:8000/auth/realms/master"), Arguments.of( aServerConfig() .withDefaultHostname(DEFAULT_HOSTNAME) .withDefaultRealm(DEFAULT_REALM) .build(), "http://defaultHost:8000/auth/realms/defaultRealm"), Arguments.of(aServerConfig().withPort(80).build(), "http://localhost/auth/realms/master"), Arguments.of( aServerConfig().withTls(true).withPort(443).build(), "https://localhost/auth/realms/master"), Arguments.of( aServerConfig().withNoContextPath().build(), "http://localhost:8000/realms/master"), Arguments.of( aServerConfig().withContextPath("auth").build(), "http://localhost:8000/auth/realms/master"), Arguments.of( aServerConfig().withContextPath("/auth").build(), "http://localhost:8000/auth/realms/master"), Arguments.of( aServerConfig().withContextPath("/context-path").build(), "http://localhost:8000/context-path/realms/master"), Arguments.of( aServerConfig().withContextPath("complex/context/path").build(), "http://localhost:8000/complex/context/path/realms/master")); } private static Stream<Arguments> request_host_and_realm_and_expected() { return Stream.of( Arguments.of(null, null, "http://localhost:8000/auth/realms/master"), Arguments.of(REQUEST_HOST, null, "http://requestHost/auth/realms/master"), Arguments.of(null, REQUEST_REALM, "http://localhost:8000/auth/realms/requestRealm"), Arguments.of(REQUEST_HOST, REQUEST_REALM, "http://requestHost/auth/realms/requestRealm")); } private static Stream<Arguments> request_host_and_realm_and_expected_with_no_context_path() { return Stream.of( Arguments.of( REQUEST_HOST_NO_CONTEXT_PATH, null, "http://requestHostNoContextPath/realms/master"), Arguments.of( REQUEST_HOST_NO_CONTEXT_PATH, REQUEST_REALM, "http://requestHostNoContextPath/realms/requestRealm")); } private static Stream<Arguments> request_host_and_realm_and_expected_with_custom_context_path() { return Stream.of( Arguments.of( REQUEST_HOST_CUSTOM_CONTEXT_PATH, null, "http://requestHostCustomContextPath/custom/context/path/realms/master"), Arguments.of( REQUEST_HOST_CUSTOM_CONTEXT_PATH, REQUEST_REALM, "http://requestHostCustomContextPath/custom/context/path/realms/requestRealm")); } @ParameterizedTest @MethodSource("server_config_and_expected_base_url") void base_url_is_generated_correctly(ServerConfig serverConfig, String expected) { urlConfiguration = new UrlConfiguration(serverConfig); assertThat(urlConfiguration.getBaseUrl()).hasToString(expected); } @ParameterizedTest @MethodSource("server_config_and_expected_issuer_url") void issuer_url_is_generated_correctly(ServerConfig serverConfig, String expected) { urlConfiguration = new UrlConfiguration(serverConfig); assertThat(urlConfiguration.getIssuer()).hasToString(expected); } @ParameterizedTest @MethodSource("request_host_and_realm_and_expected") void context_parameters_are_used_correctly( String requestHost, String requestRealm, String expected) { urlConfiguration = new UrlConfiguration(aServerConfig().build()).forRequestContext(requestHost, requestRealm); assertThat(urlConfiguration.getIssuer()).hasToString(expected); } @ParameterizedTest @MethodSource("request_host_and_realm_and_expected_with_no_context_path") void context_parameters_are_used_correctly_for_server_config_with_no_context_path( String requestHost, String requestRealm, String expected) { urlConfiguration = new UrlConfiguration(aServerConfig().withNoContextPath().build()) .forRequestContext(requestHost, requestRealm); assertThat(urlConfiguration.getIssuer()).hasToString(expected); } @ParameterizedTest @MethodSource("request_host_and_realm_and_expected_with_custom_context_path") void context_parameters_are_used_correctly_for_server_config_with_custom_context_path( String requestHost, String requestRealm, String expected) { urlConfiguration = new UrlConfiguration(aServerConfig().withContextPath("custom/context/path").build()) .forRequestContext(requestHost, requestRealm); assertThat(urlConfiguration.getIssuer()).hasToString(expected); } @Test void urls_are_correct() { urlConfiguration = new UrlConfiguration(aServerConfig().build()); assertThat(urlConfiguration.getIssuerPath()) .hasToString("http://localhost:8000/auth/realms/master/"); assertThat(urlConfiguration.getOpenIdPath("1234")) .hasToString("http://localhost:8000/auth/realms/master/protocol/openid-connect/1234"); assertThat(urlConfiguration.getAuthorizationEndpoint()) .hasToString("http://localhost:8000/auth/realms/master/protocol/openid-connect/auth"); assertThat(urlConfiguration.getEndSessionEndpoint()) .hasToString("http://localhost:8000/auth/realms/master/protocol/openid-connect/logout"); assertThat(urlConfiguration.getJwksUri()) .hasToString("http://localhost:8000/auth/realms/master/protocol/openid-connect/certs"); assertThat(urlConfiguration.getTokenEndpoint()) .hasToString("http://localhost:8000/auth/realms/master/protocol/openid-connect/token"); } @Test void urls_are_correct_with_no_context_path() { urlConfiguration = new UrlConfiguration(aServerConfig().withNoContextPath().build()); assertThat(urlConfiguration.getIssuerPath()) .hasToString("http://localhost:8000/realms/master/"); assertThat(urlConfiguration.getOpenIdPath("1234")) .hasToString("http://localhost:8000/realms/master/protocol/openid-connect/1234"); assertThat(urlConfiguration.getAuthorizationEndpoint()) .hasToString("http://localhost:8000/realms/master/protocol/openid-connect/auth"); assertThat(urlConfiguration.getEndSessionEndpoint()) .hasToString("http://localhost:8000/realms/master/protocol/openid-connect/logout"); assertThat(urlConfiguration.getJwksUri()) .hasToString("http://localhost:8000/realms/master/protocol/openid-connect/certs"); assertThat(urlConfiguration.getTokenEndpoint()) .hasToString("http://localhost:8000/realms/master/protocol/openid-connect/token"); } @Test void urls_are_correct_with_custom_context_path() { urlConfiguration = new UrlConfiguration(aServerConfig().withContextPath("/custom/context/path").build()); assertThat(urlConfiguration.getIssuerPath()) .hasToString("http://localhost:8000/custom/context/path/realms/master/"); assertThat(urlConfiguration.getOpenIdPath("1234")) .hasToString( "http://localhost:8000/custom/context/path/realms/master/protocol/openid-connect/1234"); assertThat(urlConfiguration.getAuthorizationEndpoint()) .hasToString( "http://localhost:8000/custom/context/path/realms/master/protocol/openid-connect/auth"); assertThat(urlConfiguration.getEndSessionEndpoint()) .hasToString( "http://localhost:8000/custom/context/path/realms/master/protocol/openid-connect/logout"); assertThat(urlConfiguration.getJwksUri()) .hasToString( "http://localhost:8000/custom/context/path/realms/master/protocol/openid-connect/certs"); assertThat(urlConfiguration.getTokenEndpoint()) .hasToString( "http://localhost:8000/custom/context/path/realms/master/protocol/openid-connect/token"); } @Test void port_is_correct() { urlConfiguration = new UrlConfiguration(aServerConfig().withPort(1234).build()); assertThat(urlConfiguration.getPort()).isEqualTo(1234); } @ParameterizedTest @ValueSource(booleans = {true, false}) void protocol_is_correct(boolean tls) { urlConfiguration = new UrlConfiguration(aServerConfig().withTls(tls).build()); assertThat(urlConfiguration.getProtocol()).isEqualTo(tls ? Protocol.HTTPS : Protocol.HTTP); } }
true
222d2b049ef6d3dcc9dac01846a532af19ccf931
Java
hwillians/approche-objet
/approche-objet/src/interfaces/TestObjetGeometrique.java
UTF-8
432
3.296875
3
[]
no_license
package interfaces; public class TestObjetGeometrique { public static void main(String[] args) { ObjetGeometrique[] tabGeo = new ObjetGeometrique[2]; tabGeo[0] = new Cercle(2.5); tabGeo[1] = new Rectangle(2, 4); for (int i = 0; i < tabGeo.length; i++) { System.out.println("Le perimètre du " + tabGeo[i].getType() + " est " + tabGeo[i].perimetre() + " et sa surface est " + tabGeo[i].surface()); } } }
true
121c71ebbd65b708a8c4f7b12ca12f7c57982410
Java
malbac/xtext
/web/org.eclipse.xtext.web.example.jetty/src/main/xtend-gen/org/eclipse/xtext/web/example/jetty/MyXtextServlet.java
UTF-8
3,646
1.671875
2
[ "LicenseRef-scancode-generic-cla" ]
no_license
/** * Copyright (c) 2015 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.xtext.web.example.jetty; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.binder.AnnotatedBindingBuilder; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.binder.ScopedBindingBuilder; import com.google.inject.name.Named; import com.google.inject.name.Names; import javax.servlet.annotation.WebServlet; import org.eclipse.xtext.ide.LexerIdeBindings; import org.eclipse.xtext.ide.editor.contentassist.antlr.IContentAssistParser; import org.eclipse.xtext.ide.editor.contentassist.antlr.internal.Lexer; import org.eclipse.xtext.idea.example.entities.EntitiesRuntimeModule; import org.eclipse.xtext.idea.example.entities.EntitiesStandaloneSetup; import org.eclipse.xtext.idea.example.entities.ide.contentassist.antlr.EntitiesParser; import org.eclipse.xtext.idea.example.entities.ide.contentassist.antlr.internal.InternalEntitiesLexer; import org.eclipse.xtext.service.AbstractGenericModule; import org.eclipse.xtext.web.server.persistence.FileResourceHandler; import org.eclipse.xtext.web.server.persistence.IResourceBaseProvider; import org.eclipse.xtext.web.server.persistence.IServerResourceHandler; import org.eclipse.xtext.web.server.persistence.ResourceBaseProviderImpl; import org.eclipse.xtext.web.servlet.XtextServlet; import org.eclipse.xtext.xbase.lib.Exceptions; @WebServlet(name = "Xtext Services", urlPatterns = "/xtext-services/*") @SuppressWarnings("all") public class MyXtextServlet extends XtextServlet { public static class EntitiesIdeModule extends AbstractGenericModule { public ScopedBindingBuilder configureContentAssistLexer(final Binder binder) { AnnotatedBindingBuilder<Lexer> _bind = binder.<Lexer>bind(Lexer.class); Named _named = Names.named(LexerIdeBindings.CONTENT_ASSIST); LinkedBindingBuilder<Lexer> _annotatedWith = _bind.annotatedWith(_named); return _annotatedWith.to(InternalEntitiesLexer.class); } public Class<? extends IContentAssistParser> bindIContentAssistParser() { return EntitiesParser.class; } public Class<? extends IServerResourceHandler> bindIServerResourceHandler() { return FileResourceHandler.class; } public void configureResourceBaseProvider(final Binder binder) { AnnotatedBindingBuilder<IResourceBaseProvider> _bind = binder.<IResourceBaseProvider>bind(IResourceBaseProvider.class); String _resourceBase = this.getResourceBase(); ResourceBaseProviderImpl _resourceBaseProviderImpl = new ResourceBaseProviderImpl(_resourceBase); _bind.toInstance(_resourceBaseProviderImpl); } private String getResourceBase() { return "./test-files"; } } @Override public void init() { try { new EntitiesStandaloneSetup() { @Override public Injector createInjector() { EntitiesRuntimeModule _entitiesRuntimeModule = new EntitiesRuntimeModule(); MyXtextServlet.EntitiesIdeModule _entitiesIdeModule = new MyXtextServlet.EntitiesIdeModule(); return Guice.createInjector(_entitiesRuntimeModule, _entitiesIdeModule); } }.createInjectorAndDoEMFRegistration(); super.init(); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } } }
true
ffe883da9859fba768715eed3fd030926e4383a6
Java
parkjongwoo/basic_java
/src/com/team/socket/BroadCastServer.java
UTF-8
1,989
3.078125
3
[]
no_license
package com.team.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; public class BroadCastServer implements Runnable { ServerSocket ss; ArrayList<BroadCastChatService> cl; int tcpPORT = 5000; int udpPORT = 3001; @Override public void run() { try { ss = new ServerSocket(tcpPORT); System.out.println("접속대기중:"+ss); } catch (IOException e) { e.printStackTrace(); } cl = new ArrayList<BroadCastChatService>(); while(true) { try { Socket s = ss.accept(); System.out.println("접속중:"+s); BroadCastChatService bs = new BroadCastChatService(s); bs.start(); cl.add(bs); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class BroadCastChatService extends Thread{ String myname = "guest"; BufferedReader in; OutputStream out; public BroadCastChatService(Socket s) { try { in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = s.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { while(true) { try { String msg = in.readLine(); if(msg == null) return; System.out.println("msg: "+msg); putMessageAll(msg); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } } } void putMessageAll( String msg ) { for( int i =0 ; i<cl.size() ; i++ ) { BroadCastChatService cs = ( BroadCastChatService ) cl.get(i); try { cs.putMessage(msg); }catch( Exception e ) { cl.remove(i--); } } } void putMessage( String msg ) throws Exception { out.write( (msg+"\r\n").getBytes() ); } } public static void main(String[] args) { new Thread(new BroadCastServer()).start(); } }
true
857b21e9919be06dd773eec6a507d5941d6eaaa5
Java
jarvanstack/springboot
/sb-03-JSR303数据校验和多环境配置/src/test/java/com/bmft/demo03/JSR303校验02.java
UTF-8
380
1.804688
2
[]
no_license
package com.bmft.demo03; import com.bmft.demo03.pojo.Dog02; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class JSR303校验02 { @Autowired private Dog02 dog; @Test public void test(){ System.err.println(dog); } }
true
a2008ce0a8412d2d344a0c9ce399bd808e533a62
Java
Wilczek01/alwin-projects
/alwin-middleware-grapescode/alwin-core-api/src/main/java/com/codersteam/alwin/core/api/model/demand/FormalDebtCollectionInvoiceDto.java
UTF-8
2,399
1.960938
2
[]
no_license
package com.codersteam.alwin.core.api.model.demand; import java.math.BigDecimal; import java.util.Date; /** * Faktura w procesie windykacji formalnej * * @author Tomasz Sliwinski */ public class FormalDebtCollectionInvoiceDto { private Long id; private String invoiceNumber; private String contractNumber; private Date issueDate; private Date realDueDate; private String currency; private BigDecimal netAmount; private BigDecimal grossAmount; private BigDecimal currentBalance; private Long leoId; public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getInvoiceNumber() { return invoiceNumber; } public void setInvoiceNumber(final String invoiceNumber) { this.invoiceNumber = invoiceNumber; } public String getContractNumber() { return contractNumber; } public void setContractNumber(final String contractNumber) { this.contractNumber = contractNumber; } public Date getIssueDate() { return issueDate; } public void setIssueDate(final Date issueDate) { this.issueDate = issueDate; } public Date getDueDate() { return realDueDate; } public void setDueDate(final Date dueDate) { this.realDueDate = dueDate; } public Date getRealDueDate() { return realDueDate; } public void setRealDueDate(final Date realDueDate) { this.realDueDate = realDueDate; } public String getCurrency() { return currency; } public void setCurrency(final String currency) { this.currency = currency; } public BigDecimal getNetAmount() { return netAmount; } public void setNetAmount(final BigDecimal netAmount) { this.netAmount = netAmount; } public BigDecimal getGrossAmount() { return grossAmount; } public void setGrossAmount(final BigDecimal grossAmount) { this.grossAmount = grossAmount; } public BigDecimal getCurrentBalance() { return currentBalance; } public void setCurrentBalance(final BigDecimal currentBalance) { this.currentBalance = currentBalance; } public Long getLeoId() { return leoId; } public void setLeoId(final Long leoId) { this.leoId = leoId; } }
true
4f2b5e350ca8ae73612b867b25c36e2df12f75f5
Java
smuvw/Java_Examples
/JavaExample/src/MultiThreading/MyThread.java
UTF-8
462
3.140625
3
[]
no_license
package MultiThreading; public class MyThread extends Thread{ //if no run method the by default Thread class Run will execute public void run(){ for (int i=1;i<=10;i++){ System.out.println("Child Thread"); } } // if we override start method it wont create new thread and wont call Thread class "start" method /*public void start(){ System.out.println("start method from MyThread class"); }*/ }
true
1890ad4926b0578f01f7e8616bc022a5219bcc96
Java
ElvisAgui/2021-juego-SerpientesYEscaleras
/src/main/java/com/proyecto1ipc/principal/Principal.java
UTF-8
338
1.882813
2
[]
no_license
package com.proyecto1ipc.principal; import com.proyecto1ipc.frontend.VentanaInicial; /** * * @author elvis_agui */ public class Principal { public static void main(String[] args) { VentanaInicial principal = new VentanaInicial(); principal.setVisible(true); } }
true
5fa59632792b51ff87e5454b53ccc07736d81641
Java
miraalmamun/PageObjectModelPageFactory
/src/main/java/com/qtpselenium/facebook/pom/pages/session/ProfilePage4.java
UTF-8
459
1.710938
2
[]
no_license
/* package com.qtpselenium.facebook.pom.pages.session; import org.openqa.selenium.WebDriver; import com.qtpselenium.facebook.pom.base.BasePage; import com.relevantcodes.extentreports.ExtentTest; //Before test this program please extents BasePage class public class ProfilePage4 extends BasePage{ ExtentTest test; public ProfilePage4(WebDriver driver, ExtentTest test) { super(driver); this.test = test; } public void verifyProfile() { } } */
true
da199046fa829a9f17c5633bc4a3088e18468812
Java
CarlosH2020/Condicional_Java
/operadores_ex2.java
UTF-8
1,155
3.171875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package operadoreslogicos; import java.util.Scanner; /** * * @author Root */ public class operadores_ex2 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner leitor = new Scanner(System.in); int idade; System.out.print("Idade do nadador:"); idade = leitor.nextInt(); System.out.print("\n"); if(idade >= 5 && idade <= 10){ System.out.println("Você se encaixa na cotegoria (Infantil)"); }else if(idade >= 11 && idade <= 17){ System.out.println("Você se encaixa na cotegoria (Juvenil)"); }else if(idade >= 18){ System.out.println("Você se encaixa na cotegoria (Adulta)"); }else{ System.out.println("Você ainda não está preparado para participar"); } } }
true
fcce23cd10c0e4c267e857ba676c4bc07b9f872b
Java
radhikakadiri/amex-demo-radhika
/demo/src/main/java/com/population/demo/pojo/CountryPopInfo.java
UTF-8
306
1.984375
2
[]
no_license
package com.population.demo.pojo; public class CountryPopInfo { String ccname; int pop; public String getCcname() { return ccname; } public void setCcname(String ccname) { this.ccname = ccname; } public int getPop() { return pop; } public void setPop(int pop) { this.pop = pop; } }
true
79353aa8542a30cb389a834ea68bd639a7e30d62
Java
thecodemonkeyau/taskadapter
/webshared/src/main/java/com/taskadapter/common/ui/MappingBuilder.java
UTF-8
1,529
2.40625
2
[]
no_license
package com.taskadapter.common.ui; import com.taskadapter.connector.FieldRow; import com.taskadapter.connector.definition.ExportDirection; import com.taskadapter.model.Field; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class MappingBuilder { public static List<FieldRow<?>> build(List<FieldMapping<?>> newMappings, ExportDirection exportDirection) { return newMappings.stream() .filter(FieldMapping::isSelected) .map(mapping -> buildRow(mapping, exportDirection)) .collect(Collectors.toList()); } private static <T> FieldRow<T> buildRow(FieldMapping<T> mapping, ExportDirection exportDirection) { return new FieldRow<>( getSourceField(mapping, exportDirection), getTargetField(mapping, exportDirection), mapping.getDefaultValue()); } public static <T> Optional<Field<T>> getSourceField(FieldMapping<T> fieldMapping, ExportDirection exportDirection) { return switch (exportDirection) { case RIGHT -> fieldMapping.getFieldInConnector1(); case LEFT -> fieldMapping.getFieldInConnector2(); }; } public static <T> Optional<Field<T>> getTargetField(FieldMapping<T> fieldMapping, ExportDirection exportDirection) { return switch (exportDirection) { case RIGHT -> fieldMapping.getFieldInConnector2(); case LEFT -> fieldMapping.getFieldInConnector1(); }; } }
true
0646465177b4a764635ab179b42502cb38defa79
Java
iheos/iheos-metadata-editor
/docentryeditor/src/main/java/gov/nist/hit/ds/docentryeditor/client/editor/widgets/codedterm/CodedTermFactory.java
UTF-8
1,180
2.515625
3
[]
no_license
package gov.nist.hit.ds.docentryeditor.client.editor.widgets.codedterm; import com.google.gwt.core.client.GWT; import gov.nist.hit.ds.docentryeditor.client.generics.GridModelFactory; import gov.nist.hit.ds.docentryeditor.shared.model.CodedTerm; import gov.nist.hit.ds.docentryeditor.shared.model.CodingScheme; import gov.nist.hit.ds.docentryeditor.shared.model.String256; /** * Factory class that creates an instance of CodedTerm for a GridEditor * (pattern used to solve a problem of java reflection in GWT). */ public enum CodedTermFactory implements GridModelFactory<CodedTerm> { INSTANCE; private int counter=0; /** * This methods returns a new instance of CodedTerm in order to avoid reflection in GWT. * @return new instance of CodedTerm. */ @Override public CodedTerm newInstance() { counter++; CodedTerm e = GWT.create(CodedTerm.class); e.setDisplayName(new String256("New Coded Term name")); e.setCodingScheme(new CodingScheme(new String256("New Coded Term coding scheme"))); e.setCode(new String256("New Coded term code "+counter)); return e; } }
true
41cdd810aeaa75a05573da99c5c857bb0354c81c
Java
Anand-KumarJha/ARRAYS---Java-Practice
/Minimum Domino Rotations For Equal Row/src/Main.java
UTF-8
386
2.59375
3
[]
no_license
public class Main { public static void main(String[] args) { Solution solution = new Solution(); FastSolution fastSolution = new FastSolution(); System.out.println(solution.minDominoRotations(new int[]{2,1,2,4,2,2},new int[]{5,2,6,2,3,2})); System.out.println(fastSolution.minDominoRotations(new int[]{2,1,2,4,2,2},new int[]{5,2,6,2,3,2})); } }
true
3efb789a585a1c1eca5d72845d4a628217c2b690
Java
MubarkAlharthi/themoviedb-latest-Movie
/src/application/Http_Request.java
UTF-8
9,698
2.921875
3
[]
no_license
package application; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.LinkedList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Http_Request { /** * Convert the {@link InputStream} into a String which contains the * whole JSON response from the server. */ private static String readFromStream(InputStream inputStream) throws IOException { StringBuilder output = new StringBuilder(); if (inputStream != null) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8")); BufferedReader reader = new BufferedReader(inputStreamReader); String line = reader.readLine(); while (line != null) { output.append(line); line = reader.readLine(); } } return output.toString(); } /** * Returns new URL object from the given string URL. */ private static URL createUrl(String stringUrl) { URL url = null; try { url = new URL(stringUrl); } catch (MalformedURLException e) { System.out.println("Error with creating URL "); } return url; } /** * Make an HTTP request to the given URL and return a String as the response. */ public String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // If the request was successful (response code 200), // then read the input stream and parse the response. if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { System.out.println("There was an Error"); } } catch (IOException e) { System.out.println("There was an Error in file"); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { inputStream.close(); } } return jsonResponse; } /** * Get the Genre id from genres_id JSON and map it to its corresponding name * @param genres_id * @return List of Genres that describe the movie */ public LinkedList<Genre> genres_for_Movie(JSONArray genres_id){ //in case the movie does not has type from the API if(genres_id.length()==0) return null; LinkedList<Genre> genres = new LinkedList<Genre>(); //after this loop will have the id of the type of the movie for (int i = 0; i < genres_id.length(); i++) { Genre genre =new Genre(); int genre_id=genres_id.getInt(i); genre.setId(genre_id); genres.add(genre); } // Now we try to find the name of the type that corresponding to the id we got from JSON for (int i = 0; i < genres.size(); i++) { String type = MovieInfo.find_genre_Type(genres.get(i).getId()); genres.get(i).setName(type); } return genres; } /** * Get all available Genres From API and add it to Genres list in MovieInfo Class * @param genres_JSON */ private void extract_genres_FromJson() throws Exception { URL url_genres = createUrl("http://api.themoviedb.org/3/genre/movie/list?api_key=19bc4424ccaa754c5d149f7fcb22630b"); String genres_JSON = makeHttpRequest(url_genres); // If the JSON string is empty or null, then return early. if (genres_JSON.isEmpty()) { return; } try { JSONObject baseJsonResponse = new JSONObject(genres_JSON); JSONArray genres = baseJsonResponse.getJSONArray("genres"); for(int i=0;i<genres.length();i++) { JSONObject genre_JSONObject = genres.getJSONObject(i); MovieInfo.genres.add(new Genre(genre_JSONObject.getInt("id"), genre_JSONObject.getString("name"))); } } catch (JSONException e) { System.out.println("Problem parsing the earthquake JSON results"); } } /** * Extract the movies Details JSON_Response * @param Movie_JSON * @return The list of movies in the JSON_Response */ public LinkedList<MovieInfo> extract_searched_Movie_FromJson(String name) { // If the JSON string is empty or null, then return early. LinkedList<MovieInfo> extracted_Movies = new LinkedList<MovieInfo>(); String Movie_JSON=""; try { URL url_Movie = createUrl("https://api.themoviedb.org/3/search/movie?api_key=19bc4424ccaa754c5d149f7fcb22630b&query="+name); Movie_JSON = makeHttpRequest(url_Movie); if (Movie_JSON.isEmpty()) { return null; } JSONObject baseJsonResponse = new JSONObject(Movie_JSON); JSONArray movies = baseJsonResponse.getJSONArray("results"); String poster_Path;// poster_Path declare hare because sometimes the poster comes from the API equal null for (int i = 0; i < movies.length(); i++) { JSONObject movie_JSONObject = movies.getJSONObject(i); String title=movie_JSONObject.getString("title"); if(movie_JSONObject.isNull("poster_path")) poster_Path="N/A"; else poster_Path=movie_JSONObject.getString("poster_path"); String over_View = movie_JSONObject.getString("overview"); int id= movie_JSONObject.getInt("id"); double vote_average = movie_JSONObject.getDouble("vote_average"); //try to get type of the movie if it is exiset LinkedList<Genre> kind_of_the_movie = genres_for_Movie(movie_JSONObject.getJSONArray("genre_ids")); extracted_Movies.add(new MovieInfo(title, poster_Path, over_View, kind_of_the_movie, id, vote_average)); } return extracted_Movies; } catch (JSONException e) { System.out.println(e.getMessage()); }catch (IOException e) { // TODO: handle exception System.out.println(e.getMessage()); } return null; } /** * Extract the movies Details JSON_Response * @param Movie_JSON * @return The list of movies in the JSON_Response */ public LinkedList<MovieInfo> extract_latest_Movie_FromJson() { // If the JSON string is empty or null, then return early. LinkedList<MovieInfo> extracted_Movies = new LinkedList<MovieInfo>(); String Movie_JSON=""; try { URL url_Movie = createUrl("https://api.themoviedb.org/3/discover/movie?api_key=19bc4424ccaa754c5d149f7fcb22630b&page=1&sort_by=release_date.desc&year=2018"); Movie_JSON = makeHttpRequest(url_Movie); if (Movie_JSON.isEmpty()) { return null; } JSONObject baseJsonResponse = new JSONObject(Movie_JSON); JSONArray movies = baseJsonResponse.getJSONArray("results"); String poster_Path;// poster_Path declare hare because sometimes the poster comes from the API equal null for (int i = 0; i < movies.length(); i++) { JSONObject movie_JSONObject = movies.getJSONObject(i); String title=movie_JSONObject.getString("title"); if(movie_JSONObject.isNull("poster_path")) poster_Path="N/A"; else poster_Path=movie_JSONObject.getString("poster_path"); String over_View = movie_JSONObject.getString("overview"); int id= movie_JSONObject.getInt("id"); double vote_average = movie_JSONObject.getDouble("vote_average"); //try to get type of the movie if it is exiset LinkedList<Genre> kind_of_the_movie = genres_for_Movie(movie_JSONObject.getJSONArray("genre_ids")); extracted_Movies.add(new MovieInfo(title, poster_Path, over_View, kind_of_the_movie, id, vote_average)); } return extracted_Movies; } catch (JSONException e) { System.out.println(e.getMessage()); }catch (IOException e) { // TODO: handle exception System.out.println(e.getMessage()); } return null; } public Http_Request() { try { // prepare the list of available genres from API extract_genres_FromJson(); } catch (Exception e) { // TODO: handle exception System.out.println(e.getMessage()); } } }
true
fee397d23e2563493f89f5b231c9bc354497b0d4
Java
tyamgin/AiCup
/CodeRacing/local-runner/decompile/com/google/common/collect/SingletonImmutableBiMap.java
UTF-8
1,981
2.375
2
[ "Apache-2.0" ]
permissive
package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Map.Entry; @GwtCompatible(serializable=true, emulated=true) final class SingletonImmutableBiMap extends ImmutableBiMap { final transient Object singleKey; final transient Object singleValue; transient ImmutableBiMap inverse; SingletonImmutableBiMap(Object paramObject1, Object paramObject2) { this.singleKey = paramObject1; this.singleValue = paramObject2; } private SingletonImmutableBiMap(Object paramObject1, Object paramObject2, ImmutableBiMap paramImmutableBiMap) { this.singleKey = paramObject1; this.singleValue = paramObject2; this.inverse = paramImmutableBiMap; } SingletonImmutableBiMap(Map.Entry paramEntry) { this(paramEntry.getKey(), paramEntry.getValue()); } public Object get(Object paramObject) { return this.singleKey.equals(paramObject) ? this.singleValue : null; } public int size() { return 1; } public boolean containsKey(Object paramObject) { return this.singleKey.equals(paramObject); } public boolean containsValue(Object paramObject) { return this.singleValue.equals(paramObject); } boolean isPartialView() { return false; } ImmutableSet createEntrySet() { return ImmutableSet.of(Maps.immutableEntry(this.singleKey, this.singleValue)); } ImmutableSet createKeySet() { return ImmutableSet.of(this.singleKey); } public ImmutableBiMap inverse() { ImmutableBiMap localImmutableBiMap = this.inverse; if (localImmutableBiMap == null) { return this.inverse = new SingletonImmutableBiMap(this.singleValue, this.singleKey, this); } return localImmutableBiMap; } } /* Location: D:\Projects\AiCup\CodeRacing\local-runner\local-runner.jar!\com\google\common\collect\SingletonImmutableBiMap.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
d70149e3a6e66c6db841044f3e2c56559ede6184
Java
Outlaw96/projetScrabble
/Scrabble/src/listeners/PlateauListener.java
WINDOWS-1252
3,487
2.75
3
[]
no_license
package listeners; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import model.Dictionnaire; import model.Joueur; import model.Pion; import model.Plateau; import view.PlateauView; import view.SwapPions; public class PlateauListener implements MouseListener { private PlateauView pv; private Joueur jr; private Plateau pl; private Pion pion; private int i, j, index; public PlateauListener(PlateauView pv, Plateau pl, Joueur jr) { this.pv = pv; this.pl = pl; this.jr = jr; this.i = -1; this.j = -1; this.index = -1; } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub if (this.pv.isSkiping(e.getX(), e.getY())) { System.out.println("skip"); } else if (this.pv.isSwapping(e.getX(), e.getY())) { new SwapPions(jr.getChevalet(), pv); } else if (this.pv.isMixing(e.getX(), e.getY())) { if (this.jr.isFull()) { System.out.println("mix"); this.jr.mix(); this.jr.showChevalet(); this.pv.repaint(); } } else if (this.pv.isRetrieving(e.getX(), e.getY())) { System.out.println("retrieve"); this.pv.retrieve(); this.jr.showChevalet(); this.pv.repaint(); } else if (this.pv.isPlaying(e.getX(), e.getY())) { this.pl.playWord(); this.pl.showWords(); System.out.println("play"); } else if (this.pv.isSearching(e.getX(), e.getY())) { // dans ce cas on affiche le formulaire new Dictionnaire(); } } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub // un peu sale donc redefinir if (e.getY() > 0 && e.getY() < 510 && e.getX() > 50 && e.getX() < 500) { int x = this.pv.getX(e.getY()); int y = this.pv.getY(e.getX()); if (x >= 0 && y >= 0) { if (pl.getCases()[x][y].isTaken()) { this.pion = pl.getCases()[x][y].getPion(); this.i = x; this.j = y; } } } else if (e.getY() > 510 && e.getY() < 555 && e.getX() > 50 && e.getX() < 260) { int x = this.pv.getIndexChevalet(e.getX(), e.getY()); if (x >= 0) { if (this.jr.getChevalet()[x].isTaken()) { this.pion = this.jr.getChevalet()[x].getPion(); this.index = x; } } } } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub // un peu sale donc redefinir aussi if (e.getY() > 0 && e.getY() < 510 && e.getX() > 50 && e.getX() < 500) { int x = this.pv.getX(e.getY()); int y = this.pv.getY(e.getX()); if (!this.pl.getCases()[x][y].isTaken() && this.pion != null) { if (this.i >= 0 && this.j >= 0) { this.pl.addPion(x, y, this.pion); this.pl.removePion(i, j); } else if (this.index >= 0) { this.pl.addPion(x, y, this.pion); this.jr.removePion(this.index); } } } else if (e.getY() > 510 && e.getY() < 555 && e.getX() > 50 && e.getX() < 260) { int x = this.pv.getIndexChevalet(e.getX(), e.getY()); if (x >= 0) { if (!this.jr.getChevalet()[x].isTaken()) { if (this.i >= 0 && this.j >= 0) { this.jr.addPion(x, this.pion); this.pl.removePion(i, j); } else if (this.index >= 0) { this.jr.addPion(x, this.pion); this.jr.removePion(this.index); } } } } this.i = -1; this.j = -1; this.index = -1; this.pion = null; this.pv.repaint(); } }
true
ecfb7e81dea629d705c9e3a95893441ac2ad12d5
Java
razrog/stepping
/src/main/java/com/imperva/stepping/IDistributionStrategy.java
UTF-8
242
1.789063
2
[ "Apache-2.0" ]
permissive
package com.imperva.stepping; import java.util.List; public interface IDistributionStrategy { //todo StepDecorator should not be exposed to API consumers void distribute(List<IStepDecorator> steps, Data data, String subjectType); }
true
f27df8cceb53ed2b371b8df2d7ae9f37f6e0171f
Java
EmadAnwer/b-donor
/app/src/main/java/com/example/gradandroidfirsttry/Patient_intro_Request.java
UTF-8
2,079
2.0625
2
[]
no_license
package com.example.gradandroidfirsttry; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; public class Patient_intro_Request extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.patient_intro_request); // Hide ActionBar if (getSupportActionBar() != null) { getSupportActionBar().hide(); } ImageView pat_new_req = findViewById(R.id.new_request_icon); pat_new_req.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Patient_intro_Request.this,Patient_Request.class); startActivity(intent); Toast.makeText(getApplicationContext(), "Patient Request",Toast.LENGTH_LONG).show(); } }); ImageView pat_view_history_req = findViewById(R.id.history_icon); pat_view_history_req.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Patient_intro_Request.this,Main_History.class); startActivity(intent); Toast.makeText(getApplicationContext(), "Patient View Request History",Toast.LENGTH_LONG).show(); } }); ImageView track_request_icon = findViewById(R.id.track_request_icon); track_request_icon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Patient_intro_Request.this,Track_request_items.class); startActivity(intent); Toast.makeText(getApplicationContext(), "Patient Track Request",Toast.LENGTH_LONG).show(); } }); } }
true
62b4d65f57d64ef3f2ef8e5479291b39b8f806ab
Java
cadusousa/Productos
/eRoute/Tag/1.17.0/Codigo/RouteLite/routeLite/src/main/java/com/amesol/routelite/vistas/SeleccionMercadeo.java
UTF-8
8,219
1.757813
2
[]
no_license
package com.amesol.routelite.vistas; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Point; import android.os.Bundle; import android.view.ContextMenu; import android.view.Display; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import com.amesol.routelite.R; import com.amesol.routelite.actividades.Mensajes; import com.amesol.routelite.datos.generales.ISetDatos; import com.amesol.routelite.datos.utilerias.MOTConfiguracion; import com.amesol.routelite.datos.utilerias.Sesion; import com.amesol.routelite.presentadores.Enumeradores; import com.amesol.routelite.presentadores.act.SeleccionarMercadeo; import com.amesol.routelite.presentadores.act.SeleccionarPedido; import com.amesol.routelite.presentadores.interfaces.ISeleccionMercadeo; public class SeleccionMercadeo extends Vista implements ISeleccionMercadeo { SeleccionarMercadeo mPresenta; String mAccion; boolean iniciarActividad; String sMRDIdSeleccionado = null; @Override public void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); mAccion = getIntent().getAction(); setContentView(R.layout.seleccion_transaccion); deshabilitarBarra(true); lblTitle.setText(Mensajes.get("XMercadeo")); Button btn = (Button) findViewById(R.id.btnContinuar); btn.setText(Mensajes.get("XContinuar")); btn.setOnClickListener(mContinuar); ListView lista = (ListView) findViewById(R.id.lstTransaccion); lista.setOnItemClickListener(mSeleccion); registerForContextMenu(lista); mPresenta = new SeleccionarMercadeo(this, mAccion); mPresenta.iniciar(); } catch (Exception e) { mostrarError(e.getMessage() + ". " + e.getCause().getMessage()); e.printStackTrace(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: setResult(Enumeradores.Resultados.RESULTADO_BIEN); this.finish(); return true; } return super.onKeyDown(keyCode, event); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_manto_mercadeo, menu); menu.getItem(0).setTitle(Mensajes.get("XEliminar")); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); ListView lista = (ListView) findViewById(R.id.lstTransaccion); Cursor mercadeo = (Cursor) lista.getItemAtPosition((int) info.position); mercadeo.moveToPosition((int)info.position); sMRDIdSeleccionado = mercadeo.getString(mercadeo.getColumnIndex("_id")); switch (item.getItemId()) { case R.id.eliminar: mostrarPreguntaSiNo(Mensajes.get("P0001"), 9); return true; } return true; } private AdapterView.OnItemClickListener mSeleccion = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { String MRDId = ((SimpleCursorAdapter) parent.getAdapter()).getCursor().getString(((SimpleCursorAdapter) parent.getAdapter()).getCursor().getColumnIndex("_id")); mPresenta.modificarMERDetalle(MRDId); } }; private View.OnClickListener mContinuar = new View.OnClickListener() { public void onClick(View v) { mPresenta.generarMERDetalle(); } }; @Override public void iniciar() { // TODO Auto-generated method stub } @Override public void mostrarMercadeoCliente(ISetDatos sdMERDetalle) { ListView lstMercadeo = (ListView) findViewById(R.id.lstTransaccion); Cursor cMERDetalle = (Cursor) sdMERDetalle.getOriginal(); startManagingCursor(cMERDetalle); try { SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.lista_simple3, cMERDetalle, new String[] {"Producto", "Marca","Presentacion"}, new int[] {R.id.texto1, R.id.texto2, R.id.texto3}); lstMercadeo.setAdapter(adapter); } catch (Exception e) { mostrarError(e.getMessage()); } lstMercadeo.setOnItemClickListener(mSeleccion); } @Override public void resultadoActividad(int requestCode, int resultCode, Intent data) { if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { setResultado(Enumeradores.Resultados.RESULTADO_BIEN); finalizar(); } else if (resultCode == Enumeradores.Resultados.RESULTADO_MAL) { if (data != null) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (mPresenta.existenAbonos()) mostrarError(mensajeError); else { setResultado(Enumeradores.Resultados.RESULTADO_MAL, mensajeError); finalizar(); } } } else if (resultCode == Enumeradores.Resultados.RESULTADO_TERMINAR) { if (!mPresenta.existenAbonos()) { setResultado(Enumeradores.Resultados.RESULTADO_BIEN); finalizar(); } } } @Override public void respuestaMensaje(Enumeradores.RespuestaMsg respuesta, int tipoMensaje) { if (tipoMensaje == 9 && respuesta == Enumeradores.RespuestaMsg.Si){ mPresenta.eliminarMERDetalle(sMRDIdSeleccionado); mPresenta.refrescarMERDetalle(); } } /* private void consultarCobranza(Cobranza.VistaCobranza abono) { try { HashMap<String, Cobranza.VistaCobranza> oParametros = new HashMap<String, Cobranza.VistaCobranza>(); oParametros.put("Abono", abono); iniciarActividadConResultado(ICapturaCobranzaDocs.class, 0, Enumeradores.Acciones.ACCION_CONSULTAR_COBRANZA, oParametros); } catch (Exception e) { mostrarError(e.getMessage() + ". " + e.getCause().getMessage()); e.printStackTrace(); } }*/ /* private void generarCobranza() { try { iniciarActividadConResultado(ICapturaCobranzaDocs.class, 0, Enumeradores.Acciones.ACCION_GENERAR_COBRANZA); } catch (Exception e) { mostrarError(e.getMessage() + ". " + e.getCause().getMessage()); e.printStackTrace(); } }*/ @Override public void setCliente(String cliente) { TextView texto = (TextView) findViewById(R.id.lblCliente); texto.setText(Mensajes.get("XCliente") + ": " + cliente); } @Override public void setRuta(String ruta) { TextView texto = (TextView) findViewById(R.id.lblRuta); texto.setText(Mensajes.get("XRuta") + ": " + ruta); } @Override public void setDia(String dia) { TextView texto = (TextView) findViewById(R.id.lblDia); texto.setText(Mensajes.get("XDiaTrabajo") + ": " + dia); } }
true
6a5d27b4b4d9d8105892cebd0806e9ca3862dc53
Java
Sabbir07/MentalWellBeing
/app/src/main/java/com/sabbir/preneurlab/mentalwellbeing/RememberingChildhood.java
UTF-8
2,468
2.265625
2
[]
no_license
package com.sabbir.preneurlab.mentalwellbeing; import android.graphics.PorterDuff; import android.graphics.Typeface; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; /** * Created by Sabbir on 1/13/2018. */ public class RememberingChildhood extends AppCompatActivity{ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.remembering_childhood); //setting action bar icon and text properties Toolbar toolbar = findViewById(R.id.mCustomToolbar); setSupportActionBar(toolbar); //getSupportActionBar().setTitle(" Remembering Question"); getSupportActionBar().setIcon(getDrawable(R.drawable.ic_action_name)); toolbar.setTitleTextColor(getResources().getColor(R.color.iconTintColorFrontPageButton)); Typeface raleway = Typeface.createFromAsset(this.getAssets(), "Raleway-Regular.ttf"); TextView toolbarText = toolbar.findViewById(R.id.toolBarTextView); toolbarText.setTypeface(raleway); toolbarText.setText(" Mental Health"); // customizing the underline's color EditText editText = findViewById(R.id.editText); EditText editText2 = findViewById(R.id.editText2); EditText editText3 = findViewById(R.id.editText3); EditText editText4 = findViewById(R.id.editText4); editText.getBackground().setColorFilter(getResources().getColor(R.color.blueColorForButton), PorterDuff.Mode.SRC_IN); editText2.getBackground().setColorFilter(getResources().getColor(R.color.blueColorForButton), PorterDuff.Mode.SRC_IN); editText3.getBackground().setColorFilter(getResources().getColor(R.color.blueColorForButton), PorterDuff.Mode.SRC_IN); editText4.getBackground().setColorFilter(getResources().getColor(R.color.blueColorForButton), PorterDuff.Mode.SRC_IN); //setting submit button Button submitButton = findViewById(R.id.button); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getBaseContext(), "Replace with your action...", Toast.LENGTH_SHORT).show(); } }); } }
true
3bf7651a74b6c0d5a8f3f0893a95a71a8ecacc5f
Java
allanwilsonGithub/inheritance
/src/com/allanwilson/Car.java
UTF-8
1,547
3.09375
3
[]
no_license
package com.allanwilson; import com.sun.org.apache.xpath.internal.SourceTree; /** * Created by awil on 2017-08-14. */ public class Car extends Vehicle { private int bootSpace; private int seats; private String steering; private String gear; private int speed; public Car (String type, int body, int engine, int wheels, int steeringWheel, int bootSpace, int seats, String steering, String gear, int speed) { super(type, body, engine, wheels, steeringWheel); this.bootSpace = bootSpace; this.seats = seats; this.steering = steering; this.gear = gear; this.speed = speed; } public int getSeats(){ return seats; } public String getSteering(){ return steering; } public void setSteering(String steeringDirection){ System.out.println("The car is now steering: " + steeringDirection); this.steering = steeringDirection; } public String getGear(){ return gear; } public void setGear(String newGear){ if (newGear == "First" ) { System.out.println("Setting gear to : " + newGear); this.gear = newGear; } else if (newGear == "Second" ){ System.out.println("Setting gear to : " + newGear); this.gear = newGear; } else { System.out.println(newGear + " wasn't a valid gear"); } System.out.println("Gear in now set to: " + this.gear); } public int getSpeed(){ return speed; } }
true
f1bc8cda5bc09e7bdb2524afb1b8c247a5f14f19
Java
aramnekt/ProfileScreen1
/MyApplication/app/src/main/java/com/example/prokarma/myapplication/FragmentManagerDelegate.java
UTF-8
393
2.046875
2
[]
no_license
package com.example.prokarma.myapplication; import android.support.v4.app.Fragment; /** * Created by prokarma on 4/26/2015. */ public interface FragmentManagerDelegate { public int getSlidingContainedId(); public int getFragmentContainerId(); public Fragment findFragmentByTag(String tag); public void replaceFragment(int containerId, Fragment fragment, String tag); }
true
f9799fb09d0513ae1ee1793725e170c220b0e45a
Java
IAmSam42/UpJammin2
/UpJammin2/src/model/Wall.java
UTF-8
821
2.96875
3
[]
no_license
package model; import java.awt.Graphics; import java.awt.Point; import javax.swing.ImageIcon; public class Wall extends Entity { public Wall(Map map, int health, Point point) { super(map, health, point); //Register the wall on the map. map.addBlockingEntity(this); //Increase the cost. this.getMap().getBank().buyBlock(Map.blockType.Wall); } @Override public void tick() { // TODO Auto-generated method stub } @Override public void render(Graphics g, boolean hover) { if(hover == false) { g.drawImage(new ImageIcon("resources/wall.jpg").getImage(), ((this.getPoint())).x, ((this.getPoint())).y, null); } else { g.drawImage(new ImageIcon("resources/greyWall.jpg").getImage(), ((this.getPoint())).x, ((this.getPoint())).y, null); } } }
true
61a0ae6a7f2bdfef838f95fee265065f07734e27
Java
edbolano/tremo
/src/gui/acciones/EscuchaAccionCalcular.java
ISO-8859-10
55,183
2.234375
2
[]
no_license
/* * EscuchaAccionCalcular.java * * Created on 4 de marzo de 2007, 04:35 AM * * Copyright (C) 2007 Edgar Bolaos Lujan * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * contact: jergas_bolanos@hotmail.com * */ package gui.acciones; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.UndeclaredThrowableException; import javax.swing.JOptionPane; import tremo.Main; /** * * @author __Edgar Bolaos Lujan__ */ public class EscuchaAccionCalcular implements ActionListener{ /** Creates a new instance of EscuchaAccionCalcular */ public EscuchaAccionCalcular() { } public void actionPerformed(ActionEvent e) { calcularCortantesX(); calcularCortantesZ(); calcularCentroTorsionX(); calcularCentroTorsionZ(); calcularMomentosTorsionantesX(); calcularMomentosTorsionantesZ(); distribuirFuerzasMarcosX(); distribuirFuerzasMarcosZ(); JOptionPane.showMessageDialog(null,"Calculo completado!!!","INFORMACION",JOptionPane.INFORMATION_MESSAGE); } private void calcularCortantesX() { float periodoT = Main.getArchivoDeTrabajo().getCriterioOpcional_TX(); float periodoTa = Main.getArchivoDeTrabajo().getCriterio_Ta(); float periodoTb = Main.getArchivoDeTrabajo().getCriterio_Tb(); float Qx = Main.getArchivoDeTrabajo().getCriterio_Qx(); float criterio_a = 0f; float Qprima = 0f; float criterio_c = Main.getArchivoDeTrabajo().getCriterio_c(); float criterio_aCero = Main.getArchivoDeTrabajo().getCriterio_aCero(); float criterio_r = Main.getArchivoDeTrabajo().getCriterio_r(); float sumaWi = 0f; float sumaWihi = 0f; float sumaWihihi = 0f; //float[] fuerzas = new float[20]; if( (periodoT==0f)||(periodoT>=periodoTa) ){ Qprima = Qx; }else{ Qprima = ( (periodoT/periodoTa)*(Qx-1) )+1; } //calcular columna alturas absolutas de cada entrepiso float estaAltura = 0f; for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ estaAltura = estaAltura + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[0].calcularAlturaN(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setAlturaAbsoluta(estaAltura); //Se aprovecha el ciclo para calcular sumatorias de peso y de producto peso x altura absoluta sumaWi = sumaWi + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0]; sumaWihi = sumaWihi + ( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0])* (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getAlturaAbsoluta()) ); sumaWihihi = sumaWihihi + ( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0])* (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getAlturaAbsoluta())* (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getAlturaAbsoluta()) ); } } //calcular la columna de fuerzas Fi int indiceADescender = 0; for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float estePeso = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0]; float alt = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getAlturaAbsoluta(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setFuerzaSismicaX( (criterio_c/Qprima)* (sumaWi)* ( (estePeso*alt)/sumaWihi) ); // System.out.println("c"+criterio_c); // System.out.println("Q'"+Qprima); // System.out.println("sumaWi"+sumaWi); // System.out.println("este peso"+estePeso); // System.out.println("alt"+alt); // System.out.println("sumaWihi"+sumaWihi); indiceADescender = entrepiso ; } } //calcular la columna de cortantes float cortante_i = 0f; for(int entrepiso = indiceADescender;entrepiso>=0;entrepiso--){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ cortante_i = cortante_i + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getFuerzaSismicaX(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setCortanteX(cortante_i); } } //calcular la columna vi/ki (cortante/rigidez) y el desplazamiento absoluto float desplazamientoAbsoluto = 0f; for(int entrepiso = 0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float rigidezTotal_i = 0f; int numMarcos = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX().length; for(int marco=0;marco<numMarcos;marco++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].getIdentificador().compareTo("Marco no definido")!=0) ){ rigidezTotal_i = rigidezTotal_i + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].calcularRigidez(); //se aprovecha el ciclo para asignarle la nueva rigidez a los marcos (esta rigidez es nueva porque ya se pudo // haber replanteado la informacion de las alturas superior e inferior de cada marco) Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].setRigidezR( Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].calcularRigidez() ); } } // System.out.println("\nrigidez total: "+rigidezTotal_i); // //desplazamientoRelativo = cortante/rigidez // System.out.println("cortante x: "+Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCortanteX() ); float desplazamientoDeEntrepisoRelativo_i = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCortanteX() /(rigidezTotal_i); desplazamientoAbsoluto = desplazamientoAbsoluto + desplazamientoDeEntrepisoRelativo_i; Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setDesplazamientoAbsolutoX(desplazamientoAbsoluto); // System.out.println("desplazamiento relativo: "+desplazamientoDeEntrepisoRelativo_i); // System.out.println("desplazamiento absoluto: "+desplazamientoAbsoluto); } } //calcular Sumatoria(Wixi2) y Sumatoria(Fixi) para estimar el periodo T float sumaWiXiCuad = 0f; float sumaFiXi = 0f; for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ sumaWiXiCuad = sumaWiXiCuad + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0] *Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getDesplazamientoAbsolutoX() *Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getDesplazamientoAbsolutoX(); sumaFiXi = sumaFiXi + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getFuerzaSismicaX() *Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getDesplazamientoAbsolutoX(); } } double perDoubleTemp = (2*Math.PI)*(Math.sqrt(sumaWiXiCuad/(sumaFiXi*981) ) ); periodoT = (float)perDoubleTemp; Main.getArchivoDeTrabajo().setCriterioOpcional_TX(periodoT); ///////CALCULAR " a " ///////////////////////////////////////////////////// if(periodoT < periodoTa){ criterio_a = criterio_aCero + ( (criterio_c - criterio_aCero)*(periodoT/periodoTa) ); } else if(periodoT > periodoTb){ double aTemporal = (criterio_c)*Math.pow( (periodoTb/periodoT),criterio_r ); criterio_a = (float)aTemporal; } else { //cualquier otro caso implica que Ta <= T <= Tb criterio_a = criterio_c; } ///////CALCULAR " a " ///////////////////////////////////////////////////// ///////CALCULAR " Q' " ///////////////////////////////////////////////////// if( (periodoT==0f)||(periodoT>=periodoTa) ){ Qprima = Qx; }else{ Qprima = ( (periodoT/periodoTa)*(Qx-1) )+1; } ///////CALCULAR " Q' " ///////////////////////////////////////////////////// //se evalua la posible reduccion de las fuerzas cortantes if(periodoT <= periodoTb){ //Fi = a/Q' x SumaWi x wihi/SumaWihi for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float estePeso = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0]; float alt = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getAlturaAbsoluta(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setFuerzaSismicaX( (criterio_a/Qprima)* (sumaWi)* ( (estePeso*alt)/sumaWihi) ); // System.out.println("c"+criterio_a); // System.out.println("Q'"+Qprima); // System.out.println("sumaWi"+sumaWi); // System.out.println("este peso"+estePeso); // System.out.println("alt"+alt); // System.out.println("sumaWihi"+sumaWihi); indiceADescender = entrepiso ; } } //calcular la columna de cortantes float cortante_i_segundoCiclo = 0f; for(int entrepiso = indiceADescender;entrepiso>=0;entrepiso--){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ cortante_i_segundoCiclo = cortante_i_segundoCiclo + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getFuerzaSismicaX(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setCortanteX(cortante_i_segundoCiclo); } } }else if(periodoT > periodoTb){ //Fi = a/Q' x Wi( k1hi + k2*hi*hi ) for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float estePeso = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0]; float alt = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getAlturaAbsoluta(); double qTemporal = (criterio_c)*Math.pow( (periodoTb/periodoT),criterio_r ); float factor_q = (float)qTemporal; double kUnoTemporal = (sumaWi/sumaWihi)*( 1 - (0.5*criterio_r)*(1-factor_q) ); float kUno = (float)kUnoTemporal; double kDosTemporal = (sumaWi/sumaWihihi)*(0.75)*(criterio_r)*(1 - factor_q) ; float kDos = (float)kDosTemporal; Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setFuerzaSismicaX( (criterio_a/Qprima)* (estePeso)* ( (kUno*alt) + (kDos*alt*alt) ) ); // System.out.println("c"+criterio_a); // System.out.println("Q'"+Qprima); // System.out.println("sumaWi"+sumaWi); // System.out.println("este peso"+estePeso); // System.out.println("alt"+alt); // System.out.println("sumaWihi"+sumaWihi); indiceADescender = entrepiso ; } } //calcular la columna de cortantes float cortante_i_segundoCiclo = 0f; for(int entrepiso = indiceADescender;entrepiso>=0;entrepiso--){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ cortante_i_segundoCiclo = cortante_i_segundoCiclo + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getFuerzaSismicaX(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setCortanteX(cortante_i_segundoCiclo); } } } //fin de else if(periodoT > periodoTb) //AL FINALIZAR ESTE METODO LOS ENTREPISOS DE ARCHIVO TENDRAN ASIGNADOS SUS CORRESPONDIENTES //FUERZAS Y CORTANTES DE ENTREPISO EN EL SENTIDO X } private void calcularCortantesZ() { float periodoT = Main.getArchivoDeTrabajo().getCriterioOpcional_TZ(); float periodoTa = Main.getArchivoDeTrabajo().getCriterio_Ta(); float periodoTb = Main.getArchivoDeTrabajo().getCriterio_Tb(); float Qz = Main.getArchivoDeTrabajo().getCriterio_Qz(); float criterio_a = 0f; float Qprima = 0f; float criterio_c = Main.getArchivoDeTrabajo().getCriterio_c(); float criterio_aCero = Main.getArchivoDeTrabajo().getCriterio_aCero(); float criterio_r = Main.getArchivoDeTrabajo().getCriterio_r(); float sumaWi = 0f; float sumaWihi = 0f; float sumaWihihi = 0f; //float[] fuerzas = new float[20]; if( (periodoT==0f)||(periodoT>=periodoTa) ){ Qprima = Qz; }else{ Qprima = ( (periodoT/periodoTa)*(Qz-1) )+1; } //calcular columna alturas absolutas de cada entrepiso float estaAltura = 0f; for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ estaAltura = estaAltura + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[0].calcularAlturaN(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setAlturaAbsoluta(estaAltura); //Se aprovecha el ciclo para calcular sumatorias de peso y de producto peso x altura absoluta sumaWi = sumaWi + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0]; sumaWihi = sumaWihi + ( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0])* (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getAlturaAbsoluta()) ); sumaWihihi = sumaWihihi + ( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0])* (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getAlturaAbsoluta())* (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getAlturaAbsoluta()) ); } } //calcular la columna de fuerzas Fi int indiceADescender = 0; for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float estePeso = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0]; float alt = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getAlturaAbsoluta(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setFuerzaSismicaZ( (criterio_c/Qprima)* (sumaWi)* ( (estePeso*alt)/sumaWihi) ); // System.out.println("c"+criterio_c); // System.out.println("Q'"+Qprima); // System.out.println("sumaWi"+sumaWi); // System.out.println("este peso"+estePeso); // System.out.println("alt"+alt); // System.out.println("sumaWihi"+sumaWihi); indiceADescender = entrepiso ; } } //calcular la columna de cortantes float cortante_i = 0f; for(int entrepiso = indiceADescender;entrepiso>=0;entrepiso--){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ cortante_i = cortante_i + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getFuerzaSismicaZ(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setCortanteZ(cortante_i); } } //calcular la columna vi/ki (cortante/rigidez) y el desplazamiento absoluto float desplazamientoAbsoluto = 0f; for(int entrepiso = 0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float rigidezTotal_i = 0f; int numMarcos = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ().length; for(int marco=0;marco<numMarcos;marco++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].getIdentificador().compareTo("Marco no definido")!=0) ){ rigidezTotal_i = rigidezTotal_i + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].calcularRigidez(); //se aprovecha el ciclo para asignarle la nueva rigidez a los marcos (esta rigidez es nueva porque ya se pudo // haber replanteado la informacion de las alturas superior e inferior de cada marco) Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].setRigidezR( Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].calcularRigidez() ); } } // System.out.println("\nrigidez total: "+rigidezTotal_i); // //desplazamientoRelativo = cortante/rigidez // System.out.println("cortante x: "+Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCortanteX() ); float desplazamientoDeEntrepisoRelativo_i = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCortanteZ() /(rigidezTotal_i); desplazamientoAbsoluto = desplazamientoAbsoluto + desplazamientoDeEntrepisoRelativo_i; Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setDesplazamientoAbsolutoZ(desplazamientoAbsoluto); // System.out.println("desplazamiento relativo: "+desplazamientoDeEntrepisoRelativo_i); // System.out.println("desplazamiento absoluto: "+desplazamientoAbsoluto); } } //calcular Sumatoria(Wixi2) y Sumatoria(Fixi) para estimar el periodo T float sumaWiXiCuad = 0f; float sumaFiXi = 0f; for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ sumaWiXiCuad = sumaWiXiCuad + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0] *Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getDesplazamientoAbsolutoZ() *Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getDesplazamientoAbsolutoZ(); sumaFiXi = sumaFiXi + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getFuerzaSismicaZ() *Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getDesplazamientoAbsolutoZ(); } } double perDoubleTemp = (2*Math.PI)*(Math.sqrt(sumaWiXiCuad/(sumaFiXi*981) ) ); periodoT = (float)perDoubleTemp; Main.getArchivoDeTrabajo().setCriterioOpcional_TZ(periodoT); ///////CALCULAR " a " ///////////////////////////////////////////////////// if(periodoT < periodoTa){ criterio_a = criterio_aCero + ( (criterio_c - criterio_aCero)*(periodoT/periodoTa) ); } else if(periodoT > periodoTb){ double aTemporal = (criterio_c)*Math.pow( (periodoTb/periodoT),criterio_r ); criterio_a = (float)aTemporal; } else { //cualquier otro caso implica que Ta <= T <= Tb criterio_a = criterio_c; } ///////CALCULAR " a " ///////////////////////////////////////////////////// ///////CALCULAR " Q' " ///////////////////////////////////////////////////// if( (periodoT==0f)||(periodoT>=periodoTa) ){ Qprima = Qz; }else if(periodoT < periodoTa){ Qprima = ( (periodoT/periodoTa)*(Qz-1) )+1; } ///////CALCULAR " Q' " ///////////////////////////////////////////////////// //se evalua la posible reduccion de las fuerzas cortantes if(periodoT <= periodoTb){ //Fi = a/Q' x SumaWi x wihi/SumaWihi for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float estePeso = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0]; float alt = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getAlturaAbsoluta(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setFuerzaSismicaZ( (criterio_a/Qprima)* (sumaWi)* ( (estePeso*alt)/sumaWihi) ); // System.out.println("c"+criterio_a); // System.out.println("Q'"+Qprima); // System.out.println("sumaWi"+sumaWi); // System.out.println("este peso"+estePeso); // System.out.println("alt"+alt); // System.out.println("sumaWihi"+sumaWihi); indiceADescender = entrepiso ; } } //calcular la columna de cortantes float cortante_i_segundoCiclo = 0f; for(int entrepiso = indiceADescender;entrepiso>=0;entrepiso--){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ cortante_i_segundoCiclo = cortante_i_segundoCiclo + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getFuerzaSismicaZ(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setCortanteZ(cortante_i_segundoCiclo); } } }else if(periodoT > periodoTb){ //Fi = a/Q' x Wi( k1hi + k2*hi*hi ) for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float estePeso = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[0]; float alt = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getAlturaAbsoluta(); double qTemporal = (criterio_c)*Math.pow( (periodoTb/periodoT),criterio_r ); float factor_q = (float)qTemporal; double kUnoTemporal = (sumaWi/sumaWihi)*( 1 - (0.5*criterio_r)*(1-factor_q) ); float kUno = (float)kUnoTemporal; double kDosTemporal = (sumaWi/sumaWihihi)*(0.75)*(criterio_r)*(1 - factor_q) ; float kDos = (float)kDosTemporal; Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setFuerzaSismicaZ( (criterio_a/Qprima)* (estePeso)* ( (kUno*alt) + (kDos*alt*alt) ) ); // System.out.println("c"+criterio_a); // System.out.println("Q'"+Qprima); // System.out.println("sumaWi"+sumaWi); // System.out.println("este peso"+estePeso); // System.out.println("alt"+alt); // System.out.println("sumaWihi"+sumaWihi); indiceADescender = entrepiso ; } } //calcular la columna de cortantes float cortante_i_segundoCiclo = 0f; for(int entrepiso = indiceADescender;entrepiso>=0;entrepiso--){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ cortante_i_segundoCiclo = cortante_i_segundoCiclo + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getFuerzaSismicaZ(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setCortanteZ(cortante_i_segundoCiclo); } } } //fin de else if(periodoT > periodoTb) //AL FINALIZAR ESTE METODO LOS ENTREPISOS DE ARCHIVO TENDRAN ASIGNADOS SUS CORRESPONDIENTES //FUERZAS Y CORTANTES DE ENTREPISO EN EL SENTIDO Z } private void calcularCentroTorsionX(){ for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float sumaRizXi = 0f; float sumaRiz = 0f; for(int marcoZ=0;marcoZ<50;marcoZ++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marcoZ]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marcoZ].getIdentificador().compareTo("Marco no definido")!=0) ){ //No es necesario volver a calcular la rigidez porque en el metodo calcular cortantes ya se //actualizo la rigidez... sumaRizXi = sumaRizXi + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marcoZ].getRigidezR() *(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marcoZ].getColumnasN()[0].getNodoA().getCordX()); sumaRiz = sumaRiz + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marcoZ].getRigidezR(); } } float torsionX = sumaRizXi/sumaRiz; Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setCentroTorsionX(torsionX); } } } private void calcularCentroTorsionZ(){ for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float sumaRixZi = 0f; float sumaRix = 0f; for(int marcoX=0;marcoX<50;marcoX++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marcoX]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marcoX].getIdentificador().compareTo("Marco no definido")!=0) ){ //No es necesario volver a calcular la rigidez porque en el metodo calcular cortantes ya se //actualizo la rigidez... sumaRixZi = sumaRixZi + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marcoX].getRigidezR() *(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marcoX].getColumnasN()[0].getNodoA().getCordZ()); sumaRix = sumaRix + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marcoX].getRigidezR(); } } float torsionZ = sumaRixZi/sumaRix; Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setCentroTorsionZ(torsionZ); } } } private void calcularMomentosTorsionantesX(){ for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float excentricidadX = 0f; float excentricidadXUno = 0f; float excentricidadXDos = 0f; float momentoTorsionanteUno = 0f; float momentoTorsionanteDos = 0f; float longitudMayorZ = 0f; excentricidadX = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCentroTorsionZ() -Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[2]; longitudMayorZ = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularMayorLongitudZ(); double excentricidadXUnoTemporal = (1.5*excentricidadX) + (0.1*longitudMayorZ); excentricidadXUno = (float)excentricidadXUnoTemporal; double excentricidadXDosTemporal = excentricidadX - (0.1*longitudMayorZ); excentricidadXDos = (float)excentricidadXDosTemporal; momentoTorsionanteUno = excentricidadXUno * Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCortanteX(); momentoTorsionanteDos = excentricidadXDos * Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCortanteX(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setMomentoUnoVX( momentoTorsionanteUno); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setMomentoDosVX( momentoTorsionanteDos); } } } private void calcularMomentosTorsionantesZ(){ for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float excentricidadZ = 0f; float excentricidadZUno = 0f; float excentricidadZDos = 0f; float momentoTorsionanteUno = 0f; float momentoTorsionanteDos = 0f; float longitudMayorX = 0f; excentricidadZ = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCentroTorsionX() -Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularPesoTotal()[1]; longitudMayorX = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].calcularMayorLongitudX(); double excentricidadZUnoTemporal = (1.5*excentricidadZ) + (0.1*longitudMayorX); excentricidadZUno = (float)excentricidadZUnoTemporal; double excentricidadZDosTemporal = excentricidadZ - (0.1*longitudMayorX); excentricidadZDos = (float)excentricidadZDosTemporal; momentoTorsionanteUno = excentricidadZUno * Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCortanteZ(); momentoTorsionanteDos = excentricidadZDos * Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCortanteZ(); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setMomentoUnoVZ( momentoTorsionanteUno); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].setMomentoDosVZ( momentoTorsionanteDos); } } } private void distribuirFuerzasMarcosX() { for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float suma_Rix = 0f; float suma_Rix_ZiT_ZiT = 0f; float suma_Riz_XiT_XiT = 0f; for(int marco=0;marco<50;marco++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].getIdentificador().compareTo("Marco no definido")!=0) ){ suma_Rix = suma_Rix + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].getRigidezR(); float ZiT = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCentroTorsionZ() - Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].getColumnasN()[0].getNodoA().getCordZ(); suma_Rix_ZiT_ZiT = suma_Rix_ZiT_ZiT + (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].getRigidezR() * ZiT * ZiT ); } } for(int marco=0;marco<50;marco++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].getIdentificador().compareTo("Marco no definido")!=0) ){ float XiT = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCentroTorsionX() - Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].getColumnasN()[0].getNodoA().getCordX(); suma_Riz_XiT_XiT = suma_Riz_XiT_XiT + (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].getRigidezR() * XiT * XiT ); } } //En este punto ya conozco los valores de las //sumatorias de rigidecesX , productos rigX*zt*zt y productos rigZ*xt*xt for(int marco=0;marco<50;marco++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].getIdentificador().compareTo("Marco no definido")!=0) ){ float cortanteVxDirecto = 0f; float cortanteVxTorsionUno = 0f; float cortanteVxTorsionDos = 0f; float cortanteVxTorsionAsignable = 0f; float cortanteVxTotal = 0f; float cortanteVzTorsionUno = 0f; float cortanteVzTorsionDos = 0f; float cortanteVzTorsionAsignable = 0f; float cortanteEntrepisoX = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCortanteX(); float rigidez_iX = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].getRigidezR(); float ZiT = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCentroTorsionZ() - Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].getColumnasN()[0].getNodoA().getCordZ(); float momentoUnoVX = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMomentoUnoVX(); float momentoDosVX = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMomentoDosVX(); float momentoUnoVZ = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMomentoUnoVZ(); float momentoDosVZ = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMomentoDosVZ(); cortanteVxDirecto = cortanteEntrepisoX * (rigidez_iX/suma_Rix); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].setCortEfVxDirecto( cortanteVxDirecto ); cortanteVxTorsionUno = momentoUnoVX *(rigidez_iX*ZiT)/(suma_Rix_ZiT_ZiT + suma_Riz_XiT_XiT); cortanteVxTorsionDos = momentoDosVX *(rigidez_iX*ZiT)/(suma_Rix_ZiT_ZiT + suma_Riz_XiT_XiT); if(cortanteVxTorsionUno >= cortanteVxTorsionDos){ cortanteVxTorsionAsignable = cortanteVxTorsionUno; }else if(cortanteVxTorsionUno < cortanteVxTorsionDos){ cortanteVxTorsionAsignable = cortanteVxTorsionDos; } Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].setCortEfVxTorsion( cortanteVxTorsionAsignable); cortanteVxTotal = cortanteVxDirecto + cortanteVxTorsionAsignable; Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].setCortEfVxTotal( cortanteVxTotal); cortanteVzTorsionUno = momentoUnoVZ * (rigidez_iX*ZiT)/(suma_Rix_ZiT_ZiT + suma_Riz_XiT_XiT); cortanteVzTorsionDos = momentoDosVZ * (rigidez_iX*ZiT)/(suma_Rix_ZiT_ZiT + suma_Riz_XiT_XiT); if(cortanteVzTorsionUno >= cortanteVzTorsionDos){ cortanteVzTorsionAsignable = cortanteVzTorsionUno; }else if(cortanteVzTorsionUno < cortanteVzTorsionDos){ cortanteVzTorsionAsignable = cortanteVzTorsionDos; } Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].setCortEfVzTorsion( cortanteVzTorsionAsignable); double vxMasTresDecimasVz = 0f; double vzMasTresDecimasVx = 0f; float cortanteTotal = 0f; vxMasTresDecimasVz = cortanteVxTotal + (0.3*cortanteVzTorsionAsignable); vzMasTresDecimasVx = cortanteVzTorsionAsignable +(0.3*cortanteVxTotal); if(vxMasTresDecimasVz >= vzMasTresDecimasVx){ cortanteTotal = (float)vxMasTresDecimasVz; }else if(vxMasTresDecimasVz < vzMasTresDecimasVx){ cortanteTotal = (float)vzMasTresDecimasVx; } Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].setCortanteTotal( cortanteTotal); float desplazamientoRelativo = 0f; desplazamientoRelativo = Main.getArchivoDeTrabajo().getCriterio_Qx() * (cortanteTotal/rigidez_iX); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].setDesplazRelativo( desplazamientoRelativo); float distorsion = 0f; distorsion = desplazamientoRelativo / (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].getAlturaN()*100); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].setDistorsion( distorsion); } } } } } private void distribuirFuerzasMarcosZ() { for(int entrepiso=0;entrepiso<20;entrepiso++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getIdentificador().compareTo("Entrepiso sin definir")!=0) ){ float suma_Riz = 0f; float suma_Rix_ZiT_ZiT = 0f; float suma_Riz_XiT_XiT = 0f; for(int marco=0;marco<50;marco++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].getIdentificador().compareTo("Marco no definido")!=0) ){ float ZiT = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCentroTorsionZ() - Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].getColumnasN()[0].getNodoA().getCordZ(); suma_Rix_ZiT_ZiT = suma_Rix_ZiT_ZiT + (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosX()[marco].getRigidezR() * ZiT * ZiT ); } } for(int marco=0;marco<50;marco++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].getIdentificador().compareTo("Marco no definido")!=0) ){ suma_Riz = suma_Riz + Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].getRigidezR(); float XiT = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCentroTorsionX() - Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].getColumnasN()[0].getNodoA().getCordX(); suma_Riz_XiT_XiT = suma_Riz_XiT_XiT + (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].getRigidezR() * XiT * XiT ); } } //En este punto ya conozco los valores de las //sumatorias de rigidecesZ , productos rigX*zt*zt y productos rigZ*xt*xt for(int marco=0;marco<50;marco++){ if( (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco]!=null) &&(Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].getIdentificador().compareTo("Marco no definido")!=0) ){ float cortanteVzDirecto = 0f; float cortanteVzTorsionUno = 0f; float cortanteVzTorsionDos = 0f; float cortanteVzTorsionAsignable = 0f; float cortanteVzTotal = 0f; float cortanteVxTorsionUno = 0f; float cortanteVxTorsionDos = 0f; float cortanteVxTorsionAsignable = 0f; float cortanteEntrepisoZ = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCortanteZ(); float rigidez_iZ = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].getRigidezR(); float XiT = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getCentroTorsionX() - Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].getColumnasN()[0].getNodoA().getCordX(); float momentoUnoVZ = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMomentoUnoVZ(); float momentoDosVZ = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMomentoDosVZ(); float momentoUnoVX = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMomentoUnoVX(); float momentoDosVX = Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMomentoDosVX(); cortanteVzDirecto = cortanteEntrepisoZ * (rigidez_iZ/suma_Riz); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].setCortEfVzDirecto( cortanteVzDirecto ); cortanteVzTorsionUno = momentoUnoVZ *(rigidez_iZ*XiT)/(suma_Rix_ZiT_ZiT + suma_Riz_XiT_XiT); cortanteVzTorsionDos = momentoDosVZ *(rigidez_iZ*XiT)/(suma_Rix_ZiT_ZiT + suma_Riz_XiT_XiT); if(cortanteVzTorsionUno >= cortanteVzTorsionDos){ cortanteVzTorsionAsignable = cortanteVzTorsionUno; }else if(cortanteVzTorsionUno < cortanteVzTorsionDos){ cortanteVzTorsionAsignable = cortanteVzTorsionDos; } Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].setCortEfVzTorsion( cortanteVzTorsionAsignable); cortanteVzTotal = cortanteVzDirecto + cortanteVzTorsionAsignable; Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].setCortEfVzTotal( cortanteVzTotal); cortanteVxTorsionUno = momentoUnoVX * (rigidez_iZ*XiT)/(suma_Rix_ZiT_ZiT + suma_Riz_XiT_XiT); cortanteVxTorsionDos = momentoDosVX * (rigidez_iZ*XiT)/(suma_Rix_ZiT_ZiT + suma_Riz_XiT_XiT); if(cortanteVxTorsionUno >= cortanteVxTorsionDos){ cortanteVxTorsionAsignable = cortanteVxTorsionUno; }else if(cortanteVxTorsionUno < cortanteVxTorsionDos){ cortanteVxTorsionAsignable = cortanteVxTorsionDos; } Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].setCortEfVxTorsion( cortanteVxTorsionAsignable); double vzMasTresDecimasVx = 0f; double vxMasTresDecimasVz = 0f; float cortanteTotal = 0f; vzMasTresDecimasVx = cortanteVzTotal + (0.3*cortanteVxTorsionAsignable); vxMasTresDecimasVz = cortanteVxTorsionAsignable +(0.3*cortanteVzTotal); if(vzMasTresDecimasVx >= vxMasTresDecimasVz){ cortanteTotal = (float)vzMasTresDecimasVx; }else if(vzMasTresDecimasVx < vxMasTresDecimasVz){ cortanteTotal = (float)vxMasTresDecimasVz; } Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].setCortanteTotal( cortanteTotal); float desplazamientoRelativo = 0f; desplazamientoRelativo = Main.getArchivoDeTrabajo().getCriterio_Qz() * (cortanteTotal/rigidez_iZ); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].setDesplazRelativo( desplazamientoRelativo); float distorsion = 0f; distorsion = desplazamientoRelativo / (Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].getAlturaN()*100); Main.getArchivoDeTrabajo().getEntrepisosDeArchivo()[entrepiso].getMarcosZ()[marco].setDistorsion( distorsion); } } } } } }
true
0a567171f5775f9794f16d3d6324203e0d2a2a67
Java
lomik33/MCA-AVANZADA-PFINAL
/src/Cotizacion.java
UTF-8
383
1.5625
2
[]
no_license
import java.time.LocalDateTime; import java.util.List; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author CoreMac */ public class Cotizacion { private LocalDateTime fecha; private List<Producto> items; }
true
0b091df3f438d78042054d0d31fea3eef0f334f5
Java
SemirSahman/homeworks
/HomeworkWeekend6/src/ba/bitcamp/homeworkweekend6/Task6.java
UTF-8
757
3.3125
3
[]
no_license
package ba.bitcamp.homeworkweekend6; public class Task6 { public static void fillArray(int[][] matrix, int num1, int num2, int num3) { if (num1 == matrix.length) { return; } if (num2 == matrix[num1].length - 1) { matrix[num1][num2] = num3; fillArray(matrix, num1 + 1, 0, num3 + 1); } else { matrix[num1][num2] = num3; fillArray(matrix, num1, num2 + 1, num3 + 1); } } public static void fillArray(int[][] matrix) { fillArray(matrix, 0, 0, 0); } public static void main(String[] args) { int[][] matrix = new int[5][5]; fillArray(matrix); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }
true
bd9fa41fa28dc31f232614928305ffd18fab2508
Java
doibay/openshift-playground
/src/main/java/com/bielu/oshift/rest/crime/CrimeService.java
UTF-8
7,418
2.21875
2
[]
no_license
package com.bielu.oshift.rest.crime; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.xml.namespace.QName; import com.bielu.oshift.Utils; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.MongoException; import com.mongodb.WriteResult; @Path("crime") @Produces({"application/json", "application/xml", "application/xml+fastinfoset", "application/x-protobuf"}) @Consumes({"application/json", "application/xml", "application/xml+fastinfoset", "application/x-protobuf"}) public class CrimeService { Logger logger = Logger.getLogger(this.getClass().getSimpleName()); DBCollection collection; public CrimeService() throws UnknownHostException { MongoClient mongo = new MongoClient( new MongoClientURI( "mongodb://" + Utils.getenv("OPENSHIFT_MONGODB_DB_USER", "admin") + ":" + Utils.getenv("OPENSHIFT_MONGODB_DB_PASS") + "@" + Utils.getenv("OPENSHIFT_MONGODB_DB_HOST", "localhost") + ":" + Utils.getenv("OPENSHIFT_MONGODB_DB_PORT", "27017"))); collection = mongo.getDB(Utils.getenv("OPENSHIFT_MONGODB_DB_NAME", "playground")).getCollection("crimes"); } @GET @Path("{id}") public Crime getCrime(@PathParam("id") String id) { try (DBCursor cursor = collection.find(new BasicDBObject(Crime.ID, id))) { if (cursor.hasNext()) { return Crime.fromDBObject(cursor.next()); } } return null; } WriteResult deleteCrime0(String id) throws MongoException { try (DBCursor cursor = collection.find(new BasicDBObject(Crime.ID, id))) { if (cursor.hasNext() == false) { return null; } return collection.remove(new BasicDBObject(Crime.ID, id)); } } @DELETE @Path("{id}") public Response deleteCrime(@PathParam("id") String id) { try { WriteResult result = deleteCrime0(id); if (result == null) { return notFound("delete", id); } if (result.getError() != null) { return error("delete", result.getError()); } return Response .ok(new CrimeServiceStatus("delete", "success", "Crime has been deleted")) .build(); } catch (MongoException e) { return error("delete", e.toString()); } } WriteResult updateCrime0(Crime crime) throws MongoException { try (DBCursor cursor = collection.find(new BasicDBObject(Crime.ID, crime.id.toString()))) { if (cursor.hasNext() == false) { return null; } return collection.update(cursor.next(), crime.toDBObject()); } } @POST public Response updateCrime(Crime crime) { try { WriteResult result = updateCrime0(crime); if (result == null) { return notFound("update", crime.id.toString()); } if (result.getError() != null) { return error("update", result.getError()); } return Response .ok(new CrimeServiceStatus("update", "success", crime.id.toString())) .build(); } catch (MongoException e) { return error("update", e.toString()); } } @POST @Path("/sync") public Response syncCrimes(List<Crime> crimeList) { List<Crime> dbCrimes = getCrimeList(); List<Crime> toRemove = new ArrayList<>(); List<Crime> toAdd = new ArrayList<>(); List<Crime> toUpdate = new ArrayList<>(); for (Crime crime : dbCrimes) { if (crimeList.contains(crime) == false) { toRemove.add(crime); } } for (Crime crime : crimeList) { if (dbCrimes.contains(crime)) { toUpdate.add(crime); } else { toAdd.add(crime); } } int errors = 0; int updates = 0; int inserts = 0; int removals = 0; for (Crime crime : toRemove) { if (deleteCrime0(crime.id.toString()).getError() == null) { removals++; } else { logger.warning("Unable to remove crime with id '" + crime.id + "'."); errors++; } } for (Crime crime : toAdd) { if (addCrime0(crime).getError() == null) { inserts++; } else { logger.warning("Unable to add crime with id '" + crime.id + "'."); errors++; } } for (Crime crime : toUpdate) { if (updateCrime0(crime).getError() == null) { updates++; } else { logger.warning("Unable to update crime with id '" + crime.id + "'."); errors++; } } Map<QName, String> resMap = new HashMap<>(); resMap.put(new QName("inserts"), "" + inserts); resMap.put(new QName("updates"), "" + updates); resMap.put(new QName("removals"), "" + removals); resMap.put(new QName("errors"), "" + errors); return Response.ok() .entity(new CrimeServiceStatus("sync", "success", resMap)) .build(); } WriteResult addCrime0(Crime crime) throws MongoException { try (DBCursor cursor = collection.find(new BasicDBObject(Crime.ID, crime.id.toString()))) { if (cursor.hasNext()) { return null; } return collection.insert(crime.toDBObject()); } } @PUT public Response addCrime(Crime crime) { try { WriteResult result = addCrime0(crime); if (result == null) { return Response.status(Status.CONFLICT) .entity(new CrimeServiceStatus("add", "error", "Crime with given UUID already exists")) .build(); } if (result.getError() != null) { return error("add", result.getError()); } return Response.status(Status.CREATED) .entity(new CrimeServiceStatus("add", "success", crime.id.toString())) .build(); } catch (MongoException e) { return error("add", e.toString()); } } @GET public List<Crime> getCrimeList() { List<Crime> list = new ArrayList<>(); try (DBCursor cursor = collection.find()) { while (cursor.hasNext()) { DBObject res = cursor.next(); list.add(Crime.fromDBObject(res)); } } return list; } private Response notFound(String operation, String uuid) { return Response.status(Status.NOT_FOUND) .entity(new CrimeServiceStatus(operation, "error", "Crime with given UUID '" + uuid + "' does not exist")) .build(); } private Response error(String operation, String errorMessage) { return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(new CrimeServiceStatus(operation, "error", errorMessage)) .build(); } }
true
e33d2101d14d8416a74eb5a889c60a0ea93e8783
Java
hft-uc/Haushaltsapp
/app/src/main/java/com/example/haushaltsapp/slideshow/Category.java
UTF-8
1,025
2.28125
2
[ "MIT" ]
permissive
package com.example.haushaltsapp.slideshow; import android.graphics.Color; import com.example.haushaltsapp.R; public class Category { private final String id; private String name; private final int backgroundColor; private final int resourceID; public Category(String id, String visibleName, int iconResourceID, int backgroundColor) { this.id = id; this.name = visibleName; this.resourceID = iconResourceID; this.backgroundColor = backgroundColor; } public String getCategoryID() { return id; } private static Category[] categories = new Category[]{ new Category(":others", "Others", R.drawable.ic_menu_camera, Color.parseColor("#455a64")), new Category(":clothing", "Clothing", R.drawable.ic_action_send, Color.parseColor("#d32f2f")), }; public static Category[] getDefaultCategories() { return categories; } @Override public String toString() { return getCategoryID(); } }
true
1dcdfc21099a882db692389b3629688b53fb871d
Java
zhangxiaoyu185/oilcard
/src/main/java/com/xiaoyu/lingdian/service/CoreRechargeRecordService.java
UTF-8
1,666
2.046875
2
[]
no_license
package com.xiaoyu.lingdian.service; import com.xiaoyu.lingdian.core.mybatis.page.Page; import com.xiaoyu.lingdian.entity.CoreRechargeRecord; import java.util.List; /** * 充值记录表 */ public interface CoreRechargeRecordService { /** * 添加 * * @param coreRechargeRecord * @return */ public boolean insertCoreRechargeRecord(CoreRechargeRecord coreRechargeRecord); /** * 修改 * * @param coreRechargeRecord * @return */ public boolean updateCoreRechargeRecord(CoreRechargeRecord coreRechargeRecord); /** * 查询 * * @param coreRechargeRecord * @return */ public CoreRechargeRecord getCoreRechargeRecord(CoreRechargeRecord coreRechargeRecord); /** * 根据状态获取充值总额 * @param crrerStatus * @return */ public Double getCoreRechargeRecordSumByTotal(int crrerStatus); /** * 根据状态获取当月充值 * @param crrerStatus * @return */ public Double getCoreRechargeRecordSumByMonth(int crrerStatus); /** * 根据状态获取当日充值 * @param crrerStatus * @return */ public Double getCoreRechargeRecordSumByDay(int crrerStatus); /** * 获取我的所有充值所有page * * @return List */ public Page<CoreRechargeRecord> findCoreRechargeRecordForMy(String crrerUser, int pageNum, int pageSize); /** * 后台查询所有Page * * @return Page */ public Page<CoreRechargeRecord> findCoreRechargeRecordPage(CoreRechargeRecord coreRechargeRecord, String mobile, int pageNum, int pageSize); }
true
2b6343cbc6f7519bd167fb1c5336c40c0a3a1d87
Java
Vinrithi/Quiz4Bible
/java/com/vinrithi/biblequizz/ChooseLevel.java
UTF-8
9,171
2.109375
2
[]
no_license
package com.vinrithi.biblequizz; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.util.SparseArray; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.concurrent.ThreadLocalRandom; public class ChooseLevel extends ToolbarSet implements View.OnClickListener,View.OnTouchListener,CompoundButton.OnCheckedChangeListener, BibleQuizController{ String book=""; RadioGroup rdGroup; RadioButton rdEasy,rdMedium,rdHard; EditText etNumberofQuestions; Button btStart; ProgressDialog dialog; String level = "Easy"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_choose_level); m_toolbar = (Toolbar)findViewById(R.id.include_toolbar); setToolbar(); Bundle bundle = getIntent().getExtras(); if(bundle!=null) { book = bundle.getString("Book"); } rdGroup = (RadioGroup)findViewById(R.id.rdGroup); rdEasy = (RadioButton)findViewById(R.id.rdEasy); rdMedium = (RadioButton)findViewById(R.id.rdMedium); rdHard = (RadioButton)findViewById(R.id.rdHard); etNumberofQuestions = (EditText) findViewById(R.id.etNumberofQuestions); btStart = (Button)findViewById(R.id.btStart); btStart.setOnClickListener(this); btStart.setOnTouchListener(this); dialog = new ProgressDialog(this); dialog.setCancelable(false); dialog.setMessage("Retrieving questions"); rdEasy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { level = buttonView.getText().toString(); Toast.makeText(ChooseLevel.this, level, Toast.LENGTH_SHORT).show(); } } }); rdMedium.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { level = buttonView.getText().toString(); Toast.makeText(ChooseLevel.this, level, Toast.LENGTH_SHORT).show(); } } }); rdHard.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { level = buttonView.getText().toString(); Toast.makeText(ChooseLevel.this, level, Toast.LENGTH_SHORT).show(); } } }); } @Override public void onClick(View v) { switch(v.getId()) { case R.id.btStart: String number_of_quiz = etNumberofQuestions.getText().toString(); if(number_of_quiz.equals("")) { Toast.makeText(this, "Please enter number of questions to answer", Toast.LENGTH_SHORT).show(); return; } int no = Integer.parseInt(number_of_quiz); if(no < 15 || no > 30) { Toast.makeText(this, "Please enter number of questions between 15 and 30", Toast.LENGTH_SHORT).show(); return; } JSONObject postData = new JSONObject(); try { postData.put("book", book); postData.put("level", level); postData.put("numberOfQuestions", number_of_quiz); String url = "http://192.168.137.1/quiz4bible/questions_answers/questions.php"; dialog.show(); new ConnectToServer(ChooseLevel.this,"retrieveQuestions").execute(url,postData.toString()); } catch (JSONException e) { e.printStackTrace(); } break; } } @Override public boolean onTouch(View v, MotionEvent event) { switch(v.getId()) { case R.id.btStart: /*switch (event.getAction()) { case MotionEvent.ACTION_DOWN: v.setBackgroundColor(Color.parseColor("#00B050")); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: v.setBackgroundResource(R.drawable.buttons_bg); break; }*/ break; } return false; } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { buttonView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }); } @Override public ProgressDialog getProgressDialog() { return dialog; } @Override public void resetPreferences() { } @Override public void retrieveData(String result) throws JSONException { if(result!=null) { Gson gson = new Gson(); String[] jsonArray = gson.fromJson(result,String[].class); int len = jsonArray.length/7; int pos0=0,pos1=1,pos2=2,pos3=3,pos4=4,pos5=5,pos6=6; SparseArray<PerQuestionItems> allQuestionsSparseArray = new SparseArray<>(); MyApp myApp = MyApp.getSingleInstance(); for(int i=0;i<len;i++) { String question = jsonArray[pos0]; String questionType = jsonArray[pos6]; List<Integer>positions = new ArrayList<>(); positions.add(pos1); positions.add(pos2); positions.add(pos3); positions.add(pos4); positions.add(pos5); Collections.shuffle(positions); String options[] = {jsonArray[positions.get(0)],jsonArray[positions.get(1)], jsonArray[positions.get(2)],jsonArray[positions.get(3)],jsonArray[positions.get(4)]}; SparseArray<PerAnswerDetails> choicesArray = new SparseArray<>(); int j=0; for (String option : options) { JSONObject object = new JSONObject(option); PerAnswerDetails perAnswerDetails = new PerAnswerDetails( object.getString("Answer"), object.getString("IsAnswer"), object.getString("Description"), object.getString("Verse"), object.getString("Text"), object.getString("Chapter")); choicesArray.put(j++, perAnswerDetails); } PerQuestionItems perQuestionItems = new PerQuestionItems(question,questionType,choicesArray); allQuestionsSparseArray.put(i,perQuestionItems); pos0+=7; pos1+=7; pos2+=7; pos3+=7; pos4+=7; pos5+=7; pos6+=7; } myApp.setAllQuestionsSparseArray(allQuestionsSparseArray); dialog.dismiss(); startActivity(new Intent(this,Questions.class).putExtra("Book",book) .putExtra("AllQuestions",etNumberofQuestions.getText().toString()) .putExtra("Level",level)); } else { Toast.makeText(this, "Could not complete retrieving the questions", Toast.LENGTH_SHORT).show(); } } @Override public SwipeRefreshLayout getRefresher() { return null; } }
true
8641c7b83c3ad4164d08ec30ee9d010c891dbfac
Java
COLTEC-TP/Trimestral-01
/app/src/main/java/br/ufmg/coltec/tp/moreaqui/ImovelDAO.java
UTF-8
2,959
3.171875
3
[]
no_license
package br.ufmg.coltec.tp.moreaqui; import java.util.ArrayList; /** * Classe responsável por fazer o controle da persistência dos imóveis */ public class ImovelDAO { private ArrayList<Imovel> imoveis; // singleton para lidar com única instância do DAO private static ImovelDAO instance; /** * Construtor privado (NÃO UTILIZAR) */ private ImovelDAO() { imoveis = new ArrayList<>(); carregarImoveis(); } /** * Retorna instância do DAO com os imóveis cadastrados até o momento. * * Utilize esse método para recuperar a instância do singleton * * @return Objeto do tipo ImovelDAO */ public static ImovelDAO getInstance() { if(instance == null) instance = new ImovelDAO(); return instance; } /** * Carrega a lista inicial de imóveis */ private void carregarImoveis() { imoveis.add(new Imovel("Flat Savassi", "Av. Getúlio Vargas, 3500, Savassi", "Belo Horizonte", 3000.00, "2314-1514")); imoveis.add(new Imovel("Moradia UFMG", "Flemming", "Belo Horizonte", 850.00, "3409-2525")); imoveis.add(new Imovel("Edifício JK", "Av. Olegário Maciel, 500, Centro", "Belo Horizonte", 1200.00, "99456-4430")); imoveis.add(new Imovel("Casa 3 quartos", "Rua Santa Mônica, 450, Ouro Preto", "Belo Horizonte", 1800.00, "3411-3030")); imoveis.add(new Imovel("Eldorado", "Praça da CEMIG, 500", "Contagem", 800.00, "3350-0670")); imoveis.add(new Imovel("Mansão Mangabeiras", "Av. Afonso Pena, 13000", "Belo Horizonte", 14000.00, "99999-9999")); } /** * Faz a filtragem dos imóveis por nome * * @param nome nome a ser utilizado na filtragem */ public ArrayList<Imovel> filtrarImoveis(String nome) { ArrayList<Imovel> imoveisFiltrados = new ArrayList<>(); // TODO implementar ação de filtragem // Dica: Para implementar a filtragem, você deverá verificar se o parâmetro "nome" // está incluso dentro do nome de cada imóvel (Utilize o String.contains) return imoveisFiltrados; } /** * Adiciona um novo imóvel na lista * * @param novoImovel imóvel que será adicionado na lista */ public void adicionarImovel(Imovel novoImovel) { instance.imoveis.add(novoImovel); } /** * Recupera lista completa dos imóveis * @return ArrayList com todos os imóveis cadastrados no DAO */ public ArrayList<Imovel> getImoveis() { return instance.imoveis; } }
true
8d68b33a3f5089c91e6a8830fd785a987752b51d
Java
Oceantears/IntelIDEAwork
/demo2/src/homework20190904/MathOfComplex.java
UTF-8
1,552
3.578125
4
[]
no_license
package homework20190904; class Complex{ private double real; private double im; public double getReal() { return real; } public void setReal(double real) { this.real = real; } public double getIm() { return im; } public void setIm(double im) { this.im = im; } //复数与复数相加 public Complex add(Complex c){ Complex complex=new Complex(); complex.setReal(this.getReal()+c.getReal()); complex.setIm(this.getIm()+c.getIm()); return complex; } //复数与实数相加 public Complex add(double real){ Complex complex=new Complex(); complex.setReal(this.getReal()+real); return complex; } //复数与复数相减 public Complex sub(Complex c){ Complex complex=new Complex(); complex.setReal(this.getReal()-c.getReal()); complex.setIm(this.getIm()-c.getIm()); return complex; } //复数与实数相减 public Complex sub(double real){ Complex complex=new Complex(); complex.setReal(this.getReal()-real); return complex; } //复数与复数相乘 public Complex mul(Complex c){ Complex complex=new Complex(); return complex; } //复数与实数相乘 public Complex mul(double real){ Complex complex=new Complex(); return complex; } } public class MathOfComplex { public static void main(String[] args) { Complex cop=new Complex(); } }
true
e1362f03c15f799464e99f20fa97c5d3a0be1686
Java
mbirche/saph
/src/main/java/br/com/fatecmogidascruzes/saph/model/User.java
UTF-8
3,678
2.25
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.com.fatecmogidascruzes.saph.model; import java.util.ArrayList; import java.util.List; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Enumerated; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; /** * * @author Birche */ @javax.persistence.Entity @Table(name = "users", schema = "saph") @Inheritance(strategy = InheritanceType.JOINED) @PrimaryKeyJoinColumn(name = "id") public class User extends Entity { private String name; private String surname; @Cascade(CascadeType.ALL) @OneToOne private Credential credential; @ElementCollection @CollectionTable( name="email", joinColumns=@JoinColumn(name="id_user") ) @Column(name="email") private List<String> emails; private String ra; private String rf; @Cascade(CascadeType.ALL) @OneToMany private List<Phone> phones; @ElementCollection @CollectionTable(name = "roles", joinColumns = @JoinColumn(name = "id_user")) @Column(name = "roles") @Enumerated private List<Role> roles; public User(){ phones = new ArrayList<Phone>(); roles = new ArrayList<Role>(); emails = new ArrayList<String>(); credential = new Credential(); } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public List<String> getEmails() { return emails; } public void setEmails(List<String> emails) { this.emails = emails; } public List<Phone> getPhones() { return phones; } public void setPhones(List<Phone> phones) { this.phones = phones; } public String getRa() { return ra; } public void setRa(String ra) { this.ra = ra; } public String getRf() { return rf; } public void setRf(String rf) { this.rf = rf; } public Credential getCredential() { return credential; } public void setCredential(Credential credential) { this.credential = credential; } @Override public int hashCode() { int hash = 7; hash = 23 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 23 * hash + (this.emails != null ? this.emails.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final User other = (User) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if (this.emails != other.emails && (this.emails == null || !this.emails.equals(other.emails))) { return false; } return true; } }
true
a11e9b2bf693d1f2a7a10647312e016b4bd4849c
Java
xiajngsi/zefun
/src/main/java/com/zefun/web/entity/GiftmoneyDetail.java
UTF-8
3,512
2.21875
2
[]
no_license
package com.zefun.web.entity; import java.math.BigDecimal; /** * 礼金明细 * @author 王大爷 * @date 2015年9月10日 下午4:56:08 */ public class GiftmoneyDetail { /** 礼金明细标识*/ private Integer detail; /** 礼金账户标识*/ private Integer accountId; /** 明细标识*/ private Integer detailId; /** 礼金总金额*/ private BigDecimal totalAmount; /** 当期礼金金额*/ private BigDecimal nowMoney; /** 当期剩余礼金*/ private BigDecimal residueNowMoney; /** 剩余分期数量*/ private Integer partNumber; /** 分期类型*/ private Integer partType; /** 当期赠送时间*/ private String startDate; /** 当期过期时间*/ private String endDate; /** 创建时间*/ private String createTime; /** 是否删除(0:未删除,1:已删除)*/ private Integer isDeleted; /** 是否赠送(0:未赠送,1:已赠送)*/ private Integer isPresent; /** 最后操作人标识*/ private Integer lastOperatorId; public Integer getIsPresent() { return isPresent; } public void setIsPresent(Integer isPresent) { this.isPresent = isPresent; } public BigDecimal getResidueNowMoney() { return residueNowMoney; } public void setResidueNowMoney(BigDecimal residueNowMoney) { this.residueNowMoney = residueNowMoney; } public Integer getDetailId() { return detailId; } public void setDetailId(Integer detailId) { this.detailId = detailId; } public Integer getDetail() { return detail; } public void setDetail(Integer detail) { this.detail = detail; } public Integer getAccountId() { return accountId; } public void setAccountId(Integer accountId) { this.accountId = accountId; } public BigDecimal getTotalAmount() { return totalAmount; } public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; } public BigDecimal getNowMoney() { return nowMoney; } public void setNowMoney(BigDecimal nowMoney) { this.nowMoney = nowMoney; } public Integer getPartNumber() { return partNumber; } public void setPartNumber(Integer partNumber) { this.partNumber = partNumber; } public Integer getPartType() { return partType; } public void setPartType(Integer partType) { this.partType = partType; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate == null ? null : startDate.trim(); } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate == null ? null : endDate.trim(); } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime == null ? null : createTime.trim(); } public Integer getIsDeleted() { return isDeleted; } public void setIsDeleted(Integer isDeleted) { this.isDeleted = isDeleted; } public Integer getLastOperatorId() { return lastOperatorId; } public void setLastOperatorId(Integer lastOperatorId) { this.lastOperatorId = lastOperatorId; } }
true
cfd0007a820aa94dfe37a06a29d82a3e21c39e16
Java
Ilyuza/AD_01
/src/aufgabe_1_1/Util.java
UTF-8
1,731
3.65625
4
[]
no_license
package aufgabe_1_1; /** * Wenn ihr was an dem Programm aendert, vergesst nicht die Versionsnummer * irgendwie zu aendern. * * @author Gruppe 3 * @version 1.00 */ public class Util { // Hilfsmethode um uebergebene ints auf doppelte Eintraege zu pruefen public static boolean checkForMultipleNumber(int[] numbers) { int start = 0; do { for (int i = start + 1; i < numbers.length; i++) { if (numbers[start] == numbers[i]) { return true; } } start++; } while (start < numbers.length - 1); return false; } public static boolean checkForGaps(int[] numbers) { for (int i = 0; i < numbers.length; i++) { if (numbers[i] > numbers.length) { return true; } } return false; } public static int calculateFaculty(int val) { int fakultaet = 1; for (int zahl = 1; zahl <= val; zahl++) { fakultaet = fakultaet * zahl; } return fakultaet; } public static void exchangeInt(int[] arr, int index1, int index2) { int tmp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = tmp; } public static String parseExp(String exp) { char[] expStrings = {'⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹'}; StringBuffer ret = new StringBuffer(); if (exp.length() == 1 && exp.equals("1")) { return ""; } for (int i = 0; i < exp.length(); i++) { ret.append(expStrings[Integer.parseInt(exp.substring(i, i+1))]); } return ret.toString(); } }
true
e92add3bc0a7ca24c909c30625fea3fbbb094612
Java
omnispot-ds/omnispot
/designer/src/com/kesdip/designer/command/LayoutCreationCommand.java
UTF-8
1,085
2.546875
3
[]
no_license
package com.kesdip.designer.command; import org.eclipse.gef.commands.Command; import com.kesdip.designer.model.Deployment; import com.kesdip.designer.model.Layout; public class LayoutCreationCommand extends Command { private final Layout layout; private final Deployment deployment; public LayoutCreationCommand(Layout layout, Deployment deployment) { this.layout = layout; this.deployment = deployment; setLabel("layout creation"); } /** * Can execute if all the necessary information has been provided. * @see org.eclipse.gef.commands.Command#canExecute() */ public boolean canExecute() { return layout != null && deployment != null; } /* (non-Javadoc) * @see org.eclipse.gef.commands.Command#execute() */ public void execute() { redo(); } /* (non-Javadoc) * @see org.eclipse.gef.commands.Command#redo() */ public void redo() { deployment.add(layout); } /* (non-Javadoc) * @see org.eclipse.gef.commands.Command#undo() */ public void undo() { deployment.removeChild(layout); } }
true
662aad0ebb7fbf3569cb9763fbeac4e3ae0ff182
Java
fajarsiddiq/LAW-C2
/src/java/Konten/KontakBean.java
UTF-8
2,235
2.109375
2
[ "MIT" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Konten; /** * * @author Fajar Siddiq */ public class KontakBean { private String nama, noHp, emailLain, akunFb, akunTwitter, pinBbm; /** * */ public KontakBean() { } /** * * @param nama * @param noHp * @param emailLain * @param akunFb * @param akunTwitter * @param pinBbm */ public KontakBean(String nama, String noHp, String emailLain, String akunFb, String akunTwitter, String pinBbm) { this.nama = nama; this.noHp = noHp; this.emailLain = emailLain; this.akunFb = akunFb; this.akunTwitter = akunTwitter; this.pinBbm = pinBbm; } /** * * @return */ public String getNama() { return nama; } /** * * @param nama */ public void setNama(String nama) { this.nama = nama; } /** * * @return */ public String getNoHp() { return noHp; } /** * * @param noHp */ public void setNoHp(String noHp) { this.noHp = noHp; } /** * * @return */ public String getEmailLain() { return emailLain; } /** * * @param emailLain */ public void setEmailLain(String emailLain) { this.emailLain = emailLain; } /** * * @return */ public String getAkunFb() { return akunFb; } /** * * @param akunFb */ public void setAkunFb(String akunFb) { this.akunFb = akunFb; } /** * * @return */ public String getAkunTwitter() { return akunTwitter; } /** * * @param akunTwitter */ public void setAkunTwitter(String akunTwitter) { this.akunTwitter = akunTwitter; } /** * * @return */ public String getPinBbm() { return pinBbm; } /** * * @param pinBbm */ public void setPinBbm(String pinBbm) { this.pinBbm = pinBbm; } }
true
5b79e324cf3dbd58fdc6199b17635dadda2e5666
Java
martinpg2001/xcase
/platform/src/java/com/xcase/intapp/time/SimpleTimeImpl.java
UTF-8
1,328
2.109375
2
[]
no_license
package com.xcase.intapp.time; import com.xcase.intapp.time.impl.simple.core.TimeConfigurationManager; import com.xcase.intapp.time.impl.simple.methods.*; import com.xcase.intapp.time.transputs.*; import java.lang.invoke.MethodHandles; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class SimpleTimeImpl implements TimeExternalAPI { /** * log4j logger. */ protected static final Logger LOGGER = LogManager.getLogger(MethodHandles.lookup().lookupClass()); /** * configuration manager */ public TimeConfigurationManager localConfigurationManager = TimeConfigurationManager.getConfigurationManager(); /** * method implementation. */ private GetClientsMethod getClientsMethod = new GetClientsMethod(); /** * method implementation. */ private GetRestrictedTextsMethod getRestrictedTextsMethod = new GetRestrictedTextsMethod(); @Override public GetClientsResponse getClients(GetClientsRequest getClientsRequest) { return this.getClientsMethod.getClients(getClientsRequest); } @Override public GetRestrictedTextsResponse getRestrictedTexts(GetRestrictedTextsRequest getRestrictedTextsRequest) { return this.getRestrictedTextsMethod.getRestrictedTexts(getRestrictedTextsRequest); } }
true
1e20ba42d2d7e9961f2b764f7a339a26472a09a3
Java
emkutuk/java-practices
/emre-kutuk-644851-end-assignment/src/service/Customer_SERVICE.java
UTF-8
711
2.4375
2
[]
no_license
package service; import dal.Customer_DAO; import model.Customer; import java.util.List; public class Customer_SERVICE { Customer_DAO customer_db = new Customer_DAO(); public List<Customer> GetAllCustomers() { try { return customer_db.GetAllCustomers(); } catch (Exception e) { e.printStackTrace(); return null; } } public void AddCustomers(List<Customer> customers) { try { customer_db.AddCustomers(customers); } catch (Exception e) { e.printStackTrace(); } } public void AddOneCustomer(Customer customer) { try{ customer_db.AddOneCustomer(customer); } catch (Exception e) { e.printStackTrace(); } } }
true
c302f81e9c67084bfaee9af3d882515af82bce4b
Java
Monica1009/OOP
/src/com/company/Depozit/Main.java
UTF-8
920
3
3
[]
no_license
package com.company.Depozit; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Colet colet1= new Colet("Strada Parcului"); Colet colet2= new Colet("Strada Anghelescu"); Colet colet3= new Colet("strada Iordanescu"); Colet colet4= new Colet ("Strada Vladimirescu"); Map<String, ArrayList<Colet>> depositul= new HashMap<>(); ArrayList<Colet> coleteDin1A= new ArrayList<>(); coleteDin1A.add(colet1); coleteDin1A.add(colet2); depositul.put("1A",coleteDin1A); ArrayList<Colet> coletedin1B = new ArrayList<>(); coletedin1B.add(colet3); coletedin1B.add(colet4); depositul.put("1B", coletedin1B); ArrayList<Colet> coleteDeLa1B= depositul.get("1B"); for(Colet colet: coleteDeLa1B){ System.out.println(colet.getAdresa()); } } }
true
3fca3802740616e0e03b29fd3953a73a72e1d534
Java
a654087143/logbackDBAppender
/src/main/java/com/pheonix/logging/PheonixAuditDBAppender.java
UTF-8
4,483
2.1875
2
[]
no_license
package com.pheonix.logging; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Map; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import ch.qos.logback.classic.db.DBAppender; import ch.qos.logback.classic.spi.ILoggingEvent; public class PheonixAuditDBAppender extends DBAppender { final static Logger log = LoggerFactory.getLogger(PheonixAuditDBAppender.class); protected String insertPropertiesSQL; protected String insertExceptionSQL; protected String insertSQL; protected static final Method GET_GENERATED_KEYS_METHOD; private PheonixDBNameResolver dbNameResolver; @Autowired DataSource dataSource; public Connection getConnection() throws SQLException { if(dataSource!=null) return dataSource.getConnection(); return getConnectionSource().getConnection(); } static { Method getGeneratedKeysMethod; try { getGeneratedKeysMethod = PreparedStatement.class.getMethod("getGeneratedKeys", (Class[]) null); } catch (Exception ex) { getGeneratedKeysMethod = null; } GET_GENERATED_KEYS_METHOD = getGeneratedKeysMethod; } public PheonixAuditDBAppender(){} public PheonixDBNameResolver getDbNameResolver() { return dbNameResolver; } public void setDbNameResolver(PheonixDBNameResolver dbNameResolver) { this.dbNameResolver = dbNameResolver; } @Override public void start() { super.start(); if (dbNameResolver == null) dbNameResolver = new PheonixDBNameResolver(); insertSQL = PheonixSQLBuilder.buildInsertSQL(dbNameResolver); } @Override protected void subAppend(ILoggingEvent event, Connection connection, PreparedStatement insertStatement) throws Throwable { boolean isAuditable = checkForAudit(event); if(isAuditable) { bindLoggingEventWithInsertStatement(insertStatement, event); System.out.println("=== INSERT STATEMENT === " + insertStatement); int updateCount = -1; try { updateCount = insertStatement.executeUpdate(); } catch (Exception e) { log.error(" ERROR "); e.printStackTrace(); } System.out.println(" updateCount = "+ updateCount); if (updateCount != 1) { log.error(" ERROR IT IS "); addWarn("Failed to insert loggingEvent"); } } } private boolean checkForAudit(ILoggingEvent event) { String logdata = event.getFormattedMessage(); if(logdata.contains("AUDIT#")) { return true; } return false; } protected void secondarySubAppend(ILoggingEvent event, Connection connection, long eventId) throws Throwable { } private void bindLoggingEventWithInsertStatement(PreparedStatement stmt, ILoggingEvent event) throws SQLException { String logdata = event.getFormattedMessage(); log.debug(" logdata = "+ logdata); parseLogData(logdata.substring(logdata.indexOf("#")+1), stmt); } private void parseLogData(String logdata, PreparedStatement stmt) throws SQLException { String requestid = null; String submission_date = null; String eID = null; String status = null; String service = null; String authnContextClassRef = null; String ipaddresss = null; try { if(logdata.contains(",")) { String[] entries = logdata.split(","); if (null != entries && entries.length > 0) { submission_date = entries[0]; requestid = entries[1]; eID = entries[2]; status = entries[3]; service = entries[4]; authnContextClassRef = entries[5]; ipaddresss = entries[6]; } stmt.setString(1, submission_date); stmt.setString(2, requestid); stmt.setString(3, eID); stmt.setString(4, status); stmt.setString(5, service); stmt.setString(6, authnContextClassRef); stmt.setString(7, ipaddresss); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { requestid = null; submission_date = null; eID = null; status = null; service = null; authnContextClassRef = null; ipaddresss = null; } } @Override protected Method getGeneratedKeysMethod() { return GET_GENERATED_KEYS_METHOD; } @Override protected String getInsertSQL() { return insertSQL; } protected void insertProperties(Map<String, String> mergedMap, Connection connection, long eventId) throws SQLException { } }
true
f70accb443db4b4201e3c2dc207c4bedca4134a0
Java
poojajadhavkip/Selenium
/Scripts/PageFactory/src/FacebookLoginTest.java
UTF-8
1,132
2.390625
2
[]
no_license
import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; public class FacebookLoginTest { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.gecko.driver","/home/kiprosh-hp-g6/Desktop/geckodriver"); //System.setProperty("webdriver.gecko.driver", "./libs/geckodriver.exe"); WebDriver ref=new FirefoxDriver(); ref.get("https://www.facebook.com"); ref.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //WebDriver ref=new FirefoxDriver(); //ref.get("https://www.facebook.com"); /* FacebookLogin fb=new FacebookLogin(ref); fb.login("jadhavpooja103@gmail.com", "123456789"); fb.submit();*/ /* METHOD2 FbLoginMethod2 fb1=new FbLoginMethod2(ref); PageFactory.initElements(ref, fb1); Thread.sleep(2000); fb1.login("jadhavpooja103@gmail.com", "123456789"); Thread.sleep(2000); fb1.submit(); */ FbLoginMethod2 fb1; fb1=PageFactory.initElements(ref, FbLoginMethod2.class); fb1.login("jadhavpooja103@gmail.com", "123456789"); fb1.submit(); } }
true
26085b79ec92d0455963ebd33385323e4a94712d
Java
adioss/cryptoMemo
/src/main/java/com/adioss/security/symmetric/block/ModeForSymmetricEncryption.java
UTF-8
4,250
2.796875
3
[ "Apache-2.0" ]
permissive
package com.adioss.security.symmetric.block; import javax.crypto.*; import javax.crypto.spec.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.adioss.security.Utils; import com.google.common.annotations.VisibleForTesting; import static com.adioss.security.symmetric.SymmetricEncryptConstant.INPUT; import static com.adioss.security.symmetric.SymmetricEncryptTools.*; class ModeForSymmetricEncryption { private static final Logger LOG = LoggerFactory.getLogger(ModeForSymmetricEncryption.class); /** * Symmetric encrypt by block with ECB mode: PKCS7 Padding using DES cipher * Problem: show that we can discovering patterns */ @VisibleForTesting static void encryptWithECB() throws Exception { LOG.debug("encryptWithECB"); byte[] keyBytes = new byte[]{0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef}; SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); // here ECB Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); simpleEncryptDecrypt(INPUT, key, cipher); // print cipher: 3260266c2cf202e28325790654a444d93260266c2cf202e2086f9a1d74c94d4e bytes: 32 // we can see that 3260266c2cf202e2 is printed two times: same encryption pattern discovery } /** * Symmetric encrypt by block with CBC mode: PKCS7 Padding using DES cipher and IV */ @VisibleForTesting static void encryptWithCBC() throws Exception { LOG.debug("encryptWithCBC"); byte[] keyBytes = new byte[]{0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef}; byte[] ivBytes = Utils.generateSecureRandomBytes(8); SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); // used to init cipher IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); encryptDecryptWithIV(INPUT, key, ivSpec, cipher); } /** * Symmetric encrypt by block with CBC mode: PKCS7 Padding using DES cipher and secure random IV */ @VisibleForTesting static void encryptWithCBCWithSecureRandomIV() throws Exception { LOG.debug("encryptWithCBCWithSecureRandomIV"); byte[] keyBytes = new byte[]{0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef}; byte[] ivBytes = Utils.generateSecureRandomBytes(8); SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); // used to init cipher IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); // secure random can be done by calling cipher method too // see => IvParameterSpec ivSpec = new IvParameterSpec(cipher.getIV()); encryptDecryptWithIV(INPUT, key, ivSpec, cipher); } /** * Symmetric encrypt by block with CTS mode: no padding using DES cipher and IV */ @VisibleForTesting static void encryptWithCTS() throws Exception { LOG.debug("encryptWithCTS"); byte[] keyBytes = new byte[]{0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef}; byte[] ivBytes = Utils.generateSecureRandomBytes(8); SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); // used to init cipher IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.getInstance("DES/CTS/NoPadding"); encryptDecryptWithIV(INPUT, key, ivSpec, cipher); } /** * Symmetric encrypt by block with CTR mode: no padding using DES cipher and IV */ @VisibleForTesting static void encryptWithCTR() throws Exception { LOG.debug("encryptWithCBC"); byte[] keyBytes = new byte[]{0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef}; byte[] ivBytes = new byte[]{0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00}; SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); // used to init cipher IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.getInstance("DES/CTR/NoPadding"); encryptDecryptWithIV(INPUT, key, ivSpec, cipher); } private ModeForSymmetricEncryption() { } }
true
312d7836d355b997ce0604c7ae2298dee0789183
Java
vinod88paliwal/temp
/JavaBasics/JavaBasics/Labs/src/com/collectios/basics/SortedSetWithNonComparableClass.java
UTF-8
360
2.90625
3
[]
no_license
package com.collectios.basics; import java.util.SortedSet; import java.util.TreeSet; public class SortedSetWithNonComparableClass { public static void main(String[] args) { SortedSet ss = new TreeSet(); Emp e1 = new Emp(); Emp e2 = new Emp(); Emp e3 = new Emp(); ss.add(e1); ss.add(e2); ss.add(e3); System.out.println(ss); } }
true
7e3fb4d8b56f7b566bc3ae3b7319c3273224be86
Java
minhdn7/VnptQuanLyHotel
/app/src/main/java/com/vnpt/hotel/manager/domain/model/roomtype/RoomTypeFindByHotel.java
UTF-8
501
1.695313
2
[]
no_license
package com.vnpt.hotel.manager.domain.model.roomtype; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import lombok.Getter; import lombok.Setter; /** * Created by LiKaLi on 3/12/2018. */ public class RoomTypeFindByHotel { @Expose @Setter @Getter @SerializedName("pageSize") public int pageSize; @Expose @Setter @Getter @SerializedName("pageIndex") public int pageIndex; @Expose @Setter @Getter @SerializedName("hotelId") public int hotelId; }
true
1e3c734894f7b05224c8352071d0080bc9dab3c4
Java
sriniin16/TestNGExtent
/src/test/automation/AppTest.java
UTF-8
3,148
2.15625
2
[]
no_license
import com.aventstack.extentreports.Status; import org.testng.annotations.*; import Reporting.ExtentTestManager; public class AppTest { @BeforeSuite public void suiteSetup() { System.out.println("inside suite setup"); // ExtentTestManager.getTest().log(Status.INFO,"inside suite setup"); } @AfterSuite public void suiteTeardown() { System.out.println("inside suite teardown"); // ExtentTestManager.getTest().log(Status.INFO,"inside suite teardown"); } @BeforeTest public void beforeTest() { System.out.println("inside before test"); // ExtentTestManager.getTest().log(Status.INFO,"inside before test"); } @AfterTest public void afterTest() { System.out.println("inside after test"); // ExtentTestManager.getTest().log(Status.INFO,"inside after test"); } @BeforeGroups("smoke") public void beforeGroup() { System.out.println("inside before group"); // ExtentTestManager.getTest().log(Status.INFO,"inside before group"); } @AfterGroups("smoke") public void afterGroup() { System.out.println("inside after group"); // ExtentTestManager.getTest().log(Status.INFO,"inside after group"); } @BeforeClass public void beforeClass() { System.out.println("inside before class "+getClass().getName()); // ExtentTestManager.getTest().log(Status.INFO,"inside before class"); } @AfterClass public void afterClass() { System.out.println("inside after class "+getClass().getName()); // ExtentTestManager.getTest().log(Status.INFO,"inside after class"); } @BeforeMethod public void beforeMethod() { System.out.println("inside before method"); // ExtentTestManager.getTest().log(Status.INFO,"inside before method"); } @AfterMethod public void afterMethod() { System.out.println("inside after method"); // ExtentTestManager.getTest().log(Status.INFO,"inside after method"); } @Test public void test1() { System.out.println("inside test 1"); ExtentTestManager.getTest().log(Status.INFO,"inside test 1"); } @Test public void test2() { System.out.println("inside test 2"); ExtentTestManager.getTest().log(Status.INFO,"inside test 2"); } @Test public void test3() { System.out.println("inside test 3"); ExtentTestManager.getTest().log(Status.INFO,"inside test 3"); } @Test(groups = {"smoke"}) public void test4() { System.out.println("inside test 4 smoke"); ExtentTestManager.getTest().log(Status.INFO,"inside test 4 smoke"); } @Test(groups = {"smoke"}) public void test5() { System.out.println("inside test 5 smoke"); ExtentTestManager.getTest().log(Status.INFO,"inside test 5 smoke"); } @Test(groups = {"smoke"}) public void test6() { System.out.println("inside test 6 smoke"); ExtentTestManager.getTest().log(Status.INFO,"inside test 6 smoke"); } }
true
087f46f83ca301a5df6f6bc1f4ce7a5ef7ad25b3
Java
Gear61/PADFriendFinder-Android
/app/src/main/java/com/randomappsinc/padfriendfinder/API/Callbacks/StandardCallback.java
UTF-8
1,088
2.421875
2
[ "Apache-2.0" ]
permissive
package com.randomappsinc.padfriendfinder.API.Callbacks; import com.randomappsinc.padfriendfinder.API.ApiConstants; import com.randomappsinc.padfriendfinder.API.Events.SnackbarEvent; import de.greenrobot.event.EventBus; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by alexanderchiou on 2/26/16. */ public class StandardCallback<T> implements Callback<T> { protected String screen; protected String errorMessage; public StandardCallback (String screen, String errorMessage) { this.screen = screen; this.errorMessage = errorMessage; } @Override public void onResponse(Call<T> call, Response<T> response) { if (response.code() != ApiConstants.STATUS_OK) { EventBus.getDefault().post(new SnackbarEvent(screen, errorMessage)); } else { EventBus.getDefault().post(response.body()); } } @Override public void onFailure(Call<T> call, Throwable t) { EventBus.getDefault().post(new SnackbarEvent(screen, errorMessage)); } }
true
d75f836aeca6f7e241d48a32fc4221779d62affe
Java
wangganglab/leet-code
/src/main/java/offer/T16_数值的整数次方.java
UTF-8
3,092
3.625
4
[]
no_license
package offer; import org.junit.jupiter.api.Test; /** * https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/ */ public class T16_数值的整数次方 { /** * 【二分法】 * 执行用时 :1 ms, 在所有 Java 提交中击败了90.13% 的用户 * 内存消耗 :37.1 MB, 在所有 Java 提交中击败了100.00%的用户 */ public double myPow(double x, int n) { if (x == 0) { if (n != 0) return 0; throw new IllegalArgumentException("x和n不能同时为0"); } else { if (n >= 0) return activePow(x, n); return negativePow(x, n); } } /** * 【优化代码】 * 执行用时 :1 ms, 在所有 Java 提交中击败了90.82% 的用户 * 内存消耗 :37.3 MB, 在所有 Java 提交中击败了100.00%的用户 */ public double myPow2(double x, int n) { if (x == 0) return 0; if (x == 1 || n == 0) return 1; if (n == 1) return x; if (n < 0) return myPow2(1 / x, -(n + 1)) / x; // 这么处理是为了防止计算-Integer.MIN_VALUE // n > 0 if ((n & 1) == 1) return x * myPow2(x * x, (n - 1) >> 1); return myPow2(x * x, n >> 1); } // 要采用二分法计算幂,避免超时 private double activePow(double x, int n) { if (n == 0) return 1; if (n == 1) return x; double res = 1; if ((n & 1) == 1) { // 奇数 double temp = activePow(x, (n - 1) >> 1); res *= (x * temp * temp); } else { double temp = activePow(x, n >> 1); res *= (temp * temp); } return res; } private double negativePow(double x, int n) { // n传进来是负数 double r = 1 / x; if (n == -1) return r; double res = 1; if ((-n) % 2 == 1) { double temp = negativePow(x, (n + 1) >> 1); res *= (r * temp * temp); } else { double temp = negativePow(x, n >> 1); res *= (temp * temp); } return res; } @Test public void test() { System.out.println(myPow(0.0, 2)); // 0.0 System.out.println(myPow(2.0, 0)); // 1.0 System.out.println(myPow(2.0, 1)); // 2.0 System.out.println(myPow(2.0, 10)); // 1024.0 System.out.println(myPow(2.0, -1)); // 0.5 System.out.println(myPow(2.0, -2)); // 0.25 System.out.println(myPow(1.0, -2147483647)); // 1.0 System.out.println(myPow(2.0, -2147483648)); // 0.0 } @Test public void test2() { System.out.println(myPow2(0.0, 2)); // 0.0 System.out.println(myPow2(2.0, 0)); // 1.0 System.out.println(myPow2(2.0, 1)); // 2.0 System.out.println(myPow2(2.0, 10)); // 1024.0 System.out.println(myPow2(2.0, -1)); // 0.5 System.out.println(myPow2(2.0, -2)); // 0.25 System.out.println(myPow2(1.0, -2147483647)); // 1.0 System.out.println(myPow2(2.0, -2147483648)); // 注意 -Integer.MIN_VALUE还是它本身 } }
true
c6069ef3800ab1f85f2984ce797809316794fcd5
Java
tarun2791/Java
/RunnableExamples/Algorithms/BinarySearch/Main.java
UTF-8
609
3.296875
3
[]
no_license
public class Main { public static void main(String args[]) { double [] x={-2.3,4,5.5,6,8,12.67,34,5}; double value=99; //set the lower and upper bounds int lower=0; int upper=x.length-1; int middle=0; int position=0; while(lower<upper) { middle=(upper+lower)/2; if(value>x[middle]) { lower=middle+1; position++; } else if(value<x[middle]) { upper=middle-1; position++; } else { break; } } if(lower>upper) { System.out.println("Not Found"); } else { System.out.println("Found at :"+position+" position"); } } }
true
668071daffefc9b2c3c428761f10ac2243289648
Java
emilianbold/netbeans-releases
/vmd.midp/src/org/netbeans/modules/vmd/midp/analyzer/ResourcesAnalyzerPanel.java
UTF-8
10,405
1.578125
2
[]
no_license
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.vmd.midp.analyzer; import org.netbeans.modules.vmd.api.model.DesignComponent; import org.netbeans.modules.vmd.api.model.DesignDocument; import org.netbeans.modules.vmd.api.model.Debug; import org.netbeans.modules.vmd.api.model.presenters.InfoPresenter; import org.netbeans.modules.vmd.api.model.presenters.actions.DeleteSupport; import org.netbeans.modules.vmd.midp.components.resources.ResourceCD; import org.openide.util.NbBundle; import javax.swing.*; import java.awt.*; import java.util.*; import java.util.List; /** * * @author Anton Chechel */ public class ResourcesAnalyzerPanel extends javax.swing.JPanel { private DesignDocument document; private Map<Long, String> resourceNames; private Map<Long, Icon> resourceIcons; private List<Long> resourceIDs; private Icon resourceIcon = new ImageIcon(ResourceCD.ICON_PATH); ResourcesAnalyzerPanel() { initComponents(); resourceIDs = new ArrayList<Long>(); resourceNames = new HashMap<Long, String>(); resourceIcons = new HashMap<Long, Icon>(); resourcesList.setCellRenderer(new ResourcesListRenderer()); } void setUnusedResources(DesignDocument document,List<DesignComponent> resources) { Collections.sort (resources, new Comparator<DesignComponent>() { public int compare (DesignComponent c1, DesignComponent c2) { int i = c1.getType ().toString ().compareToIgnoreCase (c2.getType ().toString ()); if (i != 0) return i; String s1 = InfoPresenter.getDisplayName (c1); String s2 = InfoPresenter.getDisplayName (c2); if (s1 != null) { i = s1.compareToIgnoreCase (s2); if (i != 0) return i; return s1.compareTo (s2); } else return s2 != null ? 1 : 0; } }); // do not change list if the resource are equal if (resources.size() == resourceIDs.size()) { for (int i = 0; i < resources.size(); i++) { if (resources.get(i).getComponentID() == resourceIDs.get(i)) { return; } } } resourceIDs.clear (); resourceNames.clear (); resourceIcons.clear (); this.document = document; ((DefaultListModel) resourcesList.getModel()).removeAllElements(); if (resources.isEmpty ()) { ((DefaultListModel) resourcesList.getModel()).addElement(NbBundle.getMessage (ResourcesAnalyzerPanel.class, "ResourcesAnalyzer.nothing-found")); // NOI18N resourcesList.clearSelection (); } else { for (DesignComponent resource : resources) { resourceIDs.add (resource.getComponentID ()); InfoPresenter info = resource.getPresenter (InfoPresenter.class); String resourceName; Image image; if (info != null) { resourceName = info.getDisplayName (InfoPresenter.NameType.PRIMARY); image = info.getIcon (InfoPresenter.IconType.COLOR_16x16); } else { Debug.warning ("Missing InfoPresenter for", resource); // NOI18N resourceName = NbBundle.getMessage (ResourcesAnalyzerPanel.class, "ResourcesAnalyzer.no-label"); // NOI18N image = null; } resourceNames.put (resource.getComponentID (), resourceName); resourceIcons.put (resource.getComponentID (), image != null ? new ImageIcon (image) : this.resourceIcon); ((DefaultListModel) resourcesList.getModel ()).addElement (resource.getComponentID ()); } int size = resourcesList.getModel().getSize(); if (size > 0) { resourcesList.setSelectionInterval(0, size - 1); } } } private void removeUnusedResources(final Object[] selectedElements) { document.getTransactionManager().writeAccess(new Runnable() { public void run() { for (Object selected : selectedElements) { if (! (selected instanceof Long)) continue; DesignComponent resource = document.getComponentByUID((Long) selected); if (resource != null) DeleteSupport.invokeDirectUserDeletion (document, Collections.singleton (resource), false); ((DefaultListModel) resourcesList.getModel()).removeElement(selected); } } }); if (resourcesList.getModel ().getSize () == 0) ((DefaultListModel) resourcesList.getModel()).addElement(NbBundle.getMessage (ResourcesAnalyzerPanel.class, "ResourcesAnalyzer.nothing-found")); // NOI18N } private class ResourcesListRenderer extends DefaultListCellRenderer { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final JLabel renderer = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (document != null && value instanceof Long) { renderer.setText(resourceNames.get((Long) value)); renderer.setIcon(resourceIcons.get((Long) value)); } return renderer; } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { removeButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); resourcesList = new javax.swing.JList(); setPreferredSize(new java.awt.Dimension(400, 150)); org.openide.awt.Mnemonics.setLocalizedText(removeButton, org.openide.util.NbBundle.getMessage(ResourcesAnalyzerPanel.class, "ResourcesAnalyzerPanel.removeButton.text")); // NOI18N removeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeButtonActionPerformed(evt); } }); resourcesList.setModel(new DefaultListModel()); jScrollPane1.setViewportView(resourcesList); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(removeButton)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(removeButton) .addContainerGap(125, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed removeUnusedResources(resourcesList.getSelectedValues()); }//GEN-LAST:event_removeButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton removeButton; private javax.swing.JList resourcesList; // End of variables declaration//GEN-END:variables }
true
1c0a3c8fa0ed2c830ede717d5bed4dcb031e05dc
Java
Rinnion/FormulaTX
/src/src/com/formulatx/archived/database/model/Profile.java
UTF-8
301
2.296875
2
[]
no_license
package com.formulatx.archived.database.model; import java.io.Serializable; public class Profile implements Serializable { public final String name; public final String avatar; public Profile(String name, String avatar) { this.name = name; this.avatar = avatar; } }
true
0908aa5379fcd91b8ece8e980476110c601fdc5e
Java
NUREKN17-JAVA/maksym.huzenko
/src/main/java/ua/nure/itai171/guzenko/usermanagement/web/AddServlet.java
UTF-8
1,031
2.390625
2
[]
no_license
package main.java.ua.nure.itai171.guzenko.usermanagement.web; import main.java.ua.nure.itai171.guzenko.usermanagement.User; import main.java.ua.nure.itai171.guzenko.usermanagement.db.DaoFactory; import main.java.ua.nure.itai171.guzenko.usermanagement.db.DatabaseException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class AddServlet extends EditServlet { @Override protected void showPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException { try { req.getRequestDispatcher(BrowseServlet.EDIT_JSP).forward(req, resp); } catch (IOException e) { e.printStackTrace(); throw new ServletException(e.getMessage()); } } @Override protected void processUser(User userToProcess) throws DatabaseException { DaoFactory.getInstance().getUserDao().create(userToProcess); } }
true
689d1c5fb7837f48ef91fc047a1b8099bb3b0ef8
Java
wkddngus5/java_web_programing
/src/test/java/com/example/demo/UserTests.java
UTF-8
255
1.875
2
[]
no_license
package com.example.demo; import com.example.demo.domain.User; import org.junit.Test; /** * Created by Naver on 2017. 11. 11.. */ public class UserTests { @Test public void test() { User user= new User("name", "passrod"); } }
true
ccf7eec0a432a03b2425189c147490c8fd7ea2d2
Java
VERATUM/J2eeMailManage
/src/com/aerfa/dao/imp/FeedbackDaoImp.java
UTF-8
4,992
2.34375
2
[]
no_license
package com.aerfa.dao.imp; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import com.aerfa.dao.FeedbackDao; import com.aerfa.entity.Feedback; import com.aerfa.utils.JDBCUntils; import com.aerfa.utils.PageInfo; public class FeedbackDaoImp implements FeedbackDao{ QueryRunner qr = new QueryRunner(JDBCUntils.getDataSource()); public int addFeedback(Feedback feedback) { int temp = 0 ; try { String sql = "INSERT INTO feedback (feed_title,feed_time,feed_content,emp_id)VALUES(?,NOW(),?,?)"; temp = qr.update(sql,new Object[]{feedback.getFeed_title(),feedback.getFeed_content(),feedback.getEmp_id()}); } catch (SQLException e) { e.printStackTrace(); } return temp; } public int deleteFeedback(Integer feed_id) { int temp = 0 ; try { String sql = "DELETE FROM feedback WHERE feed_id = ?"; temp = qr.update(sql,feed_id); } catch (SQLException e) { e.printStackTrace(); } return temp; } public int updateFeedback(Feedback feedback) { int temp = 0 ; try { String sql = "UPDATE feedback SET feed_title=?,feed_time=NOW(),feed_content=? WHERE feed_id = ?"; temp = qr.update(sql,new Object[] {feedback.getFeed_title(),feedback.getFeed_content(),feedback.getFeed_id()}); } catch (SQLException e) { e.printStackTrace(); } return temp; } public List<Feedback> selectFeedback() { List<Feedback> list = null; try { String sql = "SELECT * FROM feedback LEFT JOIN empinfo ON(feedback.`emp_id`=empinfo.`emp_id`)"; list = qr.query(sql, new BeanListHandler<>(Feedback.class)); } catch (SQLException e) { e.printStackTrace(); } return list; } public Feedback selectOneFeedback(int feed_id) { Feedback empInfo= null; try { String sql = "SELECT * FROM feedback WHERE feed_id = ?"; empInfo = qr.query(sql,new BeanHandler<>(Feedback.class),feed_id); } catch (SQLException e) { e.printStackTrace(); } System.out.println(empInfo); return empInfo; } public PageInfo<Feedback> currentFeedback(int current,int length) { List<Feedback> feed = null; PageInfo<Feedback> pageInfo = null; try { String sql = "SELECT feedback.*,empinfo.emp_name FROM feedback,empinfo WHERE feedback.emp_id=empinfo.emp_id ORDER BY feedback.feed_id DESC LIMIT ?,?"; String sql1 = "SELECT COUNT(1) FROM feedback"; pageInfo = new PageInfo<Feedback>(); feed = qr.query(sql, new BeanListHandler<>(Feedback.class), (current-1)*length,length); long count = qr.query(sql1, new ScalarHandler<>()); pageInfo.setCount((int)count); pageInfo.setResults(feed); pageInfo.setLength(length); pageInfo.setCurrent(current); } catch (SQLException e) { e.printStackTrace(); } return pageInfo; } public int deleteFeedbackEmp_id(Integer emp_id) { int temp = -1 ; try { String sql = "DELETE FROM feedback WHERE emp_id = ?"; temp = qr.update(sql,emp_id); } catch (SQLException e) { e.printStackTrace(); } return temp; } public int deleteFeedbackEmp_id(String emp_id) { int temp = -1 ; try { String sql = "DELETE FROM feedback WHERE emp_id IN ("+emp_id+")"; temp = qr.update(sql); } catch (SQLException e) { e.printStackTrace(); } return temp; } /*@Test public void getPageInfo() { PageInfo<Feedback> p =this.currentFeedback(2, 5); List<Feedback> list = p.getResults(); System.out.println("总页数"+p.getTotal()); System.out.println("页大小"+p.getLength()); System.out.println("总记录数"+p.getCount()); System.out.println("当前页数"+p.getCurrent()); for (Feedback f : list) { System.out.println(f.getEmp_name()); } } @Test public void testAdd() { Feedback feedback =new Feedback(); feedback.setFeed_content("开发部的人什么时候可以休假啊"); feedback.setFeed_title("月假"); feedback.setEmp_id(3); System.out.println(this.addFeedback(feedback)); } @Test public void testDel() { Integer feed_id=3; System.out.println(this.deleteFeedback(feed_id)); } @Test public void testSeletOne() { Integer feed_id=3; System.out.println(this.selectOneFeedback(feed_id)); } @Test public void testSelet() { System.out.println(this.selectFeedback()); } @Test public void testUpdate() { Feedback feedback =new Feedback(); feedback.setFeed_title("调休"); feedback.setFeed_content("想要两个月的假一起放,去马尔代夫浪一波!"); feedback.setFeed_id(3); System.out.println(this.updateFeedback(feedback)); } @Test public void testSelet() { List<Feedback> lis= this.selectFeedback(); System.out.println(lis.get(1).getEmp_name()); } */ }
true
72749b5a0bc347fe466a948d49a662e361ceb3ac
Java
cosmostation/cosmostation-android
/app/src/main/java/wannabit/io/cosmostaion/activities/txs/kava/HardDetailActivity.java
UTF-8
14,631
1.664063
2
[ "MIT" ]
permissive
package wannabit.io.cosmostaion.activities.txs.kava; import static wannabit.io.cosmostaion.base.BaseConstant.TASK_FETCH_KAVA_HARD_MODULE_ACCOUNT; import static wannabit.io.cosmostaion.base.BaseConstant.TASK_GRPC_FETCH_BALANCE; import static wannabit.io.cosmostaion.base.BaseConstant.TASK_GRPC_FETCH_KAVA_HARD_INTEREST_RATE; import static wannabit.io.cosmostaion.base.BaseConstant.TASK_GRPC_FETCH_KAVA_HARD_MY_BORROW; import static wannabit.io.cosmostaion.base.BaseConstant.TASK_GRPC_FETCH_KAVA_HARD_MY_DEPOSIT; import static wannabit.io.cosmostaion.base.BaseConstant.TASK_GRPC_FETCH_KAVA_HARD_RESERVES; import static wannabit.io.cosmostaion.base.BaseConstant.TASK_GRPC_FETCH_KAVA_HARD_TOTAL_BORROW; import static wannabit.io.cosmostaion.base.BaseConstant.TASK_GRPC_FETCH_KAVA_HARD_TOTAL_DEPOSIT; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import java.math.BigDecimal; import java.util.ArrayList; import cosmos.base.v1beta1.CoinOuterClass; import kava.hard.v1beta1.QueryOuterClass; import wannabit.io.cosmostaion.R; import wannabit.io.cosmostaion.base.BaseActivity; import wannabit.io.cosmostaion.base.BaseChain; import wannabit.io.cosmostaion.base.chains.ChainFactory; import wannabit.io.cosmostaion.dao.Account; import wannabit.io.cosmostaion.model.kava.IncentiveReward; import wannabit.io.cosmostaion.model.type.Coin; import wannabit.io.cosmostaion.network.res.kava.ResKavaModuleAccount; import wannabit.io.cosmostaion.task.FetchTask.KavaHardModuleAccountTask; import wannabit.io.cosmostaion.task.TaskResult; import wannabit.io.cosmostaion.task.gRpcTask.BalanceGrpcTask; import wannabit.io.cosmostaion.task.gRpcTask.KavaHardInterestRateGrpcTask; import wannabit.io.cosmostaion.task.gRpcTask.KavaHardMyBorrowGrpcTask; import wannabit.io.cosmostaion.task.gRpcTask.KavaHardMyDepositGrpcTask; import wannabit.io.cosmostaion.task.gRpcTask.KavaHardReservesGrpcTask; import wannabit.io.cosmostaion.task.gRpcTask.KavaHardTotalBorrowGrpcTask; import wannabit.io.cosmostaion.task.gRpcTask.KavaHardTotalDepositGrpcTask; import wannabit.io.cosmostaion.utils.WUtil; import wannabit.io.cosmostaion.widget.BaseHolder; import wannabit.io.cosmostaion.widget.kava.HardDetailInfoHolder; import wannabit.io.cosmostaion.widget.kava.HardDetailMyAvailableHolder; import wannabit.io.cosmostaion.widget.kava.HardDetailMyStatusHolder; public class HardDetailActivity extends BaseActivity { private Toolbar mToolbar; private SwipeRefreshLayout mSwipeRefreshLayout; private RecyclerView mRecyclerView; private RelativeLayout mLoadingLayer; private HardDetailAdapter mAdapter; private Account mAccount; private BaseChain mBaseChain; private String mHardMoneyMarketDenom; private ArrayList<QueryOuterClass.MoneyMarketInterestRate> mInterestRates = new ArrayList<>(); private ArrayList<Coin> mModuleCoins = new ArrayList<>(); private ArrayList<CoinOuterClass.Coin> mReserveCoins = new ArrayList<>(); private ArrayList<CoinOuterClass.Coin> mTotalDeposit = new ArrayList<>(); private ArrayList<CoinOuterClass.Coin> mTotalBorrow = new ArrayList<>(); private ArrayList<QueryOuterClass.DepositResponse> mMyDeposit = new ArrayList<>(); private ArrayList<QueryOuterClass.BorrowResponse> mMyBorrow = new ArrayList<>(); private IncentiveReward mIncentiveRewards; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hard_detail); initView(); loadData(); } public void initView() { mToolbar = findViewById(R.id.tool_bar); mSwipeRefreshLayout = findViewById(R.id.layer_refresher); mRecyclerView = findViewById(R.id.recycler); mLoadingLayer = findViewById(R.id.loadingLayer); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mSwipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(HardDetailActivity.this, R.color.colorPrimary)); mSwipeRefreshLayout.setOnRefreshListener(() -> { if (mTaskCount > 0) { mSwipeRefreshLayout.setRefreshing(false); } else { onFetchHardInfo(); } }); mRecyclerView.setLayoutManager(new LinearLayoutManager(getBaseContext(), LinearLayoutManager.VERTICAL, false)); mRecyclerView.setHasFixedSize(true); mAdapter = new HardDetailAdapter(); mRecyclerView.setAdapter(mAdapter); } public void loadData() { mAccount = getBaseDao().onSelectAccount(getBaseDao().getLastUser()); mBaseChain = BaseChain.getChain(mAccount.baseChain); mChainConfig = ChainFactory.getChain(mBaseChain); mHardMoneyMarketDenom = getIntent().getStringExtra("hard_money_market_denom"); mIncentiveRewards = getBaseDao().mIncentiveRewards; onFetchHardInfo(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } private int mTaskCount = 0; public void onFetchHardInfo() { mInterestRates.clear(); mModuleCoins.clear(); mReserveCoins.clear(); mTotalDeposit.clear(); mTotalBorrow.clear(); mMyDeposit.clear(); mMyBorrow.clear(); mTaskCount = 7; new KavaHardInterestRateGrpcTask(getBaseApplication(), this, mBaseChain).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); new KavaHardModuleAccountTask(getBaseApplication(), this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); new KavaHardReservesGrpcTask(getBaseApplication(), this, mBaseChain).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); new KavaHardTotalDepositGrpcTask(getBaseApplication(), this, mBaseChain).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); new KavaHardTotalBorrowGrpcTask(getBaseApplication(), this, mBaseChain).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); new KavaHardMyDepositGrpcTask(getBaseApplication(), this, mBaseChain, mAccount).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); new KavaHardMyBorrowGrpcTask(getBaseApplication(), this, mBaseChain, mAccount).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @Override public void onTaskResponse(TaskResult result) { if (isFinishing()) return; mTaskCount--; if (result.taskType == TASK_GRPC_FETCH_KAVA_HARD_INTEREST_RATE) { if (result.isSuccess && result.resultData != null) { mInterestRates = (ArrayList<QueryOuterClass.MoneyMarketInterestRate>) result.resultData; } } else if (result.taskType == TASK_FETCH_KAVA_HARD_MODULE_ACCOUNT) { if (result.isSuccess && result.resultData != null) { ResKavaModuleAccount moduleAccount = (ResKavaModuleAccount) result.resultData; mTaskCount += 1; new BalanceGrpcTask(getBaseApplication(), this, mBaseChain, moduleAccount.getAccounts().get(0).getAddress()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);; } } else if (result.taskType == TASK_GRPC_FETCH_KAVA_HARD_RESERVES) { if (result.isSuccess && result.resultData != null) { mReserveCoins = (ArrayList<CoinOuterClass.Coin>) result.resultData; getBaseDao().mReserveCoins = mReserveCoins; } } else if (result.taskType == TASK_GRPC_FETCH_KAVA_HARD_TOTAL_DEPOSIT) { if (result.isSuccess && result.resultData != null) { mTotalDeposit = (ArrayList<CoinOuterClass.Coin>) result.resultData; } } else if (result.taskType == TASK_GRPC_FETCH_KAVA_HARD_TOTAL_BORROW) { if (result.isSuccess && result.resultData != null) { mTotalBorrow = (ArrayList<CoinOuterClass.Coin>) result.resultData; } } else if (result.taskType == TASK_GRPC_FETCH_KAVA_HARD_MY_DEPOSIT) { if (result.isSuccess && result.resultData != null) { mMyDeposit = (ArrayList<QueryOuterClass.DepositResponse>) result.resultData; getBaseDao().mMyHardDeposits = mMyDeposit; } } else if (result.taskType == TASK_GRPC_FETCH_KAVA_HARD_MY_BORROW) { if (result.isSuccess && result.resultData != null) { mMyBorrow = (ArrayList<QueryOuterClass.BorrowResponse>) result.resultData; getBaseDao().mMyHardBorrows = mMyBorrow; } } else if (result.taskType == TASK_GRPC_FETCH_BALANCE) { if (result.isSuccess && result.resultData != null) { ArrayList<CoinOuterClass.Coin> tempList = (ArrayList<CoinOuterClass.Coin>) result.resultData; for (CoinOuterClass.Coin coin : tempList) { mModuleCoins.add(new Coin(coin.getDenom(), coin.getAmount())); } getBaseDao().mModuleCoins = mModuleCoins; } } if (mTaskCount == 0) { mAdapter.notifyDataSetChanged(); mLoadingLayer.setVisibility(View.GONE); mSwipeRefreshLayout.setRefreshing(false); } } public void onHardDeposit() { if (!onCommonCheck()) return; if ((getBaseDao().getAvailable(mHardMoneyMarketDenom)).compareTo(BigDecimal.ZERO) <= 0) { Toast.makeText(getBaseContext(), R.string.error_no_available_to_deposit, Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(this, DepositHardActivity.class); intent.putExtra("hardPoolDemon", mHardMoneyMarketDenom); startActivity(intent); } public void onHardWithdraw() { if (!onCommonCheck()) return; if (WUtil.getHardSuppliedValueByDenom(this, getBaseDao(), mHardMoneyMarketDenom, mMyDeposit).compareTo(BigDecimal.ZERO) <= 0) { Toast.makeText(getBaseContext(), R.string.error_no_deposited_asset, Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(this, WithdrawHardActivity.class); intent.putExtra("hardPoolDemon", mHardMoneyMarketDenom); startActivity(intent); } public void onHardBorrow() { if (!onCommonCheck()) return; BigDecimal borrowAble = WUtil.getHardBorrowableAmountByDenom(this, getBaseDao(), mHardMoneyMarketDenom, mMyDeposit, mMyBorrow, mModuleCoins, mReserveCoins); if (borrowAble.compareTo(BigDecimal.ZERO) <= 0) { Toast.makeText(getBaseContext(), R.string.error_no_borrowable_asset, Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(this, BorrowHardActivity.class); intent.putExtra("hardPoolDemon", mHardMoneyMarketDenom); startActivity(intent); } public void onHardRepay() { if (!onCommonCheck()) return; if ((getBaseDao().getAvailable(mHardMoneyMarketDenom)).compareTo(BigDecimal.ZERO) <= 0) { Toast.makeText(getBaseContext(), R.string.error_not_enough_to_balance, Toast.LENGTH_SHORT).show(); return; } if (WUtil.getHardBorrowedValueByDenom(this, getBaseDao(), mHardMoneyMarketDenom, mMyBorrow).compareTo(BigDecimal.ZERO) <= 0) { Toast.makeText(getBaseContext(), R.string.error_noting_repay_asset, Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(this, RepayHardActivity.class); intent.putExtra("hardPoolDemon", mHardMoneyMarketDenom); startActivity(intent); } private boolean onCommonCheck() { if (!mAccount.hasPrivateKey) { onInsertKeyDialog(); return false; } return true; } private class HardDetailAdapter extends RecyclerView.Adapter<BaseHolder> { private static final int TYPE_HARD_INFO = 0; private static final int TYPE_MY_STATUS = 1; private static final int TYPE_MY_AVAILABLE = 2; @NonNull @Override public BaseHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { if (viewType == TYPE_HARD_INFO) { return new HardDetailInfoHolder(getLayoutInflater().inflate(R.layout.item_hard_detail_info, viewGroup, false)); } else if (viewType == TYPE_MY_STATUS) { return new HardDetailMyStatusHolder(getLayoutInflater().inflate(R.layout.item_hard_detail_my_status, viewGroup, false)); } else if (viewType == TYPE_MY_AVAILABLE) { return new HardDetailMyAvailableHolder(getLayoutInflater().inflate(R.layout.item_hard_detail_my_available, viewGroup, false)); } return null; } @Override public void onBindViewHolder(@NonNull BaseHolder holder, int position) { if (getItemViewType(position) == TYPE_HARD_INFO) { holder.onBindHardDetailInfo(HardDetailActivity.this, getBaseDao(), mHardMoneyMarketDenom, mIncentiveRewards, mInterestRates, mTotalDeposit, mTotalBorrow, mModuleCoins, mReserveCoins); } else if (getItemViewType(position) == TYPE_MY_STATUS) { holder.onBindHardDetailMyStatus(HardDetailActivity.this, getBaseDao(), mHardMoneyMarketDenom, mMyDeposit, mMyBorrow, mModuleCoins, mReserveCoins); } else if (getItemViewType(position) == TYPE_MY_AVAILABLE) { holder.onBindHardDetailAvailable(HardDetailActivity.this, getBaseDao(), mHardMoneyMarketDenom); } } @Override public int getItemCount() { return 3; } @Override public int getItemViewType(int position) { if (position == 0) { return TYPE_HARD_INFO; } else if (position == 1) { return TYPE_MY_STATUS; } else { return TYPE_MY_AVAILABLE; } } } }
true
0640057312e2385fff7fb71760bff95ff64765ea
Java
andyarroyo5/FeriaIntApp
/app/src/main/java/edu/udem/feriaint/Activities/ActivityInicial.java
UTF-8
3,722
1.953125
2
[]
no_license
package edu.udem.feriaint.Activities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.twitter.sdk.android.Twitter; import edu.udem.feriaint.TwitterInicioSesion; import edu.udem.feriaint.SessionRecorder; import com.twitter.sdk.android.core.Session; import com.twitter.sdk.android.core.TwitterSession; /** * Created by laboratorio on 11/3/16. */ public class ActivityInicial extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks { private GoogleApiClient mGoogleApiClient; boolean conectadoGoogle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); conectadoGoogle=false; final Session activeSession = SessionRecorder.recordInitialSessionState( Twitter.getSessionManager().getActiveSession() ); Log.e("IA",String.valueOf(activeSession)); mGoogleApiClient = buildGoogleAPIClient(); mGoogleApiClient.connect(); // Log.e("IA",String.valueOf(mGoogleApiClient.getConnectionResult(result))); if (activeSession != null || mGoogleApiClient.isConnected()) { startThemeActivity(activeSession); Log.e("IA","active session"); } else { startLoginActivity(); Log.e("IA","log in "); } } private void startThemeActivity(Session activeSession) { //if twitter Intent main= new Intent(this, MainActivity.class); TwitterSession session= Twitter.getSessionManager().getSession(activeSession.getId()); main.putExtra("user",session.getUserName()); main.putExtra("token",session.getAuthToken()); main.putExtra("id",session.getUserId()); main.putExtra("session",session.getClass()); main.putExtra("tipo","twitter"); startActivity(main); finish(); } private void startLoginActivity() { Intent hacerLogIn=new Intent(this, TwitterInicioSesion.class); hacerLogIn.putExtra("cerrarS",false); // hacerLogIn.putExtra("apiClient", (Parcelable) mGoogleApiClient); startActivity(hacerLogIn); } private GoogleApiClient buildGoogleAPIClient() { GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); return mGoogleApiClient; } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { conectadoGoogle=false; Log.e("IA","onconnectionFailed"+conectadoGoogle); } @Override public void onConnected(@Nullable Bundle bundle) { //conectadoGoogle=true; Log.e("IA","onconnected"+conectadoGoogle); } @Override public void onConnectionSuspended(int i) { Log.e("IA","onconnectionsuspended"); } }
true
08fdf8677d9ac64c6bcbebe77bd4433f38b97c5b
Java
lin19950817/java-study
/cxf/REST-SERVER/src/main/java/org/lzn/Main.java
UTF-8
841
2.359375
2
[]
no_license
package org.lzn; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.lzn.service.impl.StudentImpl; /** * CXF 发布 REST 的服务(服务端) * * @author LinZhenNan lin_hehe@qq.com 2020/09/12 17:26 */ public class Main { public static void main(String[] args) { // JAXRSServerFactoryBean 发布 REST 的服务 JAXRSServerFactoryBean jaxrsServerFactoryBean = new JAXRSServerFactoryBean(); // 设置服务实现类 jaxrsServerFactoryBean.setServiceBean(new StudentImpl()); // 设置资源类,如果有多个资源,可以用 , 分隔 jaxrsServerFactoryBean.setResourceClasses(StudentImpl.class); // 设置服务地址 jaxrsServerFactoryBean.setAddress("http://127.0.0.1:12345/user"); // 发布服务 jaxrsServerFactoryBean.create(); } }
true
ad1aa2d5a5ae9256dea6c301390881b0e8e00c30
Java
waterz2013/JavaWorld
/src/com/isandou/www/algorithm/search/FibonacciSearch.java
UTF-8
2,246
3.640625
4
[]
no_license
package com.isandou.www.algorithm.search; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import com.isandou.www.algorithm.sort.QuickSort; public class FibonacciSearch { static Logger logger = Logger.getLogger(FibonacciSearch.class); /** * 斐波那契查找(费式查找) * 说明:二分搜寻法每次搜寻时,都会将搜寻区间分为一半,所以其搜寻时间为O(log(2)n),log(2)表示以2为底的log值, * 这边要介绍的费氏搜寻,其利用费氏数列作为间隔来搜寻下一个数,所以区间收敛的速度更快,搜寻时间为O(logn)。 * @param nums 待查找的数组 * @param num 带查找的值 * @return 带查找数的索引值 */ public static int search(int[] nums, int num) { int[] fib = createFibonacci(nums.length); int x = findX(fib, nums.length + 1); int m = nums.length - fib[x]; x--; int i = x; if (nums[i] < num){ i += m; } while (fib[x] > 0) { if (nums[i] < num){ i += fib[--x]; } else if (nums[i] > num){ i -= fib[--x]; } else{ return i; } } return -1; } /** * 创建斐波那契数列 * @param max 新数列长度 * @return max长度的斐波那契数组 */ private static int[] createFibonacci(int max) { int[] fib = new int[max]; for (int i = 0; i < fib.length; i++) { fib[i] = Integer.MIN_VALUE; } fib[0] = 0; fib[1] = 1; for (int i = 2; i < max; i++){ fib[i] = fib[i - 1] + fib[i - 2]; } return fib; } /** * 查找 * @param fib 查找数组对象 * @param n 长度 * @return */ private static int findX(int[] fib, int n) { int i = 0; while (fib[i] <= n){ i++; } i--; return i; } /** * 斐波那契查找实现 * @param args */ public static void main(String[] args) { //log4j默认配置 BasicConfigurator.configure(); int[] nums = { 1, 4, 2, 6, 7, 3, 9, 8 }; QuickSort.sort(nums,0,nums.length-1); int find = FibonacciSearch.search(nums, 3); if (find != -1){ logger.debug("找到数值于索引" + find); } else{ logger.debug("找不到数值"); } } }
true
ab44162ee1c07fe8ef53b22ffc6f5501ceef17fa
Java
boichukDA/fdddhfghfgh
/app/src/main/java/ru/diaproject/vkplus/core/view/VideoImageView.java
UTF-8
905
2.28125
2
[]
no_license
package ru.diaproject.vkplus.core.view; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.widget.ImageView; public class VideoImageView extends ImageView { public VideoImageView(Context context) { super(context); setBackgroundColor(Color.parseColor("#4d000000")); } public VideoImageView(Context context, AttributeSet attrs) { super(context, attrs); setBackgroundColor(Color.parseColor("#4d000000")); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int parentWidth = MeasureSpec.getSize(widthMeasureSpec); int parentHeight = (parentWidth/16)*9; heightMeasureSpec = (widthMeasureSpec/16)*9; super.onMeasure(widthMeasureSpec, heightMeasureSpec); this.setMeasuredDimension(parentWidth, parentHeight); } }
true
a36c5806990ad39333d318a6a5dee37ac22ceae6
Java
SpdPnd98/tp
/src/test/java/seedu/address/model/person/predicates/AddressContainsKeywordsPredicateTest.java
UTF-8
3,349
3.046875
3
[ "MIT" ]
permissive
package seedu.address.model.person.predicates; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import seedu.address.testutil.PersonBuilder; class AddressContainsKeywordsPredicateTest { @Test public void equals() { List<String> firstPredicateKeywordList = Collections.singletonList("family"); List<String> secondPredicateKeywordList = Arrays.asList("friend", "criminal"); AddressContainsKeywordsPredicate firstPredicate = new AddressContainsKeywordsPredicate( firstPredicateKeywordList); AddressContainsKeywordsPredicate secondPredicate = new AddressContainsKeywordsPredicate( secondPredicateKeywordList); // same object -> returns true assertTrue(firstPredicate.equals(firstPredicate)); // same values -> returns true AddressContainsKeywordsPredicate firstPredicateCopy = new AddressContainsKeywordsPredicate( firstPredicateKeywordList); assertTrue(firstPredicate.equals(firstPredicateCopy)); // different types -> returns false assertFalse(firstPredicate.equals(1)); // null -> returns false assertFalse(firstPredicate.equals(null)); // different person -> returns false assertFalse(firstPredicate.equals(secondPredicate)); } @Test public void test_nameContainsKeywords_returnsTrue() { // One keyword exact AddressContainsKeywordsPredicate predicate = new AddressContainsKeywordsPredicate( Collections.singletonList("home")); assertTrue(predicate.test(new PersonBuilder().withAddress("home").build())); // One keyword not exact predicate = new AddressContainsKeywordsPredicate(Collections.singletonList("Istana")); assertTrue(predicate.test(new PersonBuilder().withAddress("Istana Building 1").build())); // Mixed-case keywords predicate = new AddressContainsKeywordsPredicate(Arrays.asList("nUs")); assertTrue(predicate.test(new PersonBuilder().withAddress("nus").build())); } @Test public void test_nameDoesNotContainKeywords_returnsFalse() { // Zero keywords AddressContainsKeywordsPredicate predicate = new AddressContainsKeywordsPredicate(Collections.emptyList()); assertFalse(predicate.test(new PersonBuilder().withAddress("Bukit Batok Street 11").build())); // Non-matching keyword predicate = new AddressContainsKeywordsPredicate(Arrays.asList("Sentosa")); assertFalse(predicate.test(new PersonBuilder().withName("Bukit Panjang").build())); // Keywords match phone, email and address, but does not match addr predicate = new AddressContainsKeywordsPredicate(Arrays.asList("12345", "alice@email.com", "Main")); assertFalse(predicate.test(new PersonBuilder().withName("Alice").withPhone("12345") .withEmail("alice@email.com").withAddress("High Street").build())); } }
true
fc4f235a24f38e51476e0244ee693a10d6802a3a
Java
ckstn123/baekjoon-online
/baek1261(알고스팟)/Main.java
UTF-8
2,302
2.875
3
[]
no_license
import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { static int N; static int M; static int min = Integer.MAX_VALUE; static int[] dx = {1,0,-1,0}; static int[] dy = {0,1,0,-1}; static int[][] matrix; static int[][] check; static class point{ int x,y,num; point(int x, int y, int n){ this.x = x; this.y = y; this.num = n; } } static void bfs(int x, int y){ Queue<point> queue = new LinkedList<>(); queue.offer(new point(x,y,0)); check[y][x] = 0; while(!queue.isEmpty()){ point temp = queue.poll(); for(int dir = 0; dir<4; dir++){ int dis_x = temp.x + dx[dir]; int dis_y = temp.y + dy[dir]; if(dis_x < 1 || dis_x > M || dis_y < 1 || dis_y > N) continue; if(dis_x == M && dis_y == N){ min = Math.min(min, temp.num); continue; } if(matrix[dis_y][dis_x] == 1){ if(check[dis_y][dis_x] > temp.num + 1){ check[dis_y][dis_x] = temp.num + 1; queue.offer(new point(dis_x,dis_y,temp.num+1)); } } else { if(check[dis_y][dis_x] > temp.num){ check[dis_y][dis_x] = temp.num; queue.offer(new point(dis_x,dis_y,temp.num)); } } } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); M = sc.nextInt(); N = sc.nextInt(); if(N == 1 && M == 1){ System.out.println(0); return; } matrix = new int[N+1][M+1]; check = new int[N+1][M+1]; for(int i = 1; i<=N; i++){ Arrays.fill(check[i], Integer.MAX_VALUE); } for(int i = 1; i<=N; i++){ String str = sc.next(); for(int j = 0; j<M; j++){ matrix[i][j+1] = str.charAt(j) - '0'; } } bfs(1,1); System.out.println(min); } }
true
cf7c19a87f733d694a8594142a050080ae7ae7fc
Java
adventurerok/VoxelCaverns-4
/VC4 API/src/vc4/api/entity/trait/TraitCrafting.java
UTF-8
521
2.4375
2
[]
no_license
package vc4.api.entity.trait; import vc4.api.block.CraftingTable; import vc4.api.entity.Entity; public class TraitCrafting extends Trait { CraftingTable craftingTable = new CraftingTable(); public TraitCrafting(Entity entity) { super(entity); } @Override public void update() { craftingTable.update(entity); } @Override public String name() { return "crafting"; } public CraftingTable getCraftingTable() { return craftingTable; } @Override public boolean persistent() { return false; } }
true
28879af4c4ab5e4fb911bb4cffe1d5ccbacaf99b
Java
robottaway/nettyfun
/src/main/java/com/blueleftistconstructor/applug/UserApplicationHandler.java
UTF-8
3,210
2.40625
2
[]
no_license
package com.blueleftistconstructor.applug; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import com.blueleftistconstructor.web.WebSession; /** * Handle the messages from web socket requests. * * Here is where we would hand off the websocket to an application * * @author rob */ public class UserApplicationHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { private ClientHandler<?> ci; private static final Logger logger = LoggerFactory.getLogger(UserApplicationHandler.class); @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error("Error caught while processing users applicaion.", cause); ctx.close(); } /** * We implement this to catch the websocket handshake completing * successfully. At that point we'll setup this client connection. */ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) { configureClient(ctx); } } /** * Should end up being called after websocket handshake completes. Will * configure this client for communication with the application. */ protected void configureClient(ChannelHandlerContext ctx) { logger.debug("Checking auth"); // TODO: we should support many different authentication standards here // building and auth token and passing it down where the AppPlug can // then build the actual user and bind it with the contexts channel. WebSession sess = ctx.channel().attr(WebSession.webSessionKey).get(); // or basic, or digest.. // possibly OAuth // even facebook or google? // we now have some principal for the user, from whatever authentication format we used. // call webservice to get user data such as authorities, and possibly any channel specific config (ignores, preferences) // when webservice is called it can register that the user is on the given server, later if the user model get's // changed we should fire an event to this AppPlug and update the user model here (privileges comes to mind). // add user data to context. if (sess == null) { logger.info("Closing websocket connection, unable to authenticate"); ctx.writeAndFlush(new CloseWebSocketFrame(400, "UNABLE TO AUTHENTICATE")).addListener(ChannelFutureListener.CLOSE); return; } logger.debug("Got session id: "+sess.getSessionId()); AppPlug<?,?> ap = ctx.channel().attr(AppPlugGatewayHandler.appPlugKey).get(); ci = ap.getClientHandlerForContext(ctx); } /** * When a message is sent into the app by the connected user this is * invoked. */ @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception { ci.handle(frame.text()); } }
true
5109bc5e66823b9912b687b56f677125b7d9e789
Java
zolyfarkas/spf4j
/spf4j-core/src/main/java/org/spf4j/base/avro/AThrowables.java
UTF-8
10,067
1.914063
2
[]
no_license
/* * Copyright (c) 2001-2017, Zoltan Farkas All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Additionally licensed with: * * 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.spf4j.base.avro; import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.Set; import javax.annotation.Nullable; import org.spf4j.base.Throwables; import static org.spf4j.base.Throwables.CAUSE_CAPTION; import static org.spf4j.base.Throwables.SUPPRESSED_CAPTION; import static org.spf4j.base.Throwables.writeAbreviatedClassName; import org.spf4j.ds.IdentityHashSet; /** * * @author Zoltan Farkas */ public final class AThrowables { private AThrowables() { } public static void writeTo(final RemoteException t, final Appendable to, final Throwables.PackageDetail detail, final boolean abbreviatedTraceElement, final String prefix) throws IOException { to.append(prefix); writeMessageString(to, t); to.append('\n'); writeThrowableDetails(t.getRemoteCause(), to, detail, abbreviatedTraceElement, prefix); } public static void writeMessageString(final Appendable to, final RemoteException t) throws IOException { to.append(t.getClass().getName()); to.append(':'); to.append(t.getRemoteClass()); to.append('@'); to.append(t.getSource()); String message = t.getRemoteCause().getMessage(); if (message != null) { to.append(':').append(message); } } public static void writeTo(final Throwable t, final Appendable to, final Throwables.PackageDetail detail, final boolean abbreviatedTraceElement, final String prefix) throws IOException { to.append(prefix); writeMessageString(to, t); to.append('\n'); writeThrowableDetails(t, to, detail, abbreviatedTraceElement, prefix); } public static void writeThrowableDetails(final Throwable t, final Appendable to, final Throwables.PackageDetail detail, final boolean abbreviatedTraceElement, final String prefix) throws IOException { List<StackTraceElement> trace = t.getStackTrace(); writeTo(trace, to, detail, abbreviatedTraceElement, prefix); Throwable ourCause = t.getCause(); List<Throwable> suppressed = t.getSuppressed(); if (ourCause == null && suppressed.isEmpty()) { return; } Set<Throwable> dejaVu = new IdentityHashSet<Throwable>(); dejaVu.add(t); // Print suppressed exceptions, if any for (Throwable se : suppressed) { printEnclosedStackTrace(se, to, trace, SUPPRESSED_CAPTION, prefix + "\t", dejaVu, detail, abbreviatedTraceElement); } // Print cause, if any if (ourCause != null) { printEnclosedStackTrace(ourCause, to, trace, CAUSE_CAPTION, prefix, dejaVu, detail, abbreviatedTraceElement); } } public static void writeTo(final List<StackTraceElement> trace, final Appendable to, final Throwables.PackageDetail detail, final boolean abbreviatedTraceElement, final String prefix) throws IOException { StackTraceElement prevElem = null; for (StackTraceElement traceElement : trace) { to.append(prefix); to.append("\tat "); writeTo(traceElement, prevElem, to, detail, abbreviatedTraceElement); to.append('\n'); prevElem = traceElement; } } public static void writeTo(final StackTraceElement element, @Nullable final StackTraceElement previous, final Appendable to, final Throwables.PackageDetail detail, final boolean abbreviatedTraceElement) throws IOException { Method method = element.getMethod(); String currClassName = method.getDeclaringClass(); String prevClassName = previous == null ? null : previous.getMethod().getDeclaringClass(); if (abbreviatedTraceElement) { if (currClassName.equals(prevClassName)) { to.append('^'); } else { writeAbreviatedClassName(currClassName, to); } } else { to.append(currClassName); } to.append('.'); to.append(method.getName()); FileLocation location = element.getLocation(); FileLocation prevLocation = previous == null ? null : previous.getLocation(); String currFileName = location != null ? location.getFileName() : ""; String prevFileName = prevLocation != null ? prevLocation.getFileName() : ""; String fileName = currFileName; if (abbreviatedTraceElement && java.util.Objects.equals(currFileName, prevFileName)) { fileName = "^"; } final int lineNumber = location != null ? location.getLineNumber() : -1; if (fileName.isEmpty()) { to.append("(Unknown Source)"); } else if (lineNumber >= 0) { to.append('(').append(fileName).append(':') .append(Integer.toString(lineNumber)).append(')'); } else { to.append('(').append(fileName).append(')'); } if (detail == Throwables.PackageDetail.NONE) { return; } if (abbreviatedTraceElement && currClassName.equals(prevClassName)) { to.append("[^]"); return; } PackageInfo presPackageInfo = previous == null ? null : previous.getPackageInfo(); org.spf4j.base.avro.PackageInfo pInfo = element.getPackageInfo(); if (abbreviatedTraceElement && Objects.equals(pInfo, presPackageInfo)) { to.append("[^]"); return; } if (!pInfo.getUrl().isEmpty() || !pInfo.getVersion().isEmpty()) { String jarSourceUrl = pInfo.getUrl(); String version = pInfo.getVersion(); to.append('['); if (!jarSourceUrl.isEmpty()) { if (detail == Throwables.PackageDetail.SHORT) { String url = jarSourceUrl; int lastIndexOf = url.lastIndexOf('/'); if (lastIndexOf >= 0) { int lpos = url.length() - 1; if (lastIndexOf == lpos) { int prevSlPos = url.lastIndexOf('/', lpos - 1); if (prevSlPos < 0) { to.append(url); } else { to.append(url, prevSlPos + 1, url.length()); } } else { to.append(url, lastIndexOf + 1, url.length()); } } else { to.append(url); } } else { to.append(jarSourceUrl); } } else { to.append("na"); } if (!version.isEmpty()) { to.append(':'); to.append(version); } to.append(']'); } } private static void printEnclosedStackTrace(final Throwable t, final Appendable s, final List<StackTraceElement> enclosingTrace, final String caption, final String prefix, final Set<Throwable> dejaVu, final Throwables.PackageDetail detail, final boolean abbreviatedTraceElement) throws IOException { if (dejaVu.contains(t)) { s.append("\t[CIRCULAR REFERENCE:"); writeMessageString(s, t); s.append(']'); } else { dejaVu.add(t); // Compute number of frames in common between this and enclosing trace List<StackTraceElement> trace = t.getStackTrace(); int framesInCommon = commonFrames(trace, enclosingTrace); int m = trace.size() - framesInCommon; // Print our stack trace s.append(prefix).append(caption); writeMessageString(s, t); s.append('\n'); StackTraceElement prev = null; for (int i = 0; i < m; i++) { s.append(prefix).append("\tat "); StackTraceElement ste = trace.get(i); writeTo(ste, prev, s, detail, abbreviatedTraceElement); s.append('\n'); prev = ste; } if (framesInCommon != 0) { s.append(prefix).append("\t... ").append(Integer.toString(framesInCommon)).append(" more"); s.append('\n'); } // Print suppressed exceptions, if any for (Throwable se : t.getSuppressed()) { printEnclosedStackTrace(se, s, trace, SUPPRESSED_CAPTION, prefix + '\t', dejaVu, detail, abbreviatedTraceElement); } // Print cause, if any Throwable ourCause = t.getCause(); if (ourCause != null) { printEnclosedStackTrace(ourCause, s, trace, CAUSE_CAPTION, prefix, dejaVu, detail, abbreviatedTraceElement); } } } public static int commonFrames(final List<StackTraceElement> trace, final List<StackTraceElement> enclosingTrace) { int from = trace.size() - 1; int m = from; int n = enclosingTrace.size() - 1; while (m >= 0 && n >= 0 && trace.get(m).equals(enclosingTrace.get(n))) { m--; n--; } return from - m; } public static void writeMessageString(final Appendable to, final Throwable t) throws IOException { to.append(t.getClass().getName()); String message = t.getMessage(); if (message != null) { to.append(':').append(message); } } }
true
8c06da8fbaea9f035d8add66a04efc39619df25b
Java
tw-hygieia/hygieia-api
/src/main/java/com/capitalone/dashboard/service/FourKeyMetricsService.java
UTF-8
1,637
1.859375
2
[ "Apache-2.0" ]
permissive
package com.capitalone.dashboard.service; import com.capitalone.dashboard.model.PipelineCommit; import com.capitalone.dashboard.model.fourkeymetrics.Commit; import com.capitalone.dashboard.model.fourkeymetrics.DeployedCommit; import com.capitalone.dashboard.model.fourkeymetrics.Deployments; import com.capitalone.dashboard.model.fourkeymetrics.FourKeyMetrics; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.stream.Collectors; @Service public class FourKeyMetricsService { private PipelineService pipelineService; @Autowired public FourKeyMetricsService(PipelineService pipelineService) { this.pipelineService = pipelineService; } public FourKeyMetrics metrics() { Collection<PipelineCommit> pipelineCommits = pipelineService .fetchProdPipelineCommits(new ObjectId("5f15d63e4e169aa2d266045f")); List<DeployedCommit> deployedCommits = pipelineCommits.stream().map(pc -> { String[] parentCommits = new String[pc.getScmParentRevisionNumbers().size()]; pc.getScmParentRevisionNumbers().toArray(parentCommits); return new DeployedCommit(new Commit(pc.getScmRevisionNumber(), new Date(pc.getScmCommitTimestamp()), parentCommits), new Date(pc.getTimestamp())); }).collect(Collectors.toList()); return new FourKeyMetrics(new Deployments(Collections.emptyList()), deployedCommits); } }
true
9c572dc3ce11a5c3e42c2b3ea50e787333e2fc94
Java
githubken0426/ThinkingInJava
/src/th/part_14_TypeInfo/chapter_07_DynamicProxy/InterfaceProxy.java
UTF-8
231
2.640625
3
[]
no_license
package th.part_14_TypeInfo.chapter_07_DynamicProxy; /** * 14.7 简单代理 * @author Administrator * 2015-9-11:上午 */ public interface InterfaceProxy { void doSomething(); void somethingElse(String str); }
true
38fbe84b3da99c7717e91466193fa2b34ff02fee
Java
myliveding/DynamicDataSource
/src/main/java/com/dzr/dds/controller/UserController.java
UTF-8
738
2.09375
2
[]
no_license
package com.dzr.dds.controller; import com.dzr.dds.po.User; import com.dzr.dds.service.UserService; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @author dingzr * @Description * @ClassName TestController * @since 2017/11/29 17:12 */ @RestController public class UserController { @Resource private UserService userService; @RequestMapping("/test1") public String test(){ for(User d: userService.getList()){ System.out.println("test--" + d); } for(User d : userService.getListByDs1()){ System.out.println(d); } return"ok"; } }
true
eb32d41a594a326e3930ec523cab773165dbf7d3
Java
mikgran/base
/reservation/src/main/java/mg/reservation/servlet/ReservationServlet.java
UTF-8
1,684
2.421875
2
[]
no_license
package mg.reservation.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(asyncSupported = false, name = "MyServlet", urlPatterns = { "/reservation" }, initParams = { @WebInitParam(name = "webInitParam1", value = "Hello"), @WebInitParam(name = "webInitParam2", value = "World !!!") }) public class ReservationServlet extends HttpServlet { private static final long serialVersionUID = -5377899412368237345L; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html><head><title>MyServlet</title></head><body>"); out.write(getServletConfig().getInitParameter("webInitParam1") + " "); out.write(getServletConfig().getInitParameter("webInitParam2")); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; } }
true
167085401752779fa63fbeed49bcd7b769d1e8f8
Java
graycat27/AirportTrafficController
/src/main/java/com/github/graycat27/atc/defines/i/IPoint.java
UTF-8
757
2.765625
3
[]
no_license
package com.github.graycat27.atc.defines.i; import org.bukkit.Location; /** * 地点情報 */ public interface IPoint extends IMaster { Location getLocation(); int getX(); int getY(); int getZ(); /** 三次元空間での直線距離を返します */ double distance(final IPoint another); /** 水平面での直線距離を返します */ double levelDistance(final IPoint another); /** このPointを水平面に投射したときに同じであるか否かを返します */ boolean levelEqual(Object another); @Override IPoint clone(); static IPoint getByLocation(Location location){ return new ConcretePoint(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } }
true
963e4c2757ca5149a99aa16c9797de2a68cca37c
Java
sebaudracco/bubble
/com/facebook/ads/internal/view/p080c/C2189a.java
UTF-8
2,791
1.6875
2
[]
no_license
package com.facebook.ads.internal.view.p080c; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.RectF; import android.graphics.Typeface; import android.net.Uri; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.RelativeLayout; import android.widget.TextView; import com.cuebiq.cuebiqsdk.model.config.Settings; import com.facebook.ads.internal.p059a.C1873a; import com.facebook.ads.internal.p059a.C1874b; import com.facebook.ads.internal.p069m.C2012c; import com.facebook.ads.internal.view.p053e.C2249b; import com.facebook.ads.internal.view.p053e.p054b.C2228a; import java.util.HashMap; public class C2189a extends RelativeLayout { private final String f5316a; private C2249b f5317b; private final Paint f5318c = new Paint(); private final RectF f5319d; public C2189a(Context context, String str, String str2, int i, C2249b c2249b, final C2012c c2012c, final String str3) { super(context); this.f5316a = str; this.f5317b = c2249b; View textView = new TextView(context); textView.setTextColor(-1); textView.setTextSize(16.0f); textView.setText(str2); textView.setTypeface(Typeface.defaultFromStyle(1)); setGravity(17); addView(textView); this.f5318c.setStyle(Style.FILL); this.f5318c.setColor(i); this.f5319d = new RectF(); setBackgroundColor(0); setOnClickListener(new OnClickListener(this) { final /* synthetic */ C2189a f5315c; public void onClick(View view) { try { Uri parse = Uri.parse(this.f5315c.f5316a); this.f5315c.f5317b.getEventBus().m6327a(new C2228a(parse)); C1873a a = C1874b.m5632a(this.f5315c.getContext(), c2012c, str3, parse, new HashMap()); if (a != null) { a.mo3622b(); } } catch (Throwable e) { Log.e(String.valueOf(C2189a.class), "Error while opening " + this.f5315c.f5316a, e); } catch (Throwable e2) { Log.e(String.valueOf(C2189a.class), "Error executing action", e2); } } }); } protected void onDraw(Canvas canvas) { float f = getContext().getResources().getDisplayMetrics().density; this.f5319d.set(0.0f, 0.0f, (float) getWidth(), (float) getHeight()); canvas.drawRoundRect(this.f5319d, Settings.LOCATION_REQUEST_SMALLEST_DISPLACEMENT * f, f * Settings.LOCATION_REQUEST_SMALLEST_DISPLACEMENT, this.f5318c); super.onDraw(canvas); } }
true
14c526185ac7923ec185786376b20e3796e925cc
Java
holydrinker/computer-programming-II
/exams/Lab20131121 - CARRELLO/src/dictionary/LinkedDict.java
UTF-8
2,412
3.546875
4
[]
no_license
package dictionary; import java.util.Iterator; public class LinkedDict<V> implements Dictionary<V> { private Record<V> start = null; private Record<V> end = null; private int n = 0; class Record<V>{ Comparable key; V value; Record<V> prev; Record<V> next; public Record(Comparable key, V value) { this.key = key; this.value = value; prev = next = null; } } @Override public void insert(Comparable key, V value) { Record<V> add = new Record<V>(key,value); if(n == 0){ start = add; end = add; } else{ boolean duplicate = false; Record<V> tmp = start; while(!duplicate && tmp != null){ if(key.equals(tmp.key)) duplicate = true; else tmp = tmp.next; } if(duplicate) throw new EntryAlreadyExistsException(ExceptionMessages.DUPLICATE); add.prev = end; end.next = add; end = add; } n++; } @Override public void delete(Comparable key) { if(n == 0) throw new EmptyStructureException(ExceptionMessages.EMPTY); //controllo sugli estremi if(key.equals(start.key)){ if(start == end) start = end = null; else{ start = start.next; start.prev = null; } n--; return; }else if(key.equals(end.key)){ end = end.prev; end.next = null; n--; return; } //controllo su un valore intermedio boolean found = false; Record<V> tmp = start; while(!found && tmp != null){ if(key.equals(tmp.key)) found = true; else tmp = tmp.next; } if(!found) throw new EntryDoesntExistException(ExceptionMessages.NOT_KEY); tmp.prev.next = tmp.next; tmp.next.prev = tmp.prev; n--; } @Override public V search(Comparable key) { if(n == 0) throw new EmptyStructureException(ExceptionMessages.EMPTY); boolean found = false; Record<V> tmp = start; while(!found && tmp != null){ if(tmp.key.equals(key)) found = true; else tmp = tmp.next; } if(!found) throw new EntryDoesntExistException(ExceptionMessages.NOT_KEY); return tmp.value; } @Override public Iterator<Comparable> iterator() { return new Iterator<Comparable>(){ Record<V> current = start; int i = 0; @Override public boolean hasNext() { return i < n; } @Override public Comparable next() { Comparable c = current.key; i++; current = current.next; return c; } }; } }
true
291a0865445f1a42f6f670886b6986519c66e9a4
Java
MrHurniak/reactive-kafka
/src/main/java/com/reactive/example/reactivekafka/model/ChatEvent.java
UTF-8
406
1.789063
2
[]
no_license
package com.reactive.example.reactivekafka.model; import com.reactive.example.reactivekafka.ChatEventType; import java.time.Instant; import java.util.Map; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(chain = true) public class ChatEvent { private long chatId; private ChatEventType eventType; private Instant creationTime; private Map<String, Object> parameters; }
true
f628fabcca050dc1745bec0934c11a0ad11f99ad
Java
wujun728/jun_java_plugin
/jun_springboot_plugin/springboot_a_test/src/main/java/com/mycompany/myproject/base/nio/socket/nio/ServerHandle.java
UTF-8
9,928
3.109375
3
[]
no_license
package com.mycompany.myproject.base.nio.socket.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; /** * NIO服务端 *     打开ServerSocketChannel,监听客户端连接 *     绑定监听端口,设置连接为非阻塞模式 *     创建Reactor线程,创建多路复用器并启动线程 *     将ServerSocketChannel注册到Reactor线程中的Selector上,监听ACCEPT事件 *     Selector轮询准备就绪的key *     Selector监听到新的客户端接入,处理新的接入请求,完成TCP三次握手,建立物理链路 *     设置客户端链路为非阻塞模式 *     将新接入的客户端连接注册到Reactor线程的Selector上,监听读操作,读取客户端发送的网络消息 *     异步读取客户端消息到缓冲区 *     对Buffer编解码,处理半包消息,将解码成功的消息封装成Task *     将应答消息编码为Buffer,调用SocketChannel的write将消息异步发送给客户端 * * @author Wujun * @version 1.0 */ public class ServerHandle implements Runnable { private Selector selector; private ServerSocketChannel serverChannel; private volatile boolean started; /** * 构造方法 * * @param port 指定要监听的端口号 */ public ServerHandle(int port) { try { //创建选择器 selector = Selector.open(); //打开监听通道 serverChannel = ServerSocketChannel.open(); //如果为 true,则此通道将被置于阻塞模式;如果为 false,则此通道将被置于非阻塞模式 serverChannel.configureBlocking(false);//开启非阻塞模式 //绑定端口 backlog设为1024 serverChannel.socket().bind(new InetSocketAddress(port), 1024); //监听客户端连接请求 serverChannel.register(selector, SelectionKey.OP_ACCEPT); //标记服务器已开启 started = true; System.out.println("服务器已启动,端口号:" + port); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void stop() { started = false; } @Override public void run() { //循环遍历selector while (started) { try { //无论是否有读写事件发生,selector每隔1s被唤醒一次 selector.select(1000); //阻塞,只有当至少一个注册的事件发生的时候才会继续. // selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> it = keys.iterator(); SelectionKey key = null; while (it.hasNext()) { key = it.next(); it.remove(); try { handleInput(key); } catch (Exception e) { if (key != null) { key.cancel(); if (key.channel() != null) { key.channel().close(); } } } } } catch (Throwable t) { t.printStackTrace(); } } //selector关闭后会自动释放里面管理的资源 if (selector != null) { try { selector.close(); } catch (Exception e) { e.printStackTrace(); } } } private void handleInput(SelectionKey key) throws IOException { if (key.isValid()) { //处理新接入的请求消息 if (key.isAcceptable()) { accept(key); } //读消息 if (key.isReadable()) { doRead(key); // SocketChannel sc = (SocketChannel) key.channel(); // //创建ByteBuffer,并开辟一个1M的缓冲区 // ByteBuffer buffer = ByteBuffer.allocate(1024); // //读取请求码流,返回读取到的字节数 // int readBytes = sc.read(buffer); // //读取到字节,对字节进行编解码 // if (readBytes > 0) { // //将缓冲区当前的limit设置为position=0,用于后续对缓冲区的读取操作 // buffer.flip(); // //根据缓冲区可读字节数创建字节数组 // byte[] bytes = new byte[buffer.remaining()]; // //将缓冲区可读字节数组复制到新建的数组中 // buffer.get(bytes); // String expression = new String(bytes, "UTF-8"); // System.out.println("服务器收到消息:" + expression); // //处理数据 // String result = null; // try { // result = Calculator.cal(expression).toString(); // } catch (Exception e) { // result = "计算错误:" + e.getMessage(); // } // // //发送应答消息 // doWrite(sc, result); // } // //没有读取到字节 忽略 //// else if(readBytes==0); // //链路已经关闭,释放资源 // else if (readBytes < 0) { // key.cancel(); // sc.close(); // } } } } public void accept(SelectionKey key) throws IOException { ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); //通过ServerSocketChannel的accept创建SocketChannel实例 //完成该操作意味着完成TCP三次握手,TCP物理链路正式建立 SocketChannel sc = ssc.accept(); //设置为非阻塞的 sc.configureBlocking(false); //注册为读 sc.register(selector, SelectionKey.OP_READ); System.out.println("is acceptable"); } // 一个client的write事件不一定唯一对应server的read事件,所以需要缓存不完整的包,以便拼接成完整的包 //包协议:包=包头(4byte)+包体,包头内容为包体的数据长度 private int bodyLen = 0 ; public void doRead(SelectionKey selectionKey) throws IOException{ SocketChannel sc = (SocketChannel) selectionKey.channel(); if(bodyLen == 0){ ByteBuffer byteBuffer = ByteBuffer.allocate(4); sc.read(byteBuffer) ;// 当前read事件 byteBuffer.flip();// write mode to read mode byte[] head_bytes = new byte[4]; while (byteBuffer.remaining() > 0){ byteBuffer.get(head_bytes); bodyLen = byteArrayToInt(head_bytes); } }else{ ByteBuffer byteBuffer = ByteBuffer.allocate(bodyLen); sc.read(byteBuffer) ;// 当前read事件 byteBuffer.flip();// write mode to read mode byte[] body_bytes = new byte[bodyLen]; while (byteBuffer.remaining() > 0){ byteBuffer.get(body_bytes); String messages = new String(body_bytes, "UTF-8"); System.out.println("服务器收到消息:" + messages); } bodyLen = 0; } // SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); // ByteBuffer byteBuffer = ByteBuffer.allocate(bodyLen == 0 ? 4 : bodyLen); // int readBytes = socketChannel.read(byteBuffer);// 当前read事件 // // if(readBytes < 0){ // socketChannel.close(); // selectionKey.cancel(); // } // // if(readBytes == 0 ) ; // // byteBuffer.flip();// write mode to read mode // byte[] bytes = new byte[byteBuffer.remaining()]; // byteBuffer.get(bytes); // // if (bodyLen == 0) { // bodyLen = byteArrayToInt(bytes); // // } else { // String messages = new String(bytes, "UTF-8"); // System.out.println("服务器收到消息:" + messages); // bodyLen = 0; // } selectionKey.interestOps(SelectionKey.OP_READ); } //异步发送应答消息 private void doWrite(SocketChannel channel, String response) throws IOException { // 因为应答消息的发送,SocketChannel也是异步非阻塞的,所以不能保证一次能把需要发送的数据发送完, // 此时就会出现写半包的问题。我们需要注册写操作,不断轮询Selector将没有发送完的消息发送完毕, // 然后通过Buffer的hasRemain()方法判断消息是否发送完成。 //将消息编码为字节数组 byte[] bytes = response.getBytes(); //根据数组容量创建ByteBuffer ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length); //将字节数组复制到缓冲区 writeBuffer.put(bytes); //flip操作 writeBuffer.flip(); //发送缓冲区的字节数组 channel.write(writeBuffer); //****此处不含处理“写半包”的代码 } public static int byteArrayToInt(byte[] bytes) { int value = 0; // 由高位到低位 for (int i = 0; i < 4; i++) { int shift = (4 - 1 - i) * 8; value += (bytes[i] & 0x000000FF) << shift;// 往高位游 } return value; } }
true
f2b4960906585459abb14207ffd373117f364997
Java
stonezdj/systemtray
/src/com/zdj/free/config/LinuxHostConfig.java
UTF-8
473
2.234375
2
[]
no_license
package com.zdj.free.config; import java.io.File; import com.zdj.free.HostConfig; import com.zdj.free.Main; public class LinuxHostConfig extends HostConfig { public LinuxHostConfig() { super(Main.currentPath+File.separator+"config/linux.machine.properties"); } private static class InstanceHolder{ public static final LinuxHostConfig INSTANCE = new LinuxHostConfig(); } public static LinuxHostConfig getInstance() { return InstanceHolder.INSTANCE; } }
true
70106dbe9d59b64c7a12233391f5c97bebbb9a9e
Java
Lizonghan6/Experiment-3-jiekou
/Person.java
UTF-8
91
1.726563
2
[]
no_license
package interfaces; public class Person { String Age; String Name; String Sex; }
true
f480389ce4816735bb751ea8d9e403038770a613
Java
jiehaoru/utils
/src/main/java/com/jhr/common/exception/FileIOException.java
UTF-8
802
2.6875
3
[]
no_license
package com.jhr.common.exception; /** * <br> * 标题: * 描述: * * @author jhr * @create 2019/11/28 9:36 */ public class FileIOException extends Exception { public FileIOException() { } //用详细信息指定一个异常 public FileIOException(String message) { super(message); } //用指定的详细信息和原因构造一个新的异常 public FileIOException(String message, Throwable cause) { super(message, cause); } //用指定原因构造一个新的异常 public FileIOException(Throwable cause) { super(cause); } public FileIOException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
true
62cee60456fc11bc89f242d7068df0f584c77b4b
Java
calvinspider/SimpleChat
/SimpleChatClient/src/main/java/org/yang/zhang/view/RecentContractView.java
UTF-8
2,821
2.390625
2
[]
no_license
package org.yang.zhang.view; import java.util.Date; import org.yang.zhang.constants.Constant; import org.yang.zhang.dto.RecentContract; import org.yang.zhang.utils.DateUtils; import org.yang.zhang.utils.ImageUtiles; import javafx.fxml.FXMLLoader; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; /** * @Author calvin.zhang * @Description * @Date 2018 07 12 14:16 */ public class RecentContractView { private String id; private Pane recentContractPane; private Date messageTime; private String lastMessage; private String userIcon; private String nickName; public RecentContractView(RecentContract recentContract) { try { Pane pane=FXMLLoader.load(getClass().getResource("/fxml/RecentContract.fxml")); Label namelabel = (Label)pane.lookup("#namelabel"); namelabel.setText(recentContract.getNickName()); pane.setId(recentContract.getContractId()); Label messagelabel = (Label)pane.lookup("#messagelabel"); messagelabel.setText(recentContract.getLastMessage()); Label timelabel = (Label)pane.lookup("#timelabel"); timelabel.setText(DateUtils.formatDate(recentContract.getLastMessageDate(),"YYYY-MM-dd")); ImageView contracticon=(ImageView)pane.lookup("#contracticon"); contracticon.setImage(ImageUtiles.getUserIcon(recentContract.getIcon())); contracticon.setFitWidth(45); contracticon.setFitHeight(45); this.messageTime = recentContract.getLastMessageDate(); this.lastMessage = recentContract.getLastMessage(); this.userIcon = recentContract.getIcon(); this.recentContractPane=pane; this.id=recentContract.getContractId(); this.nickName=recentContract.getNickName(); }catch (Exception e){ e.printStackTrace(); } } public String getId() { return id; } public String getNickName() { return nickName; } public Pane getRecentContractPane() { return recentContractPane; } public void setRecentContractPane(Pane recentContractPane) { this.recentContractPane = recentContractPane; } public Date getMessageTime() { return messageTime; } public void setMessageTime(Date messageTime) { this.messageTime = messageTime; } public String getLastMessage() { return lastMessage; } public void setLastMessage(String lastMessage) { this.lastMessage = lastMessage; } public String getUserIcon() { return userIcon; } public void setUserIcon(String userIcon) { this.userIcon = userIcon; } }
true
365f7e2a5552fe11571558f6192793c607fe7bc7
Java
ovidiuchile/java_lab1
/prob1/src/problema1/SefGrupa.java
UTF-8
295
2.296875
2
[]
no_license
package problema1; import java.util.ArrayList; public class SefGrupa extends Angajat{ ArrayList<SefEchipa> Subordonati; SefGrupa(int varsta, String nume, String pozitie, ArrayList<SefEchipa> Angajati){ super(varsta, nume, pozitie); Subordonati = new ArrayList<SefEchipa>(Angajati); } }
true
5fe05acfc912e320df7a474df2bd31692d8f7dcd
Java
bellmit/crmtest
/src/java/com/trilogy/app/crm/support/BundleServiceSupport.java
UTF-8
8,318
1.921875
2
[]
no_license
/* * This code is a protected work and subject to domestic and international copyright * law(s). A complete listing of authors of this work is readily available. Additionally, * source code is, by its very nature, confidential information and inextricably contains * trade secrets and other information proprietary, valuable and sensitive to Redknee, no * unauthorised use, disclosure, manipulation or otherwise is permitted, and may only be * used in accordance with the terms of the licence agreement entered into with Redknee * Inc. and/or its subsidiaries. * * Copyright &copy; Redknee Inc. and its subsidiaries. All Rights Reserved. */ package com.trilogy.app.crm.support; import java.util.Collection; import java.util.Date; import com.trilogy.framework.xhome.context.Context; import com.trilogy.framework.xhome.elang.Limit; import com.trilogy.framework.xhome.home.HomeException; import com.trilogy.app.crm.bean.ChargedItemTypeEnum; import com.trilogy.app.crm.bean.Subscriber; import com.trilogy.app.crm.bean.core.BundleFee; import com.trilogy.app.crm.bean.core.BundleProfile; import com.trilogy.app.crm.bundle.exception.BundleDoesNotExistsException; import com.trilogy.app.crm.bundle.exception.BundleManagerException; import com.trilogy.app.crm.bundle.service.CRMBundleProfile; /** * Various support methods for bundle services <p/> Taken heavily from ServiceSupport and * modified for use with bundles. I am sure I can do something clever like adapting the * objects so only one Support class is needed but I don't have the time right now :(. * * @author danny.ng@redknee.com */ public final class BundleServiceSupport { /** * Creates a new <code>BundleServiceSupport</code> instance. This method is made * private to prevent instantiation of utility class. */ private BundleServiceSupport() { // empty } /** * Whether a bundle is suspension prorated. * * @param ctx * The operating context. * @param api * Bundle. * @return Returns whether the suspension is prorated. */ public static boolean isSuspensionProrated(Context ctx, BundleProfile api) { return !api.getSmartSuspensionEnabled(); } /** * Whether a bundle's unsuspension is prorated. * * @param ctx * The operating context. * @param sub * Subscriber to be unsuspended. * @param api * Bundle to be unsuspended. * @param adjustType * Adjustment type. * @param chargingDay * Day of charging. * @return Returns whether the unsuspension is prorated. * @throws HomeException * Thrown if there are problems determining whether the unsuspension is * prorated. */ public static boolean isUnsuspendProrate(Context ctx, Subscriber sub, BundleFee item, BundleProfile api, ChargedItemTypeEnum itemType, int adjustType, long amount, Date chargingDay) throws HomeException { if (!api.getSmartSuspensionEnabled()) { return true; } return !RecurringRechargeSupport.isSubscriberChargedAndNotRefunded(ctx, sub, item, itemType, item.getServicePeriod(), adjustType, amount, chargingDay); } /** * Determines whether a particular service of the subscriber has been unsuspended. * * @param ctx * The operating context. * @param sub * Subscriber. * @param adjustType * Adjustment type of the service. * @return Whether the service with the provided adjustment type has been unsuspended * from the subscriber. */ public static boolean isUnsuspend(final Context ctx, final Subscriber sub, final int adjustType) { final Collection trans = CoreTransactionSupportHelper.get(ctx).getTransactionsForSubAdjustment(ctx, sub.getId(), adjustType, new Limit(1)); return trans != null && trans.size() > 0; } /** * Returns the bundle with the provided identifier. * * @param context * The operating context. * @param spId * service provider identifier. * @param id * Bundle identifier. * @return The identified bundle. * @throws HomeException * Thrown if there are problems looking up the bundle. * @throws BundleManagerException * @throws BundleDoesNotExistsException */ public static BundleProfile getBundle(Context context, int spId, long bundleId) throws HomeException, BundleDoesNotExistsException, BundleManagerException { return getBundle(context, getService(context), spId, bundleId); } /** * Returns the bundle with the provided identifier. * * @param context * The operating context. * @param service * The BM service. * @param spId * service provider identifier. * @param bundleId * Bundle identifier. * @return The identified bundle. * @throws HomeException * Thrown if there are problems looking up the bundle. * @throws BundleManagerException * @throws BundleDoesNotExistsException */ public static BundleProfile getBundle(Context context, CRMBundleProfile service, int spId, long bundleId) throws HomeException, BundleDoesNotExistsException, BundleManagerException { if (service == null) { throw new HomeException("System error: bundle home cannot be null"); } return service.getBundleProfile(context, spId, bundleId); } /** * Returns a collection of bundles belonging to a service provider. * * @param context * The operating context. * @param spid * Service provider identifier. * @return A collection of bundles belonging to the provided service provider. * @throws HomeException * Thrown if there are problems looking up the bundles. * @throws BundleManagerException * @throws UnsupportedOperationException */ public static Collection getBundlesBySpid(final Context context, final int spid) throws HomeException, UnsupportedOperationException, BundleManagerException { return getBundlesBySpid(context, getService(context), spid); } /** * Returns a collection of bundles belonging to a service provider. * * @param context * The operating context. * @param service * Bundle service. * @param spid * Service provider identifier. * @return A collection of bundles belonging to the provided service provider. * @throws HomeException * Thrown if there are problems looking up the bundles. * @throws BundleManagerException * @throws UnsupportedOperationException */ public static Collection getBundlesBySpid(final Context context, final CRMBundleProfile service, final Integer spid) throws HomeException, UnsupportedOperationException, BundleManagerException { if (service == null) { throw new HomeException("System error: bundle home cannot be null"); } return service.getBundlesBySPID(context, spid.intValue()).selectAll(); } /** * Returns the bundle service. * * @param context * The operating context. * @return Bundle home. * @throws HomeException * Thrown if bundle home does not exist. */ public static CRMBundleProfile getService(final Context context) throws HomeException { CRMBundleProfile service = (CRMBundleProfile) context.get(CRMBundleProfile.class); if (service == null) { throw new HomeException("System error: Bundle service does not exist"); } return service; } }
true
ac6252f01b542ea1ade17e4fb1dedba2a8990aa5
Java
EasyBeans/tests
/old/src/main/java/org/ow2/easybeans/tests/environment/reference/persistenceunit/TestPersistenceUnitRefFieldInjection.java
UTF-8
2,729
2.203125
2
[]
no_license
/** * EasyBeans * Copyright (C) 2006 Bull S.A.S. * Contact: easybeans@ow2.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * -------------------------------------------------------------------------- * $Id: TestPersistenceUnitRefFieldInjection.java 5369 2010-02-24 14:58:19Z benoitf $ * -------------------------------------------------------------------------- */ package org.ow2.easybeans.tests.environment.reference.persistenceunit; import static org.ow2.easybeans.tests.common.helper.EJBHelper.getBeanRemoteInstance; import org.ow2.easybeans.tests.common.ejbs.base.ItfCheck00; import org.ow2.easybeans.tests.common.ejbs.stateless.containermanaged.persistenceunitref.SLSBPUnitRefFieldInjection00; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Verifies if the persistence unit references declaration is following the * JSR 220. * @reference JSR 220 - EJB 3.0 Core - 16.10 * @requirement Application Server must be running; the bean * org.ow2.easybeans.tests.common.ejbs.stateless.containermanaged.persistenceunitreference.* * must be deployed. * @setup gets the reference of the bean * @author Eduardo Studzinski Estima de Castro * @author Gisele Pinheiro Souza */ public class TestPersistenceUnitRefFieldInjection { /** * Bean used in tests. */ private ItfCheck00 bean; /** * Gets bean instances used in the tests. * @throws Exception if there is a problem with the bean initialization. */ @BeforeMethod public void startUp() throws Exception { bean = getBeanRemoteInstance(SLSBPUnitRefFieldInjection00.class, ItfCheck00.class); } /** * Checks if the cotainer can: <li>inject only defined name, the unit name * is not used because there is only a persistent unit declared;</li> <li>inject * with defined name and unit name;</li> <li>inject without defined name, * the default name must be defined by the container.</li> * @input - * @output - */ @Test public void test00() { bean.check(); } }
true
a133ef97362673da30a45b4e3d7f7415e0d56b7a
Java
beginnersun/BluetoothDemo
/app/src/main/java/com/example/bluetoothdemo/utils/NoTitleMessageDialog.java
UTF-8
4,288
2.328125
2
[]
no_license
package com.example.bluetoothdemo.utils; import android.app.Dialog; import android.content.Context; import android.content.res.Resources; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.TextView; import com.example.bluetoothdemo.R; import androidx.annotation.NonNull; /** * 展示通用的那种 信息 确认 取消 弹框 * Created by Home on 2019/3/29. */ public class NoTitleMessageDialog extends Dialog { private Context mContext; private String message; private boolean showClose; private OnOkClickListener onOkClickListener; private String btn1Title; private String btn2Title; public NoTitleMessageDialog(@NonNull Context context, String message) { this(context,message,false); // getWindow().setGravity(Gravity.CENTER); //显示在底部 } public NoTitleMessageDialog(@NonNull Context context,String message,boolean showClose){ // super(context,R.style.Dialog_Show_Message); // this.mContext = context; // this.showClose = showClose; // this.message = message; // init(); // final WindowManager.LayoutParams params = getWindow().getAttributes(); // params.width = (int) (Resources.getSystem().getDisplayMetrics().density * 270); // params.height = (int) (Resources.getSystem().getDisplayMetrics().density * 170); // getWindow().setAttributes(params); this(context,message,showClose,"确认","取消"); // WindowManager.LayoutParams lp = this.getWindow().getAttributes(); // lp.alpha = 0.3f; // this.getWindow() // .addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); // this.getWindow().setAttributes(lp); } public NoTitleMessageDialog(@NonNull Context context,String message,boolean showClose,String okMessage,String cancelMessage){ super(context, R.style.Dialog_Show_Message); this.mContext = context; this.showClose = showClose; this.message = message; this.btn1Title = cancelMessage; this.btn2Title = okMessage; init(); final WindowManager.LayoutParams params = getWindow().getAttributes(); params.width = (int) (Resources.getSystem().getDisplayMetrics().density * 270); params.height = (int) (Resources.getSystem().getDisplayMetrics().density * 170); getWindow().setAttributes(params); } private void init(){ // // View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_show_message,null,false); // setCanceledOnTouchOutside(true); // setContentView(view); // // TextView content = (TextView) view.findViewById(R.id.tv_content); // // content.setText(message); // // // TextView save = (TextView) view.findViewById(R.id.tv_ok); // save.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // dismiss(); // } // }); // // TextView cancel = (TextView) view.findViewById(R.id.tv_cancel); // if (showClose){ // save.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // if (onOkClickListener!=null){ // onOkClickListener.onOkClick(); // } // dismiss(); // } // }); // }else{ // view.findViewById(R.id.tv_line).setVisibility(View.GONE); // cancel.setVisibility(View.GONE); // } // // if (!TextUtils.isEmpty(this.btn1Title) && !TextUtils.isEmpty(this.btn2Title)){ // save.setText(this.btn2Title); // cancel.setText(this.btn1Title); // } // // cancel.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // dismiss(); // } // }); } public void setOnOkClickListener(OnOkClickListener onOkClickListener) { this.onOkClickListener = onOkClickListener; } public interface OnOkClickListener{ void onOkClick(); } }
true
290389f12a21ac91b2a1b27e52815466685fc8e8
Java
xiaoma61/xiaomablogweb
/src/main/java/com/xiaoma/entity/ARTICLECOMMENTUSERANDCOMMENTLIST.java
UTF-8
475
1.804688
2
[]
no_license
package com.xiaoma.entity; public class ARTICLECOMMENTUSERANDCOMMENTLIST { public ARTICLECOMMENT articlecomment; public USERMSG usermsg; public ARTICLECOMMENT getArticlecomment() { return articlecomment; } public void setArticlecomment(ARTICLECOMMENT articlecomment) { this.articlecomment = articlecomment; } public USERMSG getUsermsg() { return usermsg; } public void setUsermsg(USERMSG usermsg) { this.usermsg = usermsg; } }
true
1479588c3fdd4e1067cfc960011a999412a6508b
Java
sokolinthesky/course_practice
/src/ua/khpi/soklakov/Practice6/part4/Graph.java
UTF-8
1,098
3.484375
3
[]
no_license
package ua.khpi.soklakov.Practice6.part4; public interface Graph { /** * @param numberNodes * Number of nodes. * @return Count the specified configuration. */ AbstractGraph createGraph(int numberNodes); /** * Abstract graph. When you create a given number of vertices. */ abstract class AbstractGraph { /** The number of nodes */ protected final int numberNodes; public AbstractGraph(int numberNodes) { this.numberNodes = numberNodes; } /** * Adding edge to graph. * * @param first * The first binding top. * @param second * The second binding top. */ public abstract void addEdge(int first, int second); /** * Remove edge from graph. * * @param first * First top. * @param second * Second top. */ public abstract void removeEdge(int first, int second); /** * Checking the ribs. * * @param first * First top. * @param second * Second top. */ public abstract boolean isExistEdge(int first, int second); } }
true
6e31af46ec739155dd11cb720c093e05d7ca9b30
Java
tianzhiao/baidu-shop
/baidu-shop/baidu-shop-service/shop-service-template/src/main/java/com/baidu/shop/web/PageController.java
UTF-8
1,890
1.84375
2
[]
no_license
package com.baidu.shop.web; import com.baidu.shop.dto.SkuDTO; import com.baidu.shop.dto.SpecGroupDTO; import com.baidu.shop.dto.SpuDTO; import com.baidu.shop.entity.BrandEntity; import com.baidu.shop.entity.SpecGroupEntity; import com.baidu.shop.entity.SpecParamsEntity; import com.baidu.shop.entity.SpuDetailEntity; import com.baidu.shop.service.GoodsServiceI; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @ClassName PageController * @Description: TODO * @Author tianzhiao * @Date 2020/9/23 * @Version V1.09999999999999999 **/ @Controller @RequestMapping("item/") public class PageController { @Resource private GoodsServiceI goodsService; @GetMapping("/{spuId}.html") public String test(@PathVariable("spuId") Integer spuId, ModelMap modelMap){ Map<String ,Object> map = goodsService.getGoodsBySpuId(spuId); modelMap.addAttribute("spuInfo",(SpuDTO) map.get("spuInfo")); modelMap.addAttribute("brandInfo2",(BrandEntity) map.get("brandInfo2")); modelMap.addAttribute("groupList",(List<SpecGroupEntity>) map.get("groupList")); modelMap.addAttribute("paramsMap",(HashMap<Integer, String>) map.get("paramsMap")); modelMap.addAttribute("spuDetail",(SpuDetailEntity) map.get("spuDetail")); modelMap.addAttribute("skus",(List<SkuDTO>) map.get("skus")); modelMap.addAttribute("paramsMy",(HashMap<Integer, String>) map.get("paramsMy")); modelMap.addAttribute("paramsAndGroup",(List<SpecGroupDTO>) map.get("paramsAndGroup")); return "item"; } }
true
997ae3483e56936a5e67bb61a8a1aca6b56f3d12
Java
A-lHasan-AlKhatib/unit_one
/src/oop/day_one/shapes_oop/Try.java
UTF-8
942
3.96875
4
[]
no_license
package oop.day_one.shapes_oop; import java.util.Scanner; public class Try { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Select the shape\n1-Circle\n2-Square\n3-Triangle\n4-Rectangle\nShape: "); int shapeType = scanner.nextInt(); System.out.print("\nSelect what to calculate:\n1-Area\n2-Circumference\nType: "); int whatToCalc = scanner.nextInt(); System.out.println(); switch (shapeType) { case 1: new Circle(whatToCalc); break; case 2: new Square(whatToCalc); break; case 3: new Triangle(whatToCalc); break; case 4: new Rectangle(whatToCalc); break; default: System.out.println("wrong input!"); } } }
true
c78097c3d6d815447c56d818760415117c1aeff2
Java
sobujbd/BookProject
/app/src/main/java/mk/finki/mpip/bookproject/Database/DbOpenHelper.java
UTF-8
1,476
2.46875
2
[]
no_license
package mk.finki.mpip.bookproject.Database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DbOpenHelper extends SQLiteOpenHelper { public static final String TABLE_NAME = "Books"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_DESCRIPTION = "description"; public static final String COLUMN_IMAGE = "image"; public static final String COLUMN_AUTHORNAME = "authorName"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "BookAppDatabase.db"; //posle primary key autoincrement ako sakame ID da dodava private static final String DATABASE_CREATE = String .format("create table %s (%s integer primary key, " + "%s text not null, %s text, %s text, %s text);", TABLE_NAME, COLUMN_ID, COLUMN_TITLE, COLUMN_DESCRIPTION, COLUMN_IMAGE, COLUMN_AUTHORNAME); public DbOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase database) { database.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Don't do this in real end-user applications db.execSQL(String.format("DROP TABLE IF EXISTS %s", TABLE_NAME)); onCreate(db); } }
true
b52c9b8e0d5f1bc3ad7c60a63e12726540a0629c
Java
kaviraj333/codekata-1
/beg13.java
UTF-8
369
2.984375
3
[]
no_license
import java.util.Scanner; class beg13 { public static void main(String args[]) { int temp; boolean isPrime=true; Scanner scan=new Scanner(System.in); int num=scan.nextInt(); for(int i=2;i<=num;i++) { temp=num%i; if(temp==0) { isPrime=false; break; } } if(isPrime) System.out.println("yes"); else System.out.println("no"); } }
true
5dba553ab620283ce20baf28f0f9660eabbd0b3c
Java
yhydev/user-sys
/src/main/java/com/gushushu/yanao/usersys/security/filter/ImageCodeAuthFilter.java
UTF-8
1,771
2.109375
2
[]
no_license
package com.gushushu.yanao.usersys.security.filter; import com.google.code.kaptcha.impl.DefaultKaptcha; import com.gushushu.yanao.usersys.controller.ImageCodeController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException; @Component public class ImageCodeAuthFilter implements Filter { @Autowired private DefaultKaptcha defaultKaptcha; @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { /*SecurityContext securityContext = SecurityContextHolder.getContext(); System.out.println(securityContext);*/ String imageCode = servletRequest.getParameter("imageCode"); if (!StringUtils.isEmpty(imageCode)){ HttpServletRequest request = (HttpServletRequest) servletRequest; HttpSession session = request.getSession(); Object realImageCode = session.getAttribute(ImageCodeController.IMAGE_CODE); if(imageCode.equals(realImageCode)){ session.setAttribute(ImageCodeController.IMAGE_CODE,Math.random()); }else{ request.getRequestDispatcher("/warning?message=图片验证码错误").forward(request,servletResponse); return; } } filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
true
bf40b054e6115d6f5585400e2bc230d69360c9d4
Java
wuiler/quarkus
/devtools/gradle/src/test/java/io/quarkus/gradle/KotlinBuildFileTest.java
UTF-8
1,220
1.929688
2
[ "Apache-2.0" ]
permissive
package io.quarkus.gradle; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import org.apache.maven.model.Dependency; import org.junit.jupiter.api.BeforeAll; import org.mockito.Mockito; import io.quarkus.platform.descriptor.QuarkusPlatformDescriptor; class KotlinBuildFileTest extends AbstractBuildFileTest { private static KotlinBuildFileFromConnector buildFile; @BeforeAll public static void beforeAll() throws URISyntaxException { URL url = KotlinBuildFileTest.class.getClassLoader().getResource("gradle-kts-project"); URI uri = url.toURI(); Path gradleProjectPath = Paths.get(uri); final QuarkusPlatformDescriptor descriptor = Mockito.mock(QuarkusPlatformDescriptor.class); buildFile = new KotlinBuildFileFromConnector(gradleProjectPath, descriptor); } @Override String getProperty(String propertyName) throws IOException { return buildFile.getProperty(propertyName); } @Override List<Dependency> getDependencies() throws IOException { return buildFile.getDependencies(); } }
true
2b901c7d35f58bfa27051330d8313a29da0a20d9
Java
yaop104/plugins
/src/com/sme/util/Config.java
UTF-8
3,080
2.203125
2
[]
no_license
package com.sme.util; import java.io.FileInputStream; import java.util.Properties; /** * 配置文件 * @author yao * */ public class Config { private static Properties confProperties = new Properties(); static { try { String PATH = Thread.currentThread() .getContextClassLoader().getResource("config.properties").getFile(); confProperties.load(new FileInputStream(PATH)); } catch (Exception ex) { ex.printStackTrace(); } } public static String getConfigProperty(String key) { return confProperties.getProperty(key); } public static boolean isBoolean(String key) { return "true".equals(getConfigProperty(key)); } public static Integer getInteger(String key) { return Integer.parseInt(getConfigProperty(key)); } public static final Integer TREE_ROOT_ID = 1; public static final boolean LOG_SWITCH = isBoolean("log_switch"); public static final String EMAIL_HOST = getConfigProperty("EMAIL_HOST"); public static final String EMAIL_PORT = getConfigProperty("EMAIL_PORT"); public static final String EMAIL_USERNAME = getConfigProperty("EMAIL_USERNAME"); public static final String EAMIL_PASSWORD = getConfigProperty("EAMIL_PASSWORD"); public static final String EMAIL_FROM = getConfigProperty("EMAIL_FROM"); public static final String HOST = getConfigProperty("HOST"); public static final String PORT = getConfigProperty("PORT"); public static final String FILE_PATH = getConfigProperty("FILE_PATH"); public static final String URL_PREFIX = getConfigProperty("URL_PREFIX"); public static final String DIFF_SWITCH = getConfigProperty("DIFF_SWITCH"); public static final Integer openCountPeriod = getInteger("openCountPeriod"); public static final String DEFAULT_PASSWD = getConfigProperty("DEFAULT_PASSWD"); public static final String DEFAULT_APK_PATH = getConfigProperty("defult.apk.path"); public static final String DEFAULT_APK_ONLINEPATH = getConfigProperty("defult.apk.onlinepath"); public static final String DEFAULT_APK_IMGPATH = getConfigProperty("defult.apk.picpath"); public static final String HEAD_IMG_PATH = getConfigProperty("head.img.path"); public static final String HEAD_IMG_REALPATH = getConfigProperty("head.img.realPath"); //email public static final String MailServerHost = getConfigProperty("defult.MailServerHost"); public static final String MailServerPort = getConfigProperty("defult.MailServerPort"); public static final String UserName = getConfigProperty("defult.UserName"); public static final String Password = getConfigProperty("defult.Password"); public static final String FromAddress = getConfigProperty("defult.FromAddress"); public static final String Subject = getConfigProperty("defult.Subject"); public static final String Content1 = getConfigProperty("defult.Content1"); public static final String Content2 = getConfigProperty("defult.Content2"); public static final String CodeContent1 = getConfigProperty("defult.codeContent1"); public static final String CodeContent2 = getConfigProperty("defult.codeContent2"); }
true
0da6c76c4d22d6ac9e8664a1c843e59d760e9a42
Java
xmuzhangshuai/ExamHelperServer
/ExamHelper/src/com/yrw/idao/IQuestionsOfMaterial.java
GB18030
2,014
2.125
2
[]
no_license
package com.yrw.idao; import java.util.List; import com.yrw.domains.Questionsofmaterial; import net.sf.cglib.transform.impl.AddDelegateTransformer; /** * * ĿƣExamHelper ƣIQuestionsOfMaterial ԶѡйزĽӿ̳࣬IBasicDao ˣҶ * ʱ䣺2014-03-15 ޸ˣ ޸ʱ䣺 ޸ıע * * @version * */ public interface IQuestionsOfMaterial extends IBasicDao { /**ͨСɵõб * @param pageNow * @param stem * @return */ public List getQuestionofMaterialByStem(int pageNow,String stem); /**ͨСɵõбҳ * @param stem * @return */ public int getPageCountByStem(String stem); /** * @param pageNow * @param materialId * @return */ public List getQuestionOfMaterialByMaterialId(int pageNow,int materialId); /**õijmaterialAnalysisµС * @param materialId * @return */ public List getQuestionOfMaterialByMaterialId(int materialId); /** * @param materialId * @return */ public int getPageCountByMaterialId(int materialId); /**ͨIdŻøòµС * @param materiaAnalysisId * @return */ public int getMaxQuestionNumByMaterialId(int materiaAnalysisId); /**ʾС * @param questionOfMaterial * @return Questionofmaterial */ public Questionsofmaterial showQuestionOfMaterial(int questionOfMaterial); /**С * @param questionOfMaterial */ public void addQuestionOfMaterial(Questionsofmaterial questionOfMaterial ); /**ɾС * @param questionOfMaterial */ public void delQuestionOfMaterial(Object object ); /**޸ķС * @param questionOfMaterial */ public void updateQuestionOfMaterial(Questionsofmaterial questionOfMaterial ); }
true
9d6f365c54b7ce3640a916a7792de7067b4a0cff
Java
Thomas-Adams/elsie-dee
/src/main/java/nl/ekholabs/nlp/controller/AudioExtractorController.java
UTF-8
1,145
2.078125
2
[ "MIT" ]
permissive
package nl.ekholabs.nlp.controller; import java.io.IOException; import nl.ekholabs.nlp.client.ElsieDeeAudioRipFeignClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; @RestController public class AudioExtractorController { private final ElsieDeeAudioRipFeignClient elsieDeeAudioRipFeignClient; @Autowired public AudioExtractorController(final ElsieDeeAudioRipFeignClient elsieDeeAudioRipFeignClient) { this.elsieDeeAudioRipFeignClient = elsieDeeAudioRipFeignClient; } @PostMapping(path = "/extractAudio", consumes = MULTIPART_FORM_DATA_VALUE) public ResponseEntity<byte[]> extractAudio(final @RequestParam(value = "video") MultipartFile videoFile) throws IOException { return elsieDeeAudioRipFeignClient.extractAudio(videoFile); } }
true
64d0c24110be68fe29e0a6594638e0f67f7bcbcf
Java
batval/TextParsing
/src/test/java/com/batval/textparsing/services/sorter/WordSortTest.java
UTF-8
1,581
2.703125
3
[]
no_license
package com.batval.textparsing.services.sorter; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; public class WordSortTest { private List<String> wordsToString = new ArrayList<>(); private List<String> wordsToStringSorted = new ArrayList<>(); @Before public void beforeTest() { wordsToString.add("started"); wordsToString.add("with"); wordsToString.add("is"); wordsToString.add("an"); wordsToString.add("a"); wordsToString.add("in"); wordsToString.add("spring"); wordsToStringSorted.add("a"); wordsToStringSorted.add("an"); wordsToStringSorted.add("in"); wordsToStringSorted.add("is"); wordsToStringSorted.add("spring"); wordsToStringSorted.add("started"); wordsToStringSorted.add("with"); } @After public void afterTest() { wordsToStringSorted=null; wordsToString=null; } @Test public void sortWords() { Character character; Collections.sort(wordsToString); character = wordsToString.get(0).charAt(0); for (String word : wordsToString) { if (character != word.charAt(0)) { System.out.print("\n ".concat(word)); character = word.charAt(0); } else { System.out.print(" ".concat(word)); } } assertEquals(wordsToStringSorted,wordsToString); } }
true
5c4c6e80d71d7f81a46693b93306c9eef16ba440
Java
wahyuirgan/Katalog-Movie-Extended
/app/src/main/java/top/technopedia/myapplicationkatalogfilm/Fragment/NowPlayingFragment.java
UTF-8
2,342
2.125
2
[]
no_license
package top.technopedia.myapplicationkatalogfilm.Fragment; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import top.technopedia.myapplicationkatalogfilm.Loader.NowPlayAsyncTaskLoader; import top.technopedia.myapplicationkatalogfilm.Model.MovieList; import top.technopedia.myapplicationkatalogfilm.Adapter.NowUpAdapter; import top.technopedia.myapplicationkatalogfilm.R; import java.util.ArrayList; import java.util.Objects; /** * A simple {@link Fragment} subclass. */ public class NowPlayingFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<MovieList>> { NowUpAdapter adapter; Context context; RecyclerView mRecyclerView; ArrayList<MovieList> nowPlayingData; public NowPlayingFragment() { // Required empty public constructor } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_now_playing, container, false); context = view.getContext(); mRecyclerView = view.findViewById(R.id.rv_now_playing); adapter = new NowUpAdapter(Objects.requireNonNull(getActivity())); mRecyclerView.setLayoutManager(new LinearLayoutManager(context)); mRecyclerView.setAdapter(adapter); getLoaderManager().initLoader(0, null, this); return view; } @NonNull @Override public Loader<ArrayList<MovieList>> onCreateLoader(int id, Bundle args) { return new NowPlayAsyncTaskLoader(getContext(), nowPlayingData); } @Override public void onLoadFinished(@NonNull Loader<ArrayList<MovieList>> loader, ArrayList<MovieList> nowPlayingData) { adapter.setData(nowPlayingData); } @Override public void onLoaderReset(@NonNull Loader<ArrayList<MovieList>> loader) { adapter.setData(null); } }
true
92affd537f525f95b859e8ffac996772355f3183
Java
yangguangzb/leetcode
/lanqiao/src/main/java/com/san/zhenti2015/Main07.java
UTF-8
1,220
3.140625
3
[]
no_license
package com.san.zhenti2015; /** * 四阶幻方 * @description * @author zhangbiao * @time 2018-5-14 下午2:31:08 */ public class Main07 { //答案:416 public static void main(String[] args) { a[1]=1; vis[1]=1; dfs(2); System.out.println("count="+count); } //定义访问数组,存储数组 static int[] vis=new int[17]; static int[] a=new int[17]; static int count=0; //dfs,由于每行的和都相等,因此每行的和等于34 public static void dfs(int step){ if(step==5){ if(a[1]+a[2]+a[3]+a[4]!=34) return ; } if(step==9){ if(a[5]+a[6]+a[7]+a[8]!=34) return ; } if(step==13){ if(a[9]+a[10]+a[11]+a[12]!=34) return ; } if(step==14) if(a[1]+a[5]+a[9]+a[13]!=34) return ; if(step==15){ if(a[2]+a[6]+a[10]+a[14]!=34) return ; } if(step==16){ if(a[3]+a[7]+a[11]+a[15]!=34) return ; } if(step==17){ if(a[13]+a[14]+a[15]+a[16]==34&&a[4]+a[8]+a[12]+a[16]==34&& a[1]+a[6]+a[11]+a[16]==34&&a[4]+a[7]+a[10]+a[13]==34){ count++; } } for(int i=2;i<=16;i++){ if(vis[i]==0){ vis[i]=1; a[step]=i; dfs(step+1); vis[i]=0; } } } }
true