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
619420cc2d4913fd638eef45e5cb1611957ae173
Java
olgaFaber/beam-extapi
/src/main/java/org/esa/beam/extapi/gen/ApiInfo.java
UTF-8
9,907
2.375
2
[]
no_license
package org.esa.beam.extapi.gen; import com.sun.javadoc.*; import java.util.*; /** * Collection of API classes and their methods. * Immutable object. * * @author Norman Fomferra */ public final class ApiInfo { private final ApiGeneratorConfig config; private final Map<ApiClass, ApiMembers> apiClasses; private final Map<ApiClass, ApiMembers> allClasses; private final Set<ApiClass> usedNonApiClasses; private ApiInfo(ApiGeneratorConfig config, Map<ApiClass, ApiMembers> apiClasses, Map<ApiClass, ApiMembers> allClasses, Set<ApiClass> usedNonApiClasses) { this.config = config; this.apiClasses = apiClasses; this.allClasses = allClasses; this.usedNonApiClasses = usedNonApiClasses; } public ApiGeneratorConfig getConfig() { return config; } public Set<ApiClass> getApiClasses() { return Collections.unmodifiableSet(apiClasses.keySet()); } public Set<ApiClass> getAllClasses() { return Collections.unmodifiableSet(allClasses.keySet()); } public Set<ApiClass> getUsedNonApiClasses() { return Collections.unmodifiableSet(usedNonApiClasses); } public List<ApiConstant> getConstantsOf(ApiClass apiClass) { ApiMembers members = apiClasses.get(apiClass); return Collections.unmodifiableList(members != null ? members.apiConstants : new ArrayList<ApiConstant>(0)); } public List<ApiMethod> getMethodsOf(ApiClass apiClass) { ApiMembers members = apiClasses.get(apiClass); return Collections.unmodifiableList(members != null ? members.apiMethods : new ArrayList<ApiMethod>(0)); } public List<ApiConstant> getConstantsUsing(ApiClass apiClass) { ApiMembers members = allClasses.get(apiClass); return Collections.unmodifiableList(members != null ? members.apiConstants : new ArrayList<ApiConstant>(0)); } public List<ApiMethod> getMethodsUsing(ApiClass apiClass) { ApiMembers members = allClasses.get(apiClass); return Collections.unmodifiableList(members != null ? members.apiMethods : new ArrayList<ApiMethod>(0)); } public ApiParameter[] getParametersFor(ApiMethod apiMethod) { Parameter[] parameters = apiMethod.getMemberDoc().parameters(); ApiParameter[] apiParameters = new ApiParameter[parameters.length]; ApiParameter.Modifier[] parameterModifiers = getConfig().getParameterModifiers(apiMethod.getEnclosingClass().getJavaName(), apiMethod.getJavaName(), apiMethod.getJavaSignature()); if (parameterModifiers != null) { if (parameters.length != parameterModifiers.length) { throw new IllegalStateException("parameters.length != parameterModifiers.length"); } for (int i = 0; i < parameters.length; i++) { apiParameters[i] = new ApiParameter(parameters[i], parameterModifiers[i]); } return apiParameters; } else { for (int i = 0; i < parameters.length; i++) { apiParameters[i] = new ApiParameter(parameters[i], ApiParameter.Modifier.IN); } return apiParameters; } } public static ApiInfo create(ApiGeneratorConfig config, RootDoc rootDoc) { Map<ApiClass, ApiMembers> apiClasses = getApiMembers(rootDoc, config); Map<ApiClass, ApiMembers> allClasses = getAllClasses(apiClasses); Set<ApiClass> usedNonApiClasses = getUsedNonApiClasses(apiClasses, allClasses); return new ApiInfo(config, apiClasses, allClasses, usedNonApiClasses); } private static Map<ApiClass, ApiMembers> getApiMembers(RootDoc rootDoc, ApiGeneratorConfig config) { Map<ApiClass, ApiMembers> apiClasses = new HashMap<ApiClass, ApiMembers>(1000); for (ClassDoc classDoc : rootDoc.classes()) { final boolean isPublic = classDoc.isPublic(); final boolean isApiClass = config.isApiClass(classDoc.qualifiedName()); if (isPublic && isApiClass) { ApiClass apiClass = new ApiClass(classDoc); ArrayList<ApiConstant> apiConstants = new ArrayList<ApiConstant>(); ArrayList<ApiMethod> apiMethods = new ArrayList<ApiMethod>(); for (ConstructorDoc constructorDoc : classDoc.constructors()) { ApiMethod apiMethod = new ApiMethod(apiClass, constructorDoc); if (isApiMethod(config, apiMethod)) { apiMethods.add(apiMethod); } else { System.out.printf("Filtered out: constructor %s#%s()\n", classDoc.qualifiedTypeName(), constructorDoc.name()); } } ClassDoc classDoc0 = classDoc; do { for (FieldDoc fieldDoc : classDoc0.fields()) { if (fieldDoc.isPublic() && fieldDoc.isStatic() && fieldDoc.isFinal()) { apiConstants.add(new ApiConstant(apiClass, fieldDoc)); } } for (MethodDoc methodDoc : classDoc0.methods()) { ApiMethod apiMethod = new ApiMethod(apiClass, methodDoc); if (isApiMethod(config, apiMethod)) { if (classDoc0 == classDoc || !apiMethods.contains(apiMethod)) { apiMethods.add(apiMethod); } } else { System.out.printf("Filtered out: method %s#%s()\n", classDoc.qualifiedTypeName(), methodDoc.name()); } } classDoc0 = classDoc0.superclass(); } while (classDoc0 != null && !isObjectClass(classDoc0)); apiClasses.put(apiClass, new ApiMembers(apiConstants, apiMethods)); } else { System.out.printf("Filtered out: class %s\n", classDoc.qualifiedTypeName()); } } return apiClasses; } private static boolean isApiMethod(ApiGeneratorConfig config, ApiMethod apiMethod) { return apiMethod.getMemberDoc().isPublic() && apiMethod.getMemberDoc().tags("deprecated").length == 0 && config.isApiMethod(apiMethod.getEnclosingClass().getJavaName(), apiMethod.getJavaName(), apiMethod.getJavaSignature()); } private static boolean isObjectClass(Type type) { return type.qualifiedTypeName().equalsIgnoreCase("java.lang.Object"); } private static Map<ApiClass, ApiMembers> getAllClasses(Map<ApiClass, ApiMembers> apiClasses) { Map<ApiClass, ApiMembers> allClasses = new HashMap<ApiClass, ApiMembers>(); for (Map.Entry<ApiClass, ApiMembers> entry : apiClasses.entrySet()) { allClasses.put(entry.getKey(), new ApiMembers()); } for (Map.Entry<ApiClass, ApiMembers> entry : apiClasses.entrySet()) { ApiMembers apiMembers = entry.getValue(); for (ApiConstant apiConstant : apiMembers.apiConstants) { collectAllClasses(apiConstant.getType(), apiConstant, allClasses); } for (ApiMethod apiMethod : apiMembers.apiMethods) { collectAllClasses(apiMethod.getReturnType(), apiMethod, allClasses); for (Parameter parameter : apiMethod.getMemberDoc().parameters()) { collectAllClasses(parameter.type(), apiMethod, allClasses); } } } return allClasses; } private static void collectAllClasses(Type type, ApiConstant apiConstant, Map<ApiClass, ApiMembers> allClasses) { if (!type.isPrimitive()) { ApiMembers referencingMembers = getApiMembers(allClasses, type); referencingMembers.apiConstants.add(apiConstant); } } private static void collectAllClasses(Type type, ApiMethod apiMethod, Map<ApiClass, ApiMembers> allClasses) { if (!type.isPrimitive()) { ApiMembers referencingMembers = getApiMembers(allClasses, type); referencingMembers.apiMethods.add(apiMethod); } } private static ApiMembers getApiMembers(Map<ApiClass, ApiMembers> allClasses, Type type) { ApiClass usedClass = new ApiClass(type); ApiMembers referencingMembers = allClasses.get(usedClass); if (referencingMembers == null) { referencingMembers = new ApiMembers(); allClasses.put(usedClass, referencingMembers); } return referencingMembers; } private static Set<ApiClass> getUsedNonApiClasses(Map<ApiClass, ApiMembers> apiClasses, Map<ApiClass, ApiMembers> allClasses) { HashSet<ApiClass> usedClasses = new HashSet<ApiClass>(); for (ApiClass apiClass : allClasses.keySet()) { if (!apiClasses.containsKey(apiClass)) { usedClasses.add(apiClass); } } return usedClasses; } private final static class ApiMembers { private final List<ApiConstant> apiConstants; private final List<ApiMethod> apiMethods; private ApiMembers() { this.apiConstants = new ArrayList<ApiConstant>(); this.apiMethods = new ArrayList<ApiMethod>(); } private ApiMembers(List<ApiConstant> apiConstants, List<ApiMethod> apiMethods) { this.apiConstants = apiConstants; this.apiMethods = apiMethods; } } }
true
246595aa88a267a858c5b6fb63ff24d7f5a4401c
Java
BabyTitanium/netweb
/.svn/pristine/55/5544a11ae80d92bd38b29a9a504e632f872acdc8.svn-base
UTF-8
404
1.90625
2
[]
no_license
package com.ps.net.model; public class RoomTempAddrKey { private Integer room_id; private Integer index; public Integer getRoom_id() { return room_id; } public void setRoom_id(Integer room_id) { this.room_id = room_id; } public Integer getIndex() { return index; } public void setIndex(Integer index) { this.index = index; } }
true
2b9c88986d80b060753d95c5b764eb0dedfaab9d
Java
MarcoDeMeco/Campo-minato
/src/campoMinato/Main.java
UTF-8
8,718
2.421875
2
[]
no_license
package campoMinato; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import java.util.ArrayList; import java.util.Random; /** * @author Marco De Meco * @version (ultima modifica) 06/07/2018 */ public class Main { private static int caselleScoperte; private static int righe; private static int colonne; private static int mineTotali; private static int[][] campo; private static Casella[][] caselle; private static JPanel root; private static JPanel griglia; private static JPanel stato; private static JPanel pulsante; private static JFrame fin; private static URL sorrisoURL; private static URL vittoriaURL; private static URL sconfittaURL; private static ImageIcon sorriso; private static ImageIcon occhiali; private static ImageIcon triste; private static Timer t; private static JButton smile; public static void repaint(){ griglia.repaint(); stato.repaint(); } public static void costruisciCampo() { //La funzione può essere chiamata più volte quindi assicuriamoci di ripulire l'interfaccia grafica griglia.removeAll(); root.remove(griglia); Random rand = new Random(); int random; for(int i=0; i<campo.length; i++){ for(int j=0; j<campo[0].length; j++){ campo[i][j]=0; } } ArrayList<Integer> mine = new ArrayList<Integer>(mineTotali); random = rand.nextInt(righe*colonne-1); for(int i=0; i<mineTotali; i++){ while(mine.contains(random)){ random = rand.nextInt(righe*colonne); } mine.add(random); } int r; int c; for(int i:mine){ r=(i/colonne); c=(i%colonne); campo[r][c]=10; } for(int riga=0; riga<righe; riga++){ for(int colonna=0; colonna<colonne; colonna++){ if(campo[riga][colonna]==10){ for(int i=-1; i<2; i++) { for(int j=-1; j<2; j++) { if(j==0 && i==0) continue; else if(riga+i < righe && riga+i>=0 && colonna+j < colonne && colonna+j>=0 && campo[riga+i][colonna+j]!=10) campo[riga+i][colonna+j]++; } } } } } int valore; boolean bandiera=false; for(int i=0; i<righe; i++){ for(int j=0; j<colonne; j++){ valore = campo[i][j]; /* * Nella remota possibilità in cui l'utente metta delle bandiere e al suo primo click prenda una bomba, * il campo verrà ricostruito lasciando invariate le posizioni delle bandiere * * Assicuriamoci di catturare l'eccezione in caso le caselle non siano ancora state create */ try{ bandiera = caselle[i][j].isBandiera(); }catch(NullPointerException e){} caselle[i][j] = new Casella(valore,i,j); caselle[i][j].setBandiera(bandiera); griglia.add(caselle[i][j]); } } root.add(griglia); fin.setContentPane(root); } public static int bandiereAdiacenti(int riga, int colonna){ int cont = 0; for(int i=-1; i<2; i++) { for(int j=-1; j<2; j++) { if(j==0 && i==0) continue; else if(riga+i < righe && riga+i>=0 && colonna+j < colonne && colonna+j>=0) { if(caselle[riga+i][colonna+j].isBandiera()) cont++; } } } return cont; } public static void scopriAdiacenti(int riga, int colonna){ for(int i=-1; i<2; i++) { for(int j=-1; j<2; j++) { if(riga+i < righe && riga+i>=0 && colonna+j < colonne && colonna+j>=0) { /* * questo if mi assicura che, una volta che, per qualsiasi motivo, * la partita sia finita, l'esecutore esca da questa funzione e smetta di selezionare * caselle evitando quindi di trovarsi ad iniziare una partita con caselle già scoperte * da questa funzione */ if(Casella.isPrimoClick()) return; caselle[riga+i][colonna+j].seleziona(); } } } } public static void scopriTutte(){ for(Casella[] i:caselle){ for(Casella j:i){ j.seleziona(); } } repaint(); t.interrompiTimer(); smile.setIcon(triste); Casella.setOsservazione(true); if(JOptionPane.showConfirmDialog(null, "Hai perso!\nVuoi iniziare un'altra partita?", "Fine partita", JOptionPane.YES_NO_OPTION)==0) rigioca(); } public static void primoClick(int i, int j){ while(campo[i][j]!=0){ costruisciCampo(); } caselle[i][j].seleziona(); t.iniziaTimer(); } public static void controllaVittoria(){ caselleScoperte++; if(caselleScoperte==(righe*colonne-mineTotali)){ t.interrompiTimer(); smile.setIcon(occhiali); //Evitiamo che nel momento in cui si scelga di osservare la partita, l'utente continui a scoprire caselle Casella.setOsservazione(true); if(JOptionPane.showConfirmDialog(null, "Hai vinto! Hai impiegato "+t.getTempo()+" secondi\nVuoi iniziare un'altra partita?", "Fine partita", JOptionPane.YES_NO_OPTION)==0) rigioca(); } } public static void rigioca() { /* * questo metodo può essere chiamato da Smile anche se l'utente non ha ancora concluso la partita * assicuriamoci, dunque, di fermare il thread che conta il tempo */ t.interrompiTimer(); t.reset(); smile.setIcon(sorriso); Casella.setContBandiere(0); Casella.setPrimoClick(true); Casella.setGameOver(false); Casella.setOsservazione(false); caselleScoperte = 0; //Dato che la funzione costruisciCampo memorizza le bandiere, assicuriamoci di resettare il tutto for(Casella[] i : caselle){ for(Casella j : i){ j.setBandiera(false); } } costruisciCampo(); } public static void main(String[] args) { caselleScoperte=0; righe=9; colonne=9; mineTotali=10; campo = new int[righe][colonne]; caselle = new Casella[righe][colonne]; root = new JPanel(new BorderLayout()); griglia = new JPanel(new GridLayout(righe, colonne)); stato = new JPanel(new GridLayout(1, 3)); pulsante = new JPanel(new FlowLayout(10, 34, 10)); fin = new JFrame("Campo Minato"); sorrisoURL = Main.class.getResource("/Smile.png"); vittoriaURL = Main.class.getResource("/Vittoria.png"); sconfittaURL = Main.class.getResource("/Sconfitta.png"); sorriso = new ImageIcon(new ImageIcon(sorrisoURL).getImage().getScaledInstance(30, 30, Image.SCALE_DEFAULT)); occhiali = new ImageIcon(new ImageIcon(vittoriaURL).getImage().getScaledInstance(30, 30, Image.SCALE_DEFAULT)); triste = new ImageIcon(new ImageIcon(sconfittaURL).getImage().getScaledInstance(30, 30, Image.SCALE_DEFAULT)); t = new Timer(); t.setBackground(Color.lightGray); smile = new JButton(); @SuppressWarnings("serial") JPanel bandierine = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setFont(new Font("Dialog", Font.PLAIN, 20)); g.setColor(Color.black); g.fillRect(22, 8, 65, 34); g.setColor(Color.red); g.drawString(Integer.toString(10-Casella.getContBandiere()), 55-(Integer.toString(10-Casella.getContBandiere()).length()*5), 33); } }; bandierine.setBackground(Color.lightGray); costruisciCampo(); griglia.setBackground(Color.lightGray); griglia.setBorder(BorderFactory.createLineBorder(Color.gray)); smile.setPreferredSize(new Dimension(30, 30)); smile.setBackground(Color.GRAY); smile.setBorder(BorderFactory.createLineBorder(Color.gray)); smile.setIcon(sorriso); smile.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { rigioca(); } }); pulsante.setBackground(Color.lightGray); pulsante.add(smile); stato.add(bandierine); stato.add(pulsante); stato.add(t); stato.setBackground(Color.LIGHT_GRAY); stato.setBorder(BorderFactory.createLineBorder(Color.gray)); stato.setPreferredSize(new Dimension(100, 50)); root.setBorder(BorderFactory.createLineBorder(Color.gray)); root.add(stato, BorderLayout.NORTH); fin.setSize(300, 350); fin.setResizable(false); fin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fin.setLocationRelativeTo(null); fin.setVisible(true); JOptionPane.showMessageDialog(null, "Benvenuto a Campo Minato\n\n" + "Comandi:\n\n" + "- Click sinistro per scoprire le caselle\n" + "- Click destro per bandiera\n" + "- Pulsante smile per ricominciare\n" + "- Click centrale o doppio click per scoprire le caselle adiacenti\n" + " (Solo nel caso in cui siano posizionate abbastanza bandierine)\n\n" + "Buona fortuna!!!"); } }
true
bf8e6b9bd0150c1022c0412271cb15e6ee01df65
Java
raghuTraining/test
/eclipse-workspace/Amazon/src/test/java/tests/sauceLabs.java
UTF-8
1,223
1.953125
2
[]
no_license
package tests; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.UnreachableBrowserException; public class sauceLabs { public static final String nme="vidyanand3"; public static final String pss="rM5LDjdtqS2k39QqFvAs"; public static final String nodeURL="http://"+nme+":"+pss+"@hub-cloud.browserstack.com/wd/hub"; public static void main(String[] args) throws MalformedURLException { WebDriver driver; String baseURL; baseURL= "https://www.naukri.com"; DesiredCapabilities caps = DesiredCapabilities.chrome(); caps.setCapability("platform", "Windows 10"); caps.setCapability("version", "latest"); // WebDriver driver = new RemoteWebDriver(new URL( // driver= new RemoteWebDriver(new URI(nodeURL), caps); // WebDriver driver1 = new RemoteWebDriver(new URI(nodeURL), caps); // driver.get(baseURL); //driver.findElement(By.xpath("//*[@id=\"navbar-collapse\"]/ul/li[3]/a")); } }
true
b397c1557c2788ef35169143da2404827e121f06
Java
t0tec/formula-one-api
/main/rest/src/main/java/org/formulaone/rest/controller/CircuitController.java
UTF-8
4,948
2.375
2
[]
no_license
package org.formulaone.rest.controller; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; import org.formulaone.rest.wrapper.CircuitPage; import org.formulaone.rest.wrapper.CircuitResource; import org.formulaone.rest.wrapper.CircuitTable; import org.formulaone.service.CircuitReadOnlyService; import org.formulaone.service.dto.CircuitDto; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; /** * @author t0tec (t0tec.olmec@gmail.com) * @version $Id$ * @since 1.0 */ @Api(value = "circuits", description = "Returns information about the circuits" + " where Formula One races are hosted" , position = 1) @RestController @RequestMapping("/api/circuits") public class CircuitController { private static final Logger logger = LoggerFactory.getLogger(CircuitController.class); private final CircuitReadOnlyService circuitReadOnlyService; @Autowired CircuitController(CircuitReadOnlyService circuitReadOnlyService) { this.circuitReadOnlyService = circuitReadOnlyService; } /** * Finds a single circuit entry by reference name. * * @param referenceName The referenceName of the requested entry. * @return The information of the requested entry. * @throws org.formulaone.core.exception.NotFoundException if no entry is found by using the given * referenceName. */ @ApiOperation(value = "Returns a circuit entry", notes = "Finds a single circuit entry by a unique reference name", position = 2) @RequestMapping(value = "/{referenceName}", method = RequestMethod.GET) @ResponseBody CircuitResource findByReferenceName( @ApiParam(value = "Unique reference name of a circuit", required = true) @PathVariable("referenceName") String referenceName) { logger.info("Finding circuit entry by using referenceName: {}", referenceName); CircuitDto circuitEntry = circuitReadOnlyService.findByReferenceName(referenceName); logger.info("Found circuit entry: {}", circuitEntry); CircuitResource resource = new CircuitResource(circuitEntry); resource .add(linkTo(CircuitController.class).slash(circuitEntry.getReferenceName()).withSelfRel()); return resource; } /** * Finds all circuit entries. * * @return The information of all entries. */ @ApiOperation(value = "Returns a list of all circuits", notes = "Finds a list of circuit entries ordered alphabetically", position = 3) @RequestMapping(value = "/all", method = RequestMethod.GET) @ResponseBody CircuitTable findAll() { logger.info("Finding all circuit entries"); List<CircuitDto> circuitEntries = circuitReadOnlyService.findAll(); logger.info("Found {} circuit entries.", circuitEntries.size()); return new CircuitTable(circuitEntries); } /** * Finds all circuit entries paginated. * * @param page the page you are requesting * @param size the size of entries per page * @return The information of all entries paginated. */ @ApiOperation(value = "Returns a list of circuits limited by a query parameter", notes = "The number of results that are returned can be controlled using a limit query parameter. " + "Please use the smallest value that your application needs. If not specified, the default value is 30. " + "A page number into the url can also be specified using a page query parameter. " + "A page numbers starts at 0. For example: 'api/circuits?page=1&size=50' returns the second page of circuit information containing fifty entries per page." , position = 4) @RequestMapping(method = RequestMethod.GET) @ResponseBody CircuitPage findAllPageable(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "30") int size) { Pageable pageable = new PageRequest( page, size ); Page<CircuitDto> pageResult = circuitReadOnlyService.findAll(pageable); logger.info("Found {} circuit entries paged by {} {}.", pageResult.getNumberOfElements(), page, size); return new CircuitPage(pageResult, "page", "size"); } }
true
0e74de59bcc263a5fbd8cd7f1f4d0fce2cbdbb28
Java
nagyist/icoin
/icoin-fee/src/test/java/com/icoin/trading/fee/cash/interceptor/MaxAmountPerDayExecutingInterceptorTest.java
UTF-8
4,189
1.976563
2
[]
no_license
package com.icoin.trading.fee.cash.interceptor; import com.google.common.collect.ImmutableList; import com.icoin.trading.fee.cash.Invocation; import com.icoin.trading.fee.cash.InvocationContext; import com.icoin.trading.fee.cash.ValidationCode; import com.icoin.trading.fee.domain.DueDateService; import com.icoin.trading.fee.domain.cash.CashRepository; import com.icoin.trading.fee.domain.cash.CoinReceiveCash; import org.joda.money.BigMoney; import org.joda.money.CurrencyUnit; import org.junit.Test; import java.math.BigDecimal; import java.util.Date; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Created with IntelliJ IDEA. * User: liougehooa * Date: 14-4-1 * Time: PM11:44 * To change this template use File | Settings | File Templates. */ public class MaxAmountPerDayExecutingInterceptorTest { @Test public void testAllowed() throws Exception { final InvocationContext context = mock(InvocationContext.class); final Invocation invocation = mock(Invocation.class); when(invocation.getInvocationContext()).thenReturn(context); CashRepository cashRepository = mock(CashRepository.class); final CoinReceiveCash cash1 = new CoinReceiveCash(); cash1.confirm(BigMoney.of(CurrencyUnit.of("BTC"), BigDecimal.TEN), new Date()); final CoinReceiveCash cash2 = new CoinReceiveCash(); cash2.confirm(BigMoney.of(CurrencyUnit.of("BTC"), BigDecimal.ONE), new Date()); when(cashRepository.findByUserId(anyString(), any(Date.class))). thenReturn(ImmutableList.of(cash1), ImmutableList.of(cash2)); DueDateService dateService = mock(DueDateService.class); final MaxAmountPerDayExecutingInterceptor interceptor = new MaxAmountPerDayExecutingInterceptor("BTC 10"); interceptor.setCashRepository(cashRepository); interceptor.setService(dateService); final ValidationCode validationCode1 = interceptor.intercept(invocation); final ValidationCode validationCode2 = interceptor.intercept(invocation); assertThat(validationCode1, anyOf(nullValue(), is(ValidationCode.SUCCESSFUL))); assertThat(validationCode2, anyOf(nullValue(), is(ValidationCode.SUCCESSFUL))); verify(invocation, times(2)).invoke(); verify(dateService, times(2)).computeDueDate(any(Date.class)); verify(invocation, times(2)).invoke(); } @Test public void testDisallowed() throws Exception { final InvocationContext context = mock(InvocationContext.class); final Invocation invocation = mock(Invocation.class); when(invocation.getInvocationContext()).thenReturn(context); CashRepository cashRepository = mock(CashRepository.class); final CoinReceiveCash cash1 = new CoinReceiveCash(); cash1.confirm(BigMoney.of(CurrencyUnit.of("BTC"), BigDecimal.TEN), new Date()); final CoinReceiveCash cash2 = new CoinReceiveCash(); cash2.confirm(BigMoney.of(CurrencyUnit.of("BTC"), BigDecimal.ONE), new Date()); when(cashRepository.findByUserId(anyString(), any(Date.class))). thenReturn(ImmutableList.of(cash1, cash2)); DueDateService dateService = mock(DueDateService.class); final MaxAmountPerDayExecutingInterceptor interceptor = new MaxAmountPerDayExecutingInterceptor("BTC 10"); interceptor.setCashRepository(cashRepository); interceptor.setService(dateService); final ValidationCode validationCode = interceptor.intercept(invocation); assertThat(validationCode, is(ValidationCode.EXCEEDED_MAX_AMOUNT_PER_DAY)); verify(dateService).computeDueDate(any(Date.class)); verify(invocation, never()).invoke(); } }
true
a767ac7832a5973db8d5c9afeb1ccb2ff6b4e372
Java
XueyinGuo/LeetCode
/src/com/szu/training01/class06/StringCross.java
UTF-8
1,994
3.765625
4
[]
no_license
package com.szu.training01.class06; /* * @Author 郭学胤 * @University 深圳大学 * @Description * * PAGE 234 * * 给定三个字符串 str1、str2 , aim, 如果 aim 中包含且仅包含str1、str2中所有的字符 * 而且在 aim 中 属于str1 字符之间的 顺序 与原来保持一致, str2 也是 * 那么说 aim 是 str1 与 str2 的 交错组成。 * * 实现一个函数,判断 aim 是否是 str1 str2 的交错组成 * * 举例 : * str1 : “AB” str2:“12” * A12B AB12 A1B2 都是交错组成 * * * * @Date 2021/4/21 22:48 */ public class StringCross { public static boolean isCross(String s1, String s2, String aim) { if (aim == null || aim.length() != (s1 == null ? 0 : s1.length()) + (s2 == null ? 0 : s2.length())) return false; char[] str1 = s1.toCharArray(); char[] str2 = s2.toCharArray(); char[] strAim = aim.toCharArray(); int rows = str1.length + 1; int cols = str2.length + 1; boolean[][] dp = new boolean[rows][cols]; dp[0][0] = true; for (int c = 1; c < cols; c++) { if (str2[c - 1] != strAim[c - 1]) break; dp[0][c] = true; } for (int r = 1; r < cols; r++) { if (str1[r - 1] != strAim[r - 1]) break; dp[r][0] = true; } for (int r = 1; r < rows; r++) { for (int c = 1; c < cols; c++) { if (str1[r - 1] == strAim[r + c - 1] && dp[r - 1][c]) dp[r][c] = true; if (str2[c - 1] == strAim[r + c - 1] && dp[r][c - 1]) dp[r][c] = true; } } return dp[rows - 1][cols - 1]; } public static void main(String[] args) { String str1 = "aabc"; String str2 = "aaa31"; String aim = "aaa3aab1c"; boolean cross = isCross(str1, str2, aim); System.out.println(cross); } }
true
1e4be1126b8fb6bed15013635dc1eeb5c3c765fb
Java
zawn/logback-lite
/app/src/test/java/com/appunity/logger/LoggerTest.java
UTF-8
3,267
2.515625
3
[]
no_license
package com.appunity.logger; import org.apache.commons.codec.binary.Base64; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.time.Clock; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import ch.qos.logback.classic.LoggerContext; public class LoggerTest { private static final String srcFile = "D:\\GitHub\\android-contexts\\logger\\build\\dump.txt"; @Test public void largeAndDaysTest() throws IOException, InterruptedException { int day = 10; while (day < 11) { for (int i = 0; i < 1; i++) { testLogger(day); Thread.sleep(500); } day++; } } @Test public void testKey() { String keyString = "liFkRAy9Vqg="; byte[] keyBytes = Base64.decodeBase64(keyString); System.out.println(HexDump.dumpHexString(keyBytes)); } private static SecretKey getKey() { String keyString = "liFkRAy9Vqg="; byte[] keyBytes = Base64.decodeBase64(keyString); return new SecretKeySpec(keyBytes, "DES"); } private void testLogger(int day) throws IOException { System.out.println(new Date() + " " + day); LoggerConfig.configure("D:/testlog", getKey()); final Logger logger = LoggerFactory.getLogger(ExampleUnitTest.class); File file3 = new File(srcFile); InputStreamReader streamReader = new InputStreamReader(new FileInputStream(file3)); BufferedReader bufferedReader = new BufferedReader(streamReader); String line = bufferedReader.readLine(); while (line != null) { logger.debug(line); line = bufferedReader.readLine(); } LoggerContext loggerFactory = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerFactory.stop(); } @Test public void date() { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHssmm"); String beforeS = TimeMachine.now().format(dateTimeFormatter); System.out.println("beforeS " + beforeS); LocalDateTime fixTime = LocalDateTime.parse("20081212085959", dateTimeFormatter); TimeMachine.useFixedClockAt(fixTime); String afterS = TimeMachine.now().format(dateTimeFormatter); System.out.println("afterS " + afterS); } public static class TimeMachine { private static Clock clock = Clock.systemDefaultZone(); private static ZoneId zoneId = ZoneId.systemDefault(); public static LocalDateTime now() { return LocalDateTime.now(getClock()); } public static void useFixedClockAt(LocalDateTime date) { clock = Clock.fixed(date.atZone(zoneId).toInstant(), zoneId); } public static void useSystemDefaultZoneClock() { clock = Clock.systemDefaultZone(); } private static Clock getClock() { return clock; } } }
true
65f3a028fc49721a26abc6aeeca8ba6416e98ed4
Java
sl4475/CustomEnchantPlugin
/src/sl4475/Enchantments/Magnetism.java
UTF-8
3,010
2.59375
3
[]
no_license
package sl4475.Enchantments; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.EnchantmentTarget; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import com.gmail.nossr50.api.ExperienceAPI; public class Magnetism extends Enchantment implements Listener { public Magnetism(int id) { super(id); } @EventHandler public void onSugarCaneMine(BlockBreakEvent event) { Block block= event.getBlock(); if(block.getType().equals(Material.SUGAR_CANE_BLOCK) && event.getPlayer() instanceof Player) { Player player = event.getPlayer(); ItemStack item = player.getItemInHand(); if(item!=null && item.getType().toString().toLowerCase().contains("hoe")&&item.containsEnchantment(this)) { event.setCancelled(true); double level = ExperienceAPI.getLevel(player, "herbalism"); int sugarCane = 0; int newY = 0; for (int y = block.getY(); y != 255; y++) { // get the block relative to that height Location newLoc = new Location(block.getWorld(), block.getX(), y, block.getZ()); //player.sendMessage(""+newLoc.getBlock().getType()); if(newLoc.getBlock().getType().equals(Material.SUGAR_CANE_BLOCK)) { double check = Math.random(); if(check<level/1000) { //player.sendMessage("BONUS"); sugarCane++; } sugarCane++; } else { newY = y; player.getInventory().addItem(new ItemStack(Material.SUGAR_CANE, sugarCane)); break; } } //set sugar canes to air for(int y = newY; y != block.getY(); y--) { Location newLoc = new Location(block.getWorld(), block.getX(), y, block.getZ()); if(newLoc.getBlock().getType().equals(Material.SUGAR_CANE_BLOCK)) { newLoc.getBlock().setType(Material.AIR); } } block.setType(Material.AIR); } } } @Override public int getId() { return 125; } @Override public boolean canEnchantItem(ItemStack arg0) { return true; } @Override public boolean conflictsWith(Enchantment arg0) { return false; } @Override public EnchantmentTarget getItemTarget() { return null; } @Override public int getMaxLevel() { return 1; } @Override public String getName() { return "Magnetism"; } @Override public int getStartLevel() { return 1; } }
true
2243bb0b1a12a210ddc95d5bfc4978d78aacedad
Java
theonedev/onedev
/server-core/src/main/java/io/onedev/server/web/component/issue/side/IssueSideCssResourceReference.java
UTF-8
377
1.757813
2
[ "MIT" ]
permissive
package io.onedev.server.web.component.issue.side; import io.onedev.server.web.page.base.BaseDependentCssResourceReference; public class IssueSideCssResourceReference extends BaseDependentCssResourceReference { private static final long serialVersionUID = 1L; public IssueSideCssResourceReference() { super(IssueSideCssResourceReference.class, "issue-side.css"); } }
true
5735fe4c31ab5fee42e70bf6f71f4464c6a4e841
Java
zelinskiyrk/fts-jb-101-store
/src/main/java/com/zelinskiyrk/store/basket/exception/ProductBasketNotExistException.java
UTF-8
115
1.578125
2
[ "MIT" ]
permissive
package com.zelinskiyrk.store.basket.exception; public class ProductBasketNotExistException extends Exception { }
true
24264b759c8d9e34b8eea8ca902d0ca8508ea2b6
Java
Taher-Ghaleb/FlakeFlagger
/flakiness-predicter/input_data/original_tests/doanduyhai-Achilles/nonFlakyMethods/info.archinnov.achilles.internal.persistence.operations.EntityProxifierTest-should_unproxy_list_of_entities.java
UTF-8
314
1.921875
2
[ "BSD-3-Clause" ]
permissive
@Test public void should_unproxy_list_of_entities() throws Exception { List<Factory> proxies=new ArrayList<Factory>(); proxies.add(realProxy); when(interceptor.getTarget()).thenReturn(realProxy); Collection<Factory> actual=proxifier.removeProxy(proxies); assertThat(actual).containsExactly(realProxy); }
true
095aa28657bd8790dd9f286c3b84a32cf3ac97af
Java
zhangdengjie/weshop
/RedPlus/src/com/i5le/redplus/service/GiftInfoService.java
UTF-8
999
1.71875
2
[]
no_license
package com.i5le.redplus.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.i5le.framwork.commom.bui.vo.ListItem; import com.i5le.framwork.core.repository.BaseJapRepository; import com.i5le.framwork.core.service.BaseService; import com.i5le.framwork.sys.entity.Dictionary; import com.i5le.framwork.sys.repository.DictionaryRepository; import com.i5le.redplus.entity.GiftInfo; import com.i5le.redplus.repository.GiftInfoRepository; @Component @Transactional public class GiftInfoService extends BaseService<GiftInfo, Long> { @Autowired private GiftInfoRepository giftInfoRepository; @Override public BaseJapRepository<GiftInfo, Long> getRepository() { return this.giftInfoRepository; } }
true
04051e92be8294d6df851a27a170d09dccf210be
Java
miguelfeijoo/PRINCIPAL
/carrito.master.service.subsystem/src/main/java/co/edu/uniandes/csw/carrito/master/persistence/entity/CarritoItemEntity.java
UTF-8
2,243
2.078125
2
[]
no_license
package co.edu.uniandes.csw.carrito.master.persistence.entity; import co.edu.uniandes.csw.item.persistence.entity.ItemEntity; import co.edu.uniandes.csw.carrito.persistence.entity.CarritoEntity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.PrimaryKeyJoinColumn; import org.eclipse.persistence.annotations.JoinFetch; @Entity @IdClass(CarritoItemEntityId.class) @NamedQueries({ @NamedQuery(name = "CarritoItemEntity.getItemListForCarrito", query = "SELECT u FROM CarritoItemEntity u WHERE u.carritoId=:carritoId"), @NamedQuery(name = "CarritoItemEntity.deleteCarritoItem", query = "DELETE FROM CarritoItemEntity u WHERE u.itemId=:itemId and u.carritoId=:carritoId") }) public class CarritoItemEntity implements Serializable { @Id @Column(name = "carritoId") private Long carritoId; @Id @Column(name = "itemId") private Long itemId; @ManyToOne @PrimaryKeyJoinColumn(name = "itemId", referencedColumnName = "id") @JoinFetch private ItemEntity itemEntity; @ManyToOne @PrimaryKeyJoinColumn(name = "carritoId", referencedColumnName = "id") @JoinFetch private CarritoEntity carritoEntity; public CarritoItemEntity() { } public CarritoItemEntity(Long carritoId, Long itemId) { this.carritoId = carritoId; this.itemId = itemId; } public Long getCarritoId() { return carritoId; } public void setCarritoId(Long carritoId) { this.carritoId = carritoId; } public Long getItemId() { return itemId; } public void setItemId(Long itemId) { this.itemId = itemId; } public ItemEntity getItemEntity() { return itemEntity; } public void setItemEntity(ItemEntity itemEntity) { this.itemEntity = itemEntity; } public CarritoEntity getCarritoEntity() { return carritoEntity; } public void setCarritoEntity(CarritoEntity carritoEntity) { this.carritoEntity = carritoEntity; } }
true
90287131d6cf6d103d79f8247689c4d9a582a430
Java
matheusAle/PBTest
/pbtest1.1/src/model/Factorys/RoteiroDeTesteFactory.java
UTF-8
5,352
2.796875
3
[]
no_license
package model.Factorys; import controller.exceptions.RoteiroDeTesteExeption; import model.CasoDeTeste; import model.RoteiroDeTestes; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedList; public class RoteiroDeTesteFactory extends AbstractFactory{ /** * Salva o novo roteiro de teste no banco de dados * @param codigo codogo do roteiro * @param nomeText nome do roteiro * @param descricaoText descrição deste roteiro * @param i situação deste roteiro * @param codigo1 codigo do projeto deste roteiro * @param emailUsuarioLogado usuario que o criou * @param casosDeTeste lista de codigos de casos de uso do roteiro; * @throws RoteiroDeTesteExeption caso de algo de errado. */ public void salvar(String codigo, String nomeText, String descricaoText, int i, String codigo1, String emailUsuarioLogado, LinkedList<String> casosDeTeste) { String dml = String.format("INSERT INTO roteiros_teste VALUES ('%s', '%s', '%s', %d, %s, '%s')", codigo, nomeText, descricaoText, i, codigo1, emailUsuarioLogado); System.out.println(dml); execultarAtualizacao(dml); for (String codC : casosDeTeste) execultarAtualizacao(String.format("INSERT INTO casos_de_teste_do_Roteiro VALUES ('%s', %s, '%s')", codigo, codigo1, codC)); } /** * lista todos os roteiros de teste do projeto com o ude informado. * @param idproj id pro projeto * @return lista de roteiros de teste. */ public LinkedList<RoteiroDeTestes> listarRoteiros(String idproj) { String query = String.format("SELECT * FROM roteiros_teste WHERE projetoID = %s", idproj); ResultSet resultSet = super.execultarBusca(query); if (resultSet != null){ try { LinkedList<RoteiroDeTestes> lista = new LinkedList<>(); while (resultSet.next()){ lista.add(new RoteiroDeTestes( resultSet.getString("codigo"), resultSet.getString("nome"), resultSet.getString("descricao"), resultSet.getInt("situacao"), resultSet.getString("projetoID"), resultSet.getString("emailUsuario") )); } return lista; } catch (SQLException e) { e.printStackTrace(); } } return null; } /** * Busca no banco de dados os codigos de casos de teste vinculados com o roteiro de teste. * @param codRoteiro codigo do roteiro de testes * @param codProj codigo do projeto do roteiro de testes * @return retorna uma lista com os codigos de casos de testes. */ public LinkedList<String> listarCasosDeTesteDoRoteiro(String codRoteiro, String codProj){ String query = String.format("SELECT * FROM casos_de_teste_do_roteiro r, caso_de_teste c WHERE r.cod_caso_de_teste = c.codigo AND r.projetoID = %s AND r.codigo = '%s' ", codProj, codRoteiro); ResultSet resultSet = super.execultarBusca(query); if (resultSet != null){ try { LinkedList<String> lista = new LinkedList<>(); while (resultSet.next()){ lista.add(resultSet.getString("cod_caso_de_teste")); } return lista; } catch (SQLException e) { e.printStackTrace(); throw new RoteiroDeTesteExeption("Não foi possivel buscar os casos de teste do roteiro " + codRoteiro); } } return null; } /** * Atualiza os dados do roteiro de testes. * Os casos de teste antigos são deletados do banco de dados * e os novos são inseridos. * @param codigo codigo do roteiro de teste * @param projetoID id do projeto do roteiro de teste * @param nome novo nome do roteiro * @param descricaoText nova descrição do roteiro * @param casosDeTesteDoRoteiro novos codigos de caso de teste do roteiro */ public void atualizar(String codigo, String projetoID, String nome, String descricaoText, LinkedList<String> casosDeTesteDoRoteiro) { String dmlUP = String.format("UPDATE roteiros_teste SET nome = '%s', descricao = '%s' WHERE projetoID = %s AND codigo = '%s'", nome, descricaoText, projetoID, codigo); super.execultarAtualizacao(dmlUP); String dmlDEL = String.format("DELETE FROM casos_de_teste_do_roteiro WHERE projetoID = %s AND codigo = '%s' ", projetoID, codigo); super.execultarAtualizacao(dmlDEL); for (String codC : casosDeTesteDoRoteiro) execultarAtualizacao(String.format("INSERT INTO casos_de_teste_do_Roteiro VALUES ('%s', %s, '%s')", codigo, projetoID, codC)); } /** * Deleta o roteiro de testes que tem o codigo e o id do projeto especificados * @param codigo codigo do roteiro de testes * @param projetoID id do projeto do roteiro de testes */ public void deletar(String codigo, String projetoID) { String dmlDEL = String.format("DELETE FROM roteiros_teste WHERE projetoID = %s AND codigo = '%s' ", projetoID, codigo); super.execultarAtualizacao(dmlDEL); } }
true
9812e92670037befc12b6c3fb41f9bb78222fe72
Java
Zanry/incubator-tinkerpop
/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/SelectColumnStep.java
UTF-8
2,789
2.015625
2
[ "Apache-2.0", "MIT" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tinkerpop.gremlin.process.traversal.step.map; import org.apache.tinkerpop.gremlin.structure.Column; import org.apache.tinkerpop.gremlin.process.traversal.Path; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.Traverser; import org.apache.tinkerpop.gremlin.structure.util.StringFactory; import org.apache.tinkerpop.gremlin.util.function.ArrayListSupplier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public final class SelectColumnStep<S, E> extends MapStep<S, Collection<E>> { private final Column column; public SelectColumnStep(final Traversal.Admin traversal, final Column column) { super(traversal); this.column = column; } @Override protected Collection<E> map(Traverser.Admin<S> traverser) { final S start = traverser.get(); if (start instanceof Map) return this.column.equals(Column.keys) ? ((Map<E, ?>) start).keySet() : ((Map<?, E>) start).values(); else if (start instanceof Path) return (Collection<E>) (this.column.equals(Column.keys) ? new ArrayList<>(((Path) start).labels()) : new ArrayList(((Path) start).objects())); // necessary for serialization in complex GraphComputers (find fix) else if (start instanceof Map.Entry) // TODO: remove support for this? return Collections.singleton(this.column.equals(Column.keys) ? ((Map.Entry<E, ?>) start).getKey() : ((Map.Entry<?, E>) start).getValue()); else throw new IllegalStateException("The traverser does not reference a map or path: " + traverser); } @Override public String toString() { return StringFactory.stepString(this, this.column); } @Override public int hashCode() { return super.hashCode() ^ this.column.hashCode(); } }
true
60aa42a2e0ccfaee25a42d8457a4b205619e42f2
Java
Grom9941/Tetries
/src/main/java/View/AllCombinationsReturn.java
UTF-8
2,958
2.609375
3
[]
no_license
package View; import Model.Field; import Model.Figure; import javafx.util.Pair; import java.util.HashMap; import java.util.List; import java.util.Map; public class AllCombinationsReturn extends MethodForFuncton { private final static double weighFillRow=-5.8; private final static double weighHole=4.2; private final static double weighHeight=1.2; private final static double weighSlot=1.8; private final static double weighNumberNotFill=4.8; protected Map<int[][],Double> allPeharbsSituation(List<Integer> shapeQueue, int[][] matr, int numberfigure) { Figure figure = new Figure(); Field field = new Field(); Map<int[][],Double> mapBestFigure = new HashMap<int[][], Double>(); for (int k=1;k<=4;k++) { int[][] figure1 = figure.figureRandom(shapeQueue.get(numberfigure), k); int figure1Length = figure1.length; int figure1Width = figure1[0].length; List<Integer> onFloor = figure.figureLength(shapeQueue.get(numberfigure), k); //роняем фигуру в одном положении for (int i = 0; i <= 10 - figure1Width; i++) { List<Integer> list = MethodForFuncton.heightList(matr).subList(i,i+figure1Width); for(int o=0;o<list.size();o++){ if (list.get(o)!=0) list.set(o,20-list.get(o)); } int max = 0; //место куда встанет фигура(является самым большим difference(difference-верхняя строка фигуры) for (int j = 0; j < figure1Width; j++) { int difference = list.get(j) - onFloor.get(j); if (difference > max) { max = difference; } } Pair fieldWithFigrue = field.insert(figure1, figure1Length, figure1Width, max, i, matr); Boolean overflow = (Boolean) fieldWithFigrue.getValue(); int[][] matrWithFigure = (int[][]) fieldWithFigrue.getKey(); if (!overflow) { int numberFillRow = MethodForFuncton.numberFillRow(matrWithFigure); int numberHole = MethodForFuncton.numberHole(matrWithFigure); int maxHeight = MethodForFuncton.maxHeight(matrWithFigure); int numberSlot = MethodForFuncton.numberSlot(matrWithFigure); int numberNotFill = MethodForFuncton.numberNotFill(matrWithFigure); double function = (numberFillRow * weighFillRow) + (numberHole * weighHole) + (maxHeight * weighHeight) + (numberSlot * weighSlot) + (numberNotFill * weighNumberNotFill); mapBestFigure.put(matrWithFigure, function); } else mapBestFigure.put(Field.field, Double.MAX_VALUE); } } return mapBestFigure; } }
true
c75528f1e852d7ccd894810508a6030767c7c055
Java
jodotlearn/traveling-salesman-problem
/src/main/java/edu/nchu/cs/ai/solution/OptimumSolution.java
UTF-8
455
2.359375
2
[]
no_license
package edu.nchu.cs.ai.solution; import java.util.List; public class OptimumSolution<Solution> { private Solution solution; private double objectiveValue; private List detail; public void setSolution(Solution solution) { this.solution = solution; } public Solution getSolution() { return this.solution; } public void setExecuteDetail(List detail) { this.detail = detail; } public List getExecuteDetail() { return this.detail; } }
true
4c17af0020bb7265cdca2f7bbd03ce1576d5a521
Java
gchoudharyb/java
/src/com/gaurav/java/stream/PartitioningByTest.java
UTF-8
2,079
2.9375
3
[]
no_license
package com.gaurav.java.stream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Collectors; public class PartitioningByTest { public static void main(String[] args) { System.out.println(Runtime.getRuntime().availableProcessors()); Benificiary benificiary10 = new Benificiary("20000", "123565584"); Benificiary benificiary2 = new Benificiary("20000", "123565584"); Benificiary benificiary3 = new Benificiary("1000", "1235265584"); Benificiary benificiary4 = new Benificiary("40000", "1235265584"); Benificiary benificiary5 = new Benificiary("9000", "9899557036"); Benificiary benificiary6 = new Benificiary("100", "9899557036"); Benificiary benificiary7 = new Benificiary("10002", "9990153610"); Payment payment1 = new Payment(1, "10000", PaymentType.EFT,benificiary10); Payment payment2 = new Payment(2, "20000", PaymentType.TEST,benificiary2); Payment payment3 = new Payment(3, "10000", PaymentType.EFT,benificiary10); Payment payment4 = new Payment(4, "1000", PaymentType.IFT,benificiary3); Payment payment5 = new Payment(5, "40000", PaymentType.IFT,benificiary4); Payment payment6 = new Payment(6, "9000", PaymentType.EFT,benificiary5); Payment payment7 = new Payment(7, "10000", PaymentType.TEST,benificiary10); Payment payment8 = new Payment(8, "100", PaymentType.IFT,benificiary6); Payment payment9 = new Payment(9, "10002", PaymentType.IFT,benificiary7); Payment payment10 = new Payment(10, "100", PaymentType.EFT,benificiary6); List<Payment> payments = new ArrayList<Payment>(); payments.add(payment1); payments.add(payment2); payments.add(payment3); payments.add(payment4); payments.add(payment5); payments.add(payment6); payments.add(payment7); payments.add(payment8); payments.add(payment9); payments.add(payment10); Predicate<Payment> predicate = (p)-> p.getAmount().equals("10000"); Map<Boolean, List<Payment>> map= payments.stream().collect(Collectors.partitioningBy((p)-> p.getAmount().equals("10000"))); System.out.println(map); } }
true
59ae3f2115d229d94d448a45c91a74eec3d28490
Java
Git2191866109/cbs
/src/main/java/com/bs/plugins/custom/eb/datarelationaltable/base/BaseDataRelationalTableService.java
UTF-8
6,664
2.078125
2
[]
no_license
package com.bs.plugins.custom.eb.datarelationaltable.base; import java.util.List; import java.util.Hashtable; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import com.bs.core.entity.Entity; import com.bs.core.entity.ResultData; import com.bs.core.service.IBaseService; import com.bs.core.initialize.InitializeData; import com.bs.plugins.custom.eb.datarelationaltable.entity.DataRelationalTable; import com.bs.plugins.custom.eb.datarelationaltable.dao.IDataRelationalTableDao; public class BaseDataRelationalTableService<T extends Entity> implements IBaseService { @Autowired private IDataRelationalTableDao dataRelationalTableDao; @Autowired private InitializeData initializeData; /** * 保存 * @param entity * @return */ public ResultData create(DataRelationalTable dataRelationalTable){ ResultData resultData = new ResultData(); try { Integer result = dataRelationalTableDao.insert(dataRelationalTable); if (result > 0){ resultData.setStatus(IBaseService.SUCCESS); } else{ resultData.setStatus(IBaseService.FAIL); } } catch (Exception e) { resultData.setStatusException(e.getMessage()); e.printStackTrace(); } return resultData; } /** * 修改 * @param entity * @return */ public ResultData modify(DataRelationalTable dataRelationalTable){ ResultData resultData = new ResultData(); try { Integer result = dataRelationalTableDao.updateById(dataRelationalTable); if (result > 0){ resultData.setStatus(IBaseService.SUCCESS); } else{ resultData.setStatus(IBaseService.FAIL); } } catch (Exception e) { resultData.setStatusException(e.getMessage()); e.printStackTrace(); } return resultData; } /** * 修改 * @param entity * @return */ public ResultData modifyById(DataRelationalTable dataRelationalTable){ ResultData resultData = new ResultData(); try { Integer result = dataRelationalTableDao.updateById(dataRelationalTable); if (result > 0){ resultData.setStatus(IBaseService.SUCCESS); } else{ resultData.setStatus(IBaseService.FAIL); } } catch (Exception e) { resultData.setStatusException(e.getMessage()); e.printStackTrace(); } return resultData; } /** * 删除 * @param entity * @return */ public ResultData delete(DataRelationalTable dataRelationalTable){ ResultData resultData = new ResultData(); try { Integer result = dataRelationalTableDao.delete(dataRelationalTable); if (result > 0){ resultData.setStatus(IBaseService.SUCCESS); } else{ resultData.setStatus(IBaseService.FAIL); } } catch (Exception e) { resultData.setStatusException(e.getMessage()); e.printStackTrace(); } return resultData; } /** * 删除 * @param entity * @return */ public ResultData deleteById(DataRelationalTable dataRelationalTable){ ResultData resultData = new ResultData(); try { Integer result = dataRelationalTableDao.deleteById(dataRelationalTable); if (result > 0){ resultData.setStatus(IBaseService.SUCCESS); } else{ resultData.setStatus(IBaseService.FAIL); } } catch (Exception e) { resultData.setStatusException(e.getMessage()); e.printStackTrace(); } return resultData; } /** * 删除 * @param entity * @return */ public ResultData deleteAll(){ ResultData resultData = new ResultData(); try { Integer result = dataRelationalTableDao.deleteAll(); if (result > 0){ resultData.setStatus(IBaseService.SUCCESS); } else{ resultData.setStatus(IBaseService.FAIL); } } catch (Exception e) { resultData.setStatusException(e.getMessage()); e.printStackTrace(); } return resultData; } /** * 查询单条数据 * @param entity * @return */ public ResultData single(DataRelationalTable dataRelationalTable){ ResultData resultData = new ResultData(); try { DataRelationalTable dataRelationalTableTemp = dataRelationalTableDao.selectOneById(dataRelationalTable); if (dataRelationalTableTemp != null){ resultData.setStatus(IBaseService.SUCCESS); resultData.addObject("dataRelationalTable", dataRelationalTableTemp); } else{ resultData.setStatus(IBaseService.FAIL); } } catch (Exception e) { resultData.setStatusException(e.getMessage()); e.printStackTrace(); } return resultData; } /** * 查询列表 * @param entity * @return */ public ResultData list(DataRelationalTable dataRelationalTable){ ResultData resultData = new ResultData(); try { List<DataRelationalTable> dataRelationalTableList = dataRelationalTableDao.selectList(dataRelationalTable); if (dataRelationalTableList != null){ resultData.setStatus(IBaseService.SUCCESS); resultData.addObject("dataRelationalTableList", dataRelationalTableList); } else{ resultData.setStatus(IBaseService.FAIL); } } catch (Exception e) { resultData.setStatusException(e.getMessage()); e.printStackTrace(); } return resultData; } /** * 查询分页列表 * @param entity * @return */ public ResultData paginated(DataRelationalTable dataRelationalTable){ ResultData resultData = new ResultData(); try { List<DataRelationalTable> dataRelationalTableList = dataRelationalTableDao.selectPaginatedList(dataRelationalTable); Long dataRelationalTableCount = dataRelationalTableDao.getCount(dataRelationalTable); if (dataRelationalTableList != null){ long record = dataRelationalTableCount == null?0:dataRelationalTableCount; int pageCount = (int) Math.ceil(record / (double) dataRelationalTable.getRows()); Map<String, Object> gridMap = new Hashtable<String, Object>(); gridMap.put("page", dataRelationalTable.getPage()); gridMap.put("total", pageCount); gridMap.put("records", record); gridMap.put("rows", dataRelationalTableList); resultData.setResultMap(gridMap); resultData.setStatus(IBaseService.SUCCESS); } else{ resultData.setStatus(IBaseService.FAIL); } } catch (Exception e) { resultData.setStatusException(e.getMessage()); e.printStackTrace(); } return resultData; } @Override public void afterPropertiesSet() throws Exception { } public InitializeData getInitializeData() { return initializeData; } public void setInitializeData(InitializeData initializeData) { this.initializeData = initializeData; } public IDataRelationalTableDao getDataRelationalTableDao() { return dataRelationalTableDao; } public void setDataRelationalTableDao(IDataRelationalTableDao dataRelationalTableDao) { this.dataRelationalTableDao = dataRelationalTableDao; } }
true
40376d455f5c5004b3eabca940edca7f990cd4c6
Java
topcoder-platform/tc-java-components
/components/database_abstraction/src/java/tests/com/topcoder/util/sql/databaseabstraction/stresstests/StressTests.java
UTF-8
687
2.125
2
[]
no_license
package com.topcoder.util.sql.databaseabstraction.stresstests; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * <p> * This test case aggregates all stress test cases. * </p> * * @author TopCoder Software * @version 1.1 */ public class StressTests extends TestCase { /** * Returns the stress test suite. * * @return the stress test suite. */ public static Test suite() { final TestSuite suite = new TestSuite(); suite.addTest(DatabaseAbstractionStressTests.suite()); suite.addTest(DatabaseAbstractionStressTestsV2.suite()); return suite; } }
true
784b287d887345c4f1304b84df05969cf830b636
Java
michaelalvin/EnterpriseAPIClients
/Java/models/GetFieldValidationModel.java
UTF-8
3,901
2.125
2
[]
no_license
/** * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package softheon.enterprise.api.client.models; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * Model for the GET Template input parameters. */ public class GetFieldValidationModel { /** * Gets or sets the sort column. */ @JsonProperty(value = "SortColumn") private String sortColumn; /** * Gets or sets the metadata search options. */ @JsonProperty(value = "Metadata") private List<GetLookupFieldModel> metadata; /** * Gets or sets the page number. */ @JsonProperty(value = "Page") private Integer page; /** * Gets or sets the size of the page. */ @JsonProperty(value = "PageSize") private Integer pageSize; /** * Gets or sets the order. Possible values include: 'Unspecified', * 'Ascending', 'Descending'. */ @JsonProperty(value = "SortOrder") private String sortOrder; /** * Gets or sets the column to order by. */ @JsonProperty(value = "SortBy") private Integer sortBy; /** * Get the sortColumn value. * * @return the sortColumn value */ public String sortColumn() { return this.sortColumn; } /** * Set the sortColumn value. * * @param sortColumn the sortColumn value to set * @return the GetFieldValidationModel object itself. */ public GetFieldValidationModel withSortColumn(String sortColumn) { this.sortColumn = sortColumn; return this; } /** * Get the metadata value. * * @return the metadata value */ public List<GetLookupFieldModel> metadata() { return this.metadata; } /** * Set the metadata value. * * @param metadata the metadata value to set * @return the GetFieldValidationModel object itself. */ public GetFieldValidationModel withMetadata(List<GetLookupFieldModel> metadata) { this.metadata = metadata; return this; } /** * Get the page value. * * @return the page value */ public Integer page() { return this.page; } /** * Set the page value. * * @param page the page value to set * @return the GetFieldValidationModel object itself. */ public GetFieldValidationModel withPage(Integer page) { this.page = page; return this; } /** * Get the pageSize value. * * @return the pageSize value */ public Integer pageSize() { return this.pageSize; } /** * Set the pageSize value. * * @param pageSize the pageSize value to set * @return the GetFieldValidationModel object itself. */ public GetFieldValidationModel withPageSize(Integer pageSize) { this.pageSize = pageSize; return this; } /** * Get the sortOrder value. * * @return the sortOrder value */ public String sortOrder() { return this.sortOrder; } /** * Set the sortOrder value. * * @param sortOrder the sortOrder value to set * @return the GetFieldValidationModel object itself. */ public GetFieldValidationModel withSortOrder(String sortOrder) { this.sortOrder = sortOrder; return this; } /** * Get the sortBy value. * * @return the sortBy value */ public Integer sortBy() { return this.sortBy; } /** * Set the sortBy value. * * @param sortBy the sortBy value to set * @return the GetFieldValidationModel object itself. */ public GetFieldValidationModel withSortBy(Integer sortBy) { this.sortBy = sortBy; return this; } }
true
16dac874c1e903ac52ab42fd139f95d46c58eea6
Java
tsvetanvashkov/Java_Tutorials
/Java_Tutorials/src/_6_oop_principles/AbstactClass.java
UTF-8
963
3
3
[]
no_license
package _6_oop_principles; public abstract class AbstactClass { //Abstraktniq klas e nezavyrshen klas //Ot edin abstrakten klas NIKOGA ne moje da se napravi OBEKT //vseki klas koito ima pone 1 abstrakten metod se naricha Abstrakten klas //Abstraktniq klas samo i edinstveno moje da se nasledqva //Vsichko v abstraktniq klas za poletata e edno i syshto private String pushTheButton; private String volumeUp; // V abstraktniq klas moje da syshtestvuvat dva vida metodi //1. Zavyrsheni takiva s body (scope) public void printName(){ System.out.println("Remote control Name is Panasonic"); } // 2. Nezavyrsheni metodi (abstraktni metodi) //Abstraktnite metodi moje samo i edinstveno da bydat public public abstract void pushTheButton(); //DIferences between abstact class and interfaces /* public default String canHeroSwim(){ return "asdaskdjfkalsdjfklasdf"; }; */ }
true
244541152c9854f7ee7cb05d70c7fb4ff3f2bec2
Java
cunla/RPSP
/src/main/java/com/emc/rpsp/fal/commons/ImageAccessParameters.java
UTF-8
4,544
2.328125
2
[ "MIT" ]
permissive
package com.emc.rpsp.fal.commons; import javax.xml.bind.annotation.*; @SuppressWarnings("serial") @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ImageAccessParameters") public class ImageAccessParameters implements Validateable { @XmlElement(required = true) private RecoverPointTimeStamp timeStamp; @XmlElement(required = true) private ImageAccessMode mode; private SearchImageType imageType; private String searchText; private boolean searchExactText; private Long maximumSearchRange; /*private MountType mountType;*/ public ImageAccessParameters() { } public ImageAccessParameters(RecoverPointTimeStamp timeStamp, ImageAccessMode mode, SearchImageType imageType, String searchText, boolean searchExactText, Long maximumSearchRange, MountType mountType) { this.timeStamp = timeStamp; this.mode = mode; this.imageType = imageType; this.searchText = searchText; this.searchExactText = searchExactText; this.maximumSearchRange = maximumSearchRange; } public RecoverPointTimeStamp getTimeStamp() { return timeStamp; } public void setTimeStamp(RecoverPointTimeStamp timeStamp) { this.timeStamp = timeStamp; } public ImageAccessMode getMode() { return mode; } public void setMode(ImageAccessMode mode) { this.mode = mode; } public SearchImageType getImageType() { return imageType; } public void setImageType(SearchImageType imageType) { this.imageType = imageType; } public String getSearchText() { return searchText; } public void setSearchText(String searchText) { this.searchText = searchText; } public boolean getSearchExactText() { return searchExactText; } public void setSearchExactText(boolean searchExactText) { this.searchExactText = searchExactText; } public Long getMaximumSearchRange() { return maximumSearchRange; } public void setMaximumSearchRange(Long maximumSearchRange) { this.maximumSearchRange = maximumSearchRange; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ImageAccessParameters [timeStamp=").append(timeStamp) .append(", mode=").append(mode).append(", imageType=") .append(imageType).append(", searchText=").append(searchText) .append(", searchExactText=").append(searchExactText) .append(", maximumSearchRange=").append(maximumSearchRange) .append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((imageType == null) ? 0 : imageType.hashCode()); result = prime * result + ((maximumSearchRange == null) ? 0 : maximumSearchRange .hashCode()); result = prime * result + ((mode == null) ? 0 : mode.hashCode()); result = prime * result + (searchExactText ? 1231 : 1237); result = prime * result + ((searchText == null) ? 0 : searchText.hashCode()); result = prime * result + ((timeStamp == null) ? 0 : timeStamp.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ImageAccessParameters other = (ImageAccessParameters) obj; if (imageType != other.imageType) return false; if (maximumSearchRange == null) { if (other.maximumSearchRange != null) return false; } else if (!maximumSearchRange.equals(other.maximumSearchRange)) return false; if (mode != other.mode) return false; if (searchExactText != other.searchExactText) return false; if (searchText == null) { if (other.searchText != null) return false; } else if (!searchText.equals(other.searchText)) return false; if (timeStamp == null) { if (other.timeStamp != null) return false; } else if (!timeStamp.equals(other.timeStamp)) return false; return true; } }
true
93a2197296954a807c247555a466d76c1edbe725
Java
wjianbin/TBCredit
/creditsupport/.svn/pristine/c0/c0d488e062ee67ff4862bd0b66065da81784f5a1.svn-base
UTF-8
572
1.96875
2
[]
no_license
package com.yodata.creditsupport.orm.vo; import java.io.Serializable; public class InformationSchema implements Serializable{ /** * */ private static final long serialVersionUID = 1L; /**数据库名*/ private String tableSchema; /**表名*/ private String tableName; public String getTableSchema() { return tableSchema; } public void setTableSchema(String tableSchema) { this.tableSchema = tableSchema; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } }
true
4e83e9fadbd666bca8a75b8d655464583f0661df
Java
derelektrischemoench/ObserverPatternsExercise
/src/ObserverPattern/runner.java
UTF-8
590
3.109375
3
[]
no_license
package ObserverPattern; import java.util.Observer; import java.util.Random; public class runner { public static void main(String[] args) { Universe u = new Universe(); Random randomInt = new Random(); new ChangeObserver(u); while(true) { u.setNumStars(randomInt.nextInt(100000)); u.setSize(randomInt.nextInt(100000)); try { Thread.sleep(3000); } catch (InterruptedException e) { System.out.println("Interrupt"); } } } }
true
59584be3febcac0fdc5b3bc4548e50ca0bae7544
Java
Miguelangelhdzcast/lototress
/src/main/java/com/proyecto/lototres/Actividad.java
UTF-8
1,782
2.15625
2
[]
no_license
package com.proyecto.lototres; import java.io.Serializable; import java.sql.Blob; import javax.persistence.*; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages ={"com.proyecto.lototres.ActividadService"}) @Entity @Table ( name = "actividad" ) public class Actividad implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column (name = "id_act") private Long id_act; @Column(name = "nombre_act") private String nombre_act; @Column(name = "fecha_act") private String fecha_act; @Column (name = "horario_Act") private String horario_act; @Column(name = "info_principal") private String info_principal; @Column (name = "imagen") private Blob imagen; public Actividad() { } public Long getId_act() { return id_act; } public void setId_act(Long id_act) { this.id_act = id_act; } public String getNombre_act() { return nombre_act; } public void setNombre_act(String nombre_act) { this.nombre_act = nombre_act; } public String getFecha_act() { return fecha_act; } public void setFecha_act(String fecha_act) { this.fecha_act = fecha_act; } public String getHorario_act() { return horario_act; } public void setHorario_act(String horario_act) { this.horario_act = horario_act; } public String getInfo_principal() { return info_principal; } public void setInfo_principal(String info_principal) { this.info_principal = info_principal; } public Blob getImagen() { return imagen; } public void setImagen(Blob imagen) { this.imagen = imagen; } }
true
ab1be151cd05e42d89eb77ba819daa5693d78ba8
Java
foxxifu/my-ids
/ids-dev-all/ids-dev-network/src/main/java/com/interest/ids/dev/network/handler/subscribe/DevSubscriptionTask.java
UTF-8
2,254
2.4375
2
[]
no_license
package com.interest.ids.dev.network.handler.subscribe; import com.interest.ids.common.project.bean.signal.DeviceInfo; /** * * @author lhq * * */ public class DevSubscriptionTask { public DevSubscriptionTask(DeviceInfo dev,SubscriptionTask task){ this.dev = dev; this.task = task; } private DeviceInfo dev; private SubscriptionTask task; private boolean first; private volatile boolean isSubscribe = false; private int tryNum = 3; private int retryNum=0; public int getRetryNum() { return retryNum; } public void setRetryNum(int retryNum) { this.retryNum = retryNum; } public DeviceInfo getDev() { return dev; } public void setDev(DeviceInfo dev) { this.dev = dev; } public SubscriptionTask getTask() { return task; } public void setTask(SubscriptionTask task) { this.task = task; } public int getTryNum() { return tryNum; } public void setTryNum(int tryNum) { this.tryNum = tryNum; } public boolean isFirst() { return first; } public void setFirst(boolean first) { this.first = first; } public void decrease(){ tryNum--; } public boolean isSubscribe() { return isSubscribe; } public void setSubscribe(boolean isSubscribe) { this.isSubscribe = isSubscribe; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dev == null) ? 0 : dev.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DevSubscriptionTask other = (DevSubscriptionTask) obj; if (dev == null) { if (other.dev != null) return false; } else if (!dev.equals(other.dev)) return false; return true; } public enum SubscriptionTask{ SUBSCRIBE,WHOLECALL,Communicate,CommunicateExecute,Supplement } @Override public String toString() { return "DevSubscriptionTask [dev=" + dev + ", task=" + task + ", tryNum=" + tryNum + "]"; } }
true
5e361eaac208de235a971d4823c7e91fc397bbc0
Java
AzureAD/azure-activedirectory-library-for-android
/adal/src/telemetry/java/com/microsoft/aad/adal/DefaultEvent.java
UTF-8
6,295
1.84375
2
[ "MIT" ]
permissive
// Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package com.microsoft.aad.adal; import com.microsoft.identity.common.adal.internal.util.StringExtensions; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.provider.Settings.Secure; import android.text.TextUtils; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; class DefaultEvent implements IEvents { private final List<Map.Entry<String, String>> mEventList; private static String sApplicationName = null; private static String sApplicationVersion = "NA"; private static String sClientId = "NA"; private static String sDeviceId = "NA"; private static final int EVENT_LIST_SIZE = 30; private String mRequestId; private int mDefaultEventCount; DefaultEvent() { mEventList = new ArrayList<>(EVENT_LIST_SIZE); // Keying off Application name not being null to decide if the defaults have been set if (sApplicationName != null) { setProperty(EventStrings.APPLICATION_NAME, sApplicationName); setProperty(EventStrings.APPLICATION_VERSION, sApplicationVersion); setProperty(EventStrings.CLIENT_ID, sClientId); setProperty(EventStrings.DEVICE_ID, sDeviceId); mDefaultEventCount = mEventList.size(); } } @Override public int getDefaultEventCount() { return mDefaultEventCount; } @Override public void setProperty(final String name, final String value) { if (TextUtils.isEmpty(name)) { throw new IllegalArgumentException("Telemetry setProperty on null name"); } if (value == null || !isPrivacyCompliant(name)) { return; } mEventList.add(new AbstractMap.SimpleEntry<>(name, value)); } @Override public List<Map.Entry<String, String>> getEvents() { return Collections.unmodifiableList(mEventList); } /** * Each event chooses which of its members get picked on aggregation. * @param dispatchMap the Map that is filled with the aggregated event properties */ @Override public void processEvent(final Map<String, String> dispatchMap) { if (sApplicationName != null && isPrivacyCompliant(EventStrings.APPLICATION_NAME)) { dispatchMap.put(EventStrings.APPLICATION_NAME, sApplicationName); } if (sApplicationVersion != null && isPrivacyCompliant(EventStrings.APPLICATION_VERSION)) { dispatchMap.put(EventStrings.APPLICATION_VERSION, sApplicationVersion); } if (sClientId != null && isPrivacyCompliant(EventStrings.CLIENT_ID)) { dispatchMap.put(EventStrings.CLIENT_ID, sClientId); } if (sDeviceId != null && isPrivacyCompliant(EventStrings.DEVICE_ID)) { dispatchMap.put(EventStrings.DEVICE_ID, sDeviceId); } } @SuppressLint("HardwareIds") void setDefaults(final Context context, final String clientId) { sClientId = clientId; sApplicationName = context.getPackageName(); try { sApplicationVersion = context.getPackageManager().getPackageInfo(sApplicationName, 0).versionName; } catch (PackageManager.NameNotFoundException nnfe) { sApplicationVersion = "NA"; } try { sDeviceId = StringExtensions.createHash(Secure.getString(context.getContentResolver(), Secure.ANDROID_ID)); } catch (UnsupportedEncodingException | NoSuchAlgorithmException e) { sDeviceId = ""; } if (mDefaultEventCount == 0) { setProperty(EventStrings.APPLICATION_NAME, sApplicationName); setProperty(EventStrings.APPLICATION_VERSION, sApplicationVersion); setProperty(EventStrings.CLIENT_ID, sClientId); setProperty(EventStrings.DEVICE_ID, sDeviceId); mDefaultEventCount = mEventList.size(); } } // Sets the correlation id to the top of the list void setCorrelationId(final String correlationId) { mEventList.add(0, new AbstractMap.SimpleEntry<>(EventStrings.CORRELATION_ID, correlationId)); mDefaultEventCount++; } void setRequestId(final String requestId) { mRequestId = requestId; mEventList.add(0, new AbstractMap.SimpleEntry<>(EventStrings.REQUEST_ID, requestId)); mDefaultEventCount++; } List<Map.Entry<String, String>> getEventList() { return mEventList; } String getTelemetryRequestId() { return mRequestId; } /** * Tests supplied EventStrings for privacy compliance. * @param fieldName The EventString to evaluate. * @return True, if the field can be reported. False otherwise. */ static boolean isPrivacyCompliant(final String fieldName) { return Telemetry.getAllowPii() || !TelemetryUtils.GDPR_FILTERED_FIELDS.contains(fieldName); } }
true
040a2e6cf78c1d6be33784ea005861f715c98bca
Java
Viniciuslfta/arka
/arkanoid/src/arkanoid/models/entities/Bonus/BonusExpansion.java
UTF-8
993
2.234375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package arkanoid.models.entities.Bonus; import arkanoid.BaseColor; import arkanoid.Settings; import arkanoid.Textures; import arkanoid.models.entities.PlayArea; import org.newdawn.slick.opengl.Texture; /** * * @author sPeC */ public class BonusExpansion extends Bonus{ public BonusExpansion(float _x, float _y) { super(_x, _y, new BaseColor(1,1,1),Textures.getInstance().getBonusExpansion()); } @Override public Texture getTexture() { if (mTexture == null) { mTexture = Textures.getInstance().getBonusExpansion(); } return mTexture; } @Override public void onClubCollision(PlayArea _area) { _area.getClub().setWidth(_area.getClub().getWidth() + 50); } @Override public void undoEffect(PlayArea _area) { _area.getClub().setWidth(Settings.CLUB_WIDTH); } }
true
cd09c23fa5168017d3f0accdd362e549e0052a9b
Java
sekouu/Thread
/src/Model/RunnableTree.java
UTF-8
940
3.125
3
[]
no_license
package Model; import Model.BinarySearchTree; import java.util.Random; public class RunnableTree implements Runnable { private BinarySearchTree tree; //private E add; private int nbNode; public RunnableTree(BinarySearchTree tree, int a) { this.tree = tree; this.nbNode = a; } public void run() { String randomName; for(int i =0; i<nbNode ; i++){ randomName = generate(10); if(tree.add(randomName)) System.out.print(i+1 +". Ajout de :" + randomName + "\n"); else System.out.println(randomName + " already exist."); } } // Code from http://www.developpez.net/forums/d120817/java/general-java/generer-chaine-aleatoire/ public String generate(int length) { String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; String pass = ""; for(int x=0;x<length;x++) { int i = (int)Math.floor(Math.random() * 62); pass += chars.charAt(i); } return pass; } }
true
fee9efe2ace0a9679c4dc3229ac848b298f97f58
Java
SubashChandrabose-V/Collaboration-Project
/Collaboration_backend/src/main/java/org/com/config/DBConfig.java
UTF-8
2,069
2.078125
2
[]
no_license
package org.com.config; import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; import org.com.model.BlogComment; import org.com.model.BlogPost; import org.com.model.Friend; import org.com.model.Job; import org.com.model.ProfilePicture; import org.com.model.User; import org.hibernate.SessionFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @ComponentScan("org.com.model") public class DBConfig { public void confi(){ System.out.println("conig insta"); } @Bean public SessionFactory sessionFactory() { LocalSessionFactoryBuilder lsf= new LocalSessionFactoryBuilder(getDataSource()); Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect"); hibernateProperties.setProperty("hibernate.hbm2ddl.auto","update"); hibernateProperties.setProperty("hibernate.show_sql", "true"); lsf.addProperties(hibernateProperties); Class classes[]=new Class[] {User.class,BlogPost.class,Job.class,BlogComment.class,ProfilePicture.class,Friend.class}; return lsf.addAnnotatedClasses(classes).buildSessionFactory(); } @Bean public DataSource getDataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("oracle.jdbc.OracleDriver"); dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:XE"); dataSource.setUsername("MY"); dataSource.setPassword("my"); return dataSource; } @Bean public HibernateTransactionManager hibTransManagement() { return new HibernateTransactionManager(sessionFactory()); } }
true
a432e47bfd3d314b5d3e8ac9ff6a2fcc59d3cf79
Java
wangbo7753/ktSpider
/src/main/java/com/kthw/spider/common/db/DBParam.java
UTF-8
1,230
2.359375
2
[]
no_license
package com.kthw.spider.common.db; public class DBParam { private String alias; private String user; private String password; private String url; private String driver; public DBParam(String alias, String user, String password, String driver, String url) { this.alias = alias; this.user = user; this.password = password; this.driver = driver; this.url = url; } public void setUser(String user) { this.user = user; } public void setPassword(String password) { this.password = password; } public void setUrl(String url) { this.url = url; } public void setDriver(String driver) { this.driver = driver; } public void setAlias(String alias) { this.alias = alias; } public String getUser() { return user; } public String getPassword() { return password; } public String getUrl() { return url; } public String getDriver() { return driver; } public String getAlias() { return alias; } @Override public String toString() { return alias + ", " + url; } }
true
0581ec142ce18df4b60fe99b8d4ea42dea3956ee
Java
vishal901/storemanagerADMIN
/app/src/main/java/in/vaksys/storemanager/response/GetCustomerList.java
UTF-8
6,532
2.15625
2
[]
no_license
package in.vaksys.storemanager.response; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by lenovoi3 on 8/12/2016. */ public class GetCustomerList { /** * error : false * message : Get Customers successfully. * data : [{"id":"21","branch_id":"6","first_name":"vishal","last_name":"patel","date_of_birth":"0000-00-00","gender":"MALE","address":"address 1","address1":"address2","city":"Mehsana","state":"Gujarat","zip":"666666","mobile":"123456789012","landline":"123654789012","email":"vishal@gmail.com","how_did_you_find_us":"Other","ailments":"","pain_picture":null,"find_us_reason":"other data"},{"id":"22","branch_id":"6","first_name":"ankit","last_name":"patel","date_of_birth":"0000-00-00","gender":"MALE","address":"balol","address1":"balol","city":"Ahmedabad","state":"Gujarat","zip":"666666","mobile":"123456789089","landline":"","email":"visit@hkak.sjj","how_did_you_find_us":"Google","ailments":"","pain_picture":null,"find_us_reason":""}] */ @SerializedName("error") private boolean error; @SerializedName("message") private String message; /** * id : 21 * branch_id : 6 * first_name : vishal * last_name : patel * date_of_birth : 0000-00-00 * gender : MALE * address : address 1 * address1 : address2 * city : Mehsana * state : Gujarat * zip : 666666 * mobile : 123456789012 * landline : 123654789012 * email : vishal@gmail.com * how_did_you_find_us : Other * ailments : * pain_picture : null * find_us_reason : other data */ @SerializedName("data") private List<DataBean> data; public boolean isError() { return error; } public void setError(boolean error) { this.error = error; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List<DataBean> getData() { return data; } public void setData(List<DataBean> data) { this.data = data; } public static class DataBean { @SerializedName("id") private String id; @SerializedName("branch_id") private String branchId; @SerializedName("first_name") private String firstName; @SerializedName("last_name") private String lastName; @SerializedName("date_of_birth") private String dateOfBirth; @SerializedName("gender") private String gender; @SerializedName("address") private String address; @SerializedName("address1") private String address1; @SerializedName("city") private String city; @SerializedName("state") private String state; @SerializedName("zip") private String zip; @SerializedName("mobile") private String mobile; @SerializedName("landline") private String landline; @SerializedName("email") private String email; @SerializedName("how_did_you_find_us") private String howDidYouFindUs; @SerializedName("ailments") private String ailments; @SerializedName("pain_picture") private Object painPicture; @SerializedName("find_us_reason") private String findUsReason; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBranchId() { return branchId; } public void setBranchId(String branchId) { this.branchId = branchId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(String dateOfBirth) { this.dateOfBirth = dateOfBirth; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getAddress1() { return address1; } public void setAddress1(String address1) { this.address1 = address1; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getLandline() { return landline; } public void setLandline(String landline) { this.landline = landline; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getHowDidYouFindUs() { return howDidYouFindUs; } public void setHowDidYouFindUs(String howDidYouFindUs) { this.howDidYouFindUs = howDidYouFindUs; } public String getAilments() { return ailments; } public void setAilments(String ailments) { this.ailments = ailments; } public Object getPainPicture() { return painPicture; } public void setPainPicture(Object painPicture) { this.painPicture = painPicture; } public String getFindUsReason() { return findUsReason; } public void setFindUsReason(String findUsReason) { this.findUsReason = findUsReason; } } }
true
8f86e19c95f4a1f48c8d5b97515580fec38d284e
Java
chunyukuo88/kataWithGradle
/src/test/java/kataWithGradle/TheOfficeIVTest.java
UTF-8
1,170
3.109375
3
[]
no_license
//https://www.codewars.com/kata/the-office-iv-find-a-meeting-room/train/java package kataWithGradle; import static org.junit.Assert.*; import org.junit.Test; public class TheOfficeIVTest { @Test public void findFirstO() throws Exception { TheOfficeIV underTest = new TheOfficeIV(); char[] testArray = {'X', 'X', 'O', 'X', 'O'}; int expectedOutput = underTest.meeting(testArray); assertEquals(2, expectedOutput); } @Test public void canDetermineIfAllRoomsAreFull() { TheOfficeIV underTest = new TheOfficeIV(); char[] testArray = {'X', 'X', 'X', 'X', 'X'}; String expectedOutput = underTest.allRoomsFull(testArray); String result = "None available!"; assertEquals(result, expectedOutput); } @Test public void canProduceEmptyResultOrRoomIndex() { TheOfficeIV underTest = new TheOfficeIV(); char[] testArray1 = {'X', 'X', 'X', 'X', 'X'}; char[] testArray2 = {'X', 'X', 'O', 'X', 'X'}; Object expectedOutput1 = underTest.fullOrIndex(testArray1); Object result1 = "None available!"; Object expectedOutput2 = underTest.fullOrIndex(testArray2); Object result2 = 2; assertEquals(result1, expectedOutput1); } }
true
422162ef8aa9fd70980fa643373c650278a9658a
Java
2276089666/DataStructuresAndAlgorithms
/algorithms/violentRecursion/Hanoi.java
UTF-8
1,114
3.765625
4
[ "Apache-2.0" ]
permissive
package violentRecursion; /** * @Author ws * @Date 2021/4/17 15:25 * @Version 1.0 */ public class Hanoi { /** * 打印n层汉诺塔从最左边移动到最右边的全部过程 */ /** * @param N 圆盘的层数 */ public static void printHanoi(int N) { if (N > 0) { recursionPrint(N, "left", "mid", "right"); } } /** * @param n 层数 * @param from 起始盘 * @param help 帮助盘 * @param to 目标盘 */ private static void recursionPrint(int n, String from, String help, String to) { if (n == 1) { System.out.println("move 1 from " + from + " to " + to); } else { // 将1~N-1层从from移到help recursionPrint(n - 1, from, to, help); // 将第N最底下层从form移到to System.out.println("move " + n + " from " + from + " to " + to); // 将1~N-1层从help移到to recursionPrint(n - 1, help, from, to); } } public static void main(String[] args) { printHanoi(3); } }
true
258d5dc7fe4cf3abc7c4c5648cbaf35384cb98b5
Java
DJ956/BreakingBlue
/BreakingBlue/app/src/main/java/com/george/breakingblue/bluetooth/command/ImageFromURLCommand.java
UTF-8
8,592
2.375
2
[]
no_license
package com.george.breakingblue.bluetooth.command; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Environment; import android.support.v7.app.AlertDialog; import android.widget.Toast; import com.george.breakingblue.bluetooth.session.ConnectManager; import com.george.breakingblue.bluetooth.session.SessionTools; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; /** * URLから画像をダンロードするためのコマンド */ public class ImageFromURLCommand extends Command<String, Void> { private static final String READ_END_MESSAGE = "bt socket closed, read return: -1"; private Activity activity; public ImageFromURLCommand(Activity activity, String commandData){ super(commandData, CommandType.ImageFromURL); this.activity = activity; } @Override public void execute(SessionTools sessionTools){ new AsyncExecuteDownload(activity, sessionTools).execute(commandData); } private class AsyncExecuteDownload extends AsyncTask<String, Integer, Integer>{ private SessionTools sessionTools; private Activity activity; private ProgressDialog progressDialog; private List<byte[]> imageDataList; public AsyncExecuteDownload(Activity activity, SessionTools sessionTools){ this.activity = activity; this.sessionTools = sessionTools; } @Override protected void onPreExecute() { progressDialog = new ProgressDialog(activity); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setTitle("しばらくお待ちください"); progressDialog.setMessage("画像データダウンロード中..."); progressDialog.setCancelable(false); progressDialog.setProgress(0); progressDialog.setMax(100); progressDialog.show(); } @Override protected Integer doInBackground(String... strings) { if(!ConnectManager.isConnected()){ try { ConnectManager.connect(ConnectManager.getDevice()); sessionTools = ConnectManager.getSessionTools(); } catch (IOException e) { e.printStackTrace(); return 0; } } ByteArrayOutputStream byteArrayOutputStream = null; try{ sessionTools.getOutputStream().write(commandType.toString().getBytes()); sessionTools.getOutputStream().flush(); sessionTools.getOutputStream().write(commandData.getBytes()); sessionTools.getOutputStream().flush(); byte[] sumBuffer = new byte[24]; int sumLen = sessionTools.getInputStream().read(sumBuffer); String sumStr = new String(sumBuffer, 0, sumLen); Integer sum = Integer.parseInt(sumStr); System.out.println("Data sum:" + sum); byte[] buffer = new byte[1024]; byteArrayOutputStream = new ByteArrayOutputStream(); BufferedInputStream inputStream = new BufferedInputStream(sessionTools.getInputStream()); int len; int total = 0; while ((len = inputStream.read(buffer)) != -1) { total += buffer.length; byteArrayOutputStream.write(buffer, 0, len); double percentage = (double)total / sum * 100; publishProgress((int)percentage); } }catch (IOException e) { if (e.getMessage().equals(READ_END_MESSAGE)) { try { byteArrayOutputStream.flush(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); imageDataList = (List<byte[]>) objectInputStream.readObject(); return 1; } catch (IOException | ClassNotFoundException ex) { ex.printStackTrace(); return 0; } }else { e.printStackTrace(); return 0; } }finally { sessionTools.close(); ConnectManager.disconnect(); } return 1; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); progressDialog.setProgress(values[0]); } @Override protected void onPostExecute(Integer integer) { progressDialog.dismiss(); if(integer > 0){ Toast.makeText(activity.getApplicationContext(), "ダウンロード完了", Toast.LENGTH_SHORT).show(); new AsyncSaveFiles(activity, imageDataList).execute(); }else { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle("Error"); builder.setMessage("ダウンロードに失敗しました"); builder.create().show(); } } } private class AsyncSaveFiles extends AsyncTask<Void, Integer, Integer>{ private List<byte[]> imageDataList; private Exception exception; private Activity activity; private ProgressDialog progressDialog; private File savePath; private AsyncSaveFiles(Activity activity, List<byte[]> imageDataList){ this.activity = activity; this.imageDataList = imageDataList; } @Override protected void onPreExecute() { progressDialog = new ProgressDialog(activity); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMax(imageDataList.size()); progressDialog.setProgress(0); progressDialog.setTitle("ファイル保存"); progressDialog.setMessage("ファイル保存中..."); progressDialog.setCancelable(false); progressDialog.show(); } @Override protected Integer doInBackground(Void... voids) { try{ String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm", Locale.JAPAN); savePath = new File(path, dateFormat.format(new Date())); if(savePath.mkdir()) { int index = 1; for (byte[] imgData : imageDataList) { File file = new File(savePath, File.separator + String.valueOf(index)); FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(imgData); fileOutputStream.flush(); fileOutputStream.close(); publishProgress(index); index++; } } }catch (IOException e){ e.printStackTrace(); exception = e; return 0; } return 1; } @Override protected void onProgressUpdate(Integer... values) { progressDialog.setProgress(values[0]); } @Override protected void onPostExecute(Integer integer) { progressDialog.dismiss(); AlertDialog.Builder builder = new AlertDialog.Builder(activity); if(integer > 0){ builder.setTitle("保存完了"); builder.setMessage(savePath.getPath() + "にすべてのファイルを保存しました"); }else { builder.setTitle("Error"); builder.setMessage(exception.getMessage()); } builder.create().show(); } } }
true
255de1c695d36184f82168a21b635d3d4d6f7fe0
Java
dvspandey/Web-ChatApplication
/Code/src/com/nt/util/ChatAppCalender.java
UTF-8
1,427
2.8125
3
[]
no_license
/** * @author Devesh Pandey * mailID:: dvspandey10@gmail.com */ package com.nt.util; import java.util.Calendar; import java.util.TimeZone; public class ChatAppCalender { private String date; private String time; private String timeStamp; //Getters public String getDate() { TimeZone timeZone = TimeZone.getTimeZone("IST"); Calendar c = Calendar.getInstance(timeZone); date = c.get(Calendar.DATE)+"/" + (c.get(Calendar.MONTH)+1) + "/" + c.get(Calendar.YEAR); return date; } public String getTime() { TimeZone timeZone = TimeZone.getTimeZone("IST"); Calendar c = Calendar.getInstance(timeZone); time = c.get(Calendar.HOUR_OF_DAY)+ ":" +c.get(Calendar.MINUTE) +":"+c.get(Calendar.SECOND) + "[" + timeZone.getID()+"]"; return time; } public String getTimeStamp() { TimeZone timeZone = TimeZone.getTimeZone("IST"); Calendar c = Calendar.getInstance(timeZone); timeStamp = c.get(Calendar.DATE)+"/" + (c.get(Calendar.MONTH)+1) + "/" + c.get(Calendar.YEAR)+ ("("+c.get(Calendar.HOUR_OF_DAY)+ ":" +c.get(Calendar.MINUTE) +":"+c.get(Calendar.SECOND) + "[" + timeZone.getID()+"]")+")"; return timeStamp; } /* public static void main(String[] args) throws InterruptedException { ChatAppCalender cal = new ChatAppCalender(); System.out.println(cal.getDate()); Thread.sleep(1000); System.out.println(cal.getTime()); Thread.sleep(2000); System.out.println(cal.getTimeStamp()); }*/ }//class
true
01403202314ac34d4e72860335460366628f0fea
Java
garygb/notes
/SpringAnno/src/main/java/com/gary/SpringAnno/App.java
UTF-8
657
2.5625
3
[]
no_license
package com.gary.SpringAnno; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Hello world! * */ //Spring Core Annotations public class App { public static void main( String[] args ) { //create a class who will provide me the configuration ApplicationContext factory = new AnnotationConfigApplicationContext(AppConfig.class); //只有在配置类里面提供有返回这个类的方法之后,才能正常使用getBean方法 Samsung s7 = factory.getBean(Samsung.class); s7.config(); } }
true
7c813707bd14da61717957ff62bed3b6cba12bd0
Java
hateftad/Attraversiamo-Gradle
/core/src/com/me/utils/DimensionsHelper.java
UTF-8
673
2.625
3
[]
no_license
package com.me.utils; public class DimensionsHelper { public static float initDimension(float height, float width){ float zoom = 0f; //iphone 4 if(height == 480 && width == 800){ zoom = 9.5f; } if(height == 640 && width == 960){ zoom = 9f; } //iphone 5 if(height == 640 && width == 1136){ zoom = 8f; } if(height == 720 && width == 1280){ zoom = 6f; } //ipad mini & other if(height == 768 && width == 1024){ zoom = 6f; } if(height == 800 && width == 1280){ zoom = 6f; } if(height == 1080 && width == 1920){ zoom = 5f; } //ipad if(height == 1536 && width == 2048){ zoom = 4f; } return zoom; } }
true
bf2990b231d1dbd2538b9716619375c05b53aab5
Java
dre24/Auora
/src/Auora/tools/EconomyChecker.java
UTF-8
2,636
2.84375
3
[]
no_license
package Auora.tools; import Auora.model.Item; import Auora.model.player.Player; import Auora.model.player.Prices; import Auora.model.player.StaffRights; import Auora.model.player.account.PlayerLoading; import Auora.rscache.Cache; import java.io.File; /** * Checks the economy for dupes * * @Author Jonny */ public class EconomyChecker { public static void main(String[] args) { System.out.println("Starting loading characters..."); new Cache(); File folder = new File("./characters"); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { if (listOfFiles[i].getName().contains(".json")) { long bankValue = 0; Player other = new Player(listOfFiles[i].getName().replace(".json", "")); PlayerLoading.getResult(other); if (other.getStaffRights() == StaffRights.OWNER || other.getStaffRights() == StaffRights.ADMINISTRATOR || other.getStaffRights() == StaffRights.GLOBAL_ADMIN || other.getStaffRights() == StaffRights.COMMUNITY_MANAGER || other.getStaffRights() == StaffRights.STAFF_MANAGER || other.getStaffRights() == StaffRights.DEVELOPER) { continue; } for (Item item : other.getBank().bank.getItems()) { if (item == null) { continue; } if (Prices.unspawnable_item(other, item.getId())) { long amount = (long) Prices.getPrice(other, item.getId()); amount *= (long) item.getAmount(); bankValue += amount; } } for (Item item : other.getInventory().inventory.getItems()) { if (item == null) { continue; } if (Prices.unspawnable_item(other, item.getId())) { long amount = (long) Prices.getPrice(other, item.getId()); amount *= (long) item.getAmount(); bankValue += amount; } } if (bankValue >= 500_000_000_000L) { System.out.println(other.getUsername() + " has a crazy bank value"); } } } } System.out.println("Finished checking characters for duped items."); } }
true
4250b93a9a7b9c6e528d4a13b7461f2e1b02e236
Java
msulima/redis-client
/src/test/java/pl/msulima/redis/benchmark/nonblocking/ProtocolWriterTest.java
UTF-8
2,754
2.765625
3
[]
no_license
package pl.msulima.redis.benchmark.nonblocking; import com.google.common.base.Charsets; import org.junit.Test; import redis.clients.jedis.Protocol; import java.nio.ByteBuffer; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; public class ProtocolWriterTest { private static final int BUFFER_SIZE = 64; private final ByteBuffer out = ByteBuffer.allocate(BUFFER_SIZE); private final ProtocolWriter writer = new ProtocolWriter(out); @Test public void testSingle() { // when writer.write(Protocol.Command.SET, "1".getBytes(), "".getBytes()); // then out.flip(); byte[] fullOutputBytes = new byte[64]; out.get(fullOutputBytes, 0, out.limit()); String expected = "*3\r\n$3\r\nSET\r\n$1\r\n1\r\n$0\r\n\r\n"; assertThat(new String(fullOutputBytes, 0, out.limit(), Charsets.US_ASCII)).isEqualTo(expected); } @Test public void testMultiple() { runTest(89); } @Test public void testLong() { runTest(512); } @Test public void testMultipleInLoop() { for (int i = 0; i < 100; i++) { try { runTest(i); } catch (RuntimeException | AssertionError ex) { System.err.println("Exception in iteration " + i); throw new RuntimeException(ex); } } } private void runTest(int emptyBytesLength) { // given final int messagesToWrite = 100; final byte[] emptyBytes = new byte[emptyBytesLength]; final String expected = "*3\r\n$3\r\nSET\r\n$1\r\n1\r\n$" + emptyBytes.length + "\r\n" + new String(emptyBytes, Charsets.US_ASCII) + "\r\n"; final String join = String.join("", Collections.nCopies(messagesToWrite, expected)); final byte[] fullOutputBytes = new byte[join.getBytes().length * 2]; // when final ProtocolWriter reader = new ProtocolWriter(out); final int maxLoops = ((emptyBytesLength / BUFFER_SIZE) + 2) * messagesToWrite; int messagesWritten = 0; int loops = 0; int bytesRead = 0; while (messagesWritten < messagesToWrite && loops < maxLoops) { while (messagesWritten < messagesToWrite && reader.write(Protocol.Command.SET, "1".getBytes(), emptyBytes)) { messagesWritten++; } out.flip(); out.get(fullOutputBytes, bytesRead, out.limit()); bytesRead += out.limit(); out.clear(); loops++; } // then assertThat(loops).isLessThan(maxLoops); assertThat(new String(fullOutputBytes, 0, bytesRead, Charsets.US_ASCII)).isEqualTo(join); } }
true
133a7e8887393068d77bbbd1ef508b07985369a3
Java
aza13/Javaprojects
/src/StringBuilderTasks/task1.java
UTF-8
1,389
3.5625
4
[]
no_license
package StringBuilderTasks; public class task1 { public static void main(String[] args) { String [] str = {"a","b","c"}; System.out.println(buildFrom(str)); StringBuilder stb=new StringBuilder(); stb.append("true"); stb.append("false"); stb.insert(0,"false"); stb.delete(2,3); System.out.println(toBe(stb)); String[] str1= {"abc","foo bar","123"}; System.out.println(trim_post(str1,5)); } public static StringBuilder buildFrom(String[]arr){ StringBuilder stb = new StringBuilder(); for (String str: arr){ stb.append(str); } return stb; } public static boolean toBe(StringBuilder stb){ String str = stb.toString(); String[] arr = str.split(","); boolean result= false; for (int i=0; i<arr.length; i++){ if (arr[i].contains("true")){ result=true; }else { result= false; } } return result; } public static StringBuilder trim_post(String[] arr, int size){ StringBuilder text = new StringBuilder(); for (String word: arr){ if (word.length()<=size){ text.append("<"+word+">"); }else { continue; } } return text; } }
true
404c20b6863cc74374d0b0559bd10ca2d97a691c
Java
zlw999/crims-hd-master
/crims-sgws-api/src/main/java/com/ireal/crims/sgws/main/SgwsClientMain.java
UTF-8
5,400
2.203125
2
[]
no_license
package com.ireal.crims.sgws.main; import com.ireal.crims.sgws.enums.SgAppType; import com.ireal.crims.sgws.enums.SgDataFormat; import com.ireal.crims.sgws.interfaces.SgwsCallbackInterface; import com.ireal.crims.sgws.interfaces.SgwsInterface; import com.ireal.crims.sgws.process.MsgProcesserTest; import com.ireal.crims.sgws.process.SgAppWebSocket; import com.ireal.crims.sgws.structs.SgAppHeader; import com.ireal.crims.sgws.structs.SgBody; import com.ireal.crims.sgws.structs.SgHeader; import org.java_websocket.WebSocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; public class SgwsClientMain implements SgwsInterface { public Logger logger = LoggerFactory.getLogger(getClass()); private static SgAppWebSocket sgAppWebSocket; private static class SingletonHolder { public static SgwsClientMain instance = new SgwsClientMain(); } public static SgwsClientMain getInstance() { return SingletonHolder.instance; } private SgwsCallbackInterface ctrlCB = null; private String clientAppDomainId; // 本域Id private String clientAppNodeId; // 本节点Id //回调接口 public SgwsCallbackInterface getCtrlCB() { return this.ctrlCB; } //初始化 @Override public boolean Init(String sgServerEndPointsIp, int nConnPort, String wsClientNodeId, String wsClientDomainId) throws URISyntaxException { this.clientAppDomainId = wsClientDomainId; this.clientAppNodeId = wsClientNodeId; URI uri = new URI("ws://" + sgServerEndPointsIp + ":" + nConnPort + "/" + wsClientNodeId + "//"); sgAppWebSocket = new SgAppWebSocket(uri); logger.info("初始化ip和端口成功---url:" + uri); return true; } public void getConnect() { if (!sgAppWebSocket.isOpen()) { if (sgAppWebSocket.getReadyState().equals(WebSocket.READYSTATE.NOT_YET_CONNECTED)) { sgAppWebSocket.connect(); } } /* while(!sgAppWebSocket.getReadyState().equals(WebSocket.READYSTATE.OPEN)){ logger.info("正在连接。。。。"); }*/ } //反初始化 public void UnInit() { // TODO Auto-generated method stub } // 启动 public boolean OnStart() { return true; } //停止连接 public void OnStop() { // TODO Auto-generated method stub } @Override public boolean SendData(SgAppType appType, int sequenceNo, int reqNo, SgDataFormat dataFormat, String destDomainId, String destAppNodeId, String appData) throws UnsupportedEncodingException { if( this.clientAppNodeId.isEmpty() ) { return false; } if( this.clientAppDomainId.isEmpty() ) { return false; } if( destAppNodeId.isEmpty() ) { return false; } if( destDomainId.isEmpty() ) { return false; } SgAppHeader sgAppHeader = new SgAppHeader(); sgAppHeader.setAppType((byte)appType.getType()); sgAppHeader.setSequenceNo(sequenceNo); sgAppHeader.setReqNo(reqNo); sgAppHeader.setDataFormat((byte)dataFormat.getDataType()); sgAppHeader.getDestAddr().setDomainId(destDomainId); sgAppHeader.getDestAddr().setAppNodeId(destAppNodeId); sgAppHeader.getSrcAddr().setDomainId(this.clientAppDomainId); sgAppHeader.getSrcAddr().setAppNodeId(this.clientAppNodeId); //获取体的长度 int length = appData.getBytes(SgAppHeader.Protocol_CharsetName_UTF8).length; //转换为字节数组 byte[] appDataBytes = appData.getBytes(SgAppHeader.Protocol_CharsetName_UTF8); SgHeader sgHeader = new SgHeader(); SgBody sgBody = new SgBody(sgHeader, sgAppHeader, appDataBytes); if (!sgBody.Init()) { return false; } byte[] msg = sgBody.encode(); boolean bTest = false; if( bTest ) { MsgProcesserTest.getInstance().addMsg(msg); } else { if (null != msg) { SgHeader tmpHeader = new SgHeader(); SgAppHeader tmpAppHeader = new SgAppHeader(); SgBody.decodeHeader(msg, tmpHeader, tmpAppHeader); //发送数据 sgAppWebSocket.send(msg); } } return true; } //发送数据 public boolean SendData(SgAppHeader sgAppHeader, String appData) throws UnsupportedEncodingException { // TODO Auto-generated method stub //获取体的长度 int length = appData.getBytes(SgAppHeader.Protocol_CharsetName_UTF8).length; //转换为字节数组 byte[] appDataBytes = appData.getBytes(SgAppHeader.Protocol_CharsetName_UTF8); SgHeader sgHeader = new SgHeader(); SgBody sgBody = new SgBody(sgHeader, sgAppHeader, appDataBytes); if (!sgBody.Init()) { return false; } byte[] msg = sgBody.encode(); if (null != msg) { SgHeader tmpHeader = new SgHeader(); SgAppHeader tmpAppHeader = new SgAppHeader(); SgBody.decodeHeader(msg, tmpHeader, tmpAppHeader); //发送数据 sgAppWebSocket.send(msg); } return true; } public boolean setCtrlCB(SgwsCallbackInterface ctrlCB) { this.ctrlCB = ctrlCB; return true; } private int nProtocolRequenceNo = 0; public int getProtocolRequenceNo() { this.nProtocolRequenceNo++; return this.nProtocolRequenceNo; } }
true
3fdccff4d31db591240ef2837258b3f9308381bd
Java
mvpdev/drishti-childcount-bridge
/drishti-scheduler/src/main/java/org/ei/drishti/scheduler/DrishtiSchedules.java
UTF-8
786
1.859375
2
[]
no_license
package org.ei.drishti.scheduler; public class DrishtiSchedules { public static final String SCHEDULE_ANC = "Ante Natal Care - Normal"; public static final String SCHEDULE_EDD = "Expected Date Of Delivery"; public static final String SCHEDULE_IFA = "Iron Folic Acid Supplements"; public static final String SCHEDULE_LAB = "Lab Reminders"; public static final String SCHEDULE_TT = "Tetatnus Toxoid Vaccination"; public static final String CHILD_SCHEDULE_BCG = "BCG"; public static final String CHILD_SCHEDULE_DPT = "DPT"; public static final String CHILD_SCHEDULE_HEPATITIS = "Hepatitis"; public static final String CHILD_SCHEDULE_MEASLES = "Measles Vaccination and Vitamin Supplements"; public static final String CHILD_SCHEDULE_OPV = "OPV"; }
true
4ee19390a2cf8fbf099e3753d029b978d08763b6
Java
pnlinh-ivc/MVP-Demo
/app/src/main/java/com/pnlinh/mvpdemo/home/HomePresenterImpl.java
UTF-8
2,832
2.25
2
[]
no_license
package com.pnlinh.mvpdemo.home; import android.content.Context; import android.content.res.Resources; import android.os.Handler; import android.os.Looper; import android.speech.tts.TextToSpeech; import android.util.Log; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.pnlinh.mvpdemo.R; import com.pnlinh.mvpdemo.base.BasePresenterImpl; import com.pnlinh.mvpdemo.base.BaseView; import com.pnlinh.mvpdemo.model.WordData; import org.apache.commons.io.IOUtils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * Created by pnLinh on 19/10/2017. */ public class HomePresenterImpl extends BasePresenterImpl<HomeContract.ViewMethod> implements HomeContract.PresenterMethod { private static final String TAG = HomePresenterImpl.class.getSimpleName(); private Handler mHandler = new Handler(Looper.getMainLooper()); private TextToSpeech mTextToSpeech; public HomePresenterImpl() { super(); } @Override public void getData(String query) { new Thread(new GetDataRunnable(query)).start(); } @Override public void speak(String word) { try { Log.e(TAG, String.format("speak: ")); if (mTextToSpeech == null) mTextToSpeech = new TextToSpeech(((Context) mView), null); mTextToSpeech.setLanguage(Locale.US); mTextToSpeech.speak(word, TextToSpeech.QUEUE_ADD, null); } catch (Exception ex) { ex.printStackTrace(); } } private class GetDataRunnable implements Runnable { String query; public GetDataRunnable(String query) { this.query = query; } //onther code @Override public void run() { try { Resources res = ((Context) mView).getResources(); InputStream inputStream = res.openRawResource(R.raw.data); String data = IOUtils.toString(inputStream); Gson gson = new Gson(); List<WordData> listData = gson.fromJson(data, new TypeToken<List<WordData>>() { }.getType()); final List<WordData> result = new ArrayList<>(); for (WordData wordData : listData) { if (wordData.getTitle().toLowerCase().contains(query.toLowerCase())) result.add(wordData); } mHandler.post(new Runnable() { @Override public void run() { mView.showList(result); } }); } catch (Exception e) { e.printStackTrace(); } } } }
true
4381b437afea80639977d5813b7350be44e20b87
Java
Descartes310/OnePassTwig2Stack
/src/DataClass/XmlDocument.java
UTF-8
2,106
3.125
3
[]
no_license
/* * This class define tree structure of an XML Document. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DataClass; import java.util.ArrayList; /** * * @author Descartes Fowo */ public class XmlDocument { private DocElement root; private ArrayList<XmlDocument> childs; public XmlDocument(DocElement root) { this.root = root; this.childs = new ArrayList<>(); } public XmlDocument(String element) { this.root = new DocElement(element); this.childs = new ArrayList<>(); } public boolean isLeaf() { return childs.isEmpty(); } @Override public String toString() { return root.getTag() + "{" + childs + '}'; } public void addChild(XmlDocument xmlDoc) { childs.add(xmlDoc); } public int childSize() { return childs.size(); } public XmlDocument getChildAt(int i) { return childs.get(i); } public void printPosOrder() { String toret = ""; if (isLeaf()) { toret = toret + root.getTag() + " : Value = " + root.getValue(); } else { toret = toret + "["; for (int i = 0; i <= childs.size() - 1; i++) { childs.get(i).printPosOrder(); toret = toret + childs.get(i).getRoot().getTag() + ","; } toret = toret + "]" + root.getTag(); } System.out.println(toret); } public DocElement getRoot() { return root; } public void setRoot(DocElement root) { this.root = root; } public void buildStack(Stack<DocElement> stack) { stack.push(root); for (int i = childs.size() - 1; i >=0 ; i--) { childs.get(i).buildStack(stack); } } public void buildPrefStack(Stack<DocElementPref> stack) { DocElementPref elem = new DocElementPref(root); stack.push(elem); for (int i = childs.size() - 1; i >=0 ; i--) { childs.get(i).buildPrefStack(stack); } } }
true
5cbf57a253bf587271eff0ac76033df4ad2655de
Java
lfsidfj/zlp
/src/main/java/spiderman/test/AlipayTest.java
UTF-8
3,129
2.25
2
[]
no_license
package spiderman.test; import org.junit.Test; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.request.AlipayFundTransToaccountTransferRequest; import com.alipay.api.request.AlipayTradePagePayRequest; import com.alipay.api.response.AlipayFundTransToaccountTransferResponse; import spiderman.alipay.config.AlipayConfig; public class AlipayTest { @Test public void test1() throws AlipayApiException{ AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE); AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest(); request.setBizContent("{" + " \"out_biz_no\":\"3142321423432\"," + " \"payee_type\":\"ALIPAY_LOGONID\"," + " \"payee_account\":\"qextwe6370@sandbox.com\"," + " \"amount\":\"12.23\"," + " \"payer_show_name\":\"上海交通卡退款\"," + " \"payee_real_name\":\"沙箱环境\"," + " \"remark\":\"转账备注\"," + " }"); AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request); if(response.isSuccess()){ System.out.println("调用成功"); } else { System.out.println("调用失败"); } } @Test public void test2(){ AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE); AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request alipayRequest.setReturnUrl("http://domain.com/CallBack/return_url.jsp"); alipayRequest.setNotifyUrl("http://domain.com/CallBack/notify_url.jsp");//在公共参数中设置回跳和通知地址 alipayRequest.setBizContent("{" + " \"out_trade_no\":\"20150320010101001\"," + " \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," + " \"total_amount\":0.01," + " \"subject\":\"Iphone6 16G\"," + " \"body\":\"Iphone6 16G\"," + " \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," + " \"extend_params\":{" + " \"sys_service_provider_id\":\"2088511833207846\"" + " }"+ " }");//填充业务参数 String form=""; try { form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单 } catch (AlipayApiException e) { e.printStackTrace(); } System.out.println(form); }/* @Test public void test3() throws AlipayApiException{ AlipayFundTransToaccountTransferResponse response=AlipayInterfaceInvokeUtil.AlipayFundTransToaccountTransfer("2017050002", "ALIPAY_LOGONID", "qextwe6370@sandbox.com", "12.23", "上海交通卡退款", "沙箱环境", "kk"); if(response.isSuccess()){ System.out.println("调用成功"); } else { System.out.println("调用失败"); } }*/ }
true
aeacac0674b2992cf82ad73ec970a4168dde0b0f
Java
NewTownData/osmismerka
/app/src/main/java/com/newtowndata/osmismerka/Solver.java
UTF-8
1,415
2.734375
3
[ "Apache-2.0" ]
permissive
/** * Copyright 2021 Voyta Krizek, https://github.com/NewTownData * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.newtowndata.osmismerka; /** * * @author Voyta Krizek, https://github.com/NewTownData */ public class Solver { public String solve(String areaString, String dictString) { String[] areaRows = areaString.split("\\s"); String[] dict = dictString.split("\\s"); return solve(areaRows, dict); } public String solve(String[] areaRows, String[] dict) { char[][] area = new char[areaRows.length][]; for (int i = 0; i < areaRows.length; i++) { area[i] = areaRows[i].toCharArray(); } return solve(area, dict); } public String solve(char[][] area, String[] dict) { if (dict == null || dict.length < 1) { throw new IllegalArgumentException("dict"); } Finder f = new Finder(area); for (String word : dict) { f.foundWord(word); } return f.createResult(); } }
true
a437c7765c975c34fd347645346c9a7a0fa642b1
Java
MilicaPoparic/MRS_ISA_T10
/src/main/java/main/mrs/service/OcenaKlinikaService.java
UTF-8
1,229
2.078125
2
[]
no_license
package main.mrs.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import main.mrs.model.Lek; import main.mrs.model.OcenaKlinika; import main.mrs.repository.OcenaKlinikaRepository; @Service public class OcenaKlinikaService { @Autowired private OcenaKlinikaRepository OcenaKlinikaRepository; public OcenaKlinika findOne(Long id) { return OcenaKlinikaRepository.findById(id).orElseGet(null); } public List<OcenaKlinika> findAll() { return OcenaKlinikaRepository.findAll(); } public Page<OcenaKlinika> findAll(Pageable page) { return OcenaKlinikaRepository.findAll(page); } public OcenaKlinika save(OcenaKlinika OcenaKlinika) { return OcenaKlinikaRepository.save(OcenaKlinika); } public void remove(Long id) { OcenaKlinikaRepository.deleteById(id); } public void delete(OcenaKlinika ocena) { OcenaKlinikaRepository.delete(ocena); } public OcenaKlinika findOcenu(int klinikaId, int pacijentId) { // TODO Auto-generated method stub return OcenaKlinikaRepository.findOcenu(klinikaId, pacijentId); } }
true
418c8a857848ac344684f60219e7b9f90561f15e
Java
Khellendroscn/JavaHomeWork
/src/net/khe/homework9/App1.java
UTF-8
382
2.484375
2
[]
no_license
package net.khe.homework9; /** * Created by hyc on 2016/12/2. */ public class App1 { public static void main(String[] args) { Thread t1 = new Thread(new Runner()); t1.start(); new Thread(()->{ for(int i=100;i>=0;--i){ System.out.println("Hello"+i); Thread.yield(); } }).start(); } }
true
dfa420ff00737130aa529800a0e15e4c2d3ecf78
Java
ohmema/interview
/java/interviews/CS502/Lab2/src/NewtonIteration6.java
UTF-8
1,987
3.40625
3
[ "Apache-2.0" ]
permissive
import components.simplereader.SimpleReader; import components.simplereader.SimpleReader1L; import components.simplewriter.SimpleWriter; import components.simplewriter.SimpleWriter1L; public class NewtonIteration6 { /** * Reports the non-negative square root of {@code x} to within relative * error {@code epsilon}. * * @param x * number whose square root is to be computed * @param epsilon * maximum relative error of result * @requires <pre> * {@code * x > 0 and epsilon > 0 * } * </pre> * @ensures <pre> * {@code * sqrt >= 0 and * |sqrt - x^(1/2)| / x^(1/2) <= epsilon * * if x=0, sqrt returns 1 * } * </pre> */ private static double sqrt(double x, double r, double epsilon) { double result = r; double epsilon2 = epsilon * epsilon; int iteration = 0; // System.out.println(" x " + x + " r " + r + " e " + epsilon); // System.out.println(" first iter" + Math.abs(result * result - x) / // x); while ((Math.abs(result * result - x)) / x > epsilon2) { result = (result + x / result) / 2; System.out.println("Iteration " + iteration++ + " result: " + result); // iteration++; } // System.out.println("iteration : " + iteration); return result; } public static void main(String[] args) { SimpleReader input = new SimpleReader1L(); SimpleWriter output = new SimpleWriter1L(); if (args == null) { System.err.println("Error: NO Main arguments inserted"); System.err.println("Program terminates"); return; } double e = Double.parseDouble(args[0]); System.out.println("double e " + e); while (true) { output.print(" x (x<0, terminate) = "); double x = input.nextDouble(); if (x < 0) { output.println("Goodbye!"); return; } double r = -1; do { output.print(" r ( r>=2) = "); r = input.nextDouble(); } while (r < 2); output.println(" sqrt(x) = " + sqrt(x, r, e) + " Math.sqrt(x) =" + Math.sqrt(x)); } } }
true
b71be115c828dee9755a15fa213b6781f65b2983
Java
zhangswww/ssm_thymeleaf
/src/main/java/com/example/ssmThymeleaf/service/UserService.java
UTF-8
169
1.757813
2
[]
no_license
package com.example.ssmThymeleaf.service; import com.example.ssmThymeleaf.domain.User; import java.util.List; public interface UserService { List<User> list(); }
true
0a21773551b44d43e13c331147a0ec0c507bd2f7
Java
RomanBortnyk/crawler-microservice
/core/src/main/java/core/annotation/processor/StartupParserClassesContainer.java
UTF-8
1,163
2.34375
2
[]
no_license
package core.annotation.processor; import core.annotation.Parser; import lombok.extern.slf4j.Slf4j; import org.reflections.Reflections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; @Slf4j public class StartupParserClassesContainer { private final Map<String, Class<?>> startupClasses; // TODO throw exception if two identical names present public StartupParserClassesContainer(String parsersPackagePath) { startupClasses = new HashMap<>(); Reflections reflections = new Reflections(parsersPackagePath); Set<Class<?>> parserStartupClasses = reflections.getTypesAnnotatedWith(core.annotation.Parser.class); parserStartupClasses.forEach(c -> { String name = c.getAnnotation(Parser.class).name(); startupClasses.put(name, c); }); if (parsersPackagePath.isEmpty()){ log.warn("No parsers where found by path: " + parsersPackagePath); } } public Optional<Class<?>> getStartupClass(String parserName) { return Optional.ofNullable(startupClasses.get(parserName)); } }
true
cfec86a665d6a67ed05e521df4a2194e5cc78b8a
Java
systembugtj/reader
/src/DaisyReader/tests/com/ader/DaisyParserTest.java
UTF-8
1,477
2.8125
3
[]
no_license
package com.ader; /** * Tests for the DaisyParser class, to help us express the intent of the class * and to test the ongoing changes and refactoring. * * Currently these tests assume DAISY 202 content e.g. ncc.html */ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import com.ader.testutilities.SampleContent; import junit.framework.TestCase; public class DaisyParserTest extends TestCase { DaisyParser parser; String path; String filename; public void setUp() throws Exception { parser = new DaisyParser(); path = new File(".").getCanonicalPath(); filename = path + "/Resources/light-man/ncc.html"; } /** * Ensures we can parse the ncc.html content from a file. Runs in JUnit3 * @throws IOException */ public void testCanParseFromFile() throws IOException { ArrayList<DaisyElement> elements = parser.openAndParseFromFile(filename); assertTrue("There should be SOME content", elements.size() > 0); } public void testCanParseFromTextContent() { System.out.println(SampleContent.simpleValidNccHtml); ArrayList<DaisyElement> elements = parser.parse(SampleContent.simpleValidNccHtml); assertTrue("There should be SOME content", elements.size() > 0); } public void testCanParseFromInputStream() throws Exception { ArrayList<DaisyElement> elements = parser.parse(new FileInputStream(filename)); assertTrue("There should be SOME content", elements.size() > 0); } }
true
0605372cbe4d09e08a4c423eb6dfe8f7133ffe86
Java
gscc-sonia/ADV4_S1Project
/ADV4_S1/src/main/java/com/gscc/adv4_s1/MainActivity.java
UTF-8
6,319
2.078125
2
[]
no_license
package com.gscc.adv4_s1; import android.annotation.TargetApi; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.os.Build; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import android.widget.VideoView; public class MainActivity extends ActionBarActivity { //@@@@@全區宣告start VideoView vvVideoView1; TextView tvTextView1, tvTextView2; ImageView ivImageView1; Thread countToLoop; int i; //@@@@@全區宣告 //@@@@@ public Handler mHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); int a = msg.getData().getInt("count", 0); if (a == 1) { //@@ //musle test-----3 ImagePlayer(); //tx1.setText("影片1"); } if (a == 61) { VideoPlayer2(); //marquee.setText("影片2"); } if (a == 121) { //marquee.setText("影片3"); VideoPlayer3(); } if (a == 181) { //marquee.setText("影片4"); VideoPlayer4(); } if (a == 241) { //marquee.setText("影片5"); VideoPlayer5(); } } }; //@@@@@ @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); //@@@@@全螢幕start requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); //@@@@@全螢幕 countToLoop = new countToLoop(); countToLoop.start(); } //@@@@@播放器start @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void VideoPlayer1() { setContentView(R.layout.activity_main); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); Uri video1 = Uri.parse("sdcard/test.m4v"); vvVideoView1 = (VideoView) findViewById(R.id.videoView1); vvVideoView1.setVideoURI(video1); vvVideoView1.start(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void VideoPlayer2() { setContentView(R.layout.activity_main); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); Uri video1 = Uri.parse("sdcard/test2.mp4"); vvVideoView1 = (VideoView) findViewById(R.id.videoView1); vvVideoView1.setVideoURI(video1); vvVideoView1.start(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void VideoPlayer3() { setContentView(R.layout.activity_main); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); Uri video1 = Uri.parse("sdcard/test3.mp4"); vvVideoView1 = (VideoView) findViewById(R.id.videoView1); vvVideoView1.setVideoURI(video1); vvVideoView1.start(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void VideoPlayer4() { setContentView(R.layout.activity_main); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); Uri video1 = Uri.parse("sdcard/test4.mp4"); vvVideoView1 = (VideoView) findViewById(R.id.videoView1); vvVideoView1.setVideoURI(video1); vvVideoView1.start(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void VideoPlayer5() { setContentView(R.layout.activity_main); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); Uri video1 = Uri.parse("sdcard/test5.mp4"); vvVideoView1 = (VideoView) findViewById(R.id.videoView1); vvVideoView1.setVideoURI(video1); vvVideoView1.start(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void ImagePlayer() { setContentView(R.layout.image_main); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); Uri image1 = Uri.parse("sdcard/test1.jpg"); ivImageView1 = (ImageView) findViewById(R.id.imageView); ivImageView1.setImageURI(image1); } //@@@@@播放器 //@@@@@@計時器 class countToLoop extends Thread { @Override public void run() { super.run(); goPlay(); } public void goPlay() { try { while (true) { for (i = 0; i < 50; i++) { Thread.sleep(1000); Bundle countBundle = new Bundle(); countBundle.putInt("count", i + 1); Message msg = new Message(); msg.setData(countBundle); mHandler.sendMessage(msg); } } } catch (InterruptedException e) { e.printStackTrace(); } } } //@@@@@計時器 @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case R.id.action_settings: return true; } return super.onOptionsItemSelected(item); } }
true
0d19f21a13ae85488c741e3d03d2ddc85174a91a
Java
STAMP-project/dspot-experiments
/benchmark/training/com/annimon/stream/function/SupplierTest.java
UTF-8
3,076
2.703125
3
[]
no_license
package com.annimon.stream.function; import Supplier.Util; import com.annimon.stream.Functions; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; /** * Tests {@code Supplier}. * * @see com.annimon.stream.function.Supplier */ public class SupplierTest { private static byte[] input; @Test public void testPrivateConstructor() throws Exception { Assert.assertThat(Util.class, hasOnlyPrivateConstructors()); } @Test public void testGetString() { Supplier<String> supplier = new Supplier<String>() { @Override public String get() { return "fantastic"; } }; Assert.assertEquals("fantastic", supplier.get()); } @Test public void testGetStringBuilder() { Supplier<StringBuilder> supplier = Functions.stringBuilderSupplier(); Assert.assertThat(supplier.get(), CoreMatchers.instanceOf(StringBuilder.class)); Assert.assertTrue(supplier.get().toString().isEmpty()); } @Test public void testIncrement() { Supplier<Integer> supplier = new Supplier<Integer>() { private int counter = 0; @Override public Integer get() { return (counter)++; } }; Assert.assertEquals(0, supplier.get().intValue()); Assert.assertEquals(1, supplier.get().intValue()); Assert.assertEquals(2, supplier.get().intValue()); Assert.assertEquals(3, supplier.get().intValue()); } @Test public void testSafe() throws IOException { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(SupplierTest.input)); Supplier<String> supplier = Util.safe(new SupplierTest.UnsafeSupplier(dis)); Assert.assertThat(supplier.get(), Matchers.is("test")); Assert.assertThat(supplier.get(), Matchers.is("123")); Assert.assertThat(supplier.get(), Matchers.is(Matchers.nullValue())); Assert.assertThat(supplier.get(), Matchers.is(Matchers.nullValue())); } @Test public void testSafeWithOnFailedSupplier() throws IOException { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(SupplierTest.input)); Supplier<String> supplier = Util.safe(new SupplierTest.UnsafeSupplier(dis), "oops"); Assert.assertThat(supplier.get(), Matchers.is("test")); Assert.assertThat(supplier.get(), Matchers.is("123")); Assert.assertThat(supplier.get(), Matchers.is("oops")); Assert.assertThat(supplier.get(), Matchers.is("oops")); } private static class UnsafeSupplier implements ThrowableSupplier<String, Throwable> { private final DataInputStream is; UnsafeSupplier(DataInputStream is) { this.is = is; } @Override public String get() throws IOException { return is.readUTF(); } } }
true
78d79d37524ff5b2855caf03867d1d9547431178
Java
luyota/CS227B-Dumplings
/src/com/dumplings/heuristics/FocusedMonteCarlo.java
UTF-8
2,403
2.9375
3
[]
no_license
package com.dumplings.heuristics; import java.util.List; import java.util.Random; import util.statemachine.MachineState; import util.statemachine.Move; import util.statemachine.Role; import util.statemachine.StateMachine; import util.statemachine.exceptions.GoalDefinitionException; import util.statemachine.exceptions.MoveDefinitionException; import util.statemachine.exceptions.TransitionDefinitionException; import com.dumplings.general.AbstractHeuristic; import com.dumplings.general.PlayerHeuristic; public class FocusedMonteCarlo extends AbstractHeuristic implements PlayerHeuristic { private StateMachine stateMachine; private Random generator = new Random(); private int numSamples = 4; public FocusedMonteCarlo(StateMachine sm) { stateMachine = sm; } public void setSampleSize(int size) { numSamples = size; } @Override public Integer getScore(MachineState state, Role role) throws MoveDefinitionException, TransitionDefinitionException, GoalDefinitionException { int score = 0; // First decide which next state to apply MonteCarlo to // Reasoning: MonteCarlo will be more accurate for the next state which has more focus List<List<Move>> allMoves= stateMachine.getLegalJointMoves(state); int focus = Integer.MAX_VALUE; for (List<Move> move : allMoves) { if (stopExecution) return null; MachineState nextState = stateMachine.getNextState(state, move); // Get mobility of nextState int newMobility = stateMachine.getLegalMoves(nextState, role).size(); if (newMobility < focus) { focus = newMobility; state = nextState; } } if (stateMachine.isTerminal(state)) return stateMachine.getGoal(state, role); for (int i = 0; i < numSamples; i++) { MachineState currentState = state; while (!stateMachine.isTerminal(currentState)) { if (stopExecution) { if (i == 0) return null; // Couldn't even sample one depth charge! else return score / i; // Return average score that we have seen so far } allMoves = stateMachine.getLegalJointMoves(currentState); List<Move> randomMoves = allMoves.get(generator.nextInt(allMoves.size())); currentState = stateMachine.getNextState(currentState, randomMoves); } score += stateMachine.getGoal(currentState, role); } return score / numSamples; } @Override public String toString() { return "FocusedMonteCarlo"; } }
true
5934b79c6a8c2a2eefd59cf0d62850c8073f81ae
Java
edersonjseder/beautyfit
/projetobeauty/src/main/java/br/com/beautyfit/endpoint/Path.java
UTF-8
960
1.601563
2
[]
no_license
package br.com.beautyfit.endpoint; public class Path { public final static String BASE_URL = "beautyfit/v1"; public final static String OAUTH_URL = "http://192.168.1.101:8081"; public final static String OAUTH_URL_LH = "http://localhost:8081"; public static class urls{ public final static String CLIENTS = BASE_URL + "/clients"; public final static String PRODUCTS = BASE_URL + "/products"; public final static String SERVICES = BASE_URL + "/services"; public final static String PROVIDERS = BASE_URL + "/providers"; public final static String EMPLOYEES = BASE_URL + "/employees"; public final static String BILLSTOPAY = BASE_URL + "/billsToPay"; public final static String BILLSTORECEIVE = BASE_URL + "/billsToReceive"; public final static String USERS = BASE_URL + "/users"; } public static class tokenUrl { public final static String TOKEN_PATH = OAUTH_URL + "/oauth/check_token"; } }
true
c43935f8907307d97d3bffe6e90ee04226434f1d
Java
glauciom/combinatorial-algorithms
/src/kNSubset/UnSerialKNSubsetMethod.java
ISO-8859-1
2,315
3.171875
3
[]
no_license
/* * Created on 17/10/2004 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package kNSubset; import java.math.BigInteger; /** * @author GLAUCIO * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class UnSerialKNSubsetMethod { private int n, k,x,y,index; private BigInteger serial; private int[] subset; public UnSerialKNSubsetMethod(int n) { this.n = n; } //Calcula o fatorial de um numero. private String factorial(int r, int op) { BigInteger aux = BigInteger.ONE; for (int t = r; t > op; t--) { aux = aux.multiply(BigInteger.valueOf((long) t)); } return aux.toString(); } //Calcula o binomial, com otimizaes quanto multiplicao. public BigInteger getBinomialElements(int r, int s) { if ((r - s) < s) return new BigInteger(factorial(r, s)).divide(new BigInteger(factorial(r - s, 1))); return new BigInteger(factorial(r, r - s)).divide(new BigInteger(factorial(s, 1))); } public BigInteger unserialKNSubsetAlgorithm(int[] subset) { this.subset = subset; this.k = subset.length; x = n; y = k-1; serial = BigInteger.ONE; index = 0; serial = element(subset); return serial; } public BigInteger element(int[] subset) { for(int i = 0; i < subset.length; i++) { for(int j = 1; j < subset[i] - index; j++) serial = serial.add(getBinomialElements(x-j,y)); x = x - (subset[i] - index); y = y - 1; index = subset[i]; } return serial; } public String toString() { return serial.toString(); } public static void main(String[] args) { int n = 60; int k = 6; SerialKNSubsetMethod test = new SerialKNSubsetMethod(n,k); int k1 = test.getBinomialElements(n,k).intValue(); System.out.println(k1); UnSerialKNSubsetMethod test1 = new UnSerialKNSubsetMethod(n); int[] res = {55, 56, 57, 58, 59, 60}; test1.unserialKNSubsetAlgorithm(res); System.out.println(test1); /*for (int i = 1; i <= k1; i++) { test.serialKNSubsetAlgorithm(i+""); test1.unserialKNSubsetAlgorithm(test.getSubset()); System.out.println(test1); }*/ } }
true
3c99f251e0363824e93dfe22d319d06651ab0128
Java
deyim/OOP_Prac
/CH1/src/guitarStore/Inventory.java
UTF-8
986
3.0625
3
[]
no_license
package guitarStore; import java.util.List; import java.util.Iterator; import java.util.LinkedList; public class Inventory { private List<Guitar> guitars; public Inventory() { this.guitars = new LinkedList<Guitar>(); } public void addGuitar(String serialNumber, double price, GuitarSpec spec) { Guitar guitar = new Guitar(serialNumber, price, spec); guitars.add(guitar); } public Guitar getGuitar(String serialNumber) { for(Iterator<Guitar> i = guitars.iterator(); i.hasNext(); ) { Guitar guitar = (Guitar) i.next(); if(guitar.getSerialNumber().equals(serialNumber)) { return guitar; } } return null; } public List<Guitar> search(GuitarSpec searchSpec) { List<Guitar> matchingGuitars = new LinkedList<Guitar>(); for(Iterator<Guitar> i = guitars.iterator(); i.hasNext(); ) { Guitar guitar = (Guitar)i.next(); if(guitar.getSpec().matches(searchSpec)) matchingGuitars.add(guitar); } return matchingGuitars; } }
true
bf882e561703c29d359622fa7371fc2973f78cb1
Java
pnandi87/mstraining
/demo/src/main/java/com/bootcamp/demo/controller/GreetingController.java
UTF-8
1,373
2.46875
2
[]
no_license
package com.bootcamp.demo.controller; import java.time.Instant; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.bootcamp.demo.model.Greeting; import com.bootcamp.demo.repo.GreetingRepository; @RestController public class GreetingController { @Autowired GreetingRepository repo; @Value("${greetProp}") String defaultGreeting; @RequestMapping(path = "/greeting/default") public String getGreeting() { //return " Welcome to MS bootcamp"; return defaultGreeting; } @RequestMapping(path = "/greeting/{username}") public String getGreeting(@PathVariable String username) { return " Welcome to MS bootcamp : " + username + " " + Instant.now().toString(); } @RequestMapping(path = "/greeting/details/{username}") public Greeting getGreetingObject(@PathVariable String username) { Greeting greeting = new Greeting(100 , "Hello", username); return greeting; } @RequestMapping(path = "/greetings") public List<Greeting> getAllGreetings() { List<Greeting> list = repo.findAll(); return list; } }
true
91cc18a46a8046d159871ae6dbd9fc181e872d3c
Java
jsihota/Transactions
/src/test/java/com/transactions/reportcalculator/WithIncomeAndSpendingTest.java
UTF-8
3,577
2.5625
3
[]
no_license
package com.transactions.reportcalculator; import com.transactions.common.ReportCalculator; import com.transactions.model.Entries; import com.transactions.model.Report; import com.transactions.model.Transaction; import com.transactions.model.TransactionAction; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class WithIncomeAndSpendingTest { ReportCalculator reportCalculator = new ReportCalculator(); Report report; @Before public void setup() { System.out.println("@Before - runBeforeTestMethod"); report = reportCalculator.calculate(bothTransactions()); } @Test public void testAverageTest() { Entries average = report.getAverage(); Assert.assertNotNull(average); Assert.assertEquals("$505.00",average.getIncome()); Assert.assertEquals("$200.00",average.getSpending()); } @Test public void testLineItemsTest() { HashMap<String, Entries> lineItems = report.getLineItem(); Assert.assertNotNull(lineItems); Entries entries = lineItems.get("2015-11"); Assert.assertNotNull(entries); Assert.assertEquals("$400.00",entries.getSpending()); Assert.assertEquals("$1,010.00",entries.getIncome()); } @Test public void testIgnoredItemsTest() { HashMap<String, Entries> ignoredLineItems = report.getIgnoredLineItem(); Assert.assertNotNull(ignoredLineItems); Entries entries = ignoredLineItems.get("2015-11"); Assert.assertNotNull(entries); Assert.assertEquals("$300.00",entries.getSpending()); Assert.assertEquals("$0.00",entries.getIncome()); } private List<Transaction> bothTransactions(){ List<Transaction> anyTransactions = new ArrayList<>(); Transaction income = new Transaction(); income.setAmount(1000.00); income.setCategorization("paycheck"); income.setRawMerchant("any"); income.setMonth("2015-11"); income.setTransactionAction(TransactionAction.ADDED); Transaction secondIncome = new Transaction(); secondIncome.setAmount(10.00); secondIncome.setCategorization("paycheck"); secondIncome.setRawMerchant("any"); secondIncome.setMonth("2015-11"); secondIncome.setTransactionAction(TransactionAction.ADDED); Transaction spendingOne = new Transaction(); spendingOne.setAmount(-100.00); spendingOne.setCategorization("any"); spendingOne.setRawMerchant("any"); spendingOne.setMonth("2015-11"); spendingOne.setTransactionAction(TransactionAction.ADDED); Transaction spendingTwo = new Transaction(); spendingTwo.setAmount(-300.00); spendingTwo.setCategorization("any"); spendingTwo.setRawMerchant("any"); spendingTwo.setMonth("2015-11"); spendingTwo.setTransactionAction(TransactionAction.ADDED); Transaction ignoredSpending = new Transaction(); ignoredSpending.setAmount(-300.00); ignoredSpending.setCategorization("any"); ignoredSpending.setRawMerchant("any"); ignoredSpending.setMonth("2015-11"); ignoredSpending.setTransactionAction(TransactionAction.IGNORED); anyTransactions.add(income); anyTransactions.add(secondIncome); anyTransactions.add(spendingOne); anyTransactions.add(spendingTwo); anyTransactions.add(ignoredSpending); return anyTransactions; } }
true
523486258adeb75b28bd8b08ac4ad7429fcceb14
Java
JetBrains/intellij-community
/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/lambdaCodeBlock2Expr/beforeComparable.java
UTF-8
127
1.734375
2
[ "Apache-2.0" ]
permissive
// "Replace with expression lambda" "true-preview" class Test { { Comparable<String> c = (o) -> {r<caret>eturn 0;}; } }
true
6a7f82cfcfecf6255c78d4a6ed6de2e4156acac4
Java
PrabodDunuwila/siddhi-maven-archetype
/siddhi-script/src/main/resources/archetype-resources/component/src/main/java/__classNameOfScript__.java
UTF-8
4,390
2.65625
3
[ "Apache-2.0" ]
permissive
package ${package}; import io.siddhi.annotation.Example; import io.siddhi.annotation.Extension; import io.siddhi.core.function.Script; import io.siddhi.core.util.config.ConfigReader; import io.siddhi.query.api.definition.Attribute.Type; /** * This is a sample class-level comment, explaining what the extension class does. */ /** * Annotation of Siddhi Extension. * <pre><code> * eg:- * {@literal @}Extension( * name = "The name of the extension", * namespace = "The namespace of the extension", * description = "The description of the extension (optional).", * //Script configurations * parameters = { * {@literal @}Parameter(name = "The name of the first parameter", * description= "The description of the first parameter", * type = "Supported parameter types. * eg:{DataType.STRING, DataType.INT, DataType.LONG etc}", * dynamic= "false * (if parameter doesn't depend on each event then dynamic parameter is false.)", * optional= "true/false, defaultValue= if it is optional then assign a default value * according to the type."), * {@literal @}Parameter(name = "The name of the second parameter", * description= "The description of the second parameter", * type = "Supported parameter types. * eg:{DataType.STRING, DataType.INT, DataType.LONG etc}", * dynamic= "false * (if parameter doesn't depend on each event then dynamic parameter is false.)", * optional= "true/false, defaultValue= if it is optional then assign a default value * according to the type."), * }, * //If Script system configurations will need then * systemParameters = { * {@literal @}SystemParameter(name = "The name of the first system parameter", * description="The description of the first system parameter." , * defaultValue = "the default value of the system parameter.", * possibleParameter="the possible value of the system parameter.", * ), * }, * examples = { * {@literal @}Example(syntax = "sample query with Script annotation that explain how extension use in Siddhi." * description =" The description of the given example's query." * ), * } * ) * </code></pre> */ @Extension( name = "${_nameOfScript.toLowerCase()}", namespace = "script", description = " ", examples = { @Example( syntax = " ", description = " " ) } ) // For more information refer https://siddhi.io/en/v5.0/docs/query-guide/#script public class ${classNameOfScript} extends Script { /** * The initialization method for {@link Script}, which will be called before other methods and validate * the all configuration and getting the initial values. * * @param s denotes the function name of the {@link Script}. * @param s1 denotes the function body of the {@link Script} * @param configReader to read the Script related system configuration. */ @Override public void init(String s, String s1, ConfigReader configReader) { } /** * Get return type of the function. * * @return return type of the function. */ @Override public Type getReturnType() { return null; } /** * set return type of the function. */ @Override public void setReturnType(Type type) { } /** * Method to evaluate the function. * * @param s denotes the function name of the {@link Script}. * @param objects contains data of function which is used to evaluate the function. * * @return data after the evaluated. */ @Override public Object eval(String s, Object[] objects) { return null; } }
true
f21f5077cfa87406932c695ed16fbc33cf7b1ceb
Java
jignesh-dhua/soap-connector-camel-cxf
/src/main/java/nl/kvk/schemas/schemas/hrip/catalogus/_2015/_02/BijzondereRechtstoestandType.java
UTF-8
5,922
1.820313
2
[]
no_license
package nl.kvk.schemas.schemas.hrip.catalogus._2015._02; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for BijzondereRechtstoestandType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="BijzondereRechtstoestandType"> * &lt;complexContent> * &lt;extension base="{http://schemas.kvk.nl/schemas/hrip/catalogus/2015/02}BasisType"> * &lt;sequence> * &lt;element name="soort" type="{http://schemas.kvk.nl/schemas/hrip/catalogus/2015/02}EnumeratieType" minOccurs="0"/> * &lt;choice minOccurs="0"> * &lt;element name="uitspraakAanvang" type="{http://schemas.kvk.nl/schemas/hrip/catalogus/2015/02}RechterlijkeUitspraakType"/> * &lt;element name="uitspraakEinde" type="{http://schemas.kvk.nl/schemas/hrip/catalogus/2015/02}RechterlijkeUitspraakType"/> * &lt;/choice> * &lt;element name="redenEindeInsolventie" type="{http://schemas.kvk.nl/schemas/hrip/catalogus/2015/02}EnumeratieType" minOccurs="0"/> * &lt;element name="status" type="{http://schemas.kvk.nl/schemas/hrip/catalogus/2015/02}EnumeratieType" minOccurs="0"/> * &lt;element name="duur" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="isVerlengd" type="{http://schemas.kvk.nl/schemas/hrip/catalogus/2015/02}EnumeratieType" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "BijzondereRechtstoestandType", propOrder = { "soort", "uitspraakAanvang", "uitspraakEinde", "redenEindeInsolventie", "status", "duur", "isVerlengd" }) public class BijzondereRechtstoestandType extends BasisType { protected EnumeratieType soort; protected RechterlijkeUitspraakType uitspraakAanvang; protected RechterlijkeUitspraakType uitspraakEinde; protected EnumeratieType redenEindeInsolventie; protected EnumeratieType status; protected String duur; protected EnumeratieType isVerlengd; /** * Gets the value of the soort property. * * @return * possible object is * {@link EnumeratieType } * */ public EnumeratieType getSoort() { return soort; } /** * Sets the value of the soort property. * * @param value * allowed object is * {@link EnumeratieType } * */ public void setSoort(EnumeratieType value) { this.soort = value; } /** * Gets the value of the uitspraakAanvang property. * * @return * possible object is * {@link RechterlijkeUitspraakType } * */ public RechterlijkeUitspraakType getUitspraakAanvang() { return uitspraakAanvang; } /** * Sets the value of the uitspraakAanvang property. * * @param value * allowed object is * {@link RechterlijkeUitspraakType } * */ public void setUitspraakAanvang(RechterlijkeUitspraakType value) { this.uitspraakAanvang = value; } /** * Gets the value of the uitspraakEinde property. * * @return * possible object is * {@link RechterlijkeUitspraakType } * */ public RechterlijkeUitspraakType getUitspraakEinde() { return uitspraakEinde; } /** * Sets the value of the uitspraakEinde property. * * @param value * allowed object is * {@link RechterlijkeUitspraakType } * */ public void setUitspraakEinde(RechterlijkeUitspraakType value) { this.uitspraakEinde = value; } /** * Gets the value of the redenEindeInsolventie property. * * @return * possible object is * {@link EnumeratieType } * */ public EnumeratieType getRedenEindeInsolventie() { return redenEindeInsolventie; } /** * Sets the value of the redenEindeInsolventie property. * * @param value * allowed object is * {@link EnumeratieType } * */ public void setRedenEindeInsolventie(EnumeratieType value) { this.redenEindeInsolventie = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link EnumeratieType } * */ public EnumeratieType getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link EnumeratieType } * */ public void setStatus(EnumeratieType value) { this.status = value; } /** * Gets the value of the duur property. * * @return * possible object is * {@link String } * */ public String getDuur() { return duur; } /** * Sets the value of the duur property. * * @param value * allowed object is * {@link String } * */ public void setDuur(String value) { this.duur = value; } /** * Gets the value of the isVerlengd property. * * @return * possible object is * {@link EnumeratieType } * */ public EnumeratieType getIsVerlengd() { return isVerlengd; } /** * Sets the value of the isVerlengd property. * * @param value * allowed object is * {@link EnumeratieType } * */ public void setIsVerlengd(EnumeratieType value) { this.isVerlengd = value; } }
true
2e4abba3bef6d41a7cb4b634fff52cd25ec77e39
Java
SaibanAhmad/androidBloodBank
/app/src/main/java/com/saiban/bahawalpurblooddonors/loginorsignup.java
UTF-8
1,669
1.9375
2
[]
no_license
package com.saiban.bahawalpurblooddonors; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import com.google.firebase.auth.FirebaseAuth; public class loginorsignup extends AppCompatActivity { FirebaseAuth auth; Button login, singu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_loginorsignup); Init(); auth = FirebaseAuth.getInstance(); if (auth.getCurrentUser() != null) { startActivity(new Intent(getApplicationContext(), mainContent.class)); finish(); } login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getApplicationContext(), UserLogin.class)); finish(); } }); singu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getApplicationContext(), UserRegister.class)); finish(); } }); } void Init() { login = (Button) findViewById(R.id.btn_login__); singu = (Button) findViewById(R.id.btn_signup__); } }
true
48ee44c8c6f0540d815b24e61f76146e5151003e
Java
rafayameen/HackerRank
/1.GameEngine/src/renderEngine/Loader.java
UTF-8
3,812
2.78125
3
[]
no_license
package renderEngine; import java.util.List; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureLoader; import models.RawModel; public class Loader { //lists to store created vaos and vbos private List<Integer> vaos = new ArrayList<Integer>(); private List<Integer> vbos = new ArrayList<Integer>(); private List<Integer> textures = new ArrayList<Integer>(); public RawModel loadToVAO(float[] positions,float[] textureCoords,float[] normals, int[] indices) { int vaoID = createVAO(); storeDataInAttribList(0, 3, positions); storeDataInAttribList(1, 2, textureCoords); storeDataInAttribList(2, 3, normals); bindIndicesBuffer(indices); unbindVAO(); //every vertex has three axis so divide the length by 3 to get vertex return new RawModel(vaoID, indices.length); } public int loadTexture(String fileName) { Texture texture = null; try { texture = TextureLoader.getTexture("PNG", new FileInputStream("res/" + fileName + ".png")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int textureID = texture.getTextureID(); textures.add(textureID); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); return textureID; } public int createVAO() { int vaoID = GL30.glGenVertexArrays(); vaos.add(vaoID); GL30.glBindVertexArray(vaoID); return vaoID; } //method to create vbo and store in vao at specific index public void storeDataInAttribList(int vaoIndex,int coordinatesSize, float[] data) { //create vbo int vboID = GL15.glGenBuffers(); vbos.add(vboID); //bind vbo GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID); //create buffer FloatBuffer buffer = storeDataInFloatBuffer(data); //get data in vbo GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW); //store vbo in vao GL20.glVertexAttribPointer(vaoIndex, coordinatesSize, GL11.GL_FLOAT, false, 0, 0); //unbind vbo after use GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); } public void bindIndicesBuffer(int[] indices) { //indices belong to model so store in vbo int vboID = GL15.glGenBuffers(); vbos.add(vboID); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboID); IntBuffer buffer = storeDataInIntBuffer(indices); GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW); } public void cleanUp() { for(int vao: vaos) { GL30.glDeleteVertexArrays(vao); } for(int vbo: vbos) { GL15.glDeleteBuffers(vbo); } for(int texture: textures) { GL11.glDeleteTextures(texture); } } public void unbindVAO() { GL30.glBindVertexArray(0); } public IntBuffer storeDataInIntBuffer(int[] data) { IntBuffer buffer = BufferUtils.createIntBuffer(data.length); buffer.put(data); buffer.flip(); return buffer; } public FloatBuffer storeDataInFloatBuffer(float[] data) { FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length); buffer.put(data); buffer.flip(); return buffer; } }
true
304c03c54b6222b33d2a88b7c9b699072d8e15f5
Java
rcl4444/vsc_debug_error
/scheduler/src/main/java/com/sample/scheduler/StatsSchedulerApp.java
UTF-8
462
1.75
2
[]
no_license
package com.sample.scheduler; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.sample.scheduler.dao") public class StatsSchedulerApp { public static void main(String[] args) { SpringApplication.run(StatsSchedulerApp.class, args); System.out.println("scheduler started"); } }
true
62fcb2b8d7b1c60fe4ad6a4b2a493eaf547e8d82
Java
abcshmedu/shareit-summer-2017-fetomado
/src/test/java/edu/hm/shareit/resources/MediaResourceTest.java
UTF-8
8,109
2.328125
2
[]
no_license
package edu.hm.shareit.resources; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import edu.hm.shareit.GuiceInjectionTestFeature; import edu.hm.shareit.models.Book; import edu.hm.shareit.models.Disc; import edu.hm.shareit.models.User; import edu.hm.shareit.services.MediaService; import edu.hm.shareit.services.ServiceResult; import edu.hm.shareit.services.UserService; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Test; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; public class MediaResourceTest extends JerseyTest { private MediaService mediaServiceMock; private UserService userServiceMock; private Book[] books = { new Book("Die Kaenguru-Chroniken", "Marc-Uwe Kling", "978-3-548-37623-3"), new Book("what if?", "Randall Munroe", "978-3-8135-0625-5"), }; private Disc[] discs = { new Disc("Rennschwein Rudi Ruessel", "123456789", "Peter Timm", 0), new Disc("Deadpool", "456789123", "Tim Miller", 16), new Disc("Source Code", "101001011", "Duncan Jones", 12), }; @Override protected Application configure() { mediaServiceMock = GuiceInjectionTestFeature.getInjectorInstance().getInstance(MediaService.class); userServiceMock = GuiceInjectionTestFeature.getInjectorInstance().getInstance(UserService.class); return new ResourceConfig().register(MediaResource.class) .register(CheckTokenRequestFilter.class) .register(CustomExceptionMapper.class) .register(GuiceInjectionTestFeature.class); } @Test public void testGetBooks() { when(mediaServiceMock.getBooks()).thenReturn(new Book[0]); Response resp = target("media/books").request().get(); assertEquals(200, resp.getStatus()); assertEquals("[]", resp.readEntity(String.class)); when(mediaServiceMock.getBooks()).thenReturn(books); resp = target("media/books").request().get(); assertEquals(200, resp.getStatus()); assertEquals("[{\"title\":\"Die Kaenguru-Chroniken\",\"author\":\"Marc-Uwe Kling\",\"isbn\":\"978-3-548-37623-3\"}," + "{\"title\":\"what if?\",\"author\":\"Randall Munroe\",\"isbn\":\"978-3-8135-0625-5\"}]", resp.readEntity(String.class)); } @Test public void testGetDiscs() { when(mediaServiceMock.getDiscs()).thenReturn(new Disc[0]); Response resp = target("media/discs").request().get(); assertEquals(200, resp.getStatus()); assertEquals("[]", resp.readEntity(String.class)); when(mediaServiceMock.getDiscs()).thenReturn(discs); resp = target("media/discs").request().get(); assertEquals(200, resp.getStatus()); assertEquals("[{\"title\":\"Rennschwein Rudi Ruessel\",\"barcode\":\"123456789\",\"director\":\"Peter Timm\",\"fsk\":0}," + "{\"title\":\"Deadpool\",\"barcode\":\"456789123\",\"director\":\"Tim Miller\",\"fsk\":16}," + "{\"title\":\"Source Code\",\"barcode\":\"101001011\",\"director\":\"Duncan Jones\",\"fsk\":12}]", resp.readEntity(String.class)); } @Test public void testCreateBook() { when(mediaServiceMock.addBook(any(Book.class))).thenReturn(ServiceResult.OK); when(userServiceMock.checkToken("abc")).thenReturn(new User("TestU", "Test")); ObjectNode root = new ObjectMapper().createObjectNode(); root.put("title", "testtitel"); root.put("author", "testautor"); root.put("isbn", "978-3-548-37623-3 "); root.put("token", "abc"); Entity<ObjectNode> json = Entity.entity(root, MediaType.APPLICATION_JSON); Response resp = target("media/books").request().post(json); assertEquals(200, resp.getStatus()); assertEquals("{\"code\":200,\"detail\":\"Erfolgreich.\"}", resp.readEntity(String.class)); } @Test public void testCreateBookInvalidJSON() { when(mediaServiceMock.addBook(any(Book.class))).thenReturn(ServiceResult.OK); when(userServiceMock.checkToken("abc")).thenReturn(new User("TestU", "Test")); ObjectNode root = new ObjectMapper().createObjectNode(); // Names are not correct root.put("titel", "testtitel"); root.put("autor", "testautor"); root.put("isbn", "978-3-548-37623-3 "); root.put("token", "abc"); Entity<ObjectNode> json = Entity.entity(root, MediaType.APPLICATION_JSON); Response resp = target("media/books").request().post(json); assertEquals(400, resp.getStatus()); assertEquals("{\"code\":400,\"detail\":\"Fehlerhafte Eingabe.\"}", resp.readEntity(String.class)); } @Test public void testCreateDisc() { when(mediaServiceMock.addDisc(any(Disc.class))).thenReturn(ServiceResult.OK); when(userServiceMock.checkToken("abc")).thenReturn(new User("TestU", "Test")); ObjectNode root = new ObjectMapper().createObjectNode(); root.put("title", "testTitel"); root.put("barcode", "123456789"); root.put("director", "testDirector"); root.put("fsk", "12"); root.put("token", "abc"); Entity<ObjectNode> json = Entity.entity(root, MediaType.APPLICATION_JSON); Response resp = target("media/discs").request().post(json); assertEquals(200, resp.getStatus()); assertEquals("{\"code\":200,\"detail\":\"Erfolgreich.\"}", resp.readEntity(String.class)); } @Test public void testGetBook() { when(mediaServiceMock.getBook("978-3-8135-0625-5")).thenReturn(books[1]); Response resp = target("media/books/978-3-8135-0625-5").request().get(); assertEquals(200, resp.getStatus()); assertEquals("{\"title\":\"what if?\",\"author\":\"Randall Munroe\",\"isbn\":\"978-3-8135-0625-5\"}", resp.readEntity(String.class)); } @Test public void testGetDisc() { when(mediaServiceMock.getDisc("456789123")).thenReturn(discs[1]); Response resp = target("media/discs/456789123").request().get(); assertEquals(200, resp.getStatus()); assertEquals("{\"title\":\"Deadpool\",\"barcode\":\"456789123\",\"director\":\"Tim Miller\",\"fsk\":16}", resp.readEntity(String.class)); } @Test public void testUpdateBook() { when(mediaServiceMock.updateBook(eq("978-3-8135-0625-5"), any(Book.class))).thenReturn(ServiceResult.OK); when(userServiceMock.checkToken("abc")).thenReturn(new User("TestU", "Test")); ObjectNode root = new ObjectMapper().createObjectNode(); root.put("title", "testtitel"); root.put("author", "testautor"); root.put("isbn", "978-3-548-37623-3 "); root.put("token", "abc"); Entity<ObjectNode> json = Entity.entity(root, MediaType.APPLICATION_JSON); Response resp = target("media/books/978-3-8135-0625-5").request().put(json); assertEquals(200, resp.getStatus()); assertEquals("{\"code\":200,\"detail\":\"Erfolgreich.\"}", resp.readEntity(String.class)); } @Test public void testUpdateDisc() { when(mediaServiceMock.updateDisc(eq("456789123"), any(Disc.class))).thenReturn(ServiceResult.OK); when(userServiceMock.checkToken("abc")).thenReturn(new User("TestU", "Test")); ObjectNode root = new ObjectMapper().createObjectNode(); root.put("title", "testTitel"); root.put("barcode", "123456789"); root.put("director", "testDirector"); root.put("fsk", "12"); root.put("token", "abc"); Entity<ObjectNode> json = Entity.entity(root, MediaType.APPLICATION_JSON); Response resp = target("media/discs/456789123").request().put(json); assertEquals(200, resp.getStatus()); assertEquals("{\"code\":200,\"detail\":\"Erfolgreich.\"}", resp.readEntity(String.class)); } }
true
d059f9aad9f9177d74699e40daac2f819e4ca2e5
Java
MichelleSG2306/P8-2017
/P8-master/app/src/main/java/com/example/rasmus/p8_master/BankCard.java
UTF-8
4,507
2.265625
2
[]
no_license
package com.example.rasmus.p8_master; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; public class BankCard extends Card { public String bCCardNumber; public String bCAccountNumber; public String bCRegNumber; public String bCExpirationDate; public String bCSecurityNumber; int bankCardImageF; int bankCardImageB; public int bCAmount; SQLiteDatabase db; public BankCard(){ } public BankCard(String cardID, String type, int frontPhoto, int backPhoto, String bCCardNumber, String bCAccountNumber, String bCRegNumber, String bCExpirationDate, String bCSecurityNumber, int bCAmount) { super(cardID, type, frontPhoto, backPhoto); this.bCCardNumber = bCCardNumber; this.bCAccountNumber = bCAccountNumber; this.bCRegNumber = bCRegNumber; this.bCExpirationDate = bCExpirationDate; this.bCSecurityNumber = bCSecurityNumber; this.bCAmount = bCAmount; this.bankCardImageF = frontPhoto; this.bankCardImageB = backPhoto; } //Swipe Function SwipeAdapter swipeAdapter; ViewPager viewPager; //Swipe Function @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bank_card); //Swipe Function viewPager=(ViewPager)findViewById(R.id.view_pager); swipeAdapter=new SwipeAdapter(this); swipeAdapter.setImagesValue(new int[]{R.drawable.bankcard_f, R.drawable.bankcard_b}); viewPager.setAdapter(swipeAdapter); //dots TabLayout tabLayout = (TabLayout)findViewById(R.id.tab_layout); tabLayout.setupWithViewPager(viewPager, true); //dots //Swipe Function DBHelper dbHelper = new DBHelper(BankCard.this); db = dbHelper.getReadableDatabase(); Cursor name = db.rawQuery("Select last_name, first_name from users",null); name.moveToFirst(); String firstName = name.getString(1); String lastName = name.getString(0); String fullName = firstName + " " + lastName; TextView text = (TextView) findViewById(R.id.fullName); text.append(" " + fullName); Cursor cardNumber = db.rawQuery("Select card_no from bank_card", null); cardNumber.moveToFirst(); String cardNumber2 = cardNumber.getString(0); TextView textCardNumber = (TextView) findViewById(R.id.cardNumber); textCardNumber.append(" " + cardNumber2); Cursor accountNumber = db.rawQuery("Select account_no from bank_card", null); accountNumber.moveToFirst(); String amount2 = accountNumber.getString(0); TextView textAmount = (TextView) findViewById(R.id.accountNumber); textAmount.append(" " + amount2); Cursor regNumber = db.rawQuery("Select reg_no from bank_card", null); regNumber.moveToFirst(); String regNumber2 = regNumber.getString(0); TextView textRegNumber = (TextView) findViewById(R.id.regNumber); textRegNumber.append(" " + regNumber2); Cursor expDate = db.rawQuery("Select expiration_date from bank_card", null); expDate.moveToFirst(); String expDate2 = expDate.getString(0); TextView textExpDate = (TextView) findViewById(R.id.expDate); textExpDate.append(" " + expDate2); Cursor secNumber = db.rawQuery("Select security_no from bank_card", null); secNumber.moveToFirst(); String secNumber2 = secNumber.getString(0); TextView textSecNumber = (TextView) findViewById(R.id.secNumber); textSecNumber.append(" " + secNumber2); } public String getbCCardNumber() { return bCCardNumber; } public String getbCAccountNumber() { return bCAccountNumber; } public String getbCRegNumber() { return bCRegNumber; } public String getbCExpirationDate() { return bCExpirationDate; } public String getbCSecurityNumber() { return bCSecurityNumber; } public int getbCAmount() { return bCAmount; } public int getBankCardImageF() { return bankCardImageF; } public int getBankCardImageB() { return bankCardImageB; } }
true
b9d8abd07199a822742a35a110bba6ad8285bdd6
Java
daviarimateia93/Foound
/src/main/java/net/foound/exception/handler/HttpExceptionHandler.java
UTF-8
844
2
2
[]
no_license
package net.foound.exception.handler; import net.foound.exception.HttpException; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice public class HttpExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(value = { HttpException.class }) protected ResponseEntity<Object> handle(HttpException httpException, WebRequest webRequest) { return handleExceptionInternal(httpException, httpException.getMessage(), new HttpHeaders(), httpException.getHttpStatus(), webRequest); } }
true
061b5390678b813313c0f3a71dd5eda9d36f3042
Java
mirzabecic/SvaPredavanja
/Sedmica11Predavanje3/src/bitcamp/ba/Main.java
UTF-8
1,094
2.5625
3
[]
no_license
package bitcamp.ba; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.OutputStreamWriter; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { User u = new User("Mirza", 21, true); File file = new File("./Folder/fileKojiJePrazan"); if (file.length() == 0) { FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw); bw.write(u.toString()); bw.close(); } else { InputStream input = new BufferedInputStream(new FileInputStream( file)); byte[] buffer = new byte[8192]; try { for (int length = 0; (length = input.read(buffer)) != -1;) { System.out.write(buffer, 0, length); } } finally { input.close(); } } } }
true
234e73ef59adf9c31bb3ea04ed5fc52a4c7db560
Java
khalerev/rev2week
/Lecture/210628-JavaPrimer/java-environment/day4/src/strings/Pooling.java
UTF-8
656
4.0625
4
[]
no_license
package strings; public class Pooling { public static void main(String[] args) { String s1 = "Hello"; String s2 = new String("Hello"); String s3 = "Hello"; System.out.println(s1); System.out.println(s2); /* * '==' compares the memory address of objects in the * heap and will return true when two reference variables * are pointing to the exact same location in memory * * Because String literals are pooled, anytime you reference * a String literal, they will point to the same String * literal reference in the String pool */ System.out.println(s1 == s2); // false System.out.println(s1 == s3); // true } }
true
08b81d2995b7dd0f62744f061ecc4b3723032dfa
Java
AlaaShehab/Peer-to-peer-blockchain
/src/PeerNode.java
UTF-8
2,554
2.765625
3
[]
no_license
import java.util.ArrayList; import java.util.Collections; import java.util.Hashtable; import java.util.List; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class PeerNode { int port; String hostName; int ID; clientTCP client1; serverTCP server1; List<String> txList; List<String> blockList; //TODO first load it from file, and last save it to the file static String portsFile = "ports.txt"; static Hashtable<Integer, Integer> minersPorts; static Hashtable<Integer, Integer> clientsPorts; static int messagesCount=0; static public List<Integer> messagesCountList; public PeerNode(int port,String hostName,int ID,String type) throws InterruptedException, BrokenBarrierException { this.hostName=hostName; this.port =port; this.ID = ID; messagesCountList = new ArrayList<Integer>(); server1 = new serverTCP(); client1 = new clientTCP(); txList = Collections.synchronizedList(new ArrayList<String>()); blockList = Collections.synchronizedList(new ArrayList<String>()); if(type.equals("miner")) { if(minersPorts==null) { minersPorts = new Hashtable<Integer, Integer>(); } minersPorts.put(ID, port); }else if(type.equals("client")) { if(clientsPorts==null) { clientsPorts = new Hashtable<Integer, Integer>(); } clientsPorts.put(ID, port); } final CyclicBarrier gate = new CyclicBarrier(2); Thread t1 = new Thread(){ public void run(){ try { gate.await(); server1.start(port,txList,blockList); } catch (Exception e) { e.printStackTrace(); } }}; t1.start(); gate.await(); } /*public void broadcast(Hashtable<Integer, Integer> toPortsTable, String txFileName) throws IOException{ Enumeration<Integer> e = toPortsTable.elements(); File file=new File(txFileName); //creates a new file instance FileReader fr=new FileReader(file); //reads the file BufferedReader br=new BufferedReader(fr); //creates a buffering character input stream //constructs a string buffer with no characters String line; while((line=br.readLine())!=null) { while (e.hasMoreElements()) { client1.startConnection("127.0.0.1", e.nextElement()); String msg1 = client1.sendMessage(line); client1.stopConnection(); } e = toPortsTable.elements(); } fr.close(); }*/ }
true
63458d8c70d5aaf1d58ff7d9740d360ed19dff76
Java
JamMarHer/projecteuler
/src/projecteuler/p022.java
UTF-8
821
2.953125
3
[]
no_license
package projecteuler; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class p022 { public static void main(String[] args){ ArrayList<String> names = new ArrayList<String>(); try (Scanner scanner = new Scanner(new File("rsrc/p022.txt"))) { String[] spl = scanner.nextLine().replaceAll("\"", "").split(","); names.addAll(Arrays.asList(spl)); } catch (IOException e) { e.printStackTrace(); } Collections.sort(names); long t = 0; for(int i = 0; i < names.size(); i++){ t+= ns(names.get(i)) * (i+1); } System.out.println(t); } public static long ns(String s){ long a = 0; for(int i = 0; i < s.length(); i++){ a += s.charAt(i) - 64; } return a; } }
true
24eb095f9351dc5dceffd0c2104da24e54f822f0
Java
Vinu-Prabhakaran/MyWork
/CallHolidayWebServiceSOAP/src/main/java/com/holidaywebservice/holidayservice_v2/BankHoliday.java
UTF-8
1,241
2.390625
2
[]
no_license
package com.holidaywebservice.holidayservice_v2; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for BankHoliday. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="BankHoliday"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Recognized"/> * &lt;enumeration value="NotRecognized"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "BankHoliday") @XmlEnum public enum BankHoliday { @XmlEnumValue("Recognized") RECOGNIZED("Recognized"), @XmlEnumValue("NotRecognized") NOT_RECOGNIZED("NotRecognized"); private final String value; BankHoliday(String v) { value = v; } public String value() { return value; } public static BankHoliday fromValue(String v) { for (BankHoliday c: BankHoliday.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
true
d7c6eb47b1d434ab5cb1071b971fb2180b8f5e34
Java
zoom59rus/JavaRushTasks
/2.JavaCore/src/com/javarush/task/task19/task1915/Solution.java
UTF-8
1,180
3.296875
3
[]
no_license
package com.javarush.task.task19.task1915; /* Дублируем текст */ import java.io.*; public class Solution { public static TestString testString = new TestString(); public static void main(String[] args) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); PrintStream consoleOut = System.out; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(byteArrayOutputStream); System.setOut(printStream); testString.printSomething(); String string = byteArrayOutputStream.toString(); System.setOut(consoleOut); try { FileOutputStream fis = new FileOutputStream(new File(bufferedReader.readLine())); fis.write(string.getBytes()); System.out.println(string); bufferedReader.close(); fis.close(); }catch (IOException e){ e.printStackTrace(); } } public static class TestString { public void printSomething() { System.out.println("it's a text for testing"); } } }
true
99cdee4f3b73fc008b0f73463494a2bd99efcfd4
Java
Underlion10/MasterMind
/MasterMind/src/vista/Lienzo.java
UTF-8
1,693
2.609375
3
[]
no_license
package vista; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JPanel; import modelo.CirculoGrande; import modelo.Stuff; public class Lienzo extends JPanel { /** * */ private static final long serialVersionUID = -257640443263265082L; //private ArrayList<CirculoGrande> circulosGrandes = new ArrayList<CirculoGrande>(); private Color color = new Color(255, 255, 255); public Lienzo() { setBackground(new Color(164, 223, 169)); setBorder(BorderFactory.createLineBorder(new Color(84, 82, 158))); } public Dimension getPreferredSize() { return new Dimension(400, 500); } public void paintComponent(Graphics g) { super.paintComponent(g); int x = 25; int y = 25; int acu = 1; for (int i = 0; i < 24; i++) { if (acu <= 4) { CirculoGrande cg = new CirculoGrande(color, x, y); Stuff.circulosGrandes.add(cg); x += 100; acu++; continue; } x = 25; y += 100; acu = 1; } if (!Stuff.reiniciar) { for (int i = 0; i < 20; i++) { if (i == Stuff.pos - 1) { Stuff.circulosGrandes.get(i).setColor(Stuff.colorPintura); Stuff.circulosGrandes.get(i).dibujarCirc(g); continue; } Stuff.circulosGrandes.get(i).dibujarCirc(g); } } else { for(int i = 0; i < 20; i++) { Stuff.circulosGrandes.get(i).setColor(new Color(255,255,255)); Stuff.circulosGrandes.get(i).dibujarCirc(g); Stuff.reiniciar = false; } } } public ArrayList<CirculoGrande> getCirculoGrande() { return Stuff.circulosGrandes; } }
true
525f120843c075e561ac5709559d74593850c74d
Java
AbdielNie/AP-Computer-Science-A
/APCS work/Control Structures/Classwork/Loop_Question1.java
UTF-8
1,509
4.1875
4
[]
no_license
import java.util.Scanner; /** * Name: AbdielNie * decription: Write a program that plays an incredibly stupid * number-guessing game. The user will get one try to guess the * secret number. Tell them if they got it right or wrong, and * if they got it wrong, display what the secret number was. * You must store the secret number in a variable, and use that * variable throughout. The secret number itself must not * appear in the program at all, except in the one line * where you store it into a variable. * b) Modify your number-guessing game to actually * pick a random number from 1 to 10 and have the user try * to guess that. Tell them if they get it right or wrong, * and if they get it wrong, show them what the random number was. * They will still only get one try. * c) Modify the game so that they can guess until they get it right. * That means it will keep looping as long as the guess is different * from the secret number. * Use a while loop. */ public class Loop_Question1 { public static void question1(int num) { Scanner keyboard = new Scanner(System.in); System.out.println("WELCOME TO THE BANK OF MITCHELL."); System.out.print("ENTER YOUR PIN: "); int i = keyboard.nextInt(); while (i != num) { System.out.println("Your PIN was wrong"); System.out.print("ENTER YOUR PIN: "); i = keyboard.nextInt(); } System.out.println("Your PIN is correct!"); } }
true
01ba5c9c4731bd9d7ed9e417c25b45daa213ac41
Java
huyphatvu/Data-Structure-Course-Project
/HW3/Tester.java
UTF-8
846
3.15625
3
[]
no_license
/** * A Class to run the runtime analysis * of Cuckoo Hashing and AVL Tree * * @author Huy Vu * @version October 30 2017 */ public class Tester { public static void main(String[] args) { // System.out.println("Testing Cuckoo Hash Function:"); // CuckooHashTester.performCuckooTest(); System.out.println("\nTesting AVL Tree:"); TreeTester.performAVLTreeTest(); // CuckooHashTableVer2<Integer> c = new CuckooHashTableVer2<>(3); // c.insert(3); // c.printHashTable(); // c.insert(13); // c.printHashTable(); // c.insert(15); // c.printHashTable(); // c.insert(14); // c.printHashTable(); // c.insert(0); // c.remove(1000); // c.printHashTable(); // c.remove(3); // System.out.println(c.contains(3)); } }
true
34e3593ebe9474a93bcea2612961d872bad302d6
Java
gssinghgautam/limkokwingapp
/app/src/main/java/com/android/limkokwingapp/ui/images/ImageActivity.java
UTF-8
4,860
2.015625
2
[]
no_license
package com.android.limkokwingapp.ui.images; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ProgressBar; import com.android.limkokwingapp.R; import com.android.limkokwingapp.data.remote.model.Photo; import com.android.limkokwingapp.ui.images.adapter.ImageAdapter; import com.android.limkokwingapp.ui.images.presenter.ImagePresenter; import com.android.limkokwingapp.ui.images.view.ImageContract; import com.android.limkokwingapp.utility.ApiConstant; import com.android.limkokwingapp.utility.EndlessRecyclerOnScrollListener; import com.android.limkokwingapp.utility.NetworkUtils; import com.android.limkokwingapp.utility.Utils; import com.squareup.picasso.Picasso; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import dagger.android.AndroidInjection; public class ImageActivity extends AppCompatActivity implements ImageContract.View, ImageAdapter.OnPhotoClickListener { @Inject ImagePresenter mImagePresenter; @Inject Picasso mPicasso; @BindView(R.id.toolbar) Toolbar mToolBar; @BindView(R.id.gallery_recycler_view) RecyclerView mGalleryRecyclerView; @BindView(R.id.progress) ProgressBar mProgressBar; @BindView(R.id.empty_view) LinearLayout mEmptyView; @BindView(R.id.btn_retry) Button btnRetry; @BindView(R.id.main_view) CoordinatorLayout mainView; private ImageAdapter mImageAdapter; @Override protected void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_image); ButterKnife.bind(this); setSupportActionBar(mToolBar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } initView(); btnRetry.setOnClickListener(view -> { if (NetworkUtils.isConnected(ImageActivity.this)) { mImagePresenter.onRetry(); } else { showEmptyView(); Utils.showSnackShort(mainView, getString(R.string.internet_error)); } }); } private void initView() { mImageAdapter = new ImageAdapter(mPicasso); mGalleryRecyclerView.setAdapter(mImageAdapter); GridLayoutManager layoutManager = new GridLayoutManager(this, 2, LinearLayoutManager.VERTICAL, false); mGalleryRecyclerView.setLayoutManager(layoutManager); mGalleryRecyclerView.setHasFixedSize(true); mGalleryRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) { @Override public void onLoadMore() { if (NetworkUtils.isConnected(ImageActivity.this)) { mImagePresenter.loadNextPage(); } else { showEmptyView(); Utils.showSnackShort(mainView, getString(R.string.internet_error)); } } }); mImageAdapter.setOnPhotoClickListener(this); } @Override protected void onStart() { super.onStart(); mImagePresenter.start(); } @Override protected void onStop() { super.onStop(); mImagePresenter.stop(); } @Override public void showProgress() { mProgressBar.setVisibility(View.VISIBLE); } @Override public void hideProgress() { mProgressBar.setVisibility(View.GONE); } @Override public void showEmptyView() { if (mImageAdapter.getItemCount() == 0) { mEmptyView.setVisibility(View.VISIBLE); } } @Override public void showImages(List<Photo> photoList) { mImageAdapter.setData(photoList); } @Override public void hideEmptyView() { mEmptyView.setVisibility(View.GONE); } @Override public void onPhotoClick(Photo photo) { Intent intent = new Intent(ImageActivity.this, FullImageActivity.class); intent.putExtra(ApiConstant.PHOTO_EXTRA, photo); startActivity(intent); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return super.onOptionsItemSelected(item); } }
true
d3572c6b2fbcb88cdd1e985a83fa19895588d5c1
Java
xivanglei/view
/17 网络请求/src/main/java/xl/gcs/com/retrofit/IpService.java
UTF-8
825
2.515625
3
[ "Apache-2.0" ]
permissive
package xl.gcs.com.retrofit; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import xl.gcs.com.retrofit.model.IpModel; public interface IpService { //加入请求头,没有这行就经常会失败,这里有两个文件头,用{}包起来,中间用都好隔开,如果只有一个文件头的话,就不用大括号,也可以用动态方式添加,下面介绍 @Headers({ "Accept-Encoding: application/json", "User-Agent: MoonRetrofit" }) //表示get请求括号里是地址 @GET("getIpInfo.php?ip=59.108.54.37") //定义了getIpMsg()方法,返回Call<IpModel> Call<IpModel> getIpMsg(); //动态方式添加消息报头 Call<IpModel> getIpMsg(@Header("Location") String location); }
true
3cf8fbae974165b869660a24ede303bb045dc7b6
Java
P79N6A/icse_20_user_study
/methods/Method_1013324.java
UTF-8
158
1.75
2
[]
no_license
public FPSet init(int numThreads,String metadir,String fname){ this.metadir=metadir; this.filename=metadir + FileUtil.separator + fname; return this; }
true
2290c747b844c1ae4f757ddde5c3df62b8e620fc
Java
aaron0211/PSP_ExamenWebinar
/src/main/java/com/aaron/examen/util/AlertUtils.java
UTF-8
526
2.625
3
[]
no_license
package com.aaron.examen.util; import javafx.scene.control.Alert; public class AlertUtils { public static void mostrarAlerta(String mensaje){ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error"); alert.setContentText(mensaje); alert.show(); } public static void mostrarFinal(String mensaje){ Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Finalizado"); alert.setContentText(mensaje); alert.show(); } }
true
73b93b31e3a8b1e13328e2fff73b0e6952e2231b
Java
Nagarjune1/fap-diplom
/application/cellular-fuzzy-automata/src/main/java/cz/upol/fapapp/cfa/impls/images/SimpleBlurFilterAutomaton.java
UTF-8
678
3.078125
3
[]
no_license
package cz.upol.fapapp.cfa.impls.images; /** * Convolutional automata performing simple blur. Uses following core: * * <pre> * 1 2 1 * 2 4 2 * 1 2 1 * </pre> * * @author martin * */ public class SimpleBlurFilterAutomaton extends ConvolutionalCFA { public SimpleBlurFilterAutomaton(int size) { super(size, createCore()); } private static ConvolutionalCore createCore() { ConvolutionalCore core = new ConvolutionalCore(0.0); core.set(0, 0, 1.0); core.set(1, 0, 2.0); core.set(2, 0, 1.0); core.set(0, 1, 2.0); core.set(1, 1, 4.0); core.set(2, 1, 2.0); core.set(0, 2, 1.0); core.set(1, 2, 2.0); core.set(2, 2, 1.0); return core; } }
true
017887112b780e6ceae06ff3bbf90e85b163f600
Java
jazzman2/buildingreporter
/buildingreporter-ma/src/main/java/sk/jazzman/brmi/application/ServerConnectionThread.java
UTF-8
2,233
2.34375
2
[]
no_license
/** * */ package sk.jazzman.brmi.application; import java.lang.reflect.Constructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sk.jazzman.brmi.common.ParameterBuilder; import sk.jazzman.brmi.server.ws.ServerActionHandlerStateInf; import sk.jazzman.brmi.server.ws.WSServerActionHandler; import sk.jazzman.brmi.server.ws.action.Ping; /** * @author jkovalci * */ public class ServerConnectionThread extends Thread { private static final Logger log = LoggerFactory.getLogger(ServerConnectionThread.class); private final Sandbox sandbox; /** * {@link Constructor} * * @param a * @param sandbox * */ public ServerConnectionThread(Sandbox sandbox) { this.sandbox = sandbox; } /** * Getter logger * * @return */ private static Logger getLogger() { return log; } /** * Getter sandbox * * @return */ private synchronized SandboxInf getSandbox() { return sandbox; } @Override public void run() { super.run(); while (true) { if (getSandbox().isInitialized()) { check(); } try { sleep(100000l); } catch (InterruptedException e) { getLogger().debug(" sleep error", e); return; } } } /** * Ping server */ protected void check() { WSServerActionHandler sh = (WSServerActionHandler) getSandbox().getServerActionHandler(); try { if (!sh.isInitialized()) { getLogger().debug("init server action handler..."); sh.init(getSandbox()); getLogger().debug("init server action handler ... done "); } } catch (Exception e) { getLogger().error("Init server action handler failed", e); sh.getState().setInitializationState(ServerActionHandlerStateInf.NOT_INITIALIZED); } try { if (!sh.isConnected()) { sh.perform(Ping.getName(), new ParameterBuilder().build()); } // getLogger().debug(" try load data from db"); // // appl.getJpaActionHandler().perform("GET-mlog", new // // HashMap<String, Object>()); // getSandbox().getJPAActionHandler().perform("GET-mlog", new // HashMap<String, Object>()); } catch (Exception e) { getLogger().error("Connect data failed", e); sh.getState().setConnectionState(ServerActionHandlerStateInf.DISCONNECTED); } } }
true
deeee60158ccb8e7040a08229752064d57daeec0
Java
maruoovv/algorithm
/leetcode/TwoSum.java
UTF-8
605
3.71875
4
[]
no_license
import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class TwoSum { // 배열에서 두 수의 합의 target 이 되는 index 를 찾는 문제. // n^2 밖에 생각 못했는데.. map 을 써서 n 으로 해결 가능하다. public int[] twoSum(int[] nums, int target) { int n = nums.length; int[] res = new int[2]; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { if (map.containsKey(target - nums[i])) { res[0] = map.get(target - nums[i]); res[1] = i; return res; } map.put(nums[i], i); } return res; } }
true
c66116e57e44c261614e1cf11c47f1348f611484
Java
muojie/spring-boot-learning
/spring-boot-quartz3/src/main/java/com/kfit/App.java
UTF-8
793
2.09375
2
[]
no_license
package com.kfit; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @SpringBootApplication public class App { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(App.class, args); Scheduler scheduler = ctx.getBean(Scheduler.class); try { Thread.sleep(40000); scheduler.deleteJob(new JobKey("MyTask_job","MyTask_group")); System.out.println("App.main().deleteJob"); } catch (InterruptedException e) { e.printStackTrace(); } catch (SchedulerException e) { e.printStackTrace(); } } }
true
00c4e9a139126362b85e49ff8146e79a3f1804b8
Java
SoulApps/CrossPlatformLearning
/workspace/MultihiloCine/src/Sala.java
UTF-8
1,138
3.46875
3
[]
no_license
/** * Created by Alejandro on 04/10/2016. */ public class Sala { private final int AFORO_MAXIMO = 50, AFORO_MIMIMO = 0; private int plazasDisponibles, numero; public Sala(int numero) { this.numero = numero; plazasDisponibles = AFORO_MAXIMO; } public synchronized void comprar(int entradas) { if ((plazasDisponibles - entradas) >= AFORO_MIMIMO) { plazasDisponibles -= entradas; System.out.printf("Has comprado %d entradas para la sala %d -- Hay %d entradas en la sala %2$d%n", entradas, numero, plazasDisponibles); } else System.out.printf("No puedes comprar %d entradas para la sala %d%n", entradas, numero); } public synchronized void vender(int entradas) { if ((plazasDisponibles + entradas) <= AFORO_MAXIMO) { plazasDisponibles += entradas; System.out.printf("Has vendido %d entradas para la sala %d -- Hay %d entradas en la sala %2$d%n", entradas, numero, plazasDisponibles); } else System.out.printf("No puedes vender %d entradas para la sala %d%n", entradas, numero); } }
true
06d10dc06eab624287debefb35a46ba8ebb8fa01
Java
IgorOto/PZ
/kinoteka_api/src/main/java/com/igi/kinoteka_api/service/UserService.java
UTF-8
230
1.914063
2
[]
no_license
package com.igi.kinoteka_api.service; import com.igi.kinoteka_api.model.UserDto; import com.igi.kinoteka_api.model.User; public interface UserService { User getByUsername(String username); void addUser(UserDto user); }
true
e43d08e6fcdd96af44cfecbe7a0d16672060bc76
Java
good-k/chapter03
/src/chapter03/StringTest3.java
UTF-8
1,611
3.640625
4
[]
no_license
package chapter03; public class StringTest3 { public static void main(String[] args) { String s = "aBcAbcabcABC"; System.out.println( s.length() ); System.out.println( s.charAt(2) ); System.out.println( s.indexOf( "abc" )); System.out.println( s.indexOf( "abc", 7 )); System.out.println( s.substring( 3 ) ); System.out.println( s.substring( 3, 6 ) ); String a = " ab cd "; String b = "efg,dewdwq,dwq"; String c = a.concat(b); System.out.println(c); System.out.println("---" + a.trim() + "---"); System.out.println("---" + a.replaceAll(" ", "") + "---"); String[] t = c.split(","); // for(int i = 0; i < t.length; i++) { // System.out.println(t[i]); // } // for-each문 for(String k : t) { System.out.println(k); } StringBuffer sb = new StringBuffer(""); sb.append("Hello"); sb.append(" World"); sb.append( " java" ); System.out.println(sb); // + 연산자 String str = "Hello" + " World" + " Java"; // String str = new StringBuffer("Hello"). // append( " World" ). // append( " Java" ). // toString(); String str2 = ""; for(int i = 0; i < 100000; i++) { str2 = str2 + i; } StringBuffer sb2 = new StringBuffer(""); for(int i = 0; i < 100000; i++) { sb.append(i); } // format String name = "둘리"; int score = 100; System.out.println(name + "님의 점수는 " + score + "입니다."); String str5 = String.format("%s님의 점수는 %d입니다.", name, score); System.out.println(str5); } }
true
c25f7db5572a1efb2a2545c68c86e0fa55d31d42
Java
joseferreira01/atividade-EJB
/web/src/main/java/br/edu/ifpb/dac/atividade/jsf/controlador/ContatoControlador.java
UTF-8
3,349
2.3125
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 br.edu.ifpb.dac.atividade.jsf.controlador; import br.edu.ifpb.shared.Contato; import br.edu.ifpb.shared.ContatoService; import java.io.Serializable; import java.util.List; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.faces.event.AjaxBehaviorEvent; import javax.inject.Inject; import javax.inject.Named; /** * * @author jose */ @Named @RequestScoped public class ContatoControlador implements Serializable{ @EJB private ContatoService cs; private Contato contato; private boolean editando = false; private boolean notEditando = true; private String encontrecontato; @Inject private Mensagem mensagem; private List<Contato> allFirstLettersAsc; @PostConstruct public void init() { allFirstLettersAsc = cs.buscarTodos(); this.contato = new Contato(); } public String salvar() { try { cs.salvar(contato); mensagem.addMessage("Contato salvo com sucesso"); limparContato(); } catch (Exception e) { mensagem.addMessage("Erro ao salvar verifique os dados e tente novamente"); } return null; } public void editar(Contato contato) { this.contato = contato; this.editando = true; this.notEditando = false; } public String cancelar() { this.editando = false; this.notEditando = true; limparContato(); return null; } public void filtro(AjaxBehaviorEvent event){ this.allFirstLettersAsc = allFirstLettersAsc.stream() .filter(c -> c.getNome() .toLowerCase() .startsWith(encontrecontato.toLowerCase())) .collect(Collectors.toList()); } public void atualizar() { try { cs.atualizar(contato); limparContato(); mensagem.addMessage("Contato atualizado"); } catch (Exception e) { mensagem.addMessage("Erro ao atualizar tente novamente"); } } public void remover(Contato contato) { try { this.cs.remover(contato); mensagem.addMessage("contato removido"); } catch (Exception e) { mensagem.addMessage("Erro ao remover contato"); } } public boolean isEditando() { return editando; } public Contato getContato() { return contato; } public void setContato(Contato contato) { this.contato = contato; } public List<Contato> getAllFirstLettersAsc() { allFirstLettersAsc = cs.getAllFirstLettersAsc(); return allFirstLettersAsc; } public String getEncontrecontato() { return encontrecontato; } public void setEncontrecontato(String encontrecontato) { this.encontrecontato = encontrecontato; } public boolean isNotEditando() { return notEditando; } private void limparContato() { this.contato = new Contato(); } }
true
da535df812e53236cae888a7c5ac9d2b70170042
Java
pavliggs/java1
/src/ru/progwards/pavliggs/java2/N10dot4/SimpleApplication.java
UTF-8
206
1.929688
2
[]
no_license
package ru.progwards.pavliggs.java2.N10dot4; public class SimpleApplication { public static void main(String[] args) { System.out.println("SimpleApplication: main стартовал"); } }
true
8a13929f92c6dfae6a6fcbfc1077bb4771cad286
Java
shreeram09/mvnmm
/mvnmm-web/src/main/java/com/shreeram/otweb/MyServlet.java
UTF-8
1,636
2.3125
2
[]
no_license
package com.shreeram.otweb; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJBLocalHome; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.shreeram.otejb.MyEJBHome; import com.shreeram.otejb.MyEJBLocal; /** * Servlet implementation class MyServlet */ public class MyServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String user = request.getParameter("user"); String msg = ""; try { Context ctx = new InitialContext(); MyEJBLocal local = ((MyEJBHome)ctx.lookup("MyEJB")).create(); msg = local.welcome(user); out.write(msg); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
true
aa71d8d5cb7d59d65f9698cf0b9bf5e6837ab012
Java
RyujiSamejima/LinqDroid
/linqdroid/src/jp/linqdroid/IteratorStatus.java
UTF-8
508
2.375
2
[]
no_license
package jp.linqdroid; /** * * @author samejima * * @param <T> */ public class IteratorStatus { private final String status; private IteratorStatus(String status) { this.status = status; } public String toString() { return status; } public static final IteratorStatus BeforeEnumeration = new IteratorStatus("BeforeEnumeration"); public static final IteratorStatus Enumerating = new IteratorStatus("Enumerating"); public static final IteratorStatus Disposed = new IteratorStatus("Disposed"); }
true
818a9339e132a1b24c14b45924585555c39bfd26
Java
calpeyser/TournamentManager
/src/MockTrial/AddPlayers.java
UTF-8
349
2.25
2
[]
no_license
package MockTrial; import Base.Record; import DataAction.DefaultUITableConfigAction; public class AddPlayers extends DefaultUITableConfigAction { @Override protected Class<? extends Record> getRecordType() { return Player.class; } @Override public String description() { return "Add Players to the Tournament"; } }
true
d2661b1c2375525fc2ec5b0c2af39448f14672c7
Java
audreysperry/HorrorMovieReview
/src/main/java/com/audreysperry/moviereview/controllers/MovieController.java
UTF-8
3,812
2.375
2
[]
no_license
package com.audreysperry.moviereview.controllers; import com.audreysperry.moviereview.models.Movie; import com.audreysperry.moviereview.models.Review; import com.audreysperry.moviereview.models.User; import com.audreysperry.moviereview.repositories.MoviesRepository; import com.audreysperry.moviereview.repositories.ReviewsRepository; import com.audreysperry.moviereview.repositories.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.security.Principal; import java.util.List; @Controller public class MovieController { @Autowired private MoviesRepository movieRepo; @Autowired private ReviewsRepository reviewRepo; @Autowired private UserRepository userRepo; @RequestMapping("/") public String displayMovies(Model model) { // model.addAttribute("movie", new Movie()); model.addAttribute("movies", movieRepo.findAll()); return "index"; } @RequestMapping("/movie/add") public String addMovieForm(Model model) { model.addAttribute("movie", new Movie()); return "addMovie"; } @RequestMapping(value = "/movie/add", method = RequestMethod.POST) public String addMovie(Model model, @ModelAttribute Movie movie){ movieRepo.save(movie); return "redirect:/"; } @RequestMapping("/movie/{id}") public String viewMovieDetails(Model model, @ModelAttribute ("id") long id) { Movie movie = movieRepo.findOne(id); model.addAttribute(movie); return "movieDetail"; } @RequestMapping("/movie/{id}/edit") public String editMovieForm(Model model, @ModelAttribute ("id") long id) { Movie editMovie = movieRepo.findOne(id); model.addAttribute("movie", editMovie); return "editMovie"; } @RequestMapping(value= "/movie/{id}/edit", method= RequestMethod.POST) public String editMovie(@ModelAttribute Movie movie, @ModelAttribute ("id") long id) { movieRepo.save(movie); return "redirect:/"; } @RequestMapping(value="/movie/{movieid}/viewReviews") public String viewReviews(@PathVariable ("movieid") Long movieid, Model model) { Movie movie = movieRepo.findOne(movieid); List reviews = movie.getReviews(); model.addAttribute("movie", movie); model.addAttribute("reviews", reviews); return "viewReviews"; } @RequestMapping(value="/movie/{movieid}/review") public String writeReview(@PathVariable ("movieid") long movieid, Model model) { model.addAttribute(movieRepo.findOne(movieid)); model.addAttribute("review", new Review()); return "reviewForm"; } @RequestMapping(value="/movie/{movieid}/review", method = RequestMethod.POST) public String submitReview(@PathVariable ("movieid") Long movieid, Model model, @ModelAttribute Review review, Principal principal) { Movie movie = movieRepo.findOne(movieid); User user = userRepo.findByUsername(principal.getName()); Review newReview = review; newReview.setMovie(movie); newReview.setUser(user); reviewRepo.save(newReview); return "redirect:/"; } }
true
1dc8a6a5c758a5b6b5e78636802991bd500a45c6
Java
raven920/CompuMovil
/ConoceTuUdeA/app/src/main/java/co/edu/udea/compumovil/gr1/conocetuudea/LoginActivity.java
UTF-8
5,105
2.109375
2
[]
no_license
package co.edu.udea.compumovil.gr1.conocetuudea; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.firebase.ui.auth.AuthUI; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import co.edu.udea.compumovil.gr1.conocetuudea.domain.db.User; public class LoginActivity extends AppCompatActivity { public static final int LOGIN_REQ = 50; private static boolean persistedEnabled = false; public static final String LOGGED_USER = "loggedUser"; public static final String TAG = "LoginTAG"; public static final String SHARED_PREFS = "PlacesPrefs"; //private DbHelper dbHelper; private EditText usuario; private EditText contrasena; private DatabaseReference mDatabase; private FirebaseAuth auth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_login); //usuario = (EditText) findViewById(R.id.usernameTxt); //contrasena = (EditText) findViewById(R.id.passTxt); /* dbHelper = new DbHelper(this); SharedPreferences placesPrefs = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); if(placesPrefs != null && placesPrefs.contains(LOGGED_USER)){ Intent i = new Intent(this, LugaresMainActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); finish(); }*/ auth = FirebaseAuth.getInstance(); if(!LoginActivity.persistedEnabled){ FirebaseDatabase.getInstance().setPersistenceEnabled(true); persistedEnabled = true; } mDatabase = FirebaseDatabase.getInstance().getReference(); checkCharacter(); } public void checkCharacter(){ if(auth.getCurrentUser() == null){ startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() .setProviders( AuthUI.EMAIL_PROVIDER, AuthUI.GOOGLE_PROVIDER ) .build(), LOGIN_REQ); return; } ValueEventListener userListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Intent i; // Get Post object and use the values to update the UI User user = dataSnapshot.child("users").child(auth.getCurrentUser().getUid()).getValue(User.class); if(user == null){ user= new User(auth.getCurrentUser().getDisplayName(), auth.getCurrentUser().getEmail(), -1, 0); mDatabase.child("users").child(auth.getCurrentUser().getUid()).setValue(user); } if(user.getCharId() != -1){ i = new Intent(LoginActivity.this, MainActivity.class); }else{ i = new Intent(LoginActivity.this, CharacterSelectActivity.class); } i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); finish(); } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(LoginActivity.this, "Error while reading data", Toast.LENGTH_SHORT).show(); Log.w(TAG, "loadPost:onCancelled", databaseError.toException()); } }; mDatabase.addListenerForSingleValueEvent(userListener); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request we're responding to if (requestCode == LOGIN_REQ) { // Make sure the request was successful if (resultCode == RESULT_OK) { checkCharacter(); }else{ startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() .setProviders( AuthUI.EMAIL_PROVIDER, AuthUI.GOOGLE_PROVIDER ) .build(), LOGIN_REQ); } } } }
true
e3805c522453adf102b60e18b1f23ad1519cd190
Java
waninoko68/Week2CP2
/src/P14_HowToBreak.java
UTF-8
443
3.171875
3
[]
no_license
import java.util.Scanner; public class P14_HowToBreak { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int x = scan.nextInt(); if(x<40) { System.out.println("Fail"); } if(x>=40&&x<80) { System.out.println("Pass"); } if(x>=80) { System.out.println("Excellent"); } } }
true