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
f565f30fbf4b765c133ab98a0bf360b3c70b6f68
Java
bashakg404/harsha
/spring-demo-annotationsinje/src/com/springdemo/anninject/TennisCoach.java
UTF-8
250
1.859375
2
[]
no_license
package com.springdemo.anninject; import org.springframework.stereotype.Component; @Component public class TennisCoach implements Coach { @Override public String getDailyWorkout() { return "Practice your backend volley"; } }
true
3eb489dd5277f52e1530c064b71e5abf7f72976e
Java
HollyBrain/GunsWork
/src/net/guns_project/server/MainServer.java
WINDOWS-1251
5,870
3.046875
3
[]
no_license
package net.guns_project.server; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import net.guns_project.domain.*; import net.guns_project.manager.*; public class MainServer { private static final IMakerManager makerManager = new MakerManager(); private static final IWeaponManager weaponManager = new WeaponManager(); private static final IDescriptionManager descManager = new DescriptionManager(); public static void main(String[] args) throws Exception { // 9999 ServerSocket serverSocket = new ServerSocket(9999); while (true) { // 9999, 볺 Socket socket = serverSocket.accept(); // // RemoteRequestMessage ObjectInputStream inFromClient = new ObjectInputStream( socket.getInputStream()); RemoteRequestMessage msg = (RemoteRequestMessage) inFromClient .readObject(); // , System.out.println("** Received call for " + msg.getService() + "." + msg.getMethodName() + "()"); // , . RemoteResponseMessage response = handleRequest(msg); // response, ObjectOutputStream outToClient = new ObjectOutputStream( socket.getOutputStream()); // response 볺 outToClient.writeObject(response); } } private static RemoteResponseMessage handleRequest(RemoteRequestMessage msg) { if (IMakerManager.class.getSimpleName().equals(msg.getService())) { return handleMakerRequest(msg); } if (IWeaponManager.class.getSimpleName().equals(msg.getService())) { return handleWeaponRequest(msg); } if (IDescriptionManager.class.getSimpleName().equals(msg.getService())) { return handleDescRequest(msg); } return null; } private static RemoteResponseMessage handleMakerRequest( RemoteRequestMessage msg) { RemoteResponseMessage result = new RemoteResponseMessage(); if (msg.getMethodName().equals("getAllMakers")) { try { result.setResult(makerManager.getAllMakers()); } catch (Exception e) { result.setException(e); } } else if (msg.getMethodName().equals("getMakerById")) { try { result.setResult(makerManager.getMakerById((Integer) msg .getArguments()[0])); } catch (Exception e) { result.setException(e); } } else if (msg.getMethodName().equals("createMaker")) { try { result.setResult(makerManager.createMaker((Maker) msg .getArguments()[0])); } catch (Exception e) { result.setException(e); } } else if (msg.getMethodName().equalsIgnoreCase("removeMaker")) { try { makerManager.removeMaker((Integer) msg.getArguments()[0]); } catch (Exception e) { result.setException(e); } } else if (msg.getMethodName().equals("updateMaker")) { try { makerManager.updateMaker((Maker) msg.getArguments()[0]); } catch (Exception e) { result.setException(e); } } return result; } private static RemoteResponseMessage handleWeaponRequest( RemoteRequestMessage msg) { RemoteResponseMessage result = new RemoteResponseMessage(); if (msg.getMethodName().equals("getAllWeapons")) { try { result.setResult(weaponManager.getAllWeapons()); } catch (Exception e) { result.setException(e); } } else if (msg.getMethodName().equals("getMakerWeapons")) { try { result.setResult(weaponManager.getMakerWeapons((Integer) msg .getArguments()[0])); } catch (Exception e) { result.setException(e); } } else if (msg.getMethodName().equals("createWeapon")) { try { result.setResult(weaponManager.createWeapon((Weapon) msg .getArguments()[0])); } catch (Exception e) { result.setException(e); } } else if (msg.getMethodName().equalsIgnoreCase("removeWeapon")) { try { weaponManager.removeWeapon((Integer) msg.getArguments()[0]); } catch (Exception e) { result.setException(e); } } else if (msg.getMethodName().equals("updateWeapon")) { try { weaponManager.updateWeapon((Weapon) msg.getArguments()[0]); } catch (Exception e) { result.setException(e); } } return result; } private static RemoteResponseMessage handleDescRequest( RemoteRequestMessage msg) { RemoteResponseMessage result = new RemoteResponseMessage(); if (msg.getMethodName().equals("getAllDescription")) { try { result.setResult(descManager.getAllDescription()); } catch (Exception e) { result.setException(e); } } else if (msg.getMethodName().equals("getMakerDescription")) { try { result.setResult(descManager.getWeaponDescription((Integer) msg .getArguments()[1])); } catch (Exception e) { result.setException(e); } } else if (msg.getMethodName().equals("createDescription")) { try { result.setResult(descManager.createDescription((Description) msg .getArguments()[0])); } catch (Exception e) { result.setException(e); } } else if (msg.getMethodName().equalsIgnoreCase("removeDdescription")) { try { descManager.removeDescription((Integer) msg.getArguments()[0]); } catch (Exception e) { result.setException(e); } } else if (msg.getMethodName().equals("updateDescription")) { try { descManager.updateDescription((Description)msg.getArguments()[0]); } catch (Exception e) { result.setException(e); } } return result; } }
true
ecdf03138ac9658499cdbffb1db34a0b5ae774c2
Java
AnastasiaKislyakova/mail-scheduler
/src/test/java/ru/kislyakova/anastasia/scheduler/controller/MailingControllerTest.java
UTF-8
5,293
2
2
[]
no_license
package ru.kislyakova.anastasia.scheduler.controller; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.BodyInserters; import ru.kislyakova.anastasia.scheduler.dto.ChannelCreationDto; import ru.kislyakova.anastasia.scheduler.dto.MailingCreationDto; import ru.kislyakova.anastasia.scheduler.entity.Channel; import ru.kislyakova.anastasia.scheduler.entity.Mailing; import ru.kislyakova.anastasia.scheduler.service.ChannelService; import ru.kislyakova.anastasia.scheduler.service.MailingService; import ru.kislyakova.anastasia.scheduler.utils.EntityUtils; import javax.swing.text.html.parser.Entity; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.internal.verification.VerificationModeFactory.times; @Import(TestConfig.class) @WebFluxTest(MailingController.class) @ExtendWith(SpringExtension.class) class MailingControllerTest { @Autowired private WebTestClient webClient; @MockBean private MailingService mailingService; @Test void should_create_mailing() { MailingCreationDto mailingDto = EntityUtils.mailingCreationDto(); Mailing mailing = new Mailing(mailingDto); mailing.setId(1); when(mailingService.createMailing(mailingDto)).thenReturn(mailing); webClient.post() .uri("/api/mailings") .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(mailingDto)) .exchange() .expectStatus().isCreated(); verify(mailingService, times(1)).createMailing(mailingDto); } @Test void should_send_mailing() { Mailing mailing = EntityUtils.mailing(); int id = 1; mailing.setId(id); when(mailingService.sendMailing(id)).thenReturn(mailing); webClient.post() .uri("/api/mailings/{mailingId}/send", id) .exchange() .expectStatus().isOk() .expectBody() .jsonPath("$.id").isEqualTo(id) .jsonPath("$.channelId").isEqualTo(mailing.getChannelId()) .jsonPath("$.subject").isEqualTo(mailing.getSubject()) .jsonPath("$.text").isEqualTo(mailing.getText()) .jsonPath("$.attempt").isEqualTo(mailing.getAttempt()); verify(mailingService, times(1)).sendMailing(id); } @Test void should_not_send_not_found_by_id_mailing() { int id = 2; when(mailingService.sendMailing(id)).thenReturn(null); webClient.post() .uri("/api/mailings/{mailingId}/send", id) .exchange() .expectStatus().isNotFound(); verify(mailingService, times(1)).sendMailing(id); } @Test void should_get_mailing_by_id() { Mailing mailing = EntityUtils.mailing(); int id = 1; mailing.setId(id); when(mailingService.getMailingById(id)).thenReturn(mailing); webClient.get() .uri("/api/mailings/{mailingId}", id) .exchange() .expectStatus().isOk() .expectBody() .jsonPath("$.id").isEqualTo(id) .jsonPath("$.channelId").isEqualTo(mailing.getChannelId()) .jsonPath("$.subject").isEqualTo(mailing.getSubject()) .jsonPath("$.text").isEqualTo(mailing.getText()) .jsonPath("$.attempt").isEqualTo(mailing.getAttempt()); verify(mailingService, times(1)).getMailingById(id); } @Test void should_not_find_mailing_by_id() { int id = 2; when(mailingService.sendMailing(id)).thenReturn(null); webClient.get() .uri("/api/mailings/{mailingId}", id) .exchange() .expectStatus().isNotFound(); verify(mailingService, times(1)).getMailingById(id); } @Test void should_get_mailings() { List<Mailing> mailings = EntityUtils.mailings(); when(mailingService.getMailings()).thenReturn(mailings); webClient.get() .uri("/api/mailings") .exchange() .expectStatus().isOk() .expectBodyList(Mailing.class).value(elements -> { MatcherAssert.assertThat(elements, Matchers.hasSize(2)); MatcherAssert.assertThat(elements, Matchers.hasItem(mailings.get(0))); MatcherAssert.assertThat(elements, Matchers.hasItem(mailings.get(1))); }); verify(mailingService, times(1)).getMailings(); } }
true
6c5288afe0726a6ed844b776881f86a05c46a406
Java
mkblogs/AccountJSPWithUsers
/src/main/java/com/tech/mkblogs/pk/series/SeriesTable.java
UTF-8
1,343
1.992188
2
[]
no_license
package com.tech.mkblogs.pk.series; import java.time.LocalDateTime; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Version; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Entity @Table(name = "series") @Data @NoArgsConstructor @AllArgsConstructor(staticName = "of") @EntityListeners(AuditingEntityListener.class) public class SeriesTable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String tableName; private Integer currentValue; @CreatedBy private Integer createdBy; private String createdName; @CreatedDate private LocalDateTime createdTs; @LastModifiedBy private Integer lastModifiedBy; private String lastModifiedName; @LastModifiedDate private LocalDateTime lastModifiedTs; @Version private Integer version; }
true
e289d22b4ffde7a913f2af25b3653dd2ad940e85
Java
vovarova/ChineesePuzzle
/src/main/java/fine/project/GameProcessor.java
UTF-8
993
2.59375
3
[]
no_license
package fine.project; import java.util.ArrayList; import java.util.List; import fine.project.algorythms.Algorythm; import fine.project.algorythms.CornersAlgorythm; import fine.project.model.ColumnObj; public class GameProcessor { private Picture picture; private List<Algorythm> algorythms; public GameProcessor(Picture picture) { this.picture = picture; } public GameProcessor(Picture picture,List<Algorythm> algorythms) { this.picture = picture; this.algorythms = algorythms; } List<Algorythm> getDefaultAlgorythms(){ List<Algorythm> defaultAlgorythms = new ArrayList<Algorythm>(); defaultAlgorythms.add(new CornersAlgorythm()); return defaultAlgorythms; } public void process(){ List<ColumnObj> columsSplited = picture.getColumsSplited(); while (picture.isDone()){ for (ColumnObj columObj : columsSplited) { for (Algorythm alg : algorythms) { alg.calculate(columObj); } } } } }
true
536e092780ba9990051dcc75f4d751e03cb882b1
Java
Naxanria/nom
/src/main/java/com/naxanria/nom/util/WorldUtil.java
UTF-8
337
2.09375
2
[]
no_license
package com.naxanria.nom.util; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class WorldUtil { public static void spawnAsEntity(World world, BlockPos pos, ItemStack stack) { Block.spawnAsEntity(world, pos, stack); } }
true
2a91868972bc7b781a1f74e0aae5d71eb6b9973d
Java
shalviraj/greenlens
/sources/p298d/p299a/p300a/p301a/p303y0/p405l/C7454d.java
UTF-8
2,324
1.8125
2
[]
no_license
package p298d.p299a.p300a.p301a.p303y0.p405l; import p298d.p299a.p300a.p301a.p303y0.p405l.p408l1.C7532f; import p298d.p299a.p300a.p301a.p303y0.p405l.p408l1.C7534h; import p298d.p299a.p300a.p301a.p303y0.p405l.p408l1.C7535i; import p298d.p299a.p300a.p301a.p303y0.p405l.p408l1.C7537k; import p298d.p299a.p300a.p301a.p303y0.p405l.p408l1.C7540n; /* renamed from: d.a.a.a.y0.l.d */ public final class C7454d { /* renamed from: a */ public static final boolean m13424a(C7540n nVar, C7535i iVar, C7535i iVar2) { int b; if (nVar.mo25111b(iVar) == nVar.mo25111b(iVar2) && nVar.mo25113d(iVar) == nVar.mo25113d(iVar2)) { if ((nVar.mo25121s(iVar) == null) == (nVar.mo25121s(iVar2) == null) && nVar.mo25124v(nVar.mo25112c(iVar), nVar.mo25112c(iVar2))) { if (!nVar.mo25122t(iVar, iVar2) && (b = nVar.mo25111b(iVar)) > 0) { int i = 0; while (true) { int i2 = i + 1; C7537k j = nVar.mo25116j(iVar, i); C7537k j2 = nVar.mo25116j(iVar2, i); if (nVar.mo25119q(j) != nVar.mo25119q(j2)) { return false; } if (!nVar.mo25119q(j) && (nVar.mo25117m(j) != nVar.mo25117m(j2) || !m13425b(nVar, nVar.mo25123u(j), nVar.mo25123u(j2)))) { return false; } if (i2 >= b) { break; } i = i2; } } return true; } } return false; } /* renamed from: b */ public static final boolean m13425b(C7540n nVar, C7534h hVar, C7534h hVar2) { if (hVar == hVar2) { return true; } C7535i a = nVar.mo25110a(hVar); C7535i a2 = nVar.mo25110a(hVar2); if (a != null && a2 != null) { return m13424a(nVar, a, a2); } C7532f r = nVar.mo25120r(hVar); C7532f r2 = nVar.mo25120r(hVar2); if (r == null || r2 == null) { return false; } return m13424a(nVar, nVar.mo25125x(r), nVar.mo25125x(r2)) && m13424a(nVar, nVar.mo25115i(r), nVar.mo25115i(r2)); } }
true
3c9600a650426742077d5f2cd185c7f7352501b1
Java
Cjf1226098687/13_SSM_04_House
/src/main/java/com/fc/vo/UserAuthVo.java
UTF-8
582
2.046875
2
[]
no_license
package com.fc.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @EqualsAndHashCode(callSuper = true) @Data @NoArgsConstructor @AllArgsConstructor public class UserAuthVo extends UserVo { private String token; public UserAuthVo(UserVo userVo) { this.setId(userVo.getId()); this.setName(userVo.getName()); this.setAge(userVo.getAge()); this.setAvaUrl(userVo.getAvaUrl()); this.setGender(userVo.getGender()); this.setPhone(userVo.getPhone()); } }
true
b48e3bb3c6b7f334e59f368ac261650406baddf2
Java
Swietlon/swagger-java-client
/src/test/java/io/swagger/client/api/DefaultApiTest.java
UTF-8
1,991
2.265625
2
[]
no_license
/* * Simple calc API * This a simple API * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.api; import io.swagger.client.ApiException; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for DefaultApi */ @Ignore public class DefaultApiTest { private final DefaultApi api = new DefaultApi(); /** * * * Returns sum of x and y * * @throws ApiException * if the Api call fails */ @Test public void additionGetTest() throws ApiException { Float x = null; Float y = null; Float response = api.additionGet(x, y); // TODO: test validations } /** * * * Returns quotient of x and y * * @throws ApiException * if the Api call fails */ @Test public void divisionGetTest() throws ApiException { Float x = null; Float y = null; Float response = api.divisionGet(x, y); // TODO: test validations } /** * * * Returns product of x and y * * @throws ApiException * if the Api call fails */ @Test public void multiplicationGetTest() throws ApiException { Float x = null; Float y = null; Float response = api.multiplicationGet(x, y); // TODO: test validations } /** * * * Returns the difference x and y * * @throws ApiException * if the Api call fails */ @Test public void substractionGetTest() throws ApiException { Float x = null; Float y = null; Float response = api.substractionGet(x, y); // TODO: test validations } }
true
fd000f6ea0908899392d61b1faa777cc15758be3
Java
AshutoshSundresh/OnePlusSettings-Java
/sources/com/google/android/setupdesign/items/Item.java
UTF-8
4,968
1.835938
2
[]
no_license
package com.google.android.setupdesign.items; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.setupdesign.R$id; import com.google.android.setupdesign.R$layout; import com.google.android.setupdesign.R$styleable; public class Item extends AbstractItem { private boolean enabled; private Drawable icon; private int iconGravity; private int iconTint; private int layoutRes; private CharSequence summary; private CharSequence title; private boolean visible; public Item() { this.enabled = true; this.visible = true; this.iconTint = 0; this.iconGravity = 16; this.layoutRes = getDefaultLayoutResource(); } public Item(Context context, AttributeSet attributeSet) { super(context, attributeSet); this.enabled = true; this.visible = true; this.iconTint = 0; this.iconGravity = 16; TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, R$styleable.SudItem); this.enabled = obtainStyledAttributes.getBoolean(R$styleable.SudItem_android_enabled, true); this.icon = obtainStyledAttributes.getDrawable(R$styleable.SudItem_android_icon); this.title = obtainStyledAttributes.getText(R$styleable.SudItem_android_title); this.summary = obtainStyledAttributes.getText(R$styleable.SudItem_android_summary); this.layoutRes = obtainStyledAttributes.getResourceId(R$styleable.SudItem_android_layout, getDefaultLayoutResource()); this.visible = obtainStyledAttributes.getBoolean(R$styleable.SudItem_android_visible, true); this.iconTint = obtainStyledAttributes.getColor(R$styleable.SudItem_sudIconTint, 0); this.iconGravity = obtainStyledAttributes.getInt(R$styleable.SudItem_sudIconGravity, 16); obtainStyledAttributes.recycle(); } /* access modifiers changed from: protected */ public int getDefaultLayoutResource() { return R$layout.sud_items_default; } @Override // com.google.android.setupdesign.items.AbstractItem, com.google.android.setupdesign.items.ItemHierarchy public int getCount() { return isVisible() ? 1 : 0; } @Override // com.google.android.setupdesign.items.IItem public boolean isEnabled() { return this.enabled; } public Drawable getIcon() { return this.icon; } public void setIconGravity(int i) { this.iconGravity = i; } @Override // com.google.android.setupdesign.items.IItem public int getLayoutResource() { return this.layoutRes; } public CharSequence getSummary() { return this.summary; } public CharSequence getTitle() { return this.title; } public boolean isVisible() { return this.visible; } @Override // com.google.android.setupdesign.items.AbstractItemHierarchy public int getViewId() { return getId(); } @Override // com.google.android.setupdesign.items.IItem public void onBindView(View view) { ((TextView) view.findViewById(R$id.sud_items_title)).setText(getTitle()); TextView textView = (TextView) view.findViewById(R$id.sud_items_summary); CharSequence summary2 = getSummary(); if (summary2 == null || summary2.length() <= 0) { textView.setVisibility(8); } else { textView.setText(summary2); textView.setVisibility(0); } View findViewById = view.findViewById(R$id.sud_items_icon_container); Drawable icon2 = getIcon(); if (icon2 != null) { ImageView imageView = (ImageView) view.findViewById(R$id.sud_items_icon); imageView.setImageDrawable(null); onMergeIconStateAndLevels(imageView, icon2); imageView.setImageDrawable(icon2); int i = this.iconTint; if (i != 0) { imageView.setColorFilter(i); } else { imageView.clearColorFilter(); } ViewGroup.LayoutParams layoutParams = findViewById.getLayoutParams(); if (layoutParams instanceof LinearLayout.LayoutParams) { ((LinearLayout.LayoutParams) layoutParams).gravity = this.iconGravity; } findViewById.setVisibility(0); } else { findViewById.setVisibility(8); } view.setId(getViewId()); } /* access modifiers changed from: protected */ public void onMergeIconStateAndLevels(ImageView imageView, Drawable drawable) { imageView.setImageState(drawable.getState(), false); imageView.setImageLevel(drawable.getLevel()); } }
true
6ba3525d6283eb3ab543af8a5ea89b8ff2a8083d
Java
crazy-pizza/vote-manager
/src/main/java/com/hualala/bean/VoteDetail.java
UTF-8
262
1.539063
2
[]
no_license
package com.hualala.bean; import lombok.Data; /** * @author YuanChong * @create 2019-06-01 18:12 * @desc */ @Data public class VoteDetail { private Long voteDetailID; private Long voteID; private String content; private Long sumVote; }
true
2bd35e6a407d816bd275c500542bd1d09cce158a
Java
jfc941640/DigSim
/1.0/AnalyzerPanel.java
UTF-8
20,557
2.421875
2
[]
no_license
//**************************************************************************** // ---- version information ---- // // AnalyzerPanel.java v 1.00b2 // Written by: I. van Rienen / E-mail ivr@bart.nl // URL: http://www/bart.nl/~ivr // Initial release: v 1.00b2 06-03-1996 // Released in public domain: v 1.00b2 06-03-1996 // // ---- Description ---- // Java class containing methods for the the logic analyzer. // // This program and the Java source is in the public domain. // Permission to use, copy, modify, and distribute this software // and its documentation for NON-COMMERCIAL purposes and // without fee is hereby granted. // // Copyright 1996 // // Iwan van Rienen // Joan Maetsuyckerstr. 145 // 2593 ZG The Hague // The Netherlands // // I am not responsible for any bugs in this program and // possible damage to hard- or software when using this program. //**************************************************************************** import java.awt.*; import java.util.Vector; class AnalyzerPanel extends Panel { static final int CHANNEL_HEIGHT = 50; static final int DISPLAY_OFFSET = 5; static final int CLOCK_WIDTH = 10; static final int LINE_OFFSET = 5; static final int BUTTON_X_OFFSET = 5; static final int BUTTON_Y_OFFSET = 22; static final int BUTTON_CLOCK_NONE = 48; static final int BUTTON_CLOCK_NONE_PRESSED = 24; static final int BUTTON_CLOCK_UP_PRESSED = 72; static final int BUTTON_CLOCK_UP_SELECTED = 96; static final int BUTTON_CLOCK_DN_PRESSED = 120; static final int BUTTON_CLOCK_DN_SELECTED = 144; static final Color TextColor = Color.black; static final Color BackGroundColor = Color.black; protected Scrollbar myVertical; DigSim applet; Image OffScreenImage = null; Image ImageBuffer = null; Image CopyImage = null; Graphics cig; int ButtonOffset = 0; Graphics og; Dimension ImageSize; protected Font AnalyzerFont; protected FontMetrics AnalyzerFontMetrics; Vector probes = null; boolean ImageButtonsDisabled = false; Probe PressedProbe = null; Probe DragProbe = null; int CurrentCol = 0; boolean ImageUpdated = false; Frame frame; //---------------------------------------------------------------------------- // The constructor of the Logic Analyzer Panel //---------------------------------------------------------------------------- public AnalyzerPanel(DigSim app, Frame f) { applet = app; frame = f; setLayout( new BorderLayout()); AnalyzerFont = new Font("TimesRoman",Font.PLAIN, 14); AnalyzerFontMetrics = getFontMetrics(AnalyzerFont); super.setLayout( new BorderLayout()); LoadButtonsImage(); myVertical = new Scrollbar(Scrollbar.VERTICAL); add( "East", myVertical); ImageSize = new Dimension (400, 250); CheckOffScreenImage(); repaint(); } //---------------------------------------------------------------------------- // Adjust scrollbar to current display settings //---------------------------------------------------------------------------- public void AdjustScrollbar() { String OSName; if (probes == null) return; int ttl_height = CHANNEL_HEIGHT * probes.size(); int vis_height = size().height; int max_offs = ttl_height - vis_height; if (max_offs < 0) max_offs = 0; // Determine OS because of scrollbar implementation differences // between Win95/NT and other operating systems. OSName = System.getProperty("os.name"); if (OSName.equals ("Windows 95") || OSName.equals ("Windows NT")) { myVertical.setValues (myVertical.getValue(), vis_height, 0, max_offs + vis_height); } else { myVertical.setValues (myVertical.getValue(), vis_height, 0, max_offs); } } //---------------------------------------------------------------------------- // Check if there is an off-screen image, and check its size //---------------------------------------------------------------------------- public void CheckOffScreenImage() { if (OffScreenImage == null) { PrepareOffScreenImage(); return; } if (size().width > ImageSize.width || size().height > ImageSize.height) { ImageSize.width = size().width; ImageSize.height = size().height; PrepareOffScreenImage(); } } //---------------------------------------------------------------------------- // Create an off-screen image //---------------------------------------------------------------------------- public void PrepareOffScreenImage() { OffScreenImage = applet.createImage (ImageSize.width, ImageSize.height); og = OffScreenImage.getGraphics(); og.setFont(AnalyzerFont); repaint(); } //---------------------------------------------------------------------------- // select an ImageButton //---------------------------------------------------------------------------- public void SelectButton(int ButtonType) { cig.copyArea (0, ButtonType, 24, 24, 0, -ButtonType); } //---------------------------------------------------------------------------- // There is a button pressed //---------------------------------------------------------------------------- public void ButtonPressed (int b) { Probe ActProbe = (Probe)probes.elementAt (b); PressedProbe = ActProbe; if (ActProbe.clockup_probe) { ActProbe.clockup_probe = false; ActProbe.clockdn_probe = true; } else if (ActProbe.clockdn_probe) { ActProbe.clockup_probe = false; ActProbe.clockdn_probe = false; } else { ActProbe.clockup_probe = true; ActProbe.clockdn_probe = false; } for (int ix = 0; ix < probes.size(); ix++) { if (b != ix) { ActProbe = (Probe) probes.elementAt (ix); ActProbe.clockup_probe = false; ActProbe.clockdn_probe = false; } } repaint(); } //---------------------------------------------------------------------------- // User clicked a mousebutton //---------------------------------------------------------------------------- public boolean mouseDown(Event event, int x, int y) { Probe ActProbe; int ix, yo; PressedProbe = null; DragProbe = null; for (ix = 0; ix < probes.size(); ix++) { yo = ix * CHANNEL_HEIGHT + BUTTON_Y_OFFSET - myVertical.getValue(); if ( x >= BUTTON_X_OFFSET && x <= BUTTON_X_OFFSET + 24 && y >= yo && y <= yo + 24) { ButtonPressed(ix); } } for (ix = 0; ix < probes.size(); ix++) { ActProbe = (Probe)probes.elementAt (ix); if ( x >= ActProbe.ChannelPos.x && y >= ActProbe.ChannelPos.y && x <= ActProbe.ChannelPos.x + ActProbe.ChannelDim.width && y <= ActProbe.ChannelPos.y + ActProbe.ChannelDim.height) { DragProbe = ActProbe; repaint(); return true; } } return true; } //---------------------------------------------------------------------------- // The user releases the mouse button //---------------------------------------------------------------------------- public boolean mouseUp(Event event, int x, int y) { if (DragProbe != null) { DragProbe = null; repaint(); } if (PressedProbe != null) { PressedProbe = null; repaint(); } return true; } //---------------------------------------------------------------------------- // The user moves the mouse //---------------------------------------------------------------------------- public boolean mouseDrag(Event evt, int x, int y) { Probe ActProbe; int dpix, ix; if (DragProbe != null) { for (ix = 0; ix < probes.size(); ix++) { ActProbe = (Probe)probes.elementAt (ix); if ( x >= ActProbe.ChannelPos.x && y >= ActProbe.ChannelPos.y && x <= ActProbe.ChannelPos.x + ActProbe.ChannelDim.width && y <= ActProbe.ChannelPos.y + ActProbe.ChannelDim.height) { if (ActProbe != DragProbe) { // System.out.println ("Swap probes"); // Swap ActProbe and DragProbe. applet.MySchematic.SwapComponents (ActProbe, DragProbe); repaint(); return true; } } } } return true; } //---------------------------------------------------------------------------- // Draw the history levels of Probe ActProbe //---------------------------------------------------------------------------- public void DrawProbeHistory (Graphics g, Probe ActProbe) { g.setColor (Color.green); for (int ix = 0; ix < ActProbe.MAX_HISTORY; ix++) { if (ix > 0 && ActProbe.LevelHistory[ix - 1] != ActProbe.LevelHistory[ix]) { og.drawLine (ActProbe.ChannelPos.x + ix * CLOCK_WIDTH, ActProbe.ChannelPos.y + LINE_OFFSET, ActProbe.ChannelPos.x + ix * CLOCK_WIDTH, ActProbe.ChannelPos.y + ActProbe.ChannelDim.height - LINE_OFFSET); } if (ActProbe.LevelHistory[ix] == 5) { g.setColor (Color.green); g.drawLine (ActProbe.ChannelPos.x + ix * CLOCK_WIDTH, ActProbe.ChannelPos.y + LINE_OFFSET, ActProbe.ChannelPos.x + (ix + 1 ) * CLOCK_WIDTH, ActProbe.ChannelPos.y + LINE_OFFSET); } else { g.setColor (Color.green); g.drawLine (ActProbe.ChannelPos.x + ix * CLOCK_WIDTH, ActProbe.ChannelPos.y + ActProbe.ChannelDim.height - LINE_OFFSET, ActProbe.ChannelPos.x + (ix + 1) * CLOCK_WIDTH, ActProbe.ChannelPos.y + ActProbe.ChannelDim.height - LINE_OFFSET); } } } //---------------------------------------------------------------------------- // There are no probes available, display a message //---------------------------------------------------------------------------- public void DrawNoProbes(Graphics g) { String message = "There are no probes to display."; int StringWidth = AnalyzerFontMetrics.stringWidth(message); int x = (size().width - StringWidth) / 2; g.setColor (Color.black); g.drawString (message, x, size().height / 2); } //---------------------------------------------------------------------------- // Draw the empty probes //---------------------------------------------------------------------------- public void DrawEmptyProbes(Graphics g) { probes = applet.MySchematic.getProbes(); Probe ActProbe; int x, yo, w; int MaxTextWidth = 30; int SliderVal = myVertical.getValue(); g.setColor (Color.lightGray); g.fillRect (0, 0, ImageSize.width, ImageSize.height); if (probes.size() == 0) { DrawNoProbes(g); return; } // determine Max. text size for (int ix = 0; ix < probes.size(); ix++) { ActProbe = (Probe) probes.elementAt (ix); w = AnalyzerFontMetrics.stringWidth(ActProbe.IPin[0].getName()); if (w > MaxTextWidth) MaxTextWidth = w; } for (int ix = 0; ix < probes.size(); ix++) { ActProbe = (Probe) probes.elementAt (ix); yo = ix * CHANNEL_HEIGHT - SliderVal; g.setColor (TextColor); g.drawString (ActProbe.IPin[0].getName(), 5, yo + 16); g.setColor (Color.gray); g.drawLine (0, yo + CHANNEL_HEIGHT - 2, size().width, yo + CHANNEL_HEIGHT - 2); g.setColor (Color.white); g.drawLine (0, yo + CHANNEL_HEIGHT - 1, size().width, yo + CHANNEL_HEIGHT - 1); ActProbe.ChannelPos.x = DISPLAY_OFFSET + MaxTextWidth + 5; ActProbe.ChannelPos.y = DISPLAY_OFFSET + yo; ActProbe.ChannelDim.width = size().width - ((DISPLAY_OFFSET) + MaxTextWidth + 20); ActProbe.ChannelDim.height = CHANNEL_HEIGHT - 2 * DISPLAY_OFFSET; g.setColor (BackGroundColor); g.fillRect (ActProbe.ChannelPos.x, ActProbe.ChannelPos.y + 1, ActProbe.ChannelDim.width, ActProbe.ChannelDim.height - 1); if (ActProbe.clockup_probe) { if (ActProbe == PressedProbe) { SelectButton (BUTTON_CLOCK_UP_PRESSED); } else { SelectButton (BUTTON_CLOCK_UP_SELECTED); } } else if (ActProbe.clockdn_probe) { if (ActProbe == PressedProbe) { SelectButton (BUTTON_CLOCK_DN_PRESSED); } else { SelectButton (BUTTON_CLOCK_DN_SELECTED); } } else { if (ActProbe == PressedProbe) { SelectButton (BUTTON_CLOCK_NONE_PRESSED); } else { SelectButton (BUTTON_CLOCK_NONE); } } DrawProbeHistory (g, ActProbe); Graphics ibg = ImageBuffer.getGraphics(); ibg.drawImage (CopyImage, 0, 0, this); g.drawImage(ImageBuffer, BUTTON_X_OFFSET, BUTTON_Y_OFFSET + yo, this); } if (DragProbe != null) { g.setColor (Color.red); g.drawRect (DragProbe.ChannelPos.x, DragProbe.ChannelPos.y, DragProbe.ChannelDim.width, DragProbe.ChannelDim.height); } } //---------------------------------------------------------------------------- // Copy the off-screen image to the screen //---------------------------------------------------------------------------- public synchronized void paint (Graphics g) { if (OffScreenImage == null) return; AdjustScrollbar(); if (probes != null && size().height >= CHANNEL_HEIGHT * probes.size()) { update (g); return; } if (!ImageUpdated) { // System.out.println ("update()"); update(g); return; } g.drawImage (OffScreenImage, 0, 0, this); } //---------------------------------------------------------------------------- // Prepare the off-screen image and copy it to the screen. //---------------------------------------------------------------------------- public synchronized void update (Graphics g) { AdjustScrollbar(); CheckOffScreenImage(); if (OffScreenImage == null) return; DrawEmptyProbes (og); g.drawImage (OffScreenImage, 0, 0, this); ImageUpdated = true; } //---------------------------------------------------------------------------- // Handle the events of the analyzer //---------------------------------------------------------------------------- public boolean handleEvent(Event ev) { if (ev.target instanceof Scrollbar) { repaint(); return true; } return super.handleEvent(ev); } //---------------------------------------------------------------------------- // Handle the actions of the analyzer //---------------------------------------------------------------------------- public boolean action(Event ev, Object arg) { if (ev.target instanceof Button) { } return false; } //---------------------------------------------------------------------------- // Update the new levels of Probe ActProbe //---------------------------------------------------------------------------- public void update(Probe ActProbe) { int x = CurrentCol * CLOCK_WIDTH; if ( x >= ActProbe.ChannelDim.width) { if (ActProbe.clockup_probe && ActProbe.OldLevel == 0 && ActProbe.IPin[0].getLevel() == 5) { CurrentCol = 0; // Clock trigger } else if (ActProbe.clockdn_probe && ActProbe.OldLevel == 5 && ActProbe.IPin[0].getLevel() == 0) { CurrentCol = 0; // Clock trigger } } } //---------------------------------------------------------------------------- // Draw a new Level. //---------------------------------------------------------------------------- public void drawLevel (Probe ActProbe) { int x = CurrentCol * CLOCK_WIDTH; if ( x >= ActProbe.ChannelDim.width) return; if (CurrentCol == 0) { og.setColor (BackGroundColor); og.fillRect (ActProbe.ChannelPos.x + x, ActProbe.ChannelPos.y + 1, CLOCK_WIDTH + 1, ActProbe.ChannelDim.height - 1); } og.setColor (BackGroundColor); og.fillRect (ActProbe.ChannelPos.x + x + 1, ActProbe.ChannelPos.y + 1, CLOCK_WIDTH, ActProbe.ChannelDim.height - 1); if (CurrentCol > 0 && ActProbe.IPin[0].getLevel() != ActProbe.OldLevel) { og.setColor (Color.green); og.drawLine (ActProbe.ChannelPos.x + x, ActProbe.ChannelPos.y + LINE_OFFSET, ActProbe.ChannelPos.x + x, ActProbe.ChannelPos.y + ActProbe.ChannelDim.height - LINE_OFFSET); } if (CurrentCol < ActProbe.MAX_HISTORY) { ActProbe.LevelHistory[CurrentCol] = ActProbe.IPin[0].getLevel(); } if (ActProbe.IPin[0].getLevel() == 5) { og.setColor (Color.green); og.drawLine (ActProbe.ChannelPos.x + x, ActProbe.ChannelPos.y + LINE_OFFSET, ActProbe.ChannelPos.x + x + CLOCK_WIDTH, ActProbe.ChannelPos.y + LINE_OFFSET); } else { og.setColor (Color.green); og.drawLine (ActProbe.ChannelPos.x + x, ActProbe.ChannelPos.y + ActProbe.ChannelDim.height - LINE_OFFSET, ActProbe.ChannelPos.x + x + CLOCK_WIDTH, ActProbe.ChannelPos.y + ActProbe.ChannelDim.height - LINE_OFFSET); } paint (getGraphics()); } //---------------------------------------------------------------------------- // Update the new levels of all probes //---------------------------------------------------------------------------- public void update() { Probe ActProbe; int ix; if (probes == null) return; for (ix = 0; ix < probes.size(); ix++) { ActProbe = (Probe) probes.elementAt (ix); update (ActProbe); } for (ix = 0; ix < probes.size(); ix++) { ActProbe = (Probe) probes.elementAt (ix); drawLevel (ActProbe); ActProbe.OldLevel = ActProbe.IPin[0].getLevel(); } paint(getGraphics()); CurrentCol++; } //---------------------------------------------------------------------------- // Load the image with the buttons //---------------------------------------------------------------------------- public void LoadButtonsImage() { Image ButtonsImage; MediaTracker tracker = new MediaTracker(this); ButtonsImage = applet.getImage(applet.getDocumentBase(), "images/all_analyzer.gif"); tracker.addImage(ButtonsImage, 0); try { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); tracker.waitForAll(); } catch(Exception e) { String message = e.toString(); String DlgButtons[] = { "OK" }; SimpleDialog ExceptionDialog = new SimpleDialog(null, "Reading imagebuttons", message, DlgButtons, 1, 0, 0, SimpleDialog.IMAGE_STOP); return; } if (tracker.isErrorAny()) { ImageButtonsDisabled = true; String message = "Can't read images/all_analyzer.gif ImageButtons will be disabled"; String DlgButtons[] = { "OK" }; SimpleDialog ErrorDialog = new SimpleDialog(null, "Error while reading imagebuttons", message, DlgButtons, 1, 0, 0, SimpleDialog.IMAGE_STOP); return; } ImageBuffer = applet.createImage (ButtonsImage.getWidth(this), 24); CopyImage = applet.createImage (ButtonsImage.getWidth(this), ButtonsImage.getHeight(this)); cig = CopyImage.getGraphics(); cig.drawImage (ButtonsImage, 0, 0, this); } }
true
7988fa0babcec2153859467ab6f0f3734c13555f
Java
deeplearning4j/deeplearning4j
/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/text/tokenization/tokenizer/preprocessor/StringCleaning.java
UTF-8
1,440
2.359375
2
[ "Apache-2.0", "MIT", "BSD-3-Clause" ]
permissive
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.deeplearning4j.text.tokenization.tokenizer.preprocessor; import java.util.regex.Pattern; public class StringCleaning { private static final Pattern punctPattern = Pattern.compile("[\\d\\.:,\"\'\\(\\)\\[\\]|/?!;]+"); private StringCleaning() {} /** * Removes ASCII punctuation marks, which are: 0123456789.:,"'()[]|/?!; * @param base the base string * @return the cleaned string */ public static String stripPunct(String base) { return punctPattern.matcher(base).replaceAll(""); } }
true
07ebcf2c4c74329ab094991c4d8d6fc3dd1b32c4
Java
clhost/walkme-backend
/core_module/src/main/java/io/walkme/core/Configurator.java
UTF-8
2,733
2.28125
2
[]
no_license
package io.walkme.core; import auth.core.AuthService; import io.walkme.handlers.route.MockRoutes; import io.walkme.helpers.ConfigHelper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import route.core.RouteService; import java.io.IOException; import java.io.InputStreamReader; import java.util.Properties; public class Configurator { private static final Logger logger = LogManager.getLogger(Configurator.class); private static final Properties locProps; private static final AuthService authService; private static final RouteService routeService; static { StartInfo.start = System.currentTimeMillis(); authService = new AuthService(); routeService = new RouteService(); locProps = new Properties(); } public static Server configure() throws IOException { locProps.load(new InputStreamReader( Configurator.class.getResourceAsStream("/" + ConfigHelper.LOCAL_PROPERTIES))); String port = locProps.getProperty("server.port"); String host = locProps.getProperty("server.host"); String fullDomain = locProps.getProperty("server.full_domain"); String mockPath = locProps.getProperty("server.mock_path"); if (port == null || port.equals("")) { throw new NullPointerException("server.port is missing."); } if (host == null || host.equals("")) { throw new NullPointerException("server.host is missing."); } if (fullDomain == null || fullDomain.equals("")) { throw new NullPointerException("server.full_domain is missing."); } if (mockPath == null || mockPath.equals("")) { throw new NullPointerException("server.mock_path is missing."); } checkServerMode(); startServices(); ConfigHelper.setFullDomain(fullDomain); MockRoutes.load(mockPath); return new Server(host, Integer.parseInt(port), authService, routeService); } private static void checkServerMode() { String stub = locProps.getProperty("server.stub.enable"); switch (stub) { case "off": // prod mode ServerMode.setProdMode(); logger.info("Configured in prod mode."); break; case "on": // stub mode ServerMode.setStubMode(); logger.info("Configured in stub mode."); break; default: throw new IllegalStateException("server.stub.enable must be \"on\" or \"off\"."); } } private static void startServices() { authService.start(); routeService.start(); } }
true
b2df828e97143d0bc40409ff778d0c6e730ceca8
Java
tangyehao/Car_Customized_System
/src/cn/com/actions/LoginView_BtnLoginAction.java
GB18030
2,214
2.40625
2
[]
no_license
package cn.com.actions; import cn.com.beans.User; import cn.com.services.UserBaseServiceInf; import cn.com.services.impl.UserBaseServiceImpl; import cn.com.utils.KeyCode; import cn.com.views.MainView; import cn.com.views.loginview.LoginView; import java.awt.*; public class LoginView_BtnLoginAction implements Action { private UserBaseServiceInf service; private LoginView lv; public LoginView_BtnLoginAction(){ service = new UserBaseServiceImpl(); } public void execute(Object e, Container c,Object... params) { lv = (LoginView) c; String uID = lv.getTxtUserNo().getText().trim(); String userPwd = new String(lv.getUserPwd().getPassword()).trim(); String valPwd = KeyCode.getKeyCodeMsg(userPwd); if (uID.equals("") || valPwd.equals("")) { //JOptionPane.showMessageDialog(lv,"ʺű","",JOptionPane.ERROR_MESSAGE); lv.getLblMsg().setText("ʺŻ"); return; } if (uID.length() < 4) { // JOptionPane.showMessageDialog(lv,"ʺųҪ3λ","",JOptionPane.ERROR_MESSAGE); lv.getLblMsg().setText("ʺų4λ"); return; } User user = service.getUserBaseByUserNo(uID); if (service.validateByUserNo(uID)) { String uState = user.getuState(); if (service.validateByUserNoAndPwd(uID, valPwd, uState)) { if (uState.equals("")) { new MainView(user); lv.dispose(); } else { lv.getLblMsg().setText("ʺѱã"); lv.getLblMsg().setForeground(Color.RED); return; } }else { lv.getLblMsg().setText("ʺŻ"); lv.getLblMsg().setForeground(Color.RED); return; } }else{ lv.getLblMsg().setText("ʺŻ"); lv.getLblMsg().setForeground(Color.RED); return; } } }
true
a69962a0db47df256ea3eb1bbc3b2a00a6f6b736
Java
carrascoMDD/gvCASE_ALBA
/gvCASE_ALBA_release_wksp/es.gva.cit.gvmetrica.proinso/src/es/gva/cit/gvmetrica/proinso/ProinsoFactory.java
UTF-8
8,403
1.8125
2
[]
no_license
/** * <copyright> * </copyright> * * $Id$ */ package es.gva.cit.gvmetrica.proinso; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * @see es.gva.cit.gvmetrica.proinso.ProinsoPackage * @generated */ public interface ProinsoFactory extends EFactory { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String copyright = "Copyright Conselleria d'Infraestructures i Transport - Generalitat Valenciana 2006"; /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ ProinsoFactory eINSTANCE = es.gva.cit.gvmetrica.proinso.impl.ProinsoFactoryImpl.init(); /** * Returns a new object of class '<em>Actividad</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Actividad</em>'. * @generated */ Actividad createActividad(); /** * Returns a new object of class '<em>Actividad Abstracta</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Actividad Abstracta</em>'. * @generated */ ActividadAbstracta createActividadAbstracta(); /** * Returns a new object of class '<em>Actividad Interfaz</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Actividad Interfaz</em>'. * @generated */ ActividadInterfaz createActividadInterfaz(); /** * Returns a new object of class '<em>Cargo</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Cargo</em>'. * @generated */ Cargo createCargo(); /** * Returns a new object of class '<em>Comite</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Comite</em>'. * @generated */ Comite createComite(); /** * Returns a new object of class '<em>Documentacion</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Documentacion</em>'. * @generated */ Documentacion createDocumentacion(); /** * Returns a new object of class '<em>Entrada</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Entrada</em>'. * @generated */ Entrada createEntrada(); /** * Returns a new object of class '<em>Interfaces</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Interfaces</em>'. * @generated */ Interfaces createInterfaces(); /** * Returns a new object of class '<em>Interfaz</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Interfaz</em>'. * @generated */ Interfaz createInterfaz(); /** * Returns a new object of class '<em>Metodologia</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Metodologia</em>'. * @generated */ Metodologia createMetodologia(); /** * Returns a new object of class '<em>Parrafo</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Parrafo</em>'. * @generated */ Parrafo createParrafo(); /** * Returns a new object of class '<em>Participacion</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Participacion</em>'. * @generated */ Participacion createParticipacion(); /** * Returns a new object of class '<em>Perfiles Participantes</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Perfiles Participantes</em>'. * @generated */ PerfilesParticipantes createPerfilesParticipantes(); /** * Returns a new object of class '<em>Perfil Participante</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Perfil Participante</em>'. * @generated */ PerfilParticipante createPerfilParticipante(); /** * Returns a new object of class '<em>Practica</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Practica</em>'. * @generated */ Practica createPractica(); /** * Returns a new object of class '<em>Practicas</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Practicas</em>'. * @generated */ Practicas createPracticas(); /** * Returns a new object of class '<em>Proceso</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Proceso</em>'. * @generated */ Proceso createProceso(); /** * Returns a new object of class '<em>Proceso Interfaz</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Proceso Interfaz</em>'. * @generated */ ProcesoInterfaz createProcesoInterfaz(); /** * Returns a new object of class '<em>Procesos</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Procesos</em>'. * @generated */ Procesos createProcesos(); /** * Returns a new object of class '<em>Producto</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Producto</em>'. * @generated */ Producto createProducto(); /** * Returns a new object of class '<em>Productos</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Productos</em>'. * @generated */ Productos createProductos(); /** * Returns a new object of class '<em>Reference Run</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Reference Run</em>'. * @generated */ ReferenceRun createReferenceRun(); /** * Returns a new object of class '<em>Repositorio</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Repositorio</em>'. * @generated */ Repositorio createRepositorio(); /** * Returns a new object of class '<em>Salida</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Salida</em>'. * @generated */ Salida createSalida(); /** * Returns a new object of class '<em>Seccion</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Seccion</em>'. * @generated */ Seccion createSeccion(); /** * Returns a new object of class '<em>Tarea</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Tarea</em>'. * @generated */ Tarea createTarea(); /** * Returns a new object of class '<em>Tecnica</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Tecnica</em>'. * @generated */ Tecnica createTecnica(); /** * Returns a new object of class '<em>Tecnicas</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Tecnicas</em>'. * @generated */ Tecnicas createTecnicas(); /** * Returns a new object of class '<em>Text Run</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Text Run</em>'. * @generated */ TextRun createTextRun(); /** * Returns a new object of class '<em>Uso Practica</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Uso Practica</em>'. * @generated */ UsoPractica createUsoPractica(); /** * Returns a new object of class '<em>Uso Tecnica</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Uso Tecnica</em>'. * @generated */ UsoTecnica createUsoTecnica(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ ProinsoPackage getProinsoPackage(); } //ProinsoFactory
true
f072cd94c31ba2342e1859eaba1a8982b97fd2ef
Java
WYK845634621/security
/src/main/java/com/yikai/security/entity/Users.java
UTF-8
268
1.570313
2
[]
no_license
package com.yikai.security.entity; import lombok.Data; /** * @Description * @Tips * @Author yikai.wang * @Number K1171305 * @Date 2020/11/26 9:29 */ @Data public class Users { private Integer id; private String username; private String password; }
true
76ad3f4d095c4b08a728219609087bf1e8ef03c2
Java
The-Knights-of-Ni/FTC-2015-2016
/FtcRobotController/decompiled libs/com/qualcomm/robotcore/sensor/TargetInfo.java
UTF-8
532
2.03125
2
[ "BSD-3-Clause" ]
permissive
/* * Decompiled with CFR 0_101. */ package com.qualcomm.robotcore.sensor; import com.qualcomm.robotcore.sensor.TargetSize; import com.qualcomm.robotcore.util.Pose; public class TargetInfo { public String mTargetName; public Pose mTargetPose; public TargetSize mTargetSize; public TargetInfo() { } public TargetInfo(String targetName, Pose targetPose, TargetSize targetSize) { this.mTargetName = targetName; this.mTargetPose = targetPose; this.mTargetSize = targetSize; } }
true
37c9f72198e2bf6c394f41c633dd1e45ccb555ac
Java
Fedemc/BD3
/Practico3-Ej1/src/Main.java
ISO-8859-3
3,254
2.734375
3
[]
no_license
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.sql.SQLException; import java.util.Properties; import presentacion.VentanaResultados; public class Main { public static void main (String[] args) { String error= new String(); String driver=null; String url=null; String usuario=null; String password=null; Connection con=null; try { /* Obtengo los datos de conexin desde el archivo de configuracin */ Properties p=new Properties(); String nomArch="config/config.properties"; p.load(new FileInputStream(nomArch)); driver=p.getProperty("driver"); url = p.getProperty("url"); usuario=p.getProperty("user"); password=p.getProperty("password"); Class.forName(driver); } catch (ClassNotFoundException e) { error= e.toString(); } catch (FileNotFoundException fEx) { error= fEx.toString(); } catch (IOException ioEx) { error= ioEx.toString(); } try { con = DriverManager.getConnection(url, usuario, password); DatabaseMetaData dbmtd=con.getMetaData(); ResultSet rstDB = dbmtd.getSchemas(null, "escuelapractico3"); con.setAutoCommit(false); con.setTransactionIsolation(con.TRANSACTION_SERIALIZABLE); if(rstDB.next()) { String consultaCrearBD="CREATE DATABASE escuelapractico3;"; String consultaCrearTablaExamenes = "CREATE TABLE examenes(" + "codigo VARCHAR(45), materia VARCHAR(45), periodo VARCHAR(45)," + "PRIMARY KEY (codigo))"; String consultaCrearTablaResultados = "CREATE TABLE resultados(" + "cedula INT, codigo VARCHAR(45), calificacion INT, " + "PRIMARY KEY (cedula), FOREIGN KEY (codigo) REFERENCES Examenes(codigo)" + ");"; System.out.print("Creando BD y tablas.\n"); Statement stmt=con.createStatement(); stmt.executeUpdate(consultaCrearBD); System.out.println("DB creada."); stmt.executeQuery("Use EscuelaPractico3;"); stmt.executeUpdate(consultaCrearTablaExamenes); System.out.println("Tabla examenes creada."); stmt.executeUpdate(consultaCrearTablaResultados); System.out.println("Tabla resultados creada."); String consultaCrearDatosExamenes = "INSERT INTO Examenes" + " values ('MD2012Dic','Matemtica discreta','Diciembre 2012'), " + "('P12012Dic','Programacin','Diciembre 2012'), " + "('BD2012Dic','Bases de datos','Diciembre 2012'), " + "('MD2013Feb','Matemtica discreta','Febrero 2013');"; stmt.executeUpdate(consultaCrearDatosExamenes); stmt.close(); con.commit(); } else { System.out.println("Ya existe la DB."); String usarBD="Use escuelapractico3;"; Statement stmt=con.createStatement(); stmt.executeQuery(usarBD); stmt.close(); } con.setAutoCommit(false); VentanaResultados v = new VentanaResultados(con); v.setVisible(true); } catch (SQLException e) { try { con.rollback(); } catch (SQLException ex) { error=ex.toString(); } error= e.toString(); } } }
true
1f9f9dedde64de3240f56cff5758f6113cef45c4
Java
szendre1/training-solutions
/src/main/java/week05d03/ListCounter.java
UTF-8
723
3.3125
3
[]
no_license
package week05d03; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ListCounter { public int Counter(List<String> myList){ int talalat = 0; for (String x:myList) { if (x.toUpperCase().charAt(0)=='A'){ talalat++; } } return talalat; } public static void main(String[] args) { ListCounter listCounter = new ListCounter(); List<String> myList = new ArrayList<>(Arrays.asList("Az első", "Az első", "Az első")); myList.add("Az első"); myList.add("a második"); myList.add("harmadik"); System.out.println(""+listCounter.Counter(myList)); } }
true
8d021702cbf88c91a7560b0e451907cfb29dc273
Java
vsankara/Kyron
/trips-ejb-module/src/com/technobrain/trips/document/model/DfinDocument.java
UTF-8
746
2.078125
2
[]
no_license
package com.technobrain.trips.document.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.NamedQuery; import javax.persistence.Table; @Entity @NamedQuery(name = "DfinDocument.findAll", query = "select o from DfinDocument o") @Table(name = "DFIN_DOCUMENT") @Inheritance(strategy = InheritanceType.JOINED) public class DfinDocument extends DdocDocument { @Column(name="REASON_CODE", nullable = false) private String reasonCode; public String getReasonCode() { return reasonCode; } public void setReasonCode(String reasonCode) { this.reasonCode = reasonCode; } }
true
b61ba3a1bfddc27fb7aeadb4e1c1f674bbc67600
Java
Bir-Eda/My-Java-Projects
/src/Oracle/ForSale.java
UTF-8
83
2.109375
2
[]
no_license
package Oracle; public interface ForSale { public double getStickerPrice(); }
true
6ac7d31a1764fe00f3b9880104a1ce7928e8c1a9
Java
doublebarrelbuckshot/IFT3911TP3
/IFT3911TP3/src/TransportationPkg/AviationPkg/Economique.java
UTF-8
555
2.21875
2
[]
no_license
package TransportationPkg.AviationPkg; import TransportationPkg.ISearchable; import AdminPkg.ITripVisitor; import CommonComponentsPkg.SearchCriteria; import TransportationPkg.ComfortClass; public class Economique extends ComfortClass { private double _prixPercent = 0.50; public boolean matchCriteria(SearchCriteria aSc) { throw new UnsupportedOperationException(); } public double getPricePercentage() { return this._prixPercent; } @Override public void accept(ITripVisitor visitor) { visitor.visit(this); } }
true
7a73a593caefa55308d7eaa7331f5e6625e148b6
Java
R4ymond1/SpringMall
/src/main/java/cn/gedc/springmall/mapper/ResourceMapper.java
UTF-8
500
1.992188
2
[]
no_license
package cn.gedc.springmall.mapper; import cn.gedc.springmall.bean.MyResourceBean; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Component; import java.util.List; /** * Created by gedc on 2020/12/20. */ @Component @Mapper public interface ResourceMapper { /** * 从数据库中查询所有资源 * @return */ @Select("select * from resource ") List<MyResourceBean> selectAllResource(); }
true
e4d864f38cd8b9a2eab339e49efff3980e65e640
Java
heyuxian/idea-multimarkdown
/src/main/java/com/vladsch/idea/multimarkdown/util/GitHubVcsRoot.java
UTF-8
9,494
1.804688
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2013 Square, Inc. * No license information provided * * Copyright (c) 2015-2015 Vladimir Schneider <vladimir.schneider@gmail.com>, all rights reserved. * * This code is based on code from https://github.com/jawspeak/intellij-plugin-copy-and-open-github-url * * 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.vladsch.idea.multimarkdown.util; import com.google.common.annotations.VisibleForTesting; import com.intellij.openapi.vfs.VirtualFile; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * */ public class GitHubVcsRoot { private static final Logger logger = org.apache.log4j.Logger.getLogger(GitHubVcsRoot.class); final private static Pattern INI_CATEGORY = Pattern.compile("\\[\\s*(\\w+)[\\s'\"]+(\\w+)[\\s'\"]+\\]"); final private static Pattern URL_VALUE = Pattern.compile("\\s*url\\s*=\\s*([^\\s]*)\\.git"); final protected static String GIT_CONFIG = "config"; @NotNull private final String gitHubBaseUrl; @NotNull private final String basePath; @NotNull private final String projectBasePath; private final boolean isWiki; @VisibleForTesting protected GitHubVcsRoot(@NotNull String gitHubBaseUrl, @NotNull String basePath) { // strip out username if the url contains @ from URL // regex: ^(https?://)(?:[^@]*\Q@\E)(.*)$ // replace with $1$2 String _gitHubBaseUrl = gitHubBaseUrl; int atPos = _gitHubBaseUrl.indexOf('@', 7); if ((_gitHubBaseUrl.startsWith("http://") || _gitHubBaseUrl.startsWith("https://")) && atPos > 0) { int prefixPos = _gitHubBaseUrl.startsWith("http://") ? "http://".length() : "https://".length(); _gitHubBaseUrl = _gitHubBaseUrl.substring(0, prefixPos) + _gitHubBaseUrl.substring(atPos+1); //logger.info("cleaned username from url " + gitHubBaseUrl + " -> " + _gitHubBaseUrl); } this.gitHubBaseUrl = StringUtilKt.suffixWith(_gitHubBaseUrl, '/'); this.basePath = StringUtilKt.suffixWith(basePath, '/'); this.isWiki = new FileRef(this.basePath + "Home.md").isUnderWikiDir(); this.projectBasePath = this.isWiki ? new PathInfo(this.basePath).getPath() : this.basePath; } public boolean isWiki() { return isWiki; } @NotNull public String getBasePath() { return basePath; } @NotNull public String getMainRepoBaseDir() { return projectBasePath; } @NotNull public String getBaseUrl() { return gitHubBaseUrl; } @Nullable public String getRelativePath(@Nullable String path) { if (path != null && path.startsWith(basePath)) { return path.substring(basePath.length()); } return null; } @NotNull public String urlForVcsRemote(String relativeFilePath, @Nullable String branchOrTag, @Nullable String gitHubLink) { return urlForVcsRemote(relativeFilePath, null, branchOrTag, gitHubLink); } @Nullable public String urlForVcsRemote(@NotNull VirtualFile virtualFile, boolean withExtension, @Nullable String anchor, @Nullable String branchOrTag, @Nullable String gitHubLink) { PathInfo pathInfo = new PathInfo(virtualFile.getPath()); String relativePath = getRelativePath(withExtension ? pathInfo.getFilePath() : pathInfo.getFilePathNoExt()); return relativePath == null ? null : urlForVcsRemote(relativePath, anchor, branchOrTag, gitHubLink); } @Nullable public String urlForVcsRemote(@NotNull FileRef fileRef, boolean withExtension, @Nullable String anchor, @Nullable String branchOrTag, @Nullable String gitHubLink) { String relativePath = !fileRef.isUnderWikiDir() || withExtension ? getRelativePath(fileRef.getFilePath()) : fileRef.getFileNameNoExt(); if (isWiki && relativePath != null && relativePath.equals("Home")) relativePath = ""; return relativePath == null ? null : urlForVcsRemote(relativePath, anchor, branchOrTag, gitHubLink); } public String urlForVcsRemote(@NotNull String relativeFilePath, @Nullable String anchor, @Nullable String branchOrTag, @Nullable String gitHubLink) { if (isWiki() && relativeFilePath.startsWith("../../wiki")) { relativeFilePath = StringUtilKt.removeStart(relativeFilePath, "../../wiki"); } if (branchOrTag == null || branchOrTag.isEmpty()) branchOrTag = "master"; if (gitHubLink == null || gitHubLink.isEmpty()) gitHubLink = "blob"; return gitHubBaseUrl + (isWiki() ? "wiki/" : gitHubLink + "/" + branchOrTag + "/") + LinkRef.urlEncode(StringUtilKt.removeStart(relativeFilePath, "./")) + StringUtilKt.prefixWith(anchor, '#', false); } @Nullable protected static String getGitPath(@NotNull String filePath) { PathInfo filePathInfo = new PathInfo(filePath).append(".git"); File gitFile = new File(filePathInfo.getFilePath()); String gitPath = null; if (gitFile.exists()) { if (gitFile.isFile()) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(gitFile)); String line; while ((line = reader.readLine()) != null) { // gitdir: ../.git/modules/laravel-translation-manager.isWiki if (line.startsWith("gitdir:")) { line = line.substring("gitdir:".length()).trim(); PathInfo lineInfo = new PathInfo(line); PathInfo configInfo = lineInfo.isRelative() ? filePathInfo.append(line) : lineInfo; gitPath = configInfo.getFilePath(); break; } } } catch (IOException ignored) { logger.info("Could not read " + gitFile, ignored); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } } else { return filePathInfo.getFilePath(); } } return gitPath; } @Nullable protected static String getBaseUrl(@NotNull File gitConfigFile) { String baseUrl = null; BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(gitConfigFile)); String line; boolean inRemoteOriginSection = false; while ((line = reader.readLine()) != null) { if (line.matches("\\s*#")) continue; Matcher matcher = INI_CATEGORY.matcher(line); if (matcher.matches()) { inRemoteOriginSection = "remote".equals(matcher.group(1)) && "origin".equals(matcher.group(2)); continue; } matcher = URL_VALUE.matcher(line); if (inRemoteOriginSection && matcher.matches()) { baseUrl = "https://" + matcher.group(1) .replaceAll("git://|git@|https://", "") .replaceAll(":", "/"); if (baseUrl.endsWith(PathInfo.WIKI_HOME_DIR_EXTENSION)) { FileRef baseUrlInfo = new FileRef(baseUrl); baseUrl = baseUrlInfo.getFilePathNoExt(); } break; } } } catch (IOException ignored) { logger.info("No remote origin in " + gitConfigFile, ignored); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } return baseUrl; } @Nullable public static GitHubVcsRoot getGitHubVcsRoot(@Nullable String path, @Nullable String basePath) { if (path == null || basePath == null) return null; String nextPath = path; do { PathInfo pathInfo = new PathInfo(nextPath); String gitPath = getGitPath(pathInfo.getFilePath()); if (gitPath != null) { File gitConfigFile = new File(gitPath, GIT_CONFIG); if (gitConfigFile.exists() && gitConfigFile.isFile()) { String baseUrl = getBaseUrl(gitConfigFile); if (baseUrl != null) { return new GitHubVcsRoot(baseUrl, pathInfo.getFilePath()); } // this sub-module does not have a remote. return null; } } nextPath = pathInfo.getPath(); } while (!nextPath.isEmpty() && !nextPath.equals("/") && !nextPath.equalsIgnoreCase(basePath)); return null; } }
true
8f1b1ad5fae21ac90a47cd63ffa8487bafb0a5e9
Java
MarsAstro/LudoBoardGame
/src/main/java/no/ntnu/imt3281/ludo/logic/Ludo.java
UTF-8
20,071
3.046875
3
[]
no_license
/** * */ package no.ntnu.imt3281.ludo.logic; import java.util.ArrayList; import java.util.Random; /** * Handles all logic of a ludo game. * * @author oyste * */ public class Ludo { /** * Index of Red player */ public static final int RED = 0; /** * Index of Blue player */ public static final int BLUE = 1; /** * Index of Yellow player */ public static final int YELLOW = 2; /** * Index of Green player */ public static final int GREEN = 3; private static final String WINNER = "Winner: "; private static final String DONE = "Done: "; private static final String INACTIVE = "Inactive: "; private ArrayList<String> playerNames; private ArrayList<DiceListener> diceListeners; private ArrayList<PieceListener> pieceListeners; private ArrayList<PlayerListener> playerListeners; private int[][] piecePositions; private int[][] globalPiecePositions; private int activePlayer = 0; private int numThrows = 0; private int dice = -1; private int selectedPiece = -1; /** * Initialize a game without players */ public Ludo() { playerNames = new ArrayList<>(); for (int i = 0; i < 4; i++) { playerNames.add(null); } diceListeners = new ArrayList<>(); pieceListeners = new ArrayList<>(); playerListeners = new ArrayList<>(); piecePositions = new int[4][4]; globalPiecePositions = new int[4][4]; for (int player = 0; player < 4; player++) { for (int piece = 0; piece < 4; piece++) { globalPiecePositions[player][piece] = piece + player * 4; } } } /** * Initialize a game with already known names * * @param name1 * name of player 1 * @param name2 * name of player 2 * @param name3 * name of player 3 * @param name4 * name of player 4 * @throws NotEnoughPlayersException * thrown if less than 2 players */ public Ludo(String name1, String name2, String name3, String name4) { piecePositions = new int[4][4]; globalPiecePositions = new int[4][4]; diceListeners = new ArrayList<>(); pieceListeners = new ArrayList<>(); playerListeners = new ArrayList<>(); playerNames = new ArrayList<>(); playerNames.add(name1); playerNames.add(name2); playerNames.add(name3); playerNames.add(name4); if (nrOfPlayers() < 2) { throw new NotEnoughPlayersException(); } for (int player = 0; player < 4; player++) { for (int piece = 0; piece < 4; piece++) { globalPiecePositions[player][piece] = piece + player * 4; } } } /** * @return number of players */ public int nrOfPlayers() { int numberOfPlayers = 0; for (int i = 0; i < playerNames.size(); i++) { if (playerNames.get(i) != null) { numberOfPlayers++; } } return numberOfPlayers; } /** * Gets player name from index * * @param index * index representing a color * @return name of player at index */ public String getPlayerName(int index) { return playerNames.get(index); } /** * Adds a new player to the game * * @param newPlayer * name of the new player * @throws NoRoomForMorePlayersException * thrown if game is full */ public void addPlayer(String newPlayer) { if (nrOfPlayers() < 4) { for (int player = 0; player < 4; player++) { if (playerNames.get(player) == null) { playerNames.set(player, newPlayer); break; } } } else { throw new NoRoomForMorePlayersException(); } } /** * Remove player from gave entirely * * @param name * Name of player to be discarded */ public void discardPlayer(String name) { for (int player = 0; player < playerNames.size(); player++) { if (playerNames.get(player) != null && playerNames.get(player).equals(name)) { playerNames.set(player, null); } } } /** * Sets player with name as inactive * * @param name * Name of player to be set inactive */ public void removePlayer(String name) { for (int player = 0; player < playerNames.size(); player++) { if (playerNames.get(player) != null && playerNames.get(player).equals(name)) { playerNames.set(player, INACTIVE + playerNames.get(player)); removePiecesOnBoard(player); for (PlayerListener listener : playerListeners) { listener.playerStateChanged( new PlayerEvent(this, player, PlayerEvent.LEFTGAME)); } if (player == activePlayer) { nextPlayer(); } } } } private void removePiecesOnBoard(int player) { for (int piece = 0; piece < 4; piece++) { if (piecePositions[player][piece] != 0) { int prevPos = piecePositions[player][piece]; piecePositions[player][piece] = 0; globalPiecePositions[player][piece] = 0; for (PieceListener listener : pieceListeners) { listener.pieceMoved(new PieceEvent(this, player, piece, prevPos, 0)); } } } } /** * @return number of active players */ public int activePlayers() { int count = 0; for (int player = 0; player < playerNames.size(); player++) { if (playerNames.get(player) != null && !playerNames.get(player).contains("Inactive:")) { count++; } } return count; } /** * Find position of a specific piece * * @param player * player that owns that piece * @param piece * index of piece * @return the piece position on the board */ public int getPosition(int player, int piece) { return piecePositions[player][piece]; } /** * @return active player */ public int activePlayer() { return activePlayer; } /** * @return A randomly generated die throw */ public int throwDice() { Random random = new Random(); random.setSeed(System.currentTimeMillis()); return throwDice(random.nextInt(6) + 1); } /** * Takes a die throw and handles the game logic around dice * * @param dice * dice * @return The die throw */ public int throwDice(int dice) { this.dice = dice; for (DiceListener listener : diceListeners) { listener.diceThrown(new DiceEvent(this, activePlayer, dice)); } if (allHome()) { numThrows++; if (numThrows >= 3 && dice != 6) { nextPlayer(); } } else { if (canMove()) { numThrows++; if (dice == 6 && numThrows > 2) { nextPlayer(); } } else { nextPlayer(); } } return dice; } /** * Goes through all of the pieces for the active player and determines if * anyone of them can move * * @return A piece is able to move */ public boolean canMove() { boolean movable = false; for (int piece = 0; piece < 4; piece++) { boolean homeWithSix = piecePositions[activePlayer][piece] == 0 && dice == 6; boolean onBoard = piecePositions[activePlayer][piece] + dice < 60 && piecePositions[activePlayer][piece] != 0; if (!isBlocked(piece) && (onBoard || homeWithSix)) { movable = true; break; } } return movable; } /** * Checks if a piece is blocked by a tower * * @param currentPiece * piece to check for current player * @return if piece is blocked */ private boolean isBlocked(int currentPiece) { boolean isBlocked = false; for (int player = 0; player < playerNames.size(); player++) { if (player != activePlayer && isBlockedByPlayer(currentPiece, player)) { isBlocked = true; } } return isBlocked; } private boolean isBlockedByPlayer(int currentPiece, int player) { boolean isBlockedByPlayer = false; for (int piece = 0; piece < 4; piece++) { for (int otherPiece = piece + 1; otherPiece < 4; otherPiece++) { isBlockedByPlayer = checkForTower(currentPiece, player, isBlockedByPlayer, piece, otherPiece); } } return isBlockedByPlayer; } private boolean checkForTower(int currentPiece, int player, boolean isBlockedByPlayer, int piece, int otherPiece) { if (piecePositions[player][piece] == piecePositions[player][otherPiece]) { int towerPos = globalPiecePositions[player][piece]; if (towerIsBlocking(currentPiece, towerPos)) { isBlockedByPlayer = true; } } return isBlockedByPlayer; } private boolean towerIsBlocking(int currentPiece, int towerPos) { boolean towerIsBlocking = false; for (int i = 1; i <= dice; i++) { if (userGridToLudoBoardGrid(activePlayer, piecePositions[activePlayer][currentPiece] + i) == towerPos) { towerIsBlocking = true; } } return towerIsBlocking; } /** * Sets the next player as active */ private void nextPlayer() { numThrows = 0; dice = 0; for (PlayerListener listener : playerListeners) { listener.playerStateChanged(new PlayerEvent(this, activePlayer, PlayerEvent.WAITING)); } activePlayer = (activePlayer + 1) % playerNames.size(); for (PlayerListener listener : playerListeners) { listener.playerStateChanged(new PlayerEvent(this, activePlayer, PlayerEvent.PLAYING)); } String activeName = playerNames.get(activePlayer); boolean somePlayerValid = activePlayers() > 0 && (activeName == null || nameContainsTag(activeName)); if (!noPlayingPlayers() && somePlayerValid) { nextPlayer(); } } private boolean nameContainsTag(String activeName) { return activeName.contains(INACTIVE) || activeName.contains(WINNER) || activeName.contains(DONE); } private boolean noPlayingPlayers() { boolean bool = true; for (int player = 0; player < playerNames.size(); player++) { if (playerNames.get(player) != null && !(playerNames.get(player).contains(INACTIVE) || playerNames.get(player).contains(WINNER) || playerNames.get(player).contains(DONE))) { bool = false; } } return bool; } /** * Moves a piece * * @param player * Player index * @param from * Tile to move from * @param to * Tile to move to * @return If move was successful */ public boolean movePiece(int player, int from, int to) { boolean success = false; if (((from == 0 && dice == 6) || from + dice == to) && player == activePlayer) { if (selectedPiece == -1) { selectFirstValidPiece(player, from); } if (!isBlocked(selectedPiece)) { success = performMove(player, from, to); } } return success; } private boolean performMove(int player, int from, int to) { boolean success; piecePositions[player][selectedPiece] = to; for (PieceListener listener : pieceListeners) { listener.pieceMoved(new PieceEvent(this, player, selectedPiece, from, to)); } success = true; checkWinner(); if (numThrows >= 3 || dice != 6 || from == 0) { nextPlayer(); } checkForOpponents(player, to); updateGlobalPositions(); dice = 0; selectedPiece = -1; return success; } private void selectFirstValidPiece(int player, int from) { for (int piece = 0; piece < 4; piece++) { if (piecePositions[player][piece] == from) { selectedPiece = piece; break; } } } /** * @return Game status */ public String getStatus() { String state = "Created"; if (nrOfPlayers() != 0) { state = "Initiated"; } if (dice != -1) { state = "Started"; } for (int i = 0; i < playerNames.size(); i++) { boolean finished = true; for (int j = 0; j < 4; j++) { if (piecePositions[i][j] != 59) { finished = false; } } if (finished) { state = "Finished"; activePlayer = i; break; } } return state; } /** * @return winner */ public int getWinner() { int winner = -1; for (int player = 0; player < playerNames.size(); ++player) { if (playerNames.get(player) != null && playerNames.get(player).contains(WINNER)) { winner = player; } } return winner; } /** * @return if all pieces of active player is home */ private boolean allHome() { for (int i = 0; i < 4; i++) { if (piecePositions[activePlayer][i] != 0) { return false; } } return true; } private void checkWinner() { boolean finished = true; for (int piece = 0; piece < 4; piece++) { if (piecePositions[activePlayer][piece] != 59) { finished = false; } } if (finished) { String prefix = ""; int state = -1; if (getWinner() == -1) { prefix = WINNER; state = PlayerEvent.WON; } else { prefix = DONE; state = PlayerEvent.DONE; } playerNames.set(activePlayer, prefix + playerNames.get(activePlayer)); for (PlayerListener listener : playerListeners) { listener.playerStateChanged(new PlayerEvent(this, activePlayer, state)); } } } /** * Converts player position to ludo board grid * * @param player * The player * @param pos * Player position * @return the ludo board grid index */ public static int userGridToLudoBoardGrid(int player, int pos) { int result = 0; if (pos == 0) { result = 4 * player; } else if (pos < 54) { result = (player * 13 + pos - 1) % 52 + 16; } else { result = 68 + (pos - 54) + 6 * player; } return result; } /** * Converts global positions above 67 to players local grid * * @param player * The player space to convert to * @param pos * The position to convert * @return Local position of global input for supplied player if global * input is above 67, -1 otherwise */ public int finalTilesLudoBoardGridToUserGrid(int player, int pos) { int result = -1; if (pos > 67) { result = pos - 14 - player * 6; } return result; } /** * Checks whether someone stands on a piece's destination position. And * moves them back if landed on * * @param player * Player index * @param pos * Local position to check for opponent at */ private void checkForOpponents(int player, int pos) { int playerPos = userGridToLudoBoardGrid(player, pos); for (int otherPlayer = 0; otherPlayer < playerNames.size(); otherPlayer++) { if (otherPlayer != player) { for (int piece = 0; piece < 4; piece++) { checkForPieceOverlap(playerPos, otherPlayer, piece); } } } } private void checkForPieceOverlap(int playerPos, int otherPlayer, int piece) { if (userGridToLudoBoardGrid(otherPlayer, piecePositions[otherPlayer][piece]) == playerPos) { for (PieceListener listener : pieceListeners) { listener.pieceMoved(new PieceEvent(this, otherPlayer, piece, piecePositions[otherPlayer][piece], 0)); } piecePositions[otherPlayer][piece] = 0; globalPiecePositions[otherPlayer][piece] = 4 * otherPlayer; } } /** * Updates array of global piece positions */ private void updateGlobalPositions() { for (int player = 0; player < playerNames.size(); player++) { for (int piece = 0; piece < 4; piece++) { if (piecePositions[player][piece] > 0) { globalPiecePositions[player][piece] = userGridToLudoBoardGrid(player, piecePositions[player][piece]); } } } } /** * Adds dice listener * * @param diceListener * DiceListener to add */ public void addDiceListener(DiceListener diceListener) { diceListeners.add(diceListener); } /** * Adds piece listener * * @param pieceListener * PieceListener to add */ public void addPieceListener(PieceListener pieceListener) { pieceListeners.add(pieceListener); } /** * Adds player listener * * @param playerListener * PlayerListener to add */ public void addPlayerListener(PlayerListener playerListener) { playerListeners.add(playerListener); } /** * Gets the index of player * * @param name * The suggested player name * @return Index of player */ public int getIndexOfPlayer(String name) { int index = -1; for (int player = 0; player < 4; player++) { String playerName = playerNames.get(player); if (playerName != null) { // Strip tags off name to ensure we're comparing the bare // usernames against eachother String strippedName = playerName .replaceFirst("((Winner: )|(Done: )|(Inactive: )){1}", ""); if (strippedName.equals(name)) { index = player; break; } } } return index; } /** * @return The piece positions */ public final int[][] getPiecePositions() { return piecePositions.clone(); } /** * @return The global piece positions */ public final int[][] getGlobalPiecePositions() { return globalPiecePositions.clone(); } /** * @param selectedPiece * The piece to attempt moving in MovePiece */ public void setSelectedPiece(int selectedPiece) { this.selectedPiece = selectedPiece; } }
true
a2aedaf825e7280462e156d97916fd4161a74045
Java
riyuetian/v13
/v13-temp/temp-zookeeper/src/test/java/com/qf/zk/MyWatcher.java
UTF-8
505
2.34375
2
[]
no_license
package com.qf.zk; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; /** * @author Mr_Ma * Version: 1.0 2019/7/417:16 * @description: TODO */ public class MyWatcher implements Watcher { @Override public void process(WatchedEvent event) { System.out.println("监听的节点发生了变化...."); System.out.println("发生变化的节点:" + event.getPath()); System.out.println("发生了什么变化:" + event.getType()); } }
true
c60ad552bf0bf4a3f9dedcae75576edae7ce01cb
Java
stnevans/BytecodeParser
/site/shadyside/exception/InvalidFileFormatException.java
UTF-8
352
2.171875
2
[]
no_license
package site.shadyside.exception; import java.io.IOException; public class InvalidFileFormatException extends IOException{ public InvalidFileFormatException(String string) { super(string); } public InvalidFileFormatException(Exception e) { super(e); } /** * */ private static final long serialVersionUID = -5004846744866969063L; }
true
a50a61e712c2a47adc6d05fd4cf628091042db0c
Java
ascending-llc/spring-redis
/src/main/java/io/ascending/training/controller/CarController.java
UTF-8
1,651
2.328125
2
[]
no_license
package io.ascending.training.controller; import io.ascending.training.domain.Car; import io.ascending.training.repository.CarRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(value = "/api/cars", produces = MediaType.APPLICATION_JSON_VALUE) public class CarController { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private CarRepository carRepository; //unless = "#result.followers < 12000" @Cacheable(value = "cars") @RequestMapping(value = "/{id}", method = RequestMethod.GET) public Car getCars(@PathVariable(name="id") Long Id) { logger.info("Getting user with ID {}.", Id); Car result = carRepository.findById(Id).get(); return result; } @Cacheable(value = "cars") @RequestMapping(method = RequestMethod.GET) public List<Car> getAllCars() { logger.info("Getting all cars"); List<Car> result = carRepository.findAll(); return result; } @CachePut(value = "cars", key = "#car.id", unless = "#car.brand == null") @RequestMapping(method = RequestMethod.POST) // @CacheEvict(value = "cars", allEntries = true) public Car generateCar(@RequestBody Car car) { return carRepository.save(car); } }
true
4039f9d1770424115f035f82e950f4e8debf3abc
Java
katiefotion/POST2
/POSTB/src/Transaction/Payment.java
UTF-8
865
3
3
[]
no_license
package Transaction; /** * * @author katie */ public class Payment { private String typePayment; private double paymentTotal; private String cardNumber; public Payment(String type, double total) { this.typePayment = type; this.paymentTotal = total; this.cardNumber = ""; } public Payment(String type, String card) { this.typePayment = type; this.paymentTotal = 0.0; this.cardNumber = card; } // Getter methods public String getTypePayment() { return this.typePayment; } public String getCardNumber() { return this.cardNumber; } public double getPaymentTotal() { return this.paymentTotal; } // Setter methods public void setPaymentTotal(double total) { this.paymentTotal = total; } }
true
640064594dfea5d46b6b7a2e52f033bc46c526dc
Java
antoniosergius/serginho-jlib
/src/br/com/antoniosergius/lib/util/io/XMLStream.java
UTF-8
2,110
2.453125
2
[]
no_license
package br.com.antoniosergius.lib.util.io; import br.com.antoniosergius.lib.gui.utils.LookAndFeel; import br.com.antoniosergius.lib.util.MySQLParameters; import com.thoughtworks.xstream.XStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class XMLStream { private XStream xstream; private Configuration configuration; public XMLStream() { xstream = new XStream(); xstream.registerConverter(new XConverter<>()); xstream.alias("system", Configuration.class); xstream.alias("mysql", MySQLParameters.class); xstream.useAttributeFor(MySQLParameters.class, "server"); xstream.useAttributeFor(MySQLParameters.class, "port"); xstream.useAttributeFor(MySQLParameters.class, "database"); xstream.useAttributeFor(MySQLParameters.class, "user"); xstream.useAttributeFor(MySQLParameters.class, "encryptedPassword"); xstream.alias("lookAndFeel", LookAndFeel.class); xstream.useAttributeFor(LookAndFeel.class, "className"); } public XStream getXStream() { return xstream; } public void setXStream(XStream xstream) { this.xstream = xstream; } public Configuration read() throws IOException { File file = new File(Path.APP+"config.xml"); if (file.exists() && file.length()>0L) { configuration = (Configuration) xstream.fromXML(file); } else { file.createNewFile(); configuration = new Configuration(new MySQLParameters("localhost", 3306, "chequemate", "user", "*****"),new LookAndFeel("org.pushingpixels.substance.api.skin.MarinerSkin")); write(configuration); } return configuration; } public void write(Configuration configuration) throws IOException { try (BufferedWriter buffer = new BufferedWriter(new FileWriter( Path.APP+"config.xml"))) { buffer.write( xstream.toXML(configuration) ); buffer.flush(); } } }
true
25a43d39e724b794e8aae577fa97ed123e341336
Java
lucascraft/iorx
/iorx/src/main/java/ubiquisense/iorx/media/fmodex/impl/FMGeometryImpl.java
UTF-8
496
1.851563
2
[]
no_license
/** * <copyright> * </copyright> * * $Id$ */ package ubiquisense.iorx.media.fmodex.impl; import org.jouvieje.fmodex.Geometry; import ubiquisense.iorx.media.fmodex.FMGeometry; public class FMGeometryImpl implements FMGeometry { protected static final Geometry FMODEX_EDEFAULT = null; protected Geometry fmodex = FMODEX_EDEFAULT; public Geometry getFmodex() { return fmodex; } public void setFmodex(Geometry newFmodex) { fmodex = newFmodex; } } //FMGeometryImpl
true
04b62db47a4be8e359c58c5198ff66a7bf5e4264
Java
Niukun/Paper
/HtmlUtil.java
UTF-8
789
2.5625
3
[]
no_license
package niukun.utils; import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class HtmlUtil { public static void main(String[] args) { } /** * 根据url从网页获取文本 * @param url * @return */ public Document getHtmlTextByUrl(String url) { Document doc = null; try { int i = (int)(Math.random()*1000);//随机延迟,防止网站屏蔽 while(i!=0) { i--; } doc = Jsoup.connect(url).data("query","java").userAgent("Mosilla").cookie("auth", "token").timeout(3000000).post(); }catch (IOException e) { e.printStackTrace(); try { doc = Jsoup.connect(url).timeout(5000000).get(); } catch (Exception e2) { e2.printStackTrace(); } } return doc; } }
true
c3fd964e7f2809664306527436febece75ed8e73
Java
kaazing/gateway
/mina.core/core/src/main/java/org/apache/mina/filter/codec/demux/DemuxingProtocolDecoder.java
UTF-8
10,716
2.21875
2
[ "LicenseRef-scancode-jdom", "MIT", "MPL-1.1", "JSON", "LGPL-2.1-or-later", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "ICU", "BSD-3-Clause" ]
permissive
/** * Copyright 2007-2016, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mina.filter.codec.demux; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.AttributeKey; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderException; import org.apache.mina.filter.codec.ProtocolDecoderOutput; /** * A composite {@link ProtocolDecoder} that demultiplexes incoming {@link IoBuffer} * decoding requests into an appropriate {@link MessageDecoder}. * * <h2>Internal mechanism of {@link MessageDecoder} selection</h2> * <p> * <ol> * <li>{@link DemuxingProtocolDecoder} iterates the list of candidate * {@link MessageDecoder}s and calls {@link MessageDecoder#decodable(IoSession, IoBuffer)}. * Initially, all registered {@link MessageDecoder}s are candidates.</li> * <li>If {@link MessageDecoderResult#NOT_OK} is returned, it is removed from the candidate * list.</li> * <li>If {@link MessageDecoderResult#NEED_DATA} is returned, it is retained in the candidate * list, and its {@link MessageDecoder#decodable(IoSession, IoBuffer)} will be invoked * again when more data is received.</li> * <li>If {@link MessageDecoderResult#OK} is returned, {@link DemuxingProtocolDecoder} * found the right {@link MessageDecoder}.</li> * <li>If there's no candidate left, an exception is raised. Otherwise, * {@link DemuxingProtocolDecoder} will keep iterating the candidate list. * </ol> * * Please note that any change of position and limit of the specified {@link IoBuffer} * in {@link MessageDecoder#decodable(IoSession, IoBuffer)} will be reverted back to its * original value. * <p> * Once a {@link MessageDecoder} is selected, {@link DemuxingProtocolDecoder} calls * {@link MessageDecoder#decode(IoSession, IoBuffer, ProtocolDecoderOutput)} continuously * reading its return value: * <ul> * <li>{@link MessageDecoderResult#NOT_OK} - protocol violation; {@link ProtocolDecoderException} * is raised automatically.</li> * <li>{@link MessageDecoderResult#NEED_DATA} - needs more data to read the whole message; * {@link MessageDecoder#decode(IoSession, IoBuffer, ProtocolDecoderOutput)} * will be invoked again when more data is received.</li> * <li>{@link MessageDecoderResult#OK} - successfully decoded a message; the candidate list will * be reset and the selection process will start over.</li> * </ul> * * @author <a href="http://mina.apache.org">Apache MINA Project</a> * * @see MessageDecoderFactory * @see MessageDecoder */ public class DemuxingProtocolDecoder extends CumulativeProtocolDecoder { private final AttributeKey STATE = new AttributeKey(getClass(), "state"); private MessageDecoderFactory[] decoderFactories = new MessageDecoderFactory[0]; private static final Class<?>[] EMPTY_PARAMS = new Class[0]; public DemuxingProtocolDecoder() { // Do nothing } public void addMessageDecoder(Class<? extends MessageDecoder> decoderClass) { if (decoderClass == null) { throw new NullPointerException("decoderClass"); } try { decoderClass.getConstructor(EMPTY_PARAMS); } catch (NoSuchMethodException e) { throw new IllegalArgumentException( "The specified class doesn't have a public default constructor."); } boolean registered = false; if (MessageDecoder.class.isAssignableFrom(decoderClass)) { addMessageDecoder(new DefaultConstructorMessageDecoderFactory(decoderClass)); registered = true; } if (!registered) { throw new IllegalArgumentException( "Unregisterable type: " + decoderClass); } } public void addMessageDecoder(MessageDecoder decoder) { addMessageDecoder(new SingletonMessageDecoderFactory(decoder)); } public void addMessageDecoder(MessageDecoderFactory factory) { if (factory == null) { throw new NullPointerException("factory"); } MessageDecoderFactory[] decoderFactories = this.decoderFactories; MessageDecoderFactory[] newDecoderFactories = new MessageDecoderFactory[decoderFactories.length + 1]; System.arraycopy(decoderFactories, 0, newDecoderFactories, 0, decoderFactories.length); newDecoderFactories[decoderFactories.length] = factory; this.decoderFactories = newDecoderFactories; } @Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { State state = getState(session); if (state.currentDecoder == null) { MessageDecoder[] decoders = state.decoders; int undecodables = 0; for (int i = decoders.length - 1; i >= 0; i--) { MessageDecoder decoder = decoders[i]; int limit = in.limit(); int pos = in.position(); MessageDecoderResult result; try { result = decoder.decodable(session, in); } finally { in.position(pos); in.limit(limit); } if (result == MessageDecoder.OK) { state.currentDecoder = decoder; break; } else if (result == MessageDecoder.NOT_OK) { undecodables++; } else if (result != MessageDecoder.NEED_DATA) { throw new IllegalStateException( "Unexpected decode result (see your decodable()): " + result); } } if (undecodables == decoders.length) { // Throw an exception if all decoders cannot decode data. String dump = in.getHexDump(); in.position(in.limit()); // Skip data ProtocolDecoderException e = new ProtocolDecoderException( "No appropriate message decoder: " + dump); e.setHexdump(dump); throw e; } if (state.currentDecoder == null) { // Decoder is not determined yet (i.e. we need more data) return false; } } MessageDecoderResult result = state.currentDecoder.decode(session, in, out); if (result == MessageDecoder.OK) { state.currentDecoder = null; return true; } else if (result == MessageDecoder.NEED_DATA) { return false; } else if (result == MessageDecoder.NOT_OK) { state.currentDecoder = null; throw new ProtocolDecoderException( "Message decoder returned NOT_OK."); } else { state.currentDecoder = null; throw new IllegalStateException( "Unexpected decode result (see your decode()): " + result); } } @Override public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception { super.finishDecode(session, out); State state = getState(session); MessageDecoder currentDecoder = state.currentDecoder; if (currentDecoder == null) { return; } currentDecoder.finishDecode(session, out); } @Override public void dispose(IoSession session) throws Exception { super.dispose(session); session.removeAttribute(STATE); } private State getState(IoSession session) throws Exception { State state = (State) session.getAttribute(STATE); if (state == null) { state = new State(); State oldState = (State) session.setAttributeIfAbsent(STATE, state); if (oldState != null) { state = oldState; } } return state; } private class State { private final MessageDecoder[] decoders; private MessageDecoder currentDecoder; private State() throws Exception { MessageDecoderFactory[] decoderFactories = DemuxingProtocolDecoder.this.decoderFactories; decoders = new MessageDecoder[decoderFactories.length]; for (int i = decoderFactories.length - 1; i >= 0; i--) { decoders[i] = decoderFactories[i].getDecoder(); } } } private static class SingletonMessageDecoderFactory implements MessageDecoderFactory { private final MessageDecoder decoder; private SingletonMessageDecoderFactory(MessageDecoder decoder) { if (decoder == null) { throw new NullPointerException("decoder"); } this.decoder = decoder; } public MessageDecoder getDecoder() { return decoder; } } private static class DefaultConstructorMessageDecoderFactory implements MessageDecoderFactory { private final Class<?> decoderClass; private DefaultConstructorMessageDecoderFactory(Class<?> decoderClass) { if (decoderClass == null) { throw new NullPointerException("decoderClass"); } if (!MessageDecoder.class.isAssignableFrom(decoderClass)) { throw new IllegalArgumentException( "decoderClass is not assignable to MessageDecoder"); } this.decoderClass = decoderClass; } public MessageDecoder getDecoder() throws Exception { return (MessageDecoder) decoderClass.newInstance(); } } }
true
1ecf317e05f5cf6fefbf504d59693cfc6f430ee3
Java
0moura/tiktok_source
/df_miniapp/classes/com/bytedance/sandboxapp/b/a/a/b.java
UTF-8
1,061
1.804688
2
[]
no_license
package com.bytedance.sandboxapp.b.a.a; import d.f.b.l; public final class b implements a { public static a a; public static final b b = new b(); private static boolean c; public static void a(boolean paramBoolean) { c = paramBoolean; } public final boolean isDebugMode() { return c; } public final void logOrThrow(String paramString, Object... paramVarArgs) { l.b(paramVarArgs, "messages"); a a1 = a; if (a1 != null) a1.logOrThrow(paramString, new Object[] { com.bytedance.sandboxapp.b.a.b.b.a(paramVarArgs) }); } public final void logOrToast(String paramString, Object... paramVarArgs) { l.b(paramVarArgs, "messages"); a a1 = a; if (a1 != null) a1.logOrToast(paramString, new Object[] { com.bytedance.sandboxapp.b.a.b.b.a(paramVarArgs) }); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\sandboxapp\b\a\a\b.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
true
d3bcb6e468253b790032b1a344e3e450b1b6519d
Java
Be-Simple-Korean/Study_Room_VM_DataBinding
/app/src/main/java/com/example/studyviewmodel/TodoDAO.java
UTF-8
672
2.4375
2
[]
no_license
package com.example.studyviewmodel; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import java.util.List; @Dao //DATA ACCESS OBJECT = 룸에 있는 데이터에 접근하는 객체 // = 데이터 접근 = SELECT, INSERT, UPDATE , DELETE interface TodoDAO { @Query("SELECT * FROM Todo") LiveData<List<Todo>> getAll(); //라이브 데이터를 감싸주면 getAll 메소드는 관찰 가능한 객체가 됨 @Insert void insert(Todo todo); @Update void update(Todo todo); @Delete void delete(Todo todo); }
true
4293d71430cfdb6ac1aadc34c80cebd324604dce
Java
mesut6283/ListItem1
/app/src/main/java/com/masoud/example/listitem1/MainActivity.java
UTF-8
1,703
2.53125
3
[]
no_license
package com.masoud.example.listitem1; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ExpandableListView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MainActivity extends AppCompatActivity { ExpandableListView expandableListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); expandableListView= (ExpandableListView) findViewById(R.id.expandableListView); List<String> heading=new ArrayList<String>(); List<String> L1=new ArrayList<String>(); List<String> L2=new ArrayList<String>(); List<String> L3=new ArrayList<String>(); HashMap<String,List<String>> childList=new HashMap<String, List<String>>(); String heading_item[]=getResources().getStringArray(R.array.header_title); String l1[]=getResources().getStringArray(R.array.h1_Items); String l2[]=getResources().getStringArray(R.array.h2_Items); String l3[]=getResources().getStringArray(R.array.h3_Items); for(String title : heading_item){ heading.add(title); } for(String title : l1){ L1.add(title); } for(String title : l2){ L2.add(title); } for(String title : l3){ L3.add(title); } childList.put(heading.get(0),L1); childList.put(heading.get(1),L2); childList.put(heading.get(2),L3); MyAdapter myAdapter=new MyAdapter(this,heading,childList); expandableListView.setAdapter(myAdapter); } }
true
e3b6cf4c938877985010804e0e8594b0d7e81e50
Java
bingoohuang/npf-blackcat
/npf-blackcat/src/test/java/com/github/bingoohuang/blackcat/utils/UnsensitiveConfigTest.java
UTF-8
2,489
2.59375
3
[ "Apache-2.0" ]
permissive
package com.github.bingoohuang.blackcat.utils; import org.junit.Test; import static com.google.common.truth.Truth.assertThat; public class UnsensitiveConfigTest { @Test public void testKeyValueInJSON() { UnsensitiveConfig config = new UnsensitiveConfig( "(?<=\"PASSWORD\":\").*?(?=\"[,\\]}])"); String filter = config.filter("{\"PASSWORD\":\"BINGOOHUANG\"}"); assertThat(filter).isEqualTo("{\"PASSWORD\":\"***\"}"); } @Test public void testKeyValue() { UnsensitiveConfig config = new UnsensitiveConfig( "(?<=PASSWORD:)[^\\s]+"); String filter = config.filter("PASSWORD:BINGOOHUANG"); assertThat(filter).isEqualTo("PASSWORD:***"); } @Test public void testKeyValue0() { UnsensitiveConfig config = new UnsensitiveConfig( "(?<=PASSWORD:)[^\\s]+"); String filter = config.filter("PASSWORD:BINGOOHUANG, NAME:BINGOO"); assertThat(filter).isEqualTo("PASSWORD:*** NAME:BINGOO"); } @Test public void testKeyValue2() { UnsensitiveConfig config = new UnsensitiveConfig( "(?<=PASSWORD:)[^\\s]+", "%%%"); String filter = config.filter("PASSWORD:BINGOOHUANG"); assertThat(filter).isEqualTo("PASSWORD:%%%"); } @Test public void testKeyValue3() { UnsensitiveConfig config = new UnsensitiveConfig( "(?<=PASSWORD:)[^\\s]+", "\\$\\$\\$"); String filter = config.filter("PASSWORD:BINGOOHUANG"); assertThat(filter).isEqualTo("PASSWORD:$$$"); } @Test public void testXML() { UnsensitiveConfig config = new UnsensitiveConfig( "(?is)(?<=<PASSWORD>).*(?=</PASSWORD>)"); String filter = config.filter("<PASSWORD>BINGOOHUANG</PASSWORD>"); assertThat(filter).isEqualTo("<PASSWORD>***</PASSWORD>"); filter = config.filter("<PASSWORD>\r\nBINGOOHUANG\r\n</PASSWORD>"); assertThat(filter).isEqualTo("<PASSWORD>***</PASSWORD>"); filter = config.filter("<password>\r\nBINGOOHUANG\r\n</password>"); assertThat(filter).isEqualTo("<password>***</password>"); } @Test public void testPattern() { UnsensitiveConfig config = new UnsensitiveConfig( "(\\d{3})\\d{3}(?:19|20)\\d{2}(?:0|1)\\d(?:[0123])\\d{2}(\\d{3})", "$1***$2"); String filter = config.filter("130105199601011336"); assertThat(filter).isEqualTo("130***336"); } }
true
30c3041ce396e4f488a406ad79a7a13da322c1a9
Java
aw12sds/zxerp
/.svn/pristine/5a/5a4cfc03652eda33ab0afe9d6ece941a584639a4.svn-base
UTF-8
1,128
2
2
[]
no_license
package jehc.solrmodules.solrdao; import java.util.List; import java.util.Map; import jehc.solrmodules.solrmodel.SolrIndexAttribute; /** * 索引更多属性 * 2016-07-10 22:19:49 邓纯杰 */ public interface SolrIndexAttributeDao{ /** * 分页 * @param condition * @return */ public List<SolrIndexAttribute> getSolrIndexAttributeListByCondition(Map<String,Object> condition); /** * 查询对象 * @param solr_index_attribute_id * @return */ public SolrIndexAttribute getSolrIndexAttributeById(String solr_index_attribute_id); /** * 添加 * @param solr_index_attribute * @return */ public int addSolrIndexAttribute(SolrIndexAttribute solr_Index_Attribute); /** * 修改 * @param solr_index_attribute * @return */ public int updateSolrIndexAttribute(SolrIndexAttribute solr_Index_Attribute); /** * 删除 * @param condition * @return */ public int delSolrIndexAttribute(Map<String,Object> condition); /** * 根据实例编号查找其下面属性字段 * @param condition * @return */ public List<SolrIndexAttribute> getSolrIndexAttributeList(Map<String,Object> condition); }
true
1c4e9c68a3530f725504d509c8b95758b59a6bdb
Java
LiubovHrzhymalo/qa_nix_2
/unit_7_patters/src/main/java/ua/com/alevel/entity/Owner.java
UTF-8
887
2.203125
2
[]
no_license
package ua.com.alevel.entity; import java.util.ArrayList; import java.util.List; public class Owner extends BaseEntity { private String firstName; private String lastName; private boolean isVisible; private List<String> petIds = new ArrayList<>(); 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 boolean isVisible() { return isVisible; } public void setVisible(boolean visible) { isVisible = visible; } public List<String> getPetIds() { return petIds; } public void setPetIds(List<String> petIds) { this.petIds = petIds; } }
true
b4ed1598d261c50e5ad8f6e68e789dee544b5fcb
Java
zhaomengxia/example
/common/src/main/java/com/linln/common/interfaces/F.java
UTF-8
632
3.0625
3
[ "Apache-2.0" ]
permissive
package com.linln.common.interfaces; /** * 因为抽象类中可以没有抽象方法,即存在有方法体的方法 * java之所以只能单继承,是因为如果D和E中存在相同的方法,F不知道调用哪个类的这个方法。 * 为什么只能单继承,主要是防止多个类有相同的方法名,但方法体不一样,子类就不知道难选了。故java和C#都不支持多继承 * @Author zhaomengxia * @create 2019/7/15 13:42 */ public class F extends D { @Override public String eat() { return null; } @Override public String drink() { return null; } }
true
d96514445b272fc90221c76d378bc3aaadef21f7
Java
redsun9/leetcode
/src/leetcode/leetcode16xx/leetcode1688/Solution.java
UTF-8
139
1.6875
2
[]
no_license
package leetcode.leetcode16xx.leetcode1688; public class Solution { public int numberOfMatches(int n) { return n - 1; } }
true
1277d5cd88cc9e6a1f17048f5f9eeccb383b7dcc
Java
sahil804/Baking_App
/app/src/main/java/com/example/suris/baking_app/ui/RecipesListActivityFragment.java
UTF-8
5,844
1.984375
2
[]
no_license
package com.example.suris.baking_app.ui; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.suris.baking_app.R; import com.example.suris.baking_app.adapter.RecipeListAdapter; import com.example.suris.baking_app.data.models.Recipe; import com.example.suris.baking_app.utils.BakingIdlingResource; import com.example.suris.baking_app.utils.PreferenceUtility; import com.example.suris.baking_app.viewModel.RecipeListViewModel; import com.example.suris.baking_app.widget.BakingWidgetRemoteViewsService; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import timber.log.Timber; /** * A placeholder fragment containing a simple view. */ public class RecipesListActivityFragment extends Fragment implements RecipeListAdapter.RecipeAdapterOnClickHandler{ public static final String TAG = RecipesListActivityFragment.class.getSimpleName(); public static final String ID_EXTRA_INTENT = "recipe_id"; @BindView(R.id.rv_recipe_list) RecyclerView mRecyclerView; /*@BindView(R.id.swipeToRefresh) SwipeRefreshLayout swipeRefreshLayout;*/ private RecipeListViewModel mViewModel; private RecipeListAdapter mAdapter; BakingIdlingResource idlingResource; public RecipesListActivityFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_recipes_list, container, false); ButterKnife.bind(this, view); idlingResource = (BakingIdlingResource) ((RecipesListActivity) getActivity()).getIdlingResource(); if (idlingResource != null) { idlingResource.setIdleState(false); } intialiseRecyclerView(); initialiseViewModel(); Bundle bundle = getActivity().getIntent().getExtras(); if(bundle != null) { Recipe recipe = bundle.getParcelable(RecipeStepDetailActivity.RECIPE_KEY); if(recipe != null) { Intent recipeStepListIntent = new Intent(getContext(), RecipeStepListActivity.class); recipeStepListIntent.putExtra(ID_EXTRA_INTENT, recipe); startActivity(recipeStepListIntent); } Timber.d("List fragment: "+recipe); } else { Timber.d("List fragment: bundle null"); } return view; } @Override public void onResume() { super.onResume(); if(!isOnline()) { Toast.makeText(getContext(), getResources().getString(R.string.no_network), Toast.LENGTH_SHORT).show(); } } private void intialiseRecyclerView() { RecyclerView.LayoutManager layoutManager; if(!RecipesListActivity.ismTwoPane()) { layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false); } else { layoutManager = new GridLayoutManager(getContext(), 3); } mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setHasFixedSize(true); mAdapter = new RecipeListAdapter(getContext(), this); mRecyclerView.setAdapter(mAdapter); } private void initialiseViewModel() { mViewModel = ViewModelProviders.of(this).get(RecipeListViewModel.class); mViewModel.getmRecipeList().observe(this, new Observer<List<Recipe>>() { @Override public void onChanged(@Nullable List<Recipe> recipeList) { Timber.d( "onChanged: "+recipeList); mAdapter.swapRecipeList(recipeList); if(recipeList != null && recipeList.size() > 0) { idlingResource.setIdleState(true); PreferenceUtility.saveRecipe(getContext(), recipeList.get(0)); } } }); /*mViewModel.getAppointmentDetails().observe(this, appointmentDetailsEntities -> { if(DEBUG) Log.d(TAG,"change detected !!! "+appointmentDetailsEntities); if(appointmentDetailsEntities != null) { if(DEBUG) Log.d(TAG,"change detected size !!! "+appointmentDetailsEntities.size()); } if (appointmentDetailsEntities != null) mAppointmentsAdapter.swapAppointmentDetails(appointmentDetailsEntities); }); mViewModel.setDate(Utility.getTodayDateInString()); tvDateSelected.setText("Today, "+Utility.getTodayDateInString());*/ } @Override public void onClick(Recipe recipe) { Timber.d( "onClick: "+recipe); PreferenceUtility.saveRecipe(getContext(), recipe); BakingWidgetRemoteViewsService.updateWidget(getContext()); Intent recipeStepListIntent = new Intent(getContext(), RecipeStepListActivity.class); recipeStepListIntent.putExtra(ID_EXTRA_INTENT, recipe); startActivity(recipeStepListIntent); } private boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(getActivity().CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnected(); } }
true
818b3eabe8046ea1958cca628f980807e110dca3
Java
nafa15/master
/src/oop/encapsulation/Student.java
UTF-8
240
1.8125
2
[]
no_license
package oop.encapsulation; public class Student { // oop // Encapsulation : data hiding // Polymorphism // Inheritance // Abstraction private String nameOfStudent1; // public void setNameOfStudent1; }
true
e69b5667b9e0468da68eb5ad061ffdcf9d7ae283
Java
VasilievAndrey/codility
/src/main/java/vav/codility/arrays/strings/FindTheWinnerOfAnArrayGame.java
UTF-8
152
2.21875
2
[]
no_license
package vav.codility.arrays.strings; public class FindTheWinnerOfAnArrayGame { public int getWinner(int[] arr, int k) { return 0; } }
true
e9433256e05865f28d80e1860c38997331ec3861
Java
pralavgoa/SecureWise
/WiseStudySpaceWizard/src/edu/ucla/wise/studyspace/parameters/ParametersProviderServlet.java
UTF-8
1,723
2.296875
2
[ "BSD-3-Clause" ]
permissive
/** * */ package edu.ucla.wise.studyspace.parameters; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.common.base.Strings; /** * @author Pralav * */ @WebServlet("/getStudySpaceParams") public class ParametersProviderServlet extends HttpServlet { public static final String STUDY_SPACE_NAME_PARAMETER = "studyName"; public static final String STUDY_SPACE_KEY_PARAMETER = "studyKey"; /** * */ private static final long serialVersionUID = 1L; @Override public void service(HttpServletRequest request, HttpServletResponse response) { PrintWriter out; try { out = response.getWriter(); //TODO: First get the parameters in the post method and do some sort of authentication String studySpaceName = request.getParameter(STUDY_SPACE_NAME_PARAMETER); String studySpaceKey = request .getParameter(STUDY_SPACE_KEY_PARAMETER); if (Strings.isNullOrEmpty(studySpaceName) || Strings.isNullOrEmpty(studySpaceKey)) { out.write("FAILURE"); return; } /* * if (StringEncoderDecoder.checkStringWithKey(studySpaceName, * studySpaceKey)) { * * // TODO: once verified, just go to the study space * out.write(DatabaseConnector * .getStudySpaceParamsAsJSON(studySpaceName)); } else { out.write( * "Failed to authenticate properly. Please check the Study Space Name-Key pair, or ask the developers for assitance" * ); } */ out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
8d4647054aa7861c73ab236574288b0a63a25f2e
Java
jsbhb/servercenter
/financecenter/src/main/java/com/zm/finance/bussiness/service/impl/RebateServiceImpl.java
UTF-8
5,718
1.9375
2
[]
no_license
package com.zm.finance.bussiness.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.zm.finance.bussiness.dao.RebateConsumeMapper; import com.zm.finance.bussiness.dao.RebateMapper; import com.zm.finance.bussiness.service.RebateService; import com.zm.finance.constants.Constants; import com.zm.finance.log.LogUtil; import com.zm.finance.pojo.RebateDownload; import com.zm.finance.pojo.RebateSearchModel; import com.zm.finance.pojo.ResultModel; import com.zm.finance.pojo.rebate.Rebate; import com.zm.finance.pojo.rebate.Rebate4Order; import com.zm.finance.pojo.rebate.RebateDetail; import com.zm.finance.util.JSONUtil; @Service @Transactional(isolation = Isolation.READ_COMMITTED) public class RebateServiceImpl implements RebateService { @Resource RedisTemplate<String, String> template; @Resource RebateMapper rebateMapper; @Resource RebateConsumeMapper rebateConsumeMapper; @Override public void updateRebateTask() { List<Rebate> rebateList = new ArrayList<Rebate>(); HashOperations<String, String, String> hashOperations = template.opsForHash(); Set<String> keys = template.keys(Constants.GRADE_ORDER_REBATE + "*"); if (keys != null && keys.size() > 0) { Rebate rebate = null; Map<String, String> result = null; String[] arr = null; for (String key : keys) { result = hashOperations.entries(key); if (result != null) { try { rebate = JSONUtil.parse(JSONUtil.toJson(result), Rebate.class); arr = key.split(":"); rebate.setGradeId(Integer.valueOf(arr[arr.length - 1])); rebateList.add(rebate); } catch (Exception e) { LogUtil.writeErrorLog("【从redis中获取数据转换出错】", e); } } } } if (rebateList.size() > 0) { rebateMapper.insertRebate(rebateList); } } @Override public void saveRebateDetail(Map<String, String> map) { if (map != null && map.size() > 0) { List<RebateDetail> detailList = new ArrayList<RebateDetail>(); RebateDetail rebateDetail = null; for (Map.Entry<String, String> entry : map.entrySet()) { if ("orderId".equals(entry.getKey()) || "orderFlag".equals(entry.getKey())) { continue; } if (entry.getValue() != null && Double.valueOf(entry.getValue()) > 0) { rebateDetail = new RebateDetail(); rebateDetail.setGradeId(Integer.valueOf(entry.getKey())); rebateDetail.setRebateMoney(Double.valueOf(entry.getValue())); rebateDetail.setOrderId(map.get("orderId")); rebateDetail .setOrderFlag(map.get("orderFlag") == null ? -1 : Integer.valueOf(map.get("orderFlag"))); detailList.add(rebateDetail); } } if (detailList.size() > 0) { rebateMapper.insertRebateDetail(detailList); } } } @Override public ResultModel getRebate(Integer gradeId) { Map<String, String> result = new HashMap<String, String>(); HashOperations<String, String, String> hashOperations = template.opsForHash(); result = hashOperations.entries(Constants.GRADE_ORDER_REBATE + gradeId); if (result == null) { return new ResultModel(true, null); } Rebate rebate = JSONUtil.parse(JSONUtil.toJson(result), Rebate.class); rebate.setGradeId(gradeId); rebate.init();//把科学计数法转为正常显示 return new ResultModel(true, rebate); } @Override public Page<RebateDetail> getRebateDetail(RebateDetail entity) { PageHelper.startPage(entity.getCurrentPage(), entity.getNumPerPage(), true); return rebateMapper.selectRebateDetailById(entity); } @Override public Page<Rebate> listRebate(RebateSearchModel search) { PageHelper.startPage(search.getCurrentPage(), search.getNumPerPage(), true); return rebateMapper.listRebate(search); } @Override public void updateRebateDetail(String orderId, Integer status) { Map<String, Object> param = new HashMap<String, Object>(); param.put("orderId", orderId); param.put("status", status); rebateMapper.updateRebateDetail(param); } @Override public void redisTool(String key, Map<String, String> map) { template.opsForHash().putAll(key, map); } @Override public void redisToolList(String key, String value) { template.opsForSet().add(key, value); } @Override public List<RebateDownload> listRebateDetailForDownload(Map<String,Object> param) { return rebateMapper.listRebateDetailForDownload(param); } @Override public ResultModel saveRebate4order(Rebate4Order rebate4Order) { orderConsumAdd(rebate4Order); rebateConsumeMapper.insertRebateConsume(rebate4Order); return new ResultModel(true); } @Override public void rebate4orderBatch(List<Rebate4Order> rebate4OrderList) { if (rebate4OrderList != null && rebate4OrderList.size() > 0){ for (Rebate4Order rebate4Order : rebate4OrderList) { orderConsumAdd(rebate4Order); } rebateConsumeMapper.insertRebateConsumeBatch(rebate4OrderList); } } private void orderConsumAdd(Rebate4Order rebate4Order) { template.opsForHash().increment(Constants.GRADE_ORDER_REBATE + rebate4Order.getGradeId(), Constants.ORDER_CONSUME, rebate4Order.getMoney());// 增加订单消费金额 } }
true
137e921b5938e49bf98b6788d4b3cb22c83fe884
Java
superchaoran/cdap
/cdap-app-templates/cdap-etl/cdap-etl-archetypes/cdap-etl-batch-sink-archetype/src/main/resources/archetype-resources/src/main/java/Sink.java
UTF-8
2,012
1.796875
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright © 2015 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package $package; import co.cask.cdap.api.annotation.Description; import co.cask.cdap.api.annotation.Name; import co.cask.cdap.api.annotation.Plugin; import co.cask.cdap.api.data.format.StructuredRecord; import co.cask.cdap.api.dataset.lib.KeyValue; import co.cask.cdap.etl.api.Emitter; import co.cask.cdap.etl.api.PipelineConfigurer; import co.cask.cdap.etl.api.batch.BatchRuntimeContext; import co.cask.cdap.etl.api.batch.BatchSink; import co.cask.cdap.etl.api.batch.BatchSinkContext; import org.apache.hadoop.io.NullWritable; /** * Batch Sink. */ @Plugin(type = "batchsink") @Name("Sink") @Description("Batch sink") public class Sink extends BatchSink<StructuredRecord, byte[], NullWritable> { @Override public void configurePipeline(PipelineConfigurer configurer) { // Make sure any properties that are expected are valid } @Override public void initialize(BatchRuntimeContext context) throws Exception { super.initialize(context); // Get Config param and use to initialize // String param = config.param // Perform init operations, external operations etc. } @Override public void transform(StructuredRecord input, Emitter<KeyValue<byte[], NullWritable>> emitter) throws Exception { // Transform the records // emitter.emit(myval); } @Override public void prepareRun(BatchSinkContext context) { // Configure hadoop job before running in batch. } }
true
f5492b2e47f0874278bc6fa1440d5bfcc85a592f
Java
CsabaHalmagyi/OCSync
/src/org/rdcit/ocsync/models/odmnodes/EventNode.java
UTF-8
2,661
2.703125
3
[]
no_license
package org.rdcit.ocsync.models.odmnodes; import java.util.ArrayList; import java.util.List; /** * Represents an Event node in the ODM structure * * @author Csaba Halmagyi * */ public class EventNode { private String eventOID; private String eventRepKey; private String eventStatus; private List<FormNode> forms; public EventNode() { this.forms = new ArrayList<>(); } public String getEventOID() { return eventOID; } public void setEventOID(String eventOID) { this.eventOID = eventOID; } public String getEventRepKey() { return eventRepKey; } public void setEventRepKey(String eventRepKey) { this.eventRepKey = eventRepKey; } public String getEventStatus() { return eventStatus; } public void setEventStatus(String eventStatus) { this.eventStatus = eventStatus; } public List<FormNode> getForms() { return forms; } public void setForms(List<FormNode> forms) { this.forms = forms; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((eventOID == null) ? 0 : eventOID.hashCode()); result = prime * result + ((eventRepKey == null) ? 0 : eventRepKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EventNode other = (EventNode) obj; if (eventOID == null) { if (other.eventOID != null) return false; } else if (!eventOID.equals(other.eventOID)) return false; if (eventRepKey == null) { if (other.eventRepKey != null) return false; } else if (!eventRepKey.equals(other.eventRepKey)) return false; return true; } public void upsert(String formOID, String formStatus, String groupOID, String groupRepKey, String itemOID, String itemValue){ FormNode f = new FormNode(); f.setFormOID(formOID); f.setFormStatus(formStatus); //if the form already exists if(this.forms.contains(f)){ this.forms.get(this.forms.indexOf(f)).upsert(groupOID, groupRepKey, itemOID, itemValue); } //if this is a new form else{ this.forms.add(f); this.forms.get(this.forms.indexOf(f)).upsert(groupOID, groupRepKey, itemOID, itemValue); } } public void toXML(StringBuilder sb){ sb.append("<StudyEventData StudyEventOID=\""+this.eventOID+"\" StudyEventRepeatKey=\""+this.eventRepKey+"\">"); this.forms.forEach((f) -> { f.toXML(sb); }); sb.append("</StudyEventData>"); } }
true
4fa924e440f6965e499fd7172f7fb3cd544f4004
Java
Beescast/Beeslm
/No.2490-Bees-master/api/src/main/java/org/bees/biz/persistence/manager/ConfigManager.java
UTF-8
2,161
2.3125
2
[]
no_license
package org.bees.biz.persistence.manager; import java.util.Date; import java.util.List; import org.bees.biz.persistence.dao.ConfigDao; import org.bees.biz.persistence.model.Config; import org.bees.biz.persistence.model.ConfigExample; import org.bees.biz.persistence.model.ConfigExample.Criteria; import org.bees.utils.Const; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import projects.commons.database.BaseManager; @Component public class ConfigManager extends BaseManager<ConfigDao> { @Autowired private ConfigDao dao; @Override public ConfigDao getDao() { return dao; } public Config getInfoById(Integer id) { ConfigExample example = new ConfigExample(); Criteria crit = example.createCriteria(); crit.andDelFlagEqualTo(Const.DEL_FLAG_NOT_DEL); crit.andIdEqualTo(id); return this.getDao().getByExample(example); } public List<Config> getList(Integer limit, Integer start) { ConfigExample example = new ConfigExample(); Criteria crit = example.createCriteria(); crit.andDelFlagEqualTo(Const.DEL_FLAG_NOT_DEL); example.setLimitStart(start); example.setLimitEnd(limit); example.setOrderByClause("id desc"); return this.getDao().list(example); } public boolean add(Integer userId, String title, String content, Byte status) { Config config=new Config(); config.setAddTime(new Date()); int res= this.getDao().insert(config); if(res>0){ return true; } return false; } public boolean del(Integer id) { Config config=new Config(); config.setId(id); config.setDelFlag(Const.DEL_FLAG_DEL); int res= this.getDao().update(config); if(res>0){ return true; } return false; } public boolean edit(Integer id, String value) { Config config=new Config(); config.setId(id); config.setValue(value); int res= this.getDao().update(config); if(res>0){ return true; } return false; } public Integer getListCount() { ConfigExample example = new ConfigExample(); Criteria crit = example.createCriteria(); crit.andDelFlagEqualTo(Const.DEL_FLAG_NOT_DEL); return this.getDao().count(example); } }
true
d2ef3f3d2451c78f561921464048535227644ff9
Java
smolyakovroma/prototype
/app/src/main/java/com/cryptopay/prototype/activity/StartActivity.java
UTF-8
9,245
1.757813
2
[]
no_license
package com.cryptopay.prototype.activity; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Paint; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.constraint.ConstraintLayout; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.chaos.view.PinView; import com.cryptopay.prototype.Constants; import com.cryptopay.prototype.R; import com.cryptopay.prototype.activity.general.LoadingDialog; import com.cryptopay.prototype.activity.general.LoadingView; import com.cryptopay.prototype.domain.Wallet; import com.cryptopay.prototype.fragment.SplashFragment; import com.jungly.gridpasswordview.GridPasswordView; import java.math.BigInteger; public class StartActivity extends AppCompatActivity { public static final int LAYOUT = R.layout.activity_start; private PinView pinView; private GridPasswordView gpv, pswViewPass1, pswViewPass2; private SharedPreferences sPref; private LinearLayout llStart1; private LinearLayout llStart2; private ImageView ivLogo; private ConstraintLayout clContainer; private FragmentManager fragmentManager; private String newPassword; private LoadingView mLoadingView; private TextView tvRestoreAcc, tvStartLink; @Override protected void onCreate(Bundle savedInstanceState) { setTheme(R.style.AppTheme); super.onCreate(savedInstanceState); setContentView(LAYOUT); sPref = getPreferences(MODE_PRIVATE); clContainer = (ConstraintLayout) findViewById(R.id.start_container); llStart1 = (LinearLayout) findViewById(R.id.ll_start1); llStart2 = (LinearLayout) findViewById(R.id.ll_start2); fragmentManager = getSupportFragmentManager(); mLoadingView = LoadingDialog.view(getSupportFragmentManager()); tvRestoreAcc = (TextView) findViewById(R.id.tv_restore_acc); tvStartLink = (TextView) findViewById(R.id.tv_start_link); // if (sPref.getBoolean(Constants.settings_show_splash, false)) { // runSplash(); // } pswViewPass1 = (GridPasswordView) findViewById(R.id.pswViewPass1); pswViewPass2 = (GridPasswordView) findViewById(R.id.pswViewPass2); gpv = (GridPasswordView) findViewById(R.id.pswView); initWallet(); // gpv.requestFocus(); gpv.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() { @Override public void onTextChanged(String psw) { if (psw.length() != 4) { clContainer.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); } } @Override public void onInputFinish(String psw) { // if(psw.equals(Constants.wallet_password)) if (psw.equals(Constants.wallet.getPassword())) { if (getCurrentFocus() != null) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } clContainer.setBackgroundColor(getResources().getColor(R.color.passwordAccess)); Intent intent = new Intent(StartActivity.this, MainActivity.class); startActivity(intent); } else { clContainer.setBackgroundColor(getResources().getColor(R.color.passwordDenied)); } } }); pswViewPass1.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() { @Override public void onTextChanged(String psw) { } @Override public void onInputFinish(String psw) { pswViewPass2.requestFocus(); } }); pswViewPass2.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() { @Override public void onTextChanged(String psw) { } @Override public void onInputFinish(String psw) { if (pswViewPass2.getPassWord().equals(pswViewPass1.getPassWord())) { if (getCurrentFocus() != null) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } newPassword = pswViewPass2.getPassWord(); // mLoadingView.showLoadingIndicator(); AsyncTask<Object, Void, Wallet> execute = new Web3Utils.GenerateNewWallet() .execute(getApplicationContext().getFilesDir().getAbsolutePath(), newPassword, getPreferences(MODE_PRIVATE)); // try { // TimeUnit.SECONDS.sleep(5); // } catch (InterruptedException e) { // e.printStackTrace(); // } Intent intent = new Intent(StartActivity.this, MainActivity.class); startActivity(intent); // mLoadingView.hideLoadingIndicator(); } else { pswViewPass2.clearPassword(); pswViewPass1.clearPassword(); pswViewPass1.requestFocus(); } } }); tvRestoreAcc.setPaintFlags(tvRestoreAcc.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); tvRestoreAcc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(StartActivity.this, RecoveryActivity.class); startActivity(intent); } }); tvStartLink.setPaintFlags(tvStartLink.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); tvStartLink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://cpay.click/")); startActivity(intent); } }); } private void initWallet() { sPref = getPreferences(MODE_PRIVATE); if (Constants.wallet != null && Constants.wallet.getAddress() != null && !Constants.wallet.getAddress().equals("")) { new Web3Utils.GetBalanceWallet().execute(); llStart1.setVisibility(View.VISIBLE); SharedPreferences.Editor ed = sPref.edit(); ed.putString(Constants.wallet_address, Constants.wallet.getAddress()); ed.putString(Constants.wallet_password, Constants.wallet.getPassword()); ed.putString(Constants.wallet_file, Constants.wallet.getFile()); ed.putString(Constants.wallet_publicKey, Constants.wallet.getPublicKey().toString()); ed.putString(Constants.wallet_privateKey, Constants.wallet.getPrivateKey().toString()); ed.putBoolean(Constants.save_recovery, false); ed.commit(); if (gpv.requestFocus()) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.showSoftInput(gpv, 2); } } else if (!sPref.getString(Constants.wallet_address, "").equals("")) { Constants.wallet.setAddress(sPref.getString(Constants.wallet_address, "")); Constants.wallet.setPassword(sPref.getString(Constants.wallet_password, "")); Constants.wallet.setFile(sPref.getString(Constants.wallet_file, "")); Constants.wallet.setPublicKey(new BigInteger(sPref.getString(Constants.wallet_publicKey, "0"))); Constants.wallet.setPrivateKey(new BigInteger(sPref.getString(Constants.wallet_privateKey, "0"))); new Web3Utils.GetBalanceWallet().execute(); llStart1.setVisibility(View.VISIBLE); if (gpv.requestFocus()) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.showSoftInput(gpv, 2); } } else { llStart2.setVisibility(View.VISIBLE); if (pswViewPass1.requestFocus()) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.showSoftInput(pswViewPass1, InputMethodManager.SHOW_IMPLICIT); } } } public void runSplash() { SplashFragment splashFragment = new SplashFragment(); fragmentManager.beginTransaction() .replace(R.id.start_container, splashFragment) .addToBackStack(null) .commit(); } }
true
5a9b07d1a93181a44a599d7046c21fa014cee6e6
Java
JEBailey/fiona
/src/main/java/com/wickedknight/fiona/skin/Skin.java
UTF-8
2,816
2.328125
2
[]
no_license
package com.wickedknight.fiona.skin; import java.awt.Image; import java.util.Map; public class Skin { private static final String MAIN = "main.bmp"; private static final String BUTTONS = "cbuttons.bmp"; private static final String TITLEBAR = "titlebar.bmp"; private static final String NUMBERS = "numbers.bmp"; private static final String NUMBERS_EX = "nums_ex.bmp"; private static final String STEREO_MODE = "monoster.bmp"; private static final String VOLUME = "volume.bmp"; private static final String PLAY_PAUSE = "playpaus.bmp"; private static final String PLAY_LIST = "pledit.bmp"; private static final String SHUFFLE_REPEAT = "shufrep.bmp"; private static final String POSITION_BAR = "posbar.bmp"; private static final String balance = "balance.bmp"; private static final String plinfo = "pledit.txt"; private SkinLoader skl; private Map<String,Object> images; public Skin(String paramString) { this.skl = new SkinLoader(paramString); try { this.skl.loadImages(); this.images = this.skl.toHash(); } catch (Exception localException) { System.out.println(localException); } this.skl = null; } public Image getMainPanel() { return getImage(MAIN); } public Image getButtonPanel() { return getImage(BUTTONS); } public Image getTitlePanel() { return getImage(TITLEBAR); } public Image getNumberPanel() { return getImage(NUMBERS); } public Image getNumbersSmallPanel() { return getImage(NUMBERS_EX); } public Image getPositionBarPanel() { return getImage(POSITION_BAR); } public Image getStereoPanel() { return getImage(STEREO_MODE); } public Image getVolumePanel() { return getImage(VOLUME); } public Image getPlayPanel() { return getImage(PLAY_PAUSE); } public Image getShuffleRepeatPanel() { return getImage(SHUFFLE_REPEAT); } public Image getEqPlPanel() { return getImage(SHUFFLE_REPEAT); } public Image getPlaylistPanel() { return getImage(PLAY_LIST); } public Image getBalance() { return getImage("balance.bmp"); } public String getPlaylistInfo() { return (String) getContent(plinfo); } private Image getImage(String paramString) { if (!this.images.containsKey(paramString)) System.out.println("key " + paramString + " does not exist"); return (Image) this.images.get(paramString); } private Object getContent(String paramString) { return this.images.get(paramString); } }
true
c5a862f9b195f79cf7f053686a7280505d546311
Java
MichalSiwiak/real-estate-portal-spring-security
/src/main/java/net/coffeecoding/entity/Flat.java
UTF-8
2,954
2.390625
2
[]
no_license
package net.coffeecoding.entity; import java.sql.Timestamp; import java.util.Arrays; import java.util.Objects; import java.util.Set; import javax.persistence.*; @Entity @Table(name = "flat") public class Flat { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private int id; private Timestamp date; private String title; @Lob() private String content; private int price; private int surface; private int rooms; private String city; private byte[] image; private byte[] avatar; @ManyToOne @JoinColumn(name = "users") private Users users; public int getId() { return id; } public void setId(int id) { this.id = id; } public Timestamp getDate() { return date; } public void setDate(Timestamp date) { this.date = date; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getSurface() { return surface; } public void setSurface(int surface) { this.surface = surface; } public int getRooms() { return rooms; } public void setRooms(int rooms) { this.rooms = rooms; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } public byte[] getAvatar() { return avatar; } public void setAvatar(byte[] avatar) { this.avatar = avatar; } public Users getUsers() { return users; } public void setUsers(Users users) { this.users = users; } @Override public String toString() { return "Flat{" + "id=" + id + ", date=" + date + ", title='" + title + '\'' + ", content='" + content + '\'' + ", price=" + price + ", surface=" + surface + ", rooms=" + rooms + ", city='" + city + '\'' + ", image=" + Arrays.toString(image) + ", avatar=" + Arrays.toString(avatar) + ", users=" + users + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Flat flat = (Flat) o; return id == flat.id; } @Override public int hashCode() { return Objects.hash(id); } }
true
8a27262661c32f47f9c68a27f89cc77d80724f9d
Java
DBCDK/ocb-tools
/libraries/ocb-scripter/src/main/java/dk/dbc/ocbtools/scripter/ServiceScripter.java
UTF-8
9,668
2.15625
2
[]
no_license
package dk.dbc.ocbtools.scripter; import dk.dbc.jslib.ClasspathSchemeHandler; import dk.dbc.jslib.Environment; import dk.dbc.jslib.FileSchemeHandler; import dk.dbc.jslib.ModuleHandler; import dk.dbc.jslib.SchemeURI; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; public class ServiceScripter { private static final XLogger logger = XLoggerFactory.getXLogger(ServiceScripter.class); private static final String COMMON_INSTALL_NAME = "file"; private static final String COMMON_DISTRIBUTION_PATH = "distributions/common"; private static final String MODULES_PATH_PATTERN = "%s/%s/src"; private static final String ENTRYPOINTS_PATTERN = MODULES_PATH_PATTERN + "/entrypoints/%s/%s"; private String baseDir = ""; private List<Distribution> distributions = null; private String modulesKey = ""; private String serviceName = ""; private final Map<String, Environment> environments = new HashMap<>(); public ServiceScripter() { } public void setBaseDir(String baseDir) { this.baseDir = baseDir; } public void setDistributions(List<Distribution> distributions) { this.distributions = distributions; } public void setModulesKey(String modulesKey) { this.modulesKey = modulesKey; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } /** * Calls a function in a JavaScript environment and returns the result. * <p/> * The JavaScript environment is created and cached by the filename. * * @param fileName JavaScript file to load in the environment. * @param methodName Name of the function to call. * @param args Arguments to the function. * @return The result of the JavaScript function. * @throws ScripterException Encapsulate any exception from Rhino or is thrown * in case of an error. For instance if the file can not be loaded. */ public Object callMethod(String fileName, String methodName, Object... args) throws ScripterException { logger.entry(fileName, methodName, args); Object result = null; try { if (!environments.containsKey(fileName)) { environments.put(fileName, createEnvironment(fileName)); } Environment envir = environments.get(fileName); result = envir.callMethod(methodName, args); return result; } catch (Exception e) { throw new ScripterException(e.getMessage(), e); } finally { logger.exit(result); } } /** * Returns a list of completes path to any module paths used by the environment. * <p/> * Only paths to external files are returned. * * @return List of module paths. */ public List<String> getModulePaths() throws IOException { logger.entry(); try { ArrayList<String> modulePaths = new ArrayList<>(); String[] searchPaths = createModulesHandler().getSearchPaths().split(" "); logger.debug("Search paths: {}", searchPaths); for (String searchPath : searchPaths) { String[] path = searchPath.split(":"); if (path.length == 2) { String pathType = path[0]; String pathDir = path[1]; File file; String modulesDir; if (pathType.equals(COMMON_INSTALL_NAME)) { modulesDir = String.format(MODULES_PATH_PATTERN, baseDir, COMMON_DISTRIBUTION_PATH); file = new File(modulesDir + "/" + pathDir); if (file.isDirectory()) { logger.debug("Adding module path: {}", file.getCanonicalPath()); modulePaths.add(file.getCanonicalPath()); } } else { for (Distribution dist : distributions) { modulesDir = String.format(MODULES_PATH_PATTERN, baseDir, dist.getDirName()); file = new File(modulesDir + "/" + pathDir); if (file.isDirectory()) { logger.debug("Adding module path: {}", file.getCanonicalPath()); modulePaths.add(file.getCanonicalPath()); } } } } } return modulePaths; } finally { logger.exit(); } } /** * Constructs a new Environment from a file. * * @param fileName The name of the file to load into the new Environment. * @return The new Environment. * @throws ScripterException Thrown in case of I/O errors. */ private Environment createEnvironment(String fileName) throws ScripterException { logger.entry(fileName); String jsFileName = ""; try { Environment envir = new Environment(); envir.registerUseFunction(createModulesHandler()); for (Distribution dist : distributions) { jsFileName = String.format(ENTRYPOINTS_PATTERN, baseDir, dist.getDirName(), serviceName, fileName); logger.debug("Calculated js filename: {}", jsFileName); File file = new File(jsFileName); if (file.exists() && file.isFile()) { logger.info("Trying to evaluate {} in the new JavaScript Environment", jsFileName); envir.evalFile(jsFileName); return envir; } } throw new ScripterException("Unable to find an environment for file %s", fileName); } catch (Exception e) { logger.error("Unable to load file {}: {}", jsFileName, e.getMessage()); throw new ScripterException(e.getMessage(), e); } finally { logger.exit(); } } /** * Constructs a new module handler to load modules from the Opencat-Business * installation. * * @return The new ModuleHandler */ private ModuleHandler createModulesHandler() { logger.entry(); try { ModuleHandler handler = new ModuleHandler(); String modulesDir; for (Distribution dist : distributions) { modulesDir = String.format(MODULES_PATH_PATTERN, baseDir, dist.getDirName()); logger.debug("Adding distribution to module handler: {} -> {}", dist.getSchemaName(), modulesDir); handler.registerHandler(dist.getSchemaName(), new FileSchemeHandler(modulesDir)); addSearchPathsFromSettingsFile(handler, dist.getSchemaName(), modulesDir); } modulesDir = String.format(MODULES_PATH_PATTERN, baseDir, COMMON_DISTRIBUTION_PATH); logger.debug("Adding distribution to module handler: {} -> {}", COMMON_INSTALL_NAME, modulesDir); handler.registerHandler(COMMON_INSTALL_NAME, new FileSchemeHandler(modulesDir)); addSearchPathsFromSettingsFile(handler, COMMON_INSTALL_NAME, modulesDir); handler.registerHandler("classpath", new ClasspathSchemeHandler(this.getClass().getClassLoader())); addSearchPathsFromSettingsFile(handler, "classpath", getClass().getResourceAsStream("jsmodules.settings")); return handler; } catch (IOException e) { logger.warn("Unable to load properties from resource 'jsmodules.settings'"); logger.error(e.getMessage(), e); return null; } finally { logger.exit(); } } private void addSearchPathsFromSettingsFile(ModuleHandler handler, String schemeName, String modulesDir) { logger.entry(handler, schemeName, modulesDir); String fileName = modulesDir + "/settings.properties"; try (FileInputStream fis = new FileInputStream(fileName)){ addSearchPathsFromSettingsFile(handler, schemeName, fis); } catch (FileNotFoundException ex) { logger.warn("The file '{}' does not exist.", fileName); } catch (IOException ex) { logger.warn("Unable to load properties from file '{}'", fileName); logger.error(ex.getMessage(), ex); } finally { logger.exit(); } } private void addSearchPathsFromSettingsFile(ModuleHandler handler, String schemeName, InputStream is) throws IOException { logger.entry(handler, schemeName, is); try { Properties props = new Properties(); props.load(is); if (!props.containsKey(modulesKey)) { logger.warn("Search path for modules is not specified"); return; } String moduleSearchPathString = props.getProperty(modulesKey); if (moduleSearchPathString != null && !moduleSearchPathString.isEmpty()) { String[] moduleSearchPath = moduleSearchPathString.split(";"); for (String s : moduleSearchPath) { handler.addSearchPath(new SchemeURI(schemeName + ":" + s)); } } } finally { logger.exit(); } } }
true
3a3f9501bd2c75e5d592c56ea59e8b72da5b3c62
Java
DenysBohurskyi/Customer_support_proj
/src/test/com/util/constant/Constants.java
UTF-8
244
1.601563
2
[]
no_license
package test.com.util.constant; public interface Constants { int ELEMENTS_COUNT = 2; String SPECIFY_PATH_TO_FILE = "Specify path to the file, please:"; String INVALID_DATA = "Check input data, Something wrong with validation!"; }
true
f936aa44aa76d981109861e12fafee9a8905a49e
Java
TKXZH/Blog
/src/main/java/com/xv/dao/UserDao.java
UTF-8
1,201
2.125
2
[]
no_license
package com.xv.dao; import com.xv.entity.User; import org.apache.ibatis.annotations.Param; /** * Created by xvzh on 2016/12/27. */ public interface UserDao { /** * 创建新用户,成功时返回1 * @param user * @return */ int createUser(User user); /** * 根据id查询用户信息 * @param id * @return */ User queryById(long id); /** * 用户修改昵称 * @param id * @param nickName * @return */ int modifyNickName(@Param("id") long id, @Param("nickName") String nickName); /** * 用户修改密码 * @param id * @param pwd * @return */ int modifyPassWord(@Param("id") long id, @Param("pwd") String pwd); /** * 根据用户名获取用户密码 * @param userName * @return */ String getPwdByUserName(String userName); /** * 根据用户名获取用户id * @param userName * @return */ Long getUidByUserName(String userName); /** * 增加用户的文章数 * @param id */ void increaseArticleNum(long id); void increaseCategoryNum(long id); int increaseStarNum(long id); }
true
135b7ffab3cbffcdfd3e0f4579d9b3b595fdd9de
Java
benbriggsy/java-card-game-coursework
/src/cheat/BasicCheat.java
UTF-8
7,796
3.4375
3
[]
no_license
package cheat; import java.util.*; /** * This is a class to run the game of cheat. * I changed the rules a little, so that the game doesn't get stuck if one * player has all of the TWO's. This required me to make changes to Bid * so I have included that file. * * In this game I have one player of each strategy and the rest are BASIC * It may take a long time to get to the end of the game with MY strategy * Player calling cheat whenever someone is on their last card. * I have commented out the lines of code that include HUMAN in the game * to see HUMAN in action uncomment lines 40 - 43. */ public class BasicCheat implements CardGame { private Player[] players; private int nosPlayers; public static final int MINPLAYERS = 5; private int currentPlayer; private Hand discards; private Bid currentBid; public BasicCheat() { this(MINPLAYERS); } public BasicCheat(int n) { nosPlayers = n; players = new Player[nosPlayers]; int showHuman = 2; players[0] = new BasicPlayer(this); players[0].setStrategy(StrategyFactory.StrategyType.MY); players[1] = new BasicPlayer(this); players[1].setStrategy(StrategyFactory.StrategyType.THINKER); ////remove the comments below (40 - 43) to play game with HUMAN involved. // players[2] = new BasicPlayer(this); // players[2].setStrategy(StrategyFactory.StrategyType.HUMAN); // showHuman = 3; for (int i = showHuman; i < nosPlayers; i++) { players[i] = new BasicPlayer(this); players[i].setStrategy(StrategyFactory.StrategyType.BASIC); } currentBid = new Bid(); currentBid.setRank(Card.Rank.TWO); currentPlayer = 0; } @Override public boolean playTurn() { //Ask player for a play, System.out.println("current bid = " + currentBid); currentBid = players[currentPlayer].playHand(currentBid); System.out.println("Player bid = " + currentBid); //Add hand played to discard pile discards.add(currentBid.getHand()); //Offer all other players the chance to call cheat boolean cheatCalled = false; //changed this loop to ask the player after the current player if they //want to call cheat first for (int i = currentPlayer + 1; i != currentPlayer && !cheatCalled; i++) { //go back to i = 0 if the end off the array is reached. if(i > players.length - 1){ i = 0; } if (i != currentPlayer) { //set MY players record of current players hand size for (int j = 0; j < nosPlayers; j++) { if (players[j].getStrategy() instanceof MyStrategy){ MyStrategy ms = (MyStrategy) players[j].getStrategy(); ms.setHandSizeOfCurrentPlayer( players[currentPlayer].cardsLeft()); } } System.out.println("asked player " + i); cheatCalled = players[i].callCheat(currentBid); if (cheatCalled) { //let thinker and my players clear their memory for (int j = 0; j < nosPlayers; j++) { if(players[j].getStrategy() instanceof ThinkerStrategy){ ThinkerStrategy ts = (ThinkerStrategy) players[j].getStrategy(); ts.clearPrevious(); }else if (players[j].getStrategy() instanceof MyStrategy){ MyStrategy ms = (MyStrategy) players[j].getStrategy(); ms.clearPrevious(); } } System.out.println("Player called cheat by Player " + (i + 1)); if (isCheat(currentBid)) { //CHEAT CALLED CORRECTLY //Give the discard pile of cards to currentPlayer who then has to play again players[currentPlayer].addHand(discards); System.out.println("Player cheats!"); System.out.println("Adding cards to player " + (currentPlayer + 1) + players[currentPlayer]); } else { //CHEAT CALLED INCORRECTLY //Give cards to caller i who is new currentPlayer System.out.println("Player Honest"); currentPlayer = i; players[currentPlayer].addHand(discards); System.out.println("Adding cards to player " + (currentPlayer + 1) + players[currentPlayer]); } //If cheat is called, current bid reset to an empty bid with rank two whatever //the outcome currentBid = new Bid(); //Discards now reset to empty discards = new Hand(); } } //If i is the current player make sure the loop is exited. if(i == currentPlayer){ i = currentPlayer - 1; } } if (!cheatCalled) { //Go to the next player System.out.println("No Cheat Called"); currentPlayer = (currentPlayer + 1) % nosPlayers; } return true; } @Override public int winner() { for (int i = 0; i < nosPlayers; i++) { if (players[i].cardsLeft() == 0) { return i; } } return -1; } @Override public void initialise() { //Create Deck of cards Deck d = new Deck(); d.shuffle(); //Deal cards to players int count = 0; while (d.size() > 0) { players[count % nosPlayers].addCard(d.deal()); count++; } //Initialise Discards discards = new Hand(); //Chose first player currentPlayer = 0; currentBid = new Bid(); currentBid.setRank(Card.Rank.TWO); } public void playGame() { initialise(); int c = 0; Scanner in = new Scanner(System.in); boolean finished = false; while (!finished) { //Play a hand System.out.println(" Cheat turn for player " + (currentPlayer + 1)); playTurn(); System.out.println(" Current discards =\n" + discards); c++; System.out.println(" Turn " + c + " Complete. Press any key to " + "continue or enter Q to quit>"); String str = in.nextLine(); if (str.equals("Q") || str.equals("q") || str.equals("quit")) { finished = true; } int w = winner(); if (w >= 0) { System.out.println("The Winner is Player " + (w + 1)); finished = true; } } } public static boolean isCheat(Bid b) { for (Card c : b.getHand()) { if (c.getRank() != b.r) { return true; } } return false; } public static void main(String[] args) { BasicCheat cheat = new BasicCheat(); cheat.playGame(); } }
true
7ba96f1d6dfe42030423ccb36be470660903c882
Java
isabella232/android-sdk-sources-for-api-level-11
/java/nio/channels/DatagramChannel.java
UTF-8
2,304
2.125
2
[]
no_license
/* */ package java.nio.channels; /* */ /* */ import java.io.IOException; /* */ import java.net.DatagramSocket; /* */ import java.net.SocketAddress; /* */ import java.nio.ByteBuffer; /* */ import java.nio.channels.spi.AbstractSelectableChannel; /* */ import java.nio.channels.spi.SelectorProvider; /* */ /* */ public abstract class DatagramChannel extends AbstractSelectableChannel /* */ implements ByteChannel, ScatteringByteChannel, GatheringByteChannel /* */ { /* */ protected DatagramChannel(SelectorProvider selectorProvider) /* */ { /* 6 */ super((SelectorProvider)null); throw new RuntimeException("Stub!"); } /* 7 */ public static DatagramChannel open() throws IOException { throw new RuntimeException("Stub!"); } /* 8 */ public final int validOps() { throw new RuntimeException("Stub!"); } /* */ public abstract DatagramSocket socket(); /* */ /* */ public abstract boolean isConnected(); /* */ /* */ public abstract DatagramChannel connect(SocketAddress paramSocketAddress) throws IOException; /* */ /* */ public abstract DatagramChannel disconnect() throws IOException; /* */ /* */ public abstract SocketAddress receive(ByteBuffer paramByteBuffer) throws IOException; /* */ /* */ public abstract int send(ByteBuffer paramByteBuffer, SocketAddress paramSocketAddress) throws IOException; /* */ /* */ public abstract int read(ByteBuffer paramByteBuffer) throws IOException; /* */ /* */ public abstract long read(ByteBuffer[] paramArrayOfByteBuffer, int paramInt1, int paramInt2) throws IOException; /* */ /* 17 */ public final synchronized long read(ByteBuffer[] targets) throws IOException { throw new RuntimeException("Stub!"); } /* */ public abstract int write(ByteBuffer paramByteBuffer) throws IOException; /* */ /* */ public abstract long write(ByteBuffer[] paramArrayOfByteBuffer, int paramInt1, int paramInt2) throws IOException; /* */ /* 20 */ public final synchronized long write(ByteBuffer[] sources) throws IOException { throw new RuntimeException("Stub!"); /* */ } /* */ } /* Location: D:\xyh\Android_3.0\android.jar * Qualified Name: java.nio.channels.DatagramChannel * JD-Core Version: 0.6.0 */
true
67f4586ec13f6f2d3adb90db93b398a0f572a7ae
Java
gi865/NewRepo
/Desktop/Jyoti/scrpting5/src/methods/AppDependentMethods.java
UTF-8
6,406
2.421875
2
[]
no_license
package methods; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import driver.DriverScript; import locators.ObjectLocators; public class AppDependentMethods extends DriverScript implements ObjectLocators{ /******************************************************* * Method Name : navigateURL * Purpose : It is used to load the required URL * Return Type : void * Date Created : * Date modified : * Reviewed By : * Example : ****************************************************** */ public boolean navigateURL(WebDriver oDriver,String strURL) { try { oDriver.navigate().to(strURL); Thread.sleep(2000); if(appInd.compareValue(oDriver.getTitle(),"actiTIME - Login))")) { return true; }else { return false; } }catch(Exception e) { appInd.writeResult("Exception", "Exception in 'navigateURL()' method."+e.getMessage()); return false; } } /******************************************************* * Method Name : loginToApp * Purpose : Login to the actiTime application * Return Type : void * Date Created : * Date modified : * Reviewed By : * Example : ****************************************************** */ public boolean loginToApp(WebDriver oDriver, String strUN, String strPWD) { String strStatus=null; try { strStatus+=appInd.setObject(oDriver, obj_UserName_Edit, strUN); strStatus+=appInd.setObject(oDriver, obj_Password_Edit, strPWD); strStatus+=appInd.clickObject(oDriver, obj_Login_Btn); //Verify optional element if(appInd.verifyOptionalElemnet(oDriver, obj_Explore_Btn)) { strStatus+=String.valueOf(appInd.clickObject(oDriver, obj_Explore_Btn)); } Thread.sleep(4000); //Handle the shortcut window if(appInd.verifyOptionalElemnet(oDriver, obj_ShortCut_Window)) { strStatus+=appInd.clickObject(oDriver, obj_shortCut_Close_Btn); } //3. Verify login is successful strStatus+=appInd.verifyElementExist(oDriver, obj_Logo_Img); if(strStatus.contains("flase")) { return false; }else { return true; } }catch(Exception e) { appInd.writeResult("Exception","Exception in 'loginToApp()' method."+e.getMessage()); return false; } } /******************************************************* * Method Name : createUser * Purpose : to create the user in the actiTime application * Return Type : void * Date Created : * Date modified : * Reviewed By : * Example : ****************************************************** */ public String createUser(WebDriver oDriver) { String strUserName=null; String strStatus=null; try { strStatus+=appInd.clickObject(oDriver, obj_USER_Menu); Thread.sleep(2000); strStatus+=appInd.clickObject(oDriver, obj_AddUser_Btn); Thread.sleep(2000); String LN=appInd.getPropData("LastName"); String FN=appInd.getPropData("FirstName"); strStatus+=appInd.setObject(oDriver, obj_FirstName_Edit, FN); strStatus+=appInd.setObject(oDriver, obj_LastName_Edit, LN); strStatus+=appInd.setObject(oDriver, obj_Email_Edit, appInd.getPropData("EmailID")); strStatus+=appInd.setObject(oDriver, obj_User_UN_Edit, appInd.getPropData("User_UserName")); strStatus+=appInd.setObject(oDriver, obj_User_PWD_Edit, appInd.getPropData("User_Pwd")); strStatus+=appInd.setObject(oDriver, obj_User_Retype_Edit, appInd.getPropData("User_Pwd")); //click on "Create User" button strStatus+=appInd.clickObject(oDriver,obj_CreateUser_Btn); Thread.sleep(2000); strUserName="nagoji, jyoti"; //5. Verify user is created strStatus+=appInd.verifyElementExists(oDriver, By.xpath("//div[@class='name']/span[text()='nagoji, jyoti']")); if(strStatus.contains("false")) { appInd.writeResult("Fail","Failed to create the user"); return null; }else { appInd.writeResult("pass", "User is created"); return strUserName; } }catch(Exception e) { appInd.writeResult("Exception", "Exception in 'createUser()' method."+e.getMessage()); return null; } } /******************************************************* * Method Name : deleteUser * Purpose : to delete the user in the actiTime application * Return Type : void * Date Created : * Date modified : * Reviewed By : * Example : ****************************************************** */ public boolean deleteUser(WebDriver oDriver,String userToBeDeleted) { String strStatus=null; try { strStatus+=appInd.clickObject(oDriver, By.xpath("//div[@class='name']/span[text()="+"'"+userToBeDeleted+"'"+"]")); Thread.sleep(4000); strStatus+=appInd.clickObject(oDriver, obj_DeleteUser_Btn); Thread.sleep(2000); oDriver.switchTo().alert().accept(); Thread.sleep(2000); //7. verify user is deleted strStatus+=appInd.verifyElementExists(oDriver, By.xpath("//div[@class='name']/span[text()="+"'"+userToBeDeleted+"'"+"]")); if(strStatus.contains("flase")) { appInd.writeResult("Fail", "Failed to delete the user"); return false; }else { appInd.writeResult("pass","User deleted successful"); return true; } }catch(Exception e) { appInd.writeResult("Exception","Exception in 'deleteUser()' method."+e.getMessage()); return false; } } /******************************************************* * Method Name : logoutFromApp() * Purpose : to logout from the actiTime application * Return Type : void * Date Created : * Date modified : * Reviewed By : * Example : ****************************************************** */ public boolean logoutFromApp(WebDriver oDriver) { String strStatus = null; try { strStatus+=appInd.clickObject(oDriver, obj_Logout_Btn); Thread.sleep(2000); //9. VErify logout is successful strStatus+=appInd.verifyElementExist(oDriver, obj_Header_Text); if(strStatus.contains("false")) { appInd.writeResult("Fail", "FAiled to logout form the application"); return false; }else { appInd.writeResult("pass", "Logout is successful"); return true; } }catch(Exception e) { appInd.writeResult("Exception", "Exception in 'logoutFromApp()' method."+e.getMessage()); return false; } } }
true
b4eddb05398420b4daae113ccf1e3af94be3d192
Java
seryang/beview-conference
/android/BeView/app/src/main/java/com/nhn/android/beview/model/Speaker.java
UTF-8
1,328
2.40625
2
[]
no_license
package com.nhn.android.beview.model; import java.io.Serializable; /** * Created by HyunSeungHo on 2017. 1. 12.. */ public class Speaker implements Serializable{ private int idx; private String name; private String img; private String email; private String phone; private String description; private int sectionIdx; public int getIdx() { return idx; } public void setIdx(int idx) { this.idx = idx; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getSectionIdx() { return sectionIdx; } public void setSectionIdx(int sectionIdx) { this.sectionIdx = sectionIdx; } }
true
52d640e800c6846944c04bea00002fc7af19266e
Java
julianGoh17/design-patterns
/src/main/java/io/patterns/chain/Email.java
UTF-8
360
2.75
3
[]
no_license
package io.patterns.chain; public class Email { private final EmailType type; private final String message; public Email(EmailType type, String message) { this.type = type; this.message = message; } public EmailType getType() { return type; } public String getMessage() { return message; } }
true
7071905415b4359c0a5758c2653d19534fb42080
Java
Fureniku/AdvancedArmoury
/src/main/java/com/silvaniastudios/advancedarmoury/gun/prebuilt/M4Material.java
UTF-8
5,106
1.835938
2
[]
no_license
package com.silvaniastudios.advancedarmoury.gun.prebuilt; import java.util.List; import com.silvaniastudios.advancedarmoury.AdvancedArmoury; import com.silvaniastudios.advancedarmoury.config.MaterialStats; import com.silvaniastudios.advancedarmoury.gun.inventory.ItemIInventory; import com.silvaniastudios.advancedarmoury.gun.inventory.assault.AssaultIInventory; import com.silvaniastudios.advancedarmoury.items.components.generic.Barrel; import com.silvaniastudios.advancedarmoury.items.components.generic.GunFrame; import com.silvaniastudios.advancedarmoury.items_old.AAItemModifierCores; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; public class M4Material extends GunFrame { String material; public M4Material(String material) { this.setCreativeTab(AdvancedArmoury.tabGuns); this.material = material; } @Override @SideOnly(Side.CLIENT) public void getSubItems(Item stack, CreativeTabs tab, List list) { for (int i = 0; i < Barrel.cal.length; i++) { ItemStack item = new ItemStack(stack); item.stackTagCompound = new NBTTagCompound(); item.stackTagCompound.setBoolean("hasInternals", true); item.stackTagCompound.setBoolean("isCompletedGun", true); item.stackTagCompound.setString("name", MaterialStats.getTextCol(material) + material + " M4A1"); item.stackTagCompound.setString("tag", "Standardized Firearm, " + Barrel.cal[i] + "mm"); item.stackTagCompound.setString("creator", "\u00A7c[Advanced Armoury]"); ItemIInventory inventory = new AssaultIInventory(item); ItemStack barrel = new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "barrel" + material)); barrel.stackTagCompound = new NBTTagCompound(); barrel.stackTagCompound.setInteger("length", 15); barrel.stackTagCompound.setDouble("calibre", Barrel.cal[i]); barrel.stackTagCompound.setString("partName", "barrel"); item.stackTagCompound.setFloat("accuracy", MaterialStats.getAccuracry("Gold")); ItemStack chamber = new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "assaultChamber" + material)); chamber.stackTagCompound = new NBTTagCompound(); chamber.stackTagCompound.setDouble("calibre", Barrel.cal[i]); chamber.stackTagCompound.setString("partName", "chamber"); inventory.setInventorySlotContents(2, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "assaultBolt" + material))); //bolt inventory.setInventorySlotContents(3, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "assaultBoltCarrier" + material))); //boltCarrier inventory.setInventorySlotContents(4, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "assaultChargingHandle" + material))); //chargingHandle inventory.setInventorySlotContents(5, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "assaultEjector" + material))); //ejector inventory.setInventorySlotContents(6, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "assaultExtractor" + material))); //extractor inventory.setInventorySlotContents(7, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "assaultFiringPin" + material))); //firingPin inventory.setInventorySlotContents(8, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "assaultFiringPinRetainerPin" + material))); //firingPinRetainerPin inventory.setInventorySlotContents(9, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "assaultPistonChamber" + material))); //piston/gas chamber inventory.setInventorySlotContents(10, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "assaultSpring" + material))); //spring/gas feed inventory.setInventorySlotContents(11, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "assaultPistonChamber" + material))); //piston inventory.setInventorySlotContents(12, chamber); //chamber inventory.setInventorySlotContents(13, barrel); //barrel inventory.setInventorySlotContents(14, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "trigger" + material))); //trigger inventory.setInventorySlotContents(15, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "fireSelector" + material))); //fire selector inventory.setInventorySlotContents(16, new ItemStack(AAItemModifierCores.coreSimpleChamberNet)); //Modifier inventory.setInventorySlotContents(17, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "m4Receiver" + material))); //receiver inventory.setInventorySlotContents(18, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "m4Stock" + material))); //stock inventory.setInventorySlotContents(19, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "m4FrontEnd" + material))); //frontEnd inventory.setInventorySlotContents(20, new ItemStack(GameRegistry.findItem(AdvancedArmoury.modid, "flashHider" + material))); //Barrel Attachment list.add(item); } } }
true
6965624528bf4983043b790081cac079e645326c
Java
noboomu/shipping-carriers
/src/main/java/com/fedex/ws/openship/v18/PackageRateDetail.java
UTF-8
16,172
1.71875
2
[]
no_license
package com.fedex.ws.openship.v18; import java.util.ArrayList; import java.util.List; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlSchemaType; import jakarta.xml.bind.annotation.XmlType; /** * Data for a package's rates, as calculated per a specific rate type. * * <p>Java class for PackageRateDetail complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PackageRateDetail"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="RateType" type="{http://fedex.com/ws/openship/v18}ReturnedRateType" minOccurs="0"/&gt; * &lt;element name="RatedWeightMethod" type="{http://fedex.com/ws/openship/v18}RatedWeightMethod" minOccurs="0"/&gt; * &lt;element name="MinimumChargeType" type="{http://fedex.com/ws/openship/v18}MinimumChargeType" minOccurs="0"/&gt; * &lt;element name="BillingWeight" type="{http://fedex.com/ws/openship/v18}Weight" minOccurs="0"/&gt; * &lt;element name="DimWeight" type="{http://fedex.com/ws/openship/v18}Weight" minOccurs="0"/&gt; * &lt;element name="OversizeWeight" type="{http://fedex.com/ws/openship/v18}Weight" minOccurs="0"/&gt; * &lt;element name="BaseCharge" type="{http://fedex.com/ws/openship/v18}Money" minOccurs="0"/&gt; * &lt;element name="TotalFreightDiscounts" type="{http://fedex.com/ws/openship/v18}Money" minOccurs="0"/&gt; * &lt;element name="NetFreight" type="{http://fedex.com/ws/openship/v18}Money" minOccurs="0"/&gt; * &lt;element name="TotalSurcharges" type="{http://fedex.com/ws/openship/v18}Money" minOccurs="0"/&gt; * &lt;element name="NetFedExCharge" type="{http://fedex.com/ws/openship/v18}Money" minOccurs="0"/&gt; * &lt;element name="TotalTaxes" type="{http://fedex.com/ws/openship/v18}Money" minOccurs="0"/&gt; * &lt;element name="NetCharge" type="{http://fedex.com/ws/openship/v18}Money" minOccurs="0"/&gt; * &lt;element name="TotalRebates" type="{http://fedex.com/ws/openship/v18}Money" minOccurs="0"/&gt; * &lt;element name="FreightDiscounts" type="{http://fedex.com/ws/openship/v18}RateDiscount" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;element name="Rebates" type="{http://fedex.com/ws/openship/v18}Rebate" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;element name="Surcharges" type="{http://fedex.com/ws/openship/v18}Surcharge" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;element name="Taxes" type="{http://fedex.com/ws/openship/v18}Tax" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;element name="VariableHandlingCharges" type="{http://fedex.com/ws/openship/v18}VariableHandlingCharges" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PackageRateDetail", propOrder = { "rateType", "ratedWeightMethod", "minimumChargeType", "billingWeight", "dimWeight", "oversizeWeight", "baseCharge", "totalFreightDiscounts", "netFreight", "totalSurcharges", "netFedExCharge", "totalTaxes", "netCharge", "totalRebates", "freightDiscounts", "rebates", "surcharges", "taxes", "variableHandlingCharges" }) public class PackageRateDetail { @XmlElement(name = "RateType") @XmlSchemaType(name = "string") protected ReturnedRateType rateType; @XmlElement(name = "RatedWeightMethod") @XmlSchemaType(name = "string") protected RatedWeightMethod ratedWeightMethod; @XmlElement(name = "MinimumChargeType") @XmlSchemaType(name = "string") protected MinimumChargeType minimumChargeType; @XmlElement(name = "BillingWeight") protected Weight billingWeight; @XmlElement(name = "DimWeight") protected Weight dimWeight; @XmlElement(name = "OversizeWeight") protected Weight oversizeWeight; @XmlElement(name = "BaseCharge") protected Money baseCharge; @XmlElement(name = "TotalFreightDiscounts") protected Money totalFreightDiscounts; @XmlElement(name = "NetFreight") protected Money netFreight; @XmlElement(name = "TotalSurcharges") protected Money totalSurcharges; @XmlElement(name = "NetFedExCharge") protected Money netFedExCharge; @XmlElement(name = "TotalTaxes") protected Money totalTaxes; @XmlElement(name = "NetCharge") protected Money netCharge; @XmlElement(name = "TotalRebates") protected Money totalRebates; @XmlElement(name = "FreightDiscounts") protected List<RateDiscount> freightDiscounts; @XmlElement(name = "Rebates") protected List<Rebate> rebates; @XmlElement(name = "Surcharges") protected List<Surcharge> surcharges; @XmlElement(name = "Taxes") protected List<Tax> taxes; @XmlElement(name = "VariableHandlingCharges") protected VariableHandlingCharges variableHandlingCharges; /** * Gets the value of the rateType property. * * @return * possible object is * {@link ReturnedRateType } * */ public ReturnedRateType getRateType() { return rateType; } /** * Sets the value of the rateType property. * * @param value * allowed object is * {@link ReturnedRateType } * */ public void setRateType(ReturnedRateType value) { this.rateType = value; } /** * Gets the value of the ratedWeightMethod property. * * @return * possible object is * {@link RatedWeightMethod } * */ public RatedWeightMethod getRatedWeightMethod() { return ratedWeightMethod; } /** * Sets the value of the ratedWeightMethod property. * * @param value * allowed object is * {@link RatedWeightMethod } * */ public void setRatedWeightMethod(RatedWeightMethod value) { this.ratedWeightMethod = value; } /** * Gets the value of the minimumChargeType property. * * @return * possible object is * {@link MinimumChargeType } * */ public MinimumChargeType getMinimumChargeType() { return minimumChargeType; } /** * Sets the value of the minimumChargeType property. * * @param value * allowed object is * {@link MinimumChargeType } * */ public void setMinimumChargeType(MinimumChargeType value) { this.minimumChargeType = value; } /** * Gets the value of the billingWeight property. * * @return * possible object is * {@link Weight } * */ public Weight getBillingWeight() { return billingWeight; } /** * Sets the value of the billingWeight property. * * @param value * allowed object is * {@link Weight } * */ public void setBillingWeight(Weight value) { this.billingWeight = value; } /** * Gets the value of the dimWeight property. * * @return * possible object is * {@link Weight } * */ public Weight getDimWeight() { return dimWeight; } /** * Sets the value of the dimWeight property. * * @param value * allowed object is * {@link Weight } * */ public void setDimWeight(Weight value) { this.dimWeight = value; } /** * Gets the value of the oversizeWeight property. * * @return * possible object is * {@link Weight } * */ public Weight getOversizeWeight() { return oversizeWeight; } /** * Sets the value of the oversizeWeight property. * * @param value * allowed object is * {@link Weight } * */ public void setOversizeWeight(Weight value) { this.oversizeWeight = value; } /** * Gets the value of the baseCharge property. * * @return * possible object is * {@link Money } * */ public Money getBaseCharge() { return baseCharge; } /** * Sets the value of the baseCharge property. * * @param value * allowed object is * {@link Money } * */ public void setBaseCharge(Money value) { this.baseCharge = value; } /** * Gets the value of the totalFreightDiscounts property. * * @return * possible object is * {@link Money } * */ public Money getTotalFreightDiscounts() { return totalFreightDiscounts; } /** * Sets the value of the totalFreightDiscounts property. * * @param value * allowed object is * {@link Money } * */ public void setTotalFreightDiscounts(Money value) { this.totalFreightDiscounts = value; } /** * Gets the value of the netFreight property. * * @return * possible object is * {@link Money } * */ public Money getNetFreight() { return netFreight; } /** * Sets the value of the netFreight property. * * @param value * allowed object is * {@link Money } * */ public void setNetFreight(Money value) { this.netFreight = value; } /** * Gets the value of the totalSurcharges property. * * @return * possible object is * {@link Money } * */ public Money getTotalSurcharges() { return totalSurcharges; } /** * Sets the value of the totalSurcharges property. * * @param value * allowed object is * {@link Money } * */ public void setTotalSurcharges(Money value) { this.totalSurcharges = value; } /** * Gets the value of the netFedExCharge property. * * @return * possible object is * {@link Money } * */ public Money getNetFedExCharge() { return netFedExCharge; } /** * Sets the value of the netFedExCharge property. * * @param value * allowed object is * {@link Money } * */ public void setNetFedExCharge(Money value) { this.netFedExCharge = value; } /** * Gets the value of the totalTaxes property. * * @return * possible object is * {@link Money } * */ public Money getTotalTaxes() { return totalTaxes; } /** * Sets the value of the totalTaxes property. * * @param value * allowed object is * {@link Money } * */ public void setTotalTaxes(Money value) { this.totalTaxes = value; } /** * Gets the value of the netCharge property. * * @return * possible object is * {@link Money } * */ public Money getNetCharge() { return netCharge; } /** * Sets the value of the netCharge property. * * @param value * allowed object is * {@link Money } * */ public void setNetCharge(Money value) { this.netCharge = value; } /** * Gets the value of the totalRebates property. * * @return * possible object is * {@link Money } * */ public Money getTotalRebates() { return totalRebates; } /** * Sets the value of the totalRebates property. * * @param value * allowed object is * {@link Money } * */ public void setTotalRebates(Money value) { this.totalRebates = value; } /** * Gets the value of the freightDiscounts property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the Jakarta XML Binding object. * This is why there is not a <CODE>set</CODE> method for the freightDiscounts property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFreightDiscounts().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link RateDiscount } * * */ public List<RateDiscount> getFreightDiscounts() { if (freightDiscounts == null) { freightDiscounts = new ArrayList<RateDiscount>(); } return this.freightDiscounts; } /** * Gets the value of the rebates property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the Jakarta XML Binding object. * This is why there is not a <CODE>set</CODE> method for the rebates property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRebates().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Rebate } * * */ public List<Rebate> getRebates() { if (rebates == null) { rebates = new ArrayList<Rebate>(); } return this.rebates; } /** * Gets the value of the surcharges property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the Jakarta XML Binding object. * This is why there is not a <CODE>set</CODE> method for the surcharges property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSurcharges().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Surcharge } * * */ public List<Surcharge> getSurcharges() { if (surcharges == null) { surcharges = new ArrayList<Surcharge>(); } return this.surcharges; } /** * Gets the value of the taxes property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the Jakarta XML Binding object. * This is why there is not a <CODE>set</CODE> method for the taxes property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTaxes().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Tax } * * */ public List<Tax> getTaxes() { if (taxes == null) { taxes = new ArrayList<Tax>(); } return this.taxes; } /** * Gets the value of the variableHandlingCharges property. * * @return * possible object is * {@link VariableHandlingCharges } * */ public VariableHandlingCharges getVariableHandlingCharges() { return variableHandlingCharges; } /** * Sets the value of the variableHandlingCharges property. * * @param value * allowed object is * {@link VariableHandlingCharges } * */ public void setVariableHandlingCharges(VariableHandlingCharges value) { this.variableHandlingCharges = value; } }
true
621507fbcbea46ff70cac8586f53bd59f5b0dce4
Java
ashishjha89/MyTVList
/mobile/src/main/java/com/mytvlist/listener/ChooseItemListener.java
UTF-8
209
1.65625
2
[]
no_license
package com.mytvlist.listener; /** * Created by ashish.jha on 7/12/2015. */ public interface ChooseItemListener { public void onListItemSelected(boolean isSearch, int count, boolean isDeleteAction); }
true
dd1614eb6a02d386262bf2293d25752961ef2d2b
Java
zcwzcwzcw/xshop
/xshop_service_goods/src/main/java/com/xshop/service/impl/AlbumServiceImpl.java
UTF-8
3,662
2.3125
2
[]
no_license
package com.xshop.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.xshop.dao.AlbumMapper; import com.xshop.entity.PageResult; import com.xshop.pojo.goods.Album; import com.xshop.service.goods.AlbumService; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import tk.mybatis.mapper.entity.Example; import java.util.List; import java.util.Map; @Service public class AlbumServiceImpl implements AlbumService { @Autowired private AlbumMapper albumMapper; @Override public List<Album> findAll() { return albumMapper.selectAll(); } @Override public PageResult<Album> findPage(int page, int size) { PageHelper.startPage(page, size); Page<Album> albums = (Page<Album>) albumMapper.selectAll(); return new PageResult<Album>(albums.getTotal(), albums.getResult()); } @Override public List<Album> findList(Map<String, Object> searchMap) { Example example = createExample(searchMap); return albumMapper.selectByExample(example); } @Override public PageResult<Album> findPage(Map<String, Object> searchMap, int page, int size) { PageHelper.startPage(page, size); Example example = createExample(searchMap); Page<Album> albums = (Page<Album>) albumMapper.selectByExample(example); return new PageResult<Album>(albums.getTotal(), albums.getResult()); } @Override public Album findById(Long id) { return albumMapper.selectByPrimaryKey(id); } @Override public void add(Album album) { albumMapper.insert(album); } @Override public void update(Album album) { albumMapper.updateByPrimaryKeySelective(album); } @Override public void delete(Long id) { albumMapper.deleteByPrimaryKey(id); } @Override public void addImage(Integer id, String image) { if (id == null || StringUtils.isBlank(image)) { throw new RuntimeException("参数错误"); } Album album = albumMapper.selectByPrimaryKey(id); if (album != null) { JSONArray images = JSONObject.parseArray(album.getImageItems()); images.add(image); album.setImageItems(images.toJSONString()); int count = albumMapper.updateByPrimaryKey(album); if (count <= 0) { throw new RuntimeException("添加图片失败"); } } } /** * 构建查询条件 * * @param searchMap * @return */ private Example createExample(Map<String, Object> searchMap) { Example example = new Example(Album.class); Example.Criteria criteria = example.createCriteria(); if (searchMap != null) { // 相册名称 if (searchMap.get("title") != null && !"".equals(searchMap.get("title"))) { criteria.andLike("title", "%" + searchMap.get("title") + "%"); } // 相册封面 if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) { criteria.andLike("image", "%" + searchMap.get("image") + "%"); } // 图片列表 if (searchMap.get("imageItems") != null && !"".equals(searchMap.get("imageItems"))) { criteria.andLike("imageItems", "%" + searchMap.get("imageItems") + "%"); } } return example; } }
true
d2c37cba59d64cbe43d298d7143efd051205e2bd
Java
swetabj/DataStructureProblems
/LRUCaching/src/Tester.java
UTF-8
1,527
3.421875
3
[]
no_license
import java.util.*; public class Tester { public static void main(String[] args) { // TODO Auto-generated method stub String sizeStr; Scanner s = new Scanner(System.in); sizeStr = s.nextLine(); String[] sizeArray = splitFunc(sizeStr); int size = 0; if(validateInputArguments(sizeArray,2,"Size")) { size = Integer.parseInt(sizeArray[1]); System.out.println("SIZE OK"); } else { System.out.println("Invalid Input"); } LRUCaching caching = new LRUCaching(size); while(true) { if(size>0) { String inputStr = s.nextLine(); String[] inputArr = splitFunc(inputStr); String input = inputArr[0].toUpperCase(); switch (input) { case "GET": if(validateInputArguments(inputArr,2,"GET")) { caching.getFunc(inputArr[1]); } else { System.out.println("ERROR"); } break; case "SET": if(validateInputArguments(inputArr,3,"SET")) { caching.setFunc(inputArr[1],inputArr[2]); } else { System.out.println("InValid input"); } break; case "EXIT": System.exit(0); break; default: System.out.println("InValid input"); System.exit(0); break; } } } } public static String[] splitFunc(String s) { return s.split(" "); } public static boolean validateInputArguments(String[] strArr,int noOfArguments, String validFirstArg) { if (strArr.length == noOfArguments && strArr[0].equalsIgnoreCase(validFirstArg)) { return true; } return false; } }
true
5a33e9f3034ae1ff35959109af2912904d10f608
Java
kishorereddy11/liquibase-mongodb
/src/main/java/liquibase/ext/mongodb/statement/CountCollectionByNameStatement.java
UTF-8
1,644
2.265625
2
[ "Apache-2.0" ]
permissive
package liquibase.ext.mongodb.statement; /*- * #%L * Liquibase MongoDB Extension * %% * Copyright (C) 2019 Mastercard * %% * 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. * #L% */ import liquibase.ext.mongodb.database.MongoConnection; import liquibase.nosql.statement.NoSqlQueryForLongStatement; import lombok.EqualsAndHashCode; import lombok.Getter; import java.util.stream.StreamSupport; @Getter @EqualsAndHashCode(callSuper = true) public class CountCollectionByNameStatement extends AbstractCollectionStatement implements NoSqlQueryForLongStatement<MongoConnection> { public static final String COMMAND_NAME = "getCollectionNames"; public CountCollectionByNameStatement(final String collectionName) { super(collectionName); } @Override public String getCommandName() { return COMMAND_NAME; } @Override public long queryForLong(final MongoConnection connection) { return StreamSupport.stream(connection.getDatabase().listCollectionNames().spliterator(), false) .filter(s -> s.equals(getCollectionName())) .count(); } }
true
6d4182fac68c145c1cfc607b5b942f52eaeeaa4b
Java
DanIulian/PeerToPeer-Torrent-Client
/src/test/TestClient1.java
UTF-8
1,534
3.1875
3
[ "MIT" ]
permissive
package test; import java.io.File; import java.net.InetAddress; import client.Client; public class TestClient1 { /* lista de fisiere pe care server-ul le va publica */ public static String files[] = {"files/3DUniverse.jpg", "files/Compilers.pdf", "files/porche.jpg", "files/SPRCBook.pdf" }; public static void main(String argv[]) { System.out.println("[TestClient1]: Starting testing client 1 (this one publish a set of files)"); if (argv.length < 2) { System.out.println("[TestClient1]: The client starts with command: java Client ServerHost ServerPort ClientPort"); System.exit(-1); } try { /* adresarea serverului (ip, port) */ String serverHost = argv[0]; int serverPort = Integer.parseInt(argv[1]); /* adresarea clientului (ip, port) */ String clientHost = InetAddress.getLocalHost().getHostName(); int clientPort = Integer.parseInt(argv[2]); Client cli = new Client(clientHost,clientPort,serverHost,serverPort); /* publica fisierele */ for(String file: files) { File curentFile=new File(file); cli.publishFile(curentFile); System.out.println("[TestClient1]: File "+file+" was published... DONE!"); } Thread.sleep(50000); cli.close(); //String filename = "files/porche.jpg"; //File currentFile = new File(filename); //cli.publishFile(currentFile); //System.out.println("[TestClient1]: File " + filename + " was published... DONE !"); } catch(Exception e) { e.printStackTrace(); } } }
true
6ff768a53773eba6d633c9424212634af815947f
Java
lexbaev/directory-scanner
/src/test/java/my/app/mapper/impl/CommandLineMapperScanMenuImplTest.java
UTF-8
2,810
2.359375
2
[]
no_license
package my.app.mapper.impl; import my.app.exceptions.ValidationException; import my.app.mapper.MappedScanRequest; import my.app.parser.impl.CommandLineParserImpl; import org.apache.commons.cli.CommandLine; import org.junit.Test; import static org.junit.Assert.*; public class CommandLineMapperScanMenuImplTest { private CommandLineParserImpl commandLineParser = (CommandLineParserImpl) CommandLineParserImpl.getInstance(); private CommandLineMapperScanMenuImpl commandLineMapper = (CommandLineMapperScanMenuImpl) CommandLineMapperScanMenuImpl.getInstance(); @Test public void testParseAndMap() throws ValidationException { String command = "scan -input C:/test/in/ -output C:/test/out/new/ -mask *.txt -waitInterval 10000 -includeSubfolders true -autoDelete false"; CommandLine parsedCommandLine = commandLineParser.parse(command); assertEquals(1, parsedCommandLine.getArgs().length); assertEquals(6, parsedCommandLine.getOptions().length); MappedScanRequest mappedScanRequest = commandLineMapper.map(parsedCommandLine); assertEquals("c:/test/in/", mappedScanRequest.getSourcePath()); assertEquals("c:/test/out/new/", mappedScanRequest.getDestinationPath()); assertEquals("*.txt", mappedScanRequest.getMask()); assertEquals(10000l, mappedScanRequest.getWaitInterval()); assertEquals(true, mappedScanRequest.isIncludeSubfolders()); assertEquals(false, mappedScanRequest.isAutodelete()); } @Test public void testParseWithoutRequiredArgument() { String command = "scan -input C:/test/in/"; org.apache.commons.cli.CommandLine parsedCommandLine = commandLineParser.parse(command); assertNull(parsedCommandLine); } @Test public void testParseNull() { String command = "scan"; org.apache.commons.cli.CommandLine parsedCommandLine = commandLineParser.parse(command); assertNull(parsedCommandLine); } @Test (expected = ValidationException.class) public void testMapValidationException() throws ValidationException { String command = "scan -input aaa -output bbb -mask *.txt -waitInterval ccc -includeSubfolders ddd -autoDelete eee"; CommandLine parsedCommandLine = commandLineParser.parse(command); assertEquals(1, parsedCommandLine.getArgs().length); assertEquals(6, parsedCommandLine.getOptions().length); commandLineMapper.map(parsedCommandLine); } @Test public void isValidBoolean() { assertTrue(commandLineMapper.isValidBoolean("true")); assertTrue(commandLineMapper.isValidBoolean("FALSE")); assertFalse(commandLineMapper.isValidBoolean("FAL")); } @Test public void isValidPath() { assertTrue(commandLineMapper.isValidPath("c:/111/")); assertTrue(commandLineMapper.isValidPath("c:\\111")); assertFalse(commandLineMapper.isValidPath("\\111")); } }
true
cbe3e5f1c144d284d2051a14d4491ba69129e5a1
Java
mcculls/nexus
/nexus/nexus-api/src/test/java/org/sonatype/nexus/proxy/walker/FixedRateWalkerThrottleControllerTest.java
UTF-8
5,337
1.960938
2
[]
no_license
/** * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2007-2012 Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ package org.sonatype.nexus.proxy.walker; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.lessThan; import org.junit.Test; import org.mockito.Mockito; import org.sonatype.nexus.proxy.walker.WalkerThrottleController.ThrottleInfo; import org.sonatype.nexus.util.ConstantNumberSequence; import org.sonatype.nexus.util.FibonacciNumberSequence; import org.sonatype.nexus.util.NumberSequence; /** * Test for fixed rate walker throttle controller. * * @author cstamas */ public class FixedRateWalkerThrottleControllerTest { protected FixedRateWalkerThrottleController fixedRateWalkerThrottleController; @Test public void testDoesItHelpAtAll() { final int measuredTpsHigh = performAndMeasureActualTps( 20, new ConstantNumberSequence( 1 ) ); final int measuredTpsMid = performAndMeasureActualTps( 10, new ConstantNumberSequence( 1 ) ); final int measuredTpsLow = performAndMeasureActualTps( 5, new ConstantNumberSequence( 1 ) ); System.err.println( measuredTpsHigh + "\n" + measuredTpsMid + "\n" + measuredTpsLow ); assertThat( "Mid TPS should be less than high TPS run", measuredTpsMid, lessThan( measuredTpsHigh ) ); assertThat( "Low TPS should be less than medium TPS run", measuredTpsLow, lessThan( measuredTpsMid ) ); } // == protected int performAndMeasureActualTps( final int wantedTps, final NumberSequence loadChange ) { fixedRateWalkerThrottleController = new FixedRateWalkerThrottleController( wantedTps, new FibonacciNumberSequence( 1 ) ); fixedRateWalkerThrottleController.setSliceSize( 1 ); final TestThrottleInfo info = new TestThrottleInfo(); final WalkerContext context = Mockito.mock( WalkerContext.class ); // sleeptime starts oscillating after the 10th iteration, give some extra iterations to bring down the average final int iterationCount = 25; final long startTime = System.currentTimeMillis(); fixedRateWalkerThrottleController.walkStarted( context ); for ( int i = 0; i < iterationCount; i++ ) { info.simulateInvocation( loadChange.next() ); long sleepTime = fixedRateWalkerThrottleController.throttleTime( info ); sleep( sleepTime ); // sleep as much as throttle controller says to sleep } fixedRateWalkerThrottleController.walkEnded( context, info ); final int measuredTps = fixedRateWalkerThrottleController.calculateCPS( iterationCount, System.currentTimeMillis() - startTime ); // System.out.println( "MeasuredTps=" + measuredTps ); // System.out.println( "lastSliceTps=" + fixedRateWalkerThrottleController.getLastSliceTps() ); // System.out.println( "GlobalAvgTps=" + fixedRateWalkerThrottleController.getGlobalAverageTps() ); // System.out.println( "GlobalMaxTps=" + fixedRateWalkerThrottleController.getGlobalMaximumTps() ); return measuredTps; } // == protected static void sleep( long millis ) { try { Thread.sleep( millis ); } catch ( InterruptedException e ) { // need to kill test too throw new RuntimeException( e ); } } protected static class TestThrottleInfo implements ThrottleInfo { private final long started; private long totalProcessItemSpentMillis; private long totalProcessItemInvocationCount; public TestThrottleInfo() { this.started = System.currentTimeMillis(); this.totalProcessItemSpentMillis = 0; this.totalProcessItemInvocationCount = 0; } public void simulateInvocation( final long spentTimeInProcessItem ) { // we need to sleep to keep getTotalTimeWalking() and totalProcessItemSpentMillis aligned sleep( spentTimeInProcessItem ); totalProcessItemSpentMillis = totalProcessItemSpentMillis + spentTimeInProcessItem; totalProcessItemInvocationCount++; } @Override public long getTotalProcessItemSpentMillis() { return totalProcessItemSpentMillis; } @Override public long getTotalProcessItemInvocationCount() { return totalProcessItemInvocationCount; } @Override public long getTotalTimeWalking() { return System.currentTimeMillis() - started; } } }
true
66bc54e8707872e7734ca9fc8ba309a50ee790e7
Java
nurchold/dwinurcholis
/app/src/main/java/com/example/dwi_n/sampleapplication/Model/UserProfile.java
UTF-8
919
2.34375
2
[]
no_license
package com.example.dwi_n.sampleapplication.Model; public class UserProfile { private String id; private String name; private String gender; private String phone; private String photoProfile; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPhotoProfile() { return photoProfile; } public void setPhotoProfile(String photoProfile) { this.photoProfile = photoProfile; } }
true
2f465abcf1b898572a4d25a58a6ae69e087af708
Java
sricardo97/api-rest-filtro-gastos
/src/main/java/br/com/santander/api/repositories/GastoRepository.java
UTF-8
389
1.867188
2
[]
no_license
package br.com.santander.api.repositories; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import br.com.santander.api.documents.Gasto; public interface GastoRepository extends MongoRepository<Gasto, String> { @Query("{ 'data' : ?0 }") List<Gasto> findByData(final String data); }
true
984b898aaf643717fab07ecec9681641807d062a
Java
chengliangzhou/pinpoint-agent-demo
/common/src/main/java/com/sino/common/service/IUserService.java
UTF-8
338
1.734375
2
[]
no_license
package com.sino.common.service; import com.sino.common.dto.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; @FeignClient(value = "producer") public interface IUserService { @RequestMapping(value = "findUserByName") User findUserByName(String name); }
true
2409ec46cc88f2d497b3c7935bb535f273c0a5a3
Java
lapd87/SoftUniDatabasesFrameworksHibernateAndSpringData
/07HibernateCodeFirstEntityRelations/src/main/java/_06FootballBettingDatabase/Competition.java
UTF-8
784
2.46875
2
[ "MIT" ]
permissive
package _06FootballBettingDatabase; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import java.util.Set; /** * Created by IntelliJ IDEA. * User: LAPD * Date: 28.3.2018 г. * Time: 20:36 ч. */ @Entity @Table(name = "competitions") public class Competition extends Nameable { private CompetitionType type; private Set<Game> games; @ManyToOne public CompetitionType getType() { return type; } public void setType(CompetitionType type) { this.type = type; } @OneToMany(mappedBy = "competition") public Set<Game> getGames() { return games; } public void setGames(Set<Game> games) { this.games = games; } }
true
08ffa458bb7e83120a86047888be98816cdeb383
Java
xxliu95/ISST-Grupo10-Trip
/Trip/src/es/upm/dit/isst/trip/servlets/SubirFacturaServlet.java
UTF-8
1,826
2.34375
2
[]
no_license
package es.upm.dit.isst.trip.servlets; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import es.upm.dit.isst.trip.dao.FacturaDAO; import es.upm.dit.isst.trip.dao.FacturaDAOImplementation; import es.upm.dit.isst.trip.dao.ViajeDAO; import es.upm.dit.isst.trip.dao.ViajeDAOImplementation; import es.upm.dit.isst.trip.model.Factura; import es.upm.dit.isst.trip.model.Viaje; /** * Servlet implementation class SubirFacturaServlet */ @WebServlet("/SubirFacturaServlet") @MultipartConfig public class SubirFacturaServlet extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String nViaje = req.getParameter("nViaje"); ViajeDAO vdao = ViajeDAOImplementation.getInstance(); FacturaDAO fdao = FacturaDAOImplementation.getInstance(); Factura factura = new Factura(); Viaje viaje = vdao.read(Integer.valueOf(nViaje)); req.setAttribute("viaje", viaje); //imports java.io Part filePart = req.getPart("file"); InputStream fileContent = filePart.getInputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[10240]; for (int length = 0; (length = fileContent.read(buffer)) > 0;) output.write(buffer, 0, length); factura.setViaje(viaje); factura.setDocumento(output.toByteArray()); fdao.create(factura); getServletContext().getRequestDispatcher( "/ViajeView.jsp" ).forward( req, resp ); } }
true
ce05ab9797598873a28b4abfdb0ee53556f41940
Java
identityOrg/identity
/src/main/java/net/prasenjit/identity/controller/audit/AuditApi.java
UTF-8
1,157
1.742188
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 prasenjit-net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.prasenjit.identity.controller.audit; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import net.prasenjit.identity.entity.AuditEvent; import net.prasenjit.identity.model.api.audit.SearchAuditRequest; import java.util.List; @Tag(name = "audit", description = "API's for audit event retrieval") public interface AuditApi { @Operation(summary = "Search Audit", description = "Search audits for display") List<AuditEvent> searchAudit(SearchAuditRequest audit); }
true
d810500954a074e8572be36f6140e555c55843be
Java
lmwis/admin-system
/src/main/java/com/fehead/open/admin/login/MyUserDetailsService.java
UTF-8
1,300
2.140625
2
[]
no_license
package com.fehead.open.admin.login; import com.fehead.open.admin.dao.AdminMapper; import com.fehead.open.admin.dao.PasswordMapper; import com.fehead.open.admin.dao.pojo.Admin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; /** * @author lmwis * @description: * @date 2019-08-29 16:08 * @Version 1.0 */ @Component public class MyUserDetailsService implements UserDetailsService { @Autowired AdminMapper userMapper; @Autowired PasswordMapper passwordMapper; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { Admin admin = userMapper.selectByUsername(s); if(admin == null){ throw new UsernameNotFoundException("用户名或密码不正确"); } return new org.springframework.security.core.userdetails.User(String.valueOf(admin.getId()) ,admin.getPassword(), AuthorityUtils.createAuthorityList("admin")); } }
true
433eebdfec6d90b9e041a0ac9861b7e8fe5154f6
Java
vkalithkar/TJCS9
/Unit4/Lab15/Gameboard15.java
UTF-8
1,709
3.015625
3
[]
no_license
//Name______________________________ Date_____________ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Gameboard15 extends JPanel { private JButton[][] board; private String gamepiece; private Color color; private int count; public Gameboard15(ActionListener a) { gamepiece = "X"; color = Color.green; count = 0; setLayout(new GridLayout(3, 3)); setBackground(Color.black); board = new JButton[3][3]; for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++) { board[x][y] = new JButton("-"); board[x][y].setFont(new Font("Monospaced", Font.PLAIN, 20)); board[x][y].setBackground(Color.white); board[x][y].setFocusPainted(false); board[x][y].addActionListener(a); // <---Add this one first!!!!! board[x][y].addActionListener(new Listener(x, y)); add(board[x][y]); } } private class Listener implements ActionListener { private int myX, myY; public Listener(int x, int y) { myX = x; myY = y; } public void actionPerformed(ActionEvent e) { // your code goes here } } public void freeze() { // your code goes here } public void reset() { // your code goes here } public boolean filled() { // your code goes here } public boolean winner() { // your code goes here } }
true
e7af75fd686b784e1880a6ecf6af22d0f997ff0e
Java
fellowlei/mysharding
/src/main/java/com/mark/sharding/plugin/v3/HelloServiceTest.java
UTF-8
801
2.078125
2
[]
no_license
package com.mark.sharding.plugin.v3; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Component; /** * @Auther: lulei * @Date: 2020/1/9 15:14 * @Description: */ @Component public class HelloServiceTest { @RoutingInjected("helloServiceImplB") private HelloService helloService; public void hello(){ String hello = helloService.hello(); System.out.println(hello); } public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext("com.vipkid.digitallibrary.plugin.v3"); HelloServiceTest helloServiceTest = applicationContext.getBean(HelloServiceTest.class); helloServiceTest.hello(); } }
true
a1a317b1a93cd93dbaafac500bda1df12ccd7b61
Java
latyak/Torpedo
/src/torpedo/SettingsForm.java
UTF-8
4,069
2.390625
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 torpedo; import javax.swing.*; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.Color; import java.util.ArrayList; /** * * @author latyak1 */ public class SettingsForm extends JPanel { JLabel userNameLbl; JTextField userName; JLabel nickNameLbl; JTextField nickName; JLabel pwdLbl; JPasswordField pwd; JLabel confPwdLbl; JPasswordField confPwd; JButton regBtn; JButton backBtn; JLabel errorMsgLbl; JLabel countryLbl; JComboBox country; MainFrame frame; User user; public SettingsForm(User user) { this.user = user; ArrayList result = new ArrayList(); result = Db.getProfile(); userNameLbl = new JLabel("Felhasználónév:"); userName = new JTextField(20); nickNameLbl = new JLabel("Becenév:"); nickName = new JTextField(20); countryLbl = new JLabel("Ország:"); country = new JComboBox(); pwdLbl = new JLabel("Jelszó:"); pwd = new JPasswordField(20); confPwdLbl = new JLabel("Jelszó megerősítése:"); confPwd = new JPasswordField(20); errorMsgLbl = new JLabel(); errorMsgLbl.setForeground(Color.red); regBtn = new JButton("Regisztrálás"); backBtn = new JButton("<< Vissza"); for (int i = 0; i < 10; i++) { country.addItem(new ComboItem("Visible String " + i, "Value " + i)); } this.frame = frame; this.setLayout(new FormLayout("100px, 350px, 200px", "70px, 70px, 70px, 70px, 70px, 70px, 70px")); CellConstraints c = new CellConstraints(); this.add(errorMsgLbl, c.xy(2, 1, CellConstraints.LEFT, CellConstraints.CENTER)); this.add(userNameLbl, c.xy(2, 2, CellConstraints.LEFT, CellConstraints.CENTER)); this.add(userName, c.xy(2, 2, CellConstraints.LEFT, CellConstraints.BOTTOM)); this.add(nickName, c.xy(2, 3, CellConstraints.LEFT, CellConstraints.BOTTOM)); this.add(nickNameLbl, c.xy(2, 3, CellConstraints.LEFT, CellConstraints.CENTER)); this.add(country, c.xy(2, 4, CellConstraints.LEFT, CellConstraints.BOTTOM)); this.add(countryLbl, c.xy(2, 4, CellConstraints.LEFT, CellConstraints.CENTER)); this.add(pwdLbl, c.xy(2, 5, CellConstraints.LEFT, CellConstraints.CENTER)); this.add(pwd, c.xy(2, 5, CellConstraints.LEFT, CellConstraints.BOTTOM)); this.add(confPwdLbl, c.xy(2, 6, CellConstraints.LEFT, CellConstraints.CENTER)); this.add(confPwd, c.xy(2, 6, CellConstraints.LEFT, CellConstraints.BOTTOM)); this.add(regBtn, c.xy(2, 7, CellConstraints.RIGHT, CellConstraints.BOTTOM)); this.add(backBtn, c.xy(2, 7, CellConstraints.LEFT, CellConstraints.BOTTOM)); int result = JOptionPane.showConfirmDialog(null, this, "Test", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { System.out.println("asd"); } else { System.out.println("Cancelled"); } /*regBtn.addMouseListener(new RegEvent(this.frame)); backBtn.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { frame.showCard("loginForm"); } });*/ } public JTextField getUserName() { return userName; } public JTextField getNickName() { return nickName; } public JPasswordField getPwd() { return pwd; } public JPasswordField getConfPwd() { return confPwd; } public String getCountry() { Object item = country.getSelectedItem(); String value = ((ComboItem) item).getValue(); return value; } public void setErrorMsgLbl(String msg) { this.errorMsgLbl.setText(msg); } }
true
c0dcf66a79c91fd4f6bfca53408bec83fe684301
Java
cevaris/learn-java
/src/main/java/com/cevaris/concurrency/dining_philosophers/DiningPhilosophers.java
UTF-8
4,327
3.421875
3
[]
no_license
package com.cevaris.concurrency.dining_philosophers; import java.util.Deque; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class DiningPhilosophers { private final ExecutorService dinnerTable; private final int numberOfPhilosophers; public DiningPhilosophers(int numberOfPhilosophers) { dinnerTable = Executors.newFixedThreadPool(numberOfPhilosophers); this.numberOfPhilosophers = numberOfPhilosophers; } void start(long runForMs) throws InterruptedException { final Waiter waiter = new BenitoTheWaiter(numberOfPhilosophers); final DiningClock clock = new ChefsWatch(); for (int i = 0; i < numberOfPhilosophers; i++) { dinnerTable.submit(new LeftyRightyPhilosopher(waiter, clock)); } Thread.sleep(runForMs * 10000); // clock.endDinner(); // Thread.sleep(runForMs / 2); // dinnerTable.shutdown(); // dinnerTable.awaitTermination(1, TimeUnit.DAYS); } } interface Philosopher extends Runnable { } class LeftyRightyPhilosopher implements Philosopher { private final Waiter waiter; private final DiningClock clock; private Fork left; private Fork right; public LeftyRightyPhilosopher(Waiter waiter, DiningClock clock) { this.waiter = waiter; this.clock = clock; } @Override public void run() { while (true) { boolean isDinnerTime = clock.isDinnerTime(); boolean interrupted = Thread.currentThread().isInterrupted(); if (!isDinnerTime || interrupted) { stopEating(); printStatus("finished dinner"); break; } if (left == null) { printStatus("waiting left"); left = waiter.askForLeft(); printStatus("got left"); continue; } if (right == null) { printStatus("waiting right"); right = waiter.askForRight(); printStatus("got right"); continue; } printStatus("is eating"); stopEating(); } } private void printStatus(String msg) { System.out.println(Thread.currentThread().getName() + " " + msg + "[ " + left + "," + right + "]"); System.out.flush(); } private void stopEating() { if (left != null) { waiter.returnLeft(left); left = null; printStatus("released left"); } if (right != null) { waiter.returnRight(right); right = null; printStatus("released right"); } } private boolean isTimeToEat() { return clock.isDinnerTime() && !Thread.currentThread().isInterrupted(); } } class Fork { @Override public String toString() { return "fork"; } } interface DiningClock { boolean isDinnerTime(); void endDinner(); } class ChefsWatch implements DiningClock { private volatile boolean isKitchenOpen = true; @Override public boolean isDinnerTime() { return isKitchenOpen; } @Override public void endDinner() { isKitchenOpen = false; System.out.println("no more dinner!!!"); } } interface Waiter { Fork askForLeft(); Fork askForRight(); void returnLeft(Fork fork); void returnRight(Fork fork); } class BenitoTheWaiter implements Waiter { private final Semaphore semaphoreRight; private final Semaphore semaphoreLeft; private final Deque<Fork> forks; public BenitoTheWaiter(int numberOfForks) { semaphoreLeft = new Semaphore(numberOfForks - (numberOfForks / 2)); semaphoreRight = new Semaphore(numberOfForks / 2); forks = new LinkedList<>(); for (int i = 0; i < numberOfForks; i++) { forks.add(new Fork()); } } @Override public Fork askForRight() { return ask(semaphoreRight); } @Override public Fork askForLeft() { return ask(semaphoreLeft); } private Fork ask(Semaphore s) { try { s.tryAcquire(10, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return forks.pop(); } @Override public void returnLeft(Fork fork) { returnFork(semaphoreLeft, fork); } @Override public void returnRight(Fork fork) { returnFork(semaphoreRight, fork); } private void returnFork(Semaphore s, Fork fork) { forks.addLast(fork); s.release(); } }
true
5403ce4f77f920f3e18f76b758dfbe936c536d55
Java
HDUKimi/Lab603Projects
/violetproduct-swing/src/main/java/com/horstmann/violet/application/gui/util/wujun/SequenceTransfrom/UppaalTemplate.java
GB18030
875
2.125
2
[]
no_license
package com.horstmann.violet.application.gui.util.wujun.SequenceTransfrom; import java.util.ArrayList; public class UppaalTemplate { String declaration; String Name;//Զ ArrayList<UppaalLocation> locations=new ArrayList<UppaalLocation>();//״̬ ArrayList<UppaalTransition>transitions=new ArrayList<UppaalTransition>();//ǨƼ public String getName() { return Name; } public void setName(String name) { Name = name; } public ArrayList<UppaalLocation> getLocations() { return locations; } public void setLocations(ArrayList<UppaalLocation> locations) { this.locations = locations; } public ArrayList<UppaalTransition> getTransitions() { return transitions; } public void setTransitions(ArrayList<UppaalTransition> transitions) { this.transitions = transitions; } }
true
54f88d302794328bfc2586b4836d5c9d5d189ecc
Java
iBakuman/MyBatis
/A_01_Introduction/src/main/java/com/example/dao/IStudentDao.java
UTF-8
333
2.046875
2
[]
no_license
package com.example.dao; import com.example.domain.Student; import org.apache.ibatis.annotations.Select; import java.util.List; public interface IStudentDao { /** * 查询所有记录 * @return 返回封装了的对象数组 */ @Select("select * from student") List<Student> findAll(); }
true
04e0bb23beac1dcc27e36611e54ee97138300398
Java
roy7rohit/java-basics
/Array/array.java
UTF-8
576
3.34375
3
[ "MIT" ]
permissive
package array; import java.util.Arrays; public class array { public static void reverse(int arr[]){ //start = 0, end = length-1 //arr[] = {12,23,45,95} //arr[] = {} int start = 0; int end = arr.length - 1; while(start <= end){ int temp; temp = arr[start];//12=temp arr[start] = arr[end];//arr[0] = arr[3] = 95 = arr[0] start++; end--; } } public static void main(String[] args) { int a[] = {12,23,45,95}; // System.out.println(a); reverse(a); System.out.println(Arrays.toString(a)); } }
true
e3a8fc54a6dc872cc7a4c7a7d1b144cace03374e
Java
AmuseWorkingTeam/XXYP
/app/src/main/java/com/xxyp/xxyp/map/utils/NetworkUtils.java
UTF-8
2,643
2.671875
3
[ "Apache-2.0" ]
permissive
package com.xxyp.xxyp.map.utils; import android.Manifest; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.annotation.RequiresPermission; /** * Description : 网络工具类 */ public class NetworkUtils { /** * 判断网络是否可用 */ @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE) public static boolean isNetworkAvailable(Context context) { try { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { return false; } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (NetworkInfo networkInfo : info) { if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE || networkInfo.getType() == ConnectivityManager.TYPE_WIFI || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) { if (networkInfo.getState() == NetworkInfo.State.CONNECTED) { return true; } } } } } } catch (Exception e) { e.getStackTrace(); } return false; } /** * 是否WiFi环境 */ @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE) public static boolean isWifi(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = null; if (connectivityManager != null) { activeNetInfo = connectivityManager.getActiveNetworkInfo(); } return activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI; } /** * 是否移动环境 */ @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE) public static boolean isMobile(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (null != connectivityManager) { NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); return activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE; } else { return false; } } }
true
01e3b7c32f054070eace5cc705ca46a0baad057c
Java
RamakrishnaQA123/GoogleMaps
/SathyaProject/src/TestNGFramework/Tc1ByReusableMethods.java
UTF-8
1,252
2.046875
2
[]
no_license
package TestNGFramework; import org.openqa.selenium.By; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.server.browserlaunchers.Sleeper; import org.testng.annotations.Test; public class Tc1ByReusableMethods { HrmloginTCByTestNG obj; FirefoxDriver driver; @Test public void Tc1login(){ obj=new HrmloginTCByTestNG(); obj.open(); obj.login("Admin","admin123"); obj.verifystatus(); Sleeper.sleepTightInSeconds(5); driver.findElement(By.id("menu_pim_viewPimModule")).click(); Sleeper.sleepTightInSeconds(2); driver.findElement(By.id("menu_pim_addEmployee")).click(); driver.findElement(By.id("firstName")).sendKeys("QAUser"); driver.findElement(By.id("middleName")).sendKeys("Tester"); driver.findElement(By.id("lastName")).sendKeys("Quality"); driver.findElement(By.id("employeeId")).sendKeys("0036"); driver.findElement(By.id("btnSave")).click(); Sleeper.sleepTightInSeconds(3); String Actual=driver.findElement(By.xpath(".//*[@id='profile-pic']/h1")).getText(); String Expected="QAUser"; if(Actual.contains("Expected")){ System.out.println("pass"); } else{ System.out.println("fail"); } obj.logout(); obj.close(); } }
true
5f74ce94ed6373b387bdfa08a3a44186a4e49685
Java
omerclskn/Kizilay-Database-Sistemi
/src/basvuranDB.java
UTF-8
25,112
2.296875
2
[]
no_license
package kizilay; import java.awt.Color; import java.awt.EventQueue; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; import java.util.ArrayList; import java.awt.event.ActionEvent; import java.awt.Toolkit; import java.awt.Font; import javax.swing.SwingConstants; import javax.swing.JCheckBox; public class basvuranDB extends JFrame { private static final long serialVersionUID = 1L; private JPanel contentPane; private JTextField textField_0; private JTextField textField_1; private JTextField textField_2; private JTextField textField_3; private JTextField textField_4; private JTextField textField_5; private JTextField textField_6; private JTextField textField_7; private JTextField textField_8; private JTextField textField_9; private JTextField textField_10; private JTextField textField_11; private JTextField textField_12; private JTextField textField_13; private JTextField textField_14; private JTextField textField_15; private JTextField textField_16; private JTextField textField_17; private JLabel lblNewLabel_1; private JLabel lblNewLabel_2; private JLabel lblNewLabel_3; private JLabel lblNewLabel_4; private JLabel lblNewLabel_5; private JLabel lblNewLabel_6; private JLabel lblNewLabel_7; private JLabel lblNewLabel_8; private JLabel lblNewLabel_9; private JLabel lblNewLabel_10; private JLabel lblNewLabel_11; private JLabel lblNewLabel_12; private JLabel lblNewLabel_13; private JLabel lblNewLabel_14; private JLabel lblNewLabel_15; private JLabel lblNewLabel_16; private JLabel lblNewLabel_17; private JLabel lblNewLabel_18; private final DefaultTableModel basvuran; private JLabel lblNewLabel_19; private JLabel lblNewLabel_20; private JLabel lblNewLabel_21; private JCheckBox chckbxNewCheckBox; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { basvuranDB frame = new basvuranDB(); frame.setVisible(true); frame.setTitle("Basvuranlar"); } catch (Exception e) { e.printStackTrace(); } } }); } public basvuranDB() throws SQLException{ setTitle("Kizilay"); setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\TULPAR\\Desktop\\icons\\tkizilay.png")); String user="postgres"; String password="root"; Connection conn=DriverManager.getConnection("jdbc:postgresql://localhost:5432/proje",user,password); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 1081, 600); contentPane = new JPanel(); contentPane.setBackground(Color.LIGHT_GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblNewLabel = new JLabel("Basvuran Table"); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 16)); lblNewLabel.setBounds(921, 255, 138, 35); contentPane.add(lblNewLabel); ArrayList<String> fetch_index = new ArrayList<String>(); ArrayList<String> fields = new ArrayList<String>(); fields.add("ad"); fields.add("soyad"); fields.add("tc"); fields.add("dogumt"); fields.add("cinsiyet"); fields.add("kang"); fields.add("tarih"); fields.add("covid"); fields.add("odul"); Object[] columnNames = {"Ad", "Soyad", "TC", "Dogum Tarihi", "Cinsiyet", "Kan Grubu", "Tarih","Covid","Odul"}; basvuran = new DefaultTableModel(columnNames, 0); JTable table = new JTable(basvuran); JScrollPane sp = new JScrollPane(table); sp.setBounds(40, 115, 850, 312); contentPane.add(sp); JButton btnNewButton = new JButton("Fetch"); btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 20)); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean flag=false; String temp=""; String and = " AND "; fetch_index.clear(); if(textField_0.getText().length()!=0) { temp+="ad="+"'"+textField_0.getText()+"'"; fetch_index.add(textField_0.getText()); flag=true;} else fetch_index.add("NULL"); if(textField_1.getText().length()!=0) { if(flag==true) temp+=and; temp+="soyad="+"'"+textField_1.getText()+"'"; fetch_index.add(textField_1.getText()); flag=true; } else fetch_index.add("NULL"); if(textField_2.getText().length()!=0) { if(flag==true) temp+=and; temp+="tc="+"'"+textField_2.getText()+"'"; fetch_index.add(textField_2.getText()); flag=true; } else fetch_index.add("NULL"); if(textField_3.getText().length()!=0) { if(flag==true) temp+=and; temp+="dogumt="+"'"+textField_3.getText()+"'"; fetch_index.add(textField_3.getText()); flag=true;} else fetch_index.add("NULL"); if(textField_4.getText().length()!=0) { if(flag==true) temp+=and; temp+="cinsiyet="+"'"+textField_4.getText()+"'"; fetch_index.add(textField_4.getText()); flag=true;} else fetch_index.add("NULL"); if(textField_5.getText().length()!=0) { if(flag==true) temp+=and; temp+="kang="+"'"+textField_5.getText()+"'"; fetch_index.add(textField_5.getText()); flag=true;} else fetch_index.add("NULL"); if(textField_6.getText().length()!=0) { if(flag==true) temp+=and; temp+="tarih="+"'"+textField_6.getText()+"'"; fetch_index.add(textField_6.getText()); flag=true;} else fetch_index.add("NULL"); if(textField_7.getText().length()!=0) { if(flag==true) temp+=and; temp+="covid="+"'"+textField_7.getText()+"'"; fetch_index.add(textField_7.getText()); flag=true;} else fetch_index.add("NULL"); if(textField_16.getText().length()!=0) { temp+="odul="+"'"+textField_16.getText()+"'"; fetch_index.add(textField_16.getText()); flag=true;} else fetch_index.add("NULL"); String query; if(flag==true) query="select * from basvuran "+"where "+temp; else{ query="select * from basvuran "; } java.sql.Statement s; try { s = conn.createStatement(); ResultSet r=s.executeQuery(query); String temp2=""; DefaultTableModel dm = (DefaultTableModel)table.getModel(); // Önceki sorgu sonucu while(dm.getRowCount() > 0){ // oluşan satırları dm.removeRow(0); // temizleme kısmı } while(r.next()) { temp2 +=r.getString(1)+" "; String ad = r.getString(1); temp2 +=r.getString(2)+" "; String soyad = r.getString(2); temp2 +=r.getString(3)+" "; String tc = r.getString(3); temp2 +=r.getString(4)+" "; String dogumT = r.getString(4); temp2 +=r.getString(5)+" "; String cinsiyet = r.getString(5); temp2 +=r.getString(6)+" "; String kang = r.getString(6); temp2 +=r.getString(7)+" "; String tarih = r.getString(7); temp2 +=r.getString(8); String covid = r.getString(8); temp2 +=r.getString(9); String odul = r.getString(9); Object[] row ={ad, soyad, tc, dogumT, cinsiyet, kang, tarih, covid,odul}; basvuran.addRow(row); System.out.println(temp2); temp2 = ""; } } catch (SQLException e1) { e1.printStackTrace(); } } }); btnNewButton.setBounds(915, 23, 144, 52); contentPane.add(btnNewButton); JButton btnNewButton_1 = new JButton("Delete"); btnNewButton_1.setFont(new Font("Tahoma", Font.BOLD, 20)); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String temp="DELETE FROM basvuran "; boolean flag=false; String and=" AND "; String query=""; if(textField_0.getText().length()!=0) { query+="ad="+"'"+textField_0.getText()+"'"; flag=true;} if(textField_1.getText().length()!=0) { if(flag==true) query+=and; query+="soyad="+"'"+textField_1.getText()+"'"; flag=true; } if(textField_2.getText().length()!=0) { if(flag==true) query+=and; query+="tc="+"'"+textField_2.getText()+"'"; flag=true; } if(textField_3.getText().length()!=0) { if(flag==true) query+=and; query+="dogumt="+"'"+textField_3.getText()+"'"; flag=true;} if(textField_4.getText().length()!=0) { if(flag==true) query+=and; query+="cinsiyet="+"'"+textField_4.getText()+"'"; flag=true;} if(textField_5.getText().length()!=0) { if(flag==true) query+=and; query+="kang="+"'"+textField_5.getText()+"'"; flag=true;} if(textField_6.getText().length()!=0) { if(flag==true) query+=and; query+="tarih="+"'"+textField_6.getText()+"'"; flag=true;} if(textField_7.getText().length()!=0) { if(flag==true) query+=and; query+="covid="+"'"+textField_7.getText()+"'"; flag=true;} if(textField_16.getText().length()!=0) { if(flag==true) query+=and; query+="odul="+"'"+textField_16.getText()+"'"; flag=true;} String temp2=""; if(flag==true) { temp2=" Where "; } query=temp+temp2+query; java.sql.Statement s; try { s = conn.createStatement(); s.executeQuery(query); } catch (SQLException e1) { e1.printStackTrace(); } } }); btnNewButton_1.setBounds(921, 89, 138, 66); contentPane.add(btnNewButton_1); JButton btnNewButton_2 = new JButton("Insert"); btnNewButton_2.setFont(new Font("Tahoma", Font.BOLD, 20)); btnNewButton_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String temp=""; temp="insert into basvuran values ("; if(textField_0.getText().length()!=0) { temp+="'"+textField_0.getText()+"'"+",";} if(textField_1.getText().length()!=0) { temp+="'"+textField_1.getText()+"'"+",";} if(textField_2.getText().length()!=0) { temp+="'"+textField_2.getText()+"'"+",";} if(textField_3.getText().length()!=0) { temp+="'"+textField_3.getText()+"'"+",";} if(textField_4.getText().length()!=0) { temp+="'"+textField_4.getText()+"'"+",";} if(textField_5.getText().length()!=0) { temp+="'"+textField_5.getText()+"'"+",";} if(textField_6.getText().length()!=0) { temp+="'"+textField_6.getText()+"'"+",";} if(textField_7.getText().length()!=0) { temp+="'"+textField_7.getText()+"'";}/* if(textField_16.getText().length()!=0) { temp+="'"+textField_16.getText()+"'";}*/ temp+=");"; java.sql.Statement s=null; try { s = conn.createStatement(); s.executeQuery(temp); conn.setAutoCommit(false); conn.commit(); s.close(); } catch (SQLException e1) { try { if(s.getWarnings() == null) { JOptionPane optionPane = new JOptionPane("��lem Ba�ar�l�",JOptionPane.INFORMATION_MESSAGE); JDialog dialog = optionPane.createDialog("Bilgilendirme"); dialog.setAlwaysOnTop(true); // to show top of all other application dialog.setVisible(true); // to visible the dialog } else { SQLWarning errorText = s.getWarnings(); String errortxt = errorText.getMessage(); JOptionPane optionPane = new JOptionPane(errortxt,JOptionPane.WARNING_MESSAGE); JDialog dialog = optionPane.createDialog("Uyar�"); dialog.setAlwaysOnTop(true); // to show top of all other application dialog.setVisible(true); // to visible the dialog } } catch (SQLException e2) { // TODO Auto-generated catch block //e2.printStackTrace(); } } } }); btnNewButton_2.setBounds(921, 166, 138, 66); contentPane.add(btnNewButton_2); JButton btnNewButton_3 = new JButton("UPDATE"); btnNewButton_3.setFont(new Font("Tahoma", Font.BOLD, 20)); btnNewButton_3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String query = "UPDATE basvuran SET "; boolean flag = false; if(textField_8.getText().length()!=0) { query += (fields.get(0)+"="+"'"+textField_8.getText()+"'"+","); flag=true; } if(textField_9.getText().length()!=0) { query += (fields.get(1)+"="+"'"+textField_9.getText()+"'"+","); flag=true; } if(textField_10.getText().length()!=0) { query += (fields.get(2)+"="+"'"+textField_10.getText()+"'"+","); flag=true; } if(textField_11.getText().length()!=0) { query += (fields.get(3)+"="+"'"+textField_11.getText()+"'"+","); flag=true; } if(textField_12.getText().length()!=0) { query += (fields.get(4)+"="+"'"+textField_12.getText()+"'"+","); flag=true; } if(textField_13.getText().length()!=0) { query += (fields.get(5)+"="+"'"+textField_13.getText()+"'"+","); flag=true; } if(textField_14.getText().length()!=0) { query += (fields.get(6)+"="+"'"+textField_14.getText()+"'"+","); flag=true; } if(textField_15.getText().length()!=0) { query += (fields.get(7)+"="+"'"+textField_15.getText()+"'"+","); flag=true; }/* if(textField_17.getText().length()!=0) { query += (fields.get(8)+"="+"'"+textField_17.getText()+"'"+","); flag=true; }*/ if(query.charAt(query.length()-1)==',') { query=query.substring(0,query.length()-1); } boolean flag2=false; for(int i=0;i<fetch_index.size();i++) { if(!fetch_index.get(i).equals("NULL")) { flag2=true; break; } } if(flag==false) { return; } else { int count=0; if(flag2==true) query += " WHERE "; for (int i = 0; i < fetch_index.size(); i++) { if(! fetch_index.get(i).equals("NULL")) { if(count!=0) query += " and "; //if(i==7) query += (fields.get(i)+"="+fetch_index.get(i)); query += (fields.get(i)+"="+"'"+fetch_index.get(i)+"'"); count++; } } java.sql.Statement s; try { s = conn.createStatement(); s.executeQuery(query); } catch (SQLException e1) { e1.printStackTrace(); } } } }); btnNewButton_3.setEnabled(false); btnNewButton_3.setBounds(915, 460, 144, 59); contentPane.add(btnNewButton_3); JButton btnNewButton_4 = new JButton("X"); btnNewButton_4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); btnNewButton_4.setBackground(Color.RED); btnNewButton_4.setForeground(Color.WHITE); btnNewButton_4.setBounds(1004, 531, 55, 23); contentPane.add(btnNewButton_4); JButton btnNewButton_5 = new JButton("RESET"); btnNewButton_5.setFont(new Font("Tahoma", Font.BOLD, 20)); btnNewButton_5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(textField_0.getText().length()!=0) { textField_0.setText(null); } if(textField_1.getText().length()!=0) { textField_1.setText(null); } if(textField_2.getText().length()!=0) { textField_2.setText(null); } if(textField_3.getText().length()!=0) { textField_3.setText(null); } if(textField_4.getText().length()!=0) { textField_4.setText(null); } if(textField_5.getText().length()!=0) { textField_5.setText(null); } if(textField_6.getText().length()!=0) { textField_6.setText(null); } if(textField_7.getText().length()!=0) { textField_7.setText(null); } if(textField_16.getText().length()!=0) { textField_16.setText(null); } } }); btnNewButton_5.setBounds(921, 301, 138, 42); contentPane.add(btnNewButton_5); textField_0 = new JTextField(); textField_0.setBounds(40, 58, 70, 20); contentPane.add(textField_0); textField_0.setColumns(10); textField_1 = new JTextField(); textField_1.setBounds(130, 58, 70, 20); contentPane.add(textField_1); textField_1.setColumns(10); textField_2 = new JTextField(); textField_2.setBounds(220, 58, 80, 20); contentPane.add(textField_2); textField_2.setColumns(10); textField_3 = new JTextField(); textField_3.setBounds(310, 58, 70, 20); contentPane.add(textField_3); textField_3.setColumns(10); textField_4 = new JTextField(); textField_4.setBounds(400, 58, 70, 20); contentPane.add(textField_4); textField_4.setColumns(10); textField_5 = new JTextField(); textField_5.setBounds(490, 58, 70, 20); contentPane.add(textField_5); textField_5.setColumns(10); textField_6 = new JTextField(); textField_6.setBounds(580, 58, 70, 20); contentPane.add(textField_6); textField_6.setColumns(10); textField_7 = new JTextField(); textField_7.setBounds(670, 58, 70, 20); contentPane.add(textField_7); textField_7.setColumns(10); textField_16 = new JTextField(); textField_16.setColumns(10); textField_16.setBounds(760, 58, 70, 20); contentPane.add(textField_16); textField_8 = new JTextField(); textField_8.setColumns(10); textField_8.setBounds(40, 480, 70, 20); contentPane.add(textField_8); textField_9 = new JTextField(); textField_9.setColumns(10); textField_9.setBounds(130, 480, 70, 20); contentPane.add(textField_9); textField_10 = new JTextField(); textField_10.setColumns(10); textField_10.setBounds(220, 480, 80, 20); contentPane.add(textField_10); textField_11 = new JTextField(); textField_11.setColumns(10); textField_11.setBounds(310, 480, 70, 20); contentPane.add(textField_11); textField_12 = new JTextField(); textField_12.setColumns(10); textField_12.setBounds(400, 480, 70, 20); contentPane.add(textField_12); textField_13 = new JTextField(); textField_13.setColumns(10); textField_13.setBounds(490, 480, 70, 20); contentPane.add(textField_13); textField_14 = new JTextField(); textField_14.setColumns(10); textField_14.setBounds(580, 480, 70, 20); contentPane.add(textField_14); textField_15 = new JTextField(); textField_15.setColumns(10); textField_15.setBounds(670, 480, 70, 20); contentPane.add(textField_15); textField_17 = new JTextField(); textField_17.setColumns(10); textField_17.setBounds(760, 480, 70, 20); contentPane.add(textField_17); lblNewLabel_1 = new JLabel("ad"); lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_1.setBounds(40, 23, 70, 20); contentPane.add(lblNewLabel_1); lblNewLabel_2 = new JLabel("soyad"); lblNewLabel_2.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_2.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_2.setBounds(129, 23, 70, 20); contentPane.add(lblNewLabel_2); lblNewLabel_3 = new JLabel("tc"); lblNewLabel_3.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_3.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_3.setBounds(220, 23, 70, 20); contentPane.add(lblNewLabel_3); lblNewLabel_4 = new JLabel("dogumt"); lblNewLabel_4.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_4.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_4.setBounds(310, 23, 70, 20); contentPane.add(lblNewLabel_4); lblNewLabel_5 = new JLabel("cinsiyet"); lblNewLabel_5.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_5.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_5.setBounds(400, 23, 70, 20); contentPane.add(lblNewLabel_5); lblNewLabel_6 = new JLabel("kang"); lblNewLabel_6.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_6.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_6.setBounds(490, 23, 70, 20); contentPane.add(lblNewLabel_6); lblNewLabel_7 = new JLabel("tarih"); lblNewLabel_7.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_7.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_7.setBounds(580, 23, 70, 20); contentPane.add(lblNewLabel_7); lblNewLabel_8 = new JLabel("covid"); lblNewLabel_8.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_8.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_8.setBounds(670, 23, 70, 20); contentPane.add(lblNewLabel_8); lblNewLabel_17 = new JLabel("odul"); lblNewLabel_17.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_17.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_17.setBounds(760, 23, 70, 20); contentPane.add(lblNewLabel_17); lblNewLabel_9 = new JLabel("ad"); lblNewLabel_9.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_9.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_9.setBounds(25, 440, 92, 20); contentPane.add(lblNewLabel_9); lblNewLabel_10 = new JLabel("soyad"); lblNewLabel_10.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_10.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_10.setBounds(118, 440, 92, 20); contentPane.add(lblNewLabel_10); lblNewLabel_11 = new JLabel("tc"); lblNewLabel_11.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_11.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_11.setBounds(208, 440, 92, 20); contentPane.add(lblNewLabel_11); lblNewLabel_12 = new JLabel("dogumt"); lblNewLabel_12.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_12.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_12.setBounds(298, 440, 92, 20); contentPane.add(lblNewLabel_12); lblNewLabel_13 = new JLabel("cinsiyet"); lblNewLabel_13.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_13.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_13.setBounds(390, 440, 92, 20); contentPane.add(lblNewLabel_13); lblNewLabel_14 = new JLabel("kang"); lblNewLabel_14.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_14.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_14.setBounds(478, 440, 92, 20); contentPane.add(lblNewLabel_14); lblNewLabel_15 = new JLabel("tarih"); lblNewLabel_15.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_15.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_15.setBounds(568, 440, 92, 20); contentPane.add(lblNewLabel_15); lblNewLabel_16 = new JLabel("covid"); lblNewLabel_16.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_16.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_16.setBounds(658, 440, 92, 20); contentPane.add(lblNewLabel_16); lblNewLabel_18 = new JLabel("odul"); lblNewLabel_18.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel_18.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_18.setBounds(748, 440, 92, 20); contentPane.add(lblNewLabel_18); lblNewLabel_19 = new JLabel("Update i\u015Flemi \u00F6ncesinde"); lblNewLabel_19.setHorizontalAlignment(SwingConstants.LEFT); lblNewLabel_19.setFont(new Font("Tahoma", Font.PLAIN, 12)); lblNewLabel_19.setBounds(895, 349, 159, 24); contentPane.add(lblNewLabel_19); lblNewLabel_20 = new JLabel("g\u00FCncellenmek istenen verilerin"); lblNewLabel_20.setHorizontalAlignment(SwingConstants.LEFT); lblNewLabel_20.setFont(new Font("Tahoma", Font.PLAIN, 12)); lblNewLabel_20.setBounds(895, 372, 172, 35); contentPane.add(lblNewLabel_20); lblNewLabel_21 = new JLabel("Fetch edilmesi gerekir!"); lblNewLabel_21.setHorizontalAlignment(SwingConstants.LEFT); lblNewLabel_21.setFont(new Font("Tahoma", Font.PLAIN, 12)); lblNewLabel_21.setBounds(895, 405, 159, 24); contentPane.add(lblNewLabel_21); chckbxNewCheckBox = new JCheckBox(""); chckbxNewCheckBox.setBackground(Color.LIGHT_GRAY); chckbxNewCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { btnNewButton_3.setEnabled(true); chckbxNewCheckBox.setVisible(false); lblNewLabel_19.setVisible(false); lblNewLabel_20.setVisible(false); lblNewLabel_21.setVisible(false); } }); chckbxNewCheckBox.setBounds(1028, 413, 31, 23); contentPane.add(chckbxNewCheckBox); } }
true
2f71bb8ad1bd8dde5767d5a480afee9d63f61479
Java
mayur2402/java
/Number/StrongX.java
UTF-8
911
3.28125
3
[]
no_license
import java.util.*; import java.lang.*; class Digits { public void checkStrong(int iS,int iE) { int iAns = 0,iFact = 1,iNo ; int fact[] = {1,1,2,6,24,120,120,5040,40320,362880}; if(iS > iE) { return ; } while(iS != iE) { iNo = iS; iAns = 0; while(iNo != 0) { iFact = 1; int iDigit = iNo % 10; iAns = iAns + fact[iDigit]; /* while(iDigit != 0) { iFact = iFact * iDigit; iDigit--; } iAns = iAns + iFact;*/ iNo = iNo / 10; } if(iAns == iS) { System.out.println(iAns); } iS++; } } } class StrongX { public static void main(String[] args) { boolean bret = false; Digits D = new Digits(); Scanner sc = new Scanner(System.in); System.out.println("Enter start of range"); int iStart = sc.nextInt(); System.out.println("Enter end of range"); int iEnd = sc.nextInt(); D.checkStrong(iStart,iEnd); } }
true
578480de0587a465691b74c91da3329d0a3f0900
Java
jackshi0912/academic
/data_structures_and_algorithms/7_BST/src/BSTree.java
UTF-8
17,314
3.71875
4
[]
no_license
/* * NAME: Huize Shi * ID: A92122910 * Date: Feb. 26th, 2016 * LOGIN: cs12wjz */ package hw7; import java.util.LinkedList; /** * The binary search tree * * @author Huize Shi * @version Feb. 26, 2016 */ public class BSTree { // Declaring and initializing appropriate values private BSTNode root; private BSTNode curNode; private int size; private int level; private int depth; private int leafCount; private LinkedList<Person> personList; private int levelCount; /** * Empty argument constructor to initialize all the appropriate values */ public BSTree() { // Initialize all the appropriate values curNode = root; depth = 0; size = 0; leafCount = 0; level = 0; levelCount = 0; } /** * Insert another person into the tree by providing his name and key * * @param name * The new person's name * @param key * The new person's key */ public void insert(String name, int key) { if (name == "" || key < 1 || key > 200) { // Check the parameters throw new IllegalArgumentException(); } if (size == 0) { // Base case 1, if tree is empty, simply make the root root = new BSTNode(null, new Person(name, key), null); curNode = root; size++; return; } // Base case 2, check if the key is greater than the key of the current // person and if it's left child is empty if (curNode.getPerson().getKey() > key && curNode.getLChild() == null) { // Set the current nodes left child to the new Node curNode.setLChild(new BSTNode(null, new Person(name, key), null)); curNode = root; size++; return; } else if (curNode.getPerson().getKey() <= key && curNode.getRChild() == null) { // Check if the the key is // greater than that of the // current person and if it's // right child is empty // Set the right child of the current node to the new Node curNode.setRChild(new BSTNode(null, new Person(name, key), null)); curNode = root; size++; return; } // Check if the key is less than the key of the current Person if (key < curNode.getPerson().getKey()) { // The next stack frame will use the left child curNode = curNode.getLChild(); } else { // The next stack frame will use the right child curNode = curNode.getRChild(); } // Construct another stack frame this.insert(name, key); } /** * Find a person in the tree based on the key and the name * * @param key * The target key to find * @param name * The target name to find * @return Is the person found in the tree */ public boolean findPerson(int key, String name) { // Check if the arguments are legal if (name == "" || key < 1 || key > 200) { throw new IllegalArgumentException(); } if (curNode == null) { // Base case 1, person not found curNode = root; return false; } // Base case 2, person is found if (curNode.getPerson().getKey() == key && curNode.getPerson().getName().equals(name)) { curNode = root; return true; } // Check if the key is less than the current key if (key < curNode.getPerson().getKey()) { // Next stack frame will use the left child as the current node curNode = curNode.getLChild(); } else { // Next stack frame will use the right child as the current node curNode = curNode.getRChild(); } // Build the next stack frame return findPerson(key, name); } /** * Produce an array of person contained in this tree * * @param root * The root of the tree * @return List of person in array form */ public Person[] printToArray(BSTNode root) { if (root == null) { // Check if the tree is empty throw new NullPointerException(); } // Initialize the temporary linked list personList = new LinkedList<>(); this.printToArrayRecursive(root); // Call the recursive method Person[] p = new Person[personList.size()]; // Initialize the array // Copy all the data from the helper linked list to the array for (int i = 0; i < personList.size(); i++) { p[i] = personList.get(i); } return p; } /** * Recursive method that visit every Node of the tree * * @param root * The root of the tree */ private void printToArrayRecursive(BSTNode root) { if (root != null) { // Check if the end of the branch is reached // In order implementation of the tree visiting method this.printToArrayRecursive(root.getLChild()); personList.add(root.getPerson()); this.printToArrayRecursive(root.getRChild()); } } /** * Delete a Node based on the name and the key of the person * * @param key * The key of the person * @param name * The name of the person * @return The person deleted */ public Person delete(int key, String name) { // Check if the inputs are legal if (name == "" || key < 1 || key > 200) { throw new IllegalArgumentException(); } return this.recursiveDelete(root, key); } /** * Delete a node by visiting the tree recursively * * @param root * The current node of the tree * @param key * The target key to delete * @return The person deleted */ private Person recursiveDelete(BSTNode root, int key) { // Check if the root and the left child are present and if the left // child have the matching key if (root != null && root.getLChild() != null && root.getLChild().getPerson().getKey() == key) { // If the key is found, save the information in temp variable Person temp = root.getLChild().getPerson(); // If the left child of the left child is a leaf simply replace it // to null if (root.getLChild().getLChild() == null && root.getLChild().getRChild() == null) { root.setLChild(null); // If the left child has one left child } else if (root.getLChild().getLChild() != null && root.getLChild().getRChild() == null) { // Set the left child to it's left child root.setLChild(root.getLChild().getLChild()); // If the left child has one right child } else if (root.getLChild().getLChild() == null && root.getLChild().getRChild() != null) { // Set the left child to the right child root.setLChild(root.getLChild().getRChild()); } else { // If the left child has two children // If the left child's right child has a child, it's then needed // to find the minimum of the right subtree if (root.getLChild().getRChild().getLChild() != null) { BSTNode right = root.getLChild().getRChild(); BSTNode left = root.getLChild().getLChild(); // Let the deleted Node to the minimum of the right subtree root.setLChild(this .minimumRightSubtree(root.getLChild().getRChild())); // Fixing the tree root.getLChild().setRChild(right); root.getLChild().setLChild(left); } else { // If the left child's right child has no child, simply // set the removed node to the left child's right child BSTNode left = root.getLChild().getLChild(); // Swapping the Node root.setLChild(root.getLChild().getRChild()); // Fixing the tree root.getLChild().setLChild(left); } } size--; return temp; // Check if the root and the right child are present and if the // right child have the matching key } else if (root != null && root.getRChild() != null && root.getRChild().getPerson().getKey() == key) { Person temp = root.getRChild().getPerson(); // If the right child has no children if (root.getRChild().getLChild() == null && root.getRChild().getRChild() == null) { root.setRChild(null); // Set the leaf to null // If the right child has a left child } else if (root.getRChild().getLChild() != null && root.getRChild().getRChild() == null) { // Replace the right child with the left child root.setRChild(root.getRChild().getLChild()); // If the right child has a right child } else if (root.getRChild().getLChild() == null && root.getRChild().getRChild() != null) { // Replace the right child with a right child root.setRChild(root.getRChild().getRChild()); } else { // If the right child has no children // If the right child's right child has a left child, there will // be a need to find minimum right subtree element if (root.getRChild().getRChild().getLChild() != null) { BSTNode right = root.getRChild().getRChild(); BSTNode left = root.getRChild().getLChild(); // Set right child with the minimum element from the right // subtree root.setRChild(this .minimumRightSubtree(root.getRChild().getRChild())); // Fix the tree by adding the missing branches root.getRChild().setRChild(right); root.getRChild().setLChild(left); // If the right child's right child has no left child } else { // Set the deleted Node the right child's right child's left // child BSTNode left = root.getRChild().getLChild(); root.setRChild(root.getRChild().getRChild()); // Fixing the tree by adding the missing branches root.getRChild().setLChild(left); } } size--; return temp; // Return the deleted node } if (root != null) { // Build the next stack frame if root is not null recursiveDelete(root.getLChild(), key); recursiveDelete(root.getRChild(), key); } return null; // Collapse the current stack frame. If at the bottom, // return null to indicate the target node is not found } /** * Helper method to find the minimum right subtree * * @param current * The current node to find the minimum node of the right subtree * @return The minimum value of the right subtree */ private BSTNode minimumRightSubtree(BSTNode current) { // Check if the left child has a left child if (current.getLChild().getLChild() == null) { // If it's null, the end is reached. // store the deleted minimum element BSTNode temp = current.getLChild(); current.setLChild(null); // Remove the min elements return temp; } return minimumRightSubtree(current.getLChild()); } /** * Find the depth of the tree * * @param root * The current node visiting * @return The depth of the tree */ public int findDepth(BSTNode root) { if (root != null) { // Check if the end of the branch is reached level++; if (level > depth) { // Check if a longer branch is found depth = level; } // Recursively call the next level findDepth(root.getLChild()); findDepth(root.getRChild()); level--; // Removing levels as moving back up (collapsing stack // frame) } return depth - 1; // Return the depth - the root level } /** * Count the number of leaves in the tree * * @return The number of leaves in the tree */ public int leafCount() { leafCount = 0; return recursiveLeafCounter(root); } /** * Recursively visit all the nodes of the tree and keep the count of leaves * * @param root * The current node * @return The total leaf count */ private int recursiveLeafCounter(BSTNode root) { if (root != null) { // Check if the end of the branch is leaved // If the current node is a leaf if (root.getLChild() == null && root.getRChild() == null) { leafCount++; } // Build stack frames recursiveLeafCounter(root.getLChild()); recursiveLeafCounter(root.getRChild()); } return leafCount; // Return the leaf count } /** * Count the number of nodes in a certain level * * @param level * the level to count nodes * @return The number of nodes in a certain level */ public int levelCount(int level) { levelCount = 0; this.level = 0; // Check if the level is not within the tree if (level > this.findDepth(root) || level < 0) { return -1; } return recursiveLevelCount(root, level); } /** * Recursive level counter method * * @param root * The current node * @param target * The target level * @return The number of nodes in the level */ public int recursiveLevelCount(BSTNode root, int target) { if (root != null) { // Check if the end of the branch is reached level++; if (level == target + 1) { // Check if the node is in the level levelCount++; } // Build more stack frames with the right or left children recursiveLevelCount(root.getLChild(), target); recursiveLevelCount(root.getRChild(), target); level--; } return levelCount; } /** * Accesor for the root of the tree * * @return The root of the tree */ public BSTNode getRoot() { return root; } /** * Inner class for BSTNode * * @author Huize Shi * @version Feb. 27, 2016 */ protected class BSTNode { private Person p; // data of the person stored in node private BSTNode lChild; // Left child of the current node private BSTNode rChild; // RIght child of the current node /** * The constructor for the node containing data and children * * @param lChild // The left child of the node * @param p // Data to be stored in the node * @param rChild // THe right child of the node */ public BSTNode(BSTNode lChild, Person p, BSTNode rChild) { // Storing all the data in the appropriate instance variables this.p = p; this.lChild = lChild; this.rChild = rChild; } /** * Accesor for the person * * @return the person encapsulated in this node */ public Person getPerson() { return p; } /** * Accesor for the left child * * @return The left child of this node */ public BSTNode getLChild() { return this.lChild; } /** * Accesor for the right child * * @return The right child of this node */ public BSTNode getRChild() { return this.rChild; } /** * Mutator for the left child * * @param newLChild The new child to replace the left child */ public void setLChild(BSTNode newLChild) { this.lChild = newLChild; } /** * Mutator for the right child * * @param newRChild The new child to replace the right child */ public void setRChild(BSTNode newRChild) { this.rChild = newRChild; } } }
true
66e095e204a220270cd672af9361f136ec667bb7
Java
igeekinc/IndelibleFSClient
/src/com/igeekinc/indelible/indeliblefs/IndelibleDirectoryNodeIF.java
UTF-8
5,887
1.78125
2
[]
no_license
/* * Copyright 2002-2014 iGeek, Inc. * All Rights Reserved * @Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.@ */ package com.igeekinc.indelible.indeliblefs; import java.io.IOException; import java.rmi.RemoteException; import java.util.Map; import java.util.concurrent.Future; import com.igeekinc.indelible.indeliblefs.core.IndelibleVersion; import com.igeekinc.indelible.indeliblefs.core.RetrieveVersionFlags; import com.igeekinc.indelible.indeliblefs.exceptions.CannotDeleteDirectoryException; import com.igeekinc.indelible.indeliblefs.exceptions.FileExistsException; import com.igeekinc.indelible.indeliblefs.exceptions.NotDirectoryException; import com.igeekinc.indelible.indeliblefs.exceptions.NotFileException; import com.igeekinc.indelible.indeliblefs.exceptions.ObjectNotFoundException; import com.igeekinc.indelible.indeliblefs.exceptions.PermissionDeniedException; import com.igeekinc.indelible.indeliblefs.uniblock.CASIDDataDescriptor; import com.igeekinc.util.async.AsyncCompletion; public interface IndelibleDirectoryNodeIF extends IndelibleFileNodeIF { /* (non-Javadoc) * @see com.igeekinc.indelible.indeliblefs.core.IndelibleDirectoryNodeRemote#createChildFile(java.lang.String) */ public abstract CreateFileInfo createChildFile(String name, boolean exclusive) throws IOException, PermissionDeniedException, FileExistsException; public abstract CreateFileInfo createChildFile(String name, Map<String, CASIDDataDescriptor> initialForkData, boolean exclusive) throws IOException, PermissionDeniedException, FileExistsException, RemoteException; public abstract Future<CreateFileInfo> createChildFileAsync(String name, Map<String, CASIDDataDescriptor> initialForkData, boolean exclusive) throws IOException, PermissionDeniedException, FileExistsException, RemoteException; public abstract <A>void createChildFileAsync(String name, Map<String, CASIDDataDescriptor> initialForkData, boolean exclusive, AsyncCompletion<CreateFileInfo, ? super A>completionHandler, A attachment) throws IOException, PermissionDeniedException, FileExistsException, RemoteException; /** * This creates a new file with the same data as the original file. Changes to the new file * will not affect the original file * @param name * @param sourceFile * @param exclusive * @return * @throws PermissionDeniedException * @throws FileExistsException * @throws IOException * @throws NotFileException * @throws ObjectNotFoundException */ public abstract CreateFileInfo createChildFile(String name, IndelibleFileNodeIF sourceFile, boolean exclusive) throws PermissionDeniedException, FileExistsException, IOException, NotFileException, ObjectNotFoundException; public abstract CreateSymlinkInfo createChildSymlink(String name, String targetPath, boolean exclusive) throws PermissionDeniedException, FileExistsException, IOException, ObjectNotFoundException; /** * Creates a new link to the specified file. * @param name * @param sourceFile * @param exclusive * @return * @throws PermissionDeniedException * @throws FileExistsException * @throws IOException * @throws NotFileException * @throws ObjectNotFoundException */ public abstract CreateFileInfo createChildLink(String name, IndelibleFileNodeIF sourceFile) throws PermissionDeniedException, FileExistsException, IOException, NotFileException, ObjectNotFoundException; /* (non-Javadoc) * @see com.igeekinc.indelible.indeliblefs.core.IndelibleDirectoryNodeRemote#createChildDirectory(java.lang.String) */ public abstract CreateDirectoryInfo createChildDirectory(String name) throws IOException, PermissionDeniedException, FileExistsException; /* (non-Javadoc) * @see com.igeekinc.indelible.indeliblefs.core.IndelibleDirectoryNodeRemote#deleteChild(java.lang.String) */ public abstract DeleteFileInfo deleteChild(String name) throws IOException, PermissionDeniedException, CannotDeleteDirectoryException; public abstract DeleteFileInfo deleteChildDirectory(String name) throws IOException, PermissionDeniedException, NotDirectoryException; /* (non-Javadoc) * @see com.igeekinc.indelible.indeliblefs.core.IndelibleDirectoryNodeRemote#list() */ public abstract String[] list() throws IOException, PermissionDeniedException; public abstract int getNumChildren() throws IOException, PermissionDeniedException; /* (non-Javadoc) * @see com.igeekinc.indelible.indeliblefs.core.IndelibleDirectoryNodeRemote#getChildNode(java.lang.String) */ public abstract IndelibleFileNodeIF getChildNode(String name) throws IOException, PermissionDeniedException, ObjectNotFoundException; public abstract boolean isDirectory(); public abstract IndelibleNodeInfo[] getChildNodeInfo(String[] mdToRetrieve) throws IOException, PermissionDeniedException, RemoteException; public abstract IndelibleDirectoryNodeIF getVersion(IndelibleVersion version, RetrieveVersionFlags flags) throws IOException; public abstract Future<IndelibleNodeInfo[]> getChildNodeInfoAsync(String[] mdToRetrieve) throws IOException, PermissionDeniedException, RemoteException; public abstract <A> void getChildNodeInfoAsync(String[] mdToRetrieve, AsyncCompletion<IndelibleNodeInfo[], ? super A> completionHandler, A attachment) throws IOException, PermissionDeniedException, RemoteException; }
true
a7ec4618cdb99fc21f7f8fbd183c12ce5bc4f406
Java
htliu/labcenter
/LabCenter/src/com/lifepics/neuron/meta/OrSelector.java
UTF-8
603
2.65625
3
[]
no_license
/* * OrSelector.java */ package com.lifepics.neuron.meta; /** * A selector that combines the logic of other selectors using OR. */ public class OrSelector implements Selector { // --- fields --- private Selector selector1; private Selector selector2; // --- construction --- public OrSelector(Selector selector1, Selector selector2) { this.selector1 = selector1; this.selector2 = selector2; } // --- implementation of Selector --- public boolean select(Object o) { return selector1.select(o) || selector2.select(o); } }
true
c96513a68bf73eb8ded7c91c114ae657561d7096
Java
mik3hall/bjb
/src/org/bjb/CardComponent.java
UTF-8
950
2.71875
3
[]
no_license
package org.bjb; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.ImageIcon; import javax.swing.JComponent; public class CardComponent extends JComponent { ImageIcon cardIcon = null; int ivalue = 0; public CardComponent(ImageIcon ico) { cardIcon = ico; Dimension d = new Dimension(cardIcon.getIconWidth(),cardIcon.getIconHeight()); setSize(d); setMinimumSize(d); setMaximumSize(d); setPreferredSize(d); } public CardComponent(String path) { cardIcon = Card.getIcon(path); Dimension d = new Dimension(cardIcon.getIconWidth(),cardIcon.getIconHeight()); setSize(d); setMinimumSize(d); setMaximumSize(d); setPreferredSize(d); } public void paintComponent(final Graphics g) { super.paintComponent(g); cardIcon.paintIcon(this, g, 0, 0); } public void setImageIcon(ImageIcon cardIcon) { this.cardIcon = cardIcon; } public void setValue(int ivalue) { this.ivalue = ivalue; } }
true
35154f31347be5dc845cd6837d9b087b245eee14
Java
Alienovsky/JMSServer
/src/main/java/com/madebykamil/service/DataProvider.java
UTF-8
3,572
2.84375
3
[]
no_license
package com.madebykamil.service; import com.madebykamil.model.Author; import com.madebykamil.model.Book; import com.madebykamil.model.Catalog; import com.thoughtworks.xstream.XStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.List; public class DataProvider { private Catalog catalog; public DataProvider() { FileReader reader = null; // load file try { reader = new FileReader("C:\\Workspace\\projects\\JMS\\Server\\src\\main\\resources\\initial-data.xml"); } catch (FileNotFoundException e) { e.printStackTrace(); } XStream xstream = new XStream(); xstream.processAnnotations(Catalog.class); // inform XStream to parse annotations in Data class xstream.processAnnotations(Book.class); // and in two other classes... xstream.processAnnotations(Author.class); // we use for mappings this.catalog = (Catalog) xstream.fromXML(reader); // parse } public Book provideBook(String id) { if (id == null || id.isEmpty()) { return null; } for (Book book : catalog.getBooks()) { if (book.getId().equals(id)) { return book; } } return null; } public String addBook(String id, String authorName, String authorSurname, String title, String genre, Float price, String description) { if (id != null && authorName != null && authorSurname != null && title != null && genre != null && price != null && description != null) { if (!id.isEmpty() && !authorName.isEmpty() && !authorSurname.isEmpty() && !title.isEmpty() && !genre.isEmpty() && !description.isEmpty()) { final Book book = new Book(id, new Author(authorName, authorSurname), title, genre, price, description); if(checkIfBookIsAlreadyInCatalog(book.getId())){ return "Such book already exists"; } catalog.getBooks().add(book); return ""; } } return "There was a null value, all fields must have value in Book"; } public String addBook2(String id, String authorName, String authorSurname, String title, String genre, Float price, String description) { try{ if (!id.isEmpty() && !authorName.isEmpty() && !authorSurname.isEmpty() && !title.isEmpty() && !genre.isEmpty() && !description.isEmpty()) { Book book = new Book(id, new Author(authorName, authorSurname), title, genre, price, description); catalog.getBooks().add(book); return ""; } }catch (NullPointerException ex){ return "There was a null value, all fields must have value in Book"; } return "Book has not been added to the collection, there was an issue, please check the logs"; } public String removeBook(String id) { for (Book book : catalog.getBooks()) { if (book.getId().equals(id)) { catalog.getBooks().remove(book); return ""; } } return "Book was not removed, there is no such book with ID: "+id; } public List<Book> provideAllBooks() { return catalog.getBooks(); } public boolean checkIfBookIsAlreadyInCatalog(String id){ for(Book book : catalog.getBooks()){ if(book.getId().equals(id)){ return true; } } return false; } }
true
1396eb87a7aedafec2ba1e9b2e0a0aa7328e2ab1
Java
evernym/indy-sdk
/wrappers/java/src/test/java/org/hyperledger/indy/sdk/non_secrets/DeleteRecordTest.java
UTF-8
1,231
2.015625
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
package org.hyperledger.indy.sdk.non_secrets; import org.hyperledger.indy.sdk.wallet.WalletItemNotFoundException; import org.junit.Test; import java.util.concurrent.ExecutionException; import static org.hamcrest.CoreMatchers.isA; public class DeleteRecordTest extends NonSecretsIntegrationTest { @Test public void testDeleteRecordWorks() throws Exception { WalletRecord.add(wallet, type, id, value, tags).get(); WalletRecord.delete(wallet, type, id).get(); thrown.expect(ExecutionException.class); thrown.expectCause(isA(WalletItemNotFoundException.class)); WalletRecord.get(wallet, type, id, optionsEmpty).get(); } @Test public void testDeleteRecordWorksForTwice() throws Exception { WalletRecord.add(wallet, type, id, value, tags).get(); WalletRecord.delete(wallet, type, id).get(); thrown.expect(ExecutionException.class); thrown.expectCause(isA(WalletItemNotFoundException.class)); WalletRecord.delete(wallet, type, id).get(); } @Test public void testDeleteRecordWorksForNotFoundRecord() throws Exception { thrown.expect(ExecutionException.class); thrown.expectCause(isA(WalletItemNotFoundException.class)); WalletRecord.deleteTags(wallet, type, id, "[\"tagName1\"]").get(); } }
true
f00210630ded44e8c3210df1ea593c5ce2e29d23
Java
hyuni917/programmers
/src/datastructure/Tower.java
UTF-8
1,105
3.6875
4
[]
no_license
package datastructure; import java.util.Stack; public class Tower { public static void main(String[] args){ int numbers[] = {6,9,5,7,4}; Tower t= new Tower(); t.solution(numbers); } public int[] solution(int[] heights) { int heightsSize = heights.length; int[] answer = new int[heightsSize]; Stack<Integer> stack = new Stack<>(); for(int height : heights){ stack.push(height); } //System.out.println("heightsSize="+heightsSize); int cnt = 1; do{ int sender = stack.pop(); //System.out.println("sender="+sender); for(int i=heightsSize-cnt; i>=0; i--){ if(heights[i]>sender){ //System.out.println("i="+i); //System.out.println(heights[i]); answer[heightsSize-cnt] = i+1; break; } } cnt++; //System.out.println("stack.size()="+stack.size()); }while(!stack.empty()); return answer; } }
true
8485678ad80351f0e65a02ac611550c419e6a264
Java
stg-tud/tigerseye
/languages/src/test/groovy/de/tud/stg/tigerseye/tests/logo/TurtleMetaClass.java
UTF-8
5,183
2.421875
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
/////////////////////////////////////////////////////////////////////////////// // Copyright 2009-2015, Technische Universitaet Darmstadt (TUD), Germany // // The TUD licenses this file to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /////////////////////////////////////////////////////////////////////////////// package de.tud.stg.tigerseye.tests.logo; import groovy.lang.ExpandoMetaClass; import java.awt.Color; import java.util.Iterator; import java.util.List; import org.javalogo.Turtle; import de.tud.stg.tigerseye.lang.logo.ConcurrentLogo; public class TurtleMetaClass extends ExpandoMetaClass { protected ConcurrentLogo interpreter; public TurtleMetaClass(Class theClass, ConcurrentLogo interpreter) { super(theClass); this.interpreter= interpreter; } public Object invokeMethod(Class sender, Object object, String methodName, Object[] originalArguments, boolean isCallToSuper, boolean fromInsideClass) { Turtle turtle = (Turtle)object; if ((methodName.equals("forward") || (methodName.equals("backward"))) && !turtle.getName().equals("collusion")) { //System.out.println("MC.invokeMethod("+methodName+")="); if (isTurtleFacingACollusion(turtle)) { System.out.println(">>turtle with collusion = "+turtle.getPosition().getX()+"/"+turtle.getPosition().getY()+":"+turtle.getHeading()); Turtle collusionPainter = new Turtle("collusion",Color.MAGENTA); interpreter.getCanvas().add(collusionPainter); synchronized (interpreter.getCanvas()) { //goto collusion position collusionPainter.penUp(); collusionPainter.forward(turtle.getPosition().getY()); collusionPainter.right(90.0); collusionPainter.forward(turtle.getPosition().getX()); collusionPainter.penDown(); //paint cross collusionPainter.setPenWidth(3); collusionPainter.right(45.0); collusionPainter.forward(10); collusionPainter.backward(20); collusionPainter.forward(10); collusionPainter.right(90.0); collusionPainter.forward(10); collusionPainter.backward(20); collusionPainter.hide(); } } } Object result = super.invokeMethod(sender, object, methodName, originalArguments, isCallToSuper, fromInsideClass); return result; } public boolean isTurtleFacingACollusion(Turtle turtle) { boolean result = false; if ((turtle.getPosition().getX() == 0) && (turtle.getPosition().getX() == 0)) return false; //do no prevent collusion at home position if (turtle.getName().equals("collusion")) return false; List<Turtle> turtles = interpreter.getTurtles(); Iterator<Turtle> it = turtles.iterator(); System.out.println("DETECTING: sense all other turtles before moving"); while (it.hasNext()) { Turtle other = it.next(); if (turtle == other) continue; //a turtle has no collusion with itself System.out.println("DETECTING: 1"); if (other.getName().equals("collusion")) continue; //no collusion with the turtles that paint the cross at a collusion point System.out.println("DETECTING: 2"); if (!turtle.isPenDown() || !other.isPenDown()) continue; //if one of the turtles has the pen up, it is no collusion System.out.println("DETECTING: 3"); double distanceX = turtle.getPosition().getX() - other.getPosition().getX(); double distanceY = turtle.getPosition().getY() - other.getPosition().getY(); double penWith = Math.max(turtle.getPenWidth(), other.getPenWidth()); double distanceXY = Math.sqrt( distanceX * distanceX + distanceY * distanceY); System.out.println("DETECTING: 4"); if ((distanceXY < penWith)) { System.out.println("DETECTING: collusion between turtle="+turtle.getName()+ " other="+other.getName()+ " distance="+distanceXY+ " thread="+interpreter.getThread(other).getId()); return true; } else { /*System.out.println("DETECTING: no collusion because of save distance turtle="+turtle.getName()+ " other="+other.getName()+ " distance="+distanceXY+ " thread="+interpreter.getThread(other).getId());*/ } } return result; } }
true
dbb7cd6cc5001bc129218c86e1d80e9047254533
Java
rlong/java.jsonbroker.library
/src/jsonbroker/library/common/log/ReleaseLogDelegate.java
UTF-8
1,527
2.046875
2
[ "MIT" ]
permissive
// Copyright (c) 2013 Richard Long & HexBeerium // // Released under the MIT license ( http://opensource.org/licenses/MIT ) // package jsonbroker.library.common.log; public class ReleaseLogDelegate implements LogDelegate { LogDelegate _delegate; public ReleaseLogDelegate( LogDelegate delegate ) { _delegate = delegate; } @Override public boolean isDebugEnabled() { return false; } @Override public void debug(Log origin, String message) { } @Override public void debug(Log origin, boolean value, String name) { } @Override public void debug(Log origin, int value, String name) { } @Override public void debug(Log origin, Loggable value, String name) { } @Override public void debug(Log origin, long value, String name) { } @Override public void debug(Log origin, Object value, String name) { } @Override public void debug(Log origin, String value, String name) { } @Override public void debugFormat(Log origin, String format, Object... args) { } @Override public void debugIp4Address(Log origin, int value, String name) { } @Override public void enteredMethod(Log origin) { } @Override public void info(Log origin, String message) { _delegate.info( origin, message); } @Override public void warn(Log origin, String message) { _delegate.warn( origin, message); } @Override public void error(Log origin, String message) { _delegate.error( origin, message); } }
true
c1f5ff38fdac328602d7af194ce1a57848718731
Java
SFIDevelopment/osmv
/Parkoid/src/at/the/gogo/parkoid/fragments/OverviewFragment.java
UTF-8
8,531
2.015625
2
[]
no_license
package at.the.gogo.parkoid.fragments; import java.util.Iterator; import java.util.Map; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import at.the.gogo.parkoid.R; import at.the.gogo.parkoid.models.ViennaKurzParkZone; import at.the.gogo.parkoid.util.CoreInfoHolder; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; public class OverviewFragment extends LocationListenerFragment { private TextView kpzHeaderTitle; // private AddressListFragment adressFragment; private ListView addressList; public static OverviewFragment newInstance() { final OverviewFragment f = new OverviewFragment(); return f; } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.overview, null); initializeGUI(view); kpzHeaderTitle = (TextView) view.findViewById(R.id.kpz_list_header); addressList = (ListView) view.findViewById(R.id.kpz_list); // adressFragment = (AddressListFragment) getFragmentManager() // .findFragmentById(R.id.kpz_list); return view; } // @Override // protected void updateLocation() { // // // super.updateLocation(); // } // @Override public void zoneLevelUpdate(final Boolean inZone) { if (isDetached()) { return; } super.zoneLevelUpdate(inZone); if (inZone != null) { // fill list (again) refreshList(true); setkpzTitle(getText( (inZone) ? R.string.near_kpz : R.string.no_near_kpz) .toString()); Toast.makeText(CoreInfoHolder.getInstance().getContext(), (inZone) ? R.string.near_kpz : R.string.no_near_kpz, Toast.LENGTH_SHORT).show(); } else { setkpzTitle(getText(R.string.unknown_near_kpz).toString()); Toast.makeText(CoreInfoHolder.getInstance().getContext(), R.string.unknown_near_kpz, Toast.LENGTH_SHORT).show(); } } private void setkpzTitle(final String title) { final String newTitle = title + " (+/-" + CoreInfoHolder.getInstance().getAccuracyUsed() + "m)"; kpzHeaderTitle.setText(newTitle); } public void refreshList(final boolean forceRefresh) { // refresh = forceRefresh; fillData(); } public void fillData() { final GetAddressData asyncTask = new GetAddressData(); asyncTask.execute((Void) null); } public static class ViewHolder { TextView textView1; TextView textView2; TextView textView3; ImageView icon1; ImageView icon2; } public class GetAddressData extends AsyncTask<Void, Void, Map<String, ViennaKurzParkZone>> { @Override protected Map<String, ViennaKurzParkZone> doInBackground( final Void... params) { return CoreInfoHolder.getInstance().getVKPZCurrentList(); } @Override protected void onPostExecute( final Map<String, ViennaKurzParkZone> entries) { final ListAdapter adapter = new BaseAdapter() { private LayoutInflater inflater = null; @Override public int getCount() { return (entries != null) ? entries.size() : 0; } @Override public long getItemId(final int position) { return position; } private ViennaKurzParkZone getElementAt(final int ix) { ViennaKurzParkZone result = null; final Iterator<String> iterator = entries.keySet() .iterator(); int i = 0; while ((i <= ix) && (iterator.hasNext())) { final String key = iterator.next(); if (i == ix) { result = entries.get(key); } i++; } return result; } @Override public View getView(final int position, View convertView, final ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { if (inflater == null) { inflater = LayoutInflater.from(getActivity()); } convertView = inflater.inflate(R.layout.address_item, null); holder = new ViewHolder(); holder.textView1 = (TextView) convertView .findViewById(R.id.AddressLine1); holder.textView2 = (TextView) convertView .findViewById(R.id.AddressLine2); holder.textView3 = (TextView) convertView .findViewById(R.id.AddressLine3); holder.icon1 = (ImageView) convertView .findViewById(R.id.imageView1); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final ViennaKurzParkZone vkpz = getElementAt(position); String caption = ""; if (vkpz.getProperties().containsKey("strasse")) { caption = (String) vkpz.getProperties().get("strasse"); if (vkpz.getProperties().containsKey("geltungsbereich")) { caption += " " + vkpz.getProperties().get( "geltungsbereich"); } } else if (vkpz.getProperties().containsKey("bezirk")) { caption = vkpz.getProperties().get("bezirk") + ". Bezirk "; } else { caption = (String) vkpz.getProperties().get("type"); } holder.textView1.setText(caption); holder.textView2.setText("max Dauer: " + vkpz.getProperties().get("dauer")); holder.textView3.setText("Zeitraum: " + vkpz.getProperties().get("zeitraum")); return convertView; } @Override public Object getItem(final int position) { return entries.get(position); } }; addressList.setAdapter(adapter); } } private void pause() { // NOOP for now } private void resume() { // NOOP for now } @Override public void pageGetsActivated() { super.pageGetsActivated(); resume(); } @Override public void pageGetsDeactivated() { super.pageGetsDeactivated(); pause(); } @Override public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { inflater.inflate(R.menu.overview_option_menu, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(final MenuItem item) { final boolean result = false; return result; } }
true
d4e0664635d02a997c60aab122db99796ed3bf9a
Java
barneymaydance/leetcode_solutions
/undone/MajorityElement.java
UTF-8
497
3.109375
3
[]
no_license
//O(n) time //O(1) space //the Boyer-moore Majority vote algorithm public class Solution { public int majorityElement(int[] num) { int res=num[0]; int count=0; for(int i=0;i<num.length;i++){ if(count==0){ res=num[i]; } if(num[i]==res){ count++; } else{ count--; } } return res; } } //sort (n(logn)), then get n[length/2] element
true
a77a74e0ed6c75d820890b257fe22a8a9e5d6358
Java
TTcheng/choerodon-starters
/choerodon-starter-asgard/src/main/java/io/choerodon/asgard/property/PropertyEndpoint.java
UTF-8
585
2.03125
2
[ "Apache-2.0" ]
permissive
package io.choerodon.asgard.property; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; @RestController public class PropertyEndpoint { private PropertyData propertyData; public PropertyEndpoint(PropertyData propertyData) { this.propertyData = propertyData; } @GetMapping(value = "/choerodon/asgard", produces = {APPLICATION_JSON_VALUE}) PropertyData propertyData() { return propertyData; } }
true