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
f4f2aa206213aa481c5e894834de6e786a33228c
Java
RavenLeaks/Aegis-src-cfr
/com/google/common/collect/RegularImmutableSortedMultiset.java
UTF-8
4,981
2.21875
2
[]
no_license
/* * Decompiled with CFR <Could not determine version>. * * Could not load the following classes: * javax.annotation.Nullable */ package com.google.common.collect; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Preconditions; import com.google.common.collect.BoundType; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedMultiset; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Multiset; import com.google.common.collect.Multisets; import com.google.common.collect.Ordering; import com.google.common.collect.RegularImmutableSortedSet; import com.google.common.collect.SortedMultiset; import com.google.common.primitives.Ints; import java.util.Comparator; import java.util.NavigableSet; import java.util.Set; import java.util.SortedSet; import javax.annotation.Nullable; @GwtIncompatible final class RegularImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> { private static final long[] ZERO_CUMULATIVE_COUNTS = new long[]{0L}; static final ImmutableSortedMultiset<Comparable> NATURAL_EMPTY_MULTISET = new RegularImmutableSortedMultiset<C>(Ordering.<C>natural()); private final transient RegularImmutableSortedSet<E> elementSet; private final transient long[] cumulativeCounts; private final transient int offset; private final transient int length; RegularImmutableSortedMultiset(Comparator<? super E> comparator) { this.elementSet = ImmutableSortedSet.emptySet(comparator); this.cumulativeCounts = ZERO_CUMULATIVE_COUNTS; this.offset = 0; this.length = 0; } RegularImmutableSortedMultiset(RegularImmutableSortedSet<E> elementSet, long[] cumulativeCounts, int offset, int length) { this.elementSet = elementSet; this.cumulativeCounts = cumulativeCounts; this.offset = offset; this.length = length; } private int getCount(int index) { return (int)(this.cumulativeCounts[this.offset + index + 1] - this.cumulativeCounts[this.offset + index]); } @Override Multiset.Entry<E> getEntry(int index) { return Multisets.immutableEntry(this.elementSet.asList().get((int)index), (int)this.getCount((int)index)); } @Override public Multiset.Entry<E> firstEntry() { if (this.isEmpty()) { return null; } Multiset.Entry<E> entry = this.getEntry((int)0); return entry; } @Override public Multiset.Entry<E> lastEntry() { if (this.isEmpty()) { return null; } Multiset.Entry<E> entry = this.getEntry((int)(this.length - 1)); return entry; } @Override public int count(@Nullable Object element) { int index = this.elementSet.indexOf((Object)element); if (index < 0) return 0; int n = this.getCount((int)index); return n; } @Override public int size() { long size = this.cumulativeCounts[this.offset + this.length] - this.cumulativeCounts[this.offset]; return Ints.saturatedCast((long)size); } @Override public ImmutableSortedSet<E> elementSet() { return this.elementSet; } @Override public ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { boolean bl; if (Preconditions.checkNotNull(boundType) == BoundType.CLOSED) { bl = true; return this.getSubMultiset((int)0, (int)this.elementSet.headIndex(upperBound, (boolean)bl)); } bl = false; return this.getSubMultiset((int)0, (int)this.elementSet.headIndex(upperBound, (boolean)bl)); } @Override public ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { boolean bl; if (Preconditions.checkNotNull(boundType) == BoundType.CLOSED) { bl = true; return this.getSubMultiset((int)this.elementSet.tailIndex(lowerBound, (boolean)bl), (int)this.length); } bl = false; return this.getSubMultiset((int)this.elementSet.tailIndex(lowerBound, (boolean)bl), (int)this.length); } ImmutableSortedMultiset<E> getSubMultiset(int from, int to) { Preconditions.checkPositionIndexes((int)from, (int)to, (int)this.length); if (from == to) { return RegularImmutableSortedMultiset.emptyMultiset(this.comparator()); } if (from == 0 && to == this.length) { return this; } RegularImmutableSortedSet<E> subElementSet = this.elementSet.getSubSet((int)from, (int)to); return new RegularImmutableSortedMultiset<E>(subElementSet, (long[])this.cumulativeCounts, (int)(this.offset + from), (int)(to - from)); } @Override boolean isPartialView() { if (this.offset > 0) return true; if (this.length < this.cumulativeCounts.length - 1) return true; return false; } }
true
117768bf24dd80ae760afe576d13bb6ea00bac94
Java
tjxn/StrategyPatternUseCase
/StrategyPatternUseCase/src/TitleSort.java
UTF-8
1,717
4.125
4
[]
no_license
import java.util.ArrayList; import java.util.List; /** Sorts all Books in a BookShelf alphabetically using Insertion Sort */ public class TitleSort implements SortingStrategy { public TitleSort(){}; /** * @param currentShelf - a List of Books * * Sorts the given list of books into alphabetical order by book title. * Uses Insertion Sort. * * @return a sorted list of books * */ public List<Book> sort(List<Book> currentShelf) { List<Book> newShelf = new ArrayList<Book>(); for(Book currBook : currentShelf){ if(newShelf.size() == 0){ newShelf.add(currBook); continue; } for(int i = 0; i <= newShelf.size(); i++){ if(i == newShelf.size()){ newShelf.add(currBook); break; } if(alphaOrder(currBook.getTitle(), newShelf.get(i).getTitle())){ newShelf.add(i, currBook); break; } } } return newShelf; } /** * @param firstString - A string from the first book * @param secondString - A string from the second book * * method is used to compare two strings and determine which one comes first alphabetically. * * @return boolean - False if the second string comes after the first string or if the strings are equal, * True if the second string goes before the first string * */ private boolean alphaOrder(String firstString, String secondString){ for(int i = 0; i < firstString.length(); i++){ char character = firstString.charAt(i); if(character < secondString.charAt(i)){ return true; }else if(character > secondString.charAt(i)){ return false; } } return false; } }
true
581402a2d33caf70377a09d413c7f053bec39bbe
Java
sinhdev/java-demo
/JavaNetworkProgramming/UDP/UDPServer.java
UTF-8
1,052
3.21875
3
[ "MIT" ]
permissive
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.io.IOException; public class UDPServer { public static void main(String[] args) { try { DatagramSocket socket = new DatagramSocket(3000); byte[] buffer = new byte[512]; DatagramPacket request = new DatagramPacket(buffer, buffer.length); socket.receive(request); String receiveText = new String(request.getData(),0,request.getLength()); System.out.println("receive Data " + receiveText + " from " + request.getAddress()); String sendText = "Hello " + receiveText; buffer = sendText.getBytes(); System.out.println(buffer.length); DatagramPacket response = new DatagramPacket(buffer, buffer.length,request.getAddress(),request.getPort()); socket.send(response); socket.close(); } catch (IOException ex) { System.out.println("I/O Error :" + ex.getMessage()); } } }
true
be9a25f20a1b9135ae5e715fdd833e4ff4da1ca6
Java
fjh658/bindiff
/src_procyon/y/d/b/y.java
UTF-8
1,381
2.5
2
[]
no_license
package y.d.b; import y.g.*; public class y implements z { private static y a; private static y b; private double c; public y(final double c) { this.c = c; } public z a() { return y.a; } public z b() { return y.b; } public z a(final z z) { return new y(this.c + ((y)z).e()); } public z b(final z z) { return new y(this.c - ((y)z).e()); } public z c(final z z) { return new y(this.c * ((y)z).e()); } public z d(final z z) { return new y(this.c / ((y)z).e()); } public z d() { return new y(-this.c); } public z e(final z z) { return y.b; } public int c() { if (this.c < 0.0) { return -1; } if (this.c > 0.0) { return 1; } return 0; } public int f(final z z) { if (z == this) { return 0; } return e.a(this.c, ((y)z).e()); } public boolean equals(final Object o) { return o == this || (o instanceof y && this.c == ((y)o).e()); } public double e() { return this.c; } public String toString() { return "" + this.c; } static { y.a = new y(0.0); y.b = new y(1.0); } }
true
697d5b0c8fa8d862b956ce10cd1a146b881eab19
Java
chriscoyle101/SpringMVC
/WebApplication/src/com/nextgate/chriscoyle/service/ArtistInformation.java
UTF-8
1,189
2.34375
2
[ "Apache-2.0" ]
permissive
package com.nextgate.chriscoyle.service; public class ArtistInformation { private String singerName; private String dob; private String sex; private String album; private String releaseYear; private String company; // -------------------------- // // GETTER METHODS // -------------------------- // public String getSingerName(){ return this.singerName; } public String getDob(){ return this.dob; } public String getSex(){ return this.sex; } public String getAlbum(){ return this.album; } public String getReleaseYear(){ return this.releaseYear; } public String getCompany(){ return this.company; } // -------------------------- // // SETTER METHODS // -------------------------- // public void setSingerName(String singerName){ this.singerName = singerName; } public void setDob(String dateOfBirth){ this.dob = dateOfBirth; } public void setSex(String sex){ this.sex = sex; } public void setAlbum(String album){ this.album = album; } public void setReleaseYear(String releaseYear){ this.releaseYear = releaseYear; } public void setCompany(String recordCompany){ this.company = recordCompany; } }
true
d43793222f784668c2ba66b602d4f40a9e167288
Java
prettyhe/alpha-coding4j
/coding-bo/src/main/java/com/alpha/coding/bo/annotation/HttpParam.java
UTF-8
716
1.859375
2
[ "Apache-2.0" ]
permissive
package com.alpha.coding.bo.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.web.bind.annotation.Mapping; /** * HttpParam * * @version 1.0 * Date: 2019-12-27 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) @Documented @Mapping public @interface HttpParam { /** * 参数名 */ String[] name() default {}; /** * 是否必须 */ boolean required() default true; /** * 日期类格式候选 */ String[] dateFormatCandidate() default {}; }
true
6c2dc8e06f91bd9ff6d1394a91879845d9869d98
Java
teodora12/mbrsMaster
/mbrs-test/src/main/java/uns/ftn/mbrs/controller/ItemController.java
UTF-8
2,328
2.15625
2
[]
no_license
package uns.ftn.mbrs.controller; import java.util.*; import uns.ftn.mbrs.model.*; import uns.ftn.mbrs.service.ItemService; import uns.ftn.mbrs.service.ReportService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import uns.ftn.mbrs.model.*; import java.util.Optional; import org.springframework.ui.Model; import org.springframework.stereotype.Controller; import org.springframework.beans.factory.annotation.Autowired; @Controller public class ItemController { @Autowired private ItemService itemService; @Autowired private ReportService reportService; @GetMapping(value = "allItems") public String getAllItem(Model model) { List<Item> allItems = this.itemService.getAll(); model.addAttribute("items", allItems); return "ItemList"; } @GetMapping(value = "item/new") public String newItem(Model model) { model.addAttribute("item", new Item()); List<Report> reports = reportService.getAll(); model.addAttribute("reports", reports); return "ItemForm"; } @GetMapping(value = "item/edit") public String editItem(@RequestParam("id") String id, Model model) { Item item = itemService.getOne(Long.parseLong(id)).orElse(null); model.addAttribute("item", item); List<Report> reports = reportService.getAll(); model.addAttribute("reports", reports); return "ItemForm"; } @GetMapping(value = "item/{id}") public String showItemDetails (@PathVariable("id") Long id, Model model) { model.addAttribute("item", itemService.getOne(id).orElse(null)); return "ItemDetails"; } @GetMapping("item/delete") public String deleteItem(@RequestParam("id") String id, Model model) { itemService.delete(Long.parseLong(id)); List<Item> allItems = this.itemService.getAll(); model.addAttribute("items", allItems); return "ItemList"; } @PostMapping(value = "addItem") public String addItem(@ModelAttribute Item item, Model model) { itemService.add(item); List<Item> allItems = this.itemService.getAll(); model.addAttribute("items", allItems); return "ItemList"; } }
true
5bc2f848ede5a64363f174efd88cce59f6c2deb4
Java
AkhilaKomanduri/Selenium-2017-18
/Selenium _Learning _Project/src/WebDriver_Learning/FileDownload.java
UTF-8
512
1.898438
2
[]
no_license
package WebDriver_Learning; import org.openqa.selenium.chrome.ChromeDriver; public class FileDownload { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/Users/RaviAkhi/Desktop/Selenium Dump/chromedriver"); ChromeDriver Prof = new ChromeDriverProfile(); driver.setPreference("browser.download.dir","/Users/RaviAkhi/Desktop"); Prof.setPreference("",""); ChromeDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get(""); } }
true
1311447864a632fa4cfab0892b6e18f1526b6d28
Java
yhznd/OtoTakip
/app/src/main/java/com/example/yunus/ototakip/Araba.java
UTF-8
2,575
1.929688
2
[]
no_license
package com.example.yunus.ototakip; /** * Created by Eren Özhan on 9.4.2017. */ public class Araba { private String userId; private String userMail; private String editTextPlaka; private String editTextModel; private String editTextKaskoTarihi; private String editTextMuayeneTarihi; private String editTextSigortaTarihi; private String editTextEmisyonTarihi; public Araba(String userMail,String editTextModel,String editTextKaskoTarihi, String editTextMuayeneTarihi, String editTextSigortaTarihi,String editTextEmisyonTarihi ) { this.userId=userId; this.userMail=userMail; this.editTextPlaka = editTextPlaka; this.editTextModel = editTextModel; this.editTextKaskoTarihi = editTextKaskoTarihi; this.editTextMuayeneTarihi = editTextMuayeneTarihi; this.editTextSigortaTarihi = editTextSigortaTarihi; this.editTextEmisyonTarihi = editTextEmisyonTarihi; } public Araba() { } public String getEditTextPlaka() { return editTextPlaka; } public void setEditTextPlaka(String editTextPlaka) { this.editTextPlaka = editTextPlaka; } public String getEditTextModel() { return editTextModel; } public void setEditTextModel(String editTextModel) { this.editTextModel = editTextModel; } public String getEditTextKaskoTarihi() { return editTextKaskoTarihi; } public void setEditTextKaskoTarihi(String editTextKaskoTarihi) { this.editTextKaskoTarihi = editTextKaskoTarihi; } public String getEditTextMuayeneTarihi() { return editTextMuayeneTarihi; } public void setEditTextMuayeneTarihi(String editTextMuayeneTarihi) { this.editTextMuayeneTarihi = editTextMuayeneTarihi; } public String getEditTextSigortaTarihi() { return editTextSigortaTarihi; } public void setEditTextSigortaTarihi(String editTextSigortaTarihi) { this.editTextSigortaTarihi = editTextSigortaTarihi; } public String getEditTextEmisyonTarihi() { return editTextEmisyonTarihi; } public void setEditTextEmisyonTarihi(String editTextEmisyonTarihi) { this.editTextEmisyonTarihi = editTextEmisyonTarihi; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserMail() { return userMail; } public void setUserMail(String userMail) { this.userMail = userMail; } }
true
ee835c4b7513b8191a39e25488aa4fc482779fa3
Java
SatishTA/SeleniumSessions
/src/SeleniumSessions/locatorsConcept.java
UTF-8
1,062
2.109375
2
[]
no_license
package src.SeleniumSessions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class locatorsConcept { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","D:\\Office BackUP\\Documents\\Selenium_Session\\chromedriver.exe"); WebDriver driverc=new ChromeDriver(); driverc.get("https://smartrip.wmata.com"); driverc.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); System.out.println(driverc.getTitle()); //Thread.sleep(2000); //driverc.quit(); driverc.findElement(By.xpath("//input[@title='Enter your user name']")).sendKeys("satish_l"); driverc.findElement(By.xpath("//input[@alt=\"Password\"]")).sendKeys("Satya08@u"); driverc.findElement(By.xpath("//input[@title='Login']")).click(); driverc.findElement(By.xpath("//a[@class='LogoutLink']")).click(); System.out.println("Log out sucessfull"); } }
true
34d07c58f48df6b13081ed7c1080dda76b2ac36d
Java
ezcoding4all/coding_solutions
/week_2/linked_lists/ListCycle.java
UTF-8
1,092
4
4
[]
no_license
/** * List Cycle * * Given a linked list, return the node where the cycle begins. If there is no cycle, return null. * * 1 -> 2 -> 3 -> 4 ---> 3 * return node of value 3 * * [interviewbit] * https://www.interviewbit.com/problems/list-cycle/ */ public class ListCycle { public static void main(String[] args){ ListCycle lc = new ListCycle(); ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(3); ListNode node4 = new ListNode(4); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = null; ListNode result = lc.detectCycle(node1); System.out.println(""+result.val); } public ListNode detectCycle(ListNode a) { ListNode p1=a, p2=a, head=a; while (p2.next != null){ if(p2.next.next == null){ break; } p1 = p1.next; p2 = p2.next.next; if(p1.equals(p2)){ while (!p1.equals(head)){ p1 = p1.next; head = head.next; } return head; } } return null; } }
true
54a312fb6d948773c6457ab06e04cbf8dc87c373
Java
XlsBo/MyMusicPlayerAgain
/src/music/adapter/SongListAdapter.java
GB18030
2,044
2.796875
3
[ "Apache-2.0" ]
permissive
package music.adapter; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import music.activity.R; import music.util.GetMedia; import music.util.ListContent; public class SongListAdapter extends ArrayAdapter<ListContent>{ int resourceId;//бIJ public SongListAdapter(Context context, int textViewResourceId, List<ListContent> objects) { super(context,textViewResourceId,objects); resourceId = textViewResourceId; } @Override public View getView(int position, View convertView, ViewGroup parent) { ListContent listContent = getItem(position); View view; ViewHolder viewHolder = new ViewHolder(); //Ըбֽл if(convertView == null) { view = LayoutInflater.from(getContext()).inflate(resourceId, null); viewHolder.songImage = (ImageView) view.findViewById(R.id.song_image); viewHolder.songName = (TextView) view.findViewById(R.id.song_name); viewHolder.songDuration = (TextView) view.findViewById(R.id.song_duration); viewHolder.songArtist = (TextView) view .findViewById(R.id.song_artist); //public void setTag (Object tag)ͼıǡ view.setTag(viewHolder); }else { view = convertView; //public Object getTag ()ظͼıǡ //ͼд洢ĶΪǣδΪnull viewHolder = (ViewHolder) view.getTag(); } viewHolder.songImage.setImageResource(listContent.getImageId()); viewHolder.songName.setText(listContent.getSong()); viewHolder.songDuration.setText(GetMedia.formatTime(listContent.getDuration())); viewHolder.songArtist.setText(listContent.getSongArtist()); return view; } } //ڲ࣬ԸбڵĿؼл class ViewHolder{ ImageView songImage; TextView songName; TextView songDuration; TextView songArtist; }
true
725bcf4f6cd59b649cd79bf72d189489a560bb7e
Java
maicolstevenchunza/AKUAVIDA
/Codigo/AkuavidaJPA/src/main/java/edu/co/sena/akuavida/modelo/jpa/dao/interfaces/ICarritosComprasDAO.java
UTF-8
808
2.015625
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 edu.co.sena.akuavida.modelo.jpa.dao.interfaces; import edu.co.sena.akuavida.modelo.entitis.CarritoDeCompras; import java.util.List; /** * * @author ColsutecR */ public interface ICarritosComprasDAO { public void insert(CarritoDeCompras entity); public void update(CarritoDeCompras entity); public void delete(CarritoDeCompras entity); public CarritoDeCompras findByIDCarrito(String idCarrito); public List<CarritoDeCompras> findByAll(); public List<CarritoDeCompras> findByTotal(Double total); public List<CarritoDeCompras> findBySubtotal(Double subtotal); }
true
de432e4eb82718e6ae7d1c1676aa40609c182163
Java
romaric-roussel/Cours
/java/src/test/fr/lp/iem/tdd/TestEtudiant.java
UTF-8
1,249
3.078125
3
[]
no_license
package fr.lp.iem.tdd; import java.util.*; public class TestEtudiant { public static void main(String[] args) { //testTriList(); List<String> chaine = Arrays.asList("toto","titi","TUTU","aBc","abc"); Collections.sort(chaine, String.CASE_INSENSITIVE_ORDER); System.out.println(chaine); } private static void testTriList() { List<Etudiant> maListe = new ArrayList<>(); Etudiant johnDoe = new Etudiant("john","Doe"); maListe.add(johnDoe); maListe.add(new Etudiant("test","bidon")); Etudiant romGAG = new Etudiant("rom","GAG"); maListe.add(romGAG); maListe.add(new Etudiant("rom","gagag")); maListe.add(new Etudiant("trou","pouri")); //Collections.sort(maListe); System.out.println(maListe); Collections.sort(maListe, new Comparator<Etudiant>() { @Override public int compare(Etudiant o1, Etudiant o2) { int res= o1.getFirsttName().compareTo(o2.getFirsttName()); if(res==0){ res = o1.getName().compareTo(o2.getName()); } return res; } }); System.out.println(maListe); } }
true
7d85e0cdd5776272f4aaa1342f6b32699cc2e4f3
Java
nghuy1610/VDCAssignment
/VDCProduct/src/main/java/com/vdc/product/exception/ProductException.java
UTF-8
624
2.4375
2
[]
no_license
package com.vdc.product.exception; import lombok.AllArgsConstructor; import lombok.Getter; import org.springframework.http.HttpStatus; public class ProductException extends BaseException{ @Getter @AllArgsConstructor public enum ProductError { PRODUCT_NOT_FOUND(HttpStatus.NOT_FOUND, "ProductNotFound", "ProductNotFound"); private final HttpStatus status; private final String errCode; private final String errMsg; } public ProductException(ProductError productError) { super(productError.getStatus(), productError.getErrCode(), productError.getErrMsg()); } }
true
76959b01190d50c78a0d35637dc60fa56c8180e1
Java
maliktoujani/PFE2021-Back
/src/main/java/com/pfe2021/PFE2021/repository/ContratRepository.java
UTF-8
335
1.9375
2
[]
no_license
package com.pfe2021.PFE2021.repository; import com.pfe2021.PFE2021.model.Contrat; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface ContratRepository extends JpaRepository<Contrat, Long> { Optional<Contrat> findContratById(Long id); void deleteContratById(Long id); }
true
5a308add65bc9570d12556ab110a12a42f8a7475
Java
zhongxingyu/Seer
/Diff-Raw-Data/11/11_d9ad2f9270afefd981768de4ec83a69b11dbacbe/ImportsModel/11_d9ad2f9270afefd981768de4ec83a69b11dbacbe_ImportsModel_t.java
UTF-8
7,740
2.453125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.netbeans.modules.javafx.editor.imports; import java.util.HashSet; import java.util.Set; import javax.lang.model.element.TypeElement; import org.netbeans.api.javafx.source.ElementHandle; /** * This is a collector for all relevant information gathered during scanning for * imports. It holds the information about the declared imports, the import usage * and also the start and end position of the imports block * @author Jaroslav Bachorik */ public class ImportsModel { final static public class Unresolved implements Comparable<Unresolved> { final private String unresolvedName; final private Set<ElementHandle<TypeElement>> options; final private long elementPos; private String resolved = null; public Unresolved(long pos, String unresolvedName, Set<ElementHandle<TypeElement>> options) { this.unresolvedName = unresolvedName; this.options = options; this.elementPos = pos; } public Set<ElementHandle<TypeElement>> getOptions() { return options; } public String getUnresolvedElement() { return unresolvedName; } public String getResolvedName() { return resolved; } public void resolve(String element) { resolved = element; } public long getElementPos() { return elementPos; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Unresolved other = (Unresolved) obj; if (this.unresolvedName != other.unresolvedName && (this.unresolvedName == null || !this.unresolvedName.equals(other.unresolvedName))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + (this.unresolvedName != null ? this.unresolvedName.hashCode() : 0); return hash; } public int compareTo(Unresolved o) { if (this.getResolvedName() == null && o.getResolvedName() != null) return 1; if (this.getResolvedName() != null && o.getResolvedName() == null) return -1; if (this.getResolvedName() == null && o.getResolvedName() == null) return 0; if (this.getResolvedName().startsWith("javafx") && !o.getResolvedName().startsWith("javafx")) return -1; if (!this.getResolvedName().startsWith("javafx") && o.getResolvedName().startsWith("javafx")) return 1; return this.getResolvedName().compareTo(o.getResolvedName()); } } final static public class Declared { final private String importName; final private long start, end; public Declared(String importName, long start, long end) { this.importName = importName; this.start = start; this.end = end; } public long getEnd() { return end; } public String getImportName() { return importName; } public long getStart() { return start; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Declared other = (Declared) obj; if ((this.importName == null) ? (other.importName != null) : !this.importName.equals(other.importName)) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 67 * hash + (this.importName != null ? this.importName.hashCode() : 0); return hash; } } final private Set<Declared> declaredImports = new HashSet<Declared>(); final private Set<String> usedImports = new HashSet<String>(); final private Set<Unresolved> unresolved = new HashSet<Unresolved>(); private long importsStart = Integer.MAX_VALUE; private long importsEnd = Integer.MIN_VALUE; /** * Call this method to indicate import declaration * @param imprt The import statement * @param start The start position in the document * @param end The end position in the document */ public void addDeclaredImport(String imprt, long start, long end) { importsStart = Math.min(importsStart, start); importsEnd = Math.max(importsEnd, end); declaredImports.add(new Declared(imprt, start, end)); } /** * Call this method to indicate the usage of a particular type * @param className The type class name */ public void addUsage(String className) { usedImports.add(className); } /** * Call this method to indicate the occurance of an unknown type * @param unresolvedName The type name of the unresolved eleemnt * @param options The list of types that could be used to resolve the element * @param pos The element position in the document */ public void addUnresolved(String unresolvedName, Set<ElementHandle<TypeElement>> options, long pos) { unresolved.add(new Unresolved(pos, unresolvedName, options)); } /** * Calculates the set of unused imports * It uses full text matching as well as wildcard matching * @return Return a new set of all unused imports */ public Set<Declared> getUnusedImports() { Set<Declared> unused = new HashSet<Declared>(); for(Declared declared : declaredImports) { if (declared.importName.endsWith(".*")) { int imprtLen = declared.importName.length() - 2; String target = declared.importName.substring(0, imprtLen); boolean found = false; for(String imprt : usedImports) { if (imprt.length() > imprtLen) { if (imprt.indexOf(".", imprtLen + 2) > -1) continue; if (imprt.substring(0, imprtLen).equals(target)) { found = true; break; } } else { if (imprt.length() == imprtLen && target.equals(imprt)) { found = true; break; } } } if (!found) { unused.add(declared); } } else { if (!usedImports.contains(declared.importName)) { unused.add(declared); } } } return unused; } /** * * @return Return the set of all unresolved types */ public Set<Unresolved> getUnresolved() { return unresolved; } /** * * @return Returns the position in the document where imports end */ public long getImportsEnd() { return importsEnd; } /** * * @return Return the position in the document where imports start */ public long getImportsStart() { return importsStart; } }
true
67c81cedd872c6bd82dd07c656aa1f4674782c30
Java
HongDongwei/VSM
/app/src/main/java/com/codvision/vsm/presenter/contract/ScheduleSubmitContract.java
UTF-8
555
1.835938
2
[]
no_license
package com.codvision.vsm.presenter.contract; import com.codvision.vsm.base.BaseView; import com.codvision.vsm.module.bean.ScheduleSubmit; /** * Created by sxy on 2019/5/16 14:53 * todo */ public interface ScheduleSubmitContract { public interface Presenter { //删除 void submitSchedule(ScheduleSubmit scheduleSubmit); } public interface View extends BaseView<UserLoginContract.Presenter> { //成功 void submitScheduleSuccess(); void submitScheduleFail(String code, String message); } }
true
4796ad9d680d12c7d33c3292e5413ffb710bf0d9
Java
lhe2010/mySpringMvc2Prac01_copy
/mySpringMvc2Prac01/src/main/java/com/spring/boardPrac01/controller/BoardController.java
UTF-8
963
2.125
2
[]
no_license
package com.spring.boardPrac01.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.spring.boardPrac01.dto.BoardDTO; import com.spring.boardPrac01.service.BoardService; @Controller public class BoardController { @Autowired private BoardService boardService; @RequestMapping(value="/") public String firstpage() { return "home"; } @RequestMapping(value="/main", method=RequestMethod.GET) public String main() { return "boardPrac01/main"; } @RequestMapping(value="/boardList") public String boardList(Model model) throws Exception { List<BoardDTO> boardList = boardService.listAll(); model.addAttribute("boardList", boardList); return "boardPrac01/bList"; } }
true
3bcec3e5967634744e67cd93ff8bd56519db646c
Java
at15/mellowtech-core
/src/test/java/org/mellowtech/core/cache/LRUCacheTest.java
UTF-8
3,707
2.609375
3
[]
no_license
/* * Copyright (c) 2012 mellowtech.org. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. */ package org.mellowtech.core.cache; import org.junit.Before; import org.junit.Test; import org.mellowtech.core.cache.CacheLRU; import org.mellowtech.core.cache.CacheValue; import org.mellowtech.core.cache.Loader; import org.mellowtech.core.cache.NoSuchValueException; import org.mellowtech.core.cache.Remover; import java.util.*; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; /** * @author Martin Svensson * */ public class LRUCacheTest { public HashMap <Integer, Integer> inMemoryMap; public int numKeys = 1000; public int cacheSize = 100; public Loader <Integer, Integer> loader; public Remover <Integer, Integer> remover; public CacheLRU <Integer, Integer> cache; @Before public void before(){ Random r = new Random(); inMemoryMap = new HashMap<>(); for(int i = 0; i < numKeys; i++){ inMemoryMap.put(i, r.nextInt()); } loader = new Loader<Integer, Integer>() { @Override public Integer get(Integer key) throws NoSuchValueException { Integer i = inMemoryMap.get(key); if(i == null) throw new NoSuchValueException(); return inMemoryMap.get(key); } }; remover = new Remover<Integer, Integer>() { @Override public void remove(Integer key, CacheValue<Integer> value) { if(value.isDirty()) inMemoryMap.put(key, (int) value.getValue()); } }; cache = new CacheLRU<>(remover, loader, cacheSize); } @Test public void doTest() throws Exception{ //First load 50 keys for(int i = 0; i < 50; i++){ Integer val = cache.get(i); assertThat(val, equalTo(inMemoryMap.get(i))); } //Now make sure that all values are present in the cache for(int i = 0; i < 50; i++){ assertThat(cache.getFromCache(i), notNullValue()); } //Now set some dirty bits: Integer val1 = cache.get(10); cache.dirty(10, val1+100); Integer val2 = cache.get(500); cache.dirty(500, val2 + 100); //expect the map to differ from the cache assertThat(cache.get(10), not(equalTo(inMemoryMap.get(10)))); assertThat(cache.get(500), not(equalTo(inMemoryMap.get(500)))); cache.emptyCache(); assertThat(inMemoryMap.get(10), equalTo(val1+100)); assertThat(inMemoryMap.get(500), equalTo(val2+100)); } @Test(expected = NoSuchValueException.class) public void expectNoSuchValue() throws NoSuchValueException{ cache.get(numKeys+100); //should not exist } @Test(expected = ArithmeticException.class) public void divisionWithException() { int i = 1/0; } }
true
b150f6eab41d2d8fa33813b99211e2adc05c81da
Java
Yasinaaa/AndroidLab
/GithubMVP/app/src/test/java/ru/itis/lectures/githubmvp/api/ApiProviderTest.java
UTF-8
794
1.953125
2
[]
no_license
package ru.itis.lectures.githubmvp.api; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import ru.itis.lectures.githubmvp.testutils.TestGithubService; import ru.itis.lectures.githubmvp.testutils.TestProviderImpl; import static org.junit.Assert.assertTrue; /** * @author Artur Vasilov */ @RunWith(JUnit4.class) public class ApiProviderTest { @Before public void setUp() throws Exception { ApiFactory.resetProvider(); } @Test public void testSetAndGetProvider() throws Exception { ApiProvider provider = new TestProviderImpl(new TestGithubService()); ApiFactory.setProvider(provider); assertTrue(provider == ApiFactory.getProvider()); } }
true
1e5abea9e796a08431e46e2783eee0641a59859f
Java
Asharam-CIT/jenkinsTest
/src/client/HttpClientFactory.java
UTF-8
4,740
2.421875
2
[]
no_license
package client; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; //import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.SSLContexts; public class HttpClientFactory { private static CloseableHttpClient client; private static CloseableHttpClient httpClient; private static PoolingHttpClientConnectionManager connPool = null; private static PoolingHttpClientConnectionManager httpconnPool = null; // private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientFactory.class); static{ try { SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build(); sslcontext.init(new KeyManager[0], new TrustManager[] { new DummyTrustManager() }, new SecureRandom()); sslcontext.init(null, new X509TrustManager[]{new HttpsTrustManager()}, new SecureRandom()); SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, new HostnameVerifier() { @Override public boolean verify(final String s, final SSLSession sslSession) { return true; } }); Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory> create() .register("https", factory).build(); connPool = new PoolingHttpClientConnectionManager(r); // Increase max total connection to 200 connPool.setMaxTotal(300);//configurable through app.properties // Increase default max connection per route to 50 connPool.setDefaultMaxPerRoute(300);//configurable through app.properties // httpconnPool = new PoolingHttpClientConnectionManager(r); httpconnPool = new PoolingHttpClientConnectionManager(); // Increase max total connection to 200 httpconnPool.setMaxTotal(300);//configurable through app.properties // Increase default max connection per route to 50 httpconnPool.setDefaultMaxPerRoute(300);//configurable through app.properties client = HttpClients.custom(). setConnectionManagerShared(true). setConnectionManager(connPool). setSSLSocketFactory(factory).build(); httpClient = HttpClients.custom(). setConnectionManagerShared(true). setConnectionManager(httpconnPool). build(); } catch(Exception e){ //LOGGER.error("Error initiliazing HttpClientFactory :: ",e); e.printStackTrace(); } } public static CloseableHttpClient getHttpsClient() throws KeyManagementException, NoSuchAlgorithmException { if (client != null) { return client; } throw new RuntimeException("Client is not initiliazed properly"); } public static CloseableHttpClient getHttpClient() { if (httpClient != null) { return httpClient; } throw new RuntimeException("Client is not initiliazed properly"); } public static void releaseInstance() { client = null; httpClient = null ; } public static class DummyTrustManager implements X509TrustManager { public boolean isClientTrusted(X509Certificate[] cert) { return true; } public boolean isServerTrusted(X509Certificate[] cert) { return true; } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } } }
true
089bdab90e5b5157ffcbdd7ab2a73b42ad12e0a6
Java
Emma123456/leetcodepractice
/src/stack/NextGreaterElement503.java
UTF-8
2,111
4.125
4
[]
no_license
package stack; import java.util.Stack; public class NextGreaterElement503 { /** * 可以返回来再次比较 * * 解决循环数组的思路有两种: 第一:将原始数组扩大两倍,当做普通问题处理 第二:借助栈 * * @param nums * @return */ public int[] nextGreaterElements(int[] nums) { int[] result = new int[nums.length]; Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < nums.length; i++) { result[i] = -1; while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) { result[stack.pop()] = nums[i]; } stack.push(i); } for (int i = 0; i < nums.length - 1; i++) { while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) { result[stack.pop()] = nums[i]; } } return result; } /** * nextGreaterElements更优雅的方式 * @param nums * @return */ public int[] nextGreaterElementsV3(int[] nums) { int[] result = new int[nums.length]; int doubleLength = 2 * nums.length; Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < doubleLength; i++) { int num = nums[i % nums.length]; if (i < nums.length) { result[i] = -1; } while (!stack.isEmpty() && num > nums[stack.peek()]) { result[stack.pop()] = num; } if (i < nums.length) { stack.push(i); } } return result; } public int[] nextGreaterElementsV2(int[] nums) { int max = Integer.MIN_VALUE; for (int num : nums) { max = Math.max(max, num); } int n = nums.length; int[] result = new int[n]; int[] temp = new int[n * 2]; for (int i = 0; i < n * 2; i++) { temp[i] = nums[i % n]; } for (int i = 0; i < n; i++) { result[i] = -1; if (nums[i] == max) continue; for (int j = i + 1; j < n * 2; j++) { if (temp[j] > nums[i]) { result[i] = temp[j]; break; } } } return result; } public static void main(String[] args) { // int[] nums = new int[] { 5, 4, 3, 2, 1 }; int[] nums = new int[] { 1, 2, 1 }; int[] r = new NextGreaterElement503().nextGreaterElementsV3(nums); for (int v : r) { System.out.print(v + "\t"); } } }
true
dbd2645d87dab61318030d93af4f535b4ca5a1a1
Java
google/nomulus
/core/src/test/java/google/registry/batch/AsyncTaskEnqueuerTest.java
UTF-8
5,109
1.710938
2
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
// Copyright 2018 The Nomulus Authors. 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 google.registry.batch; import static google.registry.batch.AsyncTaskEnqueuer.PARAM_REQUESTED_TIME; import static google.registry.batch.AsyncTaskEnqueuer.PARAM_RESAVE_TIMES; import static google.registry.batch.AsyncTaskEnqueuer.PARAM_RESOURCE_KEY; import static google.registry.batch.AsyncTaskEnqueuer.QUEUE_ASYNC_ACTIONS; import static google.registry.testing.DatabaseHelper.persistActiveContact; import static google.registry.testing.TestLogHandlerUtils.assertLogMessage; import com.google.cloud.tasks.v2.HttpMethod; import com.google.common.collect.ImmutableSortedSet; import google.registry.model.contact.Contact; import google.registry.persistence.transaction.JpaTestExtensions; import google.registry.persistence.transaction.JpaTestExtensions.JpaIntegrationTestExtension; import google.registry.testing.CloudTasksHelper; import google.registry.testing.CloudTasksHelper.TaskMatcher; import google.registry.testing.FakeClock; import google.registry.util.CapturingLogHandler; import google.registry.util.JdkLoggerConfig; import java.util.logging.Level; import org.joda.time.DateTime; import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; /** Unit tests for {@link AsyncTaskEnqueuer}. */ @ExtendWith(MockitoExtension.class) public class AsyncTaskEnqueuerTest { @RegisterExtension final JpaIntegrationTestExtension jpa = new JpaTestExtensions.Builder().buildIntegrationTestExtension(); private AsyncTaskEnqueuer asyncTaskEnqueuer; private final CapturingLogHandler logHandler = new CapturingLogHandler(); private final FakeClock clock = new FakeClock(DateTime.parse("2015-05-18T12:34:56Z")); private final CloudTasksHelper cloudTasksHelper = new CloudTasksHelper(clock); @BeforeEach void beforeEach() { JdkLoggerConfig.getConfig(AsyncTaskEnqueuer.class).addHandler(logHandler); asyncTaskEnqueuer = createForTesting(cloudTasksHelper.getTestCloudTasksUtils()); } public static AsyncTaskEnqueuer createForTesting(CloudTasksUtils cloudTasksUtils) { return new AsyncTaskEnqueuer(cloudTasksUtils); } @Test void test_enqueueAsyncResave_success() { Contact contact = persistActiveContact("jd23456"); asyncTaskEnqueuer.enqueueAsyncResave( contact.createVKey(), clock.nowUtc(), ImmutableSortedSet.of(clock.nowUtc().plusDays(5))); cloudTasksHelper.assertTasksEnqueued( QUEUE_ASYNC_ACTIONS, new CloudTasksHelper.TaskMatcher() .path(ResaveEntityAction.PATH) .method(HttpMethod.POST) .service("backend") .header("content-type", "application/x-www-form-urlencoded") .param(PARAM_RESOURCE_KEY, contact.createVKey().stringify()) .param(PARAM_REQUESTED_TIME, clock.nowUtc().toString()) .scheduleTime(clock.nowUtc().plus(Duration.standardDays(5)))); } @Test void test_enqueueAsyncResave_multipleResaves() { Contact contact = persistActiveContact("jd23456"); DateTime now = clock.nowUtc(); asyncTaskEnqueuer.enqueueAsyncResave( contact.createVKey(), now, ImmutableSortedSet.of(now.plusHours(24), now.plusHours(50), now.plusHours(75))); cloudTasksHelper.assertTasksEnqueued( QUEUE_ASYNC_ACTIONS, new TaskMatcher() .path(ResaveEntityAction.PATH) .method(HttpMethod.POST) .service("backend") .header("content-type", "application/x-www-form-urlencoded") .param(PARAM_RESOURCE_KEY, contact.createVKey().stringify()) .param(PARAM_REQUESTED_TIME, now.toString()) .param(PARAM_RESAVE_TIMES, "2015-05-20T14:34:56.000Z,2015-05-21T15:34:56.000Z") .scheduleTime(clock.nowUtc().plus(Duration.standardHours(24)))); } @MockitoSettings(strictness = Strictness.LENIENT) @Test void test_enqueueAsyncResave_ignoresTasksTooFarIntoFuture() { Contact contact = persistActiveContact("jd23456"); asyncTaskEnqueuer.enqueueAsyncResave( contact.createVKey(), clock.nowUtc(), ImmutableSortedSet.of(clock.nowUtc().plusDays(31))); cloudTasksHelper.assertNoTasksEnqueued(QUEUE_ASYNC_ACTIONS); assertLogMessage(logHandler, Level.INFO, "Ignoring async re-save"); } }
true
42e5e19dbde0662877740796c8cc845ec65a0cea
Java
pjohalloran/cardgame45
/src/server/cardgame/Deck.java
UTF-8
4,061
3.578125
4
[]
no_license
/* * Created on 25-Jan-2005 */ package server.cardgame; import java.util.ArrayList; import java.util.Collections; /** * @author Pj O' Halloran * * A Deck of cards object. Cards can only be taken off the * top of the deck. */ public class Deck { private static final int INITIAL_DEFAULT_CAPACITY = 53;//Joker card included private static final int NUM_OF_SUITS = 4; //deck private ArrayList cardDeck; //cards in play private ArrayList removedCards; //Boolean marker to indicate if a deck is stripped or not private boolean stripped; /** * Creates the default deck, which has the Joker included and * is stripped of all low value cards * */ public Deck(){ this(true, true); } /** * Creates a custom deck * * @param jokerIncluded True if the joker card is included * @param strip True if the deck must be stripped, ie number of players = 2 */ public Deck(boolean includeJoker, boolean strip){ removedCards = new ArrayList(); stripped = strip; if(includeJoker == true) cardDeck = new ArrayList(INITIAL_DEFAULT_CAPACITY); else cardDeck = new ArrayList(INITIAL_DEFAULT_CAPACITY-1); init(includeJoker, strip); } /** * Initialises the cards and places them in the deck * */ public void init(boolean includeJoker, boolean toStrip){ for(int suitI=0; suitI<NUM_OF_SUITS; suitI++){ //for(int cardI=2; cardI<14; cardI++){ for(int cardI=2; cardI<15; cardI++) { if( (toStrip==true) & (cardI<5) ) //don't add unneeded cards i.e. the 2, 3 or 4 of "SUIT_NAME" continue; //Temp Bug fix Card x = new Card(cardI, suitI); if(x.toString() == null) continue; //End temp bug fix cardDeck.add(new Card(cardI, suitI)); } } //add the special case cards, ie 1) the Ace Of Hearts, 2) Joker and 3) the Ace of Diamonds if(includeJoker == true) cardDeck.add(new Card("jok")); cardDeck.add(new Card("ah")); cardDeck.add(new Card("ad")); shuffle(); } public int getCurrentDeckSize(){ return cardDeck.size(); } /** * Performs post round clean up of the deck. * Must be called when a round is over or else * there will be cards missing from the deck * when they are dealed out again. * */ public void postRound(){ cardDeck.addAll(removedCards); removedCards.clear(); shuffle(); } /** * Shuffles the deck * */ public void shuffle(){ Collections.shuffle(cardDeck); } /** * Reinserts the low cards into the deck * */ public void insertStrippedCards(){ if(stripped == true){ for(int suitI=0; suitI<NUM_OF_SUITS; suitI++){ for(int cardI=0; cardI<5; cardI++){ cardDeck.add(new Card(cardI, suitI)); } } shuffle(); } } /** * Taking off 1 card at a time off the deck * * @return the Card on the top of the deck */ public Card removeCard(){ Card topCard; topCard = (Card)cardDeck.remove(0); removedCards.add(topCard); return topCard; } /** * Used when taking off multiple cards from the deck, * as when dealing is taking place. * * @param number Number of cards to be taken off the deck * @return the Cards */ public Card[] removeCards(int number){ Card cardArr[] = new Card[number]; for(int i=0; i<number; i++){ //cardArr[i] = (Card)cardDeck.remove(i); cardArr[i] = (Card)cardDeck.remove(0); removedCards.add(cardArr[i]); } return cardArr; } /** * Used for cutting cards from the deck * * @param number The number of cards to be cut */ public void cutCards(int number){ Card temp; for(int i=0; i<number; i++){ //temp = (Card)cardDeck.remove(i); temp = (Card)cardDeck.remove(0); removedCards.add(temp); } } /** * for debugging * */ public void printDeck(){ for(int i=0; i<this.cardDeck.size(); i++){ Card x = (Card)cardDeck.get(i); System.out.println(i+" " +x.toString()); } } }
true
777f4accad34a90a21fa5965b5d37e24450f6286
Java
coexxister/Tawe-Lib-230
/src/JavaFX/AccountEditorController.java
UTF-8
5,619
2.953125
3
[]
no_license
package JavaFX; import Core.User; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import java.net.URL; import java.sql.SQLException; import java.util.ResourceBundle; /** * Handles editing data of an existing user in the database. * * @author Grzegorz Debicki, Marcos Pallikaras, Dominic Woodman * @version 1.0 */ public class AccountEditorController extends ResourceController implements Initializable { /** * user ID of the user to be edited. */ private final int id = getResourceFlowManager().getUserID(); /** * file path for the avatar image. */ private String path; /** * TextField for the first name of the account. */ @FXML private TextField firstName; /** * TextField for the surname of the account. */ @FXML private TextField surname; /** * TextField for the street name of the account's address. */ @FXML private TextField streetName; /** * TextField for the house number of the account's address. */ @FXML private TextField streetNumber; /** * TextField for the city of the account's address. */ @FXML private TextField city; /** * TextField for the county of the account's address. */ @FXML private TextField county; /** * TextField for the post code of the account's address. */ @FXML private TextField postCode; /** * TextField for the phone number of the account. */ @FXML private TextField phoneNumber; /** * avatar image displayed on the avatar selection button. */ @FXML private ImageView avatar; /** * Sets the avatar for the user. * * @param event the event triggered by clicking the button. */ @FXML private void handleSetAvatarButtonAction(ActionEvent event) { //set the image on the button to set the avatar path = setAvatar(event); avatar.setImage(new Image(path)); } /** * Saves all details set in text fields to respective variables, * to change the values in the database. */ @FXML public void handleSaveAction() { /*try to get the account by its ID and edit its details. If getting the account from the database fails or the avatar image doesn't exist, output an error. */ try { //get the account. User account = getAccountManager().getAccount(id); /* check for each text field if it is empty or not. If not, assign its text value to the equivalent attribute of the user in the database. */ if (!(firstName.getText().isEmpty())) { account.setFirstName(firstName.getText()); } if (!(surname.getText().isEmpty())) { account.setLastName(surname.getText()); } if (!(streetName.getText().isEmpty())) { account.setStreetName(streetName.getText()); } if (!(streetNumber.getText().isEmpty())) { account.setStreetNum(streetNumber.getText()); } if (!(city.getText().isEmpty())) { account.setCity(city.getText()); } if (!(county.getText().isEmpty())) { account.setCounty(county.getText()); } if (!(postCode.getText().isEmpty())) { account.setPostCode(postCode.getText()); } if (!(phoneNumber.getText().isEmpty())) { account.setTelNum(phoneNumber.getText()); } //set the user's avatar in the database. account.setAvatarID(getResourceManager().getImageID(path)); //edit the account with the new details. getAccountManager().editAccount(account); //Show the user a window indicating that their save was successful. Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setContentText("Save success."); alert.showAndWait(); goBack(); } catch (SQLException e) { //sql error in database. Alert alert = new Alert(Alert.AlertType.ERROR); alert.setContentText("Error in database!"); alert.showAndWait(); } catch (IllegalArgumentException e) { //image specified does not exist. Alert alert = new Alert(Alert.AlertType.WARNING); alert.setContentText("Image specified must already exist!"); alert.showAndWait(); } } /** * Cancels all changes and returns back to Resource Flow Interface. */ @FXML public void handleCancelAction() { goBack(); } /** * Changes the scene to the resource flow interface. */ private void goBack() { loadSubscene(SceneController.getResourceFlowInterface()); } /** * Initialises the interface to display the current details of the user in the text fields. * * @param location The location used to resolve relative paths for the root object * @param resources The resources used to localize the root object */ @Override public void initialize(URL location, ResourceBundle resources) { User account = getAccountManager().getAccount(id); firstName.setText(account.getFirstName()); surname.setText(account.getLastName()); streetName.setText(account.getStreetName()); streetNumber.setText(account.getStreetNum()); city.setText(account.getCity()); county.setText(account.getCounty()); postCode.setText(account.getPostCode()); phoneNumber.setText(account.getTelNum()); /* try to get the file path of the existing avatar for the user and set the image for the select avatar button to the image at that path. If getting the URL from the database fails, tell the user that the avatar could not be loaded. */ try { path = getResourceManager().getImageURL(account.getAvatarID()); avatar.setImage(new Image(path)); } catch (SQLException e) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setContentText("Couldn't load an avatar."); alert.showAndWait(); } } }
true
c6a8542347afc496bd3fff0b84765e54d08bd090
Java
XLOUS-X/utils_demo
/src/main/java/com/example/utilsdemo/controller/TestController.java
UTF-8
689
1.914063
2
[]
no_license
package com.example.utilsdemo.controller; import com.alibaba.fastjson.JSON; import com.example.utilsdemo.entity.NewSocketMsg; import com.example.utilsdemo.utils.HttpClientUtil; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @GetMapping("/test") public void test() { NewSocketMsg json = HttpClientUtil.initNewSocketMsg(); String[] sentGPGHttpClient2 = HttpClientUtil.sentGPGHttpClient2("/camera/test", ""); for (int i = 0; i < sentGPGHttpClient2.length; i++) { System.out.println(sentGPGHttpClient2[i]); } } }
true
41b086675ffb26c1e60acc1aa42aa8797b684bbc
Java
mikita-semiannik/grow
/src/main/java/com/grow/corebasicconcepts/Triangle.java
UTF-8
426
3.375
3
[]
no_license
package com.grow.corebasicconcepts; public class Triangle implements Figure{ Point point1; Point point2; Point point3; public Triangle(Point point1, Point point2, Point point3) { this.point1 = point1; this.point2 = point2; this.point3 = point3; } @Override public void print() { System.out.println("" + point1 + point2 + point3 + " This is Triangle."); } }
true
35b57b6dc76389e03a3d8412d839004944add8f5
Java
chenzhu005774/IndiaIPTV
/app/src/main/java/com/amt/indiaiptv/utils/net/Api.java
UTF-8
2,995
2.421875
2
[]
no_license
package com.amt.indiaiptv.utils.net; import com.amt.indiaiptv.utils.LogUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** *API 请求的基本类 **/ public class Api { //读超时长,单位:毫秒 public static final int READ_TIME_OUT = 2000; //连接时长,单位:毫秒 public static final int CONNECT_TIME_OUT = 2000; public static String token = ""; private static Api retrofitManager = null; public ApiService movieService; String HOST = "http://gank.io/"; String API_SERVER_URL = HOST + "api/data/"; // private final String basUrl=API_SERVER_URL; // private final String basUrl = "http://192.168.2.207:9003/vee_api/"; private final String basUrl = "http://47.108.143.10:8079/vee_api/"; /** * 构造方法私有化 */ private Api() { StringBuilder baseUrl = new StringBuilder(); baseUrl.append(basUrl); //新建log拦截器 HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { LogUtils.i("request OkHttpMessage:"+message); } }); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); //公共参数 BasicParamsInterceptor basicParamsInterceptor = new BasicParamsInterceptor.Builder() .addParam("reqTime", "") // .addParam("token", "123") .addHeaderLine("Content-Type:application/x-www-form-urlencoded; charset=utf-8") .addHeaderParam("token",token) //添加头 .build(); OkHttpClient okHttpClient = new OkHttpClient.Builder() .readTimeout(READ_TIME_OUT, TimeUnit.MILLISECONDS) .connectTimeout(CONNECT_TIME_OUT, TimeUnit.MILLISECONDS) .addInterceptor(loggingInterceptor) .addInterceptor(basicParamsInterceptor) .build(); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls().create(); Retrofit retrofit = new Retrofit.Builder() .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(baseUrl.toString()) .build(); movieService = retrofit.create(ApiService.class); } /** * 提供外部调用的单例 */ public static ApiService getDefault() { retrofitManager = new Api(); return retrofitManager.movieService; } }
true
b2761fe2b1c5dc27cd1cd42c9d84e6981b411817
Java
LeviSooky/Szamologep
/calculator-web/src/main/java/CurrServlet.java
UTF-8
4,170
2.28125
2
[]
no_license
import Modell.CurrencyConv; import Modell.CurrencyDAO; import Modell.CurrencyDAOImpl; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import javax.net.ssl.HttpsURLConnection; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; @WebServlet("/CurrServlet") public class CurrServlet extends HttpServlet { private final String API_KEY = "3914bdb7b2e07ae9016d869a"; String currResult; StringBuilder builder = new StringBuilder(); String ANS; String fromCurr; String toCurr; List<CurrencyConv> sessionCurrList = new ArrayList<>(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); if (req.getParameter("from") != null && req.getParameter("to") != null && req.getParameter("=") != null) { fromCurr = req.getParameter("from"); toCurr = req.getParameter("to"); String urlString = "https://v6.exchangerate-api.com/v6/" + API_KEY + "/pair/" + fromCurr + "/" + toCurr + "/" + currResult; try { URL url = new URL(urlString); HttpsURLConnection request = (HttpsURLConnection) url.openConnection(); request.connect(); JsonParser jp = new JsonParser(); JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); JsonObject jsonObj = root.getAsJsonObject(); builder = new StringBuilder((jsonObj.get("conversion_result").getAsString())); ANS = builder.toString(); if (!builder.toString().isEmpty()) { CurrencyDAO dao = new CurrencyDAOImpl(); CurrencyConv tmp = new CurrencyConv(Float.parseFloat(currResult),fromCurr,Float.parseFloat(ANS),toCurr); dao.addToDB(tmp); sessionCurrList.add(tmp); } } catch (IOException | SQLException | ClassNotFoundException e) { e.printStackTrace(); } } else if (req.getParameter("0") != null) builder.append("0"); else if (req.getParameter("1") != null) builder.append("1"); else if (req.getParameter("2") != null) builder.append("2"); else if (req.getParameter("3") != null) builder.append("3"); else if (req.getParameter("4") != null) builder.append("4"); else if (req.getParameter("5") != null) builder.append("5"); else if (req.getParameter("6") != null) builder.append("6"); else if (req.getParameter("7") != null) builder.append("7"); else if (req.getParameter("8") != null) builder.append("8"); else if (req.getParameter("9") != null) builder.append("9"); else if (req.getParameter("C") != null) builder= new StringBuilder(); else if(req.getParameter(".")!=null) builder.append("."); else if(req.getParameter("ANS")!=null) builder.append(ANS); else if(req.getParameter("DEL")!=null){ if(builder.length()>=2){ builder.deleteCharAt(builder.length()-1); } else if(builder.length()==1){ builder= new StringBuilder(); } } updateRes(builder); req.setAttribute("from", fromCurr); req.setAttribute("to", toCurr); req.setAttribute("currResult", currResult); req.getRequestDispatcher("currency.jsp").forward(req, resp); } public void updateRes(StringBuilder sb) { this.currResult = sb.toString(); } }
true
c325d2b6648da6498e3ae0c4132cc803582229b8
Java
andyvkim/lab4
/src/main/java/kim/andy/lab4/kim/andy/labTooLargeTooSmall.java
UTF-8
1,275
3.109375
3
[]
no_license
package kim.andy.lab4.kim.andy; import java.util.Scanner; import java.util.Random; /** * Created by andykim on 1/12/17. */ public class labTooLargeTooSmall { public void howManyGuesses() { Random rand = new Random(); int secretNumber = rand.nextInt(10)+1; Scanner input = new Scanner(System.in); int guess; int nextGuess = 0; int counter = 1; System.out.println("Guess a number between 1 and 10"); guess = input.nextInt(); while (guess != secretNumber) { if (guess > secretNumber) { System.out.println("Too Big. Try again"); counter++; } else if (guess < secretNumber) { System.out.println("Too Small. Try again"); counter++; } else if (nextGuess == guess) { System.out.println("Guess again"); counter += 0; } nextGuess = input.nextInt(); } System.out.println("you got it"); System.out.println(counter); } public static void main(String[] args) { labTooLargeTooSmall lab4TestRun = new labTooLargeTooSmall(); lab4TestRun.howManyGuesses(); } }
true
90275ddd112a75ff61c71ec8d0d50614753c8ffa
Java
ChadwickDS2017-2018/binary-search-tree-codewick-chadwick
/support/structures/PreOrderIterator.java
UTF-8
1,131
3.78125
4
[]
no_license
package structures; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; public class PreOrderIterator<T> implements Iterator<T> { private final Deque<BinaryTreeNode<T>> stack; public PreOrderIterator(BinaryTreeNode<T> root){ stack = new LinkedList<BinaryTreeNode<T>>(); stack.push(root); } @Override public boolean hasNext() { return !stack.isEmpty(); } @Override public T next() { BinaryTreeNode<T> toVisit = stack.pop(); //Push and pop are from the same side, like a stack, therefore it is only wise to push all of the right children first. //So all of the pops can be the left as they are the newest //popping the toVisit, goes on to the newest Left Child, after all, that one is the one you want to go to. //Also by popping the left child, the discarded toVisit is added to the list in the correct way. if(toVisit.hasRightChild()) {stack.push(toVisit.getRightChild());} if(toVisit.hasLeftChild()) {stack.push(toVisit.getLeftChild());} return toVisit.getData(); } @Override public void remove() { throw new UnsupportedOperationException(); } }
true
ef7903dd3b414ee873be390e4333308f1ded4a93
Java
madaaf/tribe
/app/src/main/java/com/tribe/app/presentation/view/widget/SquareConstraintLayout.java
UTF-8
774
2.453125
2
[]
no_license
package com.tribe.app.presentation.view.widget; import android.content.Context; import android.support.constraint.ConstraintLayout; import android.util.AttributeSet; /** * A ConstraintLayout that will always be square (based out of its width) */ public class SquareConstraintLayout extends ConstraintLayout { public SquareConstraintLayout(Context context) { super(context); } public SquareConstraintLayout(Context context, AttributeSet attrs) { super(context, attrs); } public SquareConstraintLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, widthMeasureSpec); } }
true
3754def35432d0a88c38a9f6d51106ad1ad9587b
Java
BillBrown20000/JavaNotes
/src/main/java/JavaReaderWriter/BufferedReader.java
UTF-8
1,193
3.515625
4
[]
no_license
package JavaReaderWriter; public class BufferedReader { } /* Working of BufferedReader The BufferedReader maintains an internal buffer of 8192 characters. During the read operation in BufferedReader, a chunk of characters is read from the disk and stored in the internal buffer. And from the internal buffer characters are read individually. Hence, the number of communication to the disk is reduced. This is why reading characters is faster using BufferedReader. Methods of BufferedReader read() Method read() - reads a single character from the internal buffer of the reader read(char[] array) - reads the characters from the reader and stores in the specified array read(char[] array, int start, int length) - reads the number of characters equal to length from the reader and stores in the specified array starting from the position start skip() Method To discard and skip the specified number of characters, we can use the skip() method. Other Methods of BufferedReader ready() checks if the file reader is ready to be read mark() mark the position in reader up to which data has been read reset() returns the control to the point in the reader where the mark was set */
true
3c081ead0a190857a16d974bac6757148fa256e5
Java
ChoeMinji/glide
/library/src/main/java/com/bumptech/glide/manager/SingletonConnectivityReceiver.java
UTF-8
9,859
1.953125
2
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause-Views", "Xfig", "MIT", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.bumptech.glide.manager; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.ConnectivityManager.NetworkCallback; import android.net.Network; import android.net.NetworkInfo; import android.os.Build; import android.os.Build.VERSION_CODES; import android.util.Log; import androidx.annotation.GuardedBy; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.annotation.VisibleForTesting; import com.bumptech.glide.manager.ConnectivityMonitor.ConnectivityListener; import com.bumptech.glide.util.GlideSuppliers; import com.bumptech.glide.util.GlideSuppliers.GlideSupplier; import com.bumptech.glide.util.Synthetic; import com.bumptech.glide.util.Util; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** Uses {@link android.net.ConnectivityManager} to identify connectivity changes. */ final class SingletonConnectivityReceiver { private static volatile SingletonConnectivityReceiver instance; private static final String TAG = "ConnectivityMonitor"; private final FrameworkConnectivityMonitor frameworkConnectivityMonitor; @GuardedBy("this") @Synthetic final Set<ConnectivityListener> listeners = new HashSet<ConnectivityListener>(); @GuardedBy("this") private boolean isRegistered; static SingletonConnectivityReceiver get(@NonNull Context context) { if (instance == null) { synchronized (SingletonConnectivityReceiver.class) { if (instance == null) { instance = new SingletonConnectivityReceiver(context.getApplicationContext()); } } } return instance; } @VisibleForTesting static void reset() { instance = null; } private SingletonConnectivityReceiver(final @NonNull Context context) { GlideSupplier<ConnectivityManager> connectivityManager = GlideSuppliers.memorize( new GlideSupplier<ConnectivityManager>() { @Override public ConnectivityManager get() { return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); } }); ConnectivityListener connectivityListener = new ConnectivityListener() { @Override public void onConnectivityChanged(boolean isConnected) { List<ConnectivityListener> toNotify; synchronized (SingletonConnectivityReceiver.this) { toNotify = new ArrayList<>(listeners); } for (ConnectivityListener listener : toNotify) { listener.onConnectivityChanged(isConnected); } } }; frameworkConnectivityMonitor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new FrameworkConnectivityMonitorPostApi24(connectivityManager, connectivityListener) : new FrameworkConnectivityMonitorPreApi24( context, connectivityManager, connectivityListener); } synchronized void register(ConnectivityListener listener) { listeners.add(listener); maybeRegisterReceiver(); } /** * To avoid holding a lock while notifying listeners, the unregisterd listener may still be * notified about a connectivity change after this method completes if this method is called on a * thread other than the main thread and if a connectivity broadcast is racing with this method. * Callers must handle this case. */ synchronized void unregister(ConnectivityListener listener) { listeners.remove(listener); maybeUnregisterReceiver(); } @GuardedBy("this") private void maybeRegisterReceiver() { if (isRegistered || listeners.isEmpty()) { return; } isRegistered = frameworkConnectivityMonitor.register(); } @GuardedBy("this") private void maybeUnregisterReceiver() { if (!isRegistered || !listeners.isEmpty()) { return; } frameworkConnectivityMonitor.unregister(); isRegistered = false; } private interface FrameworkConnectivityMonitor { boolean register(); void unregister(); } @RequiresApi(VERSION_CODES.N) private static final class FrameworkConnectivityMonitorPostApi24 implements FrameworkConnectivityMonitor { @Synthetic boolean isConnected; @Synthetic final ConnectivityListener listener; private final GlideSupplier<ConnectivityManager> connectivityManager; private final NetworkCallback networkCallback = new NetworkCallback() { @Override public void onAvailable(@NonNull Network network) { postOnConnectivityChange(true); } @Override public void onLost(@NonNull Network network) { postOnConnectivityChange(false); } private void postOnConnectivityChange(final boolean newState) { // We could use registerDefaultNetworkCallback with a Handler, but that's only available // on API 26, instead of API 24. We can mimic the same behavior here manually by // posting to the UI thread. All calls have to be posted to make sure that we retain the // original order. Otherwise a call on a background thread, followed by a call on the UI // thread could result in the first call running second. Util.postOnUiThread( new Runnable() { @Override public void run() { onConnectivityChange(newState); } }); } @Synthetic void onConnectivityChange(boolean newState) { // See b/201425456. Util.assertMainThread(); boolean wasConnected = isConnected; isConnected = newState; if (wasConnected != newState) { listener.onConnectivityChanged(newState); } } }; FrameworkConnectivityMonitorPostApi24( GlideSupplier<ConnectivityManager> connectivityManager, ConnectivityListener listener) { this.connectivityManager = connectivityManager; this.listener = listener; } // Permissions are checked in the factory instead. @SuppressLint("MissingPermission") @Override public boolean register() { isConnected = connectivityManager.get().getActiveNetwork() != null; try { connectivityManager.get().registerDefaultNetworkCallback(networkCallback); return true; // See b/201664814, b/204226444: At least TooManyRequestsException is not public and // doesn't extend from any subclass :/. } catch (RuntimeException e) { if (Log.isLoggable(TAG, Log.WARN)) { Log.w(TAG, "Failed to register callback", e); } return false; } } @Override public void unregister() { connectivityManager.get().unregisterNetworkCallback(networkCallback); } } private static final class FrameworkConnectivityMonitorPreApi24 implements FrameworkConnectivityMonitor { private final Context context; @Synthetic final ConnectivityListener listener; private final GlideSupplier<ConnectivityManager> connectivityManager; @Synthetic boolean isConnected; private final BroadcastReceiver connectivityReceiver = new BroadcastReceiver() { @Override public void onReceive(@NonNull Context context, Intent intent) { boolean wasConnected = isConnected; isConnected = isConnected(); if (wasConnected != isConnected) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "connectivity changed, isConnected: " + isConnected); } listener.onConnectivityChanged(isConnected); } } }; FrameworkConnectivityMonitorPreApi24( Context context, GlideSupplier<ConnectivityManager> connectivityManager, ConnectivityListener listener) { this.context = context.getApplicationContext(); this.connectivityManager = connectivityManager; this.listener = listener; } @Override public boolean register() { // Initialize isConnected so that we notice the first time around when there's a broadcast. isConnected = isConnected(); try { // See #1405 context.registerReceiver( connectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); return true; } catch (SecurityException e) { // See #1417, registering the receiver can throw SecurityException. if (Log.isLoggable(TAG, Log.WARN)) { Log.w(TAG, "Failed to register", e); } return false; } } @Override public void unregister() { context.unregisterReceiver(connectivityReceiver); } @SuppressWarnings("WeakerAccess") @Synthetic // Permissions are checked in the factory instead. @SuppressLint("MissingPermission") boolean isConnected() { NetworkInfo networkInfo; try { networkInfo = connectivityManager.get().getActiveNetworkInfo(); } catch (RuntimeException e) { // #1405 shows that this throws a SecurityException. // b/70869360 shows that this throws NullPointerException on APIs 22, 23, and 24. // b/70869360 also shows that this throws RuntimeException on API 24 and 25. if (Log.isLoggable(TAG, Log.WARN)) { Log.w(TAG, "Failed to determine connectivity status when connectivity changed", e); } // Default to true; return true; } return networkInfo != null && networkInfo.isConnected(); } } }
true
dd082d7c2720c1b49736deeb178b13d625c5b434
Java
jflores1997/car-dealership
/src/com/revature/pojo/Employee.java
UTF-8
196
1.757813
2
[]
no_license
package com.revature.pojo; public class Employee extends User { private static final long serialVersionUID = 3050062013534252559L; public Employee(String username) { super(username); } }
true
b8bc34896d2272347efaeec3faf277e15f1ff042
Java
albavi1718daw2/M6UF1Act3
/Programa.java
ISO-8859-1
1,611
4
4
[]
no_license
import java.io.IOException; import java.util.Scanner; public class Programa { public static void main(String[] args) throws IOException { // Llamamos al men menu(); } public static void menu() throws IOException { Scanner teclado = new Scanner(System.in); System.out.println("Elige una opcion: "); System.out.println("--------------------------"); System.out.println("1) Guardar persona"); System.out.println("2) Leer todas las fichas"); System.out.println("3) Consultar segn el ndice"); System.out.println("4) Salir"); int opcion = teclado.nextInt(); // Llamamos al mtodo que hace la ejecucin segn // lo que elija el usuario opcionElegida(opcion); } public static void opcionElegida(int opcion) throws IOException { switch (opcion) { case 1: // Guardamos las personas segn los campos que nos diga el usuario EscriuFitxerAleatori.escriure(); System.out.println("Persona escrita de forma correcta."); System.out.println(" "); menu(); break; case 2: // Leemos todas las fichas de las personas// Guardamos las personas segn los campos que nos diga el usuario LlegirFitxerAleatori.llegir(); System.out.println(" "); menu(); break; case 3: // Consultamos segn el ndice ConsultarFitxerAleatori.consultar(); System.out.println(" "); menu(); break; case 4: // Salimos System.out.println("Has salido correctamente."); break; default: System.out.println("Has elegido una opcin incorrecta."); menu(); break; } } }
true
34ebc9dd4baeb1c05c30b1e28e73de25e4f5b128
Java
adhamalaa111/StepView
/stepview/src/main/java/com/baoyachi/stepview/HorizontalStepView.java
UTF-8
7,203
2.21875
2
[ "Apache-2.0" ]
permissive
package com.baoyachi.stepview; import android.content.Context; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.baoyachi.stepview.bean.StepBean; import java.util.ArrayList; import java.util.List; /** * 日期:16/6/22 15:47 * <p/> * 描述:StepView */ public class HorizontalStepView extends LinearLayout implements HorizontalStepsViewIndicator.OnDrawIndicatorListener { private RelativeLayout mTextContainer; private List<TextView> mTextViews = new ArrayList<>(); private HorizontalStepsViewIndicator mStepsViewIndicator; private List<StepBean> mStepBeanList; private int mUnComplectedTextColor = ContextCompat.getColor(getContext(), R.color.uncompleted_text_color);//定义默认未完成文字的颜色; private int mComplectedTextColor = ContextCompat.getColor(getContext(), android.R.color.white);//定义默认完成文字的颜色; private int mTextSize = 14;//default textSize public HorizontalStepView(Context context) { this(context, null); } public HorizontalStepView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public HorizontalStepView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { View rootView = LayoutInflater.from(getContext()).inflate(R.layout.widget_horizontal_stepsview, this); mStepsViewIndicator = (HorizontalStepsViewIndicator) rootView.findViewById(R.id.steps_indicator); mStepsViewIndicator.setOnDrawListener(this); mTextContainer = (RelativeLayout) rootView.findViewById(R.id.rl_text_container); } /** * 设置显示的文字 * * @param stepsBeanList * @return */ public HorizontalStepView setStepViewTexts(List<StepBean> stepsBeanList) { mStepBeanList = stepsBeanList; mStepsViewIndicator.setStepNum(mStepBeanList); createTextViews(); return this; } /** * 设置未完成文字的颜色 * * @param unComplectedTextColor * @return */ public HorizontalStepView setStepViewUnComplectedTextColor(int unComplectedTextColor) { mUnComplectedTextColor = unComplectedTextColor; return this; } /** * 设置完成文字的颜色 * * @param complectedTextColor * @return */ public HorizontalStepView setStepViewComplectedTextColor(int complectedTextColor) { this.mComplectedTextColor = complectedTextColor; return this; } /** * 设置StepsViewIndicator未完成线的颜色 * * @param unCompletedLineColor * @return */ public HorizontalStepView setStepsViewIndicatorUnCompletedLineColor(int unCompletedLineColor) { mStepsViewIndicator.setUnCompletedLineColor(unCompletedLineColor); return this; } /** * 设置StepsViewIndicator完成线的颜色 * * @param completedLineColor * @return */ public HorizontalStepView setStepsViewIndicatorCompletedLineColor(int completedLineColor) { mStepsViewIndicator.setCompletedLineColor(completedLineColor); return this; } /** * 设置StepsViewIndicator默认图片 * * @param defaultIcon */ public HorizontalStepView setStepsViewIndicatorDefaultIcon(Drawable defaultIcon) { mStepsViewIndicator.setDefaultIcon(defaultIcon); return this; } /** * 设置StepsViewIndicator已完成图片 * * @param completeIcon */ public HorizontalStepView setStepsViewIndicatorCompleteIcon(Drawable completeIcon) { mStepsViewIndicator.setCompleteIcon(completeIcon); return this; } /** * 设置StepsViewIndicator正在进行中的图片 * * @param attentionIcon */ public HorizontalStepView setStepsViewIndicatorAttentionIcon(Drawable attentionIcon) { mStepsViewIndicator.setAttentionIcon(attentionIcon); return this; } /** * set textSize * * @param textSize * @return */ public HorizontalStepView setTextSize(int textSize) { if(textSize > 0) { mTextSize = textSize; } return this; } @Override public void ondrawIndicator() { updateStepTexts(); } private void createTextViews() { if (mStepBeanList != null) { int viewCount = mTextViews.size(); int beanCount = mStepBeanList.size(); int delta = viewCount - beanCount; if (beanCount == 0) { mTextContainer.removeAllViews(); mTextViews.clear(); } else if (delta < 0) { LayoutInflater inflater = LayoutInflater.from(getContext()); for (int i = viewCount; i < beanCount; i++) { TextView t = (TextView) inflater.inflate(R.layout.widget_setpsview_text_item, mTextContainer, false); mTextContainer.addView(t); mTextViews.add(t); } } else if (delta > 0) { mTextContainer.removeViews(beanCount, delta); mTextViews.removeAll(mTextViews.subList(beanCount, viewCount)); } } } private void updateStepTexts() { List<Float> complectedXPosition = mStepsViewIndicator.getCircleCenterPointPositionList(); if (mStepBeanList != null && complectedXPosition != null && complectedXPosition.size() > 0) { if (mStepBeanList.size() != mTextViews.size()) { return; } for (int i = 0; i < mStepBeanList.size(); i++) { StepBean bean = mStepBeanList.get(i); TextView t = mTextViews.get(i); t.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTextSize); t.setText(bean.getName()); int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); t.measure(spec, spec); int measuredWidth = t.getMeasuredWidth(); t.setX(complectedXPosition.get(i) - measuredWidth / 2); switch (bean.getState()) { case StepBean.STEP_COMPLETED: // fall through case StepBean.STEP_UNDO: t.setTypeface(null, Typeface.NORMAL); t.setTextColor(mUnComplectedTextColor); break; case StepBean.STEP_CURRENT: t.setTypeface(null, Typeface.BOLD); t.setTextColor(mComplectedTextColor); break; } } mTextContainer.requestLayout(); } } }
true
0bbdd4d5ed002d9fb5e7ea29ed74feefee115d6f
Java
cazous/ProjetoPersonalExpenses
/PersonalExpenses/src/crud/InserirDados.java
ISO-8859-1
815
2.5
2
[]
no_license
package crud; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.swing.JOptionPane; import jdbc.FabricaConexao; public class InserirDados { public void inserirDAO(String _nome, float _valor, int _categoria) { Connection conexao; try { conexao = FabricaConexao.getConexao(); String sql = "INSERT INTO tb_expenses (cl_nome, cl_valor, cl_categoria) VALUES (?,?,?)"; PreparedStatement stmt = conexao.prepareStatement(sql); stmt.setString(1, _nome); stmt.setFloat(2, _valor); stmt.setInt(3, _categoria); //AAAA-MM-DD hh:mm:ss //stmt.setString(4, data); stmt.execute(); } catch (SQLException e) { JOptionPane.showConfirmDialog(null, "Erro de insero"); } } }
true
191fe375a0ba981d49a427b5c119ad49670e54e9
Java
stevejia/game
/distribute-game-backend/distribute-game-service/src/main/java/com/gongyu/service/distribute/game/model/dto/PigGoodsResultDto.java
UTF-8
3,762
2.125
2
[]
no_license
package com.gongyu.service.distribute.game.model.dto; import com.gongyu.snowcloud.framework.data.mybatis.BaseEntity; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.math.BigDecimal; import java.util.Date; /** * @author zhaoQiXing * @version 1.0 * @date 2020/6/28 15:48 */ @Data public class PigGoodsResultDto extends BaseEntity implements Comparable<PigGoodsResultDto> { @ApiModelProperty(value = "级别名称", dataType = "String") private String goodsName; @ApiModelProperty(value = "最小价值", dataType = "BigDecimal") private BigDecimal smallPrice; @ApiModelProperty(value = "最大价值", dataType = "BigDecimal") private BigDecimal largePrice; @ApiModelProperty(value = "领养开始时间", dataType = "Date") // @DateTimeFormat(pattern = "HH:mm:ss") private Date startTime; @ApiModelProperty(value = "领养结束时间", dataType = "Date") // @DateTimeFormat(pattern = "HH:mm:ss") private Date endTime; @ApiModelProperty(value = "领养开始时间", dataType = "Date") private Date secondStartTime; @ApiModelProperty(value = "领养结束时间", dataType = "Date") private Date secondEndTime; @ApiModelProperty(value = "预约数量", dataType = "Integer") private Integer reservation; @ApiModelProperty(value = "领养(抢)能量", dataType = "Integer") private Integer adoptiveEnergy; @ApiModelProperty(value = "合约收益天数", dataType = "Integer") private Integer contractDays; @ApiModelProperty(value = "合约收益比例", dataType = "BigDecimal") private BigDecimal incomeRatio; @ApiModelProperty(value = "可挖PIG数量", dataType = "Integer") private Integer pigCurrency; @ApiModelProperty(value = "可挖DOGE数量", dataType = "Integer") private Integer dogeMoney; @ApiModelProperty(value = "图片", dataType = "String") private String images; @ApiModelProperty(value = "0未开奖1已开奖", dataType = "Integer") private Integer todayIsOpen; @ApiModelProperty(value = "是否上架,0默认为不上架,1为上架", dataType = "Integer") private Integer isDisplay; @ApiModelProperty(value = "解决不能实时开奖的处理 今天是否锁场次 1锁0开", dataType = "Integer") private Integer isLock; @ApiModelProperty(value = "", dataType = "Integer") private Integer resetTime; @ApiModelProperty(value = "重置时间", dataType = "Integer") private Integer gameResetTime; @ApiModelProperty(value = "开奖设置类型;0默认一天一次,1一天两次", dataType = "Integer") private Integer gameOpenType; @ApiModelProperty(value = "是否为合成宠物", dataType = "Integer") private Integer isSpell; @ApiModelProperty(value = "", dataType = "String") private String images2; @ApiModelProperty(value = "相同金额的概率", dataType = "Integer") private Integer probability; @ApiModelProperty(value = "金额分类ID", dataType = "Integer") private Integer moneyCategoryId; @ApiModelProperty(value = "可分裂精灵数量", dataType = "Integer") private Integer splitNum; @ApiModelProperty(value = "状态:1 修炼中,2 预约,3 抢购 4 已预约 5 暂未开放 6 待领养") private Integer pigStatus; @ApiModelProperty(value = "订单编号") private String orderNo; @ApiModelProperty(value = "选中策略值 优先选中最大值",dataType = "Long") private Long openms; @Override public int compareTo(PigGoodsResultDto o) { if(openms > o.getOpenms()){ return 1; }else if(openms < o.getOpenms()){ return -1; }else{ return 0; } } }
true
3afe573172eeb6036de39d7b601300611ae432af
Java
BingBingHe/IT-Learning
/LeetCode/LeetCode/src/ContinuousSubarraySum_523/Solution.java
UTF-8
694
3.15625
3
[]
no_license
package ContinuousSubarraySum_523; import java.util.HashMap; import java.util.Map; public class Solution { public static void main(String[] args) { int[] nums = { 0, 0, 0 }; System.out.println(new Solution().checkSubarraySum(nums, 0)); Map<Integer, Integer> map = new HashMap<Integer, Integer>(){{put(0,22);}}; System.out.println(map.get(0)); } public boolean checkSubarraySum(int[] nums, int k) { boolean max = false; int size = nums.length; for (int i = 0; i < size; i++) { int sum = nums[i]; int j = i + 1; while (j < size) { sum += nums[j++]; if ((k == 0 && sum == 0) || (k != 0 && sum % k == 0)) { return true; } } } return false; } }
true
7a9f52a20515dcc29669f3c3fe91e6358f1f8ed6
Java
kimjonghos/boot-jpa-gradle-handlebars
/src/main/java/com/example/webservice/dto/PostsDetailResponseDto.java
UTF-8
1,028
2.40625
2
[]
no_license
package com.example.webservice.dto; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import com.example.webservice.domain.Posts; import lombok.Getter; import lombok.ToString; @ToString @Getter public class PostsDetailResponseDto { private Long id; private String title; private String author; private String modifiedDate; private String content; private List<CommentsListResponseDto> comments; public PostsDetailResponseDto(Posts entity,List<CommentsListResponseDto> comments) { this.id=entity.getId(); this.title=entity.getTitle(); this.author=entity.getAuthor(); this.modifiedDate=toStringDateTime(entity.getModifiedDate()); this.content=entity.getContent(); this.comments=comments; } public String toStringDateTime(LocalDateTime localDateTime) { DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); return Optional.ofNullable(localDateTime) .map(formatter::format) .orElse(""); } }
true
7b7e5b3bccef8639b7b095faad2451b8b2fc59d4
Java
samiromic/interaktivni_raspored
/InteraktivniRaspored/src/modeli/Rezervacija_.java
UTF-8
2,297
2.578125
3
[]
no_license
package modeli; import java.text.SimpleDateFormat; import java.util.Date; public class Rezervacija_ { int sifRezervacija; Date datumRezervacija; String tipRezervacije; int satRezervacijeH; int satRezervacijeMin; int satRezervacijeKrajH; int satRezervacijeKrajMin; int sifPredmet; int sifSala; int sifNastavnik; public Rezervacija_() { this.sifRezervacija = -1; this.datumRezervacija = new Date(); this.tipRezervacije = ""; this.satRezervacijeH = -1; this.satRezervacijeMin = -1; this.satRezervacijeKrajH = -1; this.satRezervacijeKrajMin = -1; this.sifPredmet = -1; this.sifSala = -1; this.sifNastavnik = -1; } public int getSifRezervacija() { return sifRezervacija; } public Date getDatumRezervacija() { return datumRezervacija; } public String getTipRezervacije() { return tipRezervacije; } public int getSatRezervacijeH() { return satRezervacijeH; } public int getSatRezervacijeMin() { return satRezervacijeMin; } public int getSatRezervacijeKrajH() { return satRezervacijeKrajH; } public int getSatRezervacijeKrajMin() { return satRezervacijeKrajMin; } public int getSifPredmet() { return sifPredmet; } public int getSifSala() { return sifSala; } public int getSifNastavnik() { return sifNastavnik; } public void setSifRezervacija(int sifRezervacija) { this.sifRezervacija = sifRezervacija; } public void setDatumRezervacija(Date datumRezervacija) { this.datumRezervacija = datumRezervacija; } public void setTipRezervacije(String tipRezervacije) { this.tipRezervacije = tipRezervacije; } public void setSatRezervacijeH(int satRezervacijeH) { this.satRezervacijeH = satRezervacijeH; } public void setSatRezervacijeMin(int satRezervacijeMin) { this.satRezervacijeMin = satRezervacijeMin; } public void setSatRezervacijeKrajH(int satRezervacijeKrajH) { this.satRezervacijeKrajH = satRezervacijeKrajH; } public void setSatRezervacijeKrajMin(int satRezervacijeKrajMin) { this.satRezervacijeKrajMin = satRezervacijeKrajMin; } public void setSifPredmet(int sifPredmet) { this.sifPredmet = sifPredmet; } public void setSifSala(int sifSala) { this.sifSala = sifSala; } public void setSifNastavnik(int sifNastavnik) { this.sifNastavnik = sifNastavnik; } }
true
a021a5e9420f7d54f61ae5a6f911878d83c470b7
Java
PoisenFox/Bic-Biome-Craft-1.7.10
/src/main/java/com/tung/bicbiomecraft/SkinkiumAxe.java
UTF-8
188
2.09375
2
[]
no_license
package com.tung.bicbiomecraft; import net.minecraft.item.ItemAxe; public class SkinkiumAxe extends ItemAxe{ protected SkinkiumAxe(ToolMaterial material) { super(material); } }
true
9dbfaa2b7c7eeb3af6a1f5678b6137dc944448ee
Java
FILSSE/nationalrailways
/nationalrailways/src/main/java/businesslogic/PayCardController.java
UTF-8
619
2.265625
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package businesslogic; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import services.DatabaseTemplate; /** * * @author AndreiM */ public class PayCardController { private final DatabaseTemplate databaseTemplate; public PayCardController(DatabaseTemplate databaseTemplate) { this.databaseTemplate = databaseTemplate; } public boolean checkCard(String cnp,int pin){ return this.databaseTemplate.checkCard(cnp, pin); } }
true
8c569c26f242a7ad130fde2e374f2917d638d744
Java
pedalv/JavaApp
/CorePlatform/src/main/java/no/the/core/platform/collections/queues/b_priority_queues/PriorityHelpDeskJava8.java
UTF-8
1,755
3.234375
3
[]
no_license
package no.the.core.platform.collections.queues.b_priority_queues; import no.the.core.platform.collections.model.Category; import no.the.core.platform.collections.model.Customer; import no.the.core.platform.collections.model.Enquiry; import java.util.ArrayDeque; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue; import static java.util.Comparator.comparing; public class PriorityHelpDeskJava8 { /* private static final Comparator<Enquiry> BY_CATEGORY = new Comparator<Enquiry>() { public int compare(final Enquiry o1, final Enquiry o2) { return o1.getCategory().compareTo(o2.getCategory()); } }; // Java 7 */ private static final Comparator<Enquiry> BY_CATEGORY = comparing(Enquiry::getCategory); //priority by category: OUT [Jill, Mary, Jack] private Queue<Enquiry> enquiries = new PriorityQueue<>(BY_CATEGORY); //no priority: OUT [Jack, Jill, Mary] //private Queue<Enquiry> enquiries = new ArrayDeque<>(); public boolean enquire(final Customer customer, final Category type) { return enquiries.offer(new Enquiry(customer, type)); } public void processAllEnquires() { Enquiry enquiry; while ((enquiry = enquiries.poll()) != null) { enquiry.getCustomer().reply("Have you tried turning it off and on again?"); } } public static void main(String[] args) { PriorityHelpDeskJava8 helpDesk = new PriorityHelpDeskJava8(); helpDesk.enquire(Customer.JACK, Category.PHONE); helpDesk.enquire(Customer.JILL, Category.PRINTER); helpDesk.enquire(Customer.MARY, Category.COMPUTER); helpDesk.processAllEnquires(); } }
true
3c0c49ce22b357c61a460d775599fff086634f37
Java
pmanzoni/GRCBoxv2
/GrcBoxLib/src/es/upv/grc/grcbox/androlib/GrcBoxDatagramSocket.java
UTF-8
6,260
2.390625
2
[]
no_license
package es.upv.grc.grcbox.androlib; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.DatagramSocketImpl; import java.net.InetAddress; import java.net.SocketAddress; import java.net.SocketException; import java.nio.channels.DatagramChannel; import es.upv.grc.grcbox.common.GrcBoxRule; public class GrcBoxDatagramSocket extends DatagramSocket { private GrcBoxClientService owner; private GrcBoxRule rule; private DatagramSocket socket; public GrcBoxDatagramSocket(GrcBoxClientService owner, GrcBoxRule rule, DatagramSocket socket) throws SocketException { super(); this.owner = owner; this.rule = rule; this.socket = socket; } /** * @param localAddr * @throws SocketException * @see java.net.DatagramSocket#bind(java.net.SocketAddress) */ public void bind(SocketAddress localAddr) throws SocketException { socket.bind(localAddr); } /** * * @see java.net.DatagramSocket#close() */ public void close() { socket.close(); owner.removeRule(rule); } /** * @param peer * @throws SocketException * @see java.net.DatagramSocket#connect(java.net.SocketAddress) */ public void connect(SocketAddress peer) throws SocketException { socket.connect(peer); } /** * @param address * @param port * @see java.net.DatagramSocket#connect(java.net.InetAddress, int) */ public void connect(InetAddress address, int port) { socket.connect(address, port); } /** * * @see java.net.DatagramSocket#disconnect() */ public void disconnect() { socket.disconnect(); } /** * @param o * @return * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { return socket.equals(o); } /** * @return * @throws SocketException * @see java.net.DatagramSocket#getBroadcast() */ public boolean getBroadcast() throws SocketException { return socket.getBroadcast(); } /** * @return * @see java.net.DatagramSocket#getChannel() */ public DatagramChannel getChannel() { return socket.getChannel(); } /** * @return * @see java.net.DatagramSocket#getInetAddress() */ public InetAddress getInetAddress() { return socket.getInetAddress(); } /** * @return * @see java.net.DatagramSocket#getLocalAddress() */ public InetAddress getLocalAddress() { return socket.getLocalAddress(); } /** * @return * @see java.net.DatagramSocket#getLocalPort() */ public int getLocalPort() { return socket.getLocalPort(); } /** * @return * @see java.net.DatagramSocket#getLocalSocketAddress() */ public SocketAddress getLocalSocketAddress() { return socket.getLocalSocketAddress(); } /** * @return * @see java.net.DatagramSocket#getPort() */ public int getPort() { return socket.getPort(); } /** * @return * @throws SocketException * @see java.net.DatagramSocket#getReceiveBufferSize() */ public int getReceiveBufferSize() throws SocketException { return socket.getReceiveBufferSize(); } /** * @return * @see java.net.DatagramSocket#getRemoteSocketAddress() */ public SocketAddress getRemoteSocketAddress() { return socket.getRemoteSocketAddress(); } /** * @return * @throws SocketException * @see java.net.DatagramSocket#getReuseAddress() */ public boolean getReuseAddress() throws SocketException { return socket.getReuseAddress(); } /** * @return * @throws SocketException * @see java.net.DatagramSocket#getSendBufferSize() */ public int getSendBufferSize() throws SocketException { return socket.getSendBufferSize(); } /** * @return * @throws SocketException * @see java.net.DatagramSocket#getSoTimeout() */ public int getSoTimeout() throws SocketException { return socket.getSoTimeout(); } /** * @return * @throws SocketException * @see java.net.DatagramSocket#getTrafficClass() */ public int getTrafficClass() throws SocketException { return socket.getTrafficClass(); } /** * @return * @see java.lang.Object#hashCode() */ public int hashCode() { return socket.hashCode(); } /** * @return * @see java.net.DatagramSocket#isBound() */ public boolean isBound() { return socket.isBound(); } /** * @return * @see java.net.DatagramSocket#isClosed() */ public boolean isClosed() { return socket.isClosed(); } /** * @return * @see java.net.DatagramSocket#isConnected() */ public boolean isConnected() { return socket.isConnected(); } /** * @param pack * @throws IOException * @see java.net.DatagramSocket#receive(java.net.DatagramPacket) */ public void receive(DatagramPacket pack) throws IOException { socket.receive(pack); } /** * @param pack * @throws IOException * @see java.net.DatagramSocket#send(java.net.DatagramPacket) */ public void send(DatagramPacket pack) throws IOException { socket.send(pack); } /** * @param broadcast * @throws SocketException * @see java.net.DatagramSocket#setBroadcast(boolean) */ public void setBroadcast(boolean broadcast) throws SocketException { socket.setBroadcast(broadcast); } /** * @param size * @throws SocketException * @see java.net.DatagramSocket#setReceiveBufferSize(int) */ public void setReceiveBufferSize(int size) throws SocketException { socket.setReceiveBufferSize(size); } /** * @param reuse * @throws SocketException * @see java.net.DatagramSocket#setReuseAddress(boolean) */ public void setReuseAddress(boolean reuse) throws SocketException { socket.setReuseAddress(reuse); } /** * @param size * @throws SocketException * @see java.net.DatagramSocket#setSendBufferSize(int) */ public void setSendBufferSize(int size) throws SocketException { socket.setSendBufferSize(size); } /** * @param timeout * @throws SocketException * @see java.net.DatagramSocket#setSoTimeout(int) */ public void setSoTimeout(int timeout) throws SocketException { socket.setSoTimeout(timeout); } /** * @param value * @throws SocketException * @see java.net.DatagramSocket#setTrafficClass(int) */ public void setTrafficClass(int value) throws SocketException { socket.setTrafficClass(value); } /** * @return * @see java.lang.Object#toString() */ public String toString() { return socket.toString(); } }
true
63288e83a14897a6b2da196e9a38c2245c8344fa
Java
shift02/SextiarySector2
/src/main/java/shift/sextiarysector/SSEvents.java
UTF-8
2,560
1.835938
2
[]
no_license
package shift.sextiarysector; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.common.MinecraftForge; import shift.sextiarysector.api.event.VanillaFoodHandler; import shift.sextiarysector.event.AchievementEventHandler; import shift.sextiarysector.event.AgricultureClientEventHandler; import shift.sextiarysector.event.AgricultureEventHandler; import shift.sextiarysector.event.ClientEventHandler; import shift.sextiarysector.event.CommonEventHandler; import shift.sextiarysector.event.HUDEventHandler; import shift.sextiarysector.event.OreDictionaryEventHandler; import shift.sextiarysector.event.PlayerStatusEventHandler; import shift.sextiarysector.event.PlayerUnitEventHandler; import shift.sextiarysector.event.WorldEventHandler; import shift.sextiarysector.gui.tab.TabManager; import shift.sextiarysector.player.EntityPlayerManager; public class SSEvents { public static void preInit(FMLPreInitializationEvent event) { MinecraftForge.EVENT_BUS.register(new CommonEventHandler()); MinecraftForge.EVENT_BUS.register(EntityPlayerManager.instance); FMLCommonHandler.instance().bus().register(EntityPlayerManager.instance); if (event.getSide().isClient()) { MinecraftForge.EVENT_BUS.register(new HUDEventHandler()); } MinecraftForge.EVENT_BUS.register(new PlayerStatusEventHandler()); FMLCommonHandler.instance().bus().register(new PlayerStatusEventHandler()); MinecraftForge.EVENT_BUS.register(new PlayerUnitEventHandler()); MinecraftForge.EVENT_BUS.register(new VanillaFoodHandler()); MinecraftForge.EVENT_BUS.register(new OreDictionaryEventHandler()); if (event.getSide().isClient()) { ClientEventHandler e = new ClientEventHandler(); MinecraftForge.EVENT_BUS.register(e); FMLCommonHandler.instance().bus().register(e); } if (event.getSide().isClient()) { TabManager.initEvent(); } if (event.getSide().isClient()) { MinecraftForge.EVENT_BUS.register(new AgricultureClientEventHandler()); } MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); MinecraftForge.EVENT_BUS.register(new WorldEventHandler()); MinecraftForge.ORE_GEN_BUS.register(new WorldEventHandler()); MinecraftForge.EVENT_BUS.register(new AchievementEventHandler()); //MinecraftForge.EVENT_BUS.register(new SantaEventHandler()); } }
true
7ddbb0af4f61d1fd132459c0fa5ac2b0053b84b9
Java
cuba-platform/restapi
/test/restapi-demo/modules/global/src/com/haulmont/rest/demo/core/entity/identity/IdentityCustomer.java
UTF-8
787
1.78125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2008-2016 Haulmont. All rights reserved. * Use is subject to license terms, see http://www.cuba-platform.com/commercial-software-license for details. */ package com.haulmont.rest.demo.core.entity.identity; import com.haulmont.chile.core.annotations.NamePattern; import com.haulmont.cuba.core.entity.BaseIdentityIdEntity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity(name = "ref$IdentityCustomer") @Table(name = "REF_IK_CUSTOMER") @NamePattern("%s|name") public class IdentityCustomer extends BaseIdentityIdEntity { @Column(name = "NAME") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
768ad1e34a91a6956b2fc4d067868aafc61d0d16
Java
Alexander-Berg/serenity-core
/serenity-junit5/src/test/java/net/serenitybdd/junit5/samples/integration/WhenRunningANestedTest.java
UTF-8
1,571
2.265625
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
package net.serenitybdd.junit5.samples.integration; import net.serenitybdd.junit5.AbstractTestStepRunnerTest; import net.serenitybdd.junit5.TestLauncher; import net.thucydides.core.model.TestOutcome; import net.thucydides.core.steps.StepEventBus; import net.thucydides.samples.SamplePassingNonWebScenario; import org.junit.jupiter.api.Test; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; public class WhenRunningANestedTest { @Test public void the_test_runner_records_the_name_of_the_test_scenario() { TestLauncher.runTestForClass(JUnit5NestedExampleTest.class); List<TestOutcome> executedScenarios = StepEventBus.getEventBus().getBaseStepListener().getTestOutcomes(); assertThat(executedScenarios.size(), equalTo(3)); assertThat(inTheTestOutcomes(executedScenarios).theOutcomeFor("sampleTestForMethodA").getTitle(), is("Example test for method A")); assertThat(inTheTestOutcomes(executedScenarios).theOutcomeFor("sampleTestForMethodB").getTitle(), is("Sample test for method b")); assertThat(inTheTestOutcomes(executedScenarios).theOutcomeFor("sampleTestForMethodAOuterClass").getTitle(), is("Example test for method A outerClass")); } public AbstractTestStepRunnerTest.TestOutcomeChecker inTheTestOutcomes(List<TestOutcome> testOutcomes) { return new AbstractTestStepRunnerTest.TestOutcomeChecker(testOutcomes); } }
true
054a18d3847e7580a3e08c91aacdf53d48793f9b
Java
iamdaiyuan/App
/App/.svn/pristine/05/054a18d3847e7580a3e08c91aacdf53d48793f9b.svn-base
UTF-8
625
1.75
2
[]
no_license
package com.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.junl.apps.service.users.IUsers; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/spring/applicationContext_db.xml", "/spring/applicationContext.xml" }) public class UserTest { @Autowired private IUsers service; @Test public void test() throws Exception { System.out.println(service.doLogin()); } }
true
74bf4286ce77eee6fe8465cc7016c532f977764e
Java
kudrys/WirtualnaJava
/src/Wilk.java
UTF-8
170
1.960938
2
[]
no_license
/** * Created by RYchu on 2015-12-29. */ public class Wilk extends Zwierze { public Wilk(){ label = 'W'; sila = 9; inicjatywa = 5; } }
true
5ca32862e731bb7652345c11b2dc1e21e86dcb87
Java
TrongCanh/PTPMCN-111592
/src/main/java/com/sapo/repository/AutoPriceRepository.java
UTF-8
385
1.921875
2
[]
no_license
package com.sapo.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.sapo.model.AutoPrice; @Repository public interface AutoPriceRepository extends JpaRepository<AutoPrice, Long> { List<AutoPrice> findByItemid(Long id); List<AutoPrice> findByItemidOrderByIdDesc(Long id); }
true
1d14180b07aa9377e7232275124aaec2ed9c5a54
Java
douglascraigschmidt/CS891
/assignment1c/movies-ex/src/main/java/edu/vandy/recommender/movies/server/MoviesApplication.java
UTF-8
2,341
2.6875
3
[]
no_license
package edu.vandy.recommender.movies.server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration; import org.springframework.boot.web.embedded.tomcat.TomcatProtocolHandlerCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.support.TaskExecutorAdapter; import java.util.List; import java.util.concurrent.Executors; /** * This class provides the entry point for the MoviesApplication * microservice, whose methods return a {@link List} of objects * containing information about movies. It also configures the * use of Java 19 virtual threads to process incoming HTTP requests. * * The {@code @SpringBootApplication} annotation enables apps to use * automatic configuration, component scan, and to define extra * configurations on their "application" class. * * The {@code @ComponentnScan} annotation instructs Spring to scan * components in the "edu.vandy.recommender.movies" package. */ @SpringBootApplication @ComponentScan("edu.vandy.recommender.movies") public class MoviesApplication { /** * The static main() entry point runs this Spring application. */ public static void main(String[] args) { // Launch this application. SpringApplication.run(MoviesApplication.class, args); } /** * Configure the use of Java virtual threads to handle all * incoming HTTP requests. */ @Bean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME) public AsyncTaskExecutor asyncTaskExecutor() { return new TaskExecutorAdapter(Executors .newVirtualThreadPerTaskExecutor()); } /** * Customize the ProtocolHandler on the TomCat Connector to * use Java virtual threads to handle all incoming HTTP requests. */ @Bean public TomcatProtocolHandlerCustomizer<?> protocolHandlerVirtualThreadExecutorCustomizer() { return protocolHandler -> { protocolHandler .setExecutor(Executors.newVirtualThreadPerTaskExecutor()); }; } }
true
97dbd042e240770f6be3c7eedadba79418f863ee
Java
MHFethi/BookView
/app/src/main/java/hf/app/bookview/dao/ClientManager.java
UTF-8
3,591
2.6875
3
[]
no_license
package hf.app.bookview.dao; import android.content.Context; import android.util.Log; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.stmt.QueryBuilder; import java.sql.SQLException; import java.util.List; import hf.app.bookview.database.BddManager; import hf.app.bookview.model.Client; public class ClientManager implements IDao<Client> { private static final String TAG = "ClientManager"; // Il nous faut une reference a la bdd sur laquel il peut travailler BddManager database; // On créer le dao generique de BdManager pour recuperer les methode crud general Dao<Client,Integer>cDao; public ClientManager(Context context){ database = new BddManager(context); try { cDao = database.getDao(Client.class); } catch (SQLException e) { Log.i(TAG, "ClientManager: " + e.getMessage()); } } @Override public List<Client> getAll() { // queryForAll permet de recuperer une liste de donnée try { return cDao.queryForAll(); } catch (SQLException e) { Log.i(TAG, "ClientManager: " + e.getMessage()); } return null; } @Override public Client find(int id) { // queryForId permet recuperer une donnée par ID try { return cDao.queryForId(id); } catch (SQLException e) { Log.i(TAG, "ClientManager: " + e.getMessage()); } return null; } @Override public boolean add(Client item) { // create permet d'aajouter une donnée try { return cDao.create(item)>0; } catch (SQLException e) { Log.i(TAG, "ClientManager: " + e.getMessage()); } return false; } @Override public boolean update(Client item) { // update permet de modifier une donnée try { return cDao.update(item)>0; } catch (SQLException e) { Log.i(TAG, "ClientManager: " + e.getMessage()); } return false; } @Override public boolean delete(Client item) { // delete permet de modifier une donnée try { return cDao.delete(item)>0; } catch (SQLException e) { Log.i(TAG, "ClientManager: " + e.getMessage()); } return false; } @Override public boolean delete(int id) { try { Client c = find(id); if (c!=null){ return cDao.delete(c)>0; } } catch (SQLException e) { Log.i(TAG, "ClientManager: " + e.getMessage()); } return false; } /** * custom queries */ public Client find(String login) { // On prepare une requete // En precisant le type qu'on veux (ici User) QueryBuilder<Client, Integer> qb = cDao.queryBuilder(); Client client=null; try { //eq() = egal à // and() = AND .. qb.where().eq("login", login); client = qb.queryForFirst(); } catch (SQLException e) { e.printStackTrace(); } return client; } public Client find(String login, String password) { QueryBuilder<Client, Integer> qb = cDao.queryBuilder(); Client client=null; try { qb.where().eq("login", login).and().eq("password", password); client = qb.queryForFirst(); } catch (SQLException e) { e.printStackTrace(); } return client; } }
true
86d3c49cf2c858d9a51cd5fda9692a744a866d6d
Java
VivekGarg1/JdbcBatchProcessingDemo
/JdbcBatchProcessingDemo/src/com/home/client/PreparedStatementBatchClientTest.java
UTF-8
821
2.640625
3
[]
no_license
package com.home.client; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; import com.home.util.JdbcUtil; public class PreparedStatementBatchClientTest { public static void main(String[] args) { String SQLUPDATE="update employee_table set salary=? where employee_id=?"; try(Connection connection=JdbcUtil.getConnection(); PreparedStatement ps=connection.prepareStatement(SQLUPDATE)){ ps.setDouble(1, 25000.0); ps.setInt(2, 1); ps.addBatch(); ps.setDouble(1, 20000.0); ps.setInt(2, 2); ps.addBatch(); ps.setDouble(1, 30000.0); ps.setInt(2, 20); ps.addBatch(); int[] executeBatch = ps.executeBatch(); for (int i : executeBatch) { System.out.println(i); } } catch (Exception e) { e.printStackTrace(); } } }
true
17ec7e6366006c5a787d56998a094c196b3160ae
Java
google-code/android-ws-client
/AndroidWSProxyClient-old/src-ws/org/jinouts/transport/HttpTransportUtil.java
UTF-8
2,130
2.171875
2
[]
no_license
/** * Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0.html * * */ package org.jinouts.transport; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; /** * @author asraf * asraf344@gmail.com * */ public class HttpTransportUtil { public static String sendRequestAndGetRespXML ( String reqXMLString, String url ) throws Exception { HttpPost post = new HttpPost ( url ); post.setEntity ( new StringEntity ( reqXMLString ) ); post.setHeader ( "Content-type", "text/xml; charset=UTF-8" ); HttpParams httpParameters = new BasicHttpParams ( ); HttpConnectionParams.setConnectionTimeout ( httpParameters, 5000 ); HttpConnectionParams.setSoTimeout ( httpParameters, 6000 ); /* * if (this.isDEBUG()) { Log.i(this.getClass().getSimpleName(), * "Request: " + envelope.toString()); } */ HttpClient client = new DefaultHttpClient ( httpParameters ); HttpResponse response = client.execute ( post ); int status = response.getStatusLine ( ).getStatusCode ( ); System.out.println ( "Status " + status ); System.out.println ( "WSInvocationHandler: " + "Status " + status ); InputStream is = response.getEntity ( ).getContent ( ); InputStreamReader isr = new InputStreamReader ( is ); BufferedReader br = new BufferedReader ( isr ); StringBuilder sb = new StringBuilder ( ); for ( String line = br.readLine ( ); line != null; line = br.readLine ( ) ) { sb.append ( line ); sb.append ( "\n" ); } String resp = sb.toString ( ); System.out.println ( "WSInvocationHandler: " + "Response: " + sb.toString ( ) ); br.close ( ); isr.close ( ); is.close ( ); return resp; } }
true
256c3b952d0e9c2290c1fa28e04fe798b93ef17b
Java
2020-Summer-Cohort/blog-java-mia
/src/main/java/org/wcci/blog/controllers/PostController.java
UTF-8
2,887
2.453125
2
[]
no_license
package org.wcci.blog.controllers; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.wcci.blog.entities.Author; import org.wcci.blog.entities.Category; import org.wcci.blog.entities.Post; import org.wcci.blog.entities.Hashtag; import org.wcci.blog.storage.AuthorStorage; import org.wcci.blog.storage.CategoryStorage; import org.wcci.blog.storage.PostStorage; import org.wcci.blog.storage.HashtagStorage; @Controller public class PostController { private PostStorage postStorage; private HashtagStorage hashtagStorage; private AuthorStorage authorStorage; private CategoryStorage categoryStorage; public PostController(PostStorage postStorage, HashtagStorage hashtagStorage, AuthorStorage authorStorage, CategoryStorage categoryStorage) { this.postStorage = postStorage; this.hashtagStorage = hashtagStorage; this.authorStorage = authorStorage; this.categoryStorage = categoryStorage; } @GetMapping("post/{postTitle}") public String showSinglePost(@PathVariable String postTitle, Model model) { model.addAttribute("post", postStorage.findPostByPostTitle(postTitle)); return "post-template"; } @PostMapping("/category/addPost") public String addAPost(String postTitle, String model, int year, String postBody, String name, String categoryName, String hashtagName){ Category categoryToAdd = categoryStorage.findCategoryByName(categoryName); Hashtag hashtagToAdd = new Hashtag(hashtagName); hashtagStorage.addAHashtagToPost(hashtagToAdd); Author authorToAdd = new Author(name); authorStorage.addAuthor(authorToAdd); Post postToAdd = new Post(postTitle, model, year, postBody, authorToAdd, categoryToAdd, hashtagToAdd); postStorage.addPost(postToAdd); return "redirect:/post/" + postTitle; } @PostMapping("/post/addHashtag") public String addHashTagToReview(String postTitle, String hashtagName){ if (hashtagStorage.findHashtagByHashtagName(hashtagName) != null) { Hashtag hashtagToAdd = hashtagStorage.findHashtagByHashtagName(hashtagName); Post post = postStorage.findPostByPostTitle(postTitle); post.addAHashtagToPost(hashtagToAdd); postStorage.addPost(post); return "redirect:/post/" + postTitle; } Hashtag hashtagToAdd = new Hashtag(hashtagName); hashtagStorage.addAHashtagToPost(hashtagToAdd); Post post = postStorage.findPostByPostTitle(postTitle); post.addAHashtagToPost(hashtagToAdd); postStorage.addPost(post); return "redirect:/post/" + postTitle; } }
true
66fb945455833acf42ed19eedb12009b496fdeb2
Java
asha-github/BlogSystem
/src/main/java/com/blog/biz/UserService.java
UTF-8
1,815
2.6875
3
[]
no_license
package com.blog.biz; import java.util.logging.Logger; import com.blog.api.BlogServiceException; import com.blog.api.IUserService; import com.blog.api.User; import com.blog.data.IUserDAO; import com.blog.data.JpaUserDAO; import com.blog.security.JWTTokenUtil; public class UserService implements IUserService { private static final Logger logger = Logger.getLogger(UserService.class.getSimpleName()); private IUserDAO dao = new JpaUserDAO(); @Override public void addUser(User user) { logger.info("\nNew user details received!!"); if (user == null || user.getUserName().trim().isEmpty()) { throw new BlogServiceException(BlogServiceException.BlogError.USER_NAME_EMPTY); } dao.addUser(user); logger.info( "\nNew user created with name - " + user.getUserName() + " with profile name " + user.getProfileName()); } @Override public void editUser(String userName, User user) { logger.info("\nRequest for user update received!!"); if (user == null || user.getPassword().trim().isEmpty()) { throw new BlogServiceException(BlogServiceException.BlogError.PASSWORD_EMPTY); } boolean isEditSuccessful = dao.editUser(userName, user); if (isEditSuccessful) { logger.info("\nBlog with ID - " + user.getUserName() + " is updated "); } else { throw new BlogServiceException(BlogServiceException.BlogError.USER_UPDATE_FAILED); } } @Override public User getUserDetails(String userName) { return dao.getUserDetails(userName); } @Override public String authenticateUser(User user) { String token = null; logger.info("\nAuthenticate request for user received!!"); if (dao.isValidUser(user)) { token = JWTTokenUtil.issueToken(user.getUserName()); } else { throw new BlogServiceException(BlogServiceException.BlogError.USER_NOT_FOUND); } return token; } }
true
18134d33ed19ffba7a647d7402723372d275abde
Java
Setes-eor/Eye-of-Ra-Java
/eye_of_ra/ResourceBar.java
UTF-8
4,428
2.375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eye_of_ra; import java.awt.Graphics; import java.util.ArrayList; import java.util.List; /** * * @author setes */ public class ResourceBar extends Entity{ // attributes of the class // BasicEntity be_inhabs; BasicEntity be_numbers; List<BasicEntity> lbe_Money; List<BasicEntity> lbe_Wood; List<BasicEntity> lbe_Brick; List<BasicEntity> lbe_Inhabs; int PanelElementCounter; int m_fCoAnf; int m_iCoWo; int m_iCoBr; int m_iCoIn; int m_iMoneyX; int m_iRY; int m_iInhabsX; int m_iInhabsY; int m_iWoodX, m_iWoodY; int m_iBrickX, m_iBrickY; int m_iSMoney; //constructor // public ResourceBar(String ref, String ref2, String data, String typ, int x, int y){ super(ref,x,y); be_inhabs = new BasicEntity(ref2, x, y + 45); m_iSMoney = 4; m_iMoneyX = 130; m_iInhabsX = 130; m_iInhabsY = 59; m_iWoodX = 280; m_iBrickX = 430; m_iRY = 14; lbe_Money = new ArrayList<BasicEntity>(); lbe_Wood = new ArrayList<BasicEntity>(); lbe_Brick = new ArrayList<BasicEntity>(); lbe_Inhabs = new ArrayList<BasicEntity>(); for (int i = 0; i < m_iSMoney; i++) { BasicEntity money = new BasicEntity(data + "Anzeigen/" + "Zahlen" + typ, m_iMoneyX, m_iRY); BasicEntity wood = new BasicEntity(data + "Anzeigen/" + "Zahlen" + typ, m_iWoodX, m_iRY); BasicEntity brick = new BasicEntity(data + "Anzeigen/" + "Zahlen" + typ, m_iBrickX, m_iRY); BasicEntity inhabs = new BasicEntity(data + "Anzeigen/" + "Zahlen" + typ, m_iInhabsX, m_iInhabsY); lbe_Money.add(money); lbe_Wood.add(wood); lbe_Brick.add(brick); lbe_Inhabs.add(inhabs); m_iMoneyX -= 20; m_iWoodX -= 20; m_iBrickX -= 20; m_iInhabsX -= 20; }// for }// constructor public void Draw(Graphics g, int money, int wood, int brick, int inhabs){ sp_sprite.Draw(g,(int) d_xPos,(int) d_yPos); be_inhabs.Draw(g); for (int i = 0; i < lbe_Money.size(); i++) { switch (i) { case (0): m_fCoAnf = money % 10; m_iCoWo = wood % 10; m_iCoBr = brick % 10; m_iCoIn = inhabs % 10; break; case (1): m_fCoAnf = (money % 100) / 10; m_iCoWo = (wood % 100) / 10; m_iCoBr = (brick % 100) / 10; m_iCoIn = (inhabs % 100) / 10; break; case (2): m_fCoAnf = (money % 1000) / 100; m_iCoWo = (wood % 1000) / 100; m_iCoBr = (brick % 1000) / 100; m_iCoIn = (inhabs % 1000) / 100; break; case (3): m_fCoAnf = (money % 10000) / 1000; m_iCoWo = (wood % 10000) / 1000; m_iCoBr = (brick % 10000) / 1000; m_iCoIn = (inhabs % 10000) / 1000; break; default: break; }// swich lbe_Money.get(i).sp_sprite.setSubImage(20 * m_fCoAnf, 0, 20, 28); lbe_Money.get(i).sp_sprite.DrawSubImage(g, lbe_Money.get(i).getXPos(), lbe_Money.get(i).getYPos()); lbe_Wood.get(i).sp_sprite.setSubImage(20 * m_iCoWo , 0, 20, 28); lbe_Wood.get(i).sp_sprite.DrawSubImage(g, lbe_Wood.get(i).getXPos(), lbe_Wood.get(i).getYPos()); lbe_Brick.get(i).sp_sprite.setSubImage(20 * m_iCoBr, 0, 20, 28); lbe_Brick.get(i).sp_sprite.DrawSubImage(g, lbe_Brick.get(i).getXPos(), lbe_Brick.get(i).getYPos()); lbe_Inhabs.get(i).sp_sprite.setSubImage(20 * m_iCoIn, 0, 20, 28); lbe_Inhabs.get(i).sp_sprite.DrawSubImage(g, lbe_Inhabs.get(i).getXPos(), lbe_Inhabs.get(i).getYPos()); }// for }// Draw @Override public void collionWidth(Entity e) { throw new UnsupportedOperationException("Not supported yet."); } }// class ResourceBar
true
62c39b1065af2bcab090fcfa81eed89aed594834
Java
LTYYTL/dataStructure
/src/com/test/queue/LinkedListQueueTest.java
UTF-8
775
3.125
3
[]
no_license
package com.test.queue; import com.dataStructure.queue.LinkedListQueue; public class LinkedListQueueTest { public static void main(String[] args) { LinkedListQueue<Integer> linkedListQueue = new LinkedListQueue<>(); //入队 linkedListQueue.enqueue(1); linkedListQueue.enqueue(2); linkedListQueue.enqueue(3); linkedListQueue.enqueue(4); linkedListQueue.enqueue(5); //获得长度 System.out.println(linkedListQueue.getSize()); System.out.println(linkedListQueue); //出队 linkedListQueue.dequeue(); linkedListQueue.dequeue(); //获得队首元素 System.out.println(linkedListQueue.getFront()); System.out.println(linkedListQueue); } }
true
54275675c5f2209d3b32dc45eed77f21259c2211
Java
MDSP777/UVA-Repo-2.0
/src/UVa_12532.java
UTF-8
2,291
2.921875
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class UVa_12532 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while(true) { StringBuilder sb = new StringBuilder(); String s = br.readLine(); if(s==null) break; String[] split = s.split("\\s+"); int nQ = Integer.parseInt(split[1]); split = br.readLine().split("\\s+"); int[] terms = new int[split.length]; for(int i=0; i<split.length; i++) { int cur = Integer.parseInt(split[i]); if(cur==0) terms[i] = 0; else if(cur<0) terms[i] = -1; else terms[i] = 1; } SegmentTree st = new SegmentTree(terms); while(nQ-->0) { split = br.readLine().split("\\s+"); if(split[0].equals("C")) { int cur = Integer.parseInt(split[2]); if(cur<0) cur = -1; else if(cur>0) cur = 1; st.update(Integer.parseInt(split[1])-1, cur); } else { int ans = st.rpq(Integer.parseInt(split[1])-1, Integer.parseInt(split[2])-1); if(ans==0) sb.append("0"); else if(ans<0) sb.append("-"); else sb.append("+"); } } System.out.println(sb); } } static class SegmentTree { int[] terms; int[] st; public SegmentTree(int[] terms) { this.terms = terms; this.st = new int[4*terms.length]; build(1, 0, terms.length-1); } void build(int p, int l, int r) { if(l==r) st[p] = terms[l]; else { int mid = (l+r)/2; build(p<<1, l, mid); build((p<<1)+1, mid+1, r); st[p] = st[p<<1]*st[(p<<1)+1]; } } void update(int p, int l, int r, int index, int val) { if(l==r && l==index) st[p] = val; else { int mid = (l+r)/2; if(l<=index && index<=mid) update(p<<1, l, mid, index, val); else update((p<<1)+1, mid+1, r, index, val); st[p] = st[p<<1]*st[(p<<1)+1]; } } void update(int index, int val) { terms[index] = val; update(1, 0, terms.length-1, index, val); } int rpq(int p, int l, int r, int i, int j) { if(i>r || j<l) return 1; if(i<=l && r<=j) return st[p]; int mid = (l+r)/2; return rpq(p<<1, l, mid, i, j)*rpq((p<<1)+1, mid+1, r, i, j); } int rpq(int i, int j) { return rpq(1, 0, terms.length-1, i, j); } } }
true
eba519e338dbb8b41eaadd2d6b829eccf6378c31
Java
mahesh1981/Maidul
/rallee-androidMarket/src/com/radiorunt/businessobjects/FBGroupsReceiver.java
UTF-8
749
1.8125
2
[]
no_license
package com.radiorunt.businessobjects; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public abstract class FBGroupsReceiver extends BroadcastReceiver { public static final String ACTION_DONE = "com.radiorunt.FBGroupsLoad.done"; public static final String ACTION_FAILED = "com.radiorunt.FBGroupsLoad.failed"; public static final String ACTION_IS_NOT_CHANGED = "com.radiorunt.FBGroupsLoad.notChanged"; public static final String ACTION_NUMBER_OF_ITEMS = "com.radiorunt.FBGroupsLoad.numOfItems"; public static final String ACTION_ITEM_LOADED = "com.radiorunt.FBGroupsLoad.itemLoaded"; public static final String ACTION_ITEM_LOAD_FAILED = "com.radiorunt.FBGroupsLoad.itemLoadFailed"; }
true
cc0c1611fc777f9f79b6c245fa7ef03303840df8
Java
Christianmsousa/springboot-student-api
/src/main/java/com/christian/modelonovo/swagger/SwaggerConfig.java
UTF-8
1,219
2.109375
2
[]
no_license
package com.christian.modelonovo.swagger; import java.util.ArrayList; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.christian.modelonovo")) .paths(PathSelectors.any()) .build() .apiInfo(metaInfo()); } private ApiInfo metaInfo() { ApiInfo apiInfo = new ApiInfo( "API Escola", "API para estudar conteúdos aprendidos na sensedia", "1.0", "Sobre", new Contact( "Christian Marçal", "https://github.com/christianmsousa", "christian.sousa@sensedia.com" ), "Documentação Swagger", "https://swagger.io/", new ArrayList<>() ); return apiInfo; } }
true
3954fafdad1497153812b8ffafdfb4da3a619549
Java
namejack/publicspringboot
/src/main/java/com/chinacreator/springboot/entity/UserBean.java
GB18030
479
2.09375
2
[]
no_license
package com.chinacreator.springboot.entity; /** * @author hua.tang * * @version ʱ䣺2021-9-1 12:30:15 * * ˵ */ public class UserBean { private String userName; private String userId; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
true
23a77a63a6be08ce36c7eed80a64a2382533fc1c
Java
johnlin0228/30_Days_of_Code_Hackerrank
/Day 6/Let_Us_Review.java
UTF-8
881
3.640625
4
[]
no_license
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { /* * Enter your code here. Read input from STDIN. Print output to STDOUT. Your * class should be named Solution. */ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); sc.nextLine(); for (int i = 0; i < N; i++) { String str = sc.nextLine(); char[] charArray = str.toCharArray(); String evenStr = ""; String oddStr = ""; for (int j = 0; j < charArray.length; j++) { if (j % 2 == 0) { evenStr += charArray[j]; } else { oddStr += charArray[j]; } } System.out.println(evenStr + " " + oddStr); } sc.close(); } }
true
aab663c008f90ebb7af4f7ea0ae0c237af867112
Java
mkwert/github-upload
/src/Model/LedgerItem.java
UTF-8
1,399
2.84375
3
[]
no_license
/* */ package Model; import java.util.ArrayList; /** * * @author melis */ public class LedgerItem extends Transaction implements Printable { private String account; ArrayList <String> ledgerItemNames; public LedgerItem (Date d, String n, Category c, double am, String ac) { super (d, n, c, am); account = ac; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } @Override public String toString() { return super.toString() + " " + getAccount(); } public String getBudgetItemName(int n) { return ledgerItemNames.get(n); } public ArrayList<String> getLedgerItemNames() { ledgerItemNames = new ArrayList<>(); ledgerItemNames.add("Date"); ledgerItemNames.add("Name"); ledgerItemNames.add("Category"); ledgerItemNames.add("Amount"); ledgerItemNames.add("Account"); for (int i = 0; i < ledgerItemNames.size(); i++) { return ledgerItemNames; } return ledgerItemNames; } @Override public ArrayList<String> getLabels() { return getLedgerItemNames(); } }
true
3953e5d2f694a3e8698ea89249804aca8b245e3d
Java
bdionne/evs-history
/src/main/java/gov/nih/nci/evs/EVSHistoryTableModel.java
UTF-8
2,623
2.203125
2
[]
no_license
package gov.nih.nci.evs; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; import org.protege.editor.owl.OWLEditorKit; import org.protege.editor.owl.server.http.messages.History; import org.semanticweb.owlapi.model.OWLOntology; public class EVSHistoryTableModel extends AbstractTableModel { private static final long serialVersionUID = 1L; private List<History> historyList; //private List<History> orgHistoryList; OWLOntology ont; public EVSHistoryTableModel(OWLEditorKit k) { ont = k.getOWLModelManager().getActiveOntology(); //orgHistoryList = EVSHistoryTab.currentTab().getEvsHistory(); historyList = new ArrayList<History>(); //String prefsID = getClass().toString() + EVSHistoryTab.currentTab().getRDFSLabel(complexProp).get(); //prefs = PreferencesManager.getInstance().getApplicationPreferences(prefsID); } @Override public int getRowCount() { return historyList.size(); } @Override public int getColumnCount() { return 6; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (historyList != null && !historyList.isEmpty() && historyList.size() > rowIndex) { History history = historyList.get(rowIndex); List<String> elementList = getHistoryElements(history); if (elementList.size() > 0) { return elementList.get(columnIndex); } } return ""; } public String getColumnName(int column) { String columnName = ""; switch(column) { case 0: columnName = "Date"; break; case 1: columnName = "User Name"; break; case 2: columnName = "Code"; break; case 3: columnName = "Name"; break; case 4: columnName = "Operation"; break; case 5: columnName = "Reference"; break; default: break; } return columnName; } public void setHistoryList( History query ) { historyList = EVSHistoryTab.currentTab().getEvsHistory(query); } public void refreshHistoryList() { historyList = EVSHistoryTab.currentTab().getEvsHistory(); } public List<History> getHistoryList() { return historyList; } private List<String> getHistoryElements(History history) { List<String> elementList = new ArrayList<String>(); elementList.add(history.getDate()); elementList.add(history.getUser_name()); elementList.add(history.getCode()); elementList.add(history.getName()); elementList.add(history.getOperation()); elementList.add(history.getReference()); return elementList; } }
true
8e0e0448f6d4562f350f3508e9d6fca420369568
Java
MarianMacik/quarkus-startstop
/testsuite/src/it/resources/JSONtoEnum.java
UTF-8
3,357
2.375
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2020 Contributors to the Quarkus StartStop project * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * 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. * */ import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Michal Karm Babacek <karm@redhat.com> */ public class JSONtoEnum { public static Pattern pattern = Pattern.compile("(?i).*\"id\":\"[^:]*:([^\"]*)\".*\"name\":\"([^\"]*)\".*\"shortId\":\"([^\"]*)\".*\"tags\":\\[([^]]*)].*"); public static void main(String[] args) throws Exception { if (args.length < 1 || !args[0].startsWith("http")) { System.out.println("Expects URL e.g. https://code.quarkus.stage.redhat.com/api/extensions"); System.exit(1); } StringBuilder s = new StringBuilder(); s.append("public enum CodeQuarkusExtensions {\n\n"); Set<String> usedIds = new TreeSet<>(); new Scanner(new URL(args[0]).openStream(), StandardCharsets.UTF_8).useDelimiter("},\\{").tokens().forEach(x -> { Matcher m = pattern.matcher(x); if (m.matches() && m.groupCount() == 4) { String id = m.group(1); if (!usedIds.contains(id)) { String name = m.group(2); String shortId = m.group(3); boolean supported = m.group(4).contains("supported"); String label = id.replace("-", "_").toUpperCase(); s.append(" "); s.append(label); s.append("(\""); s.append(id); s.append("\", \""); s.append(name); s.append("\", \""); s.append(shortId); s.append("\", "); s.append(supported); s.append("),\n"); usedIds.add(id); } } }); s.replace(s.length() - 2, s.length() - 1, ";"); s.append("\n public final String id;" + "\n public final String name;" + "\n public final String shortId;" + "\n public final boolean supported;" + "\n\n" + " CodeQuarkusExtensions(String id, String name, String shortId, boolean supported) {\n" + " this.id = id;\n" + " this.name = name;\n" + " this.shortId = shortId;\n" + " this.supported = supported;\n" + " }\n" + "}\n"); System.out.println(s.toString()); } }
true
787c141e7e1dc82b8beebb4e70903ede082d5cd5
Java
nileshthummar/Android
/watchback-android/WatchBackApp/src/main/java/com/watchback2/android/viewmodels/InterestsViewModel.java
UTF-8
6,724
1.96875
2
[]
no_license
package com.watchback2.android.viewmodels; import android.content.Context; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.databinding.ObservableBoolean; import androidx.databinding.ObservableField; import com.perk.request.auth.AuthAPIRequestController; import com.perk.util.PerkLogger; import com.watchback2.android.helper.UserInfoValidator; import com.watchback2.android.models.Interest; import com.watchback2.android.navigators.IInterestsNavigator; import java.util.ArrayList; import java.util.List; /** * Created by perk on 24/03/18. */ public class InterestsViewModel { private static final String LOG_TAG = "InterestsViewModel"; private static final int MINIMUM_INTERESTS_NEEDED = 3; private final ObservableBoolean dataLoading = new ObservableBoolean(false); private final ObservableBoolean enableSubmitButton = new ObservableBoolean(false); private final ObservableField<List<Interest>> interestsList = new ObservableField<>(); private final Context mContext; private final List<Interest> mSelectedInterests = new ArrayList<>(); private final ObservableBoolean isEditingFromSettings = new ObservableBoolean(false); @Nullable private IInterestsNavigator mNavigator; public InterestsViewModel(@NonNull Context context) { mContext = context.getApplicationContext(); } public void setNavigator(@NonNull IInterestsNavigator navigator) { mNavigator = navigator; } public void handleInterestsSelected(View view) { if (mNavigator != null) { // Set enabled to false to prevent user from clicking twice view.setEnabled(false); mNavigator.onSubmitInterestsClick(); } } public void handleCancelButtonClick(View view) { if (mNavigator != null) { mNavigator.onCancelClick(); } } public void loadInterestsListItems() { if (dataLoading.get()) { return; } PerkLogger.d(LOG_TAG, "Loading Interests list data..."); dataLoading.set(true); if (getInterestsList().get() != null) { getInterestsList().get().clear(); } /*PerkAPIController.INSTANCE.getInterests(mContext, isLoggedIn(), new OnRequestFinishedListener<GetInterestsData>() { @Override public void onSuccess(@NonNull GetInterestsData interestsData, @Nullable String s) { PerkLogger.d(LOG_TAG, "Loading Interests list data successful"); dataLoading.set(false); List<Interest> interestList = interestsData.getInterests(); if (interestList != null) { // Update the selection values if user is not logged in (as the // user's selection is stored locally in that case) List<Interest> storedInterestList = isLoggedIn() ? null : PerkPreferencesManager.INSTANCE.getUserInterestsListFromPreferences(); if (storedInterestList != null) { for (Interest storedInterest : storedInterestList) { if (storedInterest != null && storedInterest.getSelected()) { for (final Interest interest : interestList) { if (interest != null && TextUtils.equals( interest.getId(), storedInterest.getId())) { interest.setSelected(true); break; } } } } } getInterestsList().set(interestList); updateSelectedInterestsList(); } } @Override public void onFailure(@NonNull ErrorType errorType, @Nullable PerkResponse<GetInterestsData> perkResponse) { dataLoading.set(false); PerkLogger.e(LOG_TAG, "Loading Interests list data failed: " + (perkResponse != null ? perkResponse.getMessage() : "")); PerkUtils.showErrorMessageToast(errorType, (perkResponse != null ? perkResponse.getMessage() : mContext.getString(R.string.generic_error))); } });*/ } public ObservableBoolean getDataLoading() { return dataLoading; } public ObservableField<List<Interest>> getInterestsList() { return interestsList; } public ObservableBoolean getEnableSubmitButton() { return enableSubmitButton; } public List<Interest> getSelectedInterests() { return mSelectedInterests; } private boolean isLoggedIn() { return UserInfoValidator.isAuthenticated( AuthAPIRequestController.INSTANCE.getCurrentAuthenticatedSessionDetails(mContext)); } public void onItemUpdated(@NonNull Interest interestItem) { if (interestItem.getSelected()) { getSelectedInterests().add(interestItem); } else { getSelectedInterests().remove(interestItem); } enableSubmitButtonIfNeeded(); } private void updateSelectedInterestsList() { List<Interest> interestsList = getInterestsList().get(); if (interestsList == null) { PerkLogger.e(LOG_TAG, "updateSelectedInterestsList(): interestsList is null! "); return; } getSelectedInterests().clear(); for (Interest interest : interestsList) { if (interest != null && interest.getSelected()) { getSelectedInterests().add(interest); } } enableSubmitButtonIfNeeded(); } private void enableSubmitButtonIfNeeded() { int selectedCount = getSelectedInterests().size(); PerkLogger.d(LOG_TAG, "enableSubmitButtonIfNeeded(): Currently selected items: " + selectedCount); getEnableSubmitButton().set(selectedCount >= MINIMUM_INTERESTS_NEEDED); } public ObservableBoolean getIsEditingFromSettings() { return isEditingFromSettings; } }
true
97a008e1b142451f54c223ff6cef8ff40bf01df9
Java
limeiyin1/helloword
/Blog/src/main/java/com/red/Dao/UserDao.java
UTF-8
226
2
2
[]
no_license
package com.red.Dao; import org.springframework.stereotype.Repository; import com.red.Pojo.User; @Repository public interface UserDao { public User selectByUsername(User user); public void insertUser(User user); }
true
f3ee2d5a4acecd8b3d415a246ce4a68e89351e28
Java
mcanterb/SC2TerranGA
/src/org/sc2sim/commands/GatherGas.java
UTF-8
1,397
2.5625
3
[]
no_license
package org.sc2sim.commands; import java.util.ArrayList; import org.sc2sim.Action; import org.sc2sim.Command; import org.sc2sim.StarcraftWorld; import org.sc2sim.Unit; import org.sc2sim.commands.GatherGas.GatherGasAction; import org.sc2sim.units.Refinery; public class GatherGas implements Command { public static final GatherGasAction action = new GatherGasAction(); public static final GatherGas INSTANCE = new GatherGas(); @Override public void issue(StarcraftWorld world, Unit issuer) { world.cancelUnitAction(issuer); world.scheduleAction(world.getTime()+6.1f, action, issuer); issuer.setCommand(this); Refinery ref = getFreeRefinery(world.getUnits()); ref.setNumOfCollectors(ref.getNumOfCollectors()+1); } private Refinery getFreeRefinery(ArrayList<Unit> units) { for(Unit unit : units) { if(unit instanceof Refinery) { Refinery ref = (Refinery)unit; if(ref.getNumOfCollectors() < 3) return ref; } } return null; } @Override public boolean canIssue(StarcraftWorld world, Unit issuer) { return issuer.getCommand()==CollectMinerals.INSTANCE && getFreeRefinery(world.getUnits())!= null; } public static class GatherGasAction implements Action { @Override public void performAction(StarcraftWorld world, Unit unit) { world.setGas(world.getGas()+4); world.scheduleAction(world.getTime()+6.1f, this, unit); } } }
true
4c65d49c2310e7d11f99651da0e1ebde1db3666b
Java
tonychiu25/TokyoMetroAppProtoType
/src/com/example/myapp/DisplayMessageActivity.java
UTF-8
1,090
2.421875
2
[]
no_license
package com.example.myapp; import android.app.Activity; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.TextView; public class DisplayMessageActivity extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get the message from the intent /*Intent intent = getIntent(); String message = intent.getStringExtra(MyFirstAppActivity.EXTRA_MESSAGE); // Create the text view TextView textView = new TextView(this); textView.setTextSize(40); textView.setText(message); setContentView(textView);*/ String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" }; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values); setListAdapter(adapter); //setContentView(R.id.scrollView1); } }
true
11403aa4ae26dbfb542540551196092683404d74
Java
GuilhermeSantannape/TrabalhoAlgaritimos2
/src/ImportaCSV.java
UTF-8
1,056
2.765625
3
[]
no_license
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; public class ImportaCSV { static int tam=10; static Pessoas contato[]=new Pessoas[tam]; private static File csv = new File("arquivo.csv"); static void run() { String linha = ""; try { Scanner ler = new Scanner(csv); String linhas = new String(); for (int i =0;i<contato.length;i++) { contato[i]=new Pessoas();} int contador=0; while(ler.hasNext()){ linhas = ler.nextLine(); String[] Divide = linhas.split(","); contato[contador].setNome(Divide[0]); contato[contador].setEmail(Divide[1]); contador++;} } catch (IOException e) { e.printStackTrace(); } finally { if (csv != null) { } } } public static void arquivo() { run();} }
true
9888ac636ea845e6c1e627fbca6a2c3740689c8d
Java
AlvaroSebastian98/CPS-20191-G1
/src/main/java/com/tecsup/lab10/CPS_20191_G1/Suma.java
UTF-8
244
2.734375
3
[]
no_license
package com.tecsup.lab10.CPS_20191_G1; public class Suma { /** * Método para sumar * @param num1 * @param num2 * @return */ public int sumar(int num1, int num2) { int res = num1 + num2; return res; } }
true
74c758e86ba325444e08a1f0c76be5cbef1c7ea3
Java
baobao555/JavaFoundation
/DesignMode/src/designmode/singleton/SingletonTest.java
UTF-8
609
2.828125
3
[]
no_license
package designmode.singleton; public class SingletonTest { public static void main(String[] args) { long start = System.currentTimeMillis(); for (int i=0;i<100000000;i++){ // SingletonHurry instance = SingletonHurry.getInstance(); SingletonLazy instance = SingletonLazy.getInstance(); // SingletonLazyDoubleCheckLock instance = SingletonLazyDoubleCheckLock.getInstance(); // SingletonStaticInnerClass instance = SingletonStaticInnerClass.getInstance(); // SingletonEnum instance = SingletonEnum.INSTANCE; } long end = System.currentTimeMillis(); System.out.println(end-start); } }
true
07456a2e1ad7a601075d55ede52ffa0d73fb8b1f
Java
kchhipa4u/core-java-practice
/src/com/kan/fundamentals/TestCompare.java
UTF-8
458
2.734375
3
[]
no_license
package com.kan.fundamentals; import java.util.ArrayList; import java.util.List; public class TestCompare { /** * @param args */ public static void main(String[] args) { Student student = new Student(); List<Student> studs = student.addStudents(); Employee emp = new Employee(); List<Employee> emps = emp.addEmployees(); System.out.println(studs.equals(emps)); studs.equals(emps); System.out.println(studs); } }
true
3353a3bb249c3d669bd8cfe3edd7eb9ecf85ee00
Java
cooker/msg-bus
/server/src/main/java/com/cooker/msgbus/server/NettyChannelHandler.java
UTF-8
937
2.21875
2
[ "Apache-2.0" ]
permissive
package com.cooker.msgbus.server; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; /* * 版权: * 创建者: ykq * 创建时间: 2018/09/07 下午4:46 * 功能描述: * 修改历史: */ public class NettyChannelHandler extends ChannelInboundHandlerAdapter { private NettyServer nettyServer; private NettyServerChannelManager serverChannelManager; public NettyChannelHandler(NettyServer nettyServer, NettyServerChannelManager serverChannelManager) { this.nettyServer = nettyServer; this.serverChannelManager = serverChannelManager; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { super.channelRead(ctx, msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { super.exceptionCaught(ctx, cause); } }
true
f1c4934461adeb1e0f28d75397c4bbf1d1bd43cb
Java
bobskay/log-collector
/base-parent/base-toolkits/src/main/java/wang/wangby/utils/dao/model/TableInfo.java
UTF-8
541
2.3125
2
[]
no_license
package wang.wangby.utils.dao.model; import lombok.Data; import wang.wangby.annotation.Remark; import java.util.List; @Data @Remark("表信息") public class TableInfo { @Remark("表名") private String tableName; @Remark("表注释") private String tableComment; @Remark("对应数据信息") private DatabaseInfo databaseInfo; @Remark("包含的列") private List<ColumnInfo> columns; public String pkName(){ for(ColumnInfo col:columns){ if(col.getIsPk()){ return col.getColumnName(); } } return null; } }
true
b063369eb9e767ec1ec7ac25867f89ee60b03303
Java
lijonathan/Coding-Challenges
/Medium/Course_Schedule_II.java
UTF-8
5,374
3.859375
4
[]
no_license
import java.util.ArrayList; import java.util.Arrays; import java.util.Stack; public class Course_Schedule_II { /* Rating: Medium There are a total of n courses you have to take labelled from 0 to n - 1. Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai. Given the total number of courses numCourses and a list of the prerequisite pairs, return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: [0,1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. Example 2: Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0,2,1,3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. Example 3: Input: numCourses = 1, prerequisites = [] Output: [0] Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= numCourses * (numCourses - 1) prerequisites[i].length == 2 0 <= ai, bi < numCourses ai != bi All the pairs [ai, bi] are distinct. */ /* Approach: Directed Graph Cycle Detection and Topological Sort Create an adjacency list of the courses and check if there is a cycle. Use two arrays, visited array and visiting array. Start with all false values in both arrays. Iterate through the vertices and if the current vertex is visiting[neighbor] = true, return true for a cycle. Otherwise, if it is not visited, dfs to that neighbor and return true if the neighbor detects a cycle. Mark visited of curr after all neighbors have been visited as true, and mark visiting of curr as false. If no cycles, topological sort for the ordering. Reset all vertices to unvisited. Iterate and for each unvisited vertex, visit it and mark it as visited, then recursively visit all its neighbors. After all neighbors of the current vertex has been visited, push it onto the stack. Return the stack popping off the vertices in order. */ // O(V + E) time where V is number of courses and E is number of prerequisites // O(V) space // Runtime: 2 ms, faster than 99.76% of Java online submissions // Memory Usage: 41.2 MB, less than 37.43% of Java online submissions public boolean detect_cycle(ArrayList[] adj_l, boolean[] visited, boolean[] visiting, int curr) { if (adj_l[curr] == null) { return false; } visiting[curr] = true; for (int i = 0; i < adj_l[curr].size(); ++i) { int neighbor = (Integer) adj_l[curr].get(i); if (visiting[neighbor]) { return true; } else if (!visited[neighbor]) { if (detect_cycle(adj_l, visited, visiting, neighbor)) { return true; } } } visited[curr] = true; visiting[curr] = false; return false; } public void topological_sort(ArrayList[] adj_l, int curr, boolean[] visited, Stack<Integer> order) { visited[curr] = true; if (adj_l[curr] != null) { for (int i = 0; i < adj_l[curr].size(); ++i) { int neighbor = (int) adj_l[curr].get(i); if (!visited[neighbor]) { topological_sort(adj_l, neighbor, visited, order); } } } order.push(curr); } public int[] findOrder(int numCourses, int[][] prerequisites) { ArrayList[] adj_l = new ArrayList[numCourses]; for (int i = 0; i < prerequisites.length; ++i) { int prereq = prerequisites[i][1]; int postreq = prerequisites[i][0]; if (adj_l[prereq] == null) { adj_l[prereq] = new ArrayList<Integer>(); } adj_l[prereq].add(postreq); } boolean[] visited = new boolean[numCourses]; boolean[] visiting = new boolean[numCourses]; for (int i = 0; i < adj_l.length; ++i) { if (adj_l[i] != null && !visited[i]) { if (detect_cycle(adj_l, visited, visiting, i)) { return new int[0]; } } } Stack<Integer> order = new Stack<Integer>(); Arrays.fill(visited, false); for (int i = 0; i < numCourses; ++i) { if (!visited[i]) { topological_sort(adj_l, i, visited, order); } } int[] ordering = new int[numCourses]; int index = 0; while(!order.empty()) { ordering[index] = order.pop(); ++index; } return ordering; } }
true
92baf2bb498c3ebd2052b08655129802d18e5710
Java
satpreetsingh/182mainproject
/Final_Build/Development_Code/TwoPointShapeFactory.java
UTF-8
725
2.9375
3
[]
no_license
import java.awt.*; import java.io.Serializable; import java.util.UUID; /** * An interface defining a class for creating TwoPointShape objects. * @author bmhelppi * */ interface TwoPointShapeFactory extends Serializable{ /** * Creates an instance of a TwoPointShape. * @param xOne X position. * @param yOne Y position. * @param xTwo Second x position. * @param yTwo Second y position. * @param c C base color. * @param uniqueId TODO * @param type int object type (outline,solid). * @return Returns an instantiated TwoPointShape. */ public TwoPointShape createShape (int xOne, int yOne, int xTwo, int yTwo, Color c, boolean IsOutline, UUID uniqueId); }
true
8327e28840e0589c04c7eb7ca92b89ba4faaae4e
Java
hexingtong/Yuerfei
/src/main/java/com/springmvc/service/impl/GoodsDetailServiceImpl.java
UTF-8
738
2
2
[]
no_license
package com.springmvc.service.impl; import com.springmvc.mapping.GoodsDetailMapper; import com.springmvc.pojo.GoodsDetail; import com.springmvc.service.GoodsDetailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @ClassName GoodsDetailServiceImpl * @Description:产品详情类 * @Author by * @Date: 2019/3/8 16:57 **/ @Service public class GoodsDetailServiceImpl extends BaseServiceImpl<GoodsDetail> implements GoodsDetailService { @Autowired GoodsDetailMapper goodsDetailMapper; @Override public GoodsDetail selectDetail(int id) { GoodsDetail goodsDetail=goodsDetailMapper.selectDetail(id); return goodsDetail; } }
true
260fbfa9b0d107668b0ead39d7d40eb95ad43599
Java
Xceptance/neodymium-example
/src/test/java/posters/pageobjects/pages/browsing/NoHitsPage.java
UTF-8
1,189
2.21875
2
[ "MIT" ]
permissive
package posters.pageobjects.pages.browsing; import static com.codeborne.selenide.Condition.exist; import static com.codeborne.selenide.Selenide.$; import com.xceptance.neodymium.util.Neodymium; import io.qameta.allure.Step; public class NoHitsPage extends AbstractBrowsingPage { @Override @Step("ensure this is a no hits page") public NoHitsPage isExpectedPage() { super.isExpectedPage(); $("#errorMessage").should(exist); return this; } /// ----- validate no hits page ----- /// @Step("validate that no products are on no hits page") public void validateNoProductsFound() { errorMessage.validateErrorMessage(Neodymium.localizedText("NoHitsPage.validation.noProductsFound")); } @Override @Step("validate structure no hits page") public void validateStructure() { super.validateStructure(); validateNoProductsFound(); } /// ----- no hits page navigation ----- /// @Step("open homepage from no hits page") public HomePage openHomePage() { $("#brand").scrollTo().click(); return new HomePage().isExpectedPage(); } }
true
d000783b249b90b551b858c2c73c389d2710e569
Java
emerinohdz/mirna-traps
/miroculus-mrna-rest/src/test/java/Start.java
UTF-8
4,670
2.28125
2
[ "Artistic-2.0" ]
permissive
import java.io.File; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.Properties; import org.eclipse.jetty.http.ssl.SslContextFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.bio.SocketConnector; import org.eclipse.jetty.server.ssl.SslSocketConnector; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.xml.XmlConfiguration; public class Start { public static void main(String[] args) throws Exception { //int timeout = (int) Duration.ONE_HOUR.getMilliseconds(); int timeout = 3600 * 1000; // 1 hour Server server = new Server(); SocketConnector connector = new SocketConnector(); // Set some timeout options to make debugging easier. connector.setMaxIdleTime(timeout); connector.setSoLingerTime(-1); connector.setPort(9191); server.addConnector(connector); // check if a keystore for a SSL certificate is available, and // if so, start a SSL connector on port 8443. By default, the // quickstart comes with a Apache Wicket Quickstart Certificate // that expires about half way september 2021. Do not use this // certificate anywhere important as the passwords are available // in the source. Resource keystore = Resource.newClassPathResource("/keystore"); keystore = null; if (keystore != null && keystore.exists()) { connector.setConfidentialPort(8443); SslContextFactory factory = new SslContextFactory(); factory.setKeyStoreResource(keystore); factory.setKeyStorePassword("wicket"); factory.setTrustStoreResource(keystore); factory.setKeyManagerPassword("wicket"); SslSocketConnector sslConnector = new SslSocketConnector(factory); sslConnector.setMaxIdleTime(timeout); sslConnector.setPort(8443); sslConnector.setAcceptors(4); server.addConnector(sslConnector); System.out.println("SSL access to the quickstart has been enabled on port 8443"); System.out.println("You can access the application using SSL on https://localhost:8443"); System.out.println(); } WebAppContext bb = new WebAppContext(); bb.setMaxFormContentSize(1000000); bb.setServer(server); bb.setContextPath("/"); bb.setAliases(true); bb.setWar("src/main/webapp"); bb.setDescriptor("src/main/webapp/WEB-INF/web.xml"); Properties props = new Properties(); //props.load(Start.class.getResourceAsStream("config.properties")); // String webXmlFile = props.getProperty("webXml"); String[] configFiles = {"src/main/webapp/WEB-INF/jetty-env.xml"}; for (String configFile : configFiles) { XmlConfiguration configuration = new XmlConfiguration( new File(configFile).toURI().toURL()); configuration.configure(bb); } /* rHandler.setDirectoriesListed(true); rHandler.setWelcomeFiles(new String[]{"index.html"}); Path docroot = FileSystems.getDefault().getPath("src/main/webapp"); rHandler.setResourceBase(docroot.toString()); LRWebSocketHandler2 wsHandler = new LRWebSocketHandler2(); wsHandler.setHandler(rHandler); HandlerList handlerList = new HandlerList(); handlerList.setHandlers(new Handler[]{bb, wsHandler}); */ // START JMX SERVER // MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); // MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer); // server.getContainer().addEventListener(mBeanContainer); // mBeanContainer.start(); server.setHandler(bb); try { // initialize LiveReload server int port = 5000; Path docroot = FileSystems.getDefault().getPath("target/classes"); //LRServer liveServer = new LRServer(port, docroot); //liveServer.start(); System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP"); server.start(); System.in.read(); System.out.println(">>> STOPPING EMBEDDED JETTY SERVER"); server.stop(); server.join(); // stop LiveReload server //liveServer.stop(); //liveServer.join(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
true
374fa2d0e6503a52475305bed37de281e0837c66
Java
cx265/mye
/Mybatis/src/com/cx/carl/test4/Test4.java
UTF-8
712
2.296875
2
[]
no_license
package com.cx.carl.test4; import java.io.IOException; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.cx.carl.bean.Order; import com.cx.carl.util.MybatisUtils; /* * 测试: 解决字段名与实体类属性名不相同的冲突 */ public class Test4 { public static void main(String[] args) throws IOException { SqlSessionFactory sessionFactory = MybatisUtils.getSessionFactory(); SqlSession session = sessionFactory.openSession(); String statement = "com.cx.carl.test4.orderMapper.getOrder"; statement = "com.cx.carl.test4.orderMapper.getOrder2"; Order order = session.selectOne(statement , 2); System.out.println(order); } }
true
9c01cdae110afb725ee99b16c9ef78152c5adfb0
Java
maybew/Yuemu
/yuemu/src/yuemu/data/io/DatabaseData.java
UTF-8
1,702
2.171875
2
[]
no_license
package yuemu.data.io; import java.io.Serializable; import java.util.List; import yuemu.core.Debug; import yuemu.po.Account; import yuemu.po.Document; import yuemu.po.Image; import yuemu.po.Music; import yuemu.po.Resource; import yuemu.po.Video; public class DatabaseData implements Serializable { private static final long serialVersionUID = 1L; public List<Account> accountList; public List<Resource> resourceList; public List<Document> documentList; public List<Image> imageList; public List<Music> musicList; public List<Video> videoList; @Override public String toString() { StringBuilder strBuilder = new StringBuilder(); strBuilder.append("Account List: "); strBuilder.append(Debug.collectionToString(accountList)); strBuilder.append("---------------------------------------\n"); strBuilder.append("Resource List: "); strBuilder.append(Debug.collectionToString(resourceList)); strBuilder.append("---------------------------------------\n"); strBuilder.append("Document List: "); strBuilder.append(Debug.collectionToString(documentList)); strBuilder.append("----------------------------------------\n"); strBuilder.append("Image List: "); strBuilder.append(Debug.collectionToString(imageList)); strBuilder.append("----------------------------------------\n"); strBuilder.append("Music List: "); strBuilder.append(Debug.collectionToString(musicList)); strBuilder.append("----------------------------------------\n"); strBuilder.append("Video List: "); strBuilder.append(Debug.collectionToString(videoList)); strBuilder.append("----------------------------------------\n"); return strBuilder.toString(); } }
true
8e59d20ee6ee8f1a74281faadba94930db9a28bd
Java
spacecowboy1310/barJEGO
/BarBestial/src/barJEGO/Mofeta.java
UTF-8
285
1.546875
2
[]
no_license
package barJEGO; public class Mofeta extends Karta{ public Mofeta(int pId,int pKolorea) { super("Mofeta",pId,pKolorea,(""),true,1,null,null,new KaleratuBiGogorrenak()); } public void animalada(){ } public void errekurrentea(){ this.animalada(); } }
true
febc542eba4e2052daf24f2709d56e4fe80afec3
Java
azjaehyun/back-end
/src/test/java/com/example/demo/controller/DemoControllerTest.java
UTF-8
464
1.679688
2
[]
no_license
package com.example.demo.controller; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class DemoControllerTest { @Autowired private DemoController demoController; @Test public void contextLoad() throws Exception { assertThat(demoController).isNotNull(); } }
true
465b8c522f9fa40e2f1df61d87ba5965c7e24d97
Java
wkgcass/vproxy
/core/src/main/java/io/vproxy/vswitch/node/EthernetInput.java
UTF-8
8,526
2.21875
2
[ "MIT" ]
permissive
package io.vproxy.vswitch.node; import io.vproxy.base.util.ByteArray; import io.vproxy.base.util.Consts; import io.vproxy.base.util.Logger; import io.vproxy.commons.graph.GraphBuilder; import io.vproxy.vfd.IP; import io.vproxy.vfd.MacAddress; import io.vproxy.vpacket.AbstractIpPacket; import io.vproxy.vpacket.AbstractPacket; import io.vproxy.vpacket.ArpPacket; import io.vproxy.vpacket.IcmpPacket; import io.vproxy.vswitch.PacketBuffer; public class EthernetInput extends Node { private final NodeEgress unicastInput = new NodeEgress("unicast-input"); private final NodeEgress multicastInput = new NodeEgress("multicast-input"); public EthernetInput() { super("ethernet-input"); } @Override protected void initGraph(GraphBuilder<Node> builder) { builder.addEdge("ethernet-input", "unicast-input", "unicast-input", DEFAULT_EDGE_DISTANCE); builder.addEdge("ethernet-input", "multicast-input", "multicast-input", DEFAULT_EDGE_DISTANCE); } @Override protected void initNode() { fillEdges(unicastInput); fillEdges(multicastInput); } @Override protected HandleResult preHandle(PacketBuffer pkb) { return HandleResult.PASS; } @Override protected HandleResult handle(PacketBuffer pkb, NodeGraphScheduler scheduler) { MacAddress src = pkb.pkt.getSrc(); // record iface in the mac table if (pkb.devin != null) { assert Logger.lowLevelDebug("record the mac -> iface info"); pkb.network.macTable.record(src, pkb.devin); } else { assert Logger.lowLevelDebug("no iface provided with this packet"); } // check whether need to refresh the arp table updateArpTable(pkb); // check whether we should accept the packet and process MacAddress dst = pkb.pkt.getDst(); if (dst.isUnicast()) { return _returnnext(pkb, unicastInput); } else { return _returnnext(pkb, multicastInput); } } private void updateArpTable(PacketBuffer pkb) { assert Logger.lowLevelDebug("updateArpTable(" + pkb + ")"); AbstractPacket packet = pkb.pkt.getPacket(); if (packet instanceof ArpPacket) { assert Logger.lowLevelDebug("is arp packet"); // ============================================================ // ============================================================ ArpPacket arp = (ArpPacket) packet; if (arp.getProtocolType() != Consts.ARP_PROTOCOL_TYPE_IP) { assert Logger.lowLevelDebug("arp type is not ip"); return; } assert Logger.lowLevelDebug("arp protocol is ip"); ByteArray senderIp; if (arp.getOpcode() == Consts.ARP_PROTOCOL_OPCODE_REQ) { assert Logger.lowLevelDebug("arp is req"); senderIp = arp.getSenderIp(); if (senderIp.length() != 4) { assert Logger.lowLevelDebug("sender ip length is not 4"); return; } assert Logger.lowLevelDebug("arp sender is ipv4"); // fall through: common code } else if (arp.getOpcode() == Consts.ARP_PROTOCOL_OPCODE_RESP) { assert Logger.lowLevelDebug("arp is resp"); senderIp = arp.getSenderIp(); if (senderIp.length() != 4) { assert Logger.lowLevelDebug("sender ip length is not 4"); return; } // fall through: common code } else { assert Logger.lowLevelDebug("arp type is neither req nor resp"); return; } // only handle ipv4 in arp, v6 should be handled with ndp IP ip = IP.from(senderIp.toJavaArray()); if (!pkb.network.v4network.contains(ip)) { assert Logger.lowLevelDebug("got arp packet not allowed in the network: " + ip + " not in " + pkb.network.v4network); // allow if it's response if (arp.getOpcode() != Consts.ARP_PROTOCOL_OPCODE_RESP) { assert Logger.lowLevelDebug("this arp packet is not a response"); return; } if (!pkb.pkt.getDst().isUnicast()) { assert Logger.lowLevelDebug("this arp packet is not unicast"); return; } assert Logger.lowLevelDebug("this arp packet is a response, continue to handle"); } pkb.network.arpTable.record(pkb.pkt.getSrc(), ip); // ============================================================ // ============================================================ assert Logger.lowLevelDebug("refresh arp table by arp done"); } else if (packet instanceof AbstractIpPacket) { assert Logger.lowLevelDebug("is ip packet"); // ============================================================ // ============================================================ var ipPkt = (AbstractIpPacket) packet; if (!(ipPkt.getPacket() instanceof IcmpPacket)) { assert Logger.lowLevelDebug("is not icmp packet"); return; } assert Logger.lowLevelDebug("is icmp packet"); var icmp = (IcmpPacket) ipPkt.getPacket(); if (icmp.getType() != Consts.ICMPv6_PROTOCOL_TYPE_Neighbor_Solicitation && icmp.getType() != Consts.ICMPv6_PROTOCOL_TYPE_Neighbor_Advertisement) { assert Logger.lowLevelDebug("is not ndp"); return; } if (pkb.ensurePartialPacketParsed()) return; assert Logger.lowLevelDebug("is ndp"); var other = icmp.getOther(); if (other.length() < 28) { // 4 reserved and 16 target address and 8 option assert Logger.lowLevelDebug("ndp length not enough"); return; } assert Logger.lowLevelDebug("ndp length is ok"); var targetIp = IP.from(other.sub(4, 16).toJavaArray()); // check the target ip if (pkb.network.v6network == null || !pkb.network.v6network.contains(targetIp)) { assert Logger.lowLevelDebug("got ndp packet not allowed in the network: " + targetIp + " not in " + pkb.network.v6network); // allow if it's response if (icmp.getType() == Consts.ICMPv6_PROTOCOL_TYPE_Neighbor_Solicitation) { assert Logger.lowLevelDebug("this ndp packet is not neighbor advertisement"); return; } if (!pkb.pkt.getDst().isUnicast()) { assert Logger.lowLevelDebug("this ndp packet is not unicast"); return; } assert Logger.lowLevelDebug("this ndp packet is neighbor advertisement, continue to handle"); } // try to build arp table var optType = other.uint8(20); var optLen = other.uint8(21); if (optLen != 1) { assert Logger.lowLevelDebug("optLen is not 1"); return; } assert Logger.lowLevelDebug("ndp optLen == 1"); var mac = new MacAddress(other.sub(22, 6)); if (optType == Consts.ICMPv6_OPTION_TYPE_Source_Link_Layer_Address) { assert Logger.lowLevelDebug("ndp has opt source link layer address"); // mac is the sender's mac, record with src ip in ip packet // this ip address might be solicited node address, but it won't harm to record IP ip = ipPkt.getSrc(); pkb.network.arpTable.record(mac, ip); } else if (optType == Consts.ICMPv6_OPTION_TYPE_Target_Link_Layer_Address) { assert Logger.lowLevelDebug("ndp has opt target link layer address"); // mac is the target's mac, record with target ip in icmp packet pkb.network.arpTable.record(mac, targetIp); } // ============================================================ // ============================================================ assert Logger.lowLevelDebug("refresh arp table by ndp done"); } } }
true
fb05dea2f2e9efbe412f0dee5587002713584490
Java
shinegwp/CattleNet
/cattlenet/src/sword_finger_offer/Merge.java
UTF-8
1,981
3.609375
4
[]
no_license
package sword_finger_offer; /** * @time 18.4.4 * @author 高位鹏 * @describe 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。 * 运行时间:15ms * 占用内存:9340k */ import utils.ListNode; public class Merge { /** * @describe * @param list1 * @param list2 * @return */ // public ListNode merge(ListNode list1,ListNode list2) { // if (list1 == null) { // return list2; // } else if (list2 == null) { // return list1; // } else if (list1.val >= list2.val) { // ListNode temp = list2, temp1 = null; // while (temp.next != null) { // if (list1.val < temp.next.val && list1 != null) { // temp1 = list1; // list1 = list1.next; // temp1.next = temp.next; // temp.next = temp1; // } // temp = temp.next; // } // if (list1 != null) { // temp.next = list1; // } // return list2; // } else { // ListNode temp = list1, temp2 = null; // while (temp.next != null) { // if (list2.val < temp.next.val && list2 != null) { // temp2 = list2; // list2 = list2.next; // temp2.next = temp.next; // temp.next = temp2; // } // temp = temp.next; // } // if (list2 != null) { // temp.next = list2; // } // return list1; // } // } /** * @describe 递归版本,效率要低。但是代码简洁 * @param list1 * @param list2 * @return */ public ListNode merge(ListNode list1,ListNode list2) { if (list1 == null) { return list2; } else if (list2 == null) { return list1; } else { if (list1.val <= list2.val) { list1.next = merge(list1.next,list2); return list1; } else { list2 = merge(list1,list2.next); return list2; } } } }
true
cc67ef87831eaf9a0b2c131013bb809492fed723
Java
Logi2110/String
/StringJTP/src/package3/StringMethod5.java
UTF-8
2,358
3.765625
4
[]
no_license
package package3; public class StringMethod5 { public static void main(String[] args) { String s ="this is my game. this is my rule"; String s1=" my name is logi "; String s2="I Am Villian"; // string.toLowerCase() && string.toUpperCase() System.out.println("////string.toLowerCase() && string.toLowerCase()////"); String lc=s2.toLowerCase(); String uc=s2.toUpperCase(); System.out.println(lc); System.out.println(uc); // string.split() System.out.println("/////////////////string.split()/////////////////////"); String[] word=s.split("\\s"); System.out.println("word length is "+ word.length); for(String w: word) { System.out.println(w); } for(String w: s.split("\\s",0)) { System.out.println(w); } for(String w: s.split("\\s",1)) { System.out.println(w); } for(String w: s.split("\\s",2)) { System.out.println(w); } for(String w: s.split("\\s",5)) { System.out.println(w); } // string.trim() System.out.println("/////////////////string.trim()///////////////////////"); System.out.println(s1.length()); String strr1=s1.trim(); System.out.println(strr1); System.out.println(strr1.length()); // string.replace() System.out.println("/////////////////string.replace()///////////////////"); String str1=s.replace('s','z'); String str2=s.replace("my","our"); String str3=s.replace("\\s",""); // can't get desired output because of \\s System.out.println(str1); System.out.println(str2); System.out.println(str3); // string.replaceAll() - accept only string args System.out.println("/////////////////string.replaceAll()///////////////////"); String str4=s.replaceAll("s","z"); // character is not valid. so giving string syntax String str5=s.replaceAll("my","our"); String str6=s.replaceAll("\\s",""); System.out.println(str4); System.out.println(str5); System.out.println(str6); // string.join() System.out.println("/////////////////string.join()///////////////////////"); String st1=String.join("-","welcome","to","java","tutorial"); String st2=String.join("/","21","10","1994"); String st3=String.join(":","09","20","00"); System.out.println(st1); System.out.println(st2); System.out.println(st3); } }
true
de03c6653c4d84003d2de285a27d5d9dcb602e99
Java
malyabanta/DS
/DataStructure/src/main/java/HashMapImplementation/HashMapImplementation.java
UTF-8
2,457
3.546875
4
[]
no_license
package HashMapImplementation; public class HashMapImplementation<T,T1> { int capacity = 16; mapEntry mapArray[] = new mapEntry[capacity]; public int GetHashCode(T Key) { return Key.hashCode(); } public void put(T Key , T1 Value) { mapEntry node = new mapEntry(Key , Value ); System.out.println("hash code:"+ GetHashCode(Key)); int bucket = GetHashCode(Key)% capacity; System.out.println("put the object in bucket: " + bucket); if(mapArray[bucket] == null) { mapArray[bucket] = node; //return null; }else { mapEntry existingNodes = mapArray[bucket]; while(existingNodes.next != null) { if(existingNodes.getKey().equals(Key) ) { existingNodes.setValue(Value); break; } else{ existingNodes = existingNodes.next; } } if(existingNodes.getKey().equals(Key) ) { // T1 eValue = (T1) existingNodes.getValue(); existingNodes.setValue(Value); //return eValue; }else { existingNodes.setNext(node); } } } public T1 get(T Key) { int bucket = GetHashCode(Key)%capacity; mapEntry enode = mapArray[bucket]; if(enode == null) { System.out.println("no element exist with this key : "+ Key); return null; }else{ while(enode != null) { if(enode.getKey().equals(Key)) { return (T1)enode.getValue(); } enode.getNext(); } } return null; } // Traverse a hashmap public void Iterate() { for(int i = 0; i < capacity;i++) { if(mapArray[i] != null) { mapEntry entry = mapArray[i]; do { System.out.println(entry.getKey() +" -> "+entry.getValue()); entry = entry.getNext(); }while(entry != null); } } } }
true
532c01cab9df443da1d43f27066b13bdded44437
Java
Anjineyulu/mybudget0123
/src/org/fortytwo/developers/mybudget0123/server/data/PMF.java
UTF-8
358
1.6875
2
[]
no_license
package org.fortytwo.developers.mybudget0123.server.data; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManagerFactory; public final class PMF { private static final PersistenceManagerFactory pmfactory = JDOHelper.getPersistenceManagerFactory("transactions-optional"); public static PersistenceManagerFactory get() { return pmfactory; } }
true
3e4e1a6e79409ae7dcc50c2bd2165f77e2fc819b
Java
ylu6/MultiThreadingTest
/Study/src/SynchronizedDemo.java
UTF-8
1,123
3.765625
4
[]
no_license
/** * Created by yeqing on 9/4/2017. */ public class SynchronizedDemo { synchronized void print1(int n) { try { for (int i = 1; i < n; i++) { System.out.println("print1: " + i); Thread.sleep((int)(Math.random()*500)); } } catch (InterruptedException e) { System.out.println(e.getMessage()); } } synchronized void print2(int n) { try { for (int i = 1; i < n; i++) { System.out.println("print2: " + i); Thread.sleep((int)(Math.random()*500)); } } catch (InterruptedException e) { System.out.println(e.getMessage()); } } public static void main(String[] args) { SynchronizedDemo demo = new SynchronizedDemo(); Thread t1 = new Thread() { public void run() { demo.print1(10); } }; Thread t2 = new Thread() { public void run() { demo.print2(10); } }; t1.start(); t2.start(); } }
true
f27b59d76e1b7bd32d106bd0ab796f1160c5bc2d
Java
GenZVirus/Hexy2
/src/main/java/com/genzvirus/hexy2/MainActivity.java
UTF-8
14,154
2.109375
2
[ "MIT" ]
permissive
package com.genzvirus.hexy2; import androidx.appcompat.app.AppCompatActivity; import android.content.pm.ActivityInfo; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.util.DisplayMetrics; import android.view.Display; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private boolean decimal = true; private boolean octal = false; private boolean binary = false; private boolean hexBool = false; private int decLimit = 9; private int binLimit = 30; private int octLimit = 10; private int hexLimit = 7; private ImageView num0; private ImageView num1; private ImageView num2; private ImageView num3; private ImageView num4; private ImageView num5; private ImageView num6; private ImageView num7; private ImageView num8; private ImageView num9; private ImageView numA; private ImageView numB; private ImageView numC; private ImageView numD; private ImageView numE; private ImageView numF; private ImageView decBtn; private ImageView binBtn; private ImageView octBtn; private ImageView hexBtn; private ImageView BS; private int resID; private ImageView image; private TextView dec; private TextView bin; private TextView oct; private TextView hex; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); this.num0 = (ImageView) findViewById(R.id.imageViewNum0); this.num1 = (ImageView) findViewById(R.id.imageViewNum1); this.num2 = (ImageView) findViewById(R.id.imageViewNum2); this.num3 = (ImageView) findViewById(R.id.imageViewNum3); this.num4 = (ImageView) findViewById(R.id.imageViewNum4); this.num5 = (ImageView) findViewById(R.id.imageViewNum5); this.num6 = (ImageView) findViewById(R.id.imageViewNum6); this.num7 = (ImageView) findViewById(R.id.imageViewNum7); this.num8 = (ImageView) findViewById(R.id.imageViewNum8); this.num9 = (ImageView) findViewById(R.id.imageViewNum9); this.numA = (ImageView) findViewById(R.id.imageViewNumA); this.numB = (ImageView) findViewById(R.id.imageViewNumB); this.numC = (ImageView) findViewById(R.id.imageViewNumC); this.numD = (ImageView) findViewById(R.id.imageViewNumD); this.numE = (ImageView) findViewById(R.id.imageViewNumE); this.numF = (ImageView) findViewById(R.id.imageViewNumF); this.decBtn = (ImageView) findViewById(R.id.imageViewDecBtn); this.octBtn = (ImageView) findViewById(R.id.imageViewOctBtn); this.hexBtn = (ImageView) findViewById(R.id.imageViewHexBtn); this.binBtn = (ImageView) findViewById(R.id.imageViewBinBtn); this.BS = (ImageView) findViewById(R.id.imageViewBS); this.dec = (TextView) findViewById(R.id.textViewDecOutput); this.bin = (TextView) findViewById(R.id.textViewBinOutput); this.oct = (TextView) findViewById(R.id.textViewOctOutput); this.hex = (TextView) findViewById(R.id.textViewHexOutput); DisplayMetrics displayMetrics=new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); decBtn.getLayoutParams().height=displayMetrics.widthPixels/8; decBtn.getLayoutParams().width=displayMetrics.widthPixels/8*2; decBtn.requestLayout(); octBtn.getLayoutParams().height=displayMetrics.widthPixels/8; octBtn.getLayoutParams().width=displayMetrics.widthPixels/8*2; octBtn.requestLayout(); hexBtn.getLayoutParams().height= displayMetrics.widthPixels/8; hexBtn.getLayoutParams().width=displayMetrics.widthPixels/8*2; hexBtn.requestLayout(); binBtn.getLayoutParams().height=displayMetrics.widthPixels/8; binBtn.getLayoutParams().width=displayMetrics.widthPixels/8*2; binBtn.requestLayout(); num1.getLayoutParams().height=num1.getLayoutParams().width=displayMetrics.widthPixels/5; num1.requestLayout(); num2.getLayoutParams().height=num2.getLayoutParams().width=displayMetrics.widthPixels/5; num2.requestLayout(); num3.getLayoutParams().height=num3.getLayoutParams().width=displayMetrics.widthPixels/5; num3.requestLayout(); numA.getLayoutParams().height=numA.getLayoutParams().width=displayMetrics.widthPixels/5; numA.requestLayout(); numB.getLayoutParams().height=numB.getLayoutParams().width=displayMetrics.widthPixels/5; numB.requestLayout(); num4.getLayoutParams().height=num4.getLayoutParams().width=displayMetrics.widthPixels/5; num4.requestLayout(); num5.getLayoutParams().height=num5.getLayoutParams().width=displayMetrics.widthPixels/5; num5.requestLayout(); num6.getLayoutParams().height=num6.getLayoutParams().width=displayMetrics.widthPixels/5; num6.requestLayout(); numC.getLayoutParams().height=numC.getLayoutParams().width=displayMetrics.widthPixels/5; numC.requestLayout(); numD.getLayoutParams().height=numD.getLayoutParams().width=displayMetrics.widthPixels/5; numD.requestLayout(); num7.getLayoutParams().height=num7.getLayoutParams().width=displayMetrics.widthPixels/5; num7.requestLayout(); num8.getLayoutParams().height=num8.getLayoutParams().width=displayMetrics.widthPixels/5; num8.requestLayout(); num9.getLayoutParams().height=num9.getLayoutParams().width=displayMetrics.widthPixels/5; num9.requestLayout(); numE.getLayoutParams().height=numE.getLayoutParams().width=displayMetrics.widthPixels/5; numE.requestLayout(); numF.getLayoutParams().height=numF.getLayoutParams().width=displayMetrics.widthPixels/5; numF.requestLayout(); num0.getLayoutParams().height=displayMetrics.widthPixels/5; num0.getLayoutParams().width=displayMetrics.widthPixels/5*3; num0.requestLayout(); BS.getLayoutParams().height=displayMetrics.widthPixels/5; BS.getLayoutParams().width=displayMetrics.widthPixels/5*2; BS.requestLayout(); if(decimal && !octal && !binary && !hexBool){ num0.setClickable(true); num1.setClickable(true); num2.setClickable(true); num3.setClickable(true); num4.setClickable(true); num5.setClickable(true); num6.setClickable(true); num7.setClickable(true); num8.setClickable(true); num9.setClickable(true); numA.setClickable(false); numB.setClickable(false); numC.setClickable(false); numD.setClickable(false); numE.setClickable(false); numF.setClickable(false); } } public void onClickDec(View v){ decimal = true; octal = false; binary = false; hexBool = false; changeImage(v); num0.setClickable(true); num1.setClickable(true); num2.setClickable(true); num3.setClickable(true); num4.setClickable(true); num5.setClickable(true); num6.setClickable(true); num7.setClickable(true); num8.setClickable(true); num9.setClickable(true); numA.setClickable(false); numB.setClickable(false); numC.setClickable(false); numD.setClickable(false); numE.setClickable(false); numF.setClickable(false); dec.setText(""); bin.setText(""); oct.setText(""); hex.setText(""); } public void onClickOct(View v){ decimal = false; octal = true; binary = false; hexBool = false; changeImage(v); num0.setClickable(true); num1.setClickable(true); num2.setClickable(true); num3.setClickable(true); num4.setClickable(true); num5.setClickable(true); num6.setClickable(true); num7.setClickable(true); num8.setClickable(false); num9.setClickable(false); numA.setClickable(false); numB.setClickable(false); numC.setClickable(false); numD.setClickable(false); numE.setClickable(false); numF.setClickable(false); dec.setText(""); bin.setText(""); oct.setText(""); hex.setText(""); } public void onClickBin(View v){ decimal = false; octal = false; binary = true; hexBool = false; changeImage(v); num0.setClickable(true); num1.setClickable(true); num2.setClickable(false); num3.setClickable(false); num4.setClickable(false); num5.setClickable(false); num6.setClickable(false); num7.setClickable(false); num8.setClickable(false); num9.setClickable(false); numA.setClickable(false); numB.setClickable(false); numC.setClickable(false); numD.setClickable(false); numE.setClickable(false); numF.setClickable(false); dec.setText(""); bin.setText(""); oct.setText(""); hex.setText(""); } public void onClickHex(View v){ decimal = false; octal = false; binary = false; hexBool = true; changeImage(v); num0.setClickable(true); num1.setClickable(true); num2.setClickable(true); num3.setClickable(true); num4.setClickable(true); num5.setClickable(true); num6.setClickable(true); num7.setClickable(true); num8.setClickable(true); num9.setClickable(true); numA.setClickable(true); numB.setClickable(true); numC.setClickable(true); numD.setClickable(true); numE.setClickable(true); numF.setClickable(true); dec.setText(""); bin.setText(""); oct.setText(""); hex.setText(""); } public void onClick(View v){ changeImage(v); if(decimal) { focusOn(dec,v,decLimit); bin.setText(dec.getText().toString().length() > 0 && dec.getText().toString() != null ? Dec.toBin(Integer.valueOf(dec.getText().toString())) : ""); oct.setText(dec.getText().toString().length() > 0 && dec.getText().toString() != null ? Dec.toOct(Integer.valueOf(dec.getText().toString())) : ""); hex.setText(dec.getText().toString().length() > 0 && dec.getText().toString() != null ? Dec.toHex(Integer.valueOf(dec.getText().toString())) : ""); } else if(binary){ focusOn(bin,v,binLimit); dec.setText(bin.getText().toString().length() > 0 && bin.getText().toString() != null ? Integer.toString(Bin.toDec(bin.getText().toString())) : ""); oct.setText(bin.getText().toString().length() > 0 && bin.getText().toString() != null ? Bin.toOct(bin.getText().toString()) : ""); hex.setText(bin.getText().toString().length() > 0 && bin.getText().toString() != null ? Bin.toHex(bin.getText().toString()).toUpperCase() : ""); } else if(octal){ focusOn(oct,v,octLimit); dec.setText(oct.getText().toString().length() > 0 && oct.getText().toString() != null ? Integer.toString(Oct.toDec(oct.getText().toString())) : ""); bin.setText(oct.getText().toString().length() > 0 && oct.getText().toString() != null ? Oct.toBin(oct.getText().toString()) : ""); hex.setText(oct.getText().toString().length() > 0 && oct.getText().toString() != null ? Oct.toHex(oct.getText().toString()).toUpperCase() : ""); } else if(hexBool){ focusOn(hex,v,hexLimit); dec.setText(hex.getText().toString().length() > 0 && hex.getText().toString() != null ? Integer.toString(Hex.toDec(hex.getText().toString())) : ""); bin.setText(hex.getText().toString().length() > 0 && hex.getText().toString() != null ? Hex.toBin(hex.getText().toString()) : ""); oct.setText(hex.getText().toString().length() > 0 && hex.getText().toString() != null ? Hex.toOct(hex.getText().toString()) : ""); } } private void focusOn(TextView tv, View v,int limit){ String text = v.getTag().toString(); text = Character.toString(text.charAt(text.length()-1)).toUpperCase(); String copy = tv.getText().toString(); if (((ImageView) v) != (ImageView) findViewById(R.id.imageViewBS)) { if (tv.getText().toString().length() < limit) tv.append(text); copy = tv.getText().toString(); } else { if (copy != null && copy.length() > 0) { copy = copy.substring(0, copy.length() - 1); tv.setText(copy); } } } private void changeImage(View v){ String name = v.getTag().toString() + "_on"; resID = getResources().getIdentifier(name , "drawable", getPackageName()); image = (ImageView) v; image.setImageResource(resID); name = v.getTag().toString() + "_off"; resID = getResources().getIdentifier(name , "drawable", getPackageName()); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { image.setImageResource(resID); } }, 50); } }
true
731f41ce160cd5434a6c736c0d130806ddbe2ef8
Java
hafeezali/glass-assistant
/Server/src/CaptionServer.java
UTF-8
4,893
3.03125
3
[]
no_license
import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class CaptionServer { private Socket socket = null; private ServerSocket serverSocket = null; private InputStream inputStream = null; private byte[] imageBytes; private Integer count = 0; private String path = "/home/hafeez/Desktop/Major Project/ImagesReceived/"; private String imageType = "jpg"; private String caption; private OutputStream out; private int byteCount; private boolean fileCreated; private Process process; private BufferedReader bufferedReader; private DataOutputStream dataOutputStream; private DataInputStream dataInputStream; private String isSendingImage; private String objects; private CaptionServer(int port) { try { serverSocket = new ServerSocket(port); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { CaptionServer captionServer = new CaptionServer(5000); captionServer.listen(); System.out.println(captionServer.getCaption()); } private void listen() { while (true) { try { socket = serverSocket.accept(); System.out.println("Connection Established..."); dataInputStream = new DataInputStream(socket.getInputStream()); isSendingImage = dataInputStream.readUTF(); if (isSendingImage.equals("TRUE")) { inputStream = socket.getInputStream(); imageBytes = new byte[16 * 1024]; fileCreated = false; while ((byteCount = inputStream.read(imageBytes)) > 0) { if (!fileCreated) { System.out.println("Receiving image: " + count.toString()); out = new FileOutputStream(path + count.toString() + "." + imageType); fileCreated = true; } out.write(imageBytes, 0, byteCount); } if (fileCreated) { out.close(); System.out.println("Saved image: " + count.toString()); socket.close(); caption = getCaption(); if (caption == null) { caption = "I am not really sure, but I think it's a blur. Please stay still and try again."; } System.out.println(caption); socket = serverSocket.accept(); dataOutputStream = new DataOutputStream(socket.getOutputStream()); dataOutputStream.writeUTF(caption); dataOutputStream.flush(); dataInputStream.close(); dataOutputStream.close(); socket.close(); objects = getObjects(); count++; } } else { if (objects == null) { objects = "Sorry, no objects have been identified. Please try again"; } dataInputStream.close(); socket.close(); socket = serverSocket.accept(); dataOutputStream = new DataOutputStream(socket.getOutputStream()); dataOutputStream.writeUTF(objects); dataOutputStream.flush(); dataInputStream.close(); dataOutputStream.close(); socket.close(); System.out.println(objects); } } catch (IOException e) { e.printStackTrace(); } } } private String getObjects() { try { process = Runtime.getRuntime().exec("python3 ./../MicrosoftAzure/analyze_image.py " + "./../../ImagesReceived/" + count.toString() + "." + imageType + " detect"); bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); objects = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } return objects; } private String getCaption() { try { process = Runtime.getRuntime().exec("python3 ./../MicrosoftAzure/analyze_image.py " + "./../../ImagesReceived/" + count.toString() + "." + imageType + " describe"); bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); caption = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } return caption; } }
true
725154ebc6de84a6e28aaac1ba362f76e1fc2166
Java
NikitaBukreyev/UniDump
/I Курс/1 Семестр/Прога/Лаб.2/op_lab2.java
UTF-8
1,202
3.296875
3
[]
no_license
import static java.lang.Math.*; class Lab2 { public static void main(String[] args) { Variant9 var9 = new Variant9(); System.out.println("Variant #9, result = " + var9.solve()); Variant19 var19 = new Variant19(); System.out.println("Variant #19, result = " + var19.solve()); Variant29 var29 = new Variant29(); System.out.println("Variant #99, result = " + var29.solve()); } } class Variant9 { private double a = -2.98; private double b = 5.55; private double c = 0.045; private double d = 0.129; public double solve() { double y = (sin(abs(a))+cos(sqrt(b))) / (2*tan(c)+exp(d)); return y; } } class Variant19 { private double a = 1.234; private double b = -3.12; private double c = 5.45; private double d = 2.0; public double solve() { double y = (pow(tan(a), c) / (1+cosh(log(d+c)))); return y; } } class Variant29 { private double a = -2.86; private double b = 1.62; private double c = 10.874; private double d = 2.19; public double solve() { double y = pow(2*cos(sqrt(a/b)+4*log(d+sqrt(pow(a, 2)+1))), c); return y; } }
true
fee367c362abd67bea60cf028fec80e1521250c7
Java
vikasv5/Assignment1
/src/main/java/com/mycompany/service/DealerService.java
UTF-8
1,930
2.265625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.service; /** * * @author Vikas */ import com.mycompany.database.DatabaseClass; import com.mycompany.model.Dealer; import com.mycompany.model.DeliveryAddress; import com.mycompany.model.Item; import com.mycompany.model.Order; import com.mycompany.model.OrderError; import com.mycompany.model.OrderMessage; import com.mycompany.model.OrderValid; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlElementWrapper; /** * * @author Vikas */ public class DealerService { private Map<String, Dealer> dealers = DatabaseClass.getDealers(); //public List<Dealer> dealers= new ArrayList<Dealer>(); public DealerService() { Dealer d1= new Dealer("dealer1","access1"); Dealer d2= new Dealer("dealer2","access2"); Dealer d3= new Dealer("dealer3","access3"); dealers.put(d1.getDealerId(), d1); dealers.put(d2.getDealerId(), d2); dealers.put(d3.getDealerId(), d3); // orders.put(2L, o2); // orders.put(3L, o3); } public List<Dealer> getAllDealersList() { return new ArrayList<Dealer>(dealers.values()); } public Map<String,Dealer> getAllDealersMap() { return dealers; } public Dealer getDealer(Long id) { Dealer dealer = dealers.get(id); if (dealer == null) { return null; } else { return dealer; } } // public Dealer addDealer(Dealer dealer) { // // } // // public Dealer updateDealer(Dealer dealer) { // // } public Dealer removeDealer(long id) { return dealers.remove(id); } }
true
17fa8befe888fd68edcd0e5cacbf58d139ac039f
Java
G4meM0ment/RPGEssentials
/src/me/G4meM0ment/Chaintrain/DataStorage/PlayerData.java
UTF-8
2,619
2.4375
2
[]
no_license
package me.G4meM0ment.Chaintrain.DataStorage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import me.G4meM0ment.Chaintrain.Chaintrain; import me.G4meM0ment.Chaintrain.Handler.PlayerHandler; import me.G4meM0ment.RPGEssentials.RPGEssentials; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; public class PlayerData { private RPGEssentials plugin; private Chaintrain subplugin; private PlayerHandler pH; private static File configFile; private static FileConfiguration config = null; private static String defConfig = "dropDataFileExample.yml"; private static String dir; public PlayerData(RPGEssentials plugin) { this.plugin = plugin; subplugin = new Chaintrain(); pH = new PlayerHandler(); dir = subplugin.getDir()+"/data"; configFile = new File(dir+"/player"); } public PlayerData() { plugin = ((RPGEssentials) Bukkit.getPluginManager().getPlugin("RPGEssentials")); subplugin = new Chaintrain(); pH = new PlayerHandler(); } public void reloadConfig() { if (configFile == null) { configFile = new File(dir+"/player"); plugin.getLogger().info("Created player file."); } config = YamlConfiguration.loadConfiguration(configFile); // Look for defaults in the jar InputStream defConfigStream = plugin.getResource(defConfig); if (defConfigStream != null) { YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); config.setDefaults(defConfig); config.options().copyHeader(true); config.options().copyDefaults(true); } plugin.getLogger().info("Player data loaded."); } public FileConfiguration getConfig() { if (config == null) reloadConfig(); return config; } public void saveConfig() { if (config == null || configFile == null) return; try { config.save(configFile); } catch (IOException ex) { plugin.getLogger().log(Level.SEVERE, "Could not save data to " + configFile, ex); } } public void saveDataToFile() { //clear old file for(String s : getConfig().getRoot().getKeys(false)) { pH.setChained(s, null); } //save cache map to file for(String s : pH.getChainedList().keySet()) { getConfig().set(s, pH.getChainer(s)); } saveConfig(); } public void loadDataFromFile() { for(String s : getConfig().getRoot().getKeys(false)) { pH.setChained(s, getConfig().getString(s)); } } }
true
704f12848ff827726eb59662d3a65fc5f84502e8
Java
jeahun/opensource
/Item.java
UTF-8
1,830
2.1875
2
[]
no_license
package com.example.webview; import java.io.File; import java.util.List; import android.os.Parcel; import android.os.Parcelable; public class Item implements Parcelable { public String url; public String realName; public File downFile; public String localPath; public List<File> listDownFfile; boolean isChekced; public Item(String url, String realName) { this.url = url; this.realName = realName; } public Item(String url, String realName, File dirList) { this.url = url; this.realName = realName; this.downFile = dirList; } @Override public String toString() { return "url : " + url + ", realName : " + realName; } public Item(Parcel in) { readFromParcel(in); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel dest, int flags) { // TODO Auto-generated method stub dest.writeString(url); dest.writeString(realName); } private void readFromParcel(Parcel in) { // TODO Auto-generated method stub url = in.readString(); realName = in.readString(); } @SuppressWarnings("rawtypes") public static final Parcelable.Creator<Item> CREATOR = new Parcelable.Creator<Item>() { @Override public Item createFromParcel(Parcel in) { return new Item(in); } @Override public Item[] newArray(int size) { // TODO Auto-generated method stub return new Item[size]; } }; }
true