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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4c57f55b5fc86ba25b994cfdf83348798788b700 | Java | lujoca12/ActasGrado-2.0 | /src/java/org/uteq/sesion/ExamenComplexivoFacadeLocal.java | UTF-8 | 727 | 1.882813 | 2 | [] | 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 org.uteq.sesion;
import java.util.List;
import javax.ejb.Local;
import org.uteq.model.ExamenComplexivo;
/**
*
* @author Moises
*/
@Local
public interface ExamenComplexivoFacadeLocal {
void create(ExamenComplexivo examenComplexivo);
void edit(ExamenComplexivo examenComplexivo);
void remove(ExamenComplexivo examenComplexivo);
ExamenComplexivo find(Object id);
List<ExamenComplexivo> findAll();
List<ExamenComplexivo> findRange(int[] range);
int count();
}
| true |
6662616f36fa90c9f4708ad6cf364249fe7e784c | Java | saarthak08/FormSubmissionPortal-AndroidClient | /app/src/main/java/com/sg/formsubmissionportal_androidclient/ui/MainActivity/MainActivity.java | UTF-8 | 6,682 | 1.71875 | 2 | [] | no_license | package com.sg.formsubmissionportal_androidclient.ui.MainActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.os.Handler;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import com.sg.formsubmissionportal_androidclient.R;
import com.sg.formsubmissionportal_androidclient.di.component.DaggerMainActivityComponent;
import com.sg.formsubmissionportal_androidclient.di.component.MainActivityComponent;
import com.sg.formsubmissionportal_androidclient.di.module.OtherNetworkServicesModule;
import com.sg.formsubmissionportal_androidclient.network.FormService;
import com.sg.formsubmissionportal_androidclient.network.RetrofitInstance;
import com.sg.formsubmissionportal_androidclient.network.UserService;
import com.sg.formsubmissionportal_androidclient.ui.LoginActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.view.Menu;
import android.widget.TextView;
import retrofit2.Retrofit;
import static com.sg.formsubmissionportal_androidclient.di.App.PREFER_NAME;
import static com.sg.formsubmissionportal_androidclient.di.App.PRIVATE_MODE;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
public DrawerLayout drawerLayout;
public NavController navController;
public SwipeRefreshLayout swipeRefreshLayout;
private NavigationView navigationView;
SharedPreferences pref;
SharedPreferences.Editor editor;
public static String firstName;
public static String lastName;
public static String email;
public static String role;
public static String token;
public static FormService formService;
public static UserService userService;
public static Long userid;
private static MainActivityComponent component;
private static Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pref=getSharedPreferences(PREFER_NAME,PRIVATE_MODE);
firstName=pref.getString("firstName","");
lastName=pref.getString("lastName","");
email=pref.getString("email","");
role=pref.getString("role","");
userid=pref.getLong("userid",0);
token=pref.getString("token","");
buildDaggerOtherComponent();
editor=pref.edit();
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_myprofile,R.id.nav_allforms,R.id.nav_myforms)
.setDrawerLayout(drawerLayout)
.build();
navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
Log.d("MainActivityDon123",pref.getString("email",""));
swipeRefreshLayout=findViewById(R.id.swipeRefreshLayoutMain);
swipeRefreshLayout.setColorSchemeColors(Color.BLUE, Color.DKGRAY, Color.RED,Color.GREEN,Color.MAGENTA,Color.BLACK,Color.CYAN);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
},4000);
}
});
View v=navigationView.getHeaderView(0);
TextView name=v.findViewById(R.id.headerNameTV);
TextView email=v.findViewById(R.id.headerEmailTV);
name.setText(firstName+" "+lastName);
email.setText(this.email);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}else {
super.onBackPressed();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_logout) {
editor.clear().apply();
editor.clear().commit();
editor.remove("firsName").commit();
editor.remove("lastName").commit();
editor.remove("email").commit();
editor.remove("token").commit();
editor.remove("userid").commit();
editor.remove("role").commit();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
MainActivity.this.finish();
}
return super.onOptionsItemSelected(item);
}
public static void buildDaggerOtherComponent(){
component= DaggerMainActivityComponent.builder()
.otherNetworkServicesModule(new OtherNetworkServicesModule(token))
.build();
}
public static MainActivityComponent getComponent(){
return component;
}
/*@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
item.setCheckable(true);
drawerLayout.closeDrawers();
int id = item.getItemId();
switch (id){
case R.id.nav_logout:
break;
}
return true;
}
*/
}
| true |
5f2bbc4ca55eed8198762cadd35b0fe5fed9ff5e | Java | tiansiyu0210/java-8-practice | /src/main/java/src/main/java/Concurrency/DeadLockDemo/mainTest.java | UTF-8 | 812 | 3.109375 | 3 | [] | no_license | package src.main.java.Concurrency.DeadLockDemo;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class mainTest {
public static void main(String[] args) {
Fox fox1 = new Fox();
Fox fox2 = new Fox();
Water water = new Water();
Food food = new Food();
Water water1 = new Water();
Food food1 = new Food();
ExecutorService executorService = null;
try{
executorService = Executors.newScheduledThreadPool(10);
executorService.submit(()-> fox1.eatAndDrink(food, water));
executorService.submit(()-> fox2.drinkAndEat(food,water));
}finally {
if(executorService != null){
executorService.shutdown();
}
}
}
}
| true |
d95d5c113154d9c5a26b7c80d88184b17f2f1c65 | Java | honeycombio/beeline-java | /beeline-core/src/test/java/io/honeycomb/beeline/tracing/propagation/HttpClientPropagatorTest.java | UTF-8 | 7,429 | 1.867188 | 2 | [
"Apache-2.0"
] | permissive | package io.honeycomb.beeline.tracing.propagation;
import io.honeycomb.beeline.tracing.Span;
import io.honeycomb.beeline.tracing.Tracer;
import io.honeycomb.libhoney.shaded.org.apache.http.HttpHeaders;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiFunction;
import static io.honeycomb.beeline.tracing.propagation.MockSpanUtils.stubFluentCalls;
import static io.honeycomb.beeline.tracing.utils.TraceFieldConstants.*;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class HttpClientPropagatorTest {
private static final String EXPECTED_TRACE_HEADER = "traceHeader1";
private static final String EXPECTED_SPAN_NAME = "expectedSpanName";
@Mock
private Tracer mockTracer;
@Mock
private Span mockSpan;
@Mock
private HttpClientRequestAdapter mockHttpRequest;
@Mock
private HttpClientResponseAdapter mockHttpResponse;
@Mock
private PropagationCodec<Map<String, String>> mockPropagationCodec;
@Mock
private BiFunction<HttpClientRequestAdapter, PropagationContext, Optional<Map<String, String>>> mockTracePropagationHook;
private HttpClientPropagator httpClientPropagator;
@Before
public void setUp() {
stubFluentCalls(mockSpan);
httpClientPropagator = new HttpClientPropagator.Builder(mockTracer, r -> EXPECTED_SPAN_NAME)
.setPropagationCodec(mockPropagationCodec)
.build();
}
@Test
public void whenStartPropagation_traceHeaderIsAdded_onlyRequiredSpanFieldsAreAdded() {
when(mockTracer.startChildSpan(EXPECTED_SPAN_NAME)).thenReturn(mockSpan);
when(mockPropagationCodec.encode(any())).thenReturn(Optional.of(Collections.singletonMap(HttpHeaderV1PropagationCodec.HONEYCOMB_TRACE_HEADER, EXPECTED_TRACE_HEADER)));
final String expectedHttpMethod = "httpMethod1";
when(mockHttpRequest.getMethod()).thenReturn(expectedHttpMethod);
final Span span = httpClientPropagator.startPropagation(mockHttpRequest);
verify(span, times(2)).addField(anyString(), any());
verify(span).addField(TYPE_FIELD, HttpClientPropagator.HTTP_CLIENT_SPAN_TYPE);
verify(span).addField(CLIENT_REQUEST_METHOD_FIELD, expectedHttpMethod);
verify(mockHttpRequest).addHeader(HttpHeaderV1PropagationCodec.HONEYCOMB_TRACE_HEADER, EXPECTED_TRACE_HEADER);
}
@Test
public void whenStartPropagation_withAdditionalData_optionalSpanFieldsAreAdded_traceHeaderIsAdded() {
when(mockTracer.startChildSpan(EXPECTED_SPAN_NAME)).thenReturn(mockSpan);
when(mockPropagationCodec.encode(any())).thenReturn(Optional.of(Collections.singletonMap(HttpHeaderV1PropagationCodec.HONEYCOMB_TRACE_HEADER, EXPECTED_TRACE_HEADER)));
final String expectedHttpMethod = "httpMethod1";
when(mockHttpRequest.getMethod()).thenReturn(expectedHttpMethod);
final String expectedPath = "expectedPath";
when(mockHttpRequest.getPath()).thenReturn(Optional.of(expectedPath));
final String expectedContentType = "expectedContentType";
when(mockHttpRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE)).thenReturn(Optional.of(expectedContentType));
final int expectedContentLength = 1;
when(mockHttpRequest.getContentLength()).thenReturn(expectedContentLength);
final Span span = httpClientPropagator.startPropagation(mockHttpRequest);
verify(span, times(5)).addField(anyString(), any());
verify(span).addField(TYPE_FIELD, HttpClientPropagator.HTTP_CLIENT_SPAN_TYPE);
verify(span).addField(CLIENT_REQUEST_METHOD_FIELD, expectedHttpMethod);
verify(span).addField(CLIENT_REQUEST_CONTENT_TYPE_FIELD, expectedContentType);
verify(span).addField(CLIENT_REQUEST_CONTENT_LENGTH_FIELD, expectedContentLength);
verify(span).addField(CLIENT_REQUEST_PATH_FIELD, expectedPath);
verify(mockHttpRequest).addHeader(HttpHeaderV1PropagationCodec.HONEYCOMB_TRACE_HEADER, EXPECTED_TRACE_HEADER);
}
@Test
public void whenStartPropagation_andTraceHeaderIsGeneratedFromContext_doNotAddTraceHeader() {
when(mockTracer.startChildSpan(EXPECTED_SPAN_NAME)).thenReturn(mockSpan);
when(mockPropagationCodec.encode(any())).thenReturn(Optional.empty());
final String expectedHttpMethod = "httpMethod1";
when(mockHttpRequest.getMethod()).thenReturn(expectedHttpMethod);
final Span span = httpClientPropagator.startPropagation(mockHttpRequest);
verify(span, times(2)).addField(anyString(), any());
verify(span).addField(TYPE_FIELD, HttpClientPropagator.HTTP_CLIENT_SPAN_TYPE);
verify(span).addField(CLIENT_REQUEST_METHOD_FIELD, expectedHttpMethod);
verify(mockHttpRequest, never()).addHeader(HttpHeaderV1PropagationCodec.HONEYCOMB_TRACE_HEADER, EXPECTED_TRACE_HEADER);
}
@Test
public void whenEndPropagation_withNonNullResponse_thenOnlyAddRequiredResponseFields_andCloseSpan() {
final int expectedHttpStatus = 200;
when(mockHttpResponse.getStatus()).thenReturn(expectedHttpStatus);
httpClientPropagator.endPropagation(mockHttpResponse, null, mockSpan);
verify(mockSpan, times(1)).addField(anyString(), any());
verify(mockSpan).addField(CLIENT_RESPONSE_STATUS_CODE_FIELD, expectedHttpStatus);
verify(mockSpan).close();
}
@Test
public void whenEndPropagation_withNonNullError_thenOnlyAddErrorFields_andCloseSpan() {
final String expectedMessage = "expectedMessage";
final TestException throwable = new TestException(expectedMessage);
httpClientPropagator.endPropagation(null, throwable, mockSpan);
verify(mockSpan, times(2)).addField(anyString(), any());
verify(mockSpan).addField(CLIENT_REQUEST_ERROR_FIELD,"TestException");
verify(mockSpan).addField(CLIENT_REQUEST_ERROR_DETAIL_FIELD, expectedMessage);
verify(mockSpan).close();
}
@Test
public void GIVEN_propagateIsNotNull_EXPECT_hookToBeUsedInsteadOfPropagationCodec() {
when(mockTracer.startChildSpan(EXPECTED_SPAN_NAME)).thenReturn(mockSpan);
when(mockHttpRequest.getFirstHeader(any(String.class))).thenReturn(Optional.empty());
when(mockHttpRequest.getPath()).thenReturn(Optional.empty());
when(mockHttpRequest.getContentLength()).thenReturn(0);
when(mockHttpRequest.getMethod()).thenReturn("GET");
when(mockSpan.getTraceContext()).thenReturn(PropagationContext.emptyContext());
when(mockTracePropagationHook.apply(mockHttpRequest, PropagationContext.emptyContext())).thenReturn(Optional.empty());
final HttpClientPropagator propagator = new HttpClientPropagator.Builder(mockTracer, r -> EXPECTED_SPAN_NAME)
.setTracePropagationHook(mockTracePropagationHook)
.build();
propagator.startPropagation(mockHttpRequest);
verify(mockTracePropagationHook, times(1)).apply(mockHttpRequest, PropagationContext.emptyContext());
verify(mockPropagationCodec, times(0)).encode(any(PropagationContext.class));
}
private class TestException extends Exception {
public TestException(String message) {
super(message);
}
}
}
| true |
2a63884db13183979dfa451e3378ff4dbd314330 | Java | truar/bank-kata | /src/main/java/com/zenikata/bank/domain/SGBankAccount.java | UTF-8 | 1,127 | 2.984375 | 3 | [] | no_license | package com.zenikata.bank.domain;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class SGBankAccount implements BankAccount {
private static final BigDecimal ZERO = new BigDecimal(0);
private final Clock clock;
private final List<Transaction> transactionsHistory = new ArrayList<>();
public SGBankAccount(Clock clock) {
this.clock = clock;
}
public void deposit(Money amountToDepose) {
Transaction transaction = new Transaction(TransactionType.DEPOSIT, amountToDepose.amount(), clock.now());
transactionsHistory.add(transaction);
}
public void withdraw(Money amountToWithdraw) {
Transaction transaction = new Transaction(TransactionType.WITHDRAW, amountToWithdraw.amount().negate(), clock.now());
transactionsHistory.add(transaction);
}
public List<Transaction> transactions() {
return transactionsHistory;
}
public BigDecimal balance() {
return transactionsHistory.stream()
.map(Transaction::amount)
.reduce(ZERO, BigDecimal::add);
}
}
| true |
004a2ed209fc0d161aa46087a12a7440a6979b65 | Java | nkhuyu/xpresso | /src/main/java/com/wantedtech/common/xpresso/HappyObject/HappyObject.java | UTF-8 | 454 | 2.5 | 2 | [
"MIT"
] | permissive | package com.wantedtech.common.xpresso.HappyObject;
import com.wantedtech.common.xpresso.helpers.Equals;
import com.wantedtech.common.xpresso.helpers.HashCode;
public class HappyObject {
Object lhs;
public HappyObject(Object o){
this.lhs = o;
}
public int hashCode(){
return new HashCode(this.lhs, new String[0]).getHashCode();
}
public boolean equals(Object rhs){
return new Equals(this.lhs, rhs, new String[0]).getEquals();
}
}
| true |
15699930a6a7b68f1bfef243dae9617b91fd4b0c | Java | tianwyam/spring-cloud-learn | /spring-cloud-learn-hystrix-books-service/src/main/java/com/tianya/springcloud/hystrix/controller/BooksController.java | UTF-8 | 1,475 | 2.1875 | 2 | [] | no_license | package com.tianya.springcloud.hystrix.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.tianya.springcloud.hystrix.entity.BookVo;
import com.tianya.springcloud.hystrix.feign.BookServiceFeignClient;
@RestController
@RequestMapping("/book")
public class BooksController {
@Autowired
private BookServiceFeignClient bookServiceFeignClient;
@Autowired
private RestTemplate restTemplate ;
@GetMapping({"","/"})
// 熔断器配置(方式一)
@HystrixCommand(fallbackMethod = "defaultBook")
public BookVo getBook() {
return restTemplate.getForObject("http://localhost:9090/book/", BookVo.class);
}
/**
* @description
* 短路器 默認執行方法
* @author TianwYam
* @date 2022年2月22日下午9:01:06
* @return
*/
public BookVo defaultBook() {
return BookVo.builder()
.name("《肖生克的救贖-DEFAULT》")
.author("tianwyam").build();
}
/**
* @description
* 采用feign方式调用
* @author TianwYam
* @date 2022年2月24日下午7:25:03
* @return
*/
@GetMapping("/feign")
public BookVo getFeignBookVo() {
return bookServiceFeignClient.getBookVo();
}
}
| true |
b2038d0685d46184bbb87651db255a10a90e99c6 | Java | iochti/process-rule-type | /src/main/java/iochti/processRuleType/document/ProcessRuleDocumentAdapter.java | UTF-8 | 743 | 2.03125 | 2 | [] | no_license | package iochti.processRuleType.document;
import iochti.processRuleType.dto.ProcessRuleTypeDTO;
import org.springframework.stereotype.Service;
@Service
public class ProcessRuleDocumentAdapter {
public ProcessRuleTypeDTO buildDTO(ProcessRuleTypeDocument document) {
ProcessRuleTypeDTO result = new ProcessRuleTypeDTO();
result.setId(document.getId());
result.setName(document.getName());
result.setParameters(document.getParameters());
return result;
}
public ProcessRuleTypeDocument buildDocument(ProcessRuleTypeDTO dto) {
ProcessRuleTypeDocument result = new ProcessRuleTypeDocument();
result.setId(dto.getId());
result.setName(dto.getName());
result.setParameters(dto.getParameters());
return result;
}
}
| true |
f9897c5db97762e95187a5ed4f2727f021f90105 | Java | liyajiele/shengaAPP | /usercore/src/main/java/com/sxp/sa/user/dao/UserDao.java | UTF-8 | 531 | 1.914063 | 2 | [] | no_license | package com.sxp.sa.user.dao;
import com.sxp.sa.user.entity.User;
import java.util.List;
/**
* Created by miss on 2017/2/17.
*/
public interface UserDao {
/**
* 根据用户名查找用户
* @param username
* @return
*/
User findByUsername(String username, Integer status);
/**
* 根据id查询用户信息
* @param uid
* @param status
* @return
*/
User findById(Long uid ,Integer status);
List<User> findByNicknamelike(String nickname,Integer status);
}
| true |
24138ece18a8fc153f3f82e07fa957b0766a8355 | Java | shaojun-zhu/dota | /src/main/java/com/zsj/dota/Handler/DotaHandler.java | UTF-8 | 544 | 1.953125 | 2 | [] | no_license | package com.zsj.dota.Handler;
import com.zsj.dota.entitty.Dota;
import com.zsj.dota.repository.DotaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class DotaHandler {
@Autowired
private DotaRepository dotaRepository;
@GetMapping("/findAll")
public List<Dota> findAll(Dota dota){
return dotaRepository.findAll();
}
}
| true |
6a968ffeaba005edb6ef177caf84a09ab7583fe4 | Java | chme/db-doc-generator | /src/main/java/io/github/chme/dbdocgenerator/OutputConfiguration.java | UTF-8 | 1,361 | 2.140625 | 2 | [
"MIT"
] | permissive | package io.github.chme.dbdocgenerator;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import io.quarkus.arc.config.ConfigProperties;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Singular;
@ConfigProperties(prefix = "output")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class OutputConfiguration {
String file;
@Builder.Default
String title = "Tables";
@Singular
List<TableConfig> tables;
@Singular
List<CategoryConfig> categories;
public boolean hasTableConfig() {
return !tables.isEmpty() && StringUtils.isNotBlank(tables.get(0).name);
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class TableConfig {
String name;
@Builder.Default
Optional<String> title = Optional.empty();
@Builder.Default
Optional<String> description = Optional.empty();
@Builder.Default
Optional<String> category = Optional.empty();
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class CategoryConfig {
String name;
@Builder.Default
Optional<String> title = Optional.empty();
@Builder.Default
Optional<String> description = Optional.empty();
@Builder.Default
boolean isDefault = false;
}
}
| true |
9191a0b363ab9ecb958e0fdbc7d0581f5edcb6c8 | Java | utamaro/UsoBasic | /src/jp/gr/java_conf/utamaro/usobasic/client/Interrupt.java | UTF-8 | 848 | 2.640625 | 3 | [] | no_license | package jp.gr.java_conf.utamaro.usobasic.client;
import java.util.logging.Logger;
public class Interrupt{
public enum STATE{
ON,OFF,STOP
};
private STATE state=STATE.OFF;
private int line=0;
private boolean pending=false;
private static ProgramContext context=null;
private static Logger logger = Logger.getLogger("interrupt");
public Interrupt(){
}
public void setState(STATE s){
state=s;
if(state==STATE.ON && pending){
pending=false;
trigger();
}
}
public static void setExecutor(ProgramContext context){
Interrupt.context=context;
}
public void setLine(int line){
this.line=line;
}
public boolean trigger(){
if(state==STATE.STOP && context!=null){
pending=true;
return true;
}
if(state==STATE.ON && context!=null && line!=0){
context.gosub(line);
return true;
}
return false;
}
}
| true |
43077adf1e758d8fc5f9407026154f703b015e52 | Java | gatechatl/DRPPM | /src/rnaseq/pcpa/AddChr.java | UTF-8 | 1,540 | 2.953125 | 3 | [] | no_license | package rnaseq.pcpa;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
/**
* Specialized class for adding chr to bed files
* @author tshaw
*
*/
public class AddChr {
public static String type() {
return "MISC";
}
public static String description() {
return "Specialized class for adding chr to bed files";
}
public static String parameter_info() {
return "[inputBedFile]";
}
public static void execute(String[] args) {
try {
String inputFile = args[0];
String tmpFile = inputFile + ".tmp";
FileWriter fwriter = new FileWriter(tmpFile);
BufferedWriter out = new BufferedWriter(fwriter);
FileInputStream fstream = new FileInputStream(inputFile);
DataInputStream din = new DataInputStream(fstream);
BufferedReader in = new BufferedReader(new InputStreamReader(din));
while (in.ready()) {
String str = in.readLine();
out.write("chr" + str + "\n");
}
in.close();
out.close();
fwriter = new FileWriter(inputFile);
out = new BufferedWriter(fwriter);
fstream = new FileInputStream(tmpFile);
din = new DataInputStream(fstream);
in = new BufferedReader(new InputStreamReader(din));
while (in.ready()) {
String str = in.readLine();
out.write(str + "\n");
}
in.close();
out.close();
File f = new File(tmpFile);
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
eee6489d6eb76962bfac36bf1ffe9ab5da6f6bbe | Java | elastic/elasticsearch-java | /java-client/src/main/java/co/elastic/clients/elasticsearch/_types/aggregations/StringStatsAggregate.java | UTF-8 | 10,655 | 1.773438 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//----------------------------------------------------
// THIS CODE IS GENERATED. MANUAL EDITS WILL BE LOST.
//----------------------------------------------------
package co.elastic.clients.elasticsearch._types.aggregations;
import co.elastic.clients.json.JsonpDeserializable;
import co.elastic.clients.json.JsonpDeserializer;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.JsonpUtils;
import co.elastic.clients.json.ObjectBuilderDeserializer;
import co.elastic.clients.json.ObjectDeserializer;
import co.elastic.clients.util.ApiTypeHelper;
import co.elastic.clients.util.ObjectBuilder;
import jakarta.json.stream.JsonGenerator;
import java.lang.Double;
import java.lang.Integer;
import java.lang.Long;
import java.lang.String;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import javax.annotation.Nullable;
// typedef: _types.aggregations.StringStatsAggregate
/**
*
* @see <a href=
* "../../doc-files/api-spec.html#_types.aggregations.StringStatsAggregate">API
* specification</a>
*/
@JsonpDeserializable
public class StringStatsAggregate extends AggregateBase implements AggregateVariant {
private final long count;
private final int minLength;
private final int maxLength;
private final double avgLength;
private final double entropy;
private final Map<String, Double> distribution;
@Nullable
private final String minLengthAsString;
@Nullable
private final String maxLengthAsString;
@Nullable
private final String avgLengthAsString;
// ---------------------------------------------------------------------------------------------
private StringStatsAggregate(Builder builder) {
super(builder);
this.count = ApiTypeHelper.requireNonNull(builder.count, this, "count");
this.minLength = ApiTypeHelper.requireNonNull(builder.minLength, this, "minLength");
this.maxLength = ApiTypeHelper.requireNonNull(builder.maxLength, this, "maxLength");
this.avgLength = ApiTypeHelper.requireNonNull(builder.avgLength, this, "avgLength");
this.entropy = ApiTypeHelper.requireNonNull(builder.entropy, this, "entropy");
this.distribution = ApiTypeHelper.unmodifiable(builder.distribution);
this.minLengthAsString = builder.minLengthAsString;
this.maxLengthAsString = builder.maxLengthAsString;
this.avgLengthAsString = builder.avgLengthAsString;
}
public static StringStatsAggregate of(Function<Builder, ObjectBuilder<StringStatsAggregate>> fn) {
return fn.apply(new Builder()).build();
}
/**
* Aggregate variant kind.
*/
@Override
public Aggregate.Kind _aggregateKind() {
return Aggregate.Kind.StringStats;
}
/**
* Required - API name: {@code count}
*/
public final long count() {
return this.count;
}
/**
* Required - API name: {@code min_length}
* <p>
* Defaults to {@code 0} if parsed from a JSON {@code null} value.
*/
public final int minLength() {
return this.minLength;
}
/**
* Required - API name: {@code max_length}
* <p>
* Defaults to {@code 0} if parsed from a JSON {@code null} value.
*/
public final int maxLength() {
return this.maxLength;
}
/**
* Required - API name: {@code avg_length}
* <p>
* Defaults to {@code 0} if parsed from a JSON {@code null} value.
*/
public final double avgLength() {
return this.avgLength;
}
/**
* Required - API name: {@code entropy}
* <p>
* Defaults to {@code 0} if parsed from a JSON {@code null} value.
*/
public final double entropy() {
return this.entropy;
}
/**
* API name: {@code distribution}
*/
public final Map<String, Double> distribution() {
return this.distribution;
}
/**
* API name: {@code min_length_as_string}
*/
@Nullable
public final String minLengthAsString() {
return this.minLengthAsString;
}
/**
* API name: {@code max_length_as_string}
*/
@Nullable
public final String maxLengthAsString() {
return this.maxLengthAsString;
}
/**
* API name: {@code avg_length_as_string}
*/
@Nullable
public final String avgLengthAsString() {
return this.avgLengthAsString;
}
protected void serializeInternal(JsonGenerator generator, JsonpMapper mapper) {
super.serializeInternal(generator, mapper);
generator.writeKey("count");
generator.write(this.count);
generator.writeKey("min_length");
JsonpUtils.serializeIntOrNull(generator, this.minLength, 0);
generator.writeKey("max_length");
JsonpUtils.serializeIntOrNull(generator, this.maxLength, 0);
generator.writeKey("avg_length");
JsonpUtils.serializeDoubleOrNull(generator, this.avgLength, 0);
generator.writeKey("entropy");
JsonpUtils.serializeDoubleOrNull(generator, this.entropy, 0);
if (ApiTypeHelper.isDefined(this.distribution)) {
generator.writeKey("distribution");
generator.writeStartObject();
for (Map.Entry<String, Double> item0 : this.distribution.entrySet()) {
generator.writeKey(item0.getKey());
generator.write(item0.getValue());
}
generator.writeEnd();
}
if (this.minLengthAsString != null) {
generator.writeKey("min_length_as_string");
generator.write(this.minLengthAsString);
}
if (this.maxLengthAsString != null) {
generator.writeKey("max_length_as_string");
generator.write(this.maxLengthAsString);
}
if (this.avgLengthAsString != null) {
generator.writeKey("avg_length_as_string");
generator.write(this.avgLengthAsString);
}
}
// ---------------------------------------------------------------------------------------------
/**
* Builder for {@link StringStatsAggregate}.
*/
public static class Builder extends AggregateBase.AbstractBuilder<Builder>
implements
ObjectBuilder<StringStatsAggregate> {
private Long count;
private Integer minLength;
private Integer maxLength;
private Double avgLength;
private Double entropy;
@Nullable
private Map<String, Double> distribution;
@Nullable
private String minLengthAsString;
@Nullable
private String maxLengthAsString;
@Nullable
private String avgLengthAsString;
/**
* Required - API name: {@code count}
*/
public final Builder count(long value) {
this.count = value;
return this;
}
/**
* Required - API name: {@code min_length}
* <p>
* Defaults to {@code 0} if parsed from a JSON {@code null} value.
*/
public final Builder minLength(int value) {
this.minLength = value;
return this;
}
/**
* Required - API name: {@code max_length}
* <p>
* Defaults to {@code 0} if parsed from a JSON {@code null} value.
*/
public final Builder maxLength(int value) {
this.maxLength = value;
return this;
}
/**
* Required - API name: {@code avg_length}
* <p>
* Defaults to {@code 0} if parsed from a JSON {@code null} value.
*/
public final Builder avgLength(double value) {
this.avgLength = value;
return this;
}
/**
* Required - API name: {@code entropy}
* <p>
* Defaults to {@code 0} if parsed from a JSON {@code null} value.
*/
public final Builder entropy(double value) {
this.entropy = value;
return this;
}
/**
* API name: {@code distribution}
* <p>
* Adds all entries of <code>map</code> to <code>distribution</code>.
*/
public final Builder distribution(Map<String, Double> map) {
this.distribution = _mapPutAll(this.distribution, map);
return this;
}
/**
* API name: {@code distribution}
* <p>
* Adds an entry to <code>distribution</code>.
*/
public final Builder distribution(String key, Double value) {
this.distribution = _mapPut(this.distribution, key, value);
return this;
}
/**
* API name: {@code min_length_as_string}
*/
public final Builder minLengthAsString(@Nullable String value) {
this.minLengthAsString = value;
return this;
}
/**
* API name: {@code max_length_as_string}
*/
public final Builder maxLengthAsString(@Nullable String value) {
this.maxLengthAsString = value;
return this;
}
/**
* API name: {@code avg_length_as_string}
*/
public final Builder avgLengthAsString(@Nullable String value) {
this.avgLengthAsString = value;
return this;
}
@Override
protected Builder self() {
return this;
}
/**
* Builds a {@link StringStatsAggregate}.
*
* @throws NullPointerException
* if some of the required fields are null.
*/
public StringStatsAggregate build() {
_checkSingleUse();
return new StringStatsAggregate(this);
}
}
// ---------------------------------------------------------------------------------------------
/**
* Json deserializer for {@link StringStatsAggregate}
*/
public static final JsonpDeserializer<StringStatsAggregate> _DESERIALIZER = ObjectBuilderDeserializer
.lazy(Builder::new, StringStatsAggregate::setupStringStatsAggregateDeserializer);
protected static void setupStringStatsAggregateDeserializer(ObjectDeserializer<StringStatsAggregate.Builder> op) {
AggregateBase.setupAggregateBaseDeserializer(op);
op.add(Builder::count, JsonpDeserializer.longDeserializer(), "count");
op.add(Builder::minLength, JsonpDeserializer.intOrNullDeserializer(0), "min_length");
op.add(Builder::maxLength, JsonpDeserializer.intOrNullDeserializer(0), "max_length");
op.add(Builder::avgLength, JsonpDeserializer.doubleOrNullDeserializer(0), "avg_length");
op.add(Builder::entropy, JsonpDeserializer.doubleOrNullDeserializer(0), "entropy");
op.add(Builder::distribution, JsonpDeserializer.stringMapDeserializer(JsonpDeserializer.doubleDeserializer()),
"distribution");
op.add(Builder::minLengthAsString, JsonpDeserializer.stringDeserializer(), "min_length_as_string");
op.add(Builder::maxLengthAsString, JsonpDeserializer.stringDeserializer(), "max_length_as_string");
op.add(Builder::avgLengthAsString, JsonpDeserializer.stringDeserializer(), "avg_length_as_string");
}
}
| true |
0ff4b1f48d209c999a83675d10f009ad80a18407 | Java | jmfdezb/calculadora | /src/calculadora/controladores/EntradaTeclado.java | UTF-8 | 847 | 2.40625 | 2 | [] | no_license | package calculadora.controladores;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class EntradaTeclado {
private static final AtajosTeclado[] ATAJOS = AtajosTeclado.getAtajos();
public EntradaTeclado(JPanel fondo, Controlador controlador) {
String etiqueta;
int atajo, modificador;
InputMap mapaEntrada = fondo.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap mapaAccion = fondo.getActionMap();
for ( int i = 0; i < ATAJOS.length; i++) {
etiqueta = ATAJOS[i].getEtiqueta();
atajo = ATAJOS[i].getAtajo();
modificador = ATAJOS[i].getModificador();
mapaEntrada.put(KeyStroke.getKeyStroke(atajo,modificador), etiqueta);
mapaAccion.put(etiqueta,new AccionPulsacion(etiqueta,controlador));
}
}
}
| true |
c469c73e4dfb8d2ad778e028db34446e987b09e0 | Java | waterif/hermes | /hermes-consumer/src/main/java/com/ctrip/hermes/consumer/engine/pipeline/ConsumerValveRegistry.java | UTF-8 | 747 | 1.679688 | 2 | [
"Apache-2.0"
] | permissive | package com.ctrip.hermes.consumer.engine.pipeline;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.unidal.lookup.annotation.Named;
import com.ctrip.hermes.consumer.build.BuildConstants;
import com.ctrip.hermes.core.pipeline.AbstractValveRegistry;
import com.ctrip.hermes.core.pipeline.ValveRegistry;
/**
* @author Leo Liang(liangjinhua@gmail.com)
*
*/
@Named(type = ValveRegistry.class, value = BuildConstants.CONSUMER)
public class ConsumerValveRegistry extends AbstractValveRegistry implements Initializable {
@Override
public void initialize() throws InitializationException {
// doRegister(ConsumerTracingValve.ID, 0);
}
}
| true |
c3bb33d20a182743700a09e88e1ddbe2b9688073 | Java | heamaya/keep-on-coding | /jhtp/src/chapter16/exercise17/SortWords.java | UTF-8 | 817 | 3.390625 | 3 | [] | no_license | package chapter16.exercise17;
import java.util.Scanner;
import java.util.TreeSet;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class SortWords {
public static void main(String [] args) {
final Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
final SortWords sortWords = new SortWords();
sortWords.print(scanner.nextLine());
}
public void print(String sentence) {
final Pattern wordsPattern = Pattern.compile("[A-Z]?[a-z]*[']?[a-z]*");
wordsPattern.matcher(sentence)
.results()
.map(matchResult -> matchResult.group().toLowerCase())
.collect(Collectors.toCollection(TreeSet::new))
.stream()
.forEach(System.out::println);
}
}
| true |
e842bc23ac9c8ef2d843adb0daef21e39ff81516 | Java | krutipandya/Project_Management | /CMPE275_TermProject/src/main/java/com/sjsu/cmpe275/projectmanager/configuration/WebSecurityConfig.java | UTF-8 | 2,186 | 2.015625 | 2 | [] | no_license | package com.sjsu.cmpe275.projectmanager.configuration;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// public class WebSecurityConfig {
@Autowired
DataSource dataSource;
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/assets/**");
web.ignoring().antMatchers("/WEB-INF/views/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// http.authorizeRequests().antMatchers("/home").access("hasRole('ROLE_ADMIN')
// or hasRole('ROLE_USER')").and()
// .formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password").and()
// .logout().permitAll().and().csrf().disable();
http.authorizeRequests().antMatchers("/getRegForm","/register").permitAll();
http.authorizeRequests().antMatchers("/","/home","/project**","/task**","/user**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')").and()
.formLogin().loginPage("/login").failureUrl("/login?error").usernameParameter("username")
.passwordParameter("password").and()
.exceptionHandling().accessDeniedPage("/403").and().csrf();
//and().logout().logoutSuccessUrl("/login?logout")
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username,password, enabled from users where username=?")
.authoritiesByUsernameQuery("select username, role from user_roles where username=?");
}
} | true |
a677e969ad31c43334a3176a0d74e4aad29e357d | Java | JacobM184/PCPartShowcase | /app/src/main/java/com/example/pcpartsoftware/Client.java | UTF-8 | 1,558 | 2.46875 | 2 | [] | no_license | package com.example.pcpartsoftware;
import android.os.Parcel;
import android.os.Parcelable;
public class Client {
private final int clientID;
private final String name;
private final String username;
private static int clientNum = 0;
private final String email;
private final String password;
private final String phoneNumber;
private final String address;
public Client(String name, String email,
String username, String password,
String phoneNumber, String address){
this.name = name;
this.username = username;
this.password = password;
this.email = email;
this.phoneNumber = phoneNumber;
this.address = address;
this.clientID = clientNum;
clientNum++;
}
public Client(Client c){
this.name = c.getName();
this.username = c.getUsername();
this.password = c.getPassword();
this.email = c.getEmail();
this.phoneNumber = c.getPhoneNumber();
this.address = c.getAddress();
this.clientID = getClientID();
}
public int getClientID() {
return clientID;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getAddress() {
return address;
}
public String getEmail() {
return email;
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
}
| true |
5b6cee0d7d74c589b85517e1bf566d4247db98ff | Java | uwitec/CarRentalSystemAndroid | /CarRentalSystem/src/solis/freddy/CarRentalSystem/RemoveReservation.java | UTF-8 | 5,469 | 2.953125 | 3 | [] | no_license | /*Title:RemoveReservation
* Name:Freddy Solis
* Date: May 8, 2012
* ID: 0338
* Abstract: This class is meant for the remove reservations activity. This activity will ask the
* user to chose an reservation they would like to cancel, then it will ask them to confirm and then it will
* remove the reservation. if the user has no reservations it will say so and return to the main menu
*/
package solis.freddy.CarRentalSystem;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class RemoveReservation extends Activity implements OnClickListener
{
private int index =0;
private ReservationSystem creatRes;
private boolean atleast = false;
private boolean doubcheck = false;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.removereservation);
creatRes = new ReservationSystem();
ArrayList <Reservation> reserv = creatRes.getReservations();
ArrayList <Customer> custs = creatRes.getCustomers();
index = creatRes.getIndex();
Customer temp = custs.get(index);
Reservation tempRes;
String name = temp.getUserId();
TextView field = (TextView)findViewById(R.id.viewres);
int size = reserv.size();
int j=0;
while(j<size)
{
tempRes = reserv.get(j);
if(temp.getUserId().equals(name) == true)
{
atleast = true;
field.append(tempRes.toString() + '\n');
}
j++;
}
if(atleast == false)
{
Toast toast = Toast.makeText(this, "No Reservations for this account.", Toast.LENGTH_LONG);
toast.show();
Intent i = new Intent(this,CarRentalSystemActivity.class);
startActivity(i);
}
View cancelButton = findViewById(R.id.cancelReservation);
cancelButton.setOnClickListener(this);
View homeButton = findViewById(R.id.homeButton);
homeButton.setOnClickListener(this);
}
public void onClick(View v)
{
if(v.getId() == R.id.cancelReservation)
{
ArrayList <Reservation> reserv = creatRes.getReservations();
ArrayList <Customer> custs = creatRes.getCustomers();
Customer temp = custs.get(index);
Reservation tempRes;
int choice;
EditText input = (EditText)findViewById(R.id.getreservationnum);
String numbers = input.getText().toString();
choice = Integer.parseInt(numbers);
int size = reserv.size();
int j=0;
while(j<size)
{
tempRes = reserv.get(j);
if(tempRes.getResNumber() == choice)
{
Dates tempdate;
if(tempRes.getCar().equals("Sedan") && doubcheck == true)
{
tempdate = tempRes.getDate();
Cars sedan = creatRes.getSedan();
sedan.removeDate(tempdate);
creatRes.setSedan(sedan);
creatRes.removeReservation(tempRes);
Transaction temptrans = new Transaction(temp, 3);
creatRes.addTrans(temptrans);
Toast toast = Toast.makeText(this, temptrans.toString(), Toast.LENGTH_LONG);
toast.show();
Intent i = new Intent(this,CarRentalSystemActivity.class);
startActivity(i);
}
if(tempRes.getCar().equals("Sedan") && doubcheck == false)
{
Toast toast = Toast.makeText(this, "Are you Sure? Press Cancel Again?, else click Main Menu " , Toast.LENGTH_LONG);
toast.show();
doubcheck =true;
}
if(tempRes.getCar().equals("Truck") && doubcheck == true)
{
tempdate = tempRes.getDate();
Cars truck = creatRes.getTruck();
truck.removeDate(tempdate);
creatRes.setTruck(truck);
creatRes.removeReservation(tempRes);
Transaction temptrans = new Transaction(temp, 3);
creatRes.addTrans(temptrans);
Toast toast = Toast.makeText(this, temptrans.toString(), Toast.LENGTH_LONG);
toast.show();
Intent i = new Intent(this,CarRentalSystemActivity.class);
startActivity(i);
}
if(tempRes.getCar().equals("Truck") && doubcheck == false)
{
Toast toast = Toast.makeText(this, "Are you Sure? Press Cancel Again?, else click Main Menu " , Toast.LENGTH_LONG);
toast.show();
doubcheck =true;
}
if(tempRes.getCar().equals("Minivan") && doubcheck == true)
{
tempdate = tempRes.getDate();
Cars van = creatRes.getVan();
van.removeDate(tempdate);
creatRes.setVan(van);
creatRes.removeReservation(tempRes);
Transaction temptrans = new Transaction(temp, 3);
creatRes.addTrans(temptrans);
Toast toast = Toast.makeText(this, temptrans.toString(), Toast.LENGTH_LONG);
toast.show();
Intent i = new Intent(this,CarRentalSystemActivity.class);
startActivity(i);
}
if(tempRes.getCar().equals("Minivan") && doubcheck == false)
{
Toast toast = Toast.makeText(this, "Are you Sure? Press Cancel Again?, else click Main Menu " , Toast.LENGTH_LONG);
toast.show();
doubcheck =true;
}
}
j++;
}
}
if(v.getId() == R.id.homeButton)
{
Intent i = new Intent(this,CarRentalSystemActivity.class);
startActivity(i);
}
}
}
| true |
95b16fe2695819daf345fd8f9e469cc8c92a5e2d | Java | CieloSun/spring-boot-demo | /src/main/java/com/example/demo/Controller/HelloController.java | UTF-8 | 774 | 2.0625 | 2 | [] | no_license | package com.example.demo.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping
public class HelloController {
@GetMapping("hello")
public String index(){
return "hello";
}
@GetMapping
public String page(ModelMap modelMap){
modelMap.addAttribute("title","Cielo's Home");
return "index";
}
@GetMapping("errorTest")
@ResponseBody
public String errorTest() throws Exception{
throw new Exception("发生错误!");
}
}
| true |
cbdfb01a93c6253b86c550dd95444c6e31821ace | Java | lengockien2000/ISD.ICT.20201-08-EcoBike | /FinalProject/Construction/EcoBike/src/controller/ViewBikeController.java | UTF-8 | 2,850 | 3.03125 | 3 | [] | no_license | package controller;
import common.exception.ViewBikeException;
import entity.bike.*;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
/**
* This class controls the flow of events in view bike screen
* @author Duong Thi Hue
* @version 1.0
*
*/
public class ViewBikeController extends BaseController {
/**
* count 1 second
* @param amount amount want to count
* @return a hashmap include: hour, minute, second
*/
public HashMap counting(int amount) {
int hour = amount / 3600;
int minute = (amount - hour * 3600) / 60;
int second = amount - hour * 3600 - minute * 60;
if (second < 59) second += 1;
else {
second = 0;
if (minute < 59) minute += 1;
else {
hour += 1;
minute = 0;
}
}
HashMap<String, Integer> time = new HashMap<>();
time.put("hour", hour);
time.put("minute", minute);
time.put("second", second);
time.put("newAmount", amount + 1);
return time;
}
/**
* convert time in localDateTime to second
* @param start
* @return seconds
*/
public int calculateAmountMinutes(LocalDateTime start) {
int hour = (int) ChronoUnit.HOURS.between(start, LocalDateTime.now());
int minute = (int) ChronoUnit.MINUTES.between(start, LocalDateTime.now());
int second = (int) ChronoUnit.SECONDS.between(start, LocalDateTime.now());
return hour * 3600 + minute * 60 + second;
}
/**
* create bike instance base on id and type
* @param id
* @param type
* @return bike
* @throws ViewBikeException
*/
public Bike setBike(int id, String type) throws ViewBikeException {
try {
if (type.equals("Standard electric bike")) {
return new StandardElectricBike().getBikeById(id);
} else if (type.equals("Standard bike")) {
return new StandardBike().getBikeById(id);
} else if (type.equals("Twin bike")) {
return new TwinBike().getBikeById(id);
} else if (type.equals("Electric twin bike")) {
return new TwinElectricBike().getBikeById(id);
}
} catch (ViewBikeException | SQLException e) {
throw new ViewBikeException("Not found Bike");
}
return null;
}
/**
* check bike isRenting
*
* @param id of the bike we want to check
* @return boolean
*/
public boolean bikeIsRenting(int id) {
try {
return new Bike().getRenting(id) == 1;
} catch (SQLException e) {
throw new ViewBikeException("Not found bikeID :" + id + "in DB");
}
}
}
| true |
49bb51b8cc10ed7eb7cf1a3fd632d54dc0b9245f | Java | Dragonstei/Project4Her | /Code/SaatBank/API/src/main/java/nl/hro/stkb/api/WithdrawResponse.java | UTF-8 | 1,272 | 2.140625 | 2 | [] | no_license | package nl.hro.stkb.api;
import org.codehaus.jackson.annotate.JsonProperty;
public class WithdrawResponse {
@JsonProperty
private boolean response;
@JsonProperty
private long newSaldo;
@JsonProperty
private long bedragGepint;
@JsonProperty
private String iban;
@JsonProperty
private int transactieNr;
public void setResponse(boolean response) {
this.response = response;
}
public boolean isResponse() {
return response;
}
public long getNewSaldo() {
return newSaldo;
}
public void setNewSaldo(long newSaldo) {
this.newSaldo = newSaldo;
}
public void setTransactieNr(int transactieNr) {
this.transactieNr = transactieNr;
}
public int getTransactieNr() {
return transactieNr;
}
public void setBedragGepint(long bedragGepint) {
this.bedragGepint = bedragGepint;
}
public long getBedragGepint() {
return bedragGepint;
}
public void setIban(String iban) {
this.iban = iban;
}
public String getIban() {
return iban;
}
@Override
public String toString() {
return super.toString();
}
}
| true |
de3b76a74676df3c5e5b7a50949681c8ef8b93c0 | Java | reo7sp/SBF-Bukkit-Plugin | /src/net/sbfmc/logging/DebugUtils.java | UTF-8 | 2,743 | 2.28125 | 2 | [
"Apache-2.0"
] | permissive | /*
Copyright 2014 Reo_SP
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package net.sbfmc.logging;
import java.util.logging.Level;
import net.sbfmc.def.SBFPlugin;
import net.sbfmc.utils.GeneralUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class DebugUtils {
private static boolean debug = true;
public static void debug(String prefix, String message) {
debug(prefix, message, Level.INFO, debug, debug);
}
public static void debug(String prefix, String message, boolean toConsole) {
debug(prefix, message, Level.INFO, toConsole, debug);
}
public static void debug(String prefix, String message, Level level) {
debug(prefix, message, level, debug, debug);
}
public static void debug(String prefix, String message, Level level, boolean toConsole) {
debug(prefix, message, level, toConsole, debug);
}
public static void debug(String prefix, String message, Level level, boolean toConsole, boolean toAdmins) {
// editing prefix
if (prefix == null) {
prefix = "";
} else if (!prefix.equals("")) {
prefix = "[" + prefix.toUpperCase() + "] ";
}
// sending message to admins
if (toAdmins || level.equals(Level.SEVERE)) {
String sendMessage;
// generating message
ChatColor color;
if (level.equals(Level.WARNING)) {
color = ChatColor.GOLD;
} else if (level.equals(Level.SEVERE)) {
color = ChatColor.DARK_RED;
} else {
color = ChatColor.WHITE;
}
sendMessage = ChatColor.LIGHT_PURPLE + "[DEBUG] " + color + prefix + message;
// sending it
for (Player player : Bukkit.getOnlinePlayers()) {
if (GeneralUtils.checkAuth(player) && player.isOp()) {
player.sendMessage(sendMessage);
}
}
}
// sending message to console
if (toConsole) {
SBFPlugin.getPlugin().getLogger().log(level, prefix + message);
}
// sending message to log
DebugLog.writeToLog(prefix + message, level);
}
public static void debugError(String prefix, String message, Exception err) {
debug(prefix, "Error! " + message + ". " + err, Level.SEVERE, true);
err.printStackTrace();
}
public static boolean isDebug() {
return debug;
}
public static void setDebug(boolean debug) {
DebugUtils.debug = debug;
}
}
| true |
b29fda5c264d544bbd67c8be2ecbc031c20ea836 | Java | wangnaiwen/BabyTest | /src/service/FindPrsByUserIdService.java | UTF-8 | 415 | 2.09375 | 2 | [] | no_license | package service;
import java.util.List;
import dao.PrDAO;
import domain.Pr;
import service.dao.BasePrServiceDAO;
import service.dao.FindPrsByUserIdServiceDAO;
public class FindPrsByUserIdService extends BasePrServiceDAO implements FindPrsByUserIdServiceDAO{
@Override
public List<Pr> findPrsByUserId(int userId, int number) {
PrDAO prDAO = getPrDAO();
return prDAO.findPrsByUserId(userId, number);
}
}
| true |
d2e1775150cf8da4fea2931d14051900f6568a8d | Java | eloksolution/elokdivaz | /AppUsers/src/main/java/in/eloksolutions/divaz/activities/Company.java | UTF-8 | 420 | 1.664063 | 2 | [] | no_license | package in.eloksolutions.divaz.activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import in.eloksolutions.divaz.R;
/**
* Created by welcome on 4/13/2018.
*/
public class Company extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.company_layout);
}
}
| true |
1b1f7499769ceaeb6138497347fcc093c1b1077d | Java | punch2475-cmis/punch2475-apcs-cmis | /THEFINAL/move.java | UTF-8 | 134 | 1.507813 | 2 | [] | no_license | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public interface move
{
public void movement();
}
| true |
dc4c0319e21889fc4cd6c77287adc7d443e90ba6 | Java | Xumpy/vastgoed | /src/main/java/com/xumpy/vastgoed/scrape/era/EraVastgoed.java | UTF-8 | 395 | 2.34375 | 2 | [] | no_license | package com.xumpy.vastgoed.scrape.era;
import com.xumpy.vastgoed.interfaces.Vastgoed;
public class EraVastgoed extends Vastgoed {
@Override
public boolean equals(Object object) {
if (object instanceof Vastgoed){
Vastgoed vastgoed = (Vastgoed) object;
return this.getUniqueName().equals(vastgoed.getUniqueName());
}
return false;
}
}
| true |
7dd6f9f5186b149379e6b4a5ced5366e09cb3e6d | Java | zxia904/learn | /learnnetty/src/main/java/me/zxia/learn/chat/protocol/IMessage.java | UTF-8 | 1,089 | 2.546875 | 3 | [] | no_license | package me.zxia.learn.chat.protocol;
public class IMessage {
private String from;
private String content;
private String to;
private Integer groupId;
public IMessage(String content) {
this.content = content;
}
public IMessage(String from, String to, String content) {
this.from = from;
this.to = to;
this.content = content;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
@Override
public String toString() {
return from+"|"+content;
}
}
| true |
3b1c3e516181e4bee8696372b89927ea699f8032 | Java | gcasasbe7/save-all-the-robots | /app/src/main/java/pis03_2016/savealltherobots/view/viewclass/SimpleClickHandler.java | UTF-8 | 6,931 | 2.359375 | 2 | [] | no_license | package pis03_2016.savealltherobots.view.viewclass;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import pis03_2016.savealltherobots.R;
import pis03_2016.savealltherobots.controller.GamePlayController;
import pis03_2016.savealltherobots.controller.GridAdapter;
import pis03_2016.savealltherobots.model.LevelInventoryCell;
import pis03_2016.savealltherobots.model.LevelSquare;
import pis03_2016.savealltherobots.view.activity.GamePlayActivity;
public abstract class SimpleClickHandler {
/**
* The robot has been selected from the inventory
*/
public static boolean robotSelectedFromInventary = false;
/**
* Instance of adapter
*/
private static GridAdapter adapter;
/**
* Controller instance
*/
private static GamePlayController ctrl = GamePlayController.getInstance();
/**
* Functions instance
*/
private static ViewFunctions func;
/**
* Application activity context
*/
private static Activity context;
/**
* It's the robot type selected
*/
private static String robotSelected = null;
/**
* Add robot to square from inventory
*
* @param view is the current view
*/
private static void addRobotToSquareFromInventory(View view) {
adapter.addRobotToSquare(view, robotSelected);
GamePlayActivity.updateNumRemainingRobots(robotSelected, ViewFunctions.ActionCounterRobots.DECREMENT);
LevelInventoryCell cell = ctrl.getGameData().getCurrentLevel().getInventory().getAtFromClassName(robotSelected);
/**
* Lower opacity if there are no robots of this type
*/
GamePlayActivity.lowerOpactiyCell(cell, robotSelected);
}
/**
* Clean global variables for selection robots.
*/
public static void cleanClipboardVariablesActionClick() {
robotSelected = null;
robotSelectedFromInventary = false;
}
/**
* @return whether some robot is selected.
*/
private static boolean isRobotSelected() {
return robotSelected != null;
}
/**
* @return whether some robot is selected from Inventary.
*/
private static boolean isRobotSelectedFromInventary() {
return robotSelectedFromInventary;
}
/**
* Selects a robot from the inventory clicked a view
*
* @param view view
*/
public static void selectRobotFromInventary(View view) {
LevelInventoryCell cell = ctrl.getGameData().getCurrentLevel().getInventory().getAtFromClassName(view.getTag().toString());
GamePlayActivity.initLightBackgroundInventory();
/**
* Click in inventory when not robot selected from grid.
*/
if (cell.isStillSomeRobots()) {
selectionRobot(view);
}
}
/**
* Actions for selection a robot
*
* @param view is the current view
*/
private static void selectionRobot(View view) {
SoundHandler.playSound(GamePlayActivity.soundClickRobot);
/**
* Light in the selected inventory
*/
int idView = func.getResourceId(ViewFunctions.ROBOT_LIGHT_PREFIX.concat(view.getTag().toString().toLowerCase()), "id");
FrameLayout frame = (FrameLayout) context.findViewById(idView);
frame.setBackgroundResource(R.drawable.bg_inventary_selected);
GamePlayActivity.currentLightBackground = frame;
/**
* Now there robot selected inventory
*/
robotSelected = view.getTag().toString();
robotSelectedFromInventary = true;
}
/**
* InnerClass:: This class represents the action of the simple click
*/
public static class ClickableInventoryRobot implements AdapterView.OnItemClickListener {
/**
* Instance adapter
*/
private GridAdapter adapter;
/**
* ClickableInventoryRobot Constructor
*
* @param context is the app context
* @param adapter is the adpter instance
*/
public ClickableInventoryRobot(Activity context, GridAdapter adapter) {
this.adapter = adapter;
SimpleClickHandler.adapter = adapter;
SimpleClickHandler.func = ViewFunctions.getInstance(context);
SimpleClickHandler.context = context;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/**
* Current square
*/
LevelSquare square = adapter.getViewsAndSquaresMap().get(view);//getItem(position);
ImageView image = (ImageView) view.findViewById(R.id.PictureErrorLayer);
/**
* Has more robots?
*/
boolean hasRobotsRemaining = ctrl.getGameData().getCurrentLevel().getInventory().hasRobotsRemaining();
/**
* Inventory cell robot selected
*/
LevelInventoryCell cell = ctrl.getGameData().getCurrentLevel().getInventory().getAtFromClassName(robotSelected);
/**
* Has more robots of current type?
*/
boolean isStillSomeRobots = false;
if (cell != null) {
isStillSomeRobots = cell.isStillSomeRobots();
}
/**
* Some robot has been selected
*/
if (isRobotSelected() && hasRobotsRemaining) {
/**
* Robot inventory has been selected
*/
if (isRobotSelectedFromInventary()) {
/**
* The square isn't occupied
*/
if (!square.isOccupied() && isStillSomeRobots) {
// add robot to square from intentory
addRobotToSquareFromInventory(view);
// add new value for variable
isStillSomeRobots = cell.isStillSomeRobots();
// We checked the value again
if (!isStillSomeRobots) {
GamePlayActivity.initLightBackgroundInventory();
cleanClipboardVariablesActionClick();
}
/**
* The square is already occupied.
*/
} else {
GamePlayActivity.staticInstance.showSetTimeOutError(image);
}
}
}
}
}
}
| true |
83398f763c5c8895022bbaeafa21d716dc19ba77 | Java | EsraaAbuHana/data-structures-and-algorithms | /Data-Structures/graph/lib/src/main/java/DepthFirst/DepthFirst.java | UTF-8 | 958 | 3.203125 | 3 | [] | no_license | package DepthFirst;
import graph.Edge;
import graph.Graph;
import graph.Vertex;
import stacksandqueues.Node;
import stacksandqueues.Queue;
import stacksandqueues.Stack;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class DepthFirst extends Graph{
public static void main(String[] args) {
}
public ArrayList<Vertex> depthFirst (Vertex vertex) {
ArrayList nodes = new ArrayList<>();
Stack depth = new Stack();
Set visited = new HashSet();
depth.push(vertex);
visited.add(vertex);
while (!depth.isEmpty()) {
Vertex front = (Vertex) ((Node) depth.pop()).getValue();
nodes.add(front.getValue());
for (Object child : this.getNeighbors(front)){
Vertex currentVertex = ((Edge) child).getVertex();
if (!visited.contains(currentVertex)) {
visited.add(currentVertex);
depth.push(currentVertex);
}
}
}
return nodes;
}
}
| true |
018f83938d76eb76ba3b6b6643a4c50afda4bf25 | Java | franklinxkk/sharebasketball | /javaserver/src/main/java/com/bblanqiu/module/mqtt/almq/MqttSSLConfig.java | UTF-8 | 1,525 | 2.375 | 2 | [] | no_license | package com.bblanqiu.module.mqtt.almq;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
public class MqttSSLConfig {
public static SSLSocketFactory initSSLSocket() throws Exception {
InputStream caInput = MqttSSLConfig.class.getResourceAsStream("/cert/intermedia.cer");//new FileInputStream("C:\\Users\\Lenovo\\Desktop\\intermedia.cer");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca = null;
try {
ca = cf.generateCertificate(caInput);
} catch (CertificateException e) {
e.printStackTrace();
} finally {
caInput.close();
}
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext context = SSLContext.getInstance("TLSV1.2");
context.init(null, tmf.getTrustManagers(), null);
SSLSocketFactory socketFactory = context.getSocketFactory();
return socketFactory;
}
}
| true |
ce2705ac65eb6c189053f07c1a2a9fda641819cb | Java | Blazebit/blaze-faces | /blaze-faces-apt/src/main/java/com/blazebit/blazefaces/apt/model/Renderer.java | UTF-8 | 1,752 | 2.640625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package com.blazebit.blazefaces.apt.model;
public class Renderer {
private String type;
private String clazz;
private String componentFamily;
public Renderer() {
}
public Renderer(String type, String clazz, String componentFamily) {
this.type = type;
this.clazz = clazz;
this.componentFamily = componentFamily;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public String getComponentFamily() {
return componentFamily;
}
public void setComponentFamily(String componentFamily) {
this.componentFamily = componentFamily;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((clazz == null) ? 0 : clazz.hashCode());
result = prime * result
+ ((componentFamily == null) ? 0 : componentFamily.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Renderer)) {
return false;
}
Renderer other = (Renderer) obj;
if (clazz == null) {
if (other.clazz != null) {
return false;
}
} else if (!clazz.equals(other.clazz)) {
return false;
}
if (componentFamily == null) {
if (other.componentFamily != null) {
return false;
}
} else if (!componentFamily.equals(other.componentFamily)) {
return false;
}
if (type == null) {
if (other.type != null) {
return false;
}
} else if (!type.equals(other.type)) {
return false;
}
return true;
}
}
| true |
5c783d1ba6696f58d5736a3a50b39074c37da29a | Java | inepex/inechart | /inechart/src/main/java/com/inepex/inechart/chartwidget/misc/ZIndexComparator.java | UTF-8 | 274 | 2.140625 | 2 | [] | no_license | package com.inepex.inechart.chartwidget.misc;
import java.util.Comparator;
public class ZIndexComparator implements Comparator<HasZIndex> {
@Override
public int compare(HasZIndex arg0, HasZIndex arg1) {
return arg0.getZIndex() - arg1.getZIndex();
}
}
| true |
8c47e597d5e97d6fb672c43467b82a000c07b848 | Java | unwin322/TPD | /Framework4/app/src/main/java/com/tpdappframework/mahesh/framework4/PrePunctureOffsetLeft60.java | UTF-8 | 639 | 1.820313 | 2 | [] | no_license | package com.tpdappframework.mahesh.framework4;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/**
* Created by Mahesh on 26/02/2018.
*/
public class PrePunctureOffsetLeft60 extends Calculator_or_Stepbystep_Menu {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pre_puncture_offset_dist_in_left_60);
}
public void goPPInLeftAlign60(View view) {
Intent getPPInLeftAlign60 = new Intent(this, PrePunctureAlignKeyInLeft60.class);
startActivity(getPPInLeftAlign60);
}
}
| true |
aa9fb212c0f879cc992597c565f84f592dbd7097 | Java | FutureGraphics/XtremeEssentials | /src/essentials/future/code/Commands/HealCommand.java | ISO-8859-1 | 2,948 | 2.484375 | 2 | [] | no_license | package essentials.future.code.Commands;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import essentials.future.code.ConfigManager.ApiManager;
import essentials.future.code.ConfigManager.ConfigManager;
import essentials.future.code.main.main;
public class HealCommand implements CommandExecutor{
private main plugin;
public HealCommand(main plugin) {
this.plugin = plugin;
}
public List<Player> healDelay = new ArrayList<>();
@Override
public boolean onCommand(CommandSender sender, Command cmd, String arg2, String[] args) {
if(sender instanceof Player) {
Player player = (Player) sender;
if(player.hasPermission("essentials.heal")) {
if(args.length == 1) {
if(player.hasPermission("essentials.heal.others")) {
try {
Player target = plugin.getServer().getPlayer(args[0]);
ApiManager.healPlayer(target);
target.sendMessage(plugin.prefix +"eDein Leben wurde von c" + player.getName() + " eaufgefllt");
player.sendMessage(plugin.prefix +"eDu hast c" + target.getName() + " eLeben aufgefllt");
} catch(NullPointerException e) {
player.sendMessage(plugin.playerNotFound);
}
} else {
player.sendMessage(plugin.noAccess);
}
} else if(args.length == 0) {
if(healDelay.contains(player)) {
player.sendMessage(plugin.prefix + "eDu kannst dich in c" + ConfigManager.getHealDelay() + "e Sekunden Heilen");
} else {
ApiManager.healPlayer(player);
player.sendMessage(plugin.prefix +"eDu wurdest geheilt");
if(!player.isOp() || !player.hasPermission("essentials.healdelay.bypass")) {
healDelay.add(player);
startScheduler(player);
}
}
} else {
player.sendMessage(plugin.prefix +"c/heal <Spieler>");
}
} else {
player.sendMessage(plugin.noAccess);
}
} else {
if(args.length == 1 ) {
try {
Player target = plugin.getServer().getPlayer(args[0]);
ApiManager.healPlayer(target);
target.sendMessage(plugin.prefix +"eDein Leben wurde von cKonsole eaufgefllt");
sender.sendMessage(plugin.prefix +"eDu hast c" + target.getName() + " eLeben aufgefllt");
} catch(NullPointerException e) {
sender.sendMessage(plugin.playerNotFound);
}
} else {
sender.sendMessage(plugin.prefix +"c/heal <Spieler>");
}
}
return true;
}
public void startScheduler(final Player player) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if(healDelay.contains(player)) {
healDelay.remove(player);
}
}
},20*ConfigManager.getHealDelay());
}
}
| true |
bfb9dd2424ce460bb9b19ab7e0c0eb0de0282666 | Java | Ghazibenslama/SMD-master | /src/org/apromore/service/GraphService.java | UTF-8 | 1,377 | 2.28125 | 2 | [] | no_license | package org.apromore.service;
import org.apromore.dao.model.Content;
import org.apromore.graph.JBPT.CPF;
import java.util.List;
/**
* Interface for the Graphing Service. Defines all the methods that will do the majority of the work for
* the Apromore application.
*
* @author <a href="mailto:cam.james@gmail.com">Cameron James</a>
*/
public interface GraphService {
/**
* Returns the request Content Object
* @param fragmentVersionId the fragment version id
* @return the content corresponding to the fragment id
*/
Content getContent(String fragmentVersionId);
/**
* returns all the Distinct Content Id's from the Vertices.
* @return the list of Id's
*/
List<String> getContentIds();
/**
* Get a processModelGraph
* @param contentID the content id
* @return the process model graph
*/
CPF getGraph(String contentID);
/**
* Fills the ProcessModelGraphs vertices
* @param procModelGraph
* @param contentID
*/
void fillNodes(CPF procModelGraph, String contentID);
/**
* Fills the ProcessModelGraphs Edges
* @param procModelGraph
* @param contentID
*/
void fillEdges(CPF procModelGraph, String contentID);
void fillNodesByFragmentId(CPF procModelGraph, String fragmentID);
void fillEdgesByFragmentId(CPF procModelGraph, String fragmentID);
}
| true |
cc1042e861bc2dc9a87b61b7714c7f276a49d96e | Java | pcalvoa/examples | /AdminWeb/src/com/tid/util/Formatter.java | UTF-8 | 8,462 | 2.703125 | 3 | [] | no_license | package com.tid.util;
import com.tid.Fields;
import com.tid.atica.htc.core.bean.CentroVO;
import com.tid.atica.htc.core.bean.ServicioVO;
import com.tid.atica.htc.core.bean.UserVO;
import com.tid.atica.htc.filtro.consultas.bean.Entidad;
import com.tid.pojo.Client;
import com.tid.pojo.Licenses;
/**
* Format objects as json
*
* @author fdelatorre
*
*/
public class Formatter {
public static String toJSON(Object value, Class type, int count) {
if (type.equals(CentroVO.class)) {
return getJSONCenter(value, count);
}
else if (type.equals(ServicioVO.class)) {
return getJSONService(value, count);
}
else if (type.equals(UserVO.class)) {
return getJSONUser(value, count);
}
else if (type.equals(Client.class)) {
return getJSONClient(value, count);
}
else if (type.equals(Licenses.class)) {
return getJSONLicenses(value, count);
}
return null;
}
public static String getJSONClient(Object client, int count) {
Client value = Client.class.cast(client);
StringBuilder json = new StringBuilder("{");
json.append("\"count\":").append("\"").append(count).append("\"").append(",");
json.append("\"name\":").append("\"").append(value.getName()).append("\"").append(",");
json.append("\"description\":").append("\"").append(value.getDescription()).append("\"");
json.append("}");
return json.toString();
}
public static String getJSONLicenses(Object licenses, int count) {
Licenses value = Licenses.class.cast(licenses);
StringBuilder json = new StringBuilder("{");
json.append("\"count\":").append("\"").append(count).append("\"").append(",");
json.append("\"total\":").append("\"").append(value.getTotalLicenses()).append("\"").append(",");
json.append("\"used\":").append("\"").append(value.getUsedLicenses()).append("\"");
json.append("}");
return json.toString();
}
public static String getJSONCenter(Object center, int count) {
StringBuilder json = new StringBuilder("{");
if (center.getClass().equals(Entidad.class)) {
Entidad value = Entidad.class.cast(center);
json.append("\"count\":").append("\"").append(count).append("\"").append(",");
json.append("\"id\":").append("\"").append(getValue(value,Fields.CENTER_ID)).append("\"").append(",");
json.append("\"name\":").append("\"").append(getValue(value,Fields.CENTER_NAME)).append("\"").append(",");
json.append("\"licenses\":").append("\"").append(getValue(value,Fields.LICENSES)).append("\"").append(",");
json.append("\"description\":").append("\"").append(getValue(value,Fields.CENTER_DESCRIPTION)).append("\"");
}
else if (center.getClass().equals(CentroVO.class)) {
CentroVO value = CentroVO.class.cast(center);
json.append("\"count\":").append("\"").append(count).append("\"").append(",");
json.append("\"id\":").append("\"").append(value.getIdCentro()).append("\"").append(",");
json.append("\"name\":").append("\"").append(value.getNombre()).append("\"").append(",");
json.append("\"licenses\":").append("\"").append(value.getLicencias()).append("\"").append(",");
json.append("\"description\":").append("\"").append(value.getDescripcion()).append("\"");
}
json.append("}");
return json.toString();
}
public static String getJSONService(Object service, int count) {
StringBuilder json = new StringBuilder("{");
if (service.getClass().equals(Entidad.class)) {
Entidad value = Entidad.class.cast(service);
json.append("\"count\":").append("\"").append(count).append("\"").append(",");
json.append("\"id\":").append("\"").append(getValue(value,Fields.SERVICE_ID)).append("\"").append(",");
json.append("\"centerid\":").append("\"").append(getValue(value,Fields.CENTER_ID)).append("\"").append(",");
json.append("\"centername\":").append("\"").append(getValue(value,Fields.CENTER_NAME)).append("\"").append(",");
json.append("\"name\":").append("\"").append(getValue(value,Fields.SERVICE_NAME)).append("\"").append(",");
json.append("\"licenses\":").append("\"").append(getValue(value,Fields.LICENSES)).append("\"").append(",");
json.append("\"description\":").append("\"").append(getValue(value,Fields.SERVICE_DESCRIPTION)).append("\"");
}
else if (service.getClass().equals(ServicioVO.class)) {
ServicioVO value = ServicioVO.class.cast(service);
json.append("\"count\":").append("\"").append(count).append("\"").append(",");
json.append("\"id\":").append("\"").append(value.getIdServicio()).append("\"").append(",");
json.append("\"centerid\":").append("\"").append(value.getCentro().getIdCentro()).append("\"").append(",");
json.append("\"centername\":").append("\"").append(value.getCentro().getNombre()).append("\"").append(",");
json.append("\"name\":").append("\"").append(value.getNombre()).append("\"").append(",");
json.append("\"licenses\":").append("\"").append(value.getLicencias()).append("\"").append(",");
json.append("\"description\":").append("\"").append(value.getDescripcion()).append("\"");
}
json.append("}");
return json.toString();
}
public static String getJSONUser(Object user, int count) {
Entidad value = Entidad.class.cast(user);
StringBuilder json = new StringBuilder("{");
json.append("\"count\":").append("\"").append(count).append("\"").append(",");
json.append("\"id\":").append("\"").append(getValue(value,Fields.USER_ID).toString()).append("\"").append(",");
json.append("\"user\":").append("\"").append(getValue(value,Fields.USER_USER).toString()).append("\"").append(",");
json.append("\"name\":").append("\"").append(getValue(value,Fields.USER_NAME).toString()).append("\"").append(",");
json.append("\"surname\":").append("\"").append(getValue(value,Fields.USER_SURNAME).toString()).append("\"").append(",");
json.append("\"password\":").append("\"").append(getValue(value,Fields.USER_PASSWORD).toString()).append("\"").append(",");
json.append("\"email\":").append("\"").append(getValue(value,Fields.USER_EMAIL).toString()).append("\"").append(",");
json.append("\"emailname\":").append("\"").append(getValue(value,Fields.USER_EMAIL_USER).toString()).append("\"").append(",");
json.append("\"emailpassword\":").append("\"").append(getValue(value,Fields.USER_EMAIL_PASSWORD).toString()).append("\"").append(",");
json.append("\"phone\":").append("\"").append(getValue(value,Fields.USER_PHONE).toString()).append("\"").append(",");
json.append("\"mobile\":").append("\"").append(getValue(value,Fields.USER_MOBILE).toString()).append("\"").append(",");
json.append("\"observations\":").append("\"").append(getValue(value,Fields.USER_OBSERVATIONS).toString()).append("\"").append(",");
json.append("\"profile\":").append("\"").append(getValue(value,Fields.PROFILE_ID).toString()).append("\"").append(",");
json.append("\"profilename\":").append("\"").append(getValue(value,Fields.PROFILE_NAME).toString()).append("\"").append(",");
json.append("\"serviceid\":").append("\"").append(getValue(value,Fields.SERVICE_ID).toString()).append("\"").append(",");
json.append("\"servicename\":").append("\"").append(getValue(value,Fields.SERVICE_NAME).toString()).append("\"").append(",");
json.append("\"centername\":").append("\"").append(getValue(value,Fields.CENTER_NAME).toString()).append("\"").append(",");
json.append("\"centerid\":").append("\"").append(getValue(value,Fields.CENTER_ID).toString()).append("\"").append(",");
json.append("\"recoverycode\":").append("\"").append(getValue(value,Fields.USER_RECOVERY_CODE).toString()).append("\"").append(",");
json.append("\"expirationdate\":").append("\"").append(getValue(value,Fields.USER_RECOVERY_EXPIRATION_DATE).toString()).append("\"").append(",");
json.append("\"securityquestion\":").append("\"").append(getValue(value,Fields.USER_SECURITY_QUESTION).toString()).append("\"").append(",");
json.append("\"securityanswer\":").append("\"").append(getValue(value,Fields.USER_SECURITY_ANSWER).toString()).append("\"");
json.append("}");
return json.toString();
}
private static String getValue(Entidad value, String field) {
String result = "";
try {
result = value.getAtributos().get(field).toString();
}
catch(Exception e) {
}
return result;
}
}
| true |
c2f7df522eda310322137094f4c6f8eb0f33db92 | Java | Javidp/BackendStack | /auth/src/main/java/com/jd/backend/auth/AuthConfiguration.java | UTF-8 | 710 | 1.945313 | 2 | [] | no_license | package com.jd.backend.auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AuthConfiguration {
@Value("${auth.jwt.token.key.path}")
private String jwtTokenKeyPath;
@Value("${auth.jwt.token.key.password}")
private String jwtTokenKeyPassword;
@Value("${auth.jwt.token.key.alias}")
private String jwtTokenKeyAlias;
public String getJwtTokenKeyPath() {
return jwtTokenKeyPath;
}
public char[] getJwtTokenKeyPassword() {
return jwtTokenKeyPassword.toCharArray();
}
public String getJwtTokenKeyAlias() {
return jwtTokenKeyAlias;
}
}
| true |
4f73d46e5a017163607e796ec45c117e0a2535e5 | Java | RyanTech/12306-Android-Decompile | /12306/src/org/codehaus/jackson/map/ResolvableSerializer.java | UTF-8 | 196 | 1.507813 | 2 | [] | no_license | package org.codehaus.jackson.map;
public abstract interface ResolvableSerializer
{
public abstract void resolve(SerializerProvider paramSerializerProvider)
throws JsonMappingException;
}
| true |
4c0614943fae542ce4de93ae7c73042062e9b75f | Java | jboxx/design-pattern | /src/io/jboxx/designpattern/proxypattern/ImplementationProxyPattern.java | UTF-8 | 256 | 2.234375 | 2 | [] | no_license | package io.jboxx.designpattern.proxypattern;
public class ImplementationProxyPattern {
public static void main(String[] args) {
LazySubjectProxy lazySubjectProxy = new LazySubjectProxy("bla bla");
lazySubjectProxy.request();
}
}
| true |
51cbc4a5bf46a4fedd0cb2110d9a49035b8f55c4 | Java | DevaCharwaka/Trainee-Management-System | /TraineeManagementSystem/src/main/java/com/dao/TraineeMgmtIDao.java | UTF-8 | 302 | 1.945313 | 2 | [] | no_license | package com.dao;
import java.util.ArrayList;
import com.model.Trainee;
public interface TraineeMgmtIDao {
int addTrainee(Trainee trainee );
int modifyTrainee(Trainee trainee);
int deleteTrainee(int tId);
Trainee retriveById(int tId);
ArrayList<Trainee> retriveAll();
}
| true |
e1ffc934be73d61c565bdc752bd65dee32d73924 | Java | plawler92/State-Paradigm | /Transition2.java | UTF-8 | 620 | 2.703125 | 3 | [] | no_license | public class Transition2 extends State{
private static Transition2 instance = null;
private Transition2(){
}
public static Transition2 getInstance(){
if(instance == null){
instance = new Transition2();
}
return instance;
}
public void read(Context c, String s){
if(s.equals("*")){
c.addJavadoc();
c.addJavadoc();
c.addJavadoc();
c.changeState(Javadoc.getInstance());
}
else{
c.addComment();
c.addComment();
c.addComment();
c.changeState(MultiComment.getInstance());
}
}
}
| true |
a1efc7158e9cc80608154e309e05666485579e06 | Java | timeazsk/my-pharma-app | /src/com/pharmacy/menu/MainAppMenu.java | UTF-8 | 3,416 | 2.53125 | 3 | [] | no_license | package com.pharmacy.menu;
import com.training.sedinta09.multilanguage.Language;
import com.training.sedinta09.multilanguage.MultilanguageImpl;
import com.training.sedinta10.menus.Menu;
import com.training.sedinta10.menus.MenuAction;
import com.training.sedinta10.menus.MenuItem;
import com.training.sedinta10.menus.SerializableMenuAction;
public class MainAppMenu {
public void showMenu() {
Menu mainMenu = new Menu("", "");
Menu back = new Menu("0", "/back");
// 1.addMed------------------------------------------------------------------------------
MenuAction addMed = new SerializableMenuAction("1", "/addmed", new AddMedicineAction());
// 2.addStock---------------------------------------------------------------------------
MenuAction addStock = new SerializableMenuAction("2", "/addstoc", new AddStockAction());
// 3.search--------------------------------------------------------------
MenuAction search = new MenuAction("3", "/searchMed", new SearchMedicineAction());
// 4.sell------------------------------------------------------------------
MenuAction sell = new SerializableMenuAction("4", "/sell", new SellMedicineAction());
// 5.inventory--------------------------------------------------------------
MenuAction inventory = new SerializableMenuAction("5", "/inventory", new InventoryAction());
// 6.orderstock-------------------------------------------------------
MenuAction orderStock = new SerializableMenuAction("6", "/order", new OrderStockAction());
// 7.stockhistory------------------------------------------------------
MenuAction stockHistory = new MenuAction("7", "/history", new ViewStockAdjustmentsAction());
// 8.viewstock----------------------------------------------------------
Menu viewStock = new Menu("8", "/view");
MenuAction complete = new MenuAction("1", "/complete", new ViewCompleteStockAction());
MenuAction drawer = new MenuAction("2", "/drawer", new ViewDrawerStockAction());
viewStock.addSubMenu(complete);
viewStock.addSubMenu(drawer);
viewStock.addSubMenu(back);
viewStock.setBackAction(back);
// 9.settings--------------------------------------------------------
Menu settings = new Menu("9", "/settings");
Menu changeLang = new Menu("1", "/chlang");
settings.addSubMenu(changeLang);
settings.addSubMenu(back);
settings.setBackAction(back);
MenuItem en = new MenuItem("1", "/en") {
@Override
public void doAction() {
MultilanguageImpl.getInstance().setLanguage(Language.EN);
}
};
MenuItem ro = new MenuItem("2", "/ro") {
@Override
public void doAction() {
MultilanguageImpl.getInstance().setLanguage(Language.RO);
}
};
changeLang.addSubMenu(en);
changeLang.addSubMenu(ro);
changeLang.addSubMenu(back);
changeLang.setBackAction(back);
// ---------------------------------------------------------------------
Menu exit = new Menu("0", "/exit");
mainMenu.addSubMenu(addMed);
mainMenu.addSubMenu(addStock);
mainMenu.addSubMenu(search);
mainMenu.addSubMenu(sell);
mainMenu.addSubMenu(inventory);
mainMenu.addSubMenu(orderStock);
mainMenu.addSubMenu(stockHistory);
mainMenu.addSubMenu(viewStock);
mainMenu.addSubMenu(settings);
mainMenu.addSubMenu(exit);
mainMenu.setBackAction(exit);
mainMenu.doAction();
}
}
| true |
0f54ddcf2ad48f4501ea503ae63467789c0a2907 | Java | catchrajatahuja/UVACP | /src/RoboLand.java | UTF-8 | 2,592 | 3.234375 | 3 | [] | no_license | import java.io.*;
import java.util.*;
/**
* Created by RaviG on 11/9/2014.
*/
public class RoboLand {
public static void main(String[] args) {
Reader in = new Reader();
int n,m,s,cc;
DIR curr=null;
char fild[][],dr;
//String ttt = "*#."
while (true) {
n = in.nextInt();
m = in.nextInt();
s = in.nextInt();
if(n+m+s==0) break;
int x,y,sx=0,sy=0;
fild = new char[n][m];
for (int i = 0; i < n; i++) {
fild[i] = in.nextString().toCharArray();
for (int j = 0; j < m; j++) {
if(fild[i][j]!='*' && fild[i][j]!='.' && fild[i][j]!='#'){
sx = i; sy = j;
curr = getDir(fild[i][j]);
}
}
}
cc=0;
char direction[] = in.nextString().toCharArray();
int nx,ny;
for (char dd : direction){
switch (dd){
case 'D':
curr = curr.turn(1);
break;
case 'E':
curr = curr.turn(0);
break;
case 'F':
nx = sx +curr.x; ny = sy +curr.y;
if(nx<0 || ny<0 || nx>=n ||ny>=m || fild[nx][ny]=='#') break;
if(fild[nx][ny]=='*'){ cc++; fild[nx][ny]='.';}
sx = nx; sy = ny;
break;
}
}
System.out.println(cc);
}//End of While
}
public static DIR getDir(char c){
switch (c){
case 'N':
return DIR.N;
case 'S':
return DIR.S;
case 'L':
return DIR.L;
case 'O':
return DIR.O;
}
return null;
}
}
enum DIR{
N (-1,0), S(1,0) , L(0,1) , O(0,-1);
public final int x,y;
DIR(int x,int y){
this.x = x;
this.y = y;
}
public DIR turn(int d){
switch (this){
case N:
if(d==0)return DIR.O;
else return DIR.L;
case S:
if(d==0)return DIR.L;
else return DIR.O;
case L:
if(d==0)return DIR.N;
else return DIR.S;
case O:
if(d==0)return DIR.S;
else return DIR.N;
}
return null;
}
} | true |
43ed17bb963703143897d62b425c79aa9173f4f6 | Java | nowhiek/javatr | /Day2ProjectConsoleShamkolovichEG/src/by/javatr/task3/runner/Main.java | UTF-8 | 705 | 2.828125 | 3 | [] | no_license | package by.javatr.task3.runner;
import by.javatr.task3.util.ArrayException;
import by.javatr.task3.util.ArrayOperation;
import by.javatr.task3.util.validator.ValidatorLengthArray;
public class Main {
public static void main(String[] args) {
try{
new ValidatorLengthArray().validate(args);
int[] array = new int[args.length];
ArrayOperation.randomFillArray(array);
for (int value : array) {
System.out.print(value + "\n");
}
for (int value : array) {
System.out.print(value + "\t");
}
}catch (ArrayException e){
e.printStackTrace();
}
}
}
| true |
cff7ff26194cbc6f8bd4ab87803b8469c34a1e44 | Java | bohdanvan/movie-theater | /src/main/java/com/bvan/movietheater/entity/Movie.java | UTF-8 | 1,861 | 2.671875 | 3 | [] | no_license | package com.bvan.movietheater.entity;
import static javax.persistence.GenerationType.SEQUENCE;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
@Entity
@Getter
@Setter
@Accessors(chain = true)
@NoArgsConstructor
public class Movie {
@Id
@GeneratedValue(strategy = SEQUENCE, generator = "movie_seq")
private Long id;
@Column
private String title;
@Column
private LocalDate releaseDate;
@ElementCollection(targetClass = Genre.class, fetch = FetchType.EAGER)
@JoinTable(name = "movie_genre", joinColumns = @JoinColumn(name = "movie_id"))
@Column(name = "genre", nullable = false)
@Enumerated(EnumType.STRING)
private List<Genre> genres;
public Movie(String title, LocalDate releaseDate, List<Genre> genres) {
this.title = title;
this.releaseDate = releaseDate;
this.genres = genres;
}
public String getInfo() {
return "Movie '" + title + "' will be shown on " + releaseDate;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Movie)) {
return false;
}
Movie movie = (Movie) o;
return Objects.equals(getTitle(), movie.getTitle());
}
@Override
public int hashCode() {
return Objects.hash(getTitle());
}
}
| true |
b9fb3867b788c08defdf66ccbb64c36e19eb52eb | Java | waldos200/clases-java | /Unidad4/Fiest1.java | UTF-8 | 575 | 3.296875 | 3 | [] | no_license | class Fiesta
{
int numeroP;
String TipoFies;
public Fiesta(){}
private Fiesta(int nP, String TF)// constructor privado
{
numeroP= nP;
TipoFies =TF;
System.out.println("#invitados "+numeroP+"Tipo de fiesta "+TipoFies);
}
void Fie(int nP,String TP) // con este método invoca al constructor privado
{
Fiesta p= new Fiesta(10,"rosa2");
numeroP =nP;
TipoFies = TP;
System.out.println("#invitados "+numeroP+"Tipo de fiesta "+TipoFies);
}
}
class Fiest1
{
public static void main(String a[])
{
Fiesta l= new Fiesta();
l.Fie(300,"fiesta Rosa");
}
} | true |
1b6a4c94c288760893144b6c82f0fe9b925d23ab | Java | chenqian1998/javaProgram | /src/main/java/Leetcode/左的课堂练习/sort/quickSort.java | UTF-8 | 1,163 | 3.265625 | 3 | [] | no_license | package Leetcode.左的课堂练习.sort;
import org.junit.Test;
import java.util.Arrays;
/**
* @author Itsuka
* @version 1.0
* @date 2020/5/15
* @description
*/
public class quickSort {
public int partition(int[] arr, int start, int end) {
int pivot_val = arr[start];
int i = start, j = end;
while (i < j) {
while (i<j && arr[j] >= pivot_val){
j -= 1;
}
// 这里其实是赋值而不是交换
arr[i] = arr[j];
while (i<j && arr[i] <= pivot_val){
i+= 1;
}
arr[j] = arr[i];
}
arr[i] = pivot_val;
//System.out.println(Arrays.toString(arr));
return i;
}
public void sortProcess(int[] arr, int start, int end){
if (start < end){
int index = partition(arr, start, end);
sortProcess(arr,start,index-1);
sortProcess(arr, index+1, end);
}
}
@Test
public void test01(){
int[] arr = {5,2,1,4,3,0,1,1,1};
sortProcess(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
}
| true |
78fed6c98c284e278bcb6caf0b2d1939a19bdde3 | Java | ryannetwork/Scratchpad | /Spark/new-york-taxis/src/main/java/org/gb/sample/spark/nytaxitrips/TripStatsPerTimeBandBdcstMain.java | UTF-8 | 305 | 1.578125 | 2 | [] | no_license | package org.gb.sample.spark.nytaxitrips;
public class TripStatsPerTimeBandBdcstMain {
public static void main(String[] args) {
String taxiTripFile = args[0];
TripStatsPerTimeBandLister statsLister = TripStatsPerTimeBandLister.getInstance();
statsLister.collectTripStats(taxiTripFile, true);
}
}
| true |
562b5a8f876c2ca0356959dd91265e421e051769 | Java | xinstall/Xinstall-Unity-SDK | /AndroidSample/XUnityActivity.java | UTF-8 | 952 | 1.820313 | 2 | [] | no_license | package com.shubao.xinstallunitysdk;
import android.content.Intent;
import android.os.Bundle;
import com.unity3d.player.UnityPlayerActivity;
import com.xinstall.XInstall;
public class XUnityActivity extends UnityPlayerActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
XInstall.getWakeUpParam(getIntent(), wakeupCallback);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
XInstall.getWakeUpParam(intent, wakeupCallback);
}
// satrt ------------ 选写 当 用户有使用应用宝的时候可以加上这段代码
@Override
protected void onResume() {
super.onResume();
XInstall.getYybWakeUpParam(this,getIntent(),wakeupCallback);
}
// end -----------------------------------------------------
XWakeUpCallback wakeupCallback = new XWakeUpCallback();
} | true |
f13aa1bac2b612501ef10378b8343051601fc599 | Java | cocolove2/shiro-uaa | /auth-server/src/main/java/com/github/xfslove/shiro/uaa/endpoint/UaaLogoutEndpoint.java | UTF-8 | 3,317 | 2.109375 | 2 | [
"Apache-2.0"
] | permissive | package com.github.xfslove.shiro.uaa.endpoint;
import com.github.xfslove.shiro.uaa.model.AccessClient;
import com.github.xfslove.shiro.uaa.model.AccessToken;
import com.github.xfslove.shiro.uaa.model.Constants;
import com.github.xfslove.shiro.uaa.service.AccessClientService;
import com.github.xfslove.shiro.uaa.service.AccessTokenService;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* Created by hanwen on 2017/10/19.
*/
@RequestMapping(Constants.SERVER_LOGOUT_PATH)
public class UaaLogoutEndpoint {
private static final Logger LOGGER = LoggerFactory.getLogger(UaaLogoutEndpoint.class);
private AccessClientService accessClientService;
private AccessTokenService accessTokenService;
@RequestMapping(value = "", method = RequestMethod.GET)
public void logout(
@RequestParam(OAuth.OAUTH_CLIENT_ID) String clientId,
@RequestParam(OAuth.OAUTH_REDIRECT_URI) String redirectURL,
HttpServletResponse response
) throws OAuthSystemException, IOException {
try {
AccessClient accessClient = accessClientService.getByClient(clientId);
if (accessClient == null) {
throw OAuthProblemException.error(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT, "client invalid");
}
if (!accessClient.isEnabled()) {
throw OAuthProblemException.error(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT, "client disabled");
}
Subject subject = SecurityUtils.getSubject();
if (!subject.isAuthenticated()) {
response.sendRedirect(redirectURL);
return;
}
List<AccessToken> tokens = accessTokenService.getBySession((String) subject.getSession(false).getId());
for (AccessToken token : tokens) {
accessTokenService.remove(token.getAccessToken());
}
String username = (String) subject.getPrincipals().getPrimaryPrincipal();
subject.logout();
LOGGER.info("UAA SERVER INFO : {} logout success from server, issued client_id:[{}]", username, clientId);
response.sendRedirect(redirectURL);
} catch (OAuthProblemException ex) {
OAuthResponse resp = OAuthASResponse
.errorResponse(HttpServletResponse.SC_FOUND)
.error(ex)
.location(redirectURL)
.buildQueryMessage();
response.sendRedirect(resp.getLocationUri());
}
}
public void setAccessClientService(AccessClientService accessClientService) {
this.accessClientService = accessClientService;
}
public void setAccessTokenService(AccessTokenService accessTokenService) {
this.accessTokenService = accessTokenService;
}
}
| true |
e7d1d29578e8784f7c6cc7a22a5639bf85979a90 | Java | aseker00/tlp | /tlp-core/src/aseker00/tlp/ling/Lemma.java | UTF-8 | 610 | 2.84375 | 3 | [] | no_license | package aseker00.tlp.ling;
import java.util.Set;
public class Lemma implements Element {
public static final String type = "LEMMA";
private Lexeme value;
private Set<Token> words;
@Override
public String type() {
return Lemma.type;
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (!(other instanceof Lemma))
return false;
Lemma that = (Lemma)other;
return this.value.equals(that.value);
}
@Override
public int hashCode() {
return this.value.hashCode();
}
@Override
public String toString() {
return this.value.toString();
}
} | true |
4134e33bcffb2cbe618cc41615731521ce865533 | Java | pvilyou/Java | /LeanJavaAWT/src/Bai_001/ExAWT_001.java | UTF-8 | 682 | 3.265625 | 3 | [] | no_license | package Bai_001;
import java.awt.Button; // cai nut
import java.awt.Frame; // khung
public class ExAWT_001 extends Frame { // ke thua
public ExAWT_001() {
setTitle("Vi du 1 AWT trong java"); // tieu de
Button b = new Button("Click me"); // tao the hien cua Button (cai nut)
b.setBounds(100, 130, 80, 30); // cai dat vi tri cua Button (cai nut)
add(b); // them cai nut vao khung
setSize(300, 300); // kich thuoc frame voi width (rong) = 300 va height (dai) = 300
setLayout(null); // khong trinh quan ly layout (bo tri)
setVisible(true); // hien thi frame
}
public static void main(String[] args) {
new ExAWT_001();
}
}
| true |
39e2e9f7f2df532480ca0d11081fc3686037c8a4 | Java | smandla/CS371ThreadsLabStarter-master-2 | /app/src/main/java/edu/up/cs301threadslab/ThreadSubclass.java | UTF-8 | 526 | 2.75 | 3 | [] | no_license | package edu.up.cs301threadslab;
import android.util.Log;
public class ThreadSubclass extends Thread {
AnimationView animationView;
public ThreadSubclass(AnimationView animationView){
this.animationView = animationView;
}
@Override
public void run(){
try{
while (true) {
animationView.postInvalidate();
Thread.sleep(50);
}
} catch (Exception e){
Log.e("ThreadSubclass", "run: Invalidate", e);
}
}
}
| true |
29d6a94f8f6da1dce1e025af25a81c038b8072c0 | Java | viiup/FlockWebApp | /src/main/java/com/viiup/web/flock/models/GroupUserModel.java | UTF-8 | 2,512 | 2.078125 | 2 | [] | no_license | package com.viiup.web.flock.models;
import java.util.Date;
/**
* Created by AbdullahMoyeen on 1/31/16.
*/
public class GroupUserModel {
private int groupUserId;
private String createUser;
private Date createDate;
private String updateUser;
private Date updateDate;
private int groupId;
private int userId;
private String groupMembershipStatus;
private boolean isGroupAdmin;
private String firstName;
private String lastName;
private String emailAddress;
public int getGroupUserId() {
return groupUserId;
}
public void setGroupUserId(int groupUserId) {
this.groupUserId = groupUserId;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getUpdateUser() {
return updateUser;
}
public void setUpdateUser(String updateUser) {
this.updateUser = updateUser;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getGroupMembershipStatus() {
return groupMembershipStatus;
}
public void setGroupMembershipStatus(String groupMembershipStatus) {
this.groupMembershipStatus = groupMembershipStatus;
}
public boolean getIsGroupAdmin() {
return isGroupAdmin;
}
public void setIsGroupAdmin(boolean isGroupAdmin) {
this.isGroupAdmin = isGroupAdmin;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
} | true |
91dbf75a09b016ad41e99ac81be2bff3d6bcf653 | Java | mccalv/smartmove | /src/main/java/com/closertag/smartmove/server/content/persistence/filter/SearchFilterCriteriaBuilder.java | UTF-8 | 9,273 | 2.0625 | 2 | [] | no_license | /* Wimove project, 2009.
* Java restful server to erogate GPS contents to multiple devices. All rights reserved
* 17 Dec 2009
* mccalv
* SearchFilterCriteriaBuilder
*
*/
package com.closertag.smartmove.server.content.persistence.filter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinFragment;
import org.hibernatespatial.criterion.SpatialRestrictions;
import com.closertag.smartmove.server.content.domain.GpsPosition;
import com.closertag.smartmove.server.content.domain.Item;
import com.closertag.smartmove.server.content.domain.LocalizedItem;
import com.closertag.smartmove.server.content.domain.LocalizedItem.Label;
import com.closertag.smartmove.server.content.persistence.hibernate.DistanceOrder;
import com.closertag.smartmove.server.content.persistence.hibernate.DistanceRestriction;
import com.vividsolutions.jts.geom.Point;
/**
* An Hibernate Criteria Builder from a {@link SearchFilter}
*
* @author mccalv
*
*/
@SuppressWarnings("rawtypes")
public class SearchFilterCriteriaBuilder {
private static final String GPS_POSITIONS_ALIAS = "gpsPositions";
/**
* Builds the HibernateCriteria from a SearchFilter. Don't apply projections
* to this list, since they are cleaned in this method call
*
* TODO: Remove unused filters
*
* @param searchFilter
* @return
*/
/*
* String query = "select cat.name, count(image) " +
* "from Category cat, Image image " + "join cat.collection.items item " +
* "where item = image.item " + "group by cat.name";
*/
@SuppressWarnings("unchecked")
public static List<Item> buildContentCriteria(Criteria criteria,
SearchFilter searchFilter) {
criteria.createAlias("localizedItems", "localizedItems",
JoinFragment.INNER_JOIN);
criteria.add(Restrictions.and(Restrictions.eq(
"localizedItems.locale", searchFilter.getLocale()), Restrictions.eq(
"localizedItems.label", LocalizedItem.Label.Title)));
// criteria.createAlias("localizedItems",
// "description",Criteria.INNER_JOIN);
/*
* criteria.add(Restrictions.and(Restrictions.eq(
* "localizedItems.locale",searchFilter.getLocale()), Restrictions.eq(
* "localizedItems.label",LocalizedItem.Label.Description.name()) ));
*/
criteria.createAlias("gpsPositions", GPS_POSITIONS_ALIAS,
JoinFragment.INNER_JOIN);
if (searchFilter.getCategory() != null) {
criteria.createAlias("category", "category").add(
Restrictions.eq("category.category", searchFilter
.getCategory().getCategory()));
}
if (searchFilter.getCategory() == null) {
criteria.createAlias("category", "category")
.add(Restrictions.not(
// replace "id" below with property name, depending on what you're
// filtering against
Restrictions.in("category.category", new String[] {
"HOT_SPOT", "BUS_STOP" })));
// Restrictions.ne("category.category", "HOT_SPOT"));
}
if (searchFilter.getRadius() != null && searchFilter.getPoint() != null) {
criteria.add(new DistanceRestriction(searchFilter.getPoint(),
GPS_POSITIONS_ALIAS, searchFilter.getRadius()));
}
if (searchFilter.getPolygon() != null) {
criteria.add(SpatialRestrictions.within("gpsPositions.geom_point",
searchFilter.getPolygon()));
}
if (searchFilter.getText() != null) {
criteria.add(Restrictions.ilike("localizedItems" + ".value", "%"
+ searchFilter.getText() + "%"));
}
if (searchFilter.getGidIdentifier() != null) {
criteria.createAlias("gid", "gid", JoinFragment.INNER_JOIN).add(
Restrictions.in(
"gid.identifier",
Arrays.asList(StringUtils.split(
searchFilter.getGidIdentifier(), ","))));
}
if (searchFilter.getTags() != null) {
criteria.createAlias("tags", "tags").add(
Restrictions.in("tags.tag",
Arrays.asList(searchFilter.getTags())));
}
if (searchFilter.getListIdentifier() != null) {
criteria.createAlias("itemList", "itemList").add(
Restrictions.eq("itemList.name",
searchFilter.getListIdentifier()));
}
if (searchFilter.getStartDate() != null) {
criteria.createAlias("timeOccurrences", "timeOccurrences",
JoinFragment.INNER_JOIN).add(
Restrictions.and(Restrictions.ge(
"timeOccurrences.startDate", searchFilter
.getStartDate()), Restrictions.le(
"timeOccurrences.endDate", searchFilter.getEndDate())));
// Needed b.o. left join
}
/*
* if (searchFilter.getStartDate() == null && searchFilter.getEndDate()
* == null) {
*
* // This in case the item doesn't have a starting date
* criteria.createAlias("timeOccurrences", "timeOccurrences",
* Criteria.INNER_JOIN).add( Restrictions.or(Restrictions
* .isNull("timeOccurrences.startDate"),Restrictions.or(Restrictions
* .isNotNull("timeOccurrences.startDate"), Restrictions
* .le("timeOccurrences.endDate", new Date())))); // A left ojoin is
* needed here
*
* }
*/
Point isPointSelected = null;
if (searchFilter.getOrderBy() != null) {
switch (searchFilter.getOrderBy()) {
case CREATION_DATA: {
criteria.addOrder(Order.desc("creationDate"));
break;
}
case UPDATE_DATA: {
criteria.addOrder(Order.desc("updateDate"));
break;
}
case PROXIMITY: {
criteria.addOrder(new DistanceOrder(searchFilter.getPoint(),
true, GPS_POSITIONS_ALIAS));
isPointSelected = searchFilter.getPoint();
break;
}
case TITLE: {
// criteria.createAlias("localizedItems", "localizedItems");
// criteria.addOrder(Order.asc("localizedItems" + ".locale"));
// criteria.addOrder(Order.desc("localizedItems" + ".label"));
criteria.addOrder(Order.asc("localizedItems" + ".value"));
// criteria.add(Projections.groupProperty("itemId"));
break;
}
}
}
if (searchFilter.getPoint() != null) {
criteria.addOrder(new DistanceOrder(searchFilter.getPoint(), true,
GPS_POSITIONS_ALIAS));
isPointSelected = searchFilter.getPoint();
}
/*
* In this case it goes to by the centroid
*/
/*
* if (searchFilter.getPolygon() != null) { criteria.addOrder(new
* DistanceOrder(searchFilter.getPolygon() .getCentroid(), true,
* GPS_POSITIONS_ALIAS)); isPointSelected =
* searchFilter.getPolygon().getCentroid(); }
*/
if (searchFilter.getLimit() == null) {
criteria.setMaxResults(com.closertag.smartmove.server.constant.Constants.MAX_RESULT_PER_PAGE);
} else {
criteria.setMaxResults(searchFilter.getLimit());
}
if (searchFilter.getStart() != null) {
criteria.setFirstResult(searchFilter.getStart());
}
ProjectionList proList = Projections.projectionList();
proList.add(Projections.distinct(Projections.property("itemId")));
proList.add(Projections.property("itemId"), "itemId");
// proList.add(Projections.property("category"), "category");
// proList.add(Projections.property("website"));
proList.add(Projections.property("localizedItems.value"), "title");
proList.add(Projections.property(GPS_POSITIONS_ALIAS + ".latitude"),
"lat");
proList.add(Projections.property(GPS_POSITIONS_ALIAS + ".longitude"),
"lon");
proList.add(Projections.property(GPS_POSITIONS_ALIAS + ".address"),
"address");
proList.add(Projections.property(GPS_POSITIONS_ALIAS + ".geom_point"),
"address");
/*
* if (isPointSelected != null) { proList.add(new
* DistanceProjection(isPointSelected, GPS_POSITIONS_ALIAS +
* ".geom_point")); }
*/
// proList.add(Projections.property("itemId"), "itemId");
// proList.add(Projections.alias("category"),"category");
// proList.add(Projections.property("timeOccurrences"),
// "timeOccurrences");
// proList.add(Projections.property("gpsPositions"), "gpsPositions");
// proList.add(Projections.property("localizedItems"),
// "localizedItems");
// proList.add(Projections.groupProperty("id"));
criteria.setProjection(proList);
// criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
// criteria
// .setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
criteria.setCacheable(true);
// criteria.setC
List list = criteria.list();
if (list != null) {
List<Object[]> results = list;
List<Item> items = new ArrayList<Item>();
for (Object[] row : results) {
Item itemDetached = new Item();
itemDetached.setItemId((String) row[0]);
GpsPosition gpsPositions = new GpsPosition();
gpsPositions.setAddress((String) row[5]);
gpsPositions.setLatitude((Float) row[3]);
gpsPositions.setLongitude((Float) row[4]);
if (isPointSelected != null) {
gpsPositions.setGeom_point((Point) row[6]);
}
itemDetached.getGpsPositions().add(gpsPositions);
LocalizedItem localizedItem = new LocalizedItem();
localizedItem.setLabel(Label.Title);
localizedItem.setLocale(searchFilter.getLocale());
localizedItem.setValue((String) row[2]);
itemDetached.getLocalizedItems().add(localizedItem);
items.add(itemDetached);
}
return items;
} else {
return new ArrayList<Item>();
}
}
}
| true |
b5072f03d24d672f29334b06568967607b4f5315 | Java | DannyOtgon/java-programming | /src/day47_constructors/Student.java | UTF-8 | 539 | 3.65625 | 4 | [] | no_license | package day47_constructors;
public class Student {
//No_args constructor
public Student(){
System.out.println("Student instance with no Args");
}
//constructor with 1 param
public Student(String name){
System.out.println("name param constructor | name = " + name);
}
public Student (int age){
System.out.println("age param constructor | age = " + age);
}
public Student (String name, int Age){
System.out.println("Student name & age: " + name + "-" +Age);
}
}
| true |
8511dc748f4f5855611f75dead21b16848ebca21 | Java | serialized-io/samples-java | /spark-todo-service/src/main/java/io/serialized/samples/domain/event/TodoCompleted.java | UTF-8 | 466 | 2.171875 | 2 | [] | no_license | package io.serialized.samples.domain.event;
import io.serialized.client.aggregate.Event;
import java.util.UUID;
import static io.serialized.client.aggregate.Event.newEvent;
public class TodoCompleted {
private UUID todoId;
public static Event<TodoCompleted> todoCompleted(UUID todoId) {
TodoCompleted event = new TodoCompleted();
event.todoId = todoId;
return newEvent(event).build();
}
public UUID getTodoId() {
return todoId;
}
}
| true |
94e751ace4cde95f86b263f15b84c0452743e2cb | Java | brucewuu520/Qianlichuanyin | /app/src/main/java/com/brucewuu/android/qlcy/activity/DiscussionDetailActivity.java | UTF-8 | 13,630 | 1.921875 | 2 | [
"MIT"
] | permissive | package com.brucewuu.android.qlcy.activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.brucewuu.android.qlcy.AppContext;
import com.brucewuu.android.qlcy.AppManager;
import com.brucewuu.android.qlcy.R;
import com.brucewuu.android.qlcy.base.SwipeBackActivity;
import com.brucewuu.android.qlcy.util.ListUtils;
import com.brucewuu.android.qlcy.util.UIHelper;
import com.brucewuu.android.qlcy.util.io.LogUtils;
import com.brucewuu.android.qlcy.widget.ScrollGridView;
import com.mcxiaoke.next.task.Failure;
import com.mcxiaoke.next.task.SimpleTaskCallback;
import com.mcxiaoke.next.task.Success;
import com.mcxiaoke.next.task.TaskBuilder;
import com.mcxiaoke.next.task.TaskCallable;
import com.mcxiaoke.next.task.TaskCallback;
import com.mcxiaoke.next.task.TaskQueue;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.yzxIM.IMManager;
import com.yzxIM.data.db.DiscussionInfo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;
/**
* Created by brucewuu on 15/9/6.
*/
public class DiscussionDetailActivity extends SwipeBackActivity {
public static final String DISCUSSION_ID = "discussion_id";
public static final String USER_ID = "user_id";
@Bind(R.id.toolbar)
Toolbar toolbar;
@Bind(R.id.gv_discussion_member)
ScrollGridView mGridView;
@Bind(R.id.tv_discussion_name)
TextView tvName;
private String discussionId;
private String userId;
private DiscussionInfo discussionInfo;
private DiscussionMemberAdapter mAdapter;
private AlertDialog addMemberDialog;
private AlertDialog clearMessageDialog;
private AlertDialog deleteDialog;
@Override
protected int getLayoutId() {
return R.layout.act_discussion_detail;
}
@Override
protected void afterViews() {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
discussionId = getIntent().getStringExtra(DISCUSSION_ID);
userId = getIntent().getStringExtra(USER_ID);
TaskQueue.getDefault().add(getCallable(), callback, this);
}
@OnClick(R.id.rl_change_discussion_name)
void changeName() {
if (addMemberDialog == null) {
View localView = View.inflate(this, R.layout.dialog_group, null);
final MaterialEditText localEditText = (MaterialEditText) localView.findViewById(R.id.et_group);
localEditText.setHint("输入新的昵称");
this.addMemberDialog = new AlertDialog.Builder(this)
.setTitle(R.string.create_group)
.setView(localView)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final String groupName = localEditText.getText().toString();
if (TextUtils.isEmpty(groupName)) {
localEditText.setError("请输入群组名~");
return;
} else if (groupName.equals(tvName.getText().toString())) {
return;
}
showProgressDialog("正在修改...");
TaskBuilder.create(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return IMManager.getInstance(AppContext.getInstance()).modifyDiscussionTitle(discussionId, groupName);
}
}).success(new Success<Boolean>() {
@Override
public void onSuccess(Boolean result, Bundle bundle) {
dismissProgressDialog();
if (result) {
tvName.setText(groupName);
} else {
UIHelper.showToast("修改失败~");
}
}
}).failure(new Failure() {
@Override
public void onFailure(Throwable throwable, Bundle bundle) {
dismissProgressDialog();
UIHelper.showToast("修改失败,请重试~");
}
}).with(DiscussionDetailActivity.this).start();
}
})
.setNegativeButton(R.string.cancle, null).create();
}
addMemberDialog.show();
}
@OnClick(R.id.label_clear_message)
void clearMessage() {
if (clearMessageDialog == null) {
clearMessageDialog = new AlertDialog.Builder(this)
.setMessage("清空此讨论组的历史消息?")
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
IMManager.getInstance(AppContext.getInstance())
.clearMessages(IMManager.getInstance(AppContext.getInstance())
.getConversation(discussionId));
}
})
.setNegativeButton(R.string.cancle, null).create();
}
clearMessageDialog.show();
}
@OnClick(R.id.btn_exit_discussion)
void exitAndDelete() {
if (deleteDialog == null) {
deleteDialog = new AlertDialog.Builder(this)
.setMessage("删除并退出后,将不再接受此讨论组信息!")
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
boolean flag = IMManager.getInstance(AppContext.getInstance())
.quitDiscussionGroup(discussionId);
if (flag) {
AppManager.getInstance().finishActivity(ChatActivity.class);
finish();
} else {
UIHelper.showToast("退出失败,请重试~");
}
}
})
.setNegativeButton(R.string.cancle, null).create();
}
deleteDialog.show();
}
final TaskCallback<List<String>> callback = new SimpleTaskCallback<List<String>>() {
@Override
public void onTaskSuccess(List<String> results, Bundle extras) {
LogUtils.e("results:" + results.size());
mAdapter = new DiscussionMemberAdapter(DiscussionDetailActivity.this, results);
mGridView.setAdapter(mAdapter);
tvName.setText(discussionInfo.getDiscussionName());
}
@Override
public void onTaskFailure(Throwable ex, Bundle extras) {
}
};
private Callable<List<String>> getCallable() {
return new TaskCallable<List<String>>() {
@Override
public List<String> call() throws Exception {
discussionInfo = IMManager.getInstance(AppContext.getInstance()).getDiscussionInfo(discussionId);
ArrayList memberList = new ArrayList();
if (discussionInfo != null) {
LogUtils.e("member::" + discussionInfo.getDiscussionMembers());
String[] members = discussionInfo.getDiscussionMembers().split(",");
for (int i = 0, length = members.length; i < length; i++) {
if (members[i].equals(userId)) {
memberList.add("我");
} else {
memberList.add(members[i]);
}
}
if (discussionInfo.getOwnerId().equals(userId)) {
memberList.add("+");
memberList.add("-");
} else {
memberList.add("+");
}
}
return memberList;
}
};
}
@Override
protected void onDestroy() {
TaskQueue.getDefault().cancelAll(this);
super.onDestroy();
}
@OnItemClick(R.id.gv_discussion_member)
void onItemClick(final int position) {
final String member = mAdapter.getItem(position);
if (member.equals("+")) {
} else if (member.equals("-")) {
if (mAdapter.isDeleting()) {
mAdapter.setDeleting(false);
} else {
mAdapter.setDeleting(true);
}
mAdapter.notifyDataSetChanged();
} else if (mAdapter.isDeleting()) {
showProgressDialog("正在删除...");
TaskBuilder.create(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
List<String> list = new ArrayList<>();
list.add(member);
return IMManager.getInstance(AppContext.getInstance())
.delDiscussionGroupMember(discussionId, list);
}
}).success(new Success<Boolean>() {
@Override
public void onSuccess(Boolean bool, Bundle bundle) {
dismissProgressDialog();
if (bool) {
mAdapter.removeAt(position);
}
}
}).failure(new Failure() {
@Override
public void onFailure(Throwable throwable, Bundle bundle) {
dismissProgressDialog();
UIHelper.showToast("删除失败,请重试~");
}
}).with(DiscussionDetailActivity.this).start();
} else {
}
}
static class DiscussionMemberAdapter extends BaseAdapter {
private List<String> items;
private boolean deleting = false;
private Context mContext;
public DiscussionMemberAdapter(Context mContext, List<String> items) {
this.mContext = mContext;
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_discussion_member, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String member = getItem(position);
if (member.equals("+")) {
holder.ivFace.setImageResource(R.drawable.add_member);
holder.tvName.setVisibility(View.GONE);
holder.flag.setVisibility(View.GONE);
} else if (member.equals("-")) {
holder.ivFace.setImageResource(R.drawable.delete_member);
holder.tvName.setVisibility(View.GONE);
holder.flag.setVisibility(View.GONE);
} else if (deleting) {
holder.ivFace.setImageResource(R.drawable.person);
holder.tvName.setVisibility(View.VISIBLE);
holder.flag.setVisibility(View.VISIBLE);
} else {
holder.ivFace.setImageResource(R.drawable.person);
holder.tvName.setVisibility(View.VISIBLE);
holder.flag.setVisibility(View.GONE);
}
return convertView;
}
@Override
public int getCount() {
return ListUtils.getSize(items);
}
@Override
public String getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public boolean isDeleting() {
return this.deleting;
}
public void setDeleting(boolean isDeleting) {
this.deleting = isDeleting;
}
public void removeAt(int position) {
items.remove(position);
}
class ViewHolder {
@Bind(R.id.iv_member_face)
ImageView ivFace;
@Bind(R.id.view_delete_flag)
ImageView flag;
@Bind(R.id.tv_member_name)
TextView tvName;
public ViewHolder(View itemView) {
ButterKnife.bind(this, itemView);
}
}
}
}
| true |
610976a09980117728fdd83c5c2d74fb1a0a31bd | Java | EwanMoshi/CM | /languages/CM/sandbox/source_gen/CM/test/ShaderProgram.java | UTF-8 | 2,800 | 2.25 | 2 | [] | no_license | package CM.test;
/*Generated by MPS */
import java.nio.FloatBuffer;
import org.lwjgl.BufferUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Vector3f;
import org.lwjgl.util.vector.Matrix4f;
public abstract class ShaderProgram {
private static FloatBuffer mBuffer = BufferUtils.createFloatBuffer(16);
private int programId;
private int fragmentShaderId;
private int vertexShaderId;
private static int loadShader(String f, int t) {
StringBuilder s = new StringBuilder();
try {
BufferedReader r = new BufferedReader(new FileReader(f));
String line;
while ((line = r.readLine()) != null) {
s.append(line).append("//\n");
}
r.close();
} catch (IOException er) {
er.printStackTrace();
System.exit(1);
}
int shaderId = GL20.glCreateShader(t);
GL20.glShaderSource(shaderId, s);
GL20.glCompileShader(shaderId);
if (GL20.glGetShaderi(shaderId, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
System.exit(-1);
}
return shaderId;
}
public ShaderProgram(String vFile, String fFile) {
vertexShaderId = loadShader(vFile, GL20.GL_VERTEX_SHADER);
fragmentShaderId = loadShader(fFile, GL20.GL_FRAGMENT_SHADER);
programId = GL20.glCreateProgram();
GL20.glAttachShader(programId, vertexShaderId);
GL20.glAttachShader(programId, fragmentShaderId);
bindAttribs();
GL20.glLinkProgram(programId);
GL20.glValidateProgram(programId);
getAllUniformLocations();
}
public void start() {
GL20.glUseProgram(programId);
}
public void stop() {
GL20.glUseProgram(0);
}
public void clean() {
stop();
GL20.glDetachShader(programId, vertexShaderId);
GL20.glDetachShader(programId, fragmentShaderId);
GL20.glDeleteShader(vertexShaderId);
GL20.glDeleteShader(fragmentShaderId);
GL20.glDeleteProgram(programId);
}
protected void bindAttrib(int attrib, String var) {
GL20.glBindAttribLocation(programId, attrib, var);
}
protected abstract void bindAttribs();
protected int getUniformLocation(String uniName) {
return GL20.glGetUniformLocation(programId, uniName);
}
protected abstract void getAllUniformLocations();
protected void loadVector(int loc, Vector3f v) {
GL20.glUniform3f(loc, v.x, v.y, v.z);
}
protected void loadBoolean(int loc, boolean b) {
float temp = 0;
if (b) {
temp = 1;
}
GL20.glUniform1f(loc, temp);
}
protected void loadFloat(int loc, float v) {
GL20.glUniform1f(loc, v);
}
protected void loadMatrix(int loc, Matrix4f m) {
m.store(mBuffer);
mBuffer.flip();
GL20.glUniformMatrix4(loc, false, mBuffer);
}
}
| true |
f2e670515a71a57523371bc4d9593170dad39a68 | Java | Olexiy911/UpWorkFramework | /src/main/java/framework/pages/home/LetsStartOptions.java | UTF-8 | 2,738 | 2.1875 | 2 | [] | no_license | package framework.pages.home;
import java.util.HashMap;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import framework.pages.Page;
import framework.pages.enterapplication.BecomeFreelancerPage;
import ru.yandex.qatools.allure.annotations.Step;
public class LetsStartOptions extends Page{
public LetsStartOptions() {
PageFactory.initElements(webDriver, this);
}
@FindBy(how = How.XPATH, using = "//li[@class='ng-scope']")
private List<WebElement> typesofwork;
@FindBy(how = How.XPATH, using = "//div[@class='bg-cloud step-title']")
private WebElement letsStartTitle;
@FindBy(how = How.XPATH, using = "//button[@class='btn btn-primary']")
private WebElement nextButton;
@FindBy(how = How.XPATH, using = "//span[@class='up-icon icon-prev']")
private WebElement backButton;
@FindBy(how = How.XPATH, using = "//p[@class='text-danger m-t-40 text-center font-gotham-medium ng-scope']")
private WebElement errorMessage;
@FindBy(how = How.XPATH, using = "//p[@class='text-center m-b-0']")
private WebElement wantToText;
@FindBy(how = How.XPATH, using = "//a[@class='font-gotham-medium']")
private WebElement becomeFreelancerButton;
@Step("Is Lets Start Window opened")
public String getTitle(){
return letsStartTitle.getText();
}
@Step("Click on Work Type {1} Checkbox")
public LetsStartOptions selectWorkType(String workType){
HashMap<String,WebElement> worktypes = new HashMap<String,WebElement>();
for(WebElement element:typesofwork){
worktypes.put(element.findElement(By.tagName("span")).getText().trim(), element.findElement(By.tagName("input")));
}
worktypes.get(workType).click();
return this;
}
@Step("Click Next Button")
public CategoryOptions clickNext(){
nextButton.click();
return PageFactory.initElements(webDriver, CategoryOptions.class);
}
@Step("Click Back Button")
public SearchOptions clickBack(){
backButton.click();
return PageFactory.initElements(webDriver, SearchOptions.class);
}
@Step("Is Error Message Displayed")
public boolean isErrorMessage(){
return errorMessage.isDisplayed(); //<--------------------
}
@Step("Is 'Want to get hired for projects?' text") //<--------------------------------------------------
public String getWantToText(){
return wantToText.getText();
}
@Step("Click on Work as a Freelancer Button")
public BecomeFreelancerPage clickBecomeFreelancerButton(){
becomeFreelancerButton.click();
return PageFactory.initElements(webDriver, BecomeFreelancerPage.class);
}
}
| true |
d432d884cb1e96871e4d0744bcc0d5479876261d | Java | quebic-source/lava-box | /src/main/java/com/lovi/quebic/web/impl/RequestMapImpl.java | UTF-8 | 1,495 | 2.40625 | 2 | [
"Apache-2.0"
] | permissive | package com.lovi.quebic.web.impl;
import com.lovi.quebic.handlers.FailureHandler;
import com.lovi.quebic.handlers.RequestHandler;
import com.lovi.quebic.web.RequestMap;
import com.lovi.quebic.web.RequestMapper;
import com.lovi.quebic.web.ServerContext;
import com.lovi.quebic.web.enums.HttpMethod;
public class RequestMapImpl implements RequestMap{
private String path;
private String regExpPath;
private HttpMethod httpMethod;
private RequestHandler<ServerContext> handler;
private FailureHandler<ServerContext> failureHandler;
public RequestMapImpl(RequestMapper requestMapper, String path, HttpMethod httpMethod) {
requestMapper.getRequestMaps().add(this);
this.path = path;
this.httpMethod = httpMethod;
}
@Override
public RequestHandler<ServerContext> getHandler() {
return handler;
}
@Override
public RequestMap setHandler(RequestHandler<ServerContext> handler) {
this.handler = handler;
return this;
}
@Override
public String getPath() {
return path;
}
@Override
public HttpMethod getHttpMethod() {
return httpMethod;
}
@Override
public String getRegExpPath() {
return regExpPath;
}
@Override
public void setRegExpPath(String regExpPath) {
this.regExpPath = regExpPath;
}
@Override
public FailureHandler<ServerContext> getFailureHandler() {
return failureHandler;
}
@Override
public RequestMap setFailureHandler(FailureHandler<ServerContext> failureHandler) {
this.failureHandler = failureHandler;
return this;
}
}
| true |
bb7b3b2e294861ce050a32fd087fbdf507e68bae | Java | jvsouza18/Orienta-oObjeto | /src/aula05/Produto.java | UTF-8 | 900 | 2.984375 | 3 | [] | no_license | package aula05;
public class Produto {
private int qtEstoque, qtVendido;
private double preco;
private static int qtTotalVendas;
public Produto(int qtEstoque, double preco)
{
this.qtEstoque = Math.max(1,qtEstoque);
this.preco = Math.max(1, preco);
this.qtVendido = 0;
}
public void vender(int qt)
{
int quantidade = Math.max(0, qt);
if (quantidade <= qtEstoque) {
qtEstoque -= quantidade;
qtVendido += quantidade;
qtTotalVendas += quantidade;
}
}
public static int getQtTotalVendas() {
return qtTotalVendas;
}
public void comprar(int quantidade)
{
qtEstoque += Math.max(0, quantidade);
}
public double calcularFaturamento()
{
return qtVendido*preco;
}
public void aumentarPreco(double pct)
{
preco = Math.max(preco,(1+pct)*preco);
}
public void diminuirPreco(double pct)
{
preco = Math.min(preco, (1-pct)*preco);
}
}
| true |
43b44f6cb4d3c8eb4acd94aa680884acbc5f8c35 | Java | requireSol/SWT1920_Learning | /common-utils/src/main/java/org/mhisoft/common/event/EventListener.java | UTF-8 | 183 | 1.703125 | 2 | [
"Apache-2.0"
] | permissive | package org.mhisoft.common.event;
/**
* Description:
*
* @author Tony Xue
* @since May, 2016
*/
public interface EventListener {
public void handleEvent(MHIEvent event) ;
}
| true |
3a612f3ea588a3797916e4187f7ea3ad829f1ec8 | Java | saisrinivasreddypatlolla/6019_CSPP2 | /cspp2-practice/m3/SumOfNNumbers.java | UTF-8 | 347 | 3.609375 | 4 | [] | no_license | import java.util.*;
class SumOfNNumbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = Integer.parseInt(scan.nextLine());
int sum = 0;
for ( int i = 1; i <= number; i++) {
sum += i;
}
System.out.format("Sum of %d numbers is : %d",number,sum);
}
} | true |
90373058bb399261c6aae976dca3f6be29bab983 | Java | gewoonniels/marktplaats-backend | /src/main/java/org/example/domain/Artikel.java | UTF-8 | 4,112 | 2.25 | 2 | [] | no_license | package org.example.domain;
import org.example.domain.dao.AbstractEntity;
import javax.persistence.*;
import java.util.Objects;
@Entity
@NamedQuery(name = "Artikel.findAll", query = "select a from Artikel a")
public class Artikel implements AbstractEntity<Long> {
@Id
@GeneratedValue
private long id;
private String naam;
@Enumerated(value = EnumType.STRING)
private Soort soort;
@Enumerated(value = EnumType.STRING)
private Categorie categorie;
private Double prijs;
private String omschrijving;
private String bijlage;
// @Convert(converter = BooleanConverter.class)
// Boolean isVerkocht;
@ManyToOne(fetch = FetchType.EAGER)
private Gebruiker eigenaar;
public Artikel() {
}
public Artikel(String naam, Soort soort, Categorie categorie, Double prijs) {
this.naam = naam;
this.soort = soort;
this.categorie = categorie;
this.prijs = prijs;
}
public Artikel(String naam, Soort soort, Categorie categorie, Double prijs, String omschrijving) {
this(naam, soort, categorie, prijs);
this.omschrijving = omschrijving;
}
public Artikel(String naam, Soort soort, Categorie categorie, Double prijs, String omschrijving, String bijlage) {
this(naam, soort, categorie, prijs, omschrijving);
this.bijlage = bijlage;
}
public Artikel(String naam, Soort soort, Categorie categorie, Double prijs, String omschrijving, String bijlage, long id) {
this(naam, soort, categorie, prijs, omschrijving, bijlage);
this.id = id;
}
public void setEigenaar(Gebruiker eigenaar) {
this.eigenaar = eigenaar;
}
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public void setId(long id) {
this.id = id;
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public Soort getSoort() {
return soort;
}
public void setSoort(Soort soort) {
this.soort = soort;
}
public Categorie getCategorie() {
return categorie;
}
public void setCategorie(Categorie categorie) {
this.categorie = categorie;
}
public Double getPrijs() {
return prijs;
}
public void setPrijs(Double prijs) {
this.prijs = prijs;
}
public String getOmschrijving() {
return omschrijving;
}
public void setOmschrijving(String omschrijving) {
this.omschrijving = omschrijving;
}
public String getBijlage() {
return bijlage;
}
public void setBijlage(String bijlage) {
this.bijlage = bijlage;
}
// public void setIsVerkocht(boolean isVerkocht) {
// this.isVerkocht = isVerkocht;
// }
//
// public Boolean getIsVerkocht() {
// return this.isVerkocht;
// }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Artikel artikel = (Artikel) o;
return id == artikel.id &&
Objects.equals(naam, artikel.naam) &&
soort == artikel.soort &&
categorie == artikel.categorie &&
Objects.equals(prijs, artikel.prijs) &&
Objects.equals(omschrijving, artikel.omschrijving);
// Objects.equals(bijlage, artikel.bijlage) &&
//// Objects.equals(isVerkocht, artikel.isVerkocht) &&
// Objects.equals(eigenaar, artikel.eigenaar);
}
@Override
public int hashCode() {
return Objects.hash(id, naam, soort, categorie, prijs, omschrijving);
}
@Override
public String toString() {
return "========================\n" +
naam + "\n" +
soort + " " + categorie + "\n" +
omschrijving + "\n" +
"Prijs: €" + prijs.doubleValue() + "\n" +
"========================\n";
}
}
| true |
4bde6e5b9d5f7c1e83027c220ac973de3ac4f284 | Java | trantuankhai/learnEnglish | /LearnService/src/main/java/com/vn/tdk/learnenglish/servicesImpl/UploadFileServicesImpl.java | UTF-8 | 2,952 | 2.46875 | 2 | [] | no_license | package com.vn.tdk.learnenglish.servicesImpl;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.vn.tdk.learnenglish.sevices.uploadService;
import com.vn.tdk.learnenglish.util.ConstanValue;
import com.vn.tdk.learnenglish.util.Status;
@Service
public class UploadFileServicesImpl implements uploadService {
private final String URL_UPLOAD_FILE_IMAGE = System.getProperty("user.dir") + "/images";
private final String URL_UPLOAD_FILE_CSV = System.getProperty("user.dir") + "/CsvFile";
@Override
public String uploadFile(MultipartFile file) throws IOException {
Date date = new Date();
File file2 = new File(URL_UPLOAD_FILE_IMAGE);
file2.mkdirs();
if (file.isEmpty()) {
return Status.INPUT_NULL;
} else {
String nameFile = date.getTime() + removeSpace(file.getOriginalFilename());
String uploadFilePath = URL_UPLOAD_FILE_IMAGE + "/" + nameFile;
byte[] bytes = file.getBytes();
Path path = Paths.get(uploadFilePath);
Files.write(path, bytes);
return nameFile;
}
}
@Override
public Resource getFileImage(String fileName) throws MalformedURLException {
if (!ConstanValue.NULL_VALUE.equals(fileName)) {
// File file = new File(URL_UPLOAD_FILE_IMAGE + "/" + fileName);
File file = new File(URL_UPLOAD_FILE_IMAGE + "/" + fileName);
System.out.println(URL_UPLOAD_FILE_IMAGE + "/" + fileName);
// System.out.println(URL_UPLOAD_FILE_IMAGE + "/" + fileName);
return new UrlResource(file.toURI());
} else {
return null;
}
}
public String removeSpace(String str) {
str = str.trim();
str = str.replaceAll("\\s+", "");
return str;
}
@Override
public String uploadFileImportData(MultipartFile file) throws IOException {
Date date = new Date();
File file2 = new File(URL_UPLOAD_FILE_CSV);
file2.mkdirs();
if (file.isEmpty()) {
return Status.INPUT_NULL;
} else {
String nameFile = date.getTime() + removeSpace(file.getOriginalFilename());
String uploadFilePath = URL_UPLOAD_FILE_CSV + "/" + nameFile;
byte[] bytes = file.getBytes();
Path path = Paths.get(uploadFilePath);
Files.write(path, bytes);
return uploadFilePath;
}
}
@Override
public Resource getFileCsv(String fileName) throws MalformedURLException {
if (!ConstanValue.NULL_VALUE.equals(fileName)) {
// File file = new File(URL_UPLOAD_FILE_IMAGE + "/" + fileName);
File file = new File(URL_UPLOAD_FILE_CSV + "/" + fileName);
System.out.println(URL_UPLOAD_FILE_CSV + "/" + fileName);
// System.out.println(URL_UPLOAD_FILE_IMAGE + "/" + fileName);
return new UrlResource(file.toURI());
} else {
return null;
}
}
}
| true |
7cdcd596215156c7cec56883005e7c77ba3161ec | Java | lpapailiou/tictactoe | /src/main/java/model/Source.java | UTF-8 | 221 | 2.390625 | 2 | [] | no_license | package main.java.model;
public enum Source {
LIBRARY("library"),
BLANK("blank");
private String name;
Source(String name) {
this.name = name;
}
public String get() {
return name;
}
}
| true |
3169816d6cebf703b4cbc988ea832b57071d972f | Java | YampoKnaf/Israelity | /Israelity/app/src/main/java/com/yampoknaf/israelity/HomeFragments/UserPicture.java | UTF-8 | 3,760 | 2 | 2 | [] | no_license | package com.yampoknaf.israelity.HomeFragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.yampoknaf.israelity.HelperFunction.BigHelper;
import com.yampoknaf.israelity.R;
/**
* Created by Orleg on 07/05/2016.
*/
public class UserPicture extends Fragment {
private boolean mOtherSize;
private int mWhichPic;
private int mXSize;
private int mYSize;
private ImageView profilePic;
public void putPrefferPicSize(int whichPic){
putPrefferPicSize(false , whichPic , -2 , -2);
}
public void putPrefferPicSize(boolean otherSize , int whichPic , int xSize , int ySize){
mOtherSize = otherSize;
mWhichPic = whichPic;
mXSize = xSize;
mYSize = ySize;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.user_picture, container, false);
profilePic = (ImageView)v.findViewById(R.id.user_profile_pic);
Glide.with(getActivity()).load(mWhichPic).override(!mOtherSize ? BigHelper.getWindowWidthSize() : mXSize, !mOtherSize ? BigHelper.getWindowHigthSize(): mYSize).fitCenter().into(profilePic);
profilePic.setTag(mWhichPic);
final TextView textViewName = (TextView)v.findViewById(R.id.userNameTitleUserPicture);
final TextView textViewScore = (TextView)v.findViewById(R.id.scoreUserPicture);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
//textView.setText("Ori Yampolsky");
if (!mOtherSize) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ABOVE, R.id.emptyLayOutUser_Picture);
params.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.user_profile_pic);
params.setMargins(20, 20, 20, 20);
textViewName.setLayoutParams(params);
textViewName.setText("Ori Yampolsky");
textViewScore.setText("your score is 5000!!");
textViewScore.setPadding(20, 20, 20, 20);
}
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
return v;
}
public void setOnClickListener(final View.OnClickListener listener){
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
profilePic.setOnClickListener(listener);
}
});
}
}).start();
}
}
| true |
195f4c7b9e03512c1c29a50b8925482ff05550c9 | Java | alirestum/gamekeystore | /src/main/java/hu/restumali/gamekeystore/service/FileService.java | UTF-8 | 1,963 | 2.28125 | 2 | [
"MIT"
] | permissive | package hu.restumali.gamekeystore.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import hu.restumali.gamekeystore.model.ProductEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
@Service
public class FileService {
@Autowired
ObjectMapper objectMapper;
@Value("${upload.location}")
String uploadPath;
public String uploadFile(MultipartFile file){
String fileName = System.currentTimeMillis() + file.getOriginalFilename();
String path = uploadPath + fileName;
try {
file.transferTo(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
public List<ProductEntity> importFile(MultipartFile file){
File importedFile = new File(file.getOriginalFilename());
try {
importedFile.createNewFile();
FileOutputStream fos = new FileOutputStream(importedFile);
fos.write(file.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
List<ProductEntity> importedProducts= null;
try {
importedProducts = objectMapper.readValue(importedFile, new TypeReference<>() {
});
} catch (IOException e) {
e.printStackTrace();
}
return importedProducts;
}
public void exportProducts(List<ProductEntity> products){
try {
objectMapper.writeValue(new File(uploadPath + "export.json"), products);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
6413649c5d7e97e6ad594960cb6daff55e971ed7 | Java | pulumi/pulumi-aws | /sdk/java/src/main/java/com/pulumi/aws/eks/inputs/NodeGroupUpdateConfigArgs.java | UTF-8 | 3,735 | 2.125 | 2 | [
"BSD-3-Clause",
"Apache-2.0",
"MPL-2.0"
] | permissive | // *** WARNING: this file was generated by pulumi-java-gen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package com.pulumi.aws.eks.inputs;
import com.pulumi.core.Output;
import com.pulumi.core.annotations.Import;
import java.lang.Integer;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
public final class NodeGroupUpdateConfigArgs extends com.pulumi.resources.ResourceArgs {
public static final NodeGroupUpdateConfigArgs Empty = new NodeGroupUpdateConfigArgs();
/**
* Desired max number of unavailable worker nodes during node group update.
*
*/
@Import(name="maxUnavailable")
private @Nullable Output<Integer> maxUnavailable;
/**
* @return Desired max number of unavailable worker nodes during node group update.
*
*/
public Optional<Output<Integer>> maxUnavailable() {
return Optional.ofNullable(this.maxUnavailable);
}
/**
* Desired max percentage of unavailable worker nodes during node group update.
*
*/
@Import(name="maxUnavailablePercentage")
private @Nullable Output<Integer> maxUnavailablePercentage;
/**
* @return Desired max percentage of unavailable worker nodes during node group update.
*
*/
public Optional<Output<Integer>> maxUnavailablePercentage() {
return Optional.ofNullable(this.maxUnavailablePercentage);
}
private NodeGroupUpdateConfigArgs() {}
private NodeGroupUpdateConfigArgs(NodeGroupUpdateConfigArgs $) {
this.maxUnavailable = $.maxUnavailable;
this.maxUnavailablePercentage = $.maxUnavailablePercentage;
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(NodeGroupUpdateConfigArgs defaults) {
return new Builder(defaults);
}
public static final class Builder {
private NodeGroupUpdateConfigArgs $;
public Builder() {
$ = new NodeGroupUpdateConfigArgs();
}
public Builder(NodeGroupUpdateConfigArgs defaults) {
$ = new NodeGroupUpdateConfigArgs(Objects.requireNonNull(defaults));
}
/**
* @param maxUnavailable Desired max number of unavailable worker nodes during node group update.
*
* @return builder
*
*/
public Builder maxUnavailable(@Nullable Output<Integer> maxUnavailable) {
$.maxUnavailable = maxUnavailable;
return this;
}
/**
* @param maxUnavailable Desired max number of unavailable worker nodes during node group update.
*
* @return builder
*
*/
public Builder maxUnavailable(Integer maxUnavailable) {
return maxUnavailable(Output.of(maxUnavailable));
}
/**
* @param maxUnavailablePercentage Desired max percentage of unavailable worker nodes during node group update.
*
* @return builder
*
*/
public Builder maxUnavailablePercentage(@Nullable Output<Integer> maxUnavailablePercentage) {
$.maxUnavailablePercentage = maxUnavailablePercentage;
return this;
}
/**
* @param maxUnavailablePercentage Desired max percentage of unavailable worker nodes during node group update.
*
* @return builder
*
*/
public Builder maxUnavailablePercentage(Integer maxUnavailablePercentage) {
return maxUnavailablePercentage(Output.of(maxUnavailablePercentage));
}
public NodeGroupUpdateConfigArgs build() {
return $;
}
}
}
| true |
00ade37439b9290f3c239caf3a63c5a2f50d25be | Java | martinsj438/Teste-de-Software | /bancario/Bancario/src/vizualizacao/ListarPessoaf.java | UTF-8 | 7,220 | 2.265625 | 2 | [] | 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 vizualizacao;
import controle.DAO.ClienteDAO;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import modelo.PessoaFisica;
/**
*
* @author 381121742018.1
*/
public class ListarPessoaf extends javax.swing.JDialog {
/**
* Creates new form ListarPessoaf
*/
public ListarPessoaf(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
iniciarDB();
montarTabela();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tblPessoaF = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(0, 102, 102));
tblPessoaF.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null}
},
new String [] {
"ID", "Nome", "Nome Social", "CPF", "CEP", "Número", "Complemento"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tblPessoaF);
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Relatorio Pessoa");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(28, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(248, 248, 248))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 625, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(121, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblPessoaF;
// End of variables declaration//GEN-END:variables
private controle.DAO.ClienteDAO clienteDao;
private void iniciarDB() {
try{
clienteDao = new ClienteDAO();
}catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
private void montarTabela() {
try {
ArrayList<PessoaFisica> pessoas = clienteDao.listarClienteF();
int linha = 0;
for(PessoaFisica pessoa : pessoas){
int id = pessoa.getIdPessoa();
String nome = pessoa.getNomePessoa();
String nomeSocial = pessoa.getNomeSocial();
String cpf = pessoa.getCpf();
String cep = pessoa.getCep();
String num = pessoa.getNum();
String complemento = pessoa.getComplemento();
tblPessoaF.getModel().setValueAt(id, linha, 0);
tblPessoaF.getModel().setValueAt(nome, linha, 1);
tblPessoaF.getModel().setValueAt(nomeSocial, linha, 2);
tblPessoaF.getModel().setValueAt(cpf, linha, 3);
tblPessoaF.getModel().setValueAt(cep, linha, 4);
tblPessoaF.getModel().setValueAt(num, linha, 5);
tblPessoaF.getModel().setValueAt(complemento, linha, 6);
linha++;
}
} catch (SQLException ex) {
Logger.getLogger(ListarPessoaf.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| true |
6250930f94884437c8345e37087abdc5435ffa17 | Java | chenJz1012/os-app | /os-test/src/test/java/com/orangeside/patchca/Sample.java | UTF-8 | 926 | 2.484375 | 2 | [] | no_license | package com.orangeside.patchca;
import com.orangeside.patchca.color.SingleColorFactory;
import com.orangeside.patchca.encoder.EncoderHelper;
import com.orangeside.patchca.filter.predefined.CurvesRippleFilterFactory;
import com.orangeside.patchca.service.ConfigurableCaptchaService;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* sample code Created by shijinkui on 15/3/15.
*/
public class Sample {
public static void main(String[] args) throws IOException {
ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
cs.setColorFactory(new SingleColorFactory(new Color(25, 60, 170)));
cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
FileOutputStream fos = new FileOutputStream("patcha_demo.png");
System.out.println(EncoderHelper.getChallangeAndWriteImage(cs, "png", fos));
fos.close();
}
}
| true |
9ca30146b0f4eaf191e5339f8b80304b4abaae2c | Java | KaranKamat0506/java | /New folder/Sukrut/CopyCharacters.java | UTF-8 | 559 | 3.46875 | 3 | [] | no_license | import java.io.*;
class CopyCharacters{
public static void main(String[] args) {
File inFile=new File("infile.txt");
File outFile=new File("outfile.txt");
FileReader ins=null;
FileWriter outs=null;
try{
ins=new FileReader(inFile);
outs=new FileWriter(outFile);
int ch;
while((ch=ins.read())!=-1){
outs.write(ch);
}
}
catch(IOException e){
System.out.println(e);
System.exit(-1);
}
finally{
System.out.println("Contents copied");
try{
ins.close();
outs.close();
}
catch(IOException e){}
}
}
} | true |
d039b4a2d9b29e9c814c13878b389c54545b5c8a | Java | harshikesh/algo | /src/Strings/SortedSubStr.java | UTF-8 | 3,293 | 3.234375 | 3 | [] | no_license | package Strings;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
/**
* Created by harshikesh.kumar on 25/07/17.
*/
public class SortedSubStr {
public static void main(String[] args) {
findSubstrings("adbaac");
}
static int[] createSuffixArray(String str) {
class SuffixTriplet implements Comparable<SuffixTriplet> {
int rootIndex;
int firstIndex;
int length;
@Override
public int compareTo(SuffixTriplet arg) {
if (arg.firstIndex != firstIndex)
return firstIndex - arg.firstIndex;
return length - arg.length;
}
SuffixTriplet(int id, int fh, int sh) {
rootIndex = id;
firstIndex = fh;
length = sh;
}
};
int n = str.length();
int rank[] = new int[n];
SuffixTriplet suffixTriplets[] = new SuffixTriplet[n];
for (int i = 0; i < n;i++) {
rank[i] = str.charAt(i) -'a';
suffixTriplets[i] = new SuffixTriplet(i,rank[i],0);
}
for (int count = 1 ; count < n; count *= 2) {
for(int i = 0; i < n; i++) {
suffixTriplets[i].firstIndex = rank[i];
suffixTriplets[i].length = i + count < n ? rank[i + count] : -1;
suffixTriplets[i].rootIndex = i;
}
Arrays.sort(suffixTriplets);
rank[suffixTriplets[0].rootIndex] = 0;
for(int i = 1, currRank = 0; i < n; i++) {
if(suffixTriplets[i - 1].firstIndex != suffixTriplets[i].firstIndex || suffixTriplets[i - 1].length != suffixTriplets[i].length)
++currRank;
rank[suffixTriplets[i].rootIndex] = currRank;
}
}
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = suffixTriplets[i].rootIndex;
return res;
}
static void findSubstrings(String s) {
List<Character> characterList = Arrays.asList(new Character[]{'a', 'e', 'u', 'o', 'i'});
HashSet<Character> vowelSet = new HashSet<>(characterList);
int last = s.length();
for (int i = s.length() - 1; i >= 0; i--) {
if (vowelSet.contains(s.charAt(i))) {
last--;
} else
break;
}
s = s.substring(0, last);
int[] resultArray = createSuffixArray(s);
int i = 0;
while (i < resultArray.length) {
if (vowelSet.contains(s.charAt(resultArray[i]))) {
break;
}
i++;
}
if (i < resultArray.length) {
String firstSubString = s.substring(resultArray[i]);
for (i = 0; i < firstSubString.length(); i++) {
if (!vowelSet.contains(firstSubString.charAt(i)))
break;
}
System.out.println(firstSubString.substring(0, i + 1));
for (i = resultArray.length - 1; i >= 0; i--) {
if (vowelSet.contains(s.substring(resultArray[i]).charAt(0))) {
break;
}
}
System.out.println(s.substring(resultArray[i]));
}
}
}
| true |
ee9de6a1c03a36972b1c12d2a66b1fc9fc2c3cc8 | Java | Rahul0506/tp | /src/test/java/seedu/address/model/util/SampleDataTest.java | UTF-8 | 818 | 1.929688 | 2 | [
"MIT"
] | permissive | package seedu.address.model.util;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
public class SampleDataTest {
@Test
public void nonNullTests() {
// sample tags
assertNotNull(SampleDataUtil.getTagSet());
// sample items
assertNotNull(SampleDataUtil.getSampleItems());
// sample itemList
assertNotNull(SampleDataUtil.getSampleItemList());
// sample locations
assertNotNull(SampleDataUtil.getSampleLocations());
// sample locationList
assertNotNull(SampleDataUtil.getSampleLocationList());
// sample recipes
assertNotNull(SampleDataUtil.getSampleRecipes());
// sample recipeList
assertNotNull(SampleDataUtil.getSampleRecipeList());
}
}
| true |
6f41c03231484ecc1b44d3080434c9898a28ede1 | Java | smilejianhua/aiis-fims-desgin | /src/com/wondersgroup/aiis/fims/service/impl/ScheduleServiceImpl.java | UTF-8 | 1,019 | 2.078125 | 2 | [] | no_license | package com.wondersgroup.aiis.fims.service.impl;
import java.io.File;
import java.util.List;
import com.wondersgroup.aiis.fims.model.NativeFlightLongTermPlan;
import com.wondersgroup.aiis.fims.service.ScheduleService;
import com.wondersgroup.aiis.fims.utils.schedule.ExcelToSchedule;
import com.wondersgroup.aiis.fims.utils.schedule.FileToSchedule;
import com.wondersgroup.aiis.fims.vo.Schedule;
public class ScheduleServiceImpl implements ScheduleService {
private FileToSchedule fs = new ExcelToSchedule();
@Override
public List<Schedule> fileToSchedule(File file) {
return null;
}
@Override
public File scheduleToFile(List<Schedule> schedule) {
// TODO Auto-generated method stub
return null;
}
public void setFileToSchedule(FileToSchedule fs){
this.fs = fs;
}
@Override
public List<NativeFlightLongTermPlan> transformToNativeFlightLongTermPlan(Schedule schedule, String locationAirport) {
// TODO Auto-generated method stub
return null;
}
}
| true |
43bb6d688d13836ba1017b6f77399da8b68081ac | Java | Maploop/SkyBlockSandbox-Old- | /src/main/java/net/maploop/items/item/items/BuildersWand.java | UTF-8 | 12,274 | 1.867188 | 2 | [
"BSD-3-Clause"
] | permissive | package net.maploop.items.item.items;
import net.maploop.items.enums.ItemType;
import net.maploop.items.enums.Rarity;
import net.maploop.items.item.CustomItem;
import net.maploop.items.item.ItemAbility;
import net.maploop.items.item.ItemUtilities;
import net.maploop.items.util.IUtil;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.util.Vector;
import java.util.*;
public class BuildersWand extends CustomItem {
public BuildersWand(int id, Rarity rarity, String name, Material material, int durability, boolean stackable, boolean oneTimeUse, boolean hasActive, List<ItemAbility> abilities, int manaCost, boolean reforgeable, ItemType itemType, boolean glowing) {
super(id, rarity, name, material, durability, stackable, oneTimeUse, hasActive, abilities, manaCost, reforgeable, itemType, glowing);
}
@Override
public void onItemStackCreate(ItemStack paramItemStack) {
}
@Override
public void getSpecificLorePrefix(List<String> paramList, ItemStack paramItemStack) {
}
@Override
public void getSpecificLoreSuffix(List<String> paramList, ItemStack paramItemStack) {
}
@Override
public void leftClickAirAction(Player player, ItemStack paramItemStack) {
player.sendMessage("§cThis ability is currently disabled!");
player.playSound(player.getLocation(), Sound.ENDERMAN_TELEPORT, 1f, 0f);
return;
/*
builder_wand.put(player, player.getItemInHand());
String uuid = ItemUtilities.getStringFromItem(item, "UUID");
Inventory inv = Bukkit.createInventory(null, 6 * 9, "Builder's Wand");
if(builders_wand_storage.containsKey(uuid)) {
inv.setContents(builders_wand_storage.get(uuid));
player.openInventory(inv);
} else {
player.openInventory(inv);
}
*/
}
@Override
public void leftClickBlockAction(Player paramPlayer, PlayerInteractEvent paramPlayerInteractEvent, Block paramBlock, ItemStack paramItemStack) {
}
@Override
public void rightClickAirAction(Player paramPlayer, PlayerInteractEvent event, ItemStack paramItemStack) {
}
@Override
public void rightClickBlockAction(Player player, PlayerInteractEvent event, Block paramBlock, ItemStack paramItemStack) {
if(player.hasPermission("dungeons.builderswand.use")) {
fillConnectedFaces(player, paramBlock, event.getBlockFace(), paramItemStack);
onItemUse(player, paramItemStack);
} else {
player.playSound(player.getLocation(), Sound.WOOD_CLICK, 1f, 1f);
player.sendMessage(ChatColor.RED + "You do not have the required permission to use this item!");
}
}
@Override
public void shiftLeftClickAirAction(Player paramPlayer, ItemStack paramItemStack) {
}
@Override
public void shiftLeftClickBlockAction(Player paramPlayer, PlayerInteractEvent paramPlayerInteractEvent, Block paramBlock, ItemStack paramItemStack) {
}
@Override
public void shiftRightClickAirAction(Player paramPlayer, PlayerInteractEvent event, ItemStack paramItemStack) {
}
@Override
public void shiftRightClickBlockAction(Player paramPlayer, PlayerInteractEvent paramPlayerInteractEvent, Block paramBlock, ItemStack paramItemStack) {
}
@Override
public void middleClickAction(Player paramPlayer, ItemStack paramItemStack) {
}
@Override
public void hitEntityAction(Player paramPlayer, EntityDamageByEntityEvent paramEntityDamageByEntityEvent, Entity paramEntity, ItemStack paramItemStack) {
}
@Override
public void breakBlockAction(Player paramPlayer, BlockBreakEvent paramBlockBreakEvent, Block paramBlock, ItemStack paramItemStack) {
}
@Override
public void clickedInInventoryAction(Player paramPlayer, InventoryClickEvent paramInventoryClickEvent) {
}
@Override
public void activeEffect(Player paramPlayer, ItemStack paramItemStack) {
}
public static HashMap<String, ItemStack[]> builders_wand_storage = new HashMap<>();
public static Map<Player, ItemStack> builder_wand = new HashMap<>();
public static Map<Player, List<Block>> blocksMap = new HashMap<>();
public static Map<Player, Integer> blocksAmount = new HashMap<>();
public static void undoWand(Player player) {
for(Block b : blocksMap.get(player)) {
b.setType(Material.AIR);
}
ItemStack step1 = new ItemStack(blocksMap.get(player).get(0).getType(), blocksAmount.get(player));
ItemStack step2 = ItemUtilities.storeStringInItem(step1, Rarity.COMMON.toString(), "Rarity");
ItemMeta meta = step2.getItemMeta();
List<String> lore = new ArrayList<>();
lore.add("§f§lCOMMON");
meta.spigot().setUnbreakable(true);
meta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE);
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
meta.setLore(lore);
step2.setItemMeta(meta);
player.getInventory().addItem(step2);
}
public void fillConnectedFaces(Player player, Block origin, BlockFace face, ItemStack item) {
Material fillMaterial = origin.getType();
int blocksInInventory = countBlocks(player.getInventory(), origin.getType(), item);
int blockLimit = 164;
if (blocksInInventory < blockLimit)
blockLimit = blocksInInventory;
List<Block> blocks = new ArrayList<>();
List<Block> blocksForUndo = new ArrayList<>();
blocks.add(origin);
World w = player.getWorld();
Vector check[] = null, translate = null;
int blocksPlaced = 0;
switch (face) {
case NORTH:
case SOUTH:
check = new Vector[] { new Vector(-1, -1, 0), new Vector(-1, 0, 0), new Vector(-1, 1, 0), new Vector(0, -1, 0), new Vector(0, 1, 0), new Vector(1, -1, 0), new Vector(1, 0, 0), new Vector(1, 1, 0) };
break;
case EAST:
case WEST:
check = new Vector[] { new Vector(0, -1, -1), new Vector(0, -1, 0), new Vector(0, -1, 1), new Vector(0, 0, -1), new Vector(0, 0, 1), new Vector(0, 1, -1), new Vector(0, 1, 0), new Vector(0, 1, 1) };
break;
case UP:
case DOWN:
check = new Vector[] { new Vector(-1, 0, -1), new Vector(-1, 0, 0), new Vector(-1, 0, 1), new Vector(0, 0, -1), new Vector(0, 0, 1), new Vector(1, 0, -1), new Vector(1, 0, 0), new Vector(1, 0, 1) };
break;
}
switch (face) {
case NORTH:
translate = new Vector(0, 0, -1);
break;
case SOUTH:
translate = new Vector(0, 0, 1);
break;
case EAST:
translate = new Vector(1, 0, 0);
break;
case WEST:
translate = new Vector(-1, 0, 0);
break;
case UP:
translate = new Vector(0, 1, 0);
break;
case DOWN:
translate = new Vector(0, -1, 0);
break;
}
while (blocks.size() > 0 && blockLimit > 0) {
Location l = (blocks.get(0)).getLocation();
for (Vector vector : check) {
if (w.getBlockAt(l.clone().add(vector)).getType() == fillMaterial && w
.getBlockAt(l.clone().add(vector).clone().add(translate)).getType() == Material.AIR)
blocks.add(w.getBlockAt(l.clone().add(vector)));
blocksForUndo.add(w.getBlockAt(l.clone().add(vector)));
}
Block fillBlock = w.getBlockAt(l.clone().add(translate));
if (canPlaceBlock(player, fillBlock.getLocation())) {
blocks.removeIf(blocks.get(0)::equals);
if (fillBlock.getType() != fillMaterial) {
fillBlock.setType(fillMaterial);
blockLimit--;
blocksPlaced++;
}
if (blocksPlaced == blockLimit)
break;
continue;
}
blocks.removeIf(blocks.get(0)::equals);
blockLimit--;
}
if(blocksPlaced == 0) {
player.playSound(player.getLocation(), Sound.WOOD_CLICK, 1f, 1f);
player.sendMessage("§cYou cannot place any blocks! You do not have enough blocks to place with your Builder's wand!");
}
if (blocksPlaced != 0) {
blocksMap.put(player, blocksForUndo);
blocksAmount.put(player, blocksPlaced);
player.getInventory().removeItem(new ItemStack(origin.getType(), blocksPlaced));
TextComponent component = new TextComponent("§eYou built §a" + blocksPlaced + "§e blocks! ");
TextComponent comp = IUtil.makeClickableText("§a§lUNDO", "§eClick to undo latest creation!", ClickEvent.Action.RUN_COMMAND, "/undograndarchitect");
player.spigot().sendMessage(component, comp);
player.playSound(player.getLocation(), Sound.EXPLODE, 1.0F, 2.0F);
removeItems(player.getInventory(), origin.getType(), blocksPlaced);
}
}
public int countBlocks(Inventory inv, Material m, ItemStack stack) {
int blockAmount = 0;
String uuid = ItemUtilities.getStringFromItem(stack, "UUID");
for (ListIterator<ItemStack> listIterator = inv.iterator(); listIterator.hasNext(); ) {
ItemStack item = listIterator.next();
if (item != null &&
item.getType() == m)
blockAmount += item.getAmount();
}
if(builders_wand_storage.containsKey(uuid)) {
for(ItemStack i : builders_wand_storage.get(uuid)) {
if(i != null && i.getType() == m)
blockAmount += i.getAmount();
}
}
return blockAmount;
}
public void removeBlocks(Player player, Material m, int blockAmount) {
ItemStack mats = new ItemStack(m, blockAmount);
player.getInventory().removeItem(mats);
}
public boolean canPlaceBlock(Player player, Location l) {
return true;
}
/**
* Removes the items of type from an inventory.
* @param inventory Inventory to modify
* @param type The type of Material to remove
* @param amount The amount to remove, or MAX_VALUE to remove all
* @return 0 for success, otherwise -1
*/
public static int removeItems(Inventory inventory, Material type, int amount) {
if(type == null || inventory == null)
return -1;
if (amount <= 0)
return -1;
if (amount == Integer.MAX_VALUE) {
inventory.remove(type);
return 0;
}
ItemStack step1 = new ItemStack(type, amount);
ItemStack step2 = ItemUtilities.storeStringInItem(step1, Rarity.COMMON.toString(), "Rarity");
ItemMeta meta = step2.getItemMeta();
List<String> lore = new ArrayList<>();
lore.add("§f§lCOMMON");
meta.spigot().setUnbreakable(true);
meta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE);
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
meta.setLore(lore);
step2.setItemMeta(meta);
inventory.removeItem(step2);
return 0;
}
private boolean a(ItemStack item) {
String uuid = ItemUtilities.getStringFromItem(item, "UUID");
return true;
}
}
| true |
7ecf47cbc88ee476b82ad739bcd9a1da8125a93d | Java | CafeGIS/gvSIG2_0 | /libFMap_dal/src/org/gvsig/fmap/dal/feature/impl/FeatureManager.java | ISO-8859-1 | 11,126 | 1.953125 | 2 | [] | no_license |
/* gvSIG. Sistema de Informacin Geogrfica de la Generalitat Valenciana
*
* Copyright (C) 2005 IVER T.I. and Generalitat Valenciana.
*
* 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.
*
* For more information, contact:
*
* Generalitat Valenciana
* Conselleria d'Infraestructures i Transport
* Av. Blasco Ibez, 50
* 46010 VALENCIA
* SPAIN
*
* +34 963862235
* gvsig@gva.es
* www.gvsig.gva.es
*
* or
*
* IVER T.I. S.A
* Salamanca 50
* 46005 Valencia
* Spain
*
* +34 963163400
* dac@iver.es
*/
package org.gvsig.fmap.dal.feature.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import org.gvsig.fmap.dal.exception.DataException;
import org.gvsig.fmap.dal.feature.EditableFeature;
import org.gvsig.fmap.dal.feature.Feature;
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
import org.gvsig.fmap.dal.feature.FeatureReference;
import org.gvsig.fmap.dal.feature.FeatureStore;
import org.gvsig.fmap.dal.feature.FeatureType;
import org.gvsig.fmap.dal.feature.impl.expansionadapter.ExpansionAdapter;
/**
* DOCUMENT ME!
*
* @author Vicente Caballero Navarro
*/
public class FeatureManager {
private ExpansionAdapter expansionAdapter;
private ArrayList deleted = new ArrayList();//<FeatureID>
private int deltaSize=0;
private Map added = new LinkedHashMap();
private HashMap modifiedFromOriginal=new HashMap();
public FeatureManager(ExpansionAdapter expansionAdapter){
this.expansionAdapter=expansionAdapter;
}
public Feature delete(FeatureReference id) {
deleted.add(id);
Integer num = (Integer) added.remove(id);
Feature feature=null;
if (num == null || num.intValue() == -1) {
feature = (Feature)modifiedFromOriginal.remove(id);
}else{
feature = (Feature) expansionAdapter.getObject(num.intValue());
}
deltaSize--;
return feature;
}
/**
* DOCUMENT ME!
*
* @param feature DOCUMENT ME!
*/
public void add(Feature feature) {
int pos = expansionAdapter.addObject(feature);
added.put(feature.getReference(),new Integer(pos));
deleted.remove(feature.getReference());
deltaSize++;
}
/**
* DOCUMENT ME!
* @param id DOCUMENT ME!
*/
public Feature deleteLastFeature() {
expansionAdapter.deleteLastObject();
Feature feature=(Feature)expansionAdapter.getObject(expansionAdapter.getSize()-1);
added.remove(feature.getReference());
modifiedFromOriginal.remove(feature.getReference());
deltaSize--;
return feature;
}
/**
* Returns a Feature of the default type.
*
* @param id
* the feature reference
* @param store
* the store to get the feature from
* @return a Feature with the given reference
* @throws DataException
* if there is an error getting the Feature
*/
public Feature get(FeatureReference id, FeatureStore store)
throws DataException {
return get(id, store, null);
}
/**
* Returns a Feature of the given type.
*
* @param id
* the feature reference
* @param store
* the store to get the feature from
* @param featureType
* the type of the feature to return
* @return a Feature with the given reference
* @throws DataException
* if there is an error getting the Feature
*/
public Feature get(FeatureReference id, FeatureStore store,
FeatureType featureType) throws DataException {
// FIXME: y si el featuretype que paso esta modificado.
// Deberia buscarlo en el featuretypemanager ?
//
// Si no existe feature con ese id... retorna null ?
// en EditedDefaultIterator se hace uso de ese comportamiento.
//
Integer intNum =((Integer) added.get(id));
if (intNum == null){
intNum =((Integer) modifiedFromOriginal.get(id));
if (intNum == null){
return null;
}
}
int num = intNum.intValue();
if (num==-1) {
return null;
}
Feature feature=(Feature)expansionAdapter.getObject(num);
if (featureType== null){
featureType = store.getDefaultFeatureType();
}
return getCorrectFeature(feature, store,featureType);
}
private Feature getCorrectFeature(Feature feature, FeatureStore store,
FeatureType featureType) throws DataException {
Iterator iterator=featureType.iterator();
EditableFeature newFeature=feature.getEditable();//store.createNewFeature(featureType, false);
FeatureType orgType = feature.getType();
int orgIndex;
while (iterator.hasNext()) {
FeatureAttributeDescriptor fad = (FeatureAttributeDescriptor) iterator.next();
orgIndex = orgType.getIndex(fad.getName());
if (orgIndex<0){
continue;
}
if (fad.isAutomatic() || fad.isReadOnly()
|| fad.getEvaluator() != null) {
continue;
}
Object value = feature.get(orgIndex);
if (value == null && !fad.allowNull()) {
continue;
}
newFeature.set(fad.getIndex(), value);
}
return newFeature.getNotEditableCopy();
}
/**
* DOCUMENT ME!
*
* @param feature DOCUMENT ME!
* @param oldFeature DOCUMENT ME!
*/
public int update(Feature feature, Feature oldFeature) {
int oldNum=-1;
int num = expansionAdapter.addObject(feature);
FeatureReference id=feature.getReference();
if (added.containsKey(id)){
oldNum=((Integer)added.get(id)).intValue();
added.put(id,new Integer(num));
}else{
if (modifiedFromOriginal.get(id)!=null) {
oldNum=((Integer)modifiedFromOriginal.get(id)).intValue();
}
modifiedFromOriginal.put(id,new Integer(num));
}
return oldNum;
}
/**
* DOCUMENT ME!
*
* @param id DOCUMENT ME!
*/
public void restore(FeatureReference id) {
deleted.remove(id);
deltaSize++;
}
public void restore(FeatureReference id,int num){
if (added.containsKey(id)){
added.put(id,new Integer(num));
}else{
modifiedFromOriginal.put(id,new Integer(num));
}
}
public boolean isDeleted(Feature feature){
return deleted.contains(feature.getReference());
}
public boolean isDeleted(FeatureReference featureID) {
return deleted.contains(featureID);
}
public void clear() {
added.clear();
modifiedFromOriginal.clear();
expansionAdapter.close();
deleted.clear();//<FeatureID>
deltaSize=0;
}
public boolean hasChanges() {
return added.size()>0 || modifiedFromOriginal.size() > 0 || deleted.size() > 0;
}
// public Iterator newsFeaturesIterator(long index) {
// if (index==0)
// return newsFeaturesIterator();
//
// return Arrays.asList(added.values()).listIterator((int)index);
// }
//
// public Iterator newsFeaturesIterator() {
// return added.values().iterator();
// }
public Iterator getDeleted() {
return new DeletedIterator();
}
class DeletedIterator implements Iterator {
private Boolean hasnext = null;
private Iterator iter;
private DefaultFeatureReference obj;
public DeletedIterator(){
iter = deleted.iterator();
}
public boolean hasNext() {
if (hasnext != null) {
return hasnext.booleanValue();
}
hasnext = Boolean.FALSE;
while (iter.hasNext()) {
obj = (DefaultFeatureReference) iter.next();
if (obj.isNewFeature()) {
continue;
}
hasnext = Boolean.TRUE;
break;
}
return hasnext.booleanValue();
}
public Object next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
hasnext = null;
return obj;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
public Iterator getInserted() {
return new InsertedIterator();
}
class InsertedIterator implements Iterator {
private Iterator addedIter;
private DefaultFeature obj;
private Boolean hasnext = null;
public InsertedIterator(){
addedIter = added.values().iterator();
}
public boolean hasNext() {
if (hasnext != null) {
return hasnext.booleanValue();
}
hasnext = Boolean.FALSE;
int pos;
while (addedIter.hasNext()) {
pos = ((Integer) addedIter.next()).intValue();
obj = (DefaultFeature) expansionAdapter.getObject(pos);
if (!deleted.contains(obj.getReference())) {
hasnext = Boolean.TRUE;
break;
}
}
return hasnext.booleanValue();
}
public Object next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
hasnext = null;
return obj.getData();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
public Iterator getUpdated() {
return new UpdatedIterator();
}
class UpdatedIterator implements Iterator{
private Boolean hasnext = null;
private Iterator iter;
private DefaultFeature obj;
private int pos;
public UpdatedIterator() {
iter = expansionAdapter.iterator();
pos = -1;
}
public boolean hasNext() {
if (hasnext != null) {
return hasnext.booleanValue();
}
hasnext = Boolean.FALSE;
while (iter.hasNext()) {
pos++;
obj = (DefaultFeature) iter.next();
if (deleted.contains(obj.getReference())){
continue;
}else if (!modifiedFromOriginal.containsValue(new Integer(pos))){
continue;
}else {
hasnext = Boolean.TRUE;
break;
}
}
return hasnext.booleanValue();
}
public Object next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
hasnext = null;
return obj.getData();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
public boolean hasNews() {
return !added.isEmpty();
}
public long getDeltaSize() {
return deltaSize;
}
}
| true |
07ff89c1b5b3b84ff884b15d4deb79063de9ab0e | Java | AlexCR97/PostgreSQL-Connection | /src/DBConnection/PostgreDB.java | UTF-8 | 1,012 | 2.765625 | 3 | [] | no_license | package DBConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PostgreDB {
private Connection connection;
private String url;
private String user;
private String pass;
private String dbName;
public Connection getConnection() {
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(url, user, pass);
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(PostgreDB.class.getName()).log(Level.SEVERE, null, ex);
}
return connection;
}
public PostgreDB(String user, String pass, String dbName) {
this.user = user;
this.pass = pass;
this.dbName = dbName;
url = "jdbc:postgresql://localhost:5432/" + this.dbName;
}
}
| true |
97246f67fe6c3e6c9eefee6420b972d0fdc455f1 | Java | kmahorker/BankWebApp | /src/org/innominds/intern/BankWebApp/Universal.java | UTF-8 | 547 | 2.6875 | 3 | [] | no_license | package org.innominds.intern.BankWebApp;
/**
* A class meant to be used for universal methods on the need basis that are used in many different classes
* @author Kaushik
*
*/
public class Universal {
/**
* Returns whether or not a String can be converted into an Integer or not
* @param input
* @return
*/
public static boolean isParsable(String input) {
boolean parsable = true;
try {
Integer.parseInt(input);
} catch (NumberFormatException e) {
parsable = false;
}
return parsable;
}
}
| true |
6d4e06f7d5450e81d83cfc34f9c92a274201ee15 | Java | nisha-nizamuddin/log4j2-elasticsearch | /log4j2-elasticsearch-core/src/test/java/org/appenders/log4j2/elasticsearch/LifeCycleTest.java | UTF-8 | 1,706 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | package org.appenders.log4j2.elasticsearch;
import org.junit.Test;
import org.mockito.Mockito;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.spy;
public class LifeCycleTest {
@Test
public void returnsLifeCycleOfGivenObjectIfAvailable() {
// given
TestObject expected = createDefaultTestLifecycle();
// when
LifeCycle lifeCycle = LifeCycle.of(expected);
// then
assertEquals(expected, lifeCycle);
}
@Test
public void returnsNoopLifeCycleIfNonLifeCycleObject() {
// given
Object expected = new Object();
// when
LifeCycle lifeCycle = LifeCycle.of(expected);
// then
assertNotEquals(expected, lifeCycle);
assertSame(LifeCycle.NOOP, lifeCycle);
}
@Test
public void stopDelegatesToParametrizedStop() {
// given
LifeCycle lifeCycle = spy(createDefaultTestLifecycle());
// when
lifeCycle.stop();
// then
Mockito.verify(lifeCycle).stop(anyLong(), anyBoolean());
}
public static TestObject createDefaultTestLifecycle() {
return new TestObject();
}
private static class TestObject implements LifeCycle {
@Override
public void start() {
}
@Override
public boolean isStarted() {
return false;
}
@Override
public boolean isStopped() {
return false;
}
}
}
| true |
0812cb82dbd6d2d77a0021926aa5121ad66a74e9 | Java | zjyzwy/air | /src/com/scnu/model/vo/Player.java | GB18030 | 2,878 | 2.6875 | 3 | [] | no_license | package com.scnu.model.vo;
import java.awt.Graphics;
import java.util.List;
import javax.swing.ImageIcon;
import com.scnu.model.load.ElementLoad;
import com.scnu.model.manager.ElementManager;
import com.scnu.thread.GameThread;
import com.scnu.thread.GameThread.GameState;
public class Player extends SuperElement{
public static int hp; //Ѫ
public static int num; //
private int moveX;
private ImageIcon img;
private boolean attack;
private String fireName;
private boolean up,right,down,left;//ƶ
public Player() {}
static {
num=0;
hp=10;
}
public Player(int x,int y,int w,int h,String fireName,ImageIcon img) {
super(x,y,w,h);
this.moveX=0;
this.img=img;
this.fireName=fireName;
}
public static Player createPlayer(String str) {
String a[]=str.split(",");
int x=Integer.parseInt(a[2]);
int y=Integer.parseInt(a[3]);
int w=Integer.parseInt(a[4]);
int h=Integer.parseInt(a[5]);
ImageIcon img=ElementLoad.getElementLoad()
.getMap().get(a[0]);
// String url="img/play/3.png";
return new Player(x, y, w, h, a[1], img);
}
public void update() {
super.update();
addPlayerFire();
updateImage();
}
@Override
public void move() {
if(up&&getY()>0)setY(getY()-10);
if(down&&getY()+getH()<790)setY(getY()+10);
if(left&&getX()>0)setX(getX()-10);
if(right&&getX()+getW()<490)setX(getX()+10);
}
@Override
public void destroy() {
if(!isVisible()) {
Boom();
GameThread.state=GameState.GameOvor;
}
}
public void updateImage() {
moveX=(moveX==0)?1:0;
}
@Override
public void showElement(Graphics g) {
g.drawImage(img.getImage(),
getX(),getY(),
getX()+getW(),getY()+getH(),
60*moveX,0, //ͼƬϽ
60*(moveX+1),60, //ͼƬ½
null);
}
public void addPlayerFire() {
if(attack) {
List<SuperElement> list1=ElementManager
.getManager().getElementList("c");
list1.add(PlayerFire.createPlayFire(getX(), getY(), fireName));
list1.add(PlayerFire.createPlayFire(getX()+getW()-10, getY(), fireName));
attack=false;
}
}
public void Boom() {
List<SuperElement> list=ElementManager
.getManager().getElementList("d");
list.add(Explode.createExplode(getX(), getY(), getW(), getH(), null));
}
public int getHp() {
return hp;
}
public int getNum() {
return num;
}
public ImageIcon getImg() {
return img;
}
public void setImg(ImageIcon img) {
this.img = img;
}
//÷ɻ˶
public void setUp(boolean up) {
this.up = up;
}
public void setRight(boolean right) {
this.right = right;
}
public void setDown(boolean down) {
this.down = down;
}
public void setLeft(boolean left) {
this.left = left;
}
//״̬
public boolean isAttack() {
return attack;
}
public void setAttack(boolean attack) {
this.attack = attack;
}
}
| true |
085340f9a6778d8d78240888dbcf32326831eb24 | Java | adrianopauli/app_android_meditec | /app/src/br/net/meditec/controller/dao/DAO.java | UTF-8 | 357 | 2 | 2 | [
"Apache-2.0"
] | permissive | package br.net.meditec.controller.dao;
import android.content.ContentValues;
import android.database.Cursor;
import java.util.List;
public interface DAO<T> {
List<T> cursorToList(Cursor cursor);
T cursorToObject(Cursor cursor);
void delete();
boolean insert(T t);
boolean insertAll(List<T> list);
ContentValues values(T t);
}
| true |
1e4081f2acc79e8b29015ce7ef1e96999b00d7f5 | Java | Jesudos/CarRentalService | /src/main/java/edu/uga/csci4050/group3/core/InvalidInputException.java | UTF-8 | 1,017 | 2.890625 | 3 | [] | no_license | package edu.uga.csci4050.group3.core;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import edu.uga.csci4050.group3.template.Alert;
import edu.uga.csci4050.group3.template.AlertType;
public class InvalidInputException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
private ArrayList<String> messages;
public InvalidInputException(){
messages = new ArrayList<String>();
}
public InvalidInputException(String message){
messages = new ArrayList<String>();
messages.add(message);
}
public void addMessage(String message){
messages.add(message);
}
public ArrayList<String> getMessages(){
return messages;
}
public int countMessages(){
return messages.size();
}
public String getMessagesHtml(ServletContext context){
String html = "";
for(String message : messages){
Alert alert = new Alert(context);
alert.setType(AlertType.ERROR);
alert.setContent(message);
html += alert.render();
}
return html;
}
}
| true |
cacf68b8beaa638cb7575d5882288f3bde6b5442 | Java | fdhia/academic-projects | /src/allwin/pkg2016/Entities/SessionDeFormation.java | UTF-8 | 2,338 | 2.359375 | 2 | [] | 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 allwin.pkg2016.Entities;
import java.util.ArrayList;
import java.sql.Date;
import java.util.Iterator;
import java.util.List;
/**
*
* @author WiKi
*/
public class SessionDeFormation {
private int IdFormation;
private Date dateDebut;
private Date dateFin;
private int nbrCandidats;
private float prix;
private String lieu;
private List<Arbitre> arbitres;
public SessionDeFormation() {
arbitres = new ArrayList<Arbitre>();
}
public SessionDeFormation(Date dateDebut, Date dateFin, int nbrCandidats, float prix, String lieu) {
this.dateDebut = dateDebut;
this.dateFin = dateFin;
this.nbrCandidats = nbrCandidats;
this.prix = prix;
this.lieu = lieu;
}
public int getIdFormation() {
return IdFormation;
}
public void setIdFormation(int IdFormation) {
this.IdFormation = IdFormation;
}
public Date getDateDebut() {
return dateDebut;
}
public void setDateDebut(Date dateDebut) {
this.dateDebut = dateDebut;
}
public Date getDateFin() {
return dateFin;
}
public void setDateFin(Date dateFin) {
this.dateFin = dateFin;
}
public int getNbrCandidats() {
return nbrCandidats;
}
public void setNbrCandidats(int nbrCandidats) {
this.nbrCandidats = nbrCandidats;
}
public float getPrix() {
return prix;
}
public void setPrix(float prix) {
this.prix = prix;
}
public String getLieu() {
return lieu;
}
public void setLieu(String lieu) {
this.lieu = lieu;
}
@Override
public String toString() {
String resultat = "SessionDeFormation{" + "IdFormation=" + IdFormation + ", dateDebut=" + dateDebut + ", dateFin=" + dateFin + ", nbrCandidats=" + nbrCandidats + ", prix=" + prix + ", lieu=" + lieu + "'}'";
Arbitre e;
Iterator<Arbitre> it;
it = arbitres.iterator();
while (it.hasNext()) {
e = it.next();
resultat += "/l'id Arbitre=" + e.getId();
}
return resultat;
}
}
| true |
bc64f50ea89ba3ef5611f808aeac2e3bba9ab72c | Java | sant0sl/ProjetoIntegradorV | /ProjetoIntegradorV/src/br/test/TesteEmail.java | UTF-8 | 629 | 1.835938 | 2 | [] | no_license | package br.test;
import org.junit.Test;
import br.model.Player;
import br.service.PlayerService;
public class TesteEmail {
@Test
public void testejunit() {
Player p = new Player();
PlayerService ps = new PlayerService();
/*String destinatario = "sant0sl@outlook.com";
String assunto = "TesteEmail";
String texto = "teste";
EmailUtil.sendEmail(destinatario, assunto, texto);*/
/*String senhaaleatoria = EmailUtil.geradorSenhaAutomatico();
System.out.println(senhaaleatoria);*/
/*p.setUsername("sant0sl");
p.setEmail("sant0sl@outlook.com");
ps.passwordRecovery(p);*/
}
}
| true |
dd094fa6509930e8f26c0528a0ae69dc46772e92 | Java | Hide-on-bush999/Hide-on-bush | /keyword/Private/four.java | UTF-8 | 256 | 2.296875 | 2 | [] | no_license | package keyword.Private;
public class four {
public static void main(String[] args) {
Three three = new Three();
three.setAge(18);
three.setName("赵泽鑫");
three.setMale(true);
three.show();
}
} | true |
88cde791f66bef5a145c4e2be5e0e31217f39fd6 | Java | leogle232323/JavaStudy | /test/src/test/BasicType.java | UTF-8 | 2,285 | 3.765625 | 4 | [] | no_license | package test;
public class BasicType {
static boolean defaultBoolean;
static Object obj;
public static void main(String[] args) {
// 1.在堆栈中创建对象
char c = 'x';
// 2.在堆中创建对象,Character是基本类型char的包装器类
Character ch = new Character(c);
Character ch1 = new Character('x');
System.out.println(c);
System.out.println(ch);
System.out.println(ch1);
// Primitive type & Wrapper type
// 1.boolean|Boolean
boolean primitiveBoolean = false;
// boolean defaultBoolean;
boolean wrapperBoolean = new Boolean(true);
System.out.println(primitiveBoolean);
System.out.println("boolean类型的默认值为:" + defaultBoolean);
System.out.println(wrapperBoolean);
// 2.char|Character Size:16-bit Minimum:Unicode 0 Maximum:Unicode
// 2(16)-1
char primitiveChar = '/';
Character wrapperCharcter = new Character(';');
System.out.println(primitiveChar);
System.out.println(wrapperCharcter);
// 3.byte|Byte Size:8-bit Minimum:-128 Maximum:127
byte primitiveByte = 1;
Byte wrapperByte = new Byte((byte) 2);
System.out.println(primitiveByte);
System.out.println(wrapperByte);
// 4.short|Short Size:16-bit Minimum:-2(15) Maximum:2(15)-1
short primitiveShort = 3;
Short wrapperShort = new Short((short) 4);
System.out.println(primitiveShort);
System.out.println(wrapperShort);
// 5.int|Integer Size:32-bit Minimum:-2(31) Maximum:2(31)-1
int primitiveInt = 6;
Integer wrapperInteger = new Integer(7);
System.out.println(primitiveInt);
System.out.println(wrapperInteger);
// 6.long|Long Size:64-bit Minimum:-2(63) Maximum:2(63)-1
long primitiveLong = 8;
Long wrapperLong = new Long(9l);
System.out.println(primitiveLong);
System.out.println(wrapperLong);
// 7.float|Float Size:32-bit Minimum:IEEE754 Maximum:IEEE754
float primitiveFloat = 10;
Float wrapperFloat = new Float(11);
System.out.println(primitiveFloat);
System.out.println(wrapperFloat);
// 8.double|Double Size:64-bit Minimum:IEEE754 Maximum:IEEE754
double primitiveDouble = 12;
Double wrapperDouble = new Double(13);
System.out.println(primitiveDouble);
System.out.println(wrapperDouble);
// 9.void|Void
}
}
| true |
eba3220244549c2efcae465ff8eab00a33a6bb75 | Java | MolMaDuv/Proyecto-SafePet | /src/interfaz/VentanaConfeccionarPlan.java | ISO-8859-3 | 15,096 | 2.171875 | 2 | [] | no_license | package interfaz;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import mundo.Afiliado;
import mundo.Beneficiario;
import mundo.Empleado;
import mundo.Plan;
import mundo.SafePet;
public class VentanaConfeccionarPlan extends JFrame implements ActionListener {
private VentanaFuncionario miVentanaFuncionario;
private SafePet miSafePet;
private Afiliado miAfiliado;
private Empleado miEmpleado;
private ArrayList<Beneficiario> misBeneficiarios = new ArrayList<Beneficiario>();
private JPanel contentPane;
private static final String FONDO = "./img/fondoGrande.png";
private static final String BTNATRAS = "./img/BtnAtras.png";
private static final String BTNAGREGAR = "./img/BtnAgregar.png";
private static final String LOGOESQUINA = "./img/LogoEsquina.png";
private static final String LATERALDERECHO = "./img/LateralDerechoGrande.png";
private static final String LATERALIZQUIERDO = "./img/LateralIzquierdoGrande.png";
private JButton btnAtras;
private JButton btnAgregar;
private JButton btnRegistrar;
private JCheckBox jcbConsultasIlimitadas;
private JCheckBox jcbAmbulancia;
private JCheckBox jcbAsistenciaCasa;
private ButtonGroup grupoTiempo;
private JRadioButton jrbTresMeses;
private JRadioButton jrbSeisMeses;
private JRadioButton jrbDoceMeses;
private JTextField JTextNombreMascota;
private JTextField JTextRaza;
private JTextField JTextCodigo;
private JTextField JTextAltura;
JScrollPane panelTabla = new JScrollPane();
DefaultTableModel modelo;
JTable tabla;
private int contadorMascotas;
boolean consultas = false;
boolean ambulancia = false;
boolean asistencia = false;
boolean tres = false;
boolean seis = false;
boolean doce = false;
private JTextField JTextEdad;
private JTextField JTextColor;
private int idAfiliadoP;
String botones [] = {"Cuenta corriente", "Cuenta de ahorros", "Tarjeta credito", "Trajeta debito", "Oficina SafePet"};
/**
* Create the frame.
*
* @param miSafePet
* @param miAfiliado
* @param miVentanaInicio
*/
public VentanaConfeccionarPlan(VentanaFuncionario miVentanaFuncionario, SafePet miSafePet, Afiliado miAfiliado,
Empleado miEmpleado) {
this.miVentanaFuncionario = miVentanaFuncionario;
this.miSafePet = miSafePet;
this.miAfiliado = miAfiliado;
this.miEmpleado = miEmpleado;
idAfiliadoP = miAfiliado.getId();
setTitle("SafePet UQ");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 620, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblTitulo = new JLabel("INGRESE LOS SIGUIENTES DATOS");
lblTitulo.setFont(new Font("Tahoma", Font.BOLD, 13));
lblTitulo.setForeground(Color.WHITE);
lblTitulo.setHorizontalAlignment(SwingConstants.CENTER);
lblTitulo.setBounds(10, 78, 584, 20);
contentPane.add(lblTitulo);
JLabel lblTextoSuperior = new JLabel("PARA CONFECCIONAR EL PLAN");
lblTextoSuperior.setHorizontalAlignment(SwingConstants.CENTER);
lblTextoSuperior.setFont(new Font("Tahoma", Font.BOLD, 11));
lblTextoSuperior.setForeground(Color.WHITE);
lblTextoSuperior.setBounds(10, 98, 584, 20);
contentPane.add(lblTextoSuperior);
JLabel lblFuncionario = new JLabel("Funcionario " + miEmpleado.getNombre() + " - " + miEmpleado.getId());
lblFuncionario.setForeground(Color.WHITE);
lblFuncionario.setBounds(128, 11, 275, 20);
contentPane.add(lblFuncionario);
JLabel lblAfiliado = new JLabel("Afiliado " + miAfiliado.getNombre());
lblAfiliado.setForeground(Color.WHITE);
lblAfiliado.setBounds(128, 47, 170, 20);
contentPane.add(lblAfiliado);
JLabel lblId = new JLabel("Id " + miAfiliado.getId());
lblId.setForeground(Color.WHITE);
lblId.setBounds(308, 47, 110, 20);
contentPane.add(lblId);
JLabel lblLogoEsquina1 = new JLabel(new ImageIcon(LOGOESQUINA));
lblLogoEsquina1.setBounds(25, 11, 80, 80);
contentPane.add(lblLogoEsquina1);
JLabel lblLogoEsquina2 = new JLabel(new ImageIcon(LOGOESQUINA));
lblLogoEsquina2.setBounds(495, 11, 80, 80);
contentPane.add(lblLogoEsquina2);
JLabel lblLateralIzquierdo = new JLabel(new ImageIcon(LATERALIZQUIERDO));
lblLateralIzquierdo.setBounds(40, 98, 50, 411);
contentPane.add(lblLateralIzquierdo);
JLabel lblLateralDerecho = new JLabel(new ImageIcon(LATERALDERECHO));
lblLateralDerecho.setBounds(515, 98, 50, 411);
contentPane.add(lblLateralDerecho);
btnAtras = new JButton(new ImageIcon(BTNATRAS));
btnAtras.setBounds(10, 520, 110, 30);
btnAtras.addActionListener(this);
contentPane.add(btnAtras);
btnRegistrar = new JButton(new ImageIcon(BTNAGREGAR));
btnRegistrar.setBounds(484, 520, 110, 30);
btnRegistrar.addActionListener(this);
contentPane.add(btnRegistrar);
btnAgregar = new JButton(new ImageIcon(BTNAGREGAR));
btnAgregar.setBounds(252, 275, 110, 30);
btnAgregar.addActionListener(this);
contentPane.add(btnAgregar);
JLabel lblDatosMascota = new JLabel("DATOS MASCOTA(S)");
lblDatosMascota.setForeground(Color.WHITE);
lblDatosMascota.setHorizontalAlignment(SwingConstants.CENTER);
lblDatosMascota.setBounds(69, 129, 450, 20);
contentPane.add(lblDatosMascota);
JLabel lblNombreMascota = new JLabel("Nombre");
lblNombreMascota.setForeground(Color.WHITE);
lblNombreMascota.setBounds(131, 160, 60, 20);
contentPane.add(lblNombreMascota);
JTextNombreMascota = new JTextField();
JTextNombreMascota.setBounds(201, 160, 86, 20);
contentPane.add(JTextNombreMascota);
JTextNombreMascota.setColumns(10);
JLabel lblRazaMascota = new JLabel("Raza");
lblRazaMascota.setForeground(Color.WHITE);
lblRazaMascota.setBounds(297, 160, 60, 20);
contentPane.add(lblRazaMascota);
JTextRaza = new JTextField();
JTextRaza.setBounds(367, 160, 86, 20);
contentPane.add(JTextRaza);
JTextRaza.setColumns(10);
JLabel lblCodigoMascota = new JLabel("Codigo");
lblCodigoMascota.setForeground(Color.WHITE);
lblCodigoMascota.setBounds(131, 191, 60, 20);
contentPane.add(lblCodigoMascota);
JTextCodigo = new JTextField();
JTextCodigo.setBounds(201, 191, 86, 20);
contentPane.add(JTextCodigo);
JTextCodigo.setColumns(10);
JLabel lblAlturaMascota = new JLabel("Altura");
lblAlturaMascota.setForeground(Color.WHITE);
lblAlturaMascota.setBounds(297, 191, 60, 20);
contentPane.add(lblAlturaMascota);
JTextAltura = new JTextField();
JTextAltura.setBounds(367, 191, 86, 20);
contentPane.add(JTextAltura);
JTextAltura.setColumns(10);
JLabel lblEdad = new JLabel("Edad");
lblEdad.setForeground(Color.WHITE);
lblEdad.setBounds(128, 222, 65, 20);
contentPane.add(lblEdad);
JTextEdad = new JTextField();
JTextEdad.setBounds(201, 222, 86, 20);
contentPane.add(JTextEdad);
JTextEdad.setColumns(10);
JLabel lblColor = new JLabel("Color");
lblColor.setForeground(Color.WHITE);
lblColor.setBounds(297, 222, 60, 20);
contentPane.add(lblColor);
JTextColor = new JTextField();
JTextColor.setBounds(367, 222, 86, 20);
contentPane.add(JTextColor);
JTextColor.setColumns(10);
modelo = new DefaultTableModel();
modelo.addColumn("Codigo");
modelo.addColumn("Nombre");
modelo.addColumn("Raza");
modelo.addColumn("Altura");
modelo.addColumn("Edad");
modelo.addColumn("Color");
tabla = new JTable(modelo);
tabla.setBounds(132, 266, 340, 80);
contentPane.add(tabla);
panelTabla = new JScrollPane(tabla, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panelTabla.setBounds(100, 316, 405, 80);
contentPane.add(panelTabla);
JLabel lblServicios = new JLabel("SERVICIOS");
lblServicios.setHorizontalAlignment(SwingConstants.CENTER);
lblServicios.setForeground(Color.WHITE);
lblServicios.setBounds(124, 407, 160, 20);
contentPane.add(lblServicios);
jcbConsultasIlimitadas = new JCheckBox();
jcbConsultasIlimitadas.setForeground(Color.WHITE);
jcbConsultasIlimitadas.setText("Consultas ilimitadas");
jcbConsultasIlimitadas.setBounds(134, 434, 150, 23);
jcbConsultasIlimitadas.setOpaque(false);
contentPane.add(jcbConsultasIlimitadas);
jcbAmbulancia = new JCheckBox();
jcbAmbulancia.setForeground(Color.WHITE);
jcbAmbulancia.setText("Ambulancia");
jcbAmbulancia.setBounds(134, 460, 150, 23);
jcbAmbulancia.setOpaque(false);
contentPane.add(jcbAmbulancia);
jcbAsistenciaCasa = new JCheckBox();
jcbAsistenciaCasa.setForeground(Color.WHITE);
jcbAsistenciaCasa.setText("Asistencia en casa");
jcbAsistenciaCasa.setBounds(134, 486, 150, 23);
jcbAsistenciaCasa.setOpaque(false);
contentPane.add(jcbAsistenciaCasa);
JLabel lblTiempo = new JLabel("TIEMPO");
lblTiempo.setForeground(Color.WHITE);
lblTiempo.setHorizontalAlignment(SwingConstants.CENTER);
lblTiempo.setBounds(308, 407, 160, 20);
contentPane.add(lblTiempo);
grupoTiempo = new ButtonGroup();
jrbTresMeses = new JRadioButton();
jrbTresMeses.setForeground(Color.WHITE);
jrbTresMeses.setText("3 meses");
jrbTresMeses.setBounds(354, 434, 90, 23);
jrbTresMeses.setOpaque(false);
contentPane.add(jrbTresMeses);
jrbSeisMeses = new JRadioButton();
jrbSeisMeses.setForeground(Color.WHITE);
jrbSeisMeses.setText("6 meses");
jrbSeisMeses.setBounds(354, 460, 90, 23);
jrbSeisMeses.setOpaque(false);
contentPane.add(jrbSeisMeses);
jrbDoceMeses = new JRadioButton();
jrbDoceMeses.setForeground(Color.WHITE);
jrbDoceMeses.setText("12 meses");
jrbDoceMeses.setBounds(354, 486, 90, 23);
jrbDoceMeses.setOpaque(false);
contentPane.add(jrbDoceMeses);
grupoTiempo.add(jrbTresMeses);
grupoTiempo.add(jrbSeisMeses);
grupoTiempo.add(jrbDoceMeses);
JLabel lblFondo = new JLabel(new ImageIcon(FONDO));
lblFondo.setBounds(0, 0, 604, 561);
contentPane.add(lblFondo);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnAtras) {
miVentanaFuncionario.setVisible(true);
miVentanaFuncionario.setLocationRelativeTo(null);
setVisible(false);
}
if (e.getSource() == btnAgregar) {
String nombre = JTextNombreMascota.getText();
String raza = JTextRaza.getText();
String codigo = JTextCodigo.getText();
String altura = JTextAltura.getText();
String edad = JTextEdad.getText();
String color = JTextColor.getText();
if (nombre == "" || raza == "" || codigo == "" || altura == "" || edad == "" || color == "") {
JOptionPane.showMessageDialog(null, "Por favor ingrese todos los datos solicitados",
"Datos mascota incompletos", JOptionPane.WARNING_MESSAGE);
} else {
boolean validacionEdad= miSafePet.isInteger(edad);
boolean validacionAltura= miSafePet.isInteger(altura);
boolean validacionCodigo = miSafePet.isInteger(codigo);
if(validacionEdad && validacionAltura && validacionCodigo) {
if(miSafePet.codigoMascotaRepetido(misBeneficiarios, Integer.parseInt(codigo))){
String beneficiario[] = { codigo, nombre, raza, altura, edad, color };
modelo.addRow(beneficiario);
Beneficiario miBeneficiario = new Beneficiario(Integer.parseInt(edad), nombre, raza,
Integer.parseInt(codigo), Integer.parseInt(altura), color);
misBeneficiarios.add(miBeneficiario);
contadorMascotas++;
limpiarInterfaz();
}else{
JOptionPane.showMessageDialog(null, "Ingrese un codigo que no este repetido", "CODIGO REPETIDO", JOptionPane.WARNING_MESSAGE);
}
}else {
JOptionPane.showMessageDialog(null, "Por favor ingresar en los campos [edad, codigo,altura] un dato numerico", "Error",
JOptionPane.WARNING_MESSAGE);
}
}
}
if (e.getSource() == btnRegistrar) {
if ((jcbConsultasIlimitadas.isSelected() == false && jcbAmbulancia.isSelected() == false
&& jcbAsistenciaCasa.isSelected() == false)
|| (jrbTresMeses.isSelected() == false && jrbSeisMeses.isSelected() == false
&& jrbDoceMeses.isSelected() == false)) {
JOptionPane.showMessageDialog(null, "Por favor ingrese todos los datos solicitados", "Campos vacios",
JOptionPane.WARNING_MESSAGE);
} else {
int tiempo = 0;
if (jcbConsultasIlimitadas.isSelected()) {
consultas = true;
}
if (jcbAmbulancia.isSelected()) {
ambulancia = true;
}
if (jcbAsistenciaCasa.isSelected()) {
asistencia = true;
}
if (jrbTresMeses.isSelected()) {
tres = true;
tiempo = 3;
}
if (jrbSeisMeses.isSelected()) {
seis = true;
tiempo = 6;
}
if (jrbDoceMeses.isSelected()) {
doce = true;
tiempo = 12;
}
String respuestaSimulacion = miSafePet.calcularPlanSimulacion(contadorMascotas, consultas, ambulancia,
asistencia, tres, seis, doce);
int i = JOptionPane.showConfirmDialog(this, respuestaSimulacion + "\n\nDesea continuar con el plan?");
if (i == 0) {
double valor = miSafePet.valorPlan(contadorMascotas, consultas, ambulancia, asistencia, tres, seis,
doce);
double copago = miSafePet.calcularCopago(valor);
int x = JOptionPane.showOptionDialog(null, "Seleccione el metodo de pago", "Cargo Pago", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, botones, botones[0]);
String metodoPago = "";
if(x == 0) {
metodoPago = "Cuenta corriente";
}
if(x == 1) {
metodoPago = "Cuenta de ahorros";
}
if(x == 2) {
metodoPago = "Tarjeta credito";
}
if(x == 3) {
metodoPago = "Trajeta debito";
}
if(x == 4) {
metodoPago = "Oficina SafePet";
}
Plan miPlan = new Plan(0, consultas, ambulancia, asistencia, valor, copago, miAfiliado,
misBeneficiarios, tiempo, metodoPago);
miSafePet.agregarPlan(miPlan);
JOptionPane.showMessageDialog(null, "Plan creado exitosamente", "Plan creado",
JOptionPane.WARNING_MESSAGE);
miVentanaFuncionario.setVisible(true);
miVentanaFuncionario.setLocationRelativeTo(null);
setVisible(false);
}
if (i == 1) {
JOptionPane.showMessageDialog(null, "Se procedera a cancelar la creacion del plan",
"Plan cancelado", JOptionPane.WARNING_MESSAGE);
miVentanaFuncionario.setVisible(true);
miVentanaFuncionario.setLocationRelativeTo(null);
setVisible(false);
}
}
}
}
public void limpiarInterfaz() {
JTextNombreMascota.setText("");
JTextRaza.setText("");
JTextCodigo.setText("");
JTextAltura.setText("");
JTextEdad.setText("");
JTextColor.setText("");
}
}
| true |
3284e95cfc0f5a7f5365189e86eb9977e1bc3ab4 | Java | paul-freez/example.reddittop | /app/src/main/java/com/testsite/reddittop/utils/exceptions/NoConnectivityException.java | UTF-8 | 362 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | package com.testsite.reddittop.utils.exceptions;
import com.testsite.reddittop.App;
import com.testsite.reddittop.R;
import java.io.IOException;
/**
* Created by paulf
*/
public class NoConnectivityException extends IOException {
@Override
public String getMessage() {
return App.getContext().getString(R.string.error_noconnection);
}
}
| true |
9dd57b6fbc74416dbe13868f62e672dc31cdadc1 | Java | alipay/alipay-sdk-java-all | /v2/src/main/java/com/alipay/api/response/KoubeiCateringPosDishBatchqueryResponse.java | UTF-8 | 722 | 1.796875 | 2 | [
"Apache-2.0"
] | permissive | package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.domain.PosCookDishQryModel;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: koubei.catering.pos.dish.batchquery response.
*
* @author auto create
* @since 1.0, 2019-01-07 20:51:15
*/
public class KoubeiCateringPosDishBatchqueryResponse extends AlipayResponse {
private static final long serialVersionUID = 5129181436844787746L;
/**
* 菜谱中的菜品的列表
*/
@ApiField("cook_dish")
private PosCookDishQryModel cookDish;
public void setCookDish(PosCookDishQryModel cookDish) {
this.cookDish = cookDish;
}
public PosCookDishQryModel getCookDish( ) {
return this.cookDish;
}
}
| true |
28456ca6749e73613bcfcfe580f929aaad8479b5 | Java | MewX/kantv-decompiled-v3.1.2 | /sources/org/fourthline/cling/support/avtransport/callback/GetCurrentTransportActions.java | UTF-8 | 1,269 | 1.90625 | 2 | [] | no_license | package org.fourthline.cling.support.avtransport.callback;
import java.util.logging.Logger;
import org.fourthline.cling.controlpoint.ActionCallback;
import org.fourthline.cling.model.action.ActionInvocation;
import org.fourthline.cling.model.meta.Service;
import org.fourthline.cling.model.types.UnsignedIntegerFourBytes;
import org.fourthline.cling.support.model.TransportAction;
public abstract class GetCurrentTransportActions extends ActionCallback {
private static Logger log = Logger.getLogger(GetCurrentTransportActions.class.getName());
public abstract void received(ActionInvocation actionInvocation, TransportAction[] transportActionArr);
public GetCurrentTransportActions(Service service) {
this(new UnsignedIntegerFourBytes(0), service);
}
public GetCurrentTransportActions(UnsignedIntegerFourBytes unsignedIntegerFourBytes, Service service) {
super(new ActionInvocation(service.getAction("GetCurrentTransportActions")));
getActionInvocation().setInput("InstanceID", unsignedIntegerFourBytes);
}
public void success(ActionInvocation actionInvocation) {
received(actionInvocation, TransportAction.valueOfCommaSeparatedList((String) actionInvocation.getOutput("Actions").getValue()));
}
}
| true |
88324a0a5d94ed2fbf3a58facde3e4b95029b15f | Java | JakubGajewski/DesignPatterns | /src/factory/Main.java | UTF-8 | 244 | 2.28125 | 2 | [] | no_license | package factory;
public class Main {
public static void main(String[] args) {
CookieFactory cookieFactory = new CookieFactory();
Cookie teryzol = cookieFactory.makeCookie("chocolate");
teryzol.eatCookie();
}
}
| true |
852035a118c3cb0cf8fc0a12e1aa50c31462113d | Java | pyromobile/nubomedia-ouatclient-src | /android/LiveTales/app/src/main/java/com/zed/livetales/models/book/BookDescription.java | UTF-8 | 421 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | package com.zed.livetales.models.book;
/**
* Created by jemalpartida on 25/11/2016.
*/
public class BookDescription
{
public BookDescription(String id, String title)
{
this.id = id;
this.title = title;
}
public String getId()
{
return this.id;
}
public String getTitle()
{
return this.title;
}
private String id;
private String title;
}
| true |
2a323227239c1aa69da930bde6655b30522dc8ef | Java | tdegueul/gemoc-pirover | /rover.raspirover/src-gen/rover/raspirover/aspects/CentimeterAspectCentimeterAspectContext.java | UTF-8 | 992 | 2.359375 | 2 | [] | no_license | package rover.raspirover.aspects;
import java.util.Map;
import rover.raspirover.raspirover.Centimeter;
import rover.raspirover.aspects.CentimeterAspectCentimeterAspectProperties;
@SuppressWarnings("all")
public class CentimeterAspectCentimeterAspectContext {
public final static CentimeterAspectCentimeterAspectContext INSTANCE = new CentimeterAspectCentimeterAspectContext();
public static CentimeterAspectCentimeterAspectProperties getSelf(final Centimeter _self) {
if (!INSTANCE.map.containsKey(_self))
INSTANCE.map.put(_self, new rover.raspirover.aspects.CentimeterAspectCentimeterAspectProperties());
return INSTANCE.map.get(_self);
}
private Map<Centimeter, CentimeterAspectCentimeterAspectProperties> map = new java.util.WeakHashMap<rover.raspirover.raspirover.Centimeter, rover.raspirover.aspects.CentimeterAspectCentimeterAspectProperties>();
public Map<Centimeter, CentimeterAspectCentimeterAspectProperties> getMap() {
return map;
}
}
| true |
c709e28ae1f4ac6926c59c0f0479c40f85ddf764 | Java | LineageOS/android_packages_services_Telecomm | /src/com/android/server/telecom/RespondViaSmsSettings.java | UTF-8 | 5,667 | 2.1875 | 2 | [] | no_license | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.telecom;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
// TODO: This class is newly copied into Telecom (com.android.server.telecom) from it previous
// location in Telephony (com.android.phone). User's preferences stored in the old location
// will be lost. We need code here to migrate KLP -> LMP settings values.
/**
* Settings activity to manage the responses available for the "Respond via SMS Message" feature to
* respond to incoming calls.
*/
public class RespondViaSmsSettings extends PreferenceActivity
implements Preference.OnPreferenceChangeListener {
private SharedPreferences mPrefs;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.d(this, "Settings: onCreate()...");
// This function guarantees that QuickResponses will be in our
// SharedPreferences with the proper values considering there may be
// old QuickResponses in Telephony pre L.
QuickResponseUtils.maybeMigrateLegacyQuickResponses(this);
getPreferenceManager().setSharedPreferencesName(QuickResponseUtils.SHARED_PREFERENCES_NAME);
mPrefs = getPreferenceManager().getSharedPreferences();
}
@Override
public void onResume() {
super.onResume();
PreferenceScreen preferenceScreen = getPreferenceScreen();
if (preferenceScreen != null) {
preferenceScreen.removeAll();
}
// This preference screen is ultra-simple; it's just 4 plain
// <EditTextPreference>s, one for each of the 4 "canned responses".
//
// The only nontrivial thing we do here is copy the text value of
// each of those EditTextPreferences and use it as the preference's
// "title" as well, so that the user will immediately see all 4
// strings when they arrive here.
//
// Also, listen for change events (since we'll need to update the
// title any time the user edits one of the strings.)
addPreferencesFromResource(R.xml.respond_via_sms_settings);
initPref(findPreference(QuickResponseUtils.KEY_CANNED_RESPONSE_PREF_1));
initPref(findPreference(QuickResponseUtils.KEY_CANNED_RESPONSE_PREF_2));
initPref(findPreference(QuickResponseUtils.KEY_CANNED_RESPONSE_PREF_3));
initPref(findPreference(QuickResponseUtils.KEY_CANNED_RESPONSE_PREF_4));
ActionBar actionBar = getActionBar();
if (actionBar != null) {
// android.R.id.home will be triggered in onOptionsItemSelected()
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
// Preference.OnPreferenceChangeListener implementation
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.d(this, "onPreferenceChange: key = %s", preference.getKey());
Log.d(this, " preference = '%s'", preference);
Log.d(this, " newValue = '%s'", newValue);
EditTextPreference pref = (EditTextPreference) preference;
// Copy the new text over to the title, just like in onCreate().
// (Watch out: onPreferenceChange() is called *before* the
// Preference itself gets updated, so we need to use newValue here
// rather than pref.getText().)
String quickResponse = ((String) newValue).trim();
if (TextUtils.isEmpty(quickResponse)) {
return false;
}
pref.setTitle((String) newValue);
// Save the new preference value.
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(pref.getKey(), (String) newValue).commit();
return true; // means it's OK to update the state of the Preference with the new value
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home:
goUpToTopLevelSetting(this);
return true;
default:
}
return super.onOptionsItemSelected(item);
}
/**
* Finish current Activity and go up to the top level Settings.
*/
public static void goUpToTopLevelSetting(Activity activity) {
activity.finish();
}
/**
* Initialize the preference to the persisted preference value or default text.
*/
private void initPref(Preference preference) {
EditTextPreference pref = (EditTextPreference) preference;
pref.setText(mPrefs.getString(pref.getKey(), pref.getText()));
pref.setTitle(pref.getText());
pref.setOnPreferenceChangeListener(this);
}
}
| true |
67bfca62adc7e2dede8533a2c73c6f9a9cdc8373 | Java | lanxuewsr/BoxHelper | /src/models/torrent/deTorrent/Result.java | UTF-8 | 889 | 2.109375 | 2 | [] | no_license | package models.torrent.deTorrent;
import java.util.Map;
/**
* Created by SpereShelde on 2018/10/18.
*/
public class Result {
private Stats stats;
private boolean connected;
private Map<String,Torrents> torrents;
private Filters filters;
public Stats getStats() {
return stats;
}
public void setStats(Stats stats) {
this.stats = stats;
}
public boolean isConnected() {
return connected;
}
public void setConnected(boolean connected) {
this.connected = connected;
}
public Map<String, Torrents> getTorrents() {
return torrents;
}
public void setTorrents(Map<String, Torrents> torrents) {
this.torrents = torrents;
}
public Filters getFilters() {
return filters;
}
public void setFilters(Filters filters) {
this.filters = filters;
}
}
| true |
6bd25a5853b2d309dcc524b258112601c160a898 | Java | smittynusmc/Sudoku-Solver | /Sudoku Solver/src/sudoku_solver/Formula.java | UTF-8 | 9,567 | 2.65625 | 3 | [] | no_license | package sudoku_solver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import org.sat4j.minisat.SolverFactory;
import org.sat4j.reader.DimacsReader;
import org.sat4j.reader.ParseFormatException;
import org.sat4j.reader.Reader;
import org.sat4j.specs.ContradictionException;
import org.sat4j.specs.IProblem;
import org.sat4j.specs.ISolver;
import org.sat4j.specs.TimeoutException;
/**
* A formula is a conjunction (and) of clauses, or a single clause, in which
* the formula evaluates itself and returns true if satisfiable and false otherwise,
* Recursively travels up and down the formula to solve the formula using backtracking
*
* @author Adam Tucker
* @author Dennis Kluader
* @author Umair Chaudhry
* @version 03/30/2016
*
*/
public class Formula {
//The end of line marker for a cnf file which marks the end of a clause
//in a boolean formula
public static final int CNF_END_OF_LINEMARKER = 0;
//The filename/location for a new file
private static String fileName = ".cnf";
//The directory for a new file
private static String directory = "C:/Dennis_Umair_Adam_Sudoku_CNF";
// list of clauses in CNF
private List<Clause> formulaList;
//for return value test
boolean isEmpty;
// number of variables in the formula
int numVariables;
// number of clauses in the formula
int numClauses;
//True if any clause is empty
boolean hasEmptyClause = false;
//keeps track of the smallest sized clause in the list
private int minClauseSize;
//keeps track of the index the first smallest clause
@SuppressWarnings("unused")
private int minClauseIndex;
/**
* This constructor takes no arguments
*/
public Formula()
{
formulaList = new ArrayList<Clause>(13000);
isEmpty = true;
numVariables = 0;
minClauseSize=Integer.MAX_VALUE;
minClauseIndex=-1;
}
/**
* Main method for the Sudoku solver
* @param args The sudoku file
* @throws IOException
*/
public static void main ( String [] args ) throws IOException {
//Start a timer
long start = System.currentTimeMillis();
//Makes a new file to be scanned for the presets
File file = new File (args[0]);
//Gets the file location of the file
String path = file.getAbsolutePath();
//Creates the board with presets
SudokuBoard board = SudokuBoard.readFromSudokuFile(path);
//Initalizes the board
board.createBoard();
// Used to ensure cnf files and output files have unique filename
// for further examination
Random random = new Random();
// The directory for cnf file
File dir = new File (directory);
// The name of the cnf file
String destFileName = args[0].toString() + "_" + start + fileName;
// Creates the cnf file
File cnfFile = new File (dir, destFileName);
//The board is written to the cnf file
board.writeToFile(cnfFile,destFileName);
// Beggining of code taken from http://www.sat4j.org/howto.php
// This creates a sequence of objects to solve a SAT instance from a cnf file
ISolver solver = SolverFactory . newDefault ();
solver . setTimeout (3600); // 1 hour timeout
Reader reader = new DimacsReader ( solver );
// CNF filename is given on the command line
try {
//Gets the path of the cnf file
String cnf = cnfFile.getAbsolutePath();
IProblem problem = reader . parseInstance (cnf);
if ( problem . isSatisfiable ()) {
System . out . println ("Satisfiable !");
//Gets the array of integers that are the solution to the formula
int[] solutionArray = problem.primeImplicant();
List <Integer> posArray = new ArrayList <Integer> ();
// Prints out the positve value from the prime implicant
// which is the SAT solution
// The below code prints only the true (positive) numbers
for (int i=0;i<solutionArray.length;i++) {
if (i%((board.SIZE_SQUARED)*(board.SIZE_SQUARED))==0) {
System.out.println();
}
if (solutionArray[i]>0) {
// Adds true values to a list
posArray.add(solutionArray[i]);
System.out.print(solutionArray[i] + " ");
}
}
System.out.println();
//Converts the sat model to a Sudoku board
board.convertSatModelToSudokuBoard(problem.model());
// Prints the sudoku board solution and saves the solution to file
// in the directory of the unsolved sudoku solution for comparison
System.out.println("Completed board:");
int[][][] solArray = board.printSudokuBoard();
board.saveSudokuResultToFile(solArray,destFileName);
System.out.println();
} else {
System . out . println (" Unsatisfiable !");
}
} catch ( FileNotFoundException e) {
e.printStackTrace();
} catch ( ParseFormatException e) {
e.printStackTrace();
} catch ( IOException e) {
e.printStackTrace();
} catch ( ContradictionException e) {
System .out . println (" Unsatisfiable ( trivial )!");
} catch ( TimeoutException e) {
System .out . println (" Timeout , sorry !");
}
long end = System.currentTimeMillis();
// Prints out the runtime of the program
System.err.println("\nThe runtime is " + (end-start)/1000.0 + " seconds");
}
/**
* Gets the formula list
* @return The formula
*/
public List<Clause> getFormulaList() {
return formulaList;
}
/**
* Sets the formula list
* @param formulaList The formula list to set
*/
public void setFormulaList(List<Clause> formulaList) {
this.formulaList = formulaList;
}
/**
* This method adds a clause to this formula
* @param c The Clause to be added
*/
public void addClause(Clause c)
{
if (this.isEmpty == true)
isEmpty=false;
formulaList.add(c);
if(c.size()<minClauseSize)
{
minClauseSize = c.size();
minClauseIndex = formulaList.size()+1;
if(minClauseSize==0)
{
hasEmptyClause=true;
}
}
}
/**
* Empty of the formula has been solved
* @return True if the collection is empty and false otherwise
*/
public boolean isEmpty () {
return isEmpty;
}
/**
* This method returns the number of variables in the formula
* @return The number of variables
*/
public int getNumVariables()
{
return numVariables;
}
/**
* This method sets the number of variables in the formula
* @param numVariables The number of variables
*/
public void setNumVariables(int numVariables)
{
this.numVariables = numVariables;
}
/**
* This method returns the number of clauses in the formula
* @return the number of clauses
*/
public int getNumClauses()
{
return formulaList.size();
}
/**
* Takes a formula and makes a new cnf file
* @param fileToWrite The file to be made into a cnf file
*/
public void writeToFile (File fileToWrite, String nameOfSudoku) {
try {
fileToWrite.getParentFile().mkdirs();
Writer fileWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileToWrite.toString()), "utf-8"));
fileWriter.write("c This file illustrates a Sudoku board named " + nameOfSudoku + "\n");
fileWriter.write("p cnf " + numVariables + " " + this.formulaList.size() + " \n");
for (Clause myClause: this.formulaList) {
String lines = myClause.toString() + CNF_END_OF_LINEMARKER + "\n";
fileWriter.write(lines);
}
fileWriter.close();
} catch (IOException e) {
System.err.println("Problem writing to the file " + nameOfSudoku);
}
}
/**
* Gets the filename/location for the a new .cnf file
* @return The filename/location
*/
public static String getFileName() {
return fileName;
}
/**
* Sets the filename/location for a new .cnf file
* @param fileName The new filename/location
*/
public static void setFileName(String fileName) {
Formula.fileName = fileName;
}
/**
* Returns a string as {{1 true or 2 true} and (3 false and 4 false}}
* @return The contents of the formula in a string format
*/
public String toString()
{
String result = "{ ";
for (int i=0;i<formulaList.size()-1;i++)
{
if (formulaList.get(i)==null) {
result += "[]" + " and ";
}
result += formulaList.get(i) + " and ";
}
result += formulaList.get(formulaList.size()-1)+" }" + "\n";
return result;
}
}
| true |