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
086a8e91f2c3f7f6037d2b251745f0bc87e4b476
Java
aghasyedbilal/intellij-community
/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaInstaller.java
UTF-8
1,031
1.679688
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.ide.ui.laf.darcula; import com.intellij.openapi.util.IconLoader; import com.intellij.ui.JBColor; /** * @author Konstantin Bulenkov */ public class DarculaInstaller { public static void uninstall() { performImpl(false); } public static void install() { performImpl(true); } private static void performImpl(final boolean dark) { JBColor.setDark(dark); IconLoader.setUseDarkIcons(dark); } }
true
20f03770ee634f4b1bca714fa934fe8305d31cb8
Java
knextsunj/guice-blazeds
/guice-blazeds/src/uk/co/chasetechnology/guice_blazeds/AbstractGuiceFactory.java
UTF-8
5,816
2.140625
2
[]
no_license
/** * Copyright (C) 2009 Chase Technology Ltd. * * 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 uk.co.chasetechnology.guice_blazeds; import javax.servlet.ServletContext; import flex.messaging.FactoryInstance; import flex.messaging.FlexContext; import flex.messaging.MessageBroker; import flex.messaging.config.ConfigMap; import flex.messaging.config.ConfigurationException; import flex.messaging.config.ConfigurationManager; import flex.messaging.factories.JavaFactory; import flex.messaging.log.Log; import flex.messaging.services.ServiceException; import flex.messaging.util.ExceptionUtil; import flex.messaging.util.StringUtils; /** * This abstract class is meant to be overridden so that it can be used for Guice injection. * Guice should be injected in the <code>createInjectedObject</code> method. Exactly how you inject is up to you, * but one possibility is to create an injector in the constructor of this factory, and then reference that * injector within <code>createInjectedObject</code>, as follows: * * <pre> * public class MyGuiceFactory extends AbstractGuiceFactory { * * private Injector injector; * * public MyGuiceFactory() { * injector = Guice.createInjector(....); * } * * public <T> T createInjectedObject(Class<T> clazz) { * return injector.getInstance(clazz); * } * } * </pre> * * @author Doug Satchwell */ public abstract class AbstractGuiceFactory extends JavaFactory { private static final String ATTRIBUTE_ID = "attribute-id"; /** * This method is overridden so that the <code>FactoryInstance</code> returned is a <code>GuiceFactoryInstance</code>. * With the exception of changing the instance created, the rest of the method is exactly the same * as for its superclass, thus keeping the ability to specify the scope. */ @Override public FactoryInstance createFactoryInstance(String id, ConfigMap properties) { // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++ only need to override the super method for this following line: // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ GuiceFactoryInstance instance = new GuiceFactoryInstance(this, id,properties); // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++ the rest must be as for the super method // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if (properties == null) { // Use destination id as the default attribute id to prevent // unwanted sharing. instance.setSource(instance.getId()); instance.setScope(SCOPE_REQUEST); instance.setAttributeId(id); } else { instance.setSource(properties.getPropertyAsString(SOURCE, instance .getId())); instance.setScope(properties.getPropertyAsString(SCOPE, SCOPE_REQUEST)); // Use destination id as the default attribute id to prevent // unwanted sharing. instance.setAttributeId(properties.getPropertyAsString( ATTRIBUTE_ID, id)); } if (instance.getScope().equalsIgnoreCase(SCOPE_APPLICATION)) { try { ServletContext ctx = FlexContext.getServletConfig() .getServletContext(); synchronized (ctx) { Object inst = ctx.getAttribute(instance.getAttributeId()); if (inst == null) { inst = instance.createInstance(); ctx.setAttribute(instance.getAttributeId(), inst); } else { Class configuredClass = instance.getInstanceClass(); Class instClass = inst.getClass(); if (configuredClass != instClass && !configuredClass.isAssignableFrom(instClass)) { ServiceException e = new ServiceException(); // e.setMessage(INVALID_CLASS_FOUND, new Object[] { // instance.getAttributeId(), "application", // instance.getId(), // instance.getInstanceClass(), inst.getClass()}); e.setCode("Server.Processing"); throw e; } } instance.applicationInstance = inst; // increment attribute-id reference count on MB MessageBroker mb = FlexContext.getMessageBroker(); if (mb != null) { mb.incrementAttributeIdRefCount(instance .getAttributeId()); } } } catch (Throwable t) { ConfigurationException ex = new ConfigurationException(); // ex.setMessage(SINGLETON_ERROR, new Object[] { // instance.getSource(), id }); ex.setRootCause(t); if (Log.isError()) Log.getLogger(ConfigurationManager.LOG_CATEGORY).error( ex.getMessage() + StringUtils.NEWLINE + ExceptionUtil.toString(t)); throw ex; } } else if (instance.getScope().equalsIgnoreCase(SCOPE_SESSION)) { // increment attribute-id reference count on MB for Session scoped // instances MessageBroker mb = FlexContext.getMessageBroker(); if (mb != null) { mb.incrementAttributeIdRefCount(instance.getAttributeId()); } } return instance; } /** * This is where we do the Guice injection. * * @param <T> type of class * @param clazz to create an instance of * @return an instance of the class */ public abstract <T> T createInjectedObject(Class<T> clazz); }
true
a1c9d08be5c14d5dd859cbd854adede1dd4a2651
Java
squarlhan/sshclient
/MyJenawork/src/cn/edu/jlu/ccst/operation/CreateHomology.java
UTF-8
3,430
2.484375
2
[]
no_license
package cn.edu.jlu.ccst.operation; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.OntModel; import cn.edu.jlu.ccst.example.SimpleExample; import cn.edu.jlu.ccst.model.Homology; public class CreateHomology { /** * judge the string whether is number * @param str * @return */ public boolean isNumeric(String str){ Pattern pattern = Pattern.compile("[0-9]*"); return pattern.matcher(str).matches(); } /** * Get all the homologies from epd * @param addr * @return */ public List<Homology> getallhomos(String addr){ List<Homology> result = new ArrayList(); File file = new File(addr); try { InputStreamReader insr = new InputStreamReader(new FileInputStream( file), "gb2312"); BufferedReader br = new BufferedReader(insr); String line; Homology homology = new Homology(); while ((line = br.readLine()) != null) { line = line.trim(); String[] lines = line.split(" "); // construct homology object if (lines[0].trim().equalsIgnoreCase("HG")) { homology = new Homology(); String[] homos = lines[1].split(";"); if (homos.length >= 2) { homology.setName(homos[1].trim().substring(0,homos[1].trim().length() - 1)); String[] ids = homos[0].trim().split(" "); if (this.isNumeric(ids[2])) { homology.setId(ids[2]); } } if(result.size() == 0){ result.add(homology); }else{ boolean flag = true; for(Homology homo:result){ if(homo.getId().equals(homology.getId())){ flag = false; break; } } if(flag)result.add(homology); } } } br.close(); insr.close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /** * Create all the homology groups ontologies * @param homos */ public void createhomeonts(List<Homology> homos){ SimpleExample se = new SimpleExample(); String nameuri = "http://miuras.inf.um.es/ontologies/OGO.owl#Name"; String homoclsuri = se.PROMOTER_PREFIX + "#Homology"; OntModel onmo = null; try { onmo = se.loadDB2nd(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(Homology homo : homos){ String homoidvuri = se.PROMOTER_PREFIX + "#Homology_" + homo.getId(); Individual itemp = onmo.createIndividual(homoidvuri, onmo.getOntClass(homoclsuri)); se.addDataProperty(onmo, homoidvuri, nameuri, homo.getName()); } se.testListIndividual(onmo, homoclsuri); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub CreateHomology myobj = new CreateHomology(); myobj.createhomeonts(myobj.getallhomos("epd104.dat")); } }
true
bcd340f25e39df5f591105f8183511a262c2a0c1
Java
sashank/Clusion
/src/main/java/org/crypto/sse/CryptoPrimitives.java
UTF-8
21,364
2.5625
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
//***********************************************************************************************// // This file contains most cryptographic primitives : AES in CTR mode for file and string encryption, HMAC, CMAC-AES and HCB1 online cipher. The file also contains some other // tools for bytes manipulation //***********************************************************************************************// package org.crypto.sse; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.macs.CMac; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.prng.ThreadedSeedGenerator; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; public class CryptoPrimitives { private CryptoPrimitives(){} //***********************************************************************************************// ///////////////////// KeyGen return a raw key based on PBE PKCS12///////////////////////////// ///////////////////// almost taken from org.bouncycastle.jce.provider.test.PBETest // check also doc in http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#SecretKeyFactory///////////////////////////// //***********************************************************************************************// public static byte[] keyGenSetM(String pass, byte[] salt, int icount, int keySize) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException{ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(pass.toCharArray(), salt, icount, keySize); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); return secret.getEncoded(); } //***********************************************************************************************// ///////////////////// CMAC-AES generation ///////////////////////////// //***********************************************************************************************// public static byte[] generateCmac(byte[] key, String msg) throws UnsupportedEncodingException { CMac cmac = new CMac(new AESFastEngine()); byte[] data = msg.getBytes("UTF-8"); byte[] output = new byte[cmac.getMacSize()]; cmac.init(new KeyParameter(key)); cmac.reset(); cmac.update(data, 0, data.length); cmac.doFinal(output, 0); return output; } //***********************************************************************************************// ///////////////////// HMAC-SHA256 generation ///////////////////////////// //***********************************************************************************************// public static byte[] generateHmac(byte[] key, String msg) throws UnsupportedEncodingException { HMac hmac=new HMac(new SHA256Digest()); byte[] result=new byte[hmac.getMacSize()]; byte[] msgAry=msg.getBytes("UTF-8"); hmac.init(new KeyParameter(key)); hmac.reset(); hmac.update(msgAry,0,msgAry.length); hmac.doFinal(result,0); return result; } //***********************************************************************************************// ///////////////////// HMAC-SHA512generation ///////////////////////////// //***********************************************************************************************// public static byte[] generateHmac512(byte[] key, String msg) throws UnsupportedEncodingException { HMac hmac=new HMac(new SHA512Digest()); byte[] result=new byte[hmac.getMacSize()]; byte[] msgAry=msg.getBytes("UTF-8"); hmac.init(new KeyParameter(key)); hmac.reset(); hmac.update(msgAry,0,msgAry.length); hmac.doFinal(result,0); return result; } //***********************************************************************************************// ///////////////////// Salt generation/RandomBytes: it is generated just once and it is not necessary to keep it secret ///////////////////////////// //can also be used for random bit generation //***********************************************************************************************// public static byte[] randomBytes(int sizeOfSalt){ byte[] salt=new byte[sizeOfSalt]; ThreadedSeedGenerator thread = new ThreadedSeedGenerator(); SecureRandom random = new SecureRandom(); random.setSeed(thread.generateSeed(20, true)); random.nextBytes(salt); return salt; } //***********************************************************************************************// ///////////////////// AES-CTR encryption of a String ///////////////////////////// //***********************************************************************************************// public static byte[] encryptAES_CTR_String(byte[] keyBytes, byte[] ivBytes, String identifier, int sizeOfFileName) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, IOException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // Concatenate the title with the text. The title should be at most "sizeOfFileName" characters including 3 characters marking the end of it identifier = identifier +"\t\t\t"; byte[] input = concat(identifier.getBytes(), new byte[sizeOfFileName - identifier.getBytes().length]); //byte[] input = concat(input1 , input0); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); ByteArrayInputStream bIn = new ByteArrayInputStream(input); CipherInputStream cIn = new CipherInputStream(bIn, cipher); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); int ch; while ((ch = cIn.read()) >= 0) { bOut.write(ch); } byte[] cipherText = concat(ivBytes, bOut.toByteArray()); return cipherText; } //***********************************************************************************************// ///////////////////// AES-CTR Decryption of String ///////////////////////////// //***********************************************************************************************// public static byte[] decryptAES_CTR_String(byte[] input, byte[] keyBytes) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, IOException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); //byte[] input = readAlternateImpl(folder + fileName); byte[] ivBytes = new byte[16]; byte[] cipherText = new byte[input.length - 16]; System.arraycopy(input, 0, ivBytes, 0, ivBytes.length); System.arraycopy(input, ivBytes.length, cipherText, 0, cipherText.length); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC"); //Initalization of the Cipher cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); CipherOutputStream cOut = new CipherOutputStream(bOut, cipher); cOut.write(cipherText); cOut.close(); return bOut.toByteArray(); } //***********************************************************************************************// ///////////////////// AES-CTR encryption (Designed for sending encrypted files directly to the outsourced servers)///////////////////////////// //***********************************************************************************************// public static void encryptAES_CTR_Socket(ObjectOutputStream out, String folderName, String outputFileName, String folderInput, String inputFileName, byte[] keyBytes, byte[] ivBytes) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, IOException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] input0 = readAlternateImpl(folderInput+inputFileName); // Concatenate the title with the text. The title should be at most 42 characters with 2 characters marking the end of it String endOfTitle = "\t"; inputFileName = inputFileName + endOfTitle; byte[] input1 = concat(inputFileName.getBytes(), new byte[42 - inputFileName.getBytes().length]); byte[] input = concat(input1 , input0); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); ByteArrayInputStream bIn = new ByteArrayInputStream(input); CipherInputStream cIn = new CipherInputStream(bIn, cipher); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); int ch; while ((ch = cIn.read()) >= 0) { bOut.write(ch); } byte[] cipherText = concat(ivBytes, bOut.toByteArray()); // Send the outputfile name out.writeObject(outputFileName); out.flush(); // Send the ciphertext out.writeObject(cipherText); out.flush(); } //***********************************************************************************************// ///////////////////// AES-CTR encryption ///////////////////////////// //***********************************************************************************************// public static void encryptAES_CTR(String folderName, String outputFileName, String folderInput, String inputFileName, byte[] keyBytes, byte[] ivBytes) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, IOException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] input0 = readAlternateImpl(folderInput+inputFileName); // Concatenate the title with the text. The title should be at most 42 characters with 2 characters marking the end of it String endOfTitle = "\t"; inputFileName = inputFileName + endOfTitle; byte[] input1 = concat(inputFileName.getBytes(), new byte[42 - inputFileName.getBytes().length]); byte[] input = concat(input1 , input0); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); ByteArrayInputStream bIn = new ByteArrayInputStream(input); CipherInputStream cIn = new CipherInputStream(bIn, cipher); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); int ch; while ((ch = cIn.read()) >= 0) { bOut.write(ch); } byte[] cipherText = concat(ivBytes, bOut.toByteArray()); write(cipherText, outputFileName, folderName); } //***********************************************************************************************// ///////////////////// AES-CTR Decryption ///////////////////////////// //***********************************************************************************************// public static void decryptAES_CTR(String folderOUT, byte[] input, byte[] keyBytes) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, IOException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] ivBytes = new byte[16]; byte[] cipherText = new byte[input.length - 16]; System.arraycopy(input, 0, ivBytes, 0, ivBytes.length); System.arraycopy(input, ivBytes.length, cipherText, 0, cipherText.length); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC"); //Initalization of the Cipher cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); CipherOutputStream cOut = new CipherOutputStream(bOut, cipher); cOut.write(cipherText); cOut.close(); //Splitting the title from the plaintext byte[] title = new byte[42]; byte[] plaintext = new byte[bOut.toByteArray().length - 42]; System.arraycopy(bOut.toByteArray(), 0, title, 0, title.length); System.arraycopy(bOut.toByteArray(), title.length, plaintext, 0, plaintext.length); String filename = new String (title).split("\t")[0]; write(plaintext, filename, folderOUT); } //***********************************************************************************************// ///////////////////// Generic Read and Write Byte to files ///////////////////////////// //***********************************************************************************************// public static void write(byte[] aInput, String aOutputFileName, String dirName){ // creation of a directory if it is not created //sanitizing the aOutputFileName (new File(dirName)).mkdir(); try { OutputStream output = null; try { output = new BufferedOutputStream(new FileOutputStream(dirName+"/"+aOutputFileName)); output.write(aInput); } finally { output.close(); } } catch(FileNotFoundException ex){ System.out.println("File not found."); } catch(IOException ex){ System.out.println(ex); } } //Read public static byte[] readAlternateImpl(String aInputFileName){ File file = new File(aInputFileName); byte[] result = null; try { InputStream input = new BufferedInputStream(new FileInputStream(file)); result = readAndClose(input); } catch (FileNotFoundException ex){ System.out.println(ex); } return result; } //Read private static byte[] readAndClose(InputStream aInput){ byte[] bucket = new byte[32*1024]; ByteArrayOutputStream result = null; try { try { result = new ByteArrayOutputStream(bucket.length); int bytesRead = 0; while(bytesRead != -1){ bytesRead = aInput.read(bucket); if(bytesRead > 0){ result.write(bucket, 0, bytesRead); } } } finally { aInput.close(); } } catch (IOException ex){ System.out.println(ex); } return result.toByteArray(); } //***********************************************************************************************// ///////////////////// Transform an array of bytes to an integer based on a specific number of bits needed // Note that these functionalities can be further enhanced for better performances ///////////////////////////// //***********************************************************************************************// public static int getBit(byte[] data, int pos) { int posByte = pos/8; int posBit = pos%8; byte valByte = data[posByte]; int valInt = valByte>>(8-(posBit+1)) & 0x0001; return valInt; } public static int[] getBits(byte[] data, int numberOfBits){ int[] bitArray=new int[numberOfBits]; for (int j=0;j<numberOfBits;j++){ bitArray[j]=getBit(data,j); } return bitArray; } public static int getIntFromByte(byte[] byteArray, int numberOfBits){ int result=0; int[] bitArray=getBits(byteArray,numberOfBits); for (int i=0;i<numberOfBits;i++){ result=result+ (int) bitArray[i]*(int)Math.pow(2, i); } return result; } public static long getLongFromByte(byte[] byteArray, int numberOfBits){ long result = 0; int[] bitArray=getBits(byteArray,numberOfBits); for (int i=0;i<numberOfBits;i++){ result=result+ bitArray[i]*(int)Math.pow(2, i); } return result; } public static boolean[] intToBoolean(int number, int numberOfBits){ boolean[] pathNumber = new boolean[numberOfBits]; //represent the number in a binary vector String s=Integer.toString(number,2); String s1 =""; for (int i=0; i<s.length(); i++){ s1 = s1+ s.charAt(s.length()-i-1); } //pad the binary vector by zeros to have the same length as the number of bits requested while (s1.length()<numberOfBits){ s1=s1+"0"; } //convert the string s to an integer representation of bits (specially in a boolean array) for (int i =0;i<numberOfBits;i++){ pathNumber[i]= (s1.charAt(i) != '0'); } return pathNumber; } public static String booleanToString(boolean[] message){ String result =""; for (int i=0; i<message.length;i++){ if (message[i]==true){ result = result+1; } else{ result = result+0; } } return result; } public static byte[] booleanToBytes(boolean[] input) { byte[] byteArray = new byte[input.length / 8]; for (int entry = 0; entry < byteArray.length; entry++) { for (int bit = 0; bit < 8; bit++) { if (input[entry * 8 + bit]) { byteArray[entry] |= (128 >> bit); } } } return byteArray; } public static boolean[] bytesToBoolean(byte[] bytes) { boolean[] bits = new boolean[bytes.length * 8]; for (int i = 0; i < bytes.length * 8; i++) { if ((bytes[i / 8] & (1 << (7 - (i % 8)))) > 0) bits[i] = true; } return bits; } //***********************************************************************************************// ///////////////////// byte array concatenation ///////////////////////////// //***********************************************************************************************// public static byte[] concat(byte[] a, byte[] b) { int aLen = a.length; int bLen = b.length; byte[] c= new byte[aLen+bLen]; System.arraycopy(a, 0, c, 0, aLen); System.arraycopy(b, 0, c, aLen, bLen); return c; } //***********************************************************************************************// ///////////////////// Circular hashing ///////////////////////////// //***********************************************************************************************// public static boolean[] circular(byte[] key, boolean[] message) throws UnsupportedEncodingException{ boolean result[] = new boolean[message.length]; String tmpResult = ""; String tmpMes = ""; for (int i=message.length-1 ; i>=0 ; i--){ tmpMes = tmpMes +String.valueOf(message[i]); byte[] cmac=CryptoPrimitives.generateCmac(key, tmpResult+tmpMes); tmpResult = tmpResult + String.valueOf(CryptoPrimitives.getBit(cmac, 0)!=0); result[i] = (CryptoPrimitives.getBit(cmac, 0)!=0); } return result; } public static boolean circularXOR(boolean[] message) { boolean result = false; for (int i=0; i<message.length; i++){ result = result ^ message[i]; } System.out.print(" RESULT \t"+result); return result; } //***********************************************************************************************// ///////////////////// Online Cipher Implementation of HCBC1 of Bellare et al. with AES-CTR block cipher //////////////////// and hash function SHA-256 (http://eprint.iacr.org/2007/197)///////////////////////////// //***********************************************************************************************// public static boolean[][] onlineCipher(byte[] keyHash, byte[] keyEnc, boolean[] plaintext) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException{ Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); //Block extension using Block expansion function int blockSize = 128; boolean[][] blocks = new boolean[plaintext.length][blockSize]; // le premier block contient le vecteur d�ntialization boolean[][] tmpResults1 = new boolean[plaintext.length+1][blockSize]; tmpResults1[0] = new boolean[blockSize];; // temporary results 2 boolean[][] tmpResults2 = new boolean[plaintext.length][blockSize]; // final results boolean[][] results = new boolean[plaintext.length][blockSize]; for (int i=0; i<plaintext.length; i++){ //we have one bit and we add 127 bits to it blocks[i][0] = plaintext[i]; for (int j=1; j<blockSize;j++){ blocks[i][j] = false; } } SecretKeySpec key = new SecretKeySpec(keyEnc, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, key); for (int i=0; i<plaintext.length; i++ ){ byte[] hmac = CryptoPrimitives.generateHmac(keyHash, CryptoPrimitives.booleanToString(tmpResults1[i])); for (int j=0; j<blockSize;j++){ tmpResults2[i][j] = (CryptoPrimitives.getBit(hmac, j)!=0) ^ blocks[i][j]; } ByteArrayInputStream bIn = new ByteArrayInputStream(CryptoPrimitives.booleanToBytes(tmpResults2[i])); CipherInputStream cIn = new CipherInputStream(bIn, cipher); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); int ch; while ((ch = cIn.read()) >= 0) { bOut.write(ch); } results[i] = CryptoPrimitives.bytesToBoolean(bOut.toByteArray()); tmpResults1[i+1] = results[i]; } return results; } }
true
11a3ba933a7232eac53f03c4f379d40d32403549
Java
huanzhz/HackerRank
/Java8/DataStructure/Insert a Node at the Tail of a Linked List.java
UTF-8
811
3.390625
3
[]
no_license
References: https://www.youtube.com/watch?v=Ktqa7d7ZK9A static SinglyLinkedListNode insertNodeAtTail(SinglyLinkedListNode head, int data) { // create a SPACE/ADDRESS/MEMORY for the linklist node SinglyLinkedListNode new_node = new SinglyLinkedListNode(data); if(head == null){ head = new_node; return head; } // get the link list // [a]->[b]->[c] // currently at [a] SinglyLinkedListNode current_node = head; // travel through the link list to the last node // after the while loop it will reach [c] while(current_node.next != null){ current_node = current_node.next; } // current location : [c] // put the node [d] at tail where it is currently pointing to null : [c]->null // [c]->[d] current_node.next = new_node; // the full linklist : [a]->[b]->[c]->[d] return head; }
true
4be7fc4fe70067c26202b16452b6c686f3d1f912
Java
PhilipHannemann/android
/WhatsForDinner/app/src/main/java/com/joakimsvedin/whatsfordinner/Meals/MealsActivity.java
UTF-8
5,951
2.359375
2
[]
no_license
package com.joakimsvedin.whatsfordinner.Meals; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Layout; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.joakimsvedin.whatsfordinner.MainActivity; import com.joakimsvedin.whatsfordinner.R; import com.joakimsvedin.whatsfordinner.Recipes.Recipes; import com.joakimsvedin.whatsfordinner.Repository; import com.joakimsvedin.whatsfordinner.newDish.NewDishActivity; import java.util.List; public class MealsActivity extends AppCompatActivity { String[] weekDays = {"Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; String[] mealTypes = {"Breakfast", "Lunch","Dinner"}; Button[] buttons = new Button[7*3]; Repository repository = Repository.getInstance(); String tempValue = ""; public void backToMain(View view) { Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); // hides the Action Bar from the Emulator setContentView(R.layout.activity_meals); createView(); // retrieve the intent variable passed from MainActivity //Intent intent = getIntent(); // show it with a Toast //Toast.makeText(this, intent.getStringExtra("username"), Toast.LENGTH_SHORT).show(); } private int getDP(int px){ float d = this.getResources().getDisplayMetrics().density; return (int)(px*d*3/4); } private void createView(){ LinearLayout linearLayout = findViewById(R.id.linearLayoutMeals); int buttonCount = 0; for (final String day: weekDays){ LinearLayout linearLayout1 = new LinearLayout(this); linearLayout1.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); linearLayout1.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.setMarginStart(getDP(16)); params.topMargin = getDP(20); TextView textView = new TextView(this); textView.setLayoutParams(params); textView.setText(day); textView.setTextSize(getDP(18)); linearLayout1.addView(textView); for (final String type: mealTypes){ LinearLayout linearLayout2 = new LinearLayout(this); linearLayout2.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); linearLayout2.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(getDP(140), getDP(50)); params2.setMarginStart(getDP(32)); params2.topMargin = getDP(4); TextView textView2 = new TextView(this); textView2.setLayoutParams(params2); textView2.setText(type); textView2.setTextSize(getDP(13)); params2 = new LinearLayout.LayoutParams(getDP(240), getDP(50)); params2.topMargin = getDP(7); buttons[buttonCount] = new Button(this); buttons[buttonCount].setLayoutParams(params2); final int d = buttonCount/3; final int t = buttonCount - d*3; String meal = Repository.getInstance().getMealsChosen(d, t); buttons[buttonCount].setText(meal); buttons[buttonCount].setTransformationMethod(null); final int buttonId = buttonCount; buttons[buttonCount].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(getApplicationContext(), RecipesList.class); tempValue = (String)buttons[buttonId].getText(); if(!tempValue.equals("eaten out")){ repository.incrementMealCount(tempValue); } Repository.resetMealsChosen(d, t); startActivityForResult(i, buttonId); } }); linearLayout2.addView(textView2); linearLayout2.addView(buttons[buttonCount]); linearLayout1.addView(linearLayout2); buttonCount++; } linearLayout.addView(linearLayout1); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); int day = requestCode/3; int type = requestCode - day*3; if (requestCode < 7*3 && resultCode != -1) { String meal = data.getStringExtra("meal"); buttons[requestCode].setText(meal); repository.setMealsChosen(day, type, meal); repository.decrementMealCount(meal); } if (resultCode == -1){ buttons[requestCode].setTag(tempValue); repository.decrementMealCount(tempValue); Repository.getInstance().setMealsChosen(day, type, tempValue); } } }
true
d89daf4291917905d8fb3fa49a99e12945c96192
Java
WangLiantao/Frist
/Course/06.27/二分法/BinarySearch16.java
UTF-8
513
3.765625
4
[]
no_license
public class BinarySearch16 { public static void main(String[] args) { int[] arr = {1,2,3,4,5,6,67,88}; System.out.println(binarySearch(arr,67)); } public static int binarySearch(int[] arr,int key) { int start = 0; int end = arr.length - 1; int kIndex = (start + end) / 2; while (start <= end) { if (arr[kIndex] < key) { start = kIndex + 1; } else if (arr[kIndex] > key) { end = kIndex - 1; } else { return kIndex; } kIndex = (start + end) / 2; } return - 1; } }
true
f919d2fcf4098ef446d04b46b5e2c2f676507d70
Java
22Dimas54/BubleShooter2D2019
/BubleShooter2D/src/ru/sibnsk/bubleshooter2d/Bullet.java
UTF-8
1,120
3.25
3
[]
no_license
package ru.sibnsk.bubleshooter2d; import java.awt.*; public class Bullet { // Fields private double x, y; private int r, speed; private double bulletDX; private double bulletDY; private double distX; private double distY; private double dist; private Color color; // Constructor public Bullet() { x = GamePanel.player.getX(); y = GamePanel.player.getY(); r = 2; speed = 10; distX = GamePanel.mouseX - x; distY = GamePanel.mouseY - y; dist = Math.sqrt(distX * distX + distY * distY); bulletDX = distX / dist * speed; bulletDY = distY / dist * speed; color = Color.WHITE; } // Function public double getX() { return x; } public double getY() { return y; } public double getR() { return r; } public boolean remove() { if (y < 0 || y > GamePanel.HEIGTH || x < 0 || x > GamePanel.WIDTH) { return true; } return false; } public void update() { y += bulletDY; x += bulletDX; } public void draw(Graphics2D g) { g.setColor(color); g.fillOval((int) x, (int) y, r, 2 * r); } }
true
74b90c6122c05eea50131479fa52866b300f1344
Java
avoloshko/merkle-tree-spark
/src/test/java/tasks/MerkleRootCalculatorTaskTest.java
UTF-8
2,515
2.234375
2
[]
no_license
package tasks; import com.typesafe.config.Config; import org.apache.commons.io.FileUtils; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Encoders; import org.apache.spark.sql.SparkSession; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import services.MerkleLeafFileReader; import services.MerkleRootCalculator; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; class MerkleRootCalculatorTaskTest { private String outputPath = ".output/" + MerkleRootCalculatorTaskTest.class.getSimpleName(); private List<String> paths = Arrays.asList("a", "b", "c"); private Integer partitionsCount = 10; @Mock private MerkleRootCalculator merkleRootCalculator; @Mock private MerkleLeafFileReader merkleLeafFileReader; @Mock private Config config; @Spy @InjectMocks private MerkleRootCalculatorTask merkleRootCalculatorTask; private SparkSession spark; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); spark = SparkSession.builder() .master("local[*]") .getOrCreate(); doReturn(spark).when(merkleRootCalculatorTask).buildSparkSession(); when(config.getString("tasks.merkle-root-calculator.output-path")).thenReturn(outputPath); when(config.getString("tasks.merkle-root-calculator.paths")).thenReturn(String.join(",", paths)); when(config.getInt("tasks.merkle-root-calculator.partitions")).thenReturn(partitionsCount); } @AfterEach void tearDown() throws IOException { FileUtils.deleteDirectory(new File(outputPath)); } @Test void testOutput() throws IOException { String output = UUID.randomUUID().toString(); Dataset<String> dataset = spark.emptyDataset(Encoders.STRING()); when(merkleLeafFileReader.call(spark, paths)).thenReturn(dataset); when(merkleRootCalculator.call(dataset, 0L, partitionsCount)).thenReturn(output); merkleRootCalculatorTask.run(); String fileContent = FileUtils.readFileToString( FileUtils.iterateFiles(new File(outputPath), new String[]{"txt"}, false).next()).trim(); assertEquals(output, fileContent); verify(merkleRootCalculatorTask, times(1)).buildSparkSession(); } }
true
6b67f291c1e02b21e0eebe08fab8509a449e1a81
Java
ishaniMadhuwanthi/spark_ncms_backend
/src/main/java/lk/spark/ishani/model/User.java
UTF-8
2,529
2.59375
3
[]
no_license
package lk.spark.ishani.model; import com.google.gson.JsonObject; import lk.spark.ishani.database.DBConnectionPool; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; public class User { private String email; private String password; private boolean ismoh; private boolean isdoctor; private boolean ispatient; public User(){ } public User(String email){ this.email=email; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean isIsmoh() { return ismoh; } public void setIsmoh(boolean ismoh) { this.ismoh = ismoh; } public boolean isIsdoctor() { return isdoctor; } public void setIsdoctor(boolean isdoctor) { this.isdoctor = isdoctor; } public boolean isIspatient() { return ispatient; } public void setIspatient(boolean ispatient) { this.ispatient = ispatient; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } //serialize data into json object public JsonObject serialize() { JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("email", this.email); jsonObj.addProperty("password", this.password); jsonObj.addProperty("ismoh", this.ismoh); jsonObj.addProperty("isdoctor", this.isdoctor); jsonObj.addProperty("ispatient",this.ispatient); return jsonObj; } //load user data public void loadUserData() { try { Connection con = DBConnectionPool.getInstance().getConnection(); PreparedStatement stmt; ResultSet resultSet; stmt = con.prepareStatement("SELECT * FROM user WHERE email=?"); resultSet = stmt.executeQuery(); while (resultSet.next()) { this.email = resultSet.getString("email"); this.password = resultSet.getString("password"); this.ismoh = resultSet.getBoolean("ismoh"); this.isdoctor = resultSet.getBoolean("isdoctor"); this.ispatient = resultSet.getBoolean("ispatient"); } con.close(); } catch (Exception exception) { } } }
true
5435561c8a31efe2bf02cf35fb0466411ab1d604
Java
matt712/testing-assess
/src/test/java/jenkinsTest/XcelTest.java
UTF-8
3,526
2.15625
2
[]
no_license
package jenkinsTest; import static org.junit.Assert.*; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import jenkinsPages.JenkinsLogin; import jenkinsPages.JenkinsMain; import jenkinsPages.JenkinsUserCreate; public class XcelTest { WebDriver driver; @Before public void setUp() { System.setProperty("webdriver.chrome.driver", "C:/Users/Admin/Downloads/chromedriver.exe"); driver = new ChromeDriver(); } @After public void tearDown() { driver.quit(); } @Test public void testUserCreation() throws IOException, InterruptedException { FileInputStream xcelIn = new FileInputStream("C:\\Users\\Admin\\Downloads\\AssessmentFriday.xlsx"); XSSFWorkbook worker = new XSSFWorkbook(xcelIn); XSSFSheet worksheet = worker.getSheetAt(0); String[][] anArray = new String[worksheet.getPhysicalNumberOfRows()][6]; for(int i =0; i<worksheet.getPhysicalNumberOfRows(); i++) { for(int j = 0; j<6; j++) { if(worksheet.getRow(i).getCell(j) == null) { anArray[i][j] = "bloop"; }else { anArray[i][j] = worksheet.getRow(i).getCell(j).toString(); } System.out.println(i + " " + j + ","); } } xcelIn.close(); driver.manage().window().maximize(); driver.get("http://35.197.228.178:8080/"); JenkinsLogin jenkin = PageFactory.initElements(driver, JenkinsLogin.class); JenkinsMain jenkin2 = PageFactory.initElements(driver, JenkinsMain.class); JenkinsUserCreate jenkin3 = PageFactory.initElements(driver, JenkinsUserCreate.class); jenkin.enterUser(); jenkin.enterPassword(); jenkin.hitSubmit(); WebElement elly = (new WebDriverWait(driver,10)).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"tasks\"]/div[4]/a[1]/img"))); elly.click(); elly = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"main-panel\"]/div[16]/a/img"))); elly.click(); for(int i = 1; i<worksheet.getPhysicalNumberOfRows(); i++) { elly = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"tasks\"]/div[3]/a[2]"))); elly.click(); Thread.sleep(1000); jenkin3.enterUsername(anArray[i][0]); jenkin3.enterPassword(anArray[i][2]); jenkin3.enterName(anArray[i][1]); jenkin3.enterEmail(anArray[i][4]); jenkin3.clickSubmit(); Thread.sleep(1000); elly = driver.findElement(By.xpath("//*[@id=\"main-panel\"]/h1")); anArray[i][5] = "True"; } for(int i = 0; i<worksheet.getPhysicalNumberOfRows(); i++) { for(int j=0; j<6; j++) { XSSFRow row = worksheet.getRow(i); XSSFCell cell = row.getCell(j); if(cell == null) { cell = row.createCell(j); } cell.setCellValue(anArray[i][j]); } } FileOutputStream xcelOut = new FileOutputStream("C:\\Users\\Admin\\Documents\\TestResults.xlsx"); worker.write(xcelOut); xcelOut.flush(); xcelOut.close(); } }
true
c0c4f63c98462a5ceb9c82cca05c6bedb4fa8ea5
Java
somainsharma/Instagram
/app/src/main/java/com/example/instagram/MainActivity.java
UTF-8
5,298
2.0625
2
[]
no_license
package com.example.instagram; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.parse.ParseException; import com.parse.ParseUser; import com.parse.SignUpCallback; import com.shashank.sony.fancytoastlib.FancyToast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private EditText edtemail,edtusername,edtpassword; private Button btnsingup, btnlogin; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle("Sign up"); edtemail = findViewById(R.id.edtemailsignup); edtusername = findViewById(R.id.edtusernamesignup); edtpassword = findViewById(R.id.edtpasswordsignup); // edtpassword.setOnKeyListener(new View.OnKeyListener(){ // // public Boolean onKey(View view, int Keycode , KeyEvent event){ // // if((Keycode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)){ // onClick(btnsingup); // } // return false; // } // // // }); edtpassword.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View view, int i, KeyEvent keyEvent) { if(i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN){ onClick(btnsingup); } return false; } }); btnsingup = findViewById(R.id.singupbutton); btnlogin = findViewById(R.id.loginbutton); btnsingup.setOnClickListener(MainActivity.this); btnlogin.setOnClickListener(MainActivity.this); if(ParseUser.getCurrentUser() != null){ // ParseUser.getCurrentUser().logOut(); transitionofActivity(); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.singupbutton: if(edtusername.getText().toString().equals("") || edtpassword.getText().toString().equals("") || edtemail.getText().toString().equals("")) { FancyToast.makeText(MainActivity.this,"Email, username, password is required ", Toast.LENGTH_SHORT, FancyToast.WARNING, true).show(); } else { final ParseUser appuser = new ParseUser(); appuser.setEmail(edtemail.getText().toString()); appuser.setUsername(edtusername.getText().toString()); appuser.setPassword(edtpassword.getText().toString()); final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage("Signing in the user: " + edtusername.getText()); progressDialog.show(); appuser.signUpInBackground(new SignUpCallback() { @Override public void done(ParseException e) { if (e == null) { //Also try appuser.getusername in the message section of the toast FancyToast.makeText(MainActivity.this, appuser.get("username") + " has signed up successfully", Toast.LENGTH_SHORT, FancyToast.SUCCESS, true).show(); transitionofActivity(); } else { FancyToast.makeText(MainActivity.this, "An error occurred" + "\n" + e.getMessage(), Toast.LENGTH_LONG, FancyToast.ERROR, true).show(); } progressDialog.dismiss(); } }); } break; case R.id.loginbutton: // Log.i("TAG","btn login is working now "); Intent intent = new Intent(MainActivity.this,loginActivity.class); startActivity(intent); break; } } public void emptylayoutapped(View view){ try { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0); } catch (Exception e){ e.printStackTrace(); } } public void transitionofActivity(){ Intent intent = new Intent(MainActivity.this,SocialMediaActivity.class); startActivity(intent); } }
true
ce0c21054422cd4e7f733c68947a35481fd91647
Java
dbsigurd/todo
/src/com/example/dbsigurd_mytodolist/Archived_Options.java
UTF-8
4,347
2.59375
3
[]
no_license
package com.example.dbsigurd_mytodolist; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; /*this class is used to display and control option for a single archived to do it uses onclick listners and both archived to do list and unarchived to list to switch items as need. also is able send email to the default email client */ public class Archived_Options extends Activity { public static final String EXTRA_CHOICE = "the Choice"; // used to pass result of activity public int positionChosen; //the position in the list of todo chosen ToDoList toDos = ToDoList.getInstance(); //singleton design to avoid duplicate class ArchivedToDoList archivedToDos = ArchivedToDoList.getInstance(); ToDoItem toEdit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_archived__options); Intent intent = getIntent(); int positionChosen = intent.getIntExtra(MainActivity.EXTRA_MESSAGE, 0); toEdit = archivedToDos.getToDoItem(positionChosen); TextView toDoChosen = (TextView) findViewById(R.id.clicked); toDoChosen.setText(archivedToDos.getToDoItem(positionChosen).getToDo()); setupCancel(); // returns as normal setupDelete(); // deletes todo setupUnarchive(); //unarchive to do setupEmail(); // emails this on to do } private void setupEmail() { Button btn = (Button) findViewById(R.id.EmailButton); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int choiceClicked = 4; Intent intent = new Intent(); intent.putExtra(EXTRA_CHOICE, choiceClicked); setResult(Activity.RESULT_OK, intent); finish(); // TODO Auto-generated method stub } }); } private void setupUnarchive() { // TODO Auto-generated method stub Button btn = (Button) findViewById(R.id.UnarchiveButton); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int choiceClicked = 3; Intent intent = new Intent(); String pop = toEdit.getToDo(); Toast.makeText(Archived_Options.this, pop + " has been Unarchived", Toast.LENGTH_LONG).show(); // add to Archived list toDos.add(toEdit); archivedToDos.remove(toEdit); intent.putExtra(EXTRA_CHOICE, choiceClicked); setResult(Activity.RESULT_OK, intent); finish(); // TODO Auto-generated method stub } }); } public void setupDelete() { // TODO Auto-generated method stub Button btn = (Button) findViewById(R.id.DeleteButton); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int choiceClicked = 2; Intent intent = new Intent(); archivedToDos.remove(toEdit); intent.putExtra(EXTRA_CHOICE, choiceClicked); setResult(Activity.RESULT_OK, intent); finish(); // TODO Auto-generated method stub } }); } public void Copy(View view) { int choiceClicked = 1; Intent intent = new Intent(); archivedToDos.add(toEdit); intent.putExtra(EXTRA_CHOICE, choiceClicked); setResult(Activity.RESULT_OK, intent); finish(); // TODO Auto-generated method stub } private void setupCancel() { Button btn = (Button) findViewById(R.id.CancelButton); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); setResult(Activity.RESULT_CANCELED, intent); finish(); // TODO Auto-generated method stub } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.archived__options, 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. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
2e24d19f2afbda4130c4e45320108d23291b90d7
Java
GOTFCodingTeam/GOTFgit
/core/src/com/alvarpq/GOTF/coreGame/event/UnitKilledEvent.java
UTF-8
808
3.03125
3
[]
no_license
package com.alvarpq.GOTF.coreGame.event; import com.alvarpq.GOTF.coreGame.Side; import com.alvarpq.GOTF.coreGame.units.Unit; /** * For handling when units are killed by units. */ public class UnitKilledEvent extends Event { /** * The killed unit. */ private Unit killedUnit; /** * Instantiates a new UnitDamagedByUnitEvent. * @param killedUnit the unit that has been killed * @param mySide the side of the event receiver * @param opponentsSide the opponents side of the event receiver */ public UnitKilledEvent(Unit killedUnit, Side mySide, Side opponentsSide) { super(mySide, opponentsSide); this.killedUnit = killedUnit; } /** * Returns the killed unit. * @return the killed unit */ public Unit getKilledUnit() { return killedUnit; } }
true
425eed1877dc158a851b7c520567aeecb18c9ac2
Java
1067899750/ElementDemo
/moduleSystem/z_lib_net/src/main/java/com/example/z_lib_net/http/net/retrofit/dns/HttpDns.java
UTF-8
687
2.203125
2
[]
no_license
package com.example.z_lib_net.http.net.retrofit.dns; /** * * @description IP基类 * @author puyantao * @date 2019/10/14 10:22 */ public class HttpDns { private static HttpDns mInstance = null; /** * URL */ public static String baseUrl; public static HttpDns getInstance() { if (mInstance == null) { synchronized (HttpDns.class) { if (mInstance == null) { mInstance = new HttpDns(); } } } return mInstance; } public void init(String url) { baseUrl = url; } public String getIp() { return baseUrl; } }
true
f943ae3a6ccc53c9356e852f7aac9d51fa1c14b0
Java
diegobugmann/Java-Projects-Diego
/src/jabberwocky/letterBased/appClasses/dataClasses/TrainingUnit.java
UTF-8
381
2.859375
3
[ "BSD-3-Clause" ]
permissive
package jabberwocky.letterBased.appClasses.dataClasses; public abstract class TrainingUnit { @Override public int hashCode() { return this.toString().hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof TrainingUnit) { TrainingUnit s = (TrainingUnit) obj; return s.toString().equals(this.toString()); } else { return false; } } }
true
db78e725d96d8c23f92ca0feaa3901fb953bc108
Java
galchev/jobsbg-it-talents
/jobsbg-it-talents/src/main/java/com/example/demo/exceptions/InvalidBulstatException.java
UTF-8
1,025
2.296875
2
[]
no_license
package com.example.demo.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_ACCEPTABLE) public class InvalidBulstatException extends Exception{ /** * */ private static final long serialVersionUID = 3372066578520157794L; public InvalidBulstatException() { super(); // TODO Auto-generated constructor stub } public InvalidBulstatException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public InvalidBulstatException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public InvalidBulstatException(String message) { super(message); // TODO Auto-generated constructor stub } public InvalidBulstatException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }
true
15504ce2803f0159b5ac04a70e943373c9a6bcfe
Java
Tob1112/seungbeomi
/flex/account-book/src/main/java/examples/account/entity/SecondTitle.java
UTF-8
1,032
2.46875
2
[]
no_license
package examples.account.entity; public class SecondTitle { private Integer secondTitleId; private String secondTitleName; private Integer firstTitleId; public Integer getFirstTitleId() { return firstTitleId; } public void setFirstTitleId(Integer firstTitleId) { this.firstTitleId = firstTitleId; } public Integer getSecondTitleId() { return secondTitleId; } public void setSecondTitleId(Integer secondTitleId) { this.secondTitleId = secondTitleId; } public String getSecondTitleName() { return secondTitleName; } public void setSecondTitleName(String secondTitleName) { this.secondTitleName = secondTitleName; } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("SecondTitle["); buffer.append("firstTitleId = ").append(firstTitleId); buffer.append(" secondTitleId = ").append(secondTitleId); buffer.append(" secondTitleName = ").append(secondTitleName); buffer.append("]"); return buffer.toString(); } }
true
8d7c6b0b53e1559faff347400f30192c89248f67
Java
doublefantansy/FragmentViewPager
/my_fragment_viewpager/src/main/java/hzkj/cc/my_fragment_viewpager/MyFragmentAdaper.java
UTF-8
795
2.25
2
[]
no_license
package hzkj.cc.my_fragment_viewpager; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; public class MyFragmentAdaper extends FragmentPagerAdapter { private Context mContext; private List<ScrollItem> list; public MyFragmentAdaper(FragmentManager fm, List<ScrollItem> list) { super(fm); this.list = list; } @Override public Fragment getItem(int i) { return list.get(i).fragment; } @Override public int getCount() { return list.size(); } }
true
5a38cef5b95c152666beaf9c0d8a2c4da10e1837
Java
majinwen/sojourn
/zraapi/src/main/java/com/zra/kanban/logic/WorkBenchAudContractLogic.java
UTF-8
1,913
2.09375
2
[]
no_license
package com.zra.kanban.logic; import com.zra.common.dto.kanban.AudContractQueryDto; import com.zra.common.utils.DateUtilFormate; import com.zra.kanban.entity.WorkBenchAudContract; import com.zra.kanban.service.WorkBenchAudContractService; import com.zra.system.entity.EmployeeEntity; import com.zra.system.entity.UserAccountEntity; import com.zra.system.service.EmployeeService; import com.zra.system.service.UserAccountService; import org.slf4j.Logger; import com.apollo.logproxy.slf4j.LoggerFactoryProxy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; /** * Created by lixn49 on 2016/12/26. */ @Component public class WorkBenchAudContractLogic { private static final Logger LOGGER = LoggerFactoryProxy.getLogger(WorkBenchAudContractLogic.class); @Autowired private WorkBenchAudContractService audContractService; @Autowired private UserAccountService userAccountService; @Autowired private EmployeeService employeeService; /** * @Author lixn49 * @Date 2016/12/26 11:32 * @Description 根据项目id 未审核通过的合同 */ public List<WorkBenchAudContract> selectNoAudContractList(AudContractQueryDto queryDto){ List<WorkBenchAudContract> resultList = new ArrayList<>(); if (userAccountService.isZO(queryDto.getUserId())) { EmployeeEntity employee = employeeService.getEmployeeByUserId(queryDto.getUserId()); queryDto.setZoCode(employee.getCode()); } resultList = audContractService.selectNoAudContractList(queryDto); if (resultList != null && resultList.size() > 0) { for (WorkBenchAudContract entity : resultList) { if (entity.getConAuditDate() != null) { entity.setConAuditDateDisplay(DateUtilFormate.formatDateToString(entity.getConAuditDate(), DateUtilFormate.DATEFORMAT_4)); } } } return resultList; } }
true
0d2ca190bd810afd259139be95c387122698c2d1
Java
kamil-sladowski/Design-Patterns
/src/builder/AnimalBuilder.java
UTF-8
523
2.921875
3
[]
no_license
package builder; class AnimalCellBuilder extends CellBuilder{} class AnimalBuilder { public void createAnimal(AnimalCellBuilder builder){ builder.createNewCell(); builder.createLysosomes(); builder.createCellMembrane(); builder.createCellNucleus(); builder.createNuclearMembrane(); builder.createCytoplasm(); builder.createEndoplasmicReticulum(); builder.createRibosomes(); builder.createMitochondria(); builder.createVacuoles(); } }
true
e3b09dbc663a2331ee20287ad32bcd65616a12da
Java
sbonzi/WC2239232_L302
/TPO_Repositorio/src/exceptions/TractorTrailerCompuestoException.java
UTF-8
269
2.09375
2
[]
no_license
package exceptions; public class TractorTrailerCompuestoException extends Exception { /** * */ private static final long serialVersionUID = 4493684187337341478L; public TractorTrailerCompuestoException(String mensaje){ super(mensaje); } }
true
4d3aaa24fdf0d9a472e5245e55a4498a03079a9b
Java
ScottTamg/GameLiveAudience2
/liveroom/src/main/java/com/ttt/liveroom/bean/websocket/GagResResponse.java
UTF-8
2,043
2.4375
2
[]
no_license
package com.ttt.liveroom.bean.websocket; public class GagResResponse extends WsRequest { private Data data; public Data getData() { return data; } public void setData(Data data) { this.data = data; } @Override public String toString() { return "GagReqRequest{" + "data=" + data.toString() + '}'; } public static class Data { private String roomId; private String userId; private String avatar; private String nickName; private String level; private String expiry; public String getRoomId() { return roomId; } public void setRoomId(String roomId) { this.roomId = roomId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getExpiry() { return expiry; } public void setExpiry(String expiry) { this.expiry = expiry; } @Override public String toString() { return "Data{" + "roomId='" + roomId + '\'' + ", userId='" + userId + '\'' + ", avatar='" + avatar + '\'' + ", nickName='" + nickName + '\'' + ", level='" + level + '\'' + ", expiry='" + expiry + '\'' + '}'; } } }
true
59e49f810edb83ef9aa68bb260fefb69573b46d2
Java
renarj/homeautomation
/home_arduino/src/main/java/com/oberasoftware/home/arduino/SerialArduinoLCD.java
UTF-8
1,570
2.859375
3
[]
no_license
package com.oberasoftware.home.arduino; import com.oberasoftware.home.api.exceptions.HomeAutomationException; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; import static org.slf4j.LoggerFactory.getLogger; /** * @author renarj */ @Component public class SerialArduinoLCD implements ArduinoLCD { private static final Logger LOG = getLogger(SerialArduinoLCD.class); @Autowired private SerialArduinoConnector serialArduinoConnector; private String firstLine = ""; private String secondLine = ""; @Override public void write(LINE line, String text) { String trimmedText = text; if(trimmedText.length() > 16) { trimmedText = text.substring(0, 16); } if(line == LINE.FIRST) { firstLine = trimmedText; } else { secondLine = trimmedText; } writeToDisplay(); } private void writeToDisplay() { if(serialArduinoConnector.isConnected()) { String totalText = firstLine + "\n" + secondLine + "\n"; LOG.debug("Writing text to LCD: {}", totalText); try { serialArduinoConnector.getOutputStream().write(totalText.getBytes()); } catch (IOException | HomeAutomationException e) { LOG.error("Unable to write to LCD display", e); } } else { LOG.warn("Cannot write to Arduino LCD, not connected"); } } }
true
888521c981fc7633d01ada03bae249ecbea5ea9d
Java
VeiNPrk/LocationS
/app/src/main/java/com/example/vnprk/locationsearch/View/RequestFragment.java
UTF-8
9,046
1.710938
2
[]
no_license
package com.example.vnprk.locationsearch.View; import android.app.AlertDialog; import android.content.DialogInterface; import android.support.v4.app.LoaderManager; import android.database.ContentObserver; import android.database.Cursor; import android.os.Handler; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.v4.content.Loader; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import com.example.vnprk.locationsearch.Controller.DataBase; import com.example.vnprk.locationsearch.Controller.DescribeRecyclerAdapter; import com.example.vnprk.locationsearch.Controller.DividerItemDecoration; import com.example.vnprk.locationsearch.Loaders.DescribeLoader; import com.example.vnprk.locationsearch.Loaders.UserLoader; import com.example.vnprk.locationsearch.Model.MessageEvent; import com.example.vnprk.locationsearch.Model.UserClass; import com.example.vnprk.locationsearch.R; import com.example.vnprk.locationsearch.Model.UserClass_Table; import com.raizlabs.android.dbflow.sql.language.Select; import org.greenrobot.eventbus.EventBus; import java.util.List; /** * Created by VNPrk on 27.10.2018. */ public class RequestFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{ RecyclerView rvRequest = null; View view=null; List<UserClass> requestUsers; DescribeRecyclerAdapter adapter; int nowPositionList = -1; int countChecked = 0; public static final String REQUEST_LOAD_COMPLETE = "request_load_complete"; public static final int REQUEST_LOAD_COMPL_CODE = 3; DescribeDialogFragment dialog; ProgressBar progressBar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_request, container, false); initViews(); initData(); return view; } private void initViews(){ rvRequest = (RecyclerView)view.findViewById(R.id.rv_request); progressBar=(ProgressBar)view.findViewById(R.id.progressBar2); } private void initData(){ updateData(); } private void setRecyclerView() { LinearLayoutManager layoutManager = new LinearLayoutManager(view.getContext(), LinearLayoutManager.VERTICAL, false); adapter = new DescribeRecyclerAdapter(view.getContext(), /*rvClickListener*/rvClickListener, requestUsers); rvRequest.setLayoutManager(layoutManager); rvRequest.setHasFixedSize(true); rvRequest.setAdapter(adapter); RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(view.getContext(), DividerItemDecoration.VERTICAL_LIST); rvRequest.addItemDecoration(itemDecoration); rvRequest.setItemAnimator(new DefaultItemAnimator()); } private void deleteElement(List<Integer> positions) { if(positions.size()>0) { for(int i:positions) { requestUsers.get(i).delete(); adapter.notifyItemRemoved(i); } refreshData(); //AppWidget.sendUpdateMessage(this); } } public void updateData(){ Bundle bundle = new Bundle(); bundle.putInt(UserLoader.OPERATION_KEY, UserLoader.REQUEST_USERS); getLoaderManager().initLoader(MapActivity.LOADER_USERS, bundle, this); } private void addElementView(){ dialog.show(getFragmentManager(), "DescribeDialog"); //if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { /*Intent intent = new Intent(MainActivity.this, NoteActivity.class); intent.putExtra(NoteActivity.KEY_CODE, requestCodeAdd); startActivityForResult(intent, requestCodeAdd);*/ // } } public void refreshData(){ requestUsers.clear(); requestUsers = new Select().from(UserClass.class).where(UserClass_Table.type.eq(2)).queryList(); //setTittleList(); adapter.setData(requestUsers); nowPositionList=-1; countChecked=0; } private ContentObserver observer = new ContentObserver(new Handler()){ @Override public void onChange(boolean selfChange){ super.onChange(selfChange); refreshData(); } }; private void deleteRequest(int idReq) { Bundle bundle = new Bundle(); bundle.putInt(DescribeLoader.OPERATION_KEY, DescribeLoader.DELETE_REQUEST); bundle.putInt(DescribeLoader.IDDEPEND_KEY, idReq); getLoaderManager().initLoader(DescribeLoader.DESCRIBE_LOADER, bundle, this); } private void succesRequest(int idReq) { Bundle bundle = new Bundle(); bundle.putInt(DescribeLoader.OPERATION_KEY, DescribeLoader.UPDATE_REQUEST); bundle.putInt(DescribeLoader.IDDEPEND_KEY, idReq); bundle.putInt(DescribeLoader.STATUS_KEY, 1); getLoaderManager().initLoader(DescribeLoader.DESCRIBE_LOADER, bundle, this); } private DescribeRecyclerAdapter.DescribeClickListener rvClickListener = new DescribeRecyclerAdapter.DescribeClickListener() { @Override public void onNoteClick(final int position){ //Log.d("rvRequest", "YES"); AlertDialog.Builder adb = new AlertDialog.Builder(getContext()); adb.setTitle(getString(R.string.request_frg_dlg_tittle)) .setPositiveButton(R.string.request_frg_dlg_done,new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { succesRequest(requestUsers.get(position).getId()); //Toast.makeText(getContext(),"id="+id+" position="+position, Toast.LENGTH_LONG).show(); } }) .setNegativeButton(getString(R.string.request_frg_dlg_del), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { deleteRequest(requestUsers.get(position).getId()); //deleteRequest(id); } }) .setNeutralButton(getString(R.string.request_frg_dlg_wait), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }) .setMessage(getString(R.string.request_frg_dlg_message)); adb.create().show(); } @Override public void onNoteLongClick(int position){ Log.d("rvRequest", "YES2"); } }; /* @Override public void onYesClicked(DialogFragment dialog, String dataDescribe) { Toast.makeText(view.getContext(), dataDescribe, Toast.LENGTH_LONG).show(); int idDescribe = Integer.valueOf(dataDescribe); if(idDescribe>0) { Bundle bundle = new Bundle(); bundle.putInt(DescribeLoader.IDDEPEND_KEY, idDescribe); bundle.putInt(DescribeLoader.STATUS_KEY, 0); bundle.putInt(DescribeLoader.OPERATION_KEY, DescribeLoader.NEW_DESCRIBE); getLoaderManager().initLoader(DescribeLoader.NEW_DESCRIBE, bundle, this); } } @Override public void onNoClicked(DialogFragment dialog) { }*/ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { progressBar.setVisibility(View.VISIBLE); switch (id) { case MapActivity.LOADER_USERS: return new UserLoader(view.getContext(), args); case DescribeLoader.DESCRIBE_LOADER: return new DescribeLoader(view.getContext(), args); /*case DescribeLoader.NEW_DESCRIBE: return new DescribeLoader(view.getContext(), args);*/ default: return null; } } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { int id = loader.getId(); if (id == MapActivity.LOADER_USERS || id == DescribeLoader.DESCRIBE_LOADER) { if (data != null) { requestUsers = DataBase.getRequestUsers(); } setRecyclerView(); } progressBar.setVisibility(View.GONE); getLoaderManager().destroyLoader(id); EventBus.getDefault().post(new MessageEvent(REQUEST_LOAD_COMPLETE, REQUEST_LOAD_COMPL_CODE, requestUsers.size())); } @Override public void onLoaderReset(Loader<Cursor> loader) { } }
true
86b1d153677040c66cb695115809542f365f7bcf
Java
Perstraube/GoogleMaps
/main/java/com/contairnes/apix/myapplication/MapsActivity.java
UTF-8
4,833
2.3125
2
[]
no_license
package com.contairnes.apix.myapplication; import android.graphics.Bitmap; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnStreetViewPanoramaReadyCallback; import com.google.android.gms.maps.StreetViewPanorama; import com.google.android.gms.maps.StreetViewPanoramaFragment; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements OnStreetViewPanoramaReadyCallback { private GoogleMap mMap; // Might be null if Google Play services APK is not available. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); StreetViewPanoramaFragment streetViewPanoramaFragment = (StreetViewPanoramaFragment) getFragmentManager() .findFragmentById(R.id.map); streetViewPanoramaFragment.getStreetViewPanoramaAsync(this); //setUpMapIfNeeded(); } @Override protected void onResume() { super.onResume(); // setUpMapIfNeeded(); } /** * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly * installed) and the map has not already been instantiated.. This will ensure that we only ever * call {@link #setUpMap()} once when {@link #mMap} is not null. * <p/> * If it isn't installed {@link SupportMapFragment} (and * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to * install/update the Google Play services APK on their device. * <p/> * A user can return to this FragmentActivity after following the prompt and correctly * installing/updating/enabling the Google Play services. Since the FragmentActivity may not * have been completely destroyed during this process (it is likely that it would only be * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this * method in {@link #onResume()} to guarantee that it will be called. */ private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } /** * This is where we can add markers or lines, add listeners or move the camera. In this case, we * just add a marker near Africa. * <p/> * This should only be called once and when we are sure that {@link #mMap} is not null. */ private void setUpMap() { CameraPosition cameraPosition = new CameraPosition.Builder() .target(new LatLng(14.8419148,-91.5181611)) .zoom(15) .bearing(0) .tilt(45) .build(); mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); mMap.addMarker( new MarkerOptions() .position(new LatLng(14.8419148, -91.5181611)) .title("Estadio Mario Camposeco") .icon(BitmapDescriptorFactory.fromResource(R.drawable.camposeco))); mMap.addMarker( new MarkerOptions() .position(new LatLng(14.8461823, -91.5345213)) .title("Templo Minerva Quetzaltenango") .icon(BitmapDescriptorFactory.fromResource(R.drawable.minerva))); mMap.addMarker( new MarkerOptions() .position(new LatLng(14.8347431, -91.520614)) .title("Pasaje Enriquez") .icon(BitmapDescriptorFactory.fromResource(R.drawable.enrique))); mMap.addMarker( new MarkerOptions() .position(new LatLng(14.8333329, -91.5087762)) .title("Cerro el Baul") .icon(BitmapDescriptorFactory.fromResource(R.drawable.baul))); } @Override public void onStreetViewPanoramaReady(StreetViewPanorama streetViewPanorama) { streetViewPanorama.setPosition(new LatLng(-33.87365,151.20688)); } }
true
209f04a9f719f1224d7d3e7227722ab944e4e824
Java
charlyecarlos/ControlPrivacy
/src/services/ServiceStatistics_index.java
UTF-8
2,174
2.375
2
[]
no_license
package services; import java.util.ArrayList; import java.util.List; import daos.TransactionManager; import daos.MySQL.MySQL_Statistics_indexDAO; import domain.Canvas_files; import domain.Statistics_index; import exceptions.DAOException; import exceptions.ServiceException; public class ServiceStatistics_index { public List<Statistics_index> readStatisticsUser() throws ServiceException { TransactionManager trans = new TransactionManager(); List<Statistics_index> statisticsIndex=new ArrayList<Statistics_index>(); try{ MySQL_Statistics_indexDAO daosStatistics=trans.getStatistics_indexDAO(); statisticsIndex=daosStatistics.readStatisticsUser(); trans.closeCommit(); }catch(DAOException e){ trans.closeRollback(); if (e.getCause() == null) throw new ServiceException(e.getMessage()); //Logical error else throw new ServiceException(e.getMessage(), e); //Internal error } return statisticsIndex; } public List<Statistics_index> readStatistics(String module) throws ServiceException { TransactionManager trans = new TransactionManager(); List<Statistics_index> statisticsIndex=new ArrayList<Statistics_index>(); try{ MySQL_Statistics_indexDAO daosStatistics=trans.getStatistics_indexDAO(); statisticsIndex=daosStatistics.readStatistics(module); trans.closeCommit(); }catch(DAOException e){ trans.closeRollback(); if (e.getCause() == null) throw new ServiceException(e.getMessage()); //Logical error else throw new ServiceException(e.getMessage(), e); //Internal error } return statisticsIndex; } public List<Canvas_files> readTypeFiles() throws ServiceException { TransactionManager trans = new TransactionManager(); List<Canvas_files> typeFiles=new ArrayList<Canvas_files>(); try{ MySQL_Statistics_indexDAO daosStatistics=trans.getStatistics_indexDAO(); typeFiles=daosStatistics.readTypeFiles(); trans.closeCommit(); }catch(DAOException e){ trans.closeRollback(); if (e.getCause() == null) throw new ServiceException(e.getMessage()); //Logical error else throw new ServiceException(e.getMessage(), e); //Internal error } return typeFiles; } }
true
03e597b1e493cff355dad96f0c325cdfee2164f8
Java
gerdb/sailsimulator
/com.sebulli.sailsimulator/src/SailSimulator.java
UTF-8
8,799
2.609375
3
[]
no_license
/* * * SailSimulator - Free Invoicing Software * Copyright (C) 2010 Gerd Bartelt * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import javax.swing.Box; import javax.swing.JApplet; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** * Sail Simulator Applet * * @author Gerd Bartelt */ public class SailSimulator extends JApplet implements ActionListener { private static final long serialVersionUID = -6566441023625011779L; // The timer animating the simulation and the simulation private Timer timer; private Simulation simulation = new Simulation(); // The main panel private JPanel mainPanel; //the applet's ocean pane private Ocean ocean; // The control panel private JPanel controlPanel; // The controls of the control panel private JSlider rudderSlider ; private JSlider sailRopeSlider ; private JSlider windDirectionSlider ; private JSlider windSpeedSlider ; private Compass compass; private Earth earth; private Roll roll; private JTextField windDirection; private JTextField windSpeed; private int calm = 0; /** * Create the GUI. For thread safety, this method should * be invoked from the event-dispatching thread. */ private void createGUI() { // Create the main panel mainPanel = new JPanel (null); setContentPane(mainPanel); // Create the ocean ocean = new Ocean(this); ocean.setBounds(0, 0, 500, 500); // Create the control panel controlPanel = new JPanel (null); //controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.PAGE_AXIS)); controlPanel.setBounds(500, 0, 300, 500); // Create the compass compass = new Compass(this); compass.setLocation(0, 2); controlPanel.add(compass); // Create the wind direction slider windDirectionSlider = new JSlider(JSlider.VERTICAL, -360, 360, 0); windDirectionSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { simulation.setWindDirection(((double)windDirectionSlider.getValue())/ 180 * Math.PI); } }); windDirectionSlider.setBounds(126, 5, 20, 123); controlPanel.add(windDirectionSlider); // Create the wind speed slider windSpeedSlider = new JSlider(JSlider.VERTICAL, 0, 30, 5); windSpeedSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { simulation.setWindSpeed(((double)windSpeedSlider.getValue())); } }); windSpeedSlider.setBounds(148, 5, 20, 123); controlPanel.add(windSpeedSlider); Font labelFont = new Font("Serif", Font.BOLD, 11); Font textFielFont = new Font("Serif", Font.BOLD, 18); // Field with the wind direction JLabel labelWindDirection = new JLabel("Wind direction:"); labelWindDirection.setFont(labelFont); labelWindDirection.setBounds(170, 5, 128, 20); controlPanel.add(labelWindDirection); windDirection = new JTextField(); windDirection.setEditable(false); windDirection.setFont(textFielFont); windDirection.setHorizontalAlignment(JTextField.RIGHT); windDirection.setBounds(170, 25, 128, 25); controlPanel.add(windDirection); // Field with the wind speed JLabel labelWindSpeed = new JLabel("Wind speed:"); labelWindSpeed.setFont(labelFont); labelWindSpeed.setBounds(170, 55, 128, 20); controlPanel.add(labelWindSpeed); windSpeed = new JTextField(); windSpeed.setEditable(false); windSpeed.setFont(textFielFont); windSpeed.setHorizontalAlignment(JTextField.RIGHT); windSpeed.setBounds(170, 75, 128, 25); controlPanel.add(windSpeed); // Create the earth control earth = new Earth(this); earth.setLocation(5,150); controlPanel.add(earth); // Create the roll instrument roll = new Roll(this); roll.setLocation(0,350); controlPanel.add(roll); // Create the components of the control panel JLabel label = new JLabel("Rudder Position:"); controlPanel.add(label); controlPanel.add(Box.createRigidArea(new Dimension(0,5))); // Create the rudder slider rudderSlider = new JSlider(JSlider.HORIZONTAL, -100, 100, 0); rudderSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { simulation.setRudder(((double)rudderSlider.getValue())*0.01); } }); rudderSlider.setBounds(0, 478, 275, 20); controlPanel.add(rudderSlider); // Create the sail rope slider sailRopeSlider = new JSlider(JSlider.VERTICAL, 0, 100, 50); sailRopeSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { simulation.setSailRope(((double)sailRopeSlider.getValue())*0.01); } }); sailRopeSlider.setBounds(275, 400, 20, 95); controlPanel.add(sailRopeSlider); // Add the ocean and the control panel to the mainPanel mainPanel.add(ocean); mainPanel.add(controlPanel); } /** * Called when this applet is loaded into the browser */ public void init() { // Execute a job on the event-dispatching thread: // Creating this applet's GUI. try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { createGUI(); } }); } catch (Exception e) { System.err.println("createGUI didn't successfully complete"); } // Set up timer to drive simulation events timer = new Timer(20, this); timer.start(); } /** * Perform the 20ms timer event */ public void actionPerformed(ActionEvent e) { // Do the simulation simulation.simulate(); // Update the components with the values of the simulation updateComponents(); // Redraw all mainPanel.repaint(); } /** * Start the applet */ public void start() { timer.restart(); } /** * Stop the applet */ public void stop() { timer.stop(); } /** * Update all components with the simulation results */ public void updateComponents() { ocean.setBoat_x(simulation.getBoat_x()); ocean.setBoat_y(simulation.getBoat_y()); ocean.setBoat_direction(simulation.getBoat_direction()); ocean.setBoat_rudder(simulation.getBoat_rudder()); ocean.setSail_angle(simulation.getSailAngle()); ocean.setCoord_north(simulation.getCoordNorth()); ocean.setCoord_east(simulation.getCoordEast()); ocean.setSailWind_angle(simulation.getSailWind_angle()); compass.setWindDirection(simulation.getWind_direction()); earth.setCoordinates(simulation.getCoordNorth(), simulation.getCoordEast()); roll.setRollAngle(simulation.getRoll_angle()); // Update these components every 20ms x 25 = 400ms calm ++; if (calm == 25) { calm = 0; DecimalFormat df = new DecimalFormat ( "0" ); windDirection.setText(df.format(simulation.getWind_direction() * 180/Math.PI) + "°"); df = new DecimalFormat ( "0.0" ); windSpeed.setText(df.format(simulation.getWind_speed()) + "m/s"); } } /** * The applet information. */ public String getAppletInfo() { return "Title: Sail Simulator v0.1, 2010-12-22\n" + "Author: Gerd Bartelt\n" + "Simulates a sail boat."; } }
true
4c34fe3c6f7bc6d9f23d563fcef4b2fbc9e17ad7
Java
theMoreTheBetter/copyneo4jaction
/chapter10/server/src/main/java/com/manning/neo4jia/chapter10/JFriendGraphHelper.java
UTF-8
1,013
2.625
3
[]
no_license
package com.manning.neo4jia.chapter10; import org.neo4j.graphdb.DynamicRelationshipType; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * */ public class JFriendGraphHelper { public static RelationshipType IS_FRIEND_OF = DynamicRelationshipType.withName("IS_FRIEND_OF"); public static List<String> extractJFriendNamesFromRawAPI(Node node) { if (node == null) { throw new IllegalArgumentException("Node cannot be null"); } List<String> names = new ArrayList<String>(); for (Relationship rel: node.getRelationships(IS_FRIEND_OF)) { Node friendNode = rel.getOtherNode(node); String friendName = (String)friendNode.getProperty("name","unknown"); if (friendName.startsWith("J")) { names.add(friendName); } } return names; } }
true
4e14dadf98a06462abf79ae48222a87ecb6d337d
Java
wils0651/cs321_BTree
/cs321_BTree/GeneBankParser.java
UTF-8
3,761
3.09375
3
[]
no_license
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class GeneBankParser { private static final String START_TAG = "ORIGIN"; private static final String END_TAG = "//"; private static final List<Character> VALID_CHARS = Arrays.asList('a', 'A', 't', 'T', 'c', 'C', 'g', 'G', 'n', 'N'); private static final List<Character> DELIMITERS = Arrays.asList('n', 'N'); public List<String> parseSequencesFromFileContents(String fileContents) { List<String> sequences = new ArrayList<>(); int startIndex = fileContents.indexOf(START_TAG); while (startIndex > -1) { int endIndex = fileContents.indexOf(END_TAG, startIndex); if (endIndex == -1) { throw new IllegalStateException("Could not find closing tag for starting tag index of: " + startIndex); } String content = fileContents.substring(startIndex + START_TAG.length(), endIndex); StringBuilder fullSequenceBuilder = new StringBuilder(); for (char c : content.toCharArray()) { if (VALID_CHARS.contains(c)) { fullSequenceBuilder.append(Character.toLowerCase(c)); } } String fullSequence = fullSequenceBuilder.toString(); for(String subSequence : fullSequence.split("[nN]")){ if(!subSequence.isEmpty()){ sequences.add(subSequence); } } startIndex = fileContents.indexOf(START_TAG, endIndex); } return sequences; } public List<String> generateSubSequencesFromSequence(String sequence, int subSequenceLength){ List<String> subSequences = new ArrayList<>(); if((sequence == null) || sequence.isEmpty()){ return subSequences; } for(int i = 0; i <= sequence.length() - subSequenceLength; i++){ subSequences.add(sequence.substring(i, i + subSequenceLength)); } return subSequences; } public long convertSequenceToLong(String sequence){ long value = 0L; for(int i = 0; i < sequence.length(); i++){ char c = sequence.charAt(i); switch(c){ case 'a': case 'A': value *= 2; value *= 2; break; case 'c': case 'C': value *= 2; value *= 2; value++; break; case 'g': case 'G': value *= 2; value++; value *= 2; break; case 't': case 'T': value *= 2; value++; value *= 2; value++; break; } } return value; } public String convertLongToSequence(long value, int sequenceLength){ String sequence = ""; while(value > 0){ boolean leftMostBit = ((value % 2) == 1); value /= 2; boolean rightMostBit = ((value % 2) == 1); value /= 2; if(leftMostBit && rightMostBit){ sequence += "t"; } else if (leftMostBit){ sequence += "c"; } else if (rightMostBit){ sequence += "g"; } else { sequence += "a"; } } for(int i = sequence.length(); i < sequenceLength; i++){ sequence += 'a'; } return new StringBuilder(sequence).reverse().toString(); } }
true
5f4ce03d1353175b52788a231fd60339c7141e8e
Java
ldj8683/javaBasic
/java10/src/arrayApplication/MovieReservation.java
UTF-8
2,124
3.453125
3
[]
no_license
package arrayApplication; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class MovieReservation { public static void main(String[] args) { JFrame f = new JFrame(); f.setSize(1000, 450); //flowlayout : 물 흐르듯이 순서대로 배치를 해주는 부품 필요 FlowLayout flow = new FlowLayout(); f.setLayout(flow); int[] seat = new int[200]; for (int i = 0; i < 200; i++) { JButton b = new JButton(); b.setText(i + ""); f.add(b); b.setBackground(Color.yellow); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("버튼을 눌렀군요!"); b.setBackground(Color.red); System.out.println("좌석번호는 " + b.getText()); // 좌석 번호가 seat배열의 index 역할! => int int index = Integer.parseInt(b.getText()); // 배열의 각 index값이 0인 경우 : 예매가 안 된 상황이라고 가정 // 배열의 각 index값이 1인 경우 : 예매가 된 상황이라고 가정 seat[index] = 1; //seat[100] = 1 -> 클릭한 인덱스가 1이 된다 -> 그 1이 된 자리만 예매가 된 상황이라 생각하면 된다. b.setEnabled(false);//클릭기능을 막음 } }); } JButton b2 = new JButton(); b2.setText("결제하기"); f.add(b2); b2.setBackground(Color.green); b2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int count = 0; String seatNo = " "; // seat배열에 있는 값을 하나씩 가져와서, 각 값이 1인 경우 // 예매가 된 자리입니다를 프린트! for (int i = 0; i < seat.length; i++) { if(seat[i] == 1) { seatNo = seatNo + i + " "; count++; } } System.out.println(seatNo + ">> 예매된 자리입니다."); System.out.println("결제금액은 " + count * 10000 + "원"); } }); f.setVisible(true); } }
true
19bc33e99dbbd3133ea50ba14542fd18d493845b
Java
kenjoel/blog
/src/main/java/models/Departments.java
UTF-8
3,414
2.90625
3
[ "MIT" ]
permissive
//package models; // //import java.util.Objects; // //public class Departments { // // private int id; // private String name; // private String description; // private int size; // // public Departments(String name, String description, int size) { // this.name = name; // this.description = description; // this.size = size; // } // // public void setName (String name) { // this.name = name; // } // // public void setDescription (String description) { // this.description = description; // } // // public void setId (int id) { // this.id = id; // } // // public void setSize (int size) { // this.size = size; // } // // public String getName () { // return name; // } // // public String getDescription () { // return description; // } // // public int getId () { // return id; // } // // public int getSize () { // return size; // } // // @Override // public boolean equals (Object o) { // if (this == o) // return true; // if (o == null || getClass () != o.getClass ()) // return false; // Departments that = (Departments) o; // return id == that.id && // size == that.size && // Objects.equals (name, that.name) && // Objects.equals (description, that.description); // } // // @Override // public int hashCode () { // return Objects.hash (name, description, id, size); // } //} package models; import java.util.Objects; public class Departments { private int id; private String name; private String about; private String phone; private String email; public Departments(String name, String about) { this.name = name; this.about = about; this.phone = "no phone listed"; this.email = "no email available"; } public Departments(String name, String about, String website, String email) { this.name = name; this.about = about; this.phone = website; this.email = email; } //override equals n hashcode @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Departments)) return false; Departments that = (Departments) o; return id == that.id && Objects.equals(name, that.name) && Objects.equals(about, that.about) && Objects.equals(phone, that.phone) && Objects.equals(email, that.email); } @Override public int hashCode() { return Objects.hash(name, about, phone, email, id); } ///Getters public String getName() { return name; } public String getAbout() { return about; } public String getWebsite() { return phone; } public String getEmail() { return email; } public int getId() { return id; } //Setters public void setName(String name) { this.name = name; } public void setAbout(String about) { this.about = about; } public void setWebsite(String website) { this.phone = website; } public void setEmail(String email) { this.email = email; } public void setId(int id) { this.id = id; } }
true
ff7f1651b782eccdfe39d19c2fe101fc708cec31
Java
flywind2/joeis
/src/irvine/oeis/a149/A149287.java
UTF-8
580
2.34375
2
[]
no_license
package irvine.oeis.a149; // Generated by gen_seq4.pl walk23 3 5 1 221200012121110 at 2019-07-08 22:06 // DO NOT EDIT here! import irvine.oeis.WalkCubeSequence; /** * A149287 Number of walks within <code>N^3</code> (the first octant of <code>Z^3)</code> starting at <code>(0,0,0)</code> and consisting of n steps taken from <code>{(-1, -1, 1), (-1, 0, 0), (0, 1, -1), (1, -1, 1), (1, 1, 0)}</code>. * @author Georg Fischer */ public class A149287 extends WalkCubeSequence { /** Construct the sequence. */ public A149287() { super(0, 3, 5, "", 1, "221200012121110"); } }
true
330d1731ac2db8cf11bae8c4eaceda74c64d77bb
Java
luizrenato2012/algamoney-app
/algamoney-api/src/main/java/com/algaworks/algamoney/api/util/CadastroSenha.java
UTF-8
315
1.859375
2
[]
no_license
package com.algaworks.algamoney.api.util; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class CadastroSenha { public static void main(String[] args) { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); System.out.println(encoder.encode("email")); } }
true
5b3940c9d8c3d736b9db7420ec3f4d7512133db2
Java
abraham-aiby/BuffaloCartProject
/src/main/java/Utils/Screenshots.java
UTF-8
640
2.40625
2
[]
no_license
package Utils; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; public class Screenshots { static WebDriver driver; public void takeScreenshots(String Filename, WebDriver driver) { File file = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(file, new File("C:\\Users\\Aiby\\eclipse-workspaceA\\BuffaloCart\\src\\main\\resources\\ScreenshotsFolder" +Filename+".jpg")); } catch(IOException e) { e.printStackTrace(); } }}
true
f90ab042dd1d5bbda70978cc80b4331ee6143692
Java
onomatofobia/basics
/Game/src/pl/com/bottega/cwiczeniowe/collections/TreeNode.java
UTF-8
331
2.6875
3
[]
no_license
package pl.com.bottega.cwiczeniowe.collections; import java.util.List; public interface TreeNode<E> { // dodaje element jako dziecko węzła void add(TreeNode<E> child); // zwraca listę dzieci tego węzła List<TreeNode<E>> children(); // zwraca element przechowywany w tym węźle E element(); }
true
b7e809a61bfa708a81d27644941608363e682aa9
Java
datcoind/VideoMaker-1
/app/src/main/java/com/cliffex/videomaker/videoeditor/introvd/template/p310g/C7363e.java
UTF-8
1,528
1.53125
2
[]
no_license
package com.introvd.template.p310g; import android.databinding.C0170e; import android.databinding.ViewDataBinding; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.introvd.template.app.community.freeze.FreezeReasonPage.C3760a; import com.introvd.template.xyui.RoundedTextView; /* renamed from: com.introvd.template.g.e */ public abstract class C7363e extends ViewDataBinding { protected String bDa; public final ImageView btnBack; public final RoundedTextView coR; public final ImageView coS; public final RelativeLayout coT; public final TextView coU; public final TextView coV; public final TextView coW; protected C3760a coX; protected boolean coY; protected C7363e(C0170e eVar, View view, int i, ImageView imageView, RoundedTextView roundedTextView, ImageView imageView2, RelativeLayout relativeLayout, TextView textView, TextView textView2, TextView textView3) { super(eVar, view, i); this.btnBack = imageView; this.coR = roundedTextView; this.coS = imageView2; this.coT = relativeLayout; this.coU = textView; this.coV = textView2; this.coW = textView3; } /* renamed from: a */ public abstract void mo31993a(C3760a aVar); /* renamed from: dJ */ public abstract void mo31994dJ(boolean z); public String getAuid() { return this.bDa; } public abstract void setAuid(String str); }
true
d3220eb2a18e42d6806e1e323f0c4d053993b075
Java
SamAllen83/bartender
/bartender-api/src/main/java/com/bevbot/bartender/api/drink/DrinkOrderCreatedEvent.java
UTF-8
939
2.34375
2
[]
no_license
package com.bevbot.bartender.api.drink; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; public class DrinkOrderCreatedEvent implements DrinkOrderEvent { private Money orderTotal; private String customerName; private String drinkName; @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } public DrinkOrderCreatedEvent() { } public DrinkOrderCreatedEvent(String customerName, String drinkName, Money orderTotal) { this.customerName = customerName; this.orderTotal = orderTotal; this.drinkName = drinkName; } public Money getOrderTotal() { return orderTotal; } public String getCustomerName() { return customerName; } public String getDrinkName() { return drinkName; } }
true
9831216e68158d9eee14b8ea9741c310bebaa076
Java
tpodgornaya/tpodgornaya
/src/main/java/com/playtika/automation/hello/arr5.java
UTF-8
380
2.921875
3
[]
no_license
package com.playtika.automation.hello; public class arr5 { public static void main(String[] args) { int[] numArr = {5, 4, 3, 2, 1}; int minNumber = 100; for (int i = 0; i < numArr.length; i++) { if (minNumber > numArr[i]) { minNumber = numArr[i]; } } System.out.println(minNumber); } }
true
e509bc9fc18a15b98a696e82280db406550f6d02
Java
alittleboyww/NCU-OA
/oa-admin/src/main/java/com/ncu/oa/admin/pojo/ResultObject.java
UTF-8
468
1.960938
2
[]
no_license
package com.ncu.oa.admin.pojo; import lombok.Data; import java.io.Serializable; /** * Created with IDEA * author:G.B.Monkey * Date:2019/10/23 0023 * Time:19:06 */ @Data public class ResultObject implements Serializable { //响应码 private int code; //返回信息 private String message; public ResultObject(){ } public ResultObject(int code, String message) { this.code = code; this.message = message; } }
true
0771f0bf7be9e1679d4b979ae6c41303df988ef1
Java
StephenPWalker/Main
/n5_practical3/src/n5_practical3/Consumer.java
UTF-8
323
2.78125
3
[]
no_license
package n5_practical3; public class Consumer extends Thread { MyQueue mq; public Consumer(MyQueue m) { mq=m; } public void run() { try { while(true) { mq.Consume(); Thread.sleep(500); } } catch(InterruptedException e) { e.printStackTrace(); } } }
true
8dbb373840503f5555e33079c21f64bea494ce00
Java
randyzhuzhiwei/Threads
/src/listenThread.java
UTF-8
793
3.203125
3
[]
no_license
import java.time.LocalDateTime; public class listenThread extends Thread { //reference to data object private testData data; public listenThread(testData data){ //set reference to data object this.data=data; } //called when .start() public void run() { while(true) { try { //this thread "delay" for 1 second sleep(1000); LocalDateTime ldt = LocalDateTime.now(); //print out time System.out.println(ldt); //increase the data object's i value data.increaseI(); } catch (InterruptedException e) { System.out.println(e); } } } }
true
ea16aff61f7942904f0ef31397b6ad95aa6dfff8
Java
ljnk975/k.barrier
/src/k/barrier/model/IDraw.java
UTF-8
251
2.265625
2
[]
no_license
package k.barrier.model; import java.awt.Graphics2D; /** * Interface allow drawing in 2D graphics * * @author ljnk975 * */ public interface IDraw { /** * Draw function * @param g graphics context */ public void draw(Graphics2D g); }
true
a5cb7e8ef0de1aaf9ca746215e3b8a938c1b8c13
Java
myk972/projets
/Java/CityCourses/web-app/src/entities/User.java
UTF-8
571
2.09375
2
[]
no_license
package entities; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; import java.util.List; /** * Created by marc on 26/02/2014. */ @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @NotEmpty @Column (nullable = false) private String firstName; @NotEmpty @Column (nullable = false) private String lastName; @NotEmpty @Column (nullable = false, unique = true) private String email; @OneToMany private List<Quizz> passedQuizzes; }
true
73f2fe6a8dab71eedc1bac38b026c68e9ad7659a
Java
alevohin/JavaTorrent
/bittorrent-tracker-udp/src/test/java/org/johnnei/javatorrent/internal/tracker/udp/ScrapeRequestTest.java
UTF-8
4,522
2.28125
2
[ "Apache-2.0" ]
permissive
package org.johnnei.javatorrent.internal.tracker.udp; import java.time.Clock; import java.util.Collections; import java.util.Optional; import org.junit.jupiter.api.Test; import org.johnnei.javatorrent.bittorrent.tracker.TorrentInfo; import org.johnnei.javatorrent.bittorrent.tracker.TrackerException; import org.johnnei.javatorrent.network.InStream; import org.johnnei.javatorrent.network.OutStream; import org.johnnei.javatorrent.test.DummyEntity; import org.johnnei.javatorrent.torrent.Torrent; import org.johnnei.javatorrent.tracker.UdpTracker; import static java.util.Arrays.asList; import static org.johnnei.javatorrent.test.TestUtils.copySection; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ScrapeRequestTest { @Test public void testWriteRequest() { Torrent torrentOne = DummyEntity.createUniqueTorrent(); Torrent torrentTwo = DummyEntity.createUniqueTorrent(torrentOne); Torrent torrentThree = DummyEntity.createUniqueTorrent(torrentOne, torrentTwo); byte[] expectedOutput = new byte[60]; copySection(torrentOne.getMetadata().getHash(), expectedOutput, 0); copySection(torrentTwo.getMetadata().getHash(), expectedOutput, 20); copySection(torrentThree.getMetadata().getHash(), expectedOutput, 40); ScrapeRequest request = new ScrapeRequest(asList(torrentOne, torrentTwo, torrentThree)); OutStream outStream = new OutStream(); request.writeRequest(outStream); byte[] actual = outStream.toByteArray(); assertEquals(expectedOutput.length, actual.length, "Unexpected request length"); assertArrayEquals(expectedOutput, actual, "Incorrect output"); } @Test public void testReadAndProcessRequest() throws Exception { Torrent torrentOne = DummyEntity.createUniqueTorrent(); Torrent torrentTwo = DummyEntity.createUniqueTorrent(); Torrent torrentThree = DummyEntity.createUniqueTorrent(); TorrentInfo infoOne = new TorrentInfo(torrentOne, Clock.systemDefaultZone()); TorrentInfo infoTwo = new TorrentInfo(torrentThree, Clock.systemDefaultZone()); byte[] inputBytes = { // Torrent one 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, // Torrent two 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, // Torrent three 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, }; ScrapeRequest request = new ScrapeRequest(asList(torrentOne, torrentTwo, torrentThree)); InStream inStream = new InStream(inputBytes); UdpTracker trackerMock = mock(UdpTracker.class); when(trackerMock.getInfo(eq(torrentOne))).thenReturn(Optional.of(infoOne)); when(trackerMock.getInfo(eq(torrentTwo))).thenReturn(Optional.empty()); when(trackerMock.getInfo(eq(torrentThree))).thenReturn(Optional.of(infoTwo)); request.readResponse(inStream); request.process(trackerMock); assertEquals(1, infoOne.getSeeders(), "Incorrect seeders"); assertEquals("2", infoOne.getDownloadCount(), "Incorrect download count"); assertEquals(3, infoOne.getLeechers(), "Incorrect leechers"); assertEquals(7, infoTwo.getSeeders(), "Incorrect seeders"); assertEquals("8", infoTwo.getDownloadCount(), "Incorrect download count"); assertEquals(9, infoTwo.getLeechers(), "Incorrect leechers"); } @Test public void testReadAndProcessBrokenRequest() throws Exception { Torrent torrentOne = DummyEntity.createUniqueTorrent(); Torrent torrentTwo = DummyEntity.createUniqueTorrent(); Torrent torrentThree = DummyEntity.createUniqueTorrent(); byte[] inputBytes = { // Torrent one 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, // Torrent two 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, // Torrent three 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, }; ScrapeRequest request = new ScrapeRequest(asList(torrentOne, torrentTwo, torrentThree)); InStream inStream = new InStream(inputBytes); assertThrows(TrackerException.class, () -> request.readResponse(inStream)); } @Test public void testMinimalSize() { ScrapeRequest request = new ScrapeRequest(Collections.emptyList()); assertEquals(0, request.getMinimalSize(), "Incorrect minimal size."); } }
true
b631d7eec801d6bd38a5d932c4432c4bb9a08be8
Java
ravishahprojects/gekkostate
/Jeel/src/tabbedpane.java
UTF-8
852
2.796875
3
[]
no_license
import java.awt.*; import javax.swing.*; /* <APPLET CODE = tabbedpane.class WIDTH = 550 HEIGHT = 200 > </APPLET> */ public class tabbedpane extends JApplet { public void init() { Container contentPane = getContentPane(); JTabbedPane jtabbedpane = new JTabbedPane(); JPanel jpanel1 = new JPanel(); JPanel jpanel2 = new JPanel(); JPanel jpanel3 = new JPanel(); jpanel1.add(new JLabel("This is panel 1")); jpanel2.add(new JLabel("This is panel 2")); jpanel3.add(new JLabel("This is panel 3")); jtabbedpane.addTab("Tab 1", new ImageIcon("tabb.jpg"), jpanel1, "This is tab 1"); jtabbedpane.addTab("Tab 2", new ImageIcon("tabb.jpg"), jpanel2, "This is tab 2"); jtabbedpane.addTab("Tab three", new ImageIcon("tabb.jpg"), jpanel3, "This is tab 3"); contentPane.setLayout(new BorderLayout()); contentPane.add(jtabbedpane); } }
true
4bb3657b20391a38502e679e15759ba368fac81d
Java
kdk-pkg-soft/freehep-ncolor-pdf
/hepio/freehep-rootio/src/main/java/hep/io/root/daemon/xrootd/RemoveOperation.java
UTF-8
331
1.992188
2
[]
no_license
package hep.io.root.daemon.xrootd; import hep.io.root.daemon.xrootd.Callback.DefaultCallback; /** * Remove (delete) a file. * @author tonyj */ class RemoveOperation extends Operation<Void> { RemoveOperation(String path) { super("remove", new Message(XrootdProtocol.kXR_rm, path),new DefaultCallback()); } }
true
75766c5efec88041be18f9872be71acb3e649e0d
Java
ZhangYouYu0/Xx
/app/src/main/java/com/example/ceshi1/Back/Back.java
UTF-8
158
1.882813
2
[]
no_license
package com.example.ceshi1.Back; import com.example.ceshi1.Bean.FoodBean; public interface Back { void sj(FoodBean foodBean); void yc(String yc); }
true
bd92870a9b2b2e07c5b75c1a125428f23d728acf
Java
miarevalo10/ReporteReddit
/reddit-decompilada/com/twitter/sdk/android/core/internal/VineCardUtils.java
UTF-8
2,686
2.03125
2
[]
no_license
package com.twitter.sdk.android.core.internal; import com.twitter.sdk.android.core.models.Card; import com.twitter.sdk.android.core.models.ImageValue; import com.twitter.sdk.android.core.models.UserValue; public class VineCardUtils { public static boolean m25864a(Card card) { return (("player".equals(card.f24027b) || "vine".equals(card.f24027b)) && m25869f(card) != null) ? true : null; } private static boolean m25869f(com.twitter.sdk.android.core.models.Card r5) { /* JADX: method processing error */ /* Error: java.lang.NullPointerException at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.searchTryCatchDominators(ProcessTryCatchRegions.java:75) at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.process(ProcessTryCatchRegions.java:45) at jadx.core.dex.visitors.regions.RegionMakerVisitor.postProcessRegions(RegionMakerVisitor.java:63) at jadx.core.dex.visitors.regions.RegionMakerVisitor.visit(RegionMakerVisitor.java:58) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:31) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:17) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:306) at jadx.api.JavaClass.decompile(JavaClass.java:62) at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:199) */ /* r5 = r5.f24026a; r0 = "site"; r5 = r5.m25889a(r0); r5 = (com.twitter.sdk.android.core.models.UserValue) r5; r0 = 0; if (r5 == 0) goto L_0x001d; L_0x000d: r5 = r5.f24110a; Catch:{ NumberFormatException -> 0x001c } r1 = java.lang.Long.parseLong(r5); Catch:{ NumberFormatException -> 0x001c } r3 = 586671909; // 0x22f7e725 float:6.719422E-18 double:2.898544356E-315; r5 = (r1 > r3 ? 1 : (r1 == r3 ? 0 : -1)); if (r5 != 0) goto L_0x001d; L_0x001a: r5 = 1; return r5; L_0x001c: return r0; L_0x001d: return r0; */ throw new UnsupportedOperationException("Method not decompiled: com.twitter.sdk.android.core.internal.VineCardUtils.f(com.twitter.sdk.android.core.models.Card):boolean"); } public static String m25865b(Card card) { return ((UserValue) card.f24026a.m25889a("site")).f24110a; } public static String m25866c(Card card) { return (String) card.f24026a.m25889a("player_stream_url"); } public static String m25867d(Card card) { return (String) card.f24026a.m25889a("card_url"); } public static ImageValue m25868e(Card card) { return (ImageValue) card.f24026a.m25889a("player_image"); } }
true
e35ace0ae0611fb6705b4a8ec45f4968ba7d568e
Java
Michael-Z/heads-up-poker
/src/Validation/src/main/java/com/saccarn/poker/betpassvalues/BetPassValuesTest5.java
UTF-8
325
1.890625
2
[]
no_license
package com.saccarn.poker.betpassvalues; import com.saccarn.poker.ai.betpassdeterminer.BetPassActionValues; /** * Created by Neil on 25/04/2017. */ public class BetPassValuesTest5 extends BetPassActionValues { public double getBet2Const() { return 0.7; } /* Leave the rest of values as default*/ }
true
b3a18f55b8b28c48c90c11a0b92b1ccd27cde4d1
Java
michaeman/ShadowWing
/src/.svn/text-base/Item.java.svn-base
UTF-8
945
3.375
3
[]
no_license
import org.newdawn.slick.SlickException; import org.newdawn.slick.Image; /** Item class that extends GameObject */ public abstract class Item extends GameObject { public boolean drawItem = true; /** Constructor for item * * @param x * @param y * @param imageFile * @throws SlickException */ public Item(double x, double y, String imageFile) throws SlickException { super(x,y,imageFile); this.x = x; this.y = y; this.image = new Image(imageFile); } /** method that detects if player is touching an item * * @param player */ public void isPickedUp(Player player){ if(Math.abs(this.x - player.getX()) < MISSILEY && Math.abs(this.y - player.getY()) < MISSILEY && this.drawItem == true){ this.drawItem = false; this.pickup(player); } } /** Method that determines the effects to do to player, handled in individual classes * @ * @param player */ public abstract void pickup(Player player); }
true
e43e35ce78a5386f6ebdb646b15e143fbf070f2b
Java
scrollmember/androidscroll
/src/jp/ac/tokushima_u/is/ll/io/NotifyJsonHandler.java
UTF-8
998
2.046875
2
[]
no_license
package jp.ac.tokushima_u.is.ll.io; import java.util.ArrayList; import java.util.List; import jp.ac.tokushima_u.is.ll.provider.LearningLogContract; import jp.ac.tokushima_u.is.ll.util.JsonNotifyUtil; import jp.ac.tokushima_u.is.ll.util.JsonQuizUtil; import jp.ac.tokushima_u.is.ll.util.Lists; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; public class NotifyJsonHandler extends JsonHandler { private Context context; public NotifyJsonHandler(Context context) { super(LearningLogContract.CONTENT_AUTHORITY); this.context = context; } public ArrayList<ContentProviderOperation> parse(ContentResolver resolver) { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); List<ContentValues> cvs = JsonNotifyUtil.searchToUpdateNotifys(resolver); for(ContentValues cv:cvs){ batch.addAll(JsonNotifyUtil.update(context, cv)); } return batch; } }
true
4b24b34a32578e799ca82ae583600aefb2032a35
Java
andrewrohde/JavaBall
/src/main/java/com/madwin/JavaBall/GameTimer.java
UTF-8
1,779
2.765625
3
[]
no_license
package com.madwin.JavaBall; import java.awt.Color; import java.util.Formatter; import java.util.Locale; import java.util.concurrent.TimeUnit; import javax.swing.JTextPane; import javax.swing.UIDefaults; import javax.swing.border.LineBorder; import org.apache.commons.lang3.time.StopWatch; public class GameTimer extends JTextPane { private static final long serialVersionUID = 1L; boolean running = false; StopWatch sw = new StopWatch(); Thread timer = new Thread(new Runnable() { @Override public void run() { StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb, Locale.US); while (running) { sb.delete(0, sb.length()); Long time = sw.getNanoTime(); long min = TimeUnit.MINUTES.convert(sw.getNanoTime(), TimeUnit.NANOSECONDS); long sec = TimeUnit.SECONDS.convert(time, TimeUnit.NANOSECONDS) % 60; long msec = TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS) % 60; formatter.format("Time: %02d:%02d.%02d", min,sec,msec); setText(sb.toString()); try { Thread.sleep(10); } catch (InterruptedException e) {e.printStackTrace();} } formatter.close(); } }); public GameTimer() { setText("Time: 00:00.00"); Color color = Color.WHITE; UIDefaults defaults = new UIDefaults(); defaults.put("TextPane[Enabled].backgroundPainter", color); putClientProperty("Nimbus.Overrides", defaults); putClientProperty("Nimbus.Overrides.InheritDefaults", true); setBorder(new LineBorder(color, 3)); setBackground(color); } public void startTimer() { running = true; sw.start(); timer.run(); } public void stopTimer() { running = false; sw.stop(); timer = null; } }
true
71c9cd325240ba7660e1f91bb9639969758877cf
Java
SII-Codelab-Chaos/Codelab-Chaos-TP
/TP1-fusiion-gestion-competences/src/test/java/fr/sii/atlantique/fusiion/fusiion_gestion_competences/TestCompetenceRepository.java
UTF-8
4,135
2.078125
2
[ "MIT" ]
permissive
package fr.sii.atlantique.fusiion.fusiion_gestion_competences; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import fr.sii.atlantique.fusiion.fusiion_gestion_competences.domain.Collaborateur; import fr.sii.atlantique.fusiion.fusiion_gestion_competences.domain.Competence; import fr.sii.atlantique.fusiion.fusiion_gestion_competences.domain.CompetentSur; import fr.sii.atlantique.fusiion.fusiion_gestion_competences.repositories.CollaborateurRepository; import fr.sii.atlantique.fusiion.fusiion_gestion_competences.repositories.CompetenceRepository; import fr.sii.atlantique.fusiion.fusiion_gestion_competences.repositories.CompetentSurRepository; @RunWith(SpringRunner.class) @SpringBootTest(classes = GestionCompetencesApplication.class) @DataNeo4jTest//permet, entre autre, de réinitialiser la base à chaque test public class TestCompetenceRepository { @Autowired CompetenceRepository competenceRepository; @Autowired CollaborateurRepository collaborateurRepository; @Autowired CompetentSurRepository competentSurRepository; Competence competence = new Competence("aktest", "nomtest", "desctest", true, false); Competence competence2 = new Competence("aktest2", "nomtest2", "desctest2", false, true); @Test public void testFindByNomFind() { competenceRepository.save(competence); competenceRepository.save(competence2); List<Competence> result = (competenceRepository.findByNom("nomtest")); assertTrue(result.size() == 1); } @Test public void testFindByNomNotFind() { competenceRepository.save(competence2); List<Competence> result = (competenceRepository.findByNom("nomtest")); assertTrue(result.size() == 0); } @Test public void testFindByAkCompetenceFind() { competenceRepository.save(competence); competenceRepository.save(competence2); Optional<Competence> result = (competenceRepository.findOneByAkCompetence("aktest")); assertTrue(competence.equals(result.get())); } @Test public void testFindByAkCompetenceNotFind() { competenceRepository.save(competence2); Optional<Competence> result = (competenceRepository.findOneByAkCompetence("aktest")); assertTrue(!result.isPresent()); } @Test public void testFindLikeCompetenceFindOne() { competenceRepository.save(competence); competenceRepository.save(competence2); List<Competence> result = (competenceRepository.findLikeCompetence("nomtest2")); assertTrue(result.size() ==1); } @Test public void testFindLikeCompetenceFindTwo() { competenceRepository.save(competence); competenceRepository.save(competence2); List<Competence> result = (competenceRepository.findLikeCompetence("nom.*")); assertTrue(result.size() ==2); } @Test public void testDeleteCompetenceAndRelation() { competenceRepository.save(competence); competenceRepository.save(competence2); Collaborateur collaborateur = new Collaborateur("akcollab"); collaborateurRepository.save(collaborateur); LocalDateTime date = LocalDateTime.now(); CompetentSur relation = new CompetentSur(collaborateur, competence, date, 3, false); CompetentSur relation2 = new CompetentSur(collaborateur, competence, date, 1, true); competentSurRepository.save(relation); competentSurRepository.save(relation2); competenceRepository.deleteCompetenceAndRelation(competence.getAkCompetence()); assertFalse((competenceRepository.findOneByAkCompetence(competence.getAkCompetence())).isPresent()); assertTrue((competentSurRepository.findByAkCollaborateur(collaborateur.getAkCollaborateur())).count() ==0); assertTrue((collaborateurRepository.findOneByAkCollaborateur(collaborateur.getAkCollaborateur())).isPresent()); } }
true
a5d23425bed70ce659e6c4cbdaaa735a09c87f06
Java
happy6eve/ve_np
/itemcenter/.svn/pristine/04/0489b88096d61f2d305a6b8675ebdabf5a43b403.svn-base
UTF-8
3,704
2.3125
2
[]
no_license
package com.ve.itemcenter.core.manager.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Service; import com.ve.itemcenter.common.constant.DBConst; import com.ve.itemcenter.common.constant.ResCodeNum; import com.ve.itemcenter.common.domain.dto.ItemCommentDTO; import com.ve.itemcenter.common.domain.qto.ItemCommentQTO; import com.ve.itemcenter.core.dao.ItemCommentDAO; import com.ve.itemcenter.core.domain.ItemCommentDO; import com.ve.itemcenter.core.exception.ItemException; import com.ve.itemcenter.core.manager.ItemCommentManager; import com.ve.itemcenter.core.util.ExceptionUtil; import com.ve.itemcenter.core.util.ItemUtil; @Service public class ItemCommentManagerImpl implements ItemCommentManager { @Resource private ItemCommentDAO itemCommentDAO; @Override public ItemCommentDTO addItemComment(ItemCommentDTO itemCommentDTO) throws ItemException { try { if (itemCommentDTO == null) { throw ExceptionUtil.getException(ResCodeNum.PARAM_E_MISSING, "itemCommentDTO property incorrect"); } verifyItemCommentDTOProperty(itemCommentDTO);// 验证参数 ItemCommentDO itemCommentDO = new ItemCommentDO(); ItemUtil.copyProperties(itemCommentDTO, itemCommentDO);// DTO转DO long newInsertedId = itemCommentDAO.addItemComment(itemCommentDO);// 新增的记录返回的ID long sellerId = itemCommentDTO.getSellerId();// 供应商ID return getItemComment(newInsertedId, sellerId);// 新增加的记录对应的itemCommentDTO } catch (Exception e) { throw new ItemException(ResCodeNum.SYS_E_DEFAULT_ERROR, e); } } public ItemCommentDTO getItemComment(Long id, Long sellerId) throws ItemException { ItemCommentDO itemCommentDO = itemCommentDAO.getItemComment(id, sellerId); if (itemCommentDO == null) { throw ExceptionUtil .getException(ResCodeNum.BASE_PARAM_E_RECORD_NOT_EXIST, "requested record doesn't exist from table item_comment-->id:" + id); } ItemCommentDTO itemCommentDTO = new ItemCommentDTO(); ItemUtil.copyProperties(itemCommentDO, itemCommentDTO);// DO转DTO return itemCommentDTO; } @Override public boolean deleteItemComment(Long id, Long sellerId) throws ItemException { // TODO 校验sellerId ,id ItemCommentDO itemCommentDO = new ItemCommentDO(); itemCommentDO.setId(id); itemCommentDO.setSellerId(sellerId); itemCommentDO.setIsDeleted(DBConst.DELETED.getCode()); int num = itemCommentDAO.deleteItemComment(id, sellerId); if (num > 0) { return true; } else { throw ExceptionUtil .getException(ResCodeNum.SYS_E_DB_DELETE, "requested record doesn't exist from table item_comment-->id:->id:" + id + " sellerId:" + sellerId); } } /** * 验证itemCommentDTO */ private void verifyItemCommentDTOProperty(ItemCommentDTO itemCommentDTO) throws ItemException { // TODO 验证ItemCommentDTO字段属性 // 1.验证订单状状态调用交易接口 // 2.验证供应商ID sellerId // 3.验证用户ID是否合法 if (StringUtils.isBlank(itemCommentDTO.getContent())) { throw ExceptionUtil.getException(ResCodeNum.PARAM_E_MISSING, "itemComment content is null"); } } public List<ItemCommentDTO> queryItemComment(ItemCommentQTO itemCommentQTO) throws ItemException { List<ItemCommentDO> list = itemCommentDAO.queryItemCommentByItemId(itemCommentQTO); List<ItemCommentDTO> DTOList = new ArrayList<ItemCommentDTO>(); for (ItemCommentDO itemCommentDO : list) { ItemCommentDTO itemCommentDTO = new ItemCommentDTO(); ItemUtil.copyProperties(itemCommentDO, itemCommentDTO); DTOList.add(itemCommentDTO); } return DTOList; } }
true
68dbb8bf7884c1a10d37e321b757abf6da6d04ba
Java
raybiju/Organisation-Management
/UserDetails.java
UTF-8
1,520
2.390625
2
[]
no_license
package com.spring.springrest.entities; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class UserDetails { private long organisationId; @Id private long userid; private String username; private String address; public UserDetails(long organisationId, long userid, String username, String address) { super(); this.organisationId = organisationId; this.userid = userid; this.username = username; this.address = address; } public UserDetails() { super(); } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public long getUserid() { return userid; } public void setUserid(long userid) { this.userid = userid; } public java.lang.String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public long getOrganization_id() { return organisationId; } public void setOrganization_id(long organization_id) { this.organisationId = organization_id; } @Override public String toString() { return "UserDetails{" + "organisation_id=" + organisationId + ", userid=" + userid + ", username='" + username + '\'' + ", address='" + address + '\'' + '}'; } }
true
d559716caa0073de738932b36964a2a6a85f7a15
Java
Antonio-klgtm/EjerRepositorio
/EjerRepositorio/src/Repositorios/Repositorio.java
ISO-8859-1
9,536
3
3
[]
no_license
package Repositorios; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; public class Repositorio extends Application { @Override public void start(Stage stage) { try { GridPane grid = new GridPane(); Button pulsa = new Button("Que dios eres? "); grid.add(pulsa, 0, 0); grid.setAlignment(Pos.CENTER); MenuBar barraMenu = new MenuBar(); //Un cambio para el commit he decidico un menubar que perimta salir // Creamos el menu Menu ayuda = new Menu("Ayuda"); MenuItem cerrar = new MenuItem("Cerrar"); ayuda.getItems().add(cerrar); barraMenu.getMenus().add(ayuda); GridPane.setMargin(barraMenu, new Insets(-350, 0, 0, 0)); grid.getChildren().add(barraMenu); // Ponemos un evento al pulsar sobre cerrar para que cierre la aplicacion cerrar.setOnAction(value -> { stage.close(); }); // ************************si pulsamos el boton saldr un segundo panel con las preguntas pulsa.setOnMouseClicked(value -> { Stage preguntas = new Stage(); VBox vbox = new VBox(); // aqu le aadimos una imagen // vbox.setStyle("-fx-background-image: // url(/Repositorio/src/Repositorios/69.jpg)"); Image image1 = new Image(getClass().getResourceAsStream("69.jpg")); ImageView imageView1 = new ImageView(image1); imageView1.setFitHeight(350.0);// (350.0, 550.0) imageView1.setFitWidth(550.0); ; vbox.getChildren().add(imageView1); // ImageView inicial = new ImageView("/Repositorio/src/Repositorios/69.jpg"); // ************************ponemos la 1 regunta Text texto1 = new Text("La fuerza o la paciencia, " + "cual es mejor herramienta ante un problema?"); vbox.getChildren().add(texto1); // ************************posibles respuestas Button fuerza = new Button("Fuerza "); vbox.getChildren().add(fuerza); Button paciencia = new Button("Paciencia "); vbox.getChildren().add(paciencia); //segundo cambio a realizar aado un boton de cerrar Button cerrar1 = new Button("Salir! "); vbox.getChildren().add(cerrar1); // Ponemos un evento al pulsar sobre cerrar para que cierre la aplicacion cerrar1.setOnAction(valueExit -> { preguntas.close(); }); // ponemos una separacin, para que los elementos no esten pegados vbox.setSpacing(10.0); // centramos el xvox vbox.setAlignment(Pos.CENTER); // Anadimos los nodos vbox.getChildren().addAll(); // Creamos una escena, se la establecemos al stage y lo mostramos Scene Firstask = new Scene(vbox, 800.0, 600.0); preguntas.setScene(Firstask); preguntas.show(); // ELIMINAR----->// ************************si pulsamos el boton cambiara el // panel con las preguntas fuerza.setOnMouseClicked(value1 -> { VBox vbo = new VBox(); // aqu le aadimos una imagen imageView1.setFitHeight(350.0);// (350.0, 550.0) imageView1.setFitWidth(550.0); ; vbo.getChildren().add(imageView1); // ************************ponemos la 2 regunta Text texto2 = new Text( "Eres una persona distrada o mas bien eres una persona segura y dominante?"); vbo.getChildren().add(texto2); // ************************posibles respuestas Button distraida = new Button("Distrada "); vbo.getChildren().add(distraida); Button sd = new Button("Segura y dominante "); vbo.getChildren().add(sd); // ponemos una separacin, para que los elementos no esten pegados vbo.setSpacing(10.0); // centramos el xvox vbo.setAlignment(Pos.CENTER); // Anadimos los nodos vbo.getChildren().addAll(); // Creamos una escena, se la establecemos al stage y lo mostramos Scene Secondask = new Scene(vbo, 800.0, 600.0); preguntas.setScene(Secondask); preguntas.show(); // ************************Dios_Dominante sd.setOnMouseClicked(valueUrano -> { VBox Urrano = new VBox(); Image imagAno = new Image(getClass().getResourceAsStream("Urano.jpg")); ImageView imageVie1 = new ImageView(imagAno); imageVie1.setFitHeight(350.0);// (350.0, 550.0) imageVie1.setFitWidth(550.0); ; Urrano.getChildren().add(imageVie1); // Descripcion del mono preguntas.setTitle("Eres Urano Dios Celeste"); Text GriegoHistorio = new Text("Se lo not ser sabio e inteligente. "); Text GriegoHistorio1 = new Text(" Urano tambin toma todo a la normalidad, " + "aceptando la muerte en manos de su hijo, "); Text GriegoHistorio2 = new Text("pero sabiendo del futuro de su vengador."); Urrano.getChildren().add(GriegoHistorio); Urrano.getChildren().add(GriegoHistorio1); Urrano.getChildren().add(GriegoHistorio2); Urrano.setSpacing(10.0); // centramos el xvox Urrano.setAlignment(Pos.CENTER); Scene Ano = new Scene(Urrano, 800.0, 600.0); preguntas.setScene(Ano); preguntas.show(); }); }); // ************************si pulsamos el boton cambiara el panel con las preguntas paciencia.setOnMouseClicked(value2 -> { VBox vb = new VBox(); // aqu le aadimos una imagen imageView1.setFitHeight(350.0);// (350.0, 550.0) imageView1.setFitWidth(550.0); ; vb.getChildren().add(imageView1); // ************************ponemos la 2 regunta Text texto3 = new Text("Eres una persona energca o una persona tranquila?"); vb.getChildren().add(texto3); // ************************posibles respuestas Button energica = new Button("Energca "); vb.getChildren().add(energica); Button tranquila = new Button("Tranquila "); vb.getChildren().add(tranquila); // ponemos una separacin, para que los elementos no esten pegados vb.setSpacing(10.0); // centramos el xvox vb.setAlignment(Pos.CENTER); // Anadimos los nodos vb.getChildren().addAll(); // Creamos una escena, se la establecemos al stage y lo mostramos Scene Thirdask = new Scene(vb, 800.0, 600.0); preguntas.setScene(Thirdask); preguntas.show(); // ************************Dios_Bastet energica.setOnMouseClicked(valueBastet -> { VBox Basttet = new VBox(); Image imagBast = new Image(getClass().getResourceAsStream("Bastet.jpg")); ImageView imageVie2 = new ImageView(imagBast); imageVie2.setFitHeight(350.0);// (350.0, 550.0) imageVie2.setFitWidth(550.0); ; Basttet.getChildren().add(imageVie2); // Descripcion del mono preguntas.setTitle("Eres Bastet Purr"); Text GatoHistorio = new Text( "Bastet tena una doble personalidad.Por un lado, en su lado ms bondadoso, "); Text GatoHistorio1 = new Text( " ocupa el puesto de guardiana del hogar y protectora de la familia. " + "Adems de ayudar a la fertilidad de las mujeres. "); Text GatoHistorio2 = new Text("Por otro lado, posee un carcter agresivo y violento."); Basttet.getChildren().add(GatoHistorio); Basttet.getChildren().add(GatoHistorio1); Basttet.getChildren().add(GatoHistorio2); Basttet.setSpacing(10.0); // centramos el xvox Basttet.setAlignment(Pos.CENTER); Scene Bas = new Scene(Basttet, 800.0, 600.0); preguntas.setScene(Bas); preguntas.show(); }); // ************************Dios_Frigg tranquila.setOnMouseClicked(valueBastet -> { VBox Friggg = new VBox(); Image imagFrig = new Image(getClass().getResourceAsStream("Frigg.jpg")); ImageView imageVie3 = new ImageView(imagFrig); imageVie3.setFitHeight(350.0);// (350.0, 550.0) imageVie3.setFitWidth(550.0); ; Friggg.getChildren().add(imageVie3); // Descripcion del mono preguntas.setTitle("Eres Frigg Reina del Valhalla"); Text NoruegaHistorica = new Text( "Frigg es descrita como una diosa bella y alta, muy aficionada a las joyas "); Text NoruegaHistorica1 = new Text( "y a los vestidos suntuosos. Se dice que su humor era cambiante, "); Text NoruegaHistorica2 = new Text( "hasta el punto de que se vesta de blanco o negro segn su estado de nimo."); Friggg.getChildren().add(NoruegaHistorica); Friggg.getChildren().add(NoruegaHistorica1); Friggg.getChildren().add(NoruegaHistorica2); Friggg.setSpacing(10.0); // centramos el xvox Friggg.setAlignment(Pos.CENTER); Scene Fri = new Scene(Friggg, 800.0, 600.0); preguntas.setScene(Fri); preguntas.show(); }); }); }); Scene scene = new Scene(grid, 600, 400); stage.setScene(scene); stage.show(); } catch ( Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } }
true
8de69b028ba462ae7890f11f429f35307f6d356b
Java
happyjianguo/finance-hkjf
/finance-vas/finance-vas-dao/src/main/java/com/hongkun/finance/vas/dao/impl/VasVipGrowRecordDaoImpl.java
UTF-8
1,726
1.976563
2
[]
no_license
package com.hongkun.finance.vas.dao.impl; import com.hongkun.finance.vas.constants.VasConstants; import com.hongkun.finance.vas.model.VasVipGrowRecord; import com.hongkun.finance.vas.dao.VasVipGrowRecordDao; import com.yirun.framework.core.annotation.Dao; import com.yirun.framework.dao.mybatis.impl.MyBatisBaseDaoImpl; import java.util.List; import java.util.Map; import java.util.Set; /** * @Project : finance * @Program Name : com.hongkun.finance.vas.dao.impl.VasVipGrowRecordDaoImpl.java * @Class Name : VasVipGrowRecordDaoImpl.java * @Description : GENERATOR DAO实现类 * @Author : generator */ @Dao public class VasVipGrowRecordDaoImpl extends MyBatisBaseDaoImpl<VasVipGrowRecord, Long> implements VasVipGrowRecordDao { @Override public int findUserCurrentGrowValue(int regUserId) { return this.getCurSqlSessionTemplate().selectOne(VasVipGrowRecord.class.getName() + ".findUserCurrentGrowValue", regUserId); } @Override public Map<Integer, VasVipGrowRecord> findUserGrowValueMap(List<Integer> userIdList) { return this.getCurSqlSessionTemplate().selectMap(VasVipGrowRecord.class.getName() + ".findUserGrowValueMap",userIdList,"regUserId"); } @Override public Map<Integer, VasVipGrowRecord> findUserLevelGtZeroMap() { return this.getCurSqlSessionTemplate().selectMap(VasVipGrowRecord.class.getName() + ".findUserLevelGtZero", "regUserId"); } @Override public List<Integer> findUserThreeMonthHasDown(Set<Integer> userIdList) { return this.getCurSqlSessionTemplate().selectList(VasVipGrowRecord.class.getName() + ".findUserThreeMonthHasDown", userIdList); } }
true
43878ae6979d978243d7ccf1ec83c1663abf3e69
Java
OrgSmells/codehaus-mule-git
/trunk/mule-sandbox/tools/benchmark/src/main/java/org/mule/tools/benchmark/Sender.java
UTF-8
4,652
1.921875
2
[]
no_license
/* * $Id: Sender.java 2668 2006-08-10 03:34:44Z holger $ * -------------------------------------------------------------------------------------- * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com * * The software in this package is published under the terms of the BSD style * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.tools.benchmark; import org.mule.MuleException; import org.mule.MuleManager; import org.mule.config.PoolingProfile; import org.mule.config.QueueProfile; import org.mule.config.ThreadingProfile; import org.mule.config.builders.QuickConfigurationBuilder; import org.mule.extras.client.MuleClient; import org.mule.impl.MuleDescriptor; import org.mule.impl.endpoint.MuleEndpointURI; import org.mule.providers.service.ConnectorFactory; import org.mule.umo.UMOException; import org.mule.umo.endpoint.EndpointException; import org.mule.umo.endpoint.UMOEndpoint; import org.mule.umo.endpoint.UMOEndpointURI; import org.mule.umo.manager.UMOManager; import java.util.Arrays; /** * <code>Sender</code> sends messages according to the Runner configuration * * @author <a href="mailto:ross.mason@cubis.co.uk">Ross Mason</a> * @version $Revision: 2668 $ */ public class Sender extends Runner { public static void main(String[] args) { try { Sender sender = new Sender(new RunnerConfig(args)); sender.start(); sender.send(); } catch (Throwable e) { e.printStackTrace(); } } public Sender(RunnerConfig config) throws Exception { super(config); init(); } protected void init() throws UMOException { QuickConfigurationBuilder builder = new QuickConfigurationBuilder(true); builder.setModel(config.getModel()); ThreadingProfile tp = new ThreadingProfile(config.getConnectorThreads(), config.getConnectorThreads(), -1, (byte) 2, null, null); MuleManager.getConfiguration().setMessageReceiverThreadingProfile(tp); MuleManager.getConfiguration().setMessageDispatcherThreadingProfile(tp); UMOManager manager = builder.createStartedManager(config.isSynchronous(), ""); manager.stop(); if (config.getEndpointsArray().length > 1) { int j = 1; String in; String out; String[] endpoints = config.getEndpointsArray(); for (int i = 0; i < endpoints.length - 1; i++) { in = endpoints[i]; if ((i + 1) <= endpoints.length) { out = endpoints[i + 1]; } else { break; } MuleDescriptor d = createDescriptor("benchmark" + j, in, out); builder.registerComponent(d); j++; } } } protected MuleDescriptor createDescriptor(String name, String in, String out) throws EndpointException, MuleException { UMOEndpointURI inbound = null; UMOEndpointURI outbound = null; if (in != null) inbound = new MuleEndpointURI(in); if (out != null) outbound = new MuleEndpointURI(out); MuleDescriptor d = new MuleDescriptor(name); d.setImplementation(BenchmarkComponent.class.getName()); d.setThreadingProfile(new ThreadingProfile(config.getThreads(), config.getThreads(), -1, (byte) 4, null, null)); d.setQueueProfile(new QueueProfile(config.getQueue(), false)); d.setPoolingProfile(new PoolingProfile(config.getThreads(), config.getThreads(), 0, (byte) 2, PoolingProfile.POOL_INITIALISE_ALL_COMPONENTS)); d.setInboundEndpoint(ConnectorFactory.createEndpoint(inbound, UMOEndpoint.ENDPOINT_TYPE_RECEIVER)); if (outbound != null) { d.setOutboundEndpoint(ConnectorFactory.createEndpoint(outbound, UMOEndpoint.ENDPOINT_TYPE_SENDER)); } return d; } public void send() throws UMOException { byte[] msg = new byte[config.getMessageSize()]; Arrays.fill(msg, (byte) 0); String message = new String(msg); MuleClient client = new MuleClient(); String endpoint = config.getEndpointsArray()[0]; System.out.println("Starting sender on : " + endpoint); System.out.println("Message length: " + message.length()); for (int i = 0; i < config.getMessages(); i++) { client.dispatch(endpoint, message, null); count(1); } printReport(); } protected void printReport() { System.out.println("Sent : " + config.getMessages() + " Messages"); } }
true
3c4cfce17c769011cb309f089edd536e6e908014
Java
fernandolopez/remotebot4Android
/ar.edu.unlp.linti.remotebot/src/ar/edu/unlp/linti/remotebot/Setup.java
UTF-8
8,299
2.125
2
[]
no_license
package ar.edu.unlp.linti.remotebot; import java.util.Vector; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import ar.edu.unlp.linti.remotebot.R; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import ar.edu.unlp.linti.robot.Board; import ar.edu.unlp.linti.robot.exceptions.ClientSideException; import ar.edu.unlp.linti.robot.exceptions.RemoteBotException; import ar.edu.unlp.linti.robot.exceptions.ConnectionException; import ar.edu.unlp.linti.robot.exceptions.ServerSideException; import ar.edu.unlp.linti.robot.exceptions.ServerTimeoutException; public class Setup extends Activity { // Defaults //private final String defaultServer = "http://10.0.0.1:8000"; //private final String defaultServer = "http://192.168.1.3:8000"; private final String defaultServer = "http://192.168.1.116:8000"; //private final String defaultServer = "http://192.168.43.210:8000"; private final String defaultDevice = "/dev/ttyUSB0"; private final Integer defaultRobotId = 1; // Parámetros para la otra activity private String server = defaultServer; public String device = defaultDevice; public Integer robotId = defaultRobotId; // Colecciones para los Spinners private Vector<String> devices = new Vector<String>(); private Vector<Integer> robots = new Vector<Integer>(); private Spinner deviceSpinner; private Spinner robotSpinner; private ArrayAdapter<String> devAdapter; private ArrayAdapter<Integer> robAdapter; // Tareas private AsyncTask<String, Object, int[]> deviceTask; private AsyncTask<String, Object, JSONObject> serverTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); toggleActive(R.id.progressBar1, false); toggleActive(R.id.deviceOk, false); toggleActive(R.id.robotOk, false); ((TextView) findViewById(R.id.url)).setText(this.defaultServer); this.deviceSpinner = (Spinner) findViewById(R.id.device); devAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, devices); devAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); this.deviceSpinner.setAdapter(devAdapter); this.robotSpinner = (Spinner) findViewById(R.id.robotId); robAdapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, robots); robAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); this.robotSpinner.setAdapter(robAdapter); this.deviceSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { Setup.this.device = (String) parent.getItemAtPosition(pos); } @Override public void onNothingSelected(AdapterView<?> arg0) {} }); this.robotSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { Setup.this.robotId = (Integer) parent.getItemAtPosition(pos); } @Override public void onNothingSelected(AdapterView<?> arg0) {} }); } private void toggleActive(int id, boolean active){ View v = findViewById(id); if (active) v.setVisibility(View.VISIBLE); else v.setVisibility(View.INVISIBLE); } public void serverOk(View v){ TextView tv = (TextView) findViewById(R.id.url); this.server = tv.getText().toString(); cancelThreads(); this.serverTask = new AsyncTask<String,Object,JSONObject>(){ String error = null; @Override protected void onPreExecute(){ toggleActive(R.id.deviceOk, false); toggleActive(R.id.robotOk, false); toggleActive(R.id.progressBar1, true); } @Override protected JSONObject doInBackground(String... args) { String server = args[0]; JSONObject result = null; try{ result = AndroidBridge.moduleCommand(server, "boards", null); } catch (ClientSideException e) { error = "Error decodificando datos del servidor"; } catch (ServerTimeoutException e) { error = "Timeout intentando conectar con el servidor"; } catch (ServerSideException e) { error = "Error del lado del servidor. " + e.getMessage(); } catch (ConnectionException e) { error = "Error conectando con el servidor.\nVerifique la URL."; } catch (RemoteBotException e) { error = "Error indeterminado al conectarse con el servidor"; } return result; } @Override protected void onPostExecute(JSONObject result){ toggleActive(R.id.progressBar1, false); if (this.error != null){ Util.alert(Setup.this, this.error); return; } try { JSONArray boards = result.getJSONArray("values").getJSONArray(0); //this.devices = new Vector<String>(); Setup.this.devices.clear(); for (int i = 0; i < boards.length(); i++){ Setup.this.devices.add(boards.getString(i)); } Setup.this.devAdapter.notifyDataSetChanged(); if (boards.length() == 0){ Util.alert(Setup.this, "No se encontraron placas XBee conectadas al servidor"); return; } } catch (JSONException e) { Util.alert(Setup.this, "El servidor devolvió un código desconocido"); return; } toggleActive(R.id.deviceOk, true); } }.execute(this.server); } private void cancelThreads(){ if (this.deviceTask != null && !this.deviceTask.isCancelled()){ this.deviceTask.cancel(true); } if (this.serverTask != null && !this.serverTask.isCancelled()){ this.serverTask.cancel(true); } } public void deviceOk(View v) throws RemoteBotException{ this.cancelThreads(); this.deviceTask = new AsyncTask<String,Object,int[]>(){ @Override protected void onPreExecute(){ toggleActive(R.id.progressBar1, true); toggleActive(R.id.robotOk, false); } String error = null; @Override protected int[] doInBackground(String... args) { // Work Board board = null; try { board = new Board(args[0], args[1]); } catch (ServerTimeoutException e) { error = "Timeout intentando conectar con el servidor"; } catch (ServerSideException e) { error = "Error instanciando Board(), verifique que el XBee esté conectado"; } catch (RemoteBotException e) { error = "Error indeterminado comunicandose con el servidor: " + e.toString(); } try { return board.report(); } catch (RemoteBotException e) { int[] def = new int[4]; for (int i = 0; i < 4; i++){ def[i] = i + 1; } return def; } } @Override protected void onPostExecute(int[] robotsArray){ toggleActive(R.id.progressBar1, false); if (error != null){ Util.alert(Setup.this, error); return; } Setup.this.robots.clear(); for (int i = 0; i < robotsArray.length; i++){ Setup.this.robots.add(robotsArray[i]); } if (robotsArray == null || robotsArray.length == 0){ for (int i = 1; i < 5; i++){ Setup.this.robots.add(i); } } Setup.this.robAdapter.notifyDataSetChanged(); toggleActive(R.id.robotOk, true); } }.execute(this.server, this.device); } public void robotOk(View v){ toggleActive(R.id.progressBar1, true); // Work Intent controls = new Intent(this, Controls.class); controls.putExtra("server", this.server); controls.putExtra("device", this.device); controls.putExtra("robotId", this.robotId); this.startActivity(controls); toggleActive(R.id.progressBar1, false); } @Override public void onPause(){ super.onPause(); cancelThreads(); } }
true
3ccb93c41dbfe13f477a883ea54c7379b44d3e43
Java
shahabyunus/urbansentiment
/urban-stmt-ws/src/main/java/org/urbanstmt/analytics/ws/SentimentService.java
UTF-8
5,719
2.15625
2
[]
no_license
package org.urbanstmt.analytics.ws; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang.StringUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.urbanstmt.analytics.exception.AnalyticsServiceBadRequestException; import org.urbanstmt.analytics.model.TermCountRow; import org.urbanstmt.analytics.model.TermCountRow.LonLatPair; import org.urbanstmt.analytics.store.AnalyticsStore; import org.urbanstmt.analytics.store.impl.HBaseAnalyticsStore; import org.urbanstmt.util.ConstantsAndEnums; @Path("/getdata") public class SentimentService { private static final Logger LOG = LoggerFactory .getLogger(SentimentService.class.getName()); private final AnalyticsStore store = new HBaseAnalyticsStore(); private final ThreadLocal<SimpleDateFormat> dateFormatter = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { SimpleDateFormat formatter = new SimpleDateFormat( ConstantsAndEnums.WS_DATE_RANGE_FORMAT); formatter.setLenient(false); return formatter; } }; @SuppressWarnings("unchecked") @GET @Path("{type}") @Produces(MediaType.APPLICATION_JSON) public Response getAnalyticData(@PathParam("type") String type, @QueryParam("stime") String stime, @QueryParam("etime") String etime, @QueryParam("bbox") String bbox) { JSONObject responseParent = new JSONObject(); JSONArray response = new JSONArray(); try { validateDateTimeParams(stime, etime); float[] lonLat = new float[8]; if (bbox != null) { String[] lonLatValues = bbox.split(","); if (lonLatValues.length < 8) { throw new AnalyticsServiceBadRequestException( "Not all 4 pairs (8 values) of lon/lat values provided. 4 set of lon/lat pairs in a comma separated list must be passed in. We got=" + lonLatValues.length + " values."); } try { lonLat[0] = Float.parseFloat(lonLatValues[0]); lonLat[1] = Float.parseFloat(lonLatValues[1]); lonLat[2] = Float.parseFloat(lonLatValues[2]); lonLat[3] = Float.parseFloat(lonLatValues[3]); lonLat[4] = Float.parseFloat(lonLatValues[4]); lonLat[5] = Float.parseFloat(lonLatValues[5]); lonLat[6] = Float.parseFloat(lonLatValues[6]); lonLat[7] = Float.parseFloat(lonLatValues[7]); LOG.info("The requested coords=" + StringUtils.join(lonLatValues)); } catch (NumberFormatException nfe) { throw new AnalyticsServiceBadRequestException( "Invalid float lon/lat values for bounding box provided. What we got=" + lonLatValues); } } else { throw new AnalyticsServiceBadRequestException( "No bounding box values provided. 4 set of lon/lat pairs in a comma separated list must be passed in."); } List<TermCountRow> rows = store.getTermCountResults(stime, etime); LOG.info("Number of records read=" + rows.size()); if (rows != null) { for (TermCountRow r : rows) { List<LonLatPair> lls = r.getLonLats(); if (lls != null) { populateResponses(response, lonLat, r, lls); } } } } catch (Exception ex) { LOG.error("There was an error", ex); if (ex instanceof AnalyticsServiceBadRequestException) { return Response.status(Status.BAD_REQUEST) .entity(ex.getMessage()).build(); } return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(ex.getMessage()).build(); } JSONObject req = new JSONObject(); req.put("type", type); req.put("bbox", bbox); req.put("stime", stime); req.put("etime", etime); responseParent.put("request", req); responseParent.put("response", response); return Response.ok(responseParent.toString()).build(); } private void validateDateTimeParams(String stime, String etime) throws AnalyticsServiceBadRequestException { SimpleDateFormat formatter = dateFormatter.get(); try { Date sdt = formatter.parse(stime); Date edt = formatter.parse(etime); if (sdt.after(edt)) { throw new AnalyticsServiceBadRequestException( "Invalid data parameters provided. Start value is greater than end value. We got the range=[" + sdt + "," + edt + "]"); } } catch (ParseException e) { throw new AnalyticsServiceBadRequestException( "Invalid data parameters provided. They should be in the format=" + ConstantsAndEnums.WS_DATE_RANGE_FORMAT + ". But we got=[" + stime + "," + etime + "]"); } } @SuppressWarnings("unchecked") private void populateResponses(JSONArray response, float[] lonLat, TermCountRow r, List<LonLatPair> lls) { JSONArray regionInfos = new JSONArray(); for (LonLatPair ll : lls) { float lo = ll.getLon(); float la = ll.getLat(); if ((Float.compare(lo, lonLat[0]) <= 0 && Float.compare(la, lonLat[1]) <= 0) && (Float.compare(lo, lonLat[2]) >= 0 && Float.compare(la, lonLat[3]) <= 0) && (Float.compare(lo, lonLat[4]) <= 0 && Float.compare(la, lonLat[5]) >= 0) && (Float.compare(lo, lonLat[6]) >= 0 && Float.compare(la, lonLat[7]) >= 0)) { JSONArray regionInfo = new JSONArray(); regionInfo.add(lo); regionInfo.add(la); regionInfos.add(regionInfo); } } JSONObject res = new JSONObject(); res.put("hour", r.getHour()); res.put("score", r.getScore()); res.put("regions", regionInfos); response.add(res); } }
true
d0382995482acf22648198387efd6c640dde9104
Java
btingle/software-renderer-v1
/src/Game/FreeCam.java
UTF-8
1,339
2.96875
3
[]
no_license
package Game; import Datatypes.Vec2; import Datatypes.Vec3; import Engine.Input; import Engine.Scene.Component; import Engine.Scene.Transform; public class FreeCam extends Component { public float speed; Transform transform; float forwardMovement; float backwardsMovement; public FreeCam(float speed) { this.speed = speed; } @Override protected void Start() { transform = object.getTransform(); forwardMovement = 0; backwardsMovement = 0; } @Override protected void Update() { if (Input.GetKeyDown("W")) { forwardMovement = 1; } if (Input.GetKeyUp("W")) { forwardMovement = 0; } if (Input.GetKeyDown("S")) { backwardsMovement = 1; } if (Input.GetKeyUp("S")) { backwardsMovement = 0; } float movement = (forwardMovement - backwardsMovement) * speed; //System.out.println("movement: " + movement); if (movement != 0) { transform.setLocalPosition( transform.getLocalPosition().add( transform.forward().mul(movement))); } Vec2 mouseMovment = Input.GetMouseDrag(); transform.rotate(new Vec3(mouseMovment.x, 0, mouseMovment.y)); } }
true
34f9596cf7c03449d3d8574cdf0695432b75e8e6
Java
saulocalixto/cs20162-aula04
/exercicios/src/main/java/com/github/saulocalixto/exercicios/RestoDivisao.java
UTF-8
1,166
3.46875
3
[]
no_license
/* * Copyright (c) 2016. Engenharia de Software - Instituto de Informática (UFG) * Creative Commons Attribution 4.0 International License. * Discente : Saulo de Araújo Calixto */ package com.github.saulocalixto.exercicios; /** *Algoritimo retorna o resto da divisão entre dois números. * @author Saulo Calixto */ public final class RestoDivisao { /** * Construtor privado para atender ao checkstyle. */ private RestoDivisao() { //Para atender ao checkstyle } /** * Método para chamar o construtor privado e ter 100% no teste. */ public static void chamarConstrutor() { RestoDivisao resto = new RestoDivisao(); } /** * @param x : Dividendo * @param y : Divisor * @throws IllegalArgumentException se o dividendo for menor ou igual a 0, * ou divisor menor que 0, retorna excessão. * @return : Resto da divisão. */ public static int obterResto(final int x, final int y) { if (y < 0 || x <= 0) { throw new IllegalArgumentException("Número inválido."); } int s = x; while (y <= s) { s -= y; } return (s); } }
true
562d879cfa2c844676292e2b3c1b99daf9abfa04
Java
Gdula/voteApp
/src/main/java/com/gdula/vote/service/exception/SurveyDataInvalid.java
UTF-8
167
1.585938
2
[]
no_license
package com.gdula.vote.service.exception; /** * class: SurveyDataInvalid * Reprezentuje wyjątek ankiety. */ public class SurveyDataInvalid extends Exception { }
true
f34c79c3c08f92cc98f2abe267103a491d3daaf9
Java
wxyBUPT/leetCode.py
/leetcodejava/src/main/java/bupt/wxy/wangyi/Q1/Main.java
UTF-8
774
3.078125
3
[]
no_license
package bupt.wxy.wangyi.Q1; import java.util.Scanner; /** * Created by xiyuanbupt on 8/12/17. */ public class Main { public static void main(String[] args){ int x, f, d, p; Scanner sc = new Scanner(System.in); x = sc.nextInt(); f = sc.nextInt(); d = sc.nextInt(); p = sc.nextInt(); int res = 0; int dayCost = 0; if(f > 0){ dayCost = x; f -= 1; }else { dayCost = x + p; } while (d >= dayCost){ res ++; d -= dayCost; if(f > 0){ dayCost = x; f -= 1; }else { dayCost = x + p; } } System.out.println(res); } }
true
2bcd41b55dac4bcacfed056a09fb83d6aede037f
Java
obhen233/purslane-engine
/src/main/java/com/github/obhen233/out/FeildInfo.java
UTF-8
1,436
2.671875
3
[ "MIT" ]
permissive
package com.github.obhen233.out; import java.io.Serializable; public class FeildInfo implements Serializable,Comparable { private String name; private String simpleName; private String desc; private String lang; private String value; private FieldType fieldType; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getLang() { return lang; } public void setLang(String lang) { this.lang = lang; } public FieldType getFieldType() { return fieldType; } public void setFieldType(FieldType fieldType) { this.fieldType = fieldType; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getSimpleName() { return simpleName; } public void setSimpleName(String simpleName) { this.simpleName = simpleName; } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub if(!(obj instanceof FeildInfo)) return false; return this.name.equals(((FeildInfo)obj).getName()); } @Override public int compareTo(Object obj){ if (!(obj instanceof FeildInfo)) throw new RuntimeException("noy a FeildInfo:"+obj.getClass()); FeildInfo feildInfo = (FeildInfo)obj; return this.name.compareTo(feildInfo.name); } }
true
f6e02375894c2134473a71b8faf22f23676fb985
Java
GIIB/mypolicynow-sdk
/app/src/main/java/com/indicosmic/www/mypolicynow_ags/breakin_app_files/InspectionImageModel.java
UTF-8
2,644
2.125
2
[ "MIT" ]
permissive
package com.indicosmic.www.mypolicynow_ags.breakin_app_files; import android.graphics.Bitmap; /** * Created by Ind3 on 16-01-18. */ public class InspectionImageModel { private String id; private String question; private String is_mand; public String getIs_mand() { return is_mand; } public void setIs_mand(String is_mand) { this.is_mand = is_mand; } private String camera; private Bitmap image; private int listItemPosition; private String imagePath; boolean haveImage; boolean status; private String txtodometer; private String setImage; public InspectionImageModel() { } public InspectionImageModel(String id, String question, String camera, Bitmap image, int listItemPosition, String imagePath, boolean haveImage, boolean status) { this.id = id; this.question = question; this.camera = camera; this.image = image; this.listItemPosition = listItemPosition; this.imagePath = imagePath; this.haveImage = haveImage; this.status = status; } public String getSetImage() { return setImage; } public void setSetImage(String setImage) { this.setImage = setImage; } public String getTxtodometer() { return txtodometer; } public void setTxtodometer(String txtodometer) { this.txtodometer = txtodometer; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getCamera() { return camera; } public void setCamera(String camera) { this.camera = camera; } public Bitmap getImage() { return image; } public void setImage(Bitmap image) { this.image = image; } public int getListItemPosition() { return listItemPosition; } public void setListItemPosition(int listItemPosition) { this.listItemPosition = listItemPosition; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public boolean isHaveImage() { return haveImage; } public void setHaveImage(boolean haveImage) { this.haveImage = haveImage; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } }
true
e671074f0615f6bebefdae9eed368a726e728960
Java
RajathInuganti/IOT-Internet-Of-Things
/Mediator.java
UTF-8
523
1.882813
2
[]
no_license
package ca.uvic.seng330.assn3; import ca.uvic.seng330.assn3.devices.Device; import ca.uvic.seng330.assn3.Client; public interface Mediator { public void unregister(Device device) throws HubRegistrationException; public void unregister(Client client) throws HubRegistrationException; //not in spec, do not test public void register(Device pDevice) throws HubRegistrationException; public void register(Client pClient) throws HubRegistrationException; public void alert(Device pDevice, String pMessage); }
true
c6848cd07fa683a960e13c52163f8887e1f88159
Java
viniciusfernandes/kafka-connector
/src/main/java/br/com/viavarejo/kafkaconnector/connector/KConsumer.java
UTF-8
9,114
2
2
[]
no_license
package br.com.viavarejo.kafkaconnector.connector; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.errors.WakeupException; import org.apache.kafka.common.serialization.Deserializer; import br.com.viavarejo.kafkaconnector.config.SubscriptionConfig; public abstract class KConsumer<K, V, C> { private final List<String> topics = new ArrayList<>(); private String groupId; private SubscriptionConfig config; public KConsumer(final List<String> hosts) { if (hosts == null || hosts.isEmpty()) { throw new IllegalArgumentException("A lista de hosts não pode ser nula ou vazia."); } config.addHosts(hosts); } public KConsumer(final String groupId) { config = new SubscriptionConfig(); this.groupId = groupId; } public String getGroupId() { return groupId; } public KConsumer<K, V, C> addHosts(final List<String> hosts) { config.addHosts(hosts); return this; } public KConsumer<K, V, C> addHost(final String host) { config.addHost(host); return this; } public KConsumer<K, V, C> configStringMessageDeserializer() { config.configStringMessageDeserializer(); return this; } public KConsumer<K, V, C> configStringKeyDeserializer() { config.configStringKeyDeserializer(); return this; } public KConsumer<K, V, C> configLongMessageDeserializer() { config.configLongMessageDeserializer(); return this; } public KConsumer<K, V, C> configLongKeyDeserializer() { config.configLongKeyDeserializer(); return this; } public KConsumer<K, V, C> configDoubleMessageDeserializer() { config.configDoubleMessageDeserializer(); return this; } public KConsumer<K, V, C> configDoubleKeyDeserializer() { config.configDoubleKeyDeserializer(); return this; } public KConsumer<K, V, C> configFloatMessageDeserializer() { config.configFloatMessageDeserializer(); return this; } public KConsumer<K, V, C> configFloatKeyDeserializer() { config.configFloatKeyDeserializer(); return this; } public KConsumer<K, V, C> configIntegerMessageDeserializer() { config.configIntegerMessageDeserializer(); return this; } public KConsumer<K, V, C> configIntegerKeyDeserializer() { config.configIntegerKeyDeserializer(); return this; } public KConsumer<K, V, C> configShortMessageDeserializer() { config.configShortMessageDeserializer(); return this; } public KConsumer<K, V, C> configShortKeyDeserializer() { config.configShortKeyDeserializer(); return this; } public KConsumer<K, V, C> configBytesMessageDeserializer() { config.configBytesMessageDeserializer(); return this; } public KConsumer<K, V, C> configBytesKeyDeserializer() { config.configBytesKeyDeserializer(); return this; } public KConsumer<K, V, C> configCustomKeyDeserializer(final Class<? extends Deserializer<?>> deserializerKeyType) { config.configCustomKeyDeserializer(deserializerKeyType); return this; } public KConsumer<K, V, C> configCustomMessageDeserializer(final Class<? extends Deserializer<?>> deserializerMessageType) { config.configCustomMessageDeserializer(deserializerMessageType); return this; } public KConsumer<K, V, C> configClientId(final String clientId) { config.configClientId(clientId); return this; } public String getClientId() { return config.getClientId(); } public KConsumer<K, V, C> configPollAttempts(final int attempts) { config.configPollAttempts(attempts); return this; } public KConsumer<K, V, C> addTopic(final String topicName) { String topic = null; if (topicName == null) { throw new IllegalArgumentException("O tópico não pode ser nulo"); } topic = topicName.trim(); if (topic.isEmpty()) { throw new IllegalArgumentException("O tópico não pode ser vazio"); } topics.add(topic); return this; } public SubscriptionConfig getConfig() { return config; } public List<String> getTopics() { return topics; } public int getPollAttempts() { return config.getPollAttempts(); } public KConsumer<K, V, C> configMaxNumberMessages(final int maxNumberMessages) { config.configMaxNumberMessages(maxNumberMessages); return this; } public int getMaxNumberMessages() { return config.getMaxNumberMessages(); } public void subscribe(final Consumer<C> callback) { subscribe(callback, null); } public void subscribe(final Consumer<C> callback, final Consumer<C> onError) { if (getGroupId() == null || getGroupId().trim().length() <= 0) { throw new IllegalArgumentException("Falha no consumo das mensagens do kafka. O grupo do consumer não deve ser nulo ou vazio."); } if (getClientId() == null || getClientId().trim().length() <= 0) { throw new IllegalArgumentException( "Falha no consumo das mensagens do kafka. O CLIENT ID do consumer não deve ser nulo ou vazio."); } if (callback == null) { throw new IllegalArgumentException("Falha no consumo das mensagens do kafka. O callback de consumo não pode ser nulo."); } final org.apache.kafka.clients.consumer.Consumer<K, V> kConsumer = parseConsumer(); ConsumerRecords<K, V> records = null; int attempts = getPollAttempts(); final Duration waiting = Duration.ofMillis(100); // eh com esse laco que estamos implementando o mecanismo de heartbeat, // fundamental para comunicar ao group coordinator do kafka que o consumer esta // ativo no grupo, caso contrario o consumer sera marcado como inativo e nao vai // ler as mensagens dos topicos em que esta inscrito. while (--attempts >= 0) { try { records = kConsumer.poll(waiting); } catch (final WakeupException e) { kConsumer.close(); throw new IllegalStateException("Falha na comunicação com o servidor Kafka", e); } if (records.count() > 0) { commitOffset(callback, onError, kConsumer, records); break; } } kConsumer.close(); } public abstract void commitOffset(final Consumer<C> callback, final Consumer<C> onError, final org.apache.kafka.clients.consumer.Consumer<K, V> kConsumer, final ConsumerRecords<K, V> records); private Map<String, Object> createConfigMap(final SubscriptionConfig config, final String groupId) { final Map<String, Object> configMap = new HashMap<>(); configMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, config.appendHosts()); configMap.put(ConsumerConfig.CLIENT_ID_CONFIG, config.getClientId()); configMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, config.getKeyDeserializer()); configMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, config.getMessageDeserializer()); // Estamos fazendo o commit do offset manualmente sempre apos a leitura dos // registros pelo consumer. configMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); // Parametro que define que o consumer ira recuperar as mensagens a partir do offset mais // recente, isto eh, a partir da ultima mensagem recuperada, que pode ser diferente da // ultima mensagem publicada. configMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); // Configurando a que grupo de consumidores o consumer sera incluido. configMap.put("group.id", groupId); configMap.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, config.getMaxNumberMessages()); configMap.put(ConsumerConfig.RECONNECT_BACKOFF_MS_CONFIG, 10000); return configMap; } private org.apache.kafka.clients.consumer.Consumer<K, V> parseConsumer() { addHosts(config.getHosts()); final KafkaConsumer<K, V> kConsumer = new KafkaConsumer<>(createConfigMap(getConfig(), getGroupId())); kConsumer.subscribe(getTopics()); return kConsumer; } }
true
6dfca765eb784f73c4fef8139f71f81a7cc71741
Java
nikolaymishakin/java1
/src/ru/progwards/java1/lessons/bigints/ArrayInteger.java
UTF-8
2,238
3.34375
3
[]
no_license
package ru.progwards.java1.lessons.bigints; import java.math.BigInteger; public class ArrayInteger { byte[] digits; int signif; ArrayInteger() { int n = 10; digits = new byte[n]; clear(n); } ArrayInteger(int n) { digits = new byte[n]; clear(n); } ArrayInteger(String value) { this(); fromString(value); } private void clear() { clear(signif); } private void clear(int count) { for (int i = 0; i < count; i++) digits[i] = 0; signif = 0; } void fromString(String value) { char[] s = value.toCharArray(); int sig = s.length; for (int i = sig - 1, k = 0; i >= 0; i--, k++) { digits[k] = (byte) (s[i] - '0'); } for (int i = sig; i < signif; i++) { digits[i] = 0; } signif = sig; } void fromInt(BigInteger value) { fromString(value.toString()); } BigInteger toInt() { char[] s = new char[signif]; for (int i = signif - 1, k = 0; i >= 0; i--, k++) { s[i] = (char) ((digits[k] + '0') & 0xFF); } return new BigInteger(String.valueOf(s)); } boolean raiseCalcError() { clear(digits.length); return false; } boolean add(ArrayInteger num) { int sigMax = num.signif >= signif ? num.signif : signif; int l = digits.length; int ln = num.digits.length; int p = 0; int r; int sig = 0; for (int i = 0; i <= sigMax; i++) { r = p; if (i < l) r += digits[i]; if (i < ln) r += num.digits[i]; if (r > 0) { sig = i; if (sig >= l) return raiseCalcError(); digits[sig] = (byte) (r % 10); } else { if (i < l) digits[i] = 0; } p = r / 10; } signif = sig + 1; return true; } @Override public String toString() { byte[] r = new byte[signif]; for (int i = signif - 1, k = 0; i >= 0; i--, k++) { r[k] = (byte) (digits[i] + '0'); } return new String(r); } }
true
4dbf7aee4aed5fdc12d69015856ab08d1ecea6ad
Java
jonathanqbo/algorithm
/src/main/java/bq/algorithm/array/TwoSumClosest.java
UTF-8
514
3.078125
3
[]
no_license
package bq.algorithm.array; import java.util.Arrays; public class TwoSumClosest { public int twoSumCloset(int[] nums, int target) { if (nums == null || nums.length < 2) { return -1; } Arrays.sort(nums); int start = 0, end = nums.length - 1; int minDiff = Integer.MAX_VALUE; while (start < end) { int sum = nums[start] + nums[end]; minDiff = Math.min(minDiff, Math.abs(target - sum)); if (sum < target) { start++; } else { end--; } } return minDiff; } }
true
93e11ec58263ecc5fbb13693dd2f941d096fe123
Java
somiya96/seleniumFramework
/src/main/java/pages/ProductPage.java
UTF-8
1,270
1.96875
2
[]
no_license
package pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class ProductPage extends PageBase { public ProductPage(WebDriver driver) { super(driver); } @FindBy(partialLinkText = "Apple MacBook Pro 13-inch") public WebElement prouductNameprop; @FindBy(css = "input.button-2.email-a-friend-button") WebElement emailFreindBtn; @FindBy(id = "price-value-4") public WebElement productPriceLbl; @FindBy(linkText = "Add your review") WebElement addReviewLink; @FindBy(id = "add-to-wishlist-button-4") WebElement wishListBtn; //@FindBy(className = "button-2.add-to-compare-list-button")WebElement addTOCartbtn; @FindBy(id = "add-to-cart-button-4") public WebElement addToCartBtn; public void openSendEmailPage() { clickButton(emailFreindBtn); } public void OpenaddReviewPage() { clickButton(addReviewLink); } public void AddProductToWishList() { clickButton(wishListBtn); } //public void AddCompareProductsPage(){clickButton(addTOComarebtn);} public void AddToCart() { clickButton(addToCartBtn); } }
true
dc6e54a9420e302ca9b7805057d8aa62e2f12aa1
Java
AndreyPavlenko/android-utils
/src/main/java/me/aap/utils/net/http/HttpRequestHandler.java
UTF-8
362
1.953125
2
[]
no_license
package me.aap.utils.net.http; import androidx.annotation.Nullable; import me.aap.utils.async.FutureSupplier; /** * @author Andrey Pavlenko */ public interface HttpRequestHandler { FutureSupplier<?> handleRequest(HttpRequest req); interface Provider { @Nullable HttpRequestHandler getHandler(CharSequence path, HttpMethod method, HttpVersion version); } }
true
e06225108423bee080aa5542a43eda572f90420b
Java
Trickerzgit/s8-SpringPrima
/GodFatherPizza/src/main/java/it/epicode/be/model/PizzaPersonalizzata.java
UTF-8
883
3.0625
3
[]
no_license
package it.epicode.be.model; public class PizzaPersonalizzata implements Pizza{ private Pizza pizza; private Condimento c; public PizzaPersonalizzata(Pizza pizza, Condimento c) { this.pizza = pizza; this.c = c; } @Override public double getCalories() { return pizza.getCalories() + c.getCalories(); } @Override public double getPrice() { return pizza.getPrice() + c.getPrice(); } @Override public String getName() { return pizza.getName() + " e " + c.getName(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MenuItem altro = (MenuItem) obj; if (getName() == null) { if (altro.getName() != null) { return false; } else if (!getName().equals(altro.getName())) return false; } return true; } }
true
b8fc65bc64c346c55a166e045061b9f210ca1e09
Java
phamjoe/java-assignment
/Circle.java
UTF-8
885
3.75
4
[]
no_license
public class Circle extends Shape{ double Pi = 3.14; double radius; public Circle() { this.radius = 0.0; } public Circle(double r) { this.radius = r; } public double getPerimeter(){ double total = 0.0 ; total = 2 * Pi * this.radius ; return total ; } public double getArea(){ double total =0.0 ; total = Pi * this.radius * this.radius ; return total; } @Override public String toString() { return "Circle's radius: " + this.radius + "\n" + "Perimeter of circle " + this.getPerimeter() + "\n" + "Area of circle " + this.getArea() + "\n"; } public boolean equals(Circle obj){ if(this.toString().equals(obj.toString()) == true ) { return true ; } return false ; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
true
7841baaf9c9198d1506245bfc30415771adf4e0f
Java
Glyba98/education
/app/target/generated-sources/openapi/src/main/java/education/app/model/Employee.java
UTF-8
9,154
2.046875
2
[]
no_license
/* * app API * app API documentation * * The version of the OpenAPI document: 0.0.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package education.app.model; import java.util.Objects; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import education.app.model.Department; import education.app.model.Job; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.time.OffsetDateTime; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * Employee */ @JsonPropertyOrder({ Employee.JSON_PROPERTY_DEPARTMENT, Employee.JSON_PROPERTY_EMAIL, Employee.JSON_PROPERTY_FIRST_NAME, Employee.JSON_PROPERTY_HIRE_DATE, Employee.JSON_PROPERTY_ID, Employee.JSON_PROPERTY_JOBS, Employee.JSON_PROPERTY_LAST_NAME, Employee.JSON_PROPERTY_MANAGER, Employee.JSON_PROPERTY_PHONE, Employee.JSON_PROPERTY_SALARY }) @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-09-27T20:18:25.349920400+03:00[Europe/Moscow]") public class Employee implements Serializable { private static final long serialVersionUID = 1L; public static final String JSON_PROPERTY_DEPARTMENT = "department"; private Department department; public static final String JSON_PROPERTY_EMAIL = "email"; private String email; public static final String JSON_PROPERTY_FIRST_NAME = "firstName"; private String firstName; public static final String JSON_PROPERTY_HIRE_DATE = "hireDate"; private OffsetDateTime hireDate; public static final String JSON_PROPERTY_ID = "id"; private Long id; public static final String JSON_PROPERTY_JOBS = "jobs"; private Set<Job> jobs = null; public static final String JSON_PROPERTY_LAST_NAME = "lastName"; private String lastName; public static final String JSON_PROPERTY_MANAGER = "manager"; private Employee manager; public static final String JSON_PROPERTY_PHONE = "phone"; private String phone; public static final String JSON_PROPERTY_SALARY = "salary"; private BigDecimal salary; public Employee department(Department department) { this.department = department; return this; } /** * Get department * @return department **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_DEPARTMENT) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public Employee email(String email) { this.email = email; return this; } /** * Get email * @return email **/ @ApiModelProperty(required = true, value = "") @JsonProperty(JSON_PROPERTY_EMAIL) @JsonInclude(value = JsonInclude.Include.ALWAYS) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Employee firstName(String firstName) { this.firstName = firstName; return this; } /** * Get firstName * @return firstName **/ @ApiModelProperty(required = true, value = "") @JsonProperty(JSON_PROPERTY_FIRST_NAME) @JsonInclude(value = JsonInclude.Include.ALWAYS) public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Employee hireDate(OffsetDateTime hireDate) { this.hireDate = hireDate; return this; } /** * Get hireDate * @return hireDate **/ @ApiModelProperty(required = true, value = "") @JsonProperty(JSON_PROPERTY_HIRE_DATE) @JsonInclude(value = JsonInclude.Include.ALWAYS) public OffsetDateTime getHireDate() { return hireDate; } public void setHireDate(OffsetDateTime hireDate) { this.hireDate = hireDate; } public Employee id(Long id) { this.id = id; return this; } /** * Get id * @return id **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Employee jobs(Set<Job> jobs) { this.jobs = jobs; return this; } public Employee addJobsItem(Job jobsItem) { if (this.jobs == null) { this.jobs = new LinkedHashSet<>(); } this.jobs.add(jobsItem); return this; } /** * Get jobs * @return jobs **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_JOBS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public Set<Job> getJobs() { return jobs; } public void setJobs(Set<Job> jobs) { this.jobs = jobs; } public Employee lastName(String lastName) { this.lastName = lastName; return this; } /** * Get lastName * @return lastName **/ @ApiModelProperty(required = true, value = "") @JsonProperty(JSON_PROPERTY_LAST_NAME) @JsonInclude(value = JsonInclude.Include.ALWAYS) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Employee manager(Employee manager) { this.manager = manager; return this; } /** * Get manager * @return manager **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_MANAGER) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public Employee getManager() { return manager; } public void setManager(Employee manager) { this.manager = manager; } public Employee phone(String phone) { this.phone = phone; return this; } /** * Get phone * @return phone **/ @ApiModelProperty(required = true, value = "") @JsonProperty(JSON_PROPERTY_PHONE) @JsonInclude(value = JsonInclude.Include.ALWAYS) public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Employee salary(BigDecimal salary) { this.salary = salary; return this; } /** * Get salary * @return salary **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_SALARY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public BigDecimal getSalary() { return salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Employee employee = (Employee) o; return Objects.equals(this.department, employee.department) && Objects.equals(this.email, employee.email) && Objects.equals(this.firstName, employee.firstName) && Objects.equals(this.hireDate, employee.hireDate) && Objects.equals(this.id, employee.id) && Objects.equals(this.jobs, employee.jobs) && Objects.equals(this.lastName, employee.lastName) && Objects.equals(this.manager, employee.manager) && Objects.equals(this.phone, employee.phone) && Objects.equals(this.salary, employee.salary); } @Override public int hashCode() { return Objects.hash(department, email, firstName, hireDate, id, jobs, lastName, manager, phone, salary); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Employee {\n"); sb.append(" department: ").append(toIndentedString(department)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); sb.append(" hireDate: ").append(toIndentedString(hireDate)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" jobs: ").append(toIndentedString(jobs)).append("\n"); sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); sb.append(" manager: ").append(toIndentedString(manager)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" salary: ").append(toIndentedString(salary)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
true
c1b5080aeed7d6b053a449519aa3f2c28a237529
Java
vvalitsky/spring-boot-course
/src/main/java/com/vvalitsky/course/service/EmployeeServiceImpl.java
UTF-8
1,283
2.390625
2
[ "Apache-2.0" ]
permissive
package com.vvalitsky.course.service; import com.vvalitsky.course.component.EmployeeConverter; import com.vvalitsky.course.entities.db.Employee; import com.vvalitsky.course.entities.dto.EmployeeDto; import com.vvalitsky.course.repository.EmployeeRepository; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; /** * Created by Vladislav Valitsky at 09.08.2020 */ @Service @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class EmployeeServiceImpl implements EmployeeService { private final EmployeeRepository employeeRepository; private final EmployeeConverter employeeConverter; @Override public List<EmployeeDto> getAllEmployees() { return employeeRepository .findAll() .stream() .map(employeeConverter::convertToEmployeeDto) .collect(Collectors.toList()); } @Override public EmployeeDto createEmployee(EmployeeDto employeeDto) { Employee employee = employeeConverter.convertToEmployee(employeeDto); return employeeConverter.convertToEmployeeDto( employeeRepository.save(employee) ); } }
true
9ad2d3d4a4c725926bac954cd82036bc15fb0019
Java
whataa/Note
/fragment-app/src/main/java/io/whataa/fragmentapp/pagedemo/PageDemoFragment.java
UTF-8
3,100
2.234375
2
[]
no_license
package io.whataa.fragmentapp.pagedemo; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.whataa.fragmentapp.R; import java.text.MessageFormat; import io.whataa.fragmentapp.common.BaseFragment; /** * Created by Summer on 2016/12/25. */ public class PageDemoFragment extends BaseFragment { private int curTab; public static PageDemoFragment newInstance(int curTab) { PageDemoFragment fragment = new PageDemoFragment(); Bundle bundle = new Bundle(); bundle.putInt("DATA", curTab); fragment.setArguments(bundle); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); curTab = getArguments().getInt("DATA"); setHasOptionsMenu(true); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); return inflater.inflate(R.layout.fragment_pagedemo, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); TextView textView = (TextView) view.findViewById(R.id.pagedemo_fragment_txt); textView.setText(MessageFormat.format("this is page {0}", curTab)); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (curTab == 2) { canTwoOwnMenu = !canTwoOwnMenu; setMenuVisibility(canTwoOwnMenu); } } }); } private boolean canTwoOwnMenu; @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (curTab != 2) { setMenuVisibility(isVisibleToUser); } else { setMenuVisibility(false); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { Log.d(getTAG(), "onCreateOptionsMenu: " + menu); menu.clear(); switch (curTab) { case 0: inflater.inflate(R.menu.act_pager_0, menu); break; case 1: inflater.inflate(R.menu.act_pager_1, menu); break; case 2: if (canTwoOwnMenu) { inflater.inflate(R.menu.act_pager_2, menu); } break; case 3: inflater.inflate(R.menu.act_pager_3, menu); break; } } @Override public void onPrepareOptionsMenu(Menu menu) { Log.d(getTAG(), "onPrepareOptionsMenu: " + menu); } }
true
e72eef5592ce927c4d7376154dc4a2352af04414
Java
dotcompany/SISTEMA-ERP-EM-JAVA-GWT-VAADIN
/src/main/java/dc/visao/framework/component/export/PdfExporter.java
UTF-8
1,273
2.203125
2
[]
no_license
package dc.visao.framework.component.export; import com.vaadin.data.Container; import com.vaadin.ui.Table; public class PdfExporter extends Exporter { /** * */ private static final long serialVersionUID = 1L; private TableHolder tableHolder; public PdfExporter() { super(); } public PdfExporter(Table table) { super(table); } public PdfExporter(Container container, Object[] visibleColumns) { super(container, visibleColumns); } public PdfExporter(Container container) { super(container); } @Override protected FileBuilder createFileBuilder(Container container) { return new PdfFileBuilder(container); } @Override protected String getDownloadFileName() { if(downloadFileName == null){ return "exported-pdf.pdf"; } if(downloadFileName.endsWith(".pdf")){ return downloadFileName; }else{ return downloadFileName + ".pdf"; } } public void setWithBorder(boolean withBorder) { ((PdfFileBuilder) fileBuilder).setWithBorder(withBorder); } @Override public void convertTable() { // TODO Auto-generated method stub } @Override public String getFilename() { return getDownloadFileName(); } }
true
b684509627925389625cfbdb60fef9c4616f1f82
Java
jproberto/desafio-grupo-zap
/desafioGrupoZap/src/main/java/br/com/jproberto/desafioGrupoZap/util/Validator.java
UTF-8
460
3.09375
3
[]
no_license
package br.com.jproberto.desafioGrupoZap.util; /** * Classe que faz validações pertinentes à aplicação */ public class Validator { /** * Verifica se a String passada é um número válido * @param string */ public static boolean isNumber(String string) { char[] characters = string.toCharArray(); for (char c : characters) { if (!Character.isDigit(c)) { return false; } } return true; } }
true
01766a1cb23664c85bf09fecfe7cd5ab436f7b25
Java
jacktian/TaiHuWan
/src/com/gloria/slidingmenu/lib/fragment/TrafficFragment.java
UTF-8
2,896
2.109375
2
[]
no_license
package com.gloria.slidingmenu.lib.fragment; import com.gloria.hbh.main.Activity_Main; import com.gloria.hbh.main.Activity_RoutePlan; import com.gloria.hbh.main.R; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; /* * 交通页面 */ @SuppressLint("ValidFragment") public class TrafficFragment extends BaseFragment { String text = "咨讯"; Activity_Main mMain = null; private FrameLayout mFrameLayout = null; public TrafficFragment(String text) { this.text = text; } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); mMain = (Activity_Main) getActivity(); mFrameLayout = (FrameLayout) mMain.findViewById(R.id.content_main); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_traffic, null); setView(view); setListener(); // if(isFirstShow){ // isFirstShow = false; // }else{ // onResume(); // } return view; } private void setView(View view) { titlebar = (LinearLayout) view.findViewById(R.id.titlebar); titlebar.setVisibility(View.VISIBLE); titlebar_name = (TextView) view.findViewById(R.id.titlebar_name); titlebar_left = (Button) view.findViewById(R.id.titlebar_left); titlebar_menu = (Button) view.findViewById(R.id.titlebar_lu); titlebar_menu.setVisibility(View.VISIBLE); titlebar_left.setVisibility(View.INVISIBLE); titlebar_name.setVisibility(View.VISIBLE); titlebar_name.setText("交通信息"); titlebar_name.setTextColor(Color.BLACK); titlebar_menu.setBackgroundResource(R.drawable.titlebtn_bg); titlebar_menu.setPadding(10, 5, 10, 5); titlebar_menu.setText("带我去太湖湾"); titlebar_menu.setTextColor(Color.BLACK); titlebar.setBackgroundResource(R.drawable.top_img); } private void setListener() { titlebar_menu.setOnClickListener(onClickListener); titlebar_left.setOnClickListener(onClickListener); titlebar_name.setOnClickListener(onClickListener); } private OnClickListener onClickListener = new OnClickListener() { public void onClick(View v) { switch (v.getId()) { case R.id.titlebar_lu: goToNavigator(); break; case R.id.titlebar_right: break; } } }; /* * 进入导航页面 */ protected void goToNavigator() { Intent intent = new Intent(); intent.setClass(mMain, Activity_RoutePlan.class); startActivity(intent); } }
true
14abd0cfc4191cf4fc32a2fb44f4b984e4e53b03
Java
paipeng/javaee7-webapplication-startup-project
/src/main/java/com/paipeng/jms/client/NettyJmsClient.java
UTF-8
3,189
2.59375
3
[ "MIT" ]
permissive
package com.paipeng.jms.client; import static org.hornetq.integration.transports.netty.TransportConstants.HOST_PROP_NAME; import static org.hornetq.integration.transports.netty.TransportConstants.PORT_PROP_NAME; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import org.hornetq.api.core.TransportConfiguration; import org.hornetq.core.remoting.impl.netty.NettyConnectorFactory; import org.hornetq.jms.client.HornetQConnectionFactory; import org.hornetq.jms.client.HornetQQueue; public class NettyJmsClient { public static void main(String[] args) { NettyJmsClient bean = new NettyJmsClient(); try { bean.start(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private Connection connection = null; public void start() throws Exception { try { connection = createDefaultConnection(); produceToQueue(connection); consumeFromQueue(connection); } finally { if (connection != null) { connection.close(); } } } protected Connection createDefaultConnection() throws Exception { Map<String, Object> connectionParams = new HashMap<String, Object>(); connectionParams.put(HOST_PROP_NAME, "localhost"); connectionParams.put(PORT_PROP_NAME, 5445); TransportConfiguration transportConfiguration = new TransportConfiguration( NettyConnectorFactory.class.getName(), connectionParams); ConnectionFactory cf = new HornetQConnectionFactory(true, transportConfiguration); Connection connection = cf.createConnection(); return connection; } protected void produceToQueue(Connection connection) throws Exception { Queue queue = new HornetQQueue("QueueOne"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); TextMessage message = session .createTextMessage("This is a text message. Date: " + new Date()); producer.send(message); System.out.println("Sent message: " + message.getText()); session.close(); } protected void consumeFromQueue(Connection connection) throws Exception { Queue queue = new HornetQQueue("ExampleQueue"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer messageConsumer = session.createConsumer(queue); connection.start(); TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived.getText()); session.close(); } }
true
8f0c1e8238feb6825f249ae899d29660589473c2
Java
aerisarn/animdataparser
/src/main/java/org/tes/tools/animdataparser/ProjectAttackBlock.java
UTF-8
1,658
2.46875
2
[]
no_license
package org.tes.tools.animdataparser; import java.util.Scanner; public class ProjectAttackBlock extends BlockObject { String animVersion = "V3"; StringListBlock unkEventList = new StringListBlock(); UnkEventData unkEventData = new UnkEventData(); ClipAttacksBlock attackData = new ClipAttacksBlock(); ClipFilesCRC32Block crc32Data = new ClipFilesCRC32Block(); public StringListBlock getUnkEventList() { return unkEventList; } public void setUnkEventList(StringListBlock unkEventList) { this.unkEventList = unkEventList; } public UnkEventData getUnkEventData() { return unkEventData; } public void setUnkEventData(UnkEventData unkEventData) { this.unkEventData = unkEventData; } public ClipAttacksBlock getAttackData() { return attackData; } public void setAttackData(ClipAttacksBlock attackData) { this.attackData = attackData; } public ClipFilesCRC32Block getCrc32Data() { return crc32Data; } public void setCrc32Data(ClipFilesCRC32Block crc32Data) { this.crc32Data = crc32Data; } @Override public void parseBlock(Scanner input) throws Exception { animVersion = input.nextLine(); unkEventList.fromASCII(input); unkEventData.fromASCII(input); int numAttackBlocks = input.nextInt();input.nextLine(); attackData.blocks = numAttackBlocks; attackData.parseBlock(input); crc32Data.fromASCII(input); } @Override public String getBlock() throws Exception { String out=animVersion+System.lineSeparator(); out+=unkEventList.toASCII(); out+=unkEventData.toASCII(); out+=attackData.blocks+System.lineSeparator(); out+=attackData.getBlock(); out+=crc32Data.toASCII(); return out; } }
true
7146b1099e3f8b49f52a573a36a2c3db0d367cea
Java
yankurk/gocd-guest-login-plugin
/src/main/java/cd/go/authorization/guest/executor/GetAuthorizationServerRedirectUrlExecutor.java
UTF-8
980
2.015625
2
[ "Apache-2.0" ]
permissive
package cd.go.authorization.guest.executor; import cd.go.authorization.guest.model.AuthConfig; import cd.go.authorization.guest.utils.Util; import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import java.util.List; public class GetAuthorizationServerRedirectUrlExecutor { private GoPluginApiRequest request; public GetAuthorizationServerRedirectUrlExecutor(GoPluginApiRequest request) { this.request = request; } public GoPluginApiResponse execute() { final List<AuthConfig> authConfigs = AuthConfig.fromJSONList(request.requestBody()); String serverUrl = authConfigs.get(0).getConfiguration().getServerUrl(); return DefaultGoPluginApiResponse.success(String.format("{\"authorization_server_url\": \"%s/plugin/%s/authenticate\"}", serverUrl, Util.pluginId())); } }
true
512dd3fc0ed1b233061f909fc6d11f3823be438a
Java
openwstcc/androidtcc
/app/src/main/java/edu/fatec/json/JsonResposta.java
UTF-8
2,121
2.09375
2
[]
no_license
package edu.fatec.json; public class JsonResposta { private String criador; private String resposta; private String dataCriacao; private boolean flagCriador; private boolean flagProfessor; private int idResposta; private int rank; private int idUsuario; private int idDuvida; private int usuarioLogado; private boolean deuLike; public String getCriador() { return criador; } public void setCriador(String criador) { this.criador = criador; } public String getResposta() { return resposta; } public void setResposta(String resposta) { this.resposta = resposta; } public String getDataCriacao() { return dataCriacao; } public void setDataCriacao(String dataCriacao) { this.dataCriacao = dataCriacao; } public boolean isFlagCriador() { return flagCriador; } public void setFlagCriador(boolean flagCriador) { this.flagCriador = flagCriador; } public boolean isFlagProfessor() { return flagProfessor; } public void setFlagProfessor(boolean flagProfessor) { this.flagProfessor = flagProfessor; } public int getIdResposta() { return idResposta; } public void setIdResposta(int idResposta) { this.idResposta = idResposta; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } public int getIdUsuario() { return idUsuario; } public void setIdUsuario(int idUsuario) { this.idUsuario = idUsuario; } public int getIdDuvida() { return idDuvida; } public void setIdDuvida(int idDuvida) { this.idDuvida = idDuvida; } public int getUsuarioLogado() { return usuarioLogado; } public void setUsuarioLogado(int usuarioLogado) { this.usuarioLogado = usuarioLogado; } public boolean isDeuLike() { return deuLike; } public void setDeuLike(boolean deuLike) { this.deuLike = deuLike; } }
true
8717409e830227ba28c9809998569c38db3d9587
Java
freelanceapp/Obi
/app/src/main/java/com/obiapp/models/ProductModel.java
UTF-8
7,645
2.09375
2
[]
no_license
package com.obiapp.models; import java.io.Serializable; import java.util.List; public class ProductModel implements Serializable { private int id; private String title; private String desc; private String main_image; private String video; private int user_id; private int category_id; private int sub_category_id; private int price; private int old_price; private String address; private double latitude; private double longitude; private String have_offer; private String offer_type; private int offer_value; private String offer_started_at; private String offer_finished_at; private int rating_value; private String is_shown; private String created_at; private String updated_at; private int time_in_days_from_creating; private String is_favorite; private String is_report; private UserModel.Data user; private Category category; private SubCategory sub_category; private List<ProductImageModel> product_images; private List<ProductDetail> product_details; private GovernorateModel governorate; private ProductType product_type; public int getId() { return id; } public String getTitle() { return title; } public String getDesc() { return desc; } public String getMain_image() { return main_image; } public String getVideo() { return video; } public int getUser_id() { return user_id; } public int getCategory_id() { return category_id; } public int getSub_category_id() { return sub_category_id; } public int getPrice() { return price; } public int getOld_price() { return old_price; } public String getAddress() { return address; } public double getLatitude() { return latitude; } public double getLongitude() { return longitude; } public String getHave_offer() { return have_offer; } public String getOffer_type() { return offer_type; } public int getOffer_value() { return offer_value; } public String getOffer_started_at() { return offer_started_at; } public String getOffer_finished_at() { return offer_finished_at; } public int getRating_value() { return rating_value; } public String getIs_shown() { return is_shown; } public String getCreated_at() { return created_at; } public String getUpdated_at() { return updated_at; } public int getTime_in_days_from_creating() { return time_in_days_from_creating; } public GovernorateModel getGovernorate() { return governorate; } public UserModel.Data getUser() { return user; } public Category getCategory() { return category; } public SubCategory getSub_category() { return sub_category; } public List<ProductImageModel> getProduct_images() { return product_images; } public List<ProductDetail> getProduct_details() { return product_details; } public ProductType getProduct_type() { return product_type; } public String getIs_favorite() { return is_favorite; } public String getIs_report() { return is_report; } public void setIs_favorite(String is_favorite) { this.is_favorite = is_favorite; } public void setIs_report(String is_report) { this.is_report = is_report; } public static class Category implements Serializable { private int id; private String title; private String desc; private String image; private int parent_id; private String level; private String is_shown; private String created_at; private String updated_at; public int getId() { return id; } public String getTitle() { return title; } public String getDesc() { return desc; } public String getImage() { return image; } public int getParent_id() { return parent_id; } public String getLevel() { return level; } public String getIs_shown() { return is_shown; } public String getCreated_at() { return created_at; } public String getUpdated_at() { return updated_at; } } public static class SubCategory implements Serializable { private int id; private String title; private String desc; private String image; private int parent_id; private String level; private String is_shown; private String created_at; private String updated_at; public int getId() { return id; } public String getTitle() { return title; } public String getDesc() { return desc; } public String getImage() { return image; } public int getParent_id() { return parent_id; } public String getLevel() { return level; } public String getIs_shown() { return is_shown; } public String getCreated_at() { return created_at; } public String getUpdated_at() { return updated_at; } } public static class ProductDetail implements Serializable { private int id; private String icon; private String title; private String value; private int product_id; private String created_at; private String updated_at; public int getId() { return id; } public String getIcon() { return icon; } public String getTitle() { return title; } public String getValue() { return value; } public int getProduct_id() { return product_id; } public String getCreated_at() { return created_at; } public String getUpdated_at() { return updated_at; } } public static class Type implements Serializable { private int id; private String title; private String created_at; private String updated_at; public int getId() { return id; } public String getTitle() { return title; } public String getCreated_at() { return created_at; } public String getUpdated_at() { return updated_at; } } public static class ProductType implements Serializable { private int id; private int type_id; private int product_id; private String created_at; private String updated_at; private Type type; public int getId() { return id; } public int getType_id() { return type_id; } public int getProduct_id() { return product_id; } public String getCreated_at() { return created_at; } public String getUpdated_at() { return updated_at; } public Type getType() { return type; } } }
true
87c43f68ea85f5cb9c044599370a8f3752c0cbc1
Java
Aghiles-ramdani/Telecom-Italia-Optimization-project
/Solution src/Heuristic/Move.java
UTF-8
567
3.15625
3
[]
no_license
package Heuristic; public class Move{ int m,t,i,j,c,cu; float cuc; public Move(int m, int t, int i, int j, int c, int cu, float cuc) { super(); this.m = m; this.t = t; this.i = i; this.j = j; this.c = c; //costo per task moltiplicato 100 * numero di task degli utenti di tipo diverso da this.m this.cu=cu; //costo per mossa (arrotondato) this.cuc=cuc; //cost per mossa (non arrotondato) } @Override public boolean equals(Object arg0) { Move x=(Move) arg0; if(x.m==m&&x.t==t&&x.i==i&&x.j==j) return true; return false; } }
true
a06adbf03fdc75ee62a5938da6b12a4afda02a5e
Java
xulifengyanjie/10bao
/10bao1/src/cn/com/twsm/newstopic/service/impl/TopicSelectionServiceImpl.java
UTF-8
560
1.765625
2
[]
no_license
package cn.com.twsm.newstopic.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import cn.com.twsm.newstopic.dao.BaseMapper; import cn.com.twsm.newstopic.dao.TopicSelectionMapper; import cn.com.twsm.newstopic.service.TopicSelectionService; @Service public class TopicSelectionServiceImpl extends BaseServiceImpl implements TopicSelectionService { @Resource private TopicSelectionMapper topicSelectionMapper; @Override public BaseMapper getMapper() { return topicSelectionMapper; } }
true
fe065f8f13b448d9493c5abf8ae288339ecdd911
Java
qntlb/javacourse-2021
/src/main/java/com/andreamazzon/session4/inheritanceandconstructors/sportsmans/Sportsman.java
UTF-8
914
3.59375
4
[]
no_license
package com.andreamazzon.session4.inheritanceandconstructors.sportsmans; import static com.andreamazzon.session3.useful.Print.printn; /** * Parent (or base) class: it has two constructors with different arguments * * @author Andrea Mazzon * */ public class Sportsman { /* * Without defining a default constructor in the base class, we have to * explicitly call a constructor of the base class, giving it the arguments it * needs. This would have been the same if Sportsman had only one constructor * with arguments and no default constructor. */ Sportsman(String name) { printn("I am a sportsman. My name is " + name); } Sportsman(String name, String team) { printn("I am a sportsman. My name is " + name + " and my team is " + team); } /* * try to uncomment it: if you do so, you don't need to explicitly call the * super constructor in the derived class */ // Sportsman() { // } }
true
eb0217a85dd772be0b9dfb3265b6fb992371e5d1
Java
larserikstrand/IMT4904-Master
/Todoity/src/no/hig/strand/lars/todoity/MainActivity.java
UTF-8
9,844
1.757813
2
[]
no_license
package no.hig.strand.lars.todoity; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import no.hig.strand.lars.todoity.services.ContextService; import no.hig.strand.lars.todoity.services.GeofenceService; import no.hig.strand.lars.todoity.utils.Utilities.ErrorDialogFragment; import no.hig.strand.lars.todoity.utils.Utilities.Installation; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.FragmentTransaction; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.DatePicker; import android.widget.ListView; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; public class MainActivity extends FragmentActivity { private TabsPagerAdapter mTabsPagerAdapter; private ViewPager mViewPager; private TasksDb mTasksDb; public static Context mContext; public static boolean isAppVisible; private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; public static final int EDIT_TASK_REQUEST = 2; public static final String TASKS_EXTRA = "no.hig.strand.lars.mtp.TASKS"; public static final String DATE_EXTRA = "no.hig.strand.lars.mtp.DATE"; public static final String RECEIVER_EXTRA = "no.hig.strand.lars.mtp.RECEIVER"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Generate unique installation id on first launch. Installation.id(this); PreferenceManager.setDefaultValues(this, R.xml.preferences, false); SharedPreferences sharedPref = PreferenceManager .getDefaultSharedPreferences(this); String occupationPref = sharedPref.getString( SettingsActivity.PREF_OCCUPATION_KEY, getString(R.string.pref_occupation_default)); if (occupationPref.equals(getString( R.string.pref_occupation_default))) { showWelcomeDialog(); } mContext = this; mTasksDb = TasksDb.getInstance(this); mTabsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mTabsPagerAdapter); setupUI(); } @Override protected void onResume() { super.onResume(); isAppVisible = true; } @Override protected void onPause() { super.onPause(); isAppVisible = false; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: startActivity(new Intent(this, SettingsActivity.class)); return true; case R.id.action_about: startActivity(new Intent(this, AboutActivity.class)); return true; } return super.onOptionsItemSelected(item); } private void showWelcomeDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.dialog_welcome, null); ListView list = (ListView) view.findViewById(R.id.occupation_list); builder.setTitle(getString(R.string.welcome)); builder.setView(view); final AlertDialog dialog = builder.create(); // To make sure the user selects an occupation and to not override the // back button. dialog.setCanceledOnTouchOutside(false); dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { SharedPreferences sharedPref = PreferenceManager .getDefaultSharedPreferences(MainActivity.this); Editor editor = sharedPref.edit(); editor.putString(SettingsActivity.PREF_OCCUPATION_KEY, ((TextView)view).getText().toString()); editor.commit(); dialog.dismiss(); } }); dialog.show(); } private void setupUI() { final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ActionBar.TabListener tabListener = new ActionBar.TabListener() { @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) {} }; actionBar.addTab(actionBar.newTab().setText(R.string.today) .setTabListener(tabListener)); actionBar.addTab(actionBar.newTab().setText(R.string.week) .setTabListener(tabListener)); actionBar.addTab(actionBar.newTab().setText(R.string.all_tasks) .setTabListener(tabListener)); mViewPager.setOnPageChangeListener( new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { getActionBar().setSelectedNavigationItem(position); } }); } public Fragment getActiveFragment(int position) { return getSupportFragmentManager() .findFragmentByTag( "android:switcher:" + R.id.pager + ":" + position); } public void startTask() { if (isServicesAvailable()) { ArrayList<Task> activeTasks = mTasksDb.getActiveTasks(); if (activeTasks.size() <= 1) { Intent intent = new Intent(this, ContextService.class); startService(intent); } } } public void pauseTask() { ArrayList<Task> activeTasks = mTasksDb.getActiveTasks(); if (activeTasks.isEmpty()) { Intent intent = new Intent(this, ContextService.class); stopService(intent); } } public void updateGeofences() { Intent intent = new Intent(this, GeofenceService.class); startService(intent); } private boolean isServicesAvailable() { int resultCode = GooglePlayServicesUtil .isGooglePlayServicesAvailable(this); if (resultCode == ConnectionResult.SUCCESS) { Log.d("Todoity MainActivity", "Google Play Services is available"); return true; } else { Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog( resultCode, this, CONNECTION_FAILURE_RESOLUTION_REQUEST); if (errorDialog != null) { ErrorDialogFragment errorFragment = new ErrorDialogFragment(); errorFragment.setDialog(errorDialog); errorFragment.show(getSupportFragmentManager(), "Location Updates"); } return false; } } @Override protected void onActivityResult( int requestCode, int resultCode, Intent data) { if (requestCode == CONNECTION_FAILURE_RESOLUTION_REQUEST) { if (resultCode == RESULT_OK) { } } super.onActivityResult(requestCode, resultCode, data); } public class TabsPagerAdapter extends FragmentStatePagerAdapter { public TabsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { switch (i) { case 0: return new TodayFragment(); case 1: return new WeekFragment(); case 2: return new AllTasksFragment(); default: return new TodayFragment(); } } @Override public int getCount() { return 3; } } public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); DatePickerDialog dpd = new DatePickerDialog(getActivity(), this, year, month, day); dpd.getDatePicker().setMinDate(c.getTimeInMillis()); return dpd; } @SuppressLint("SimpleDateFormat") @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy"); Calendar c = new GregorianCalendar(year, monthOfYear, dayOfMonth); String date = formatter.format(c.getTime()); Fragment fragment = getTargetFragment(); if (fragment instanceof TodayFragment) { ((TodayFragment)fragment).onDateSet(date); } else if (fragment instanceof WeekFragment) { ((WeekFragment)fragment).onDateSet(date); } else { ((AllTasksFragment)fragment).onDateSet(date); } } } }
true
2c836379558e522b10e92c407c7a4a2af5810200
Java
byeongik11/SpringWebProject
/src/main/java/com/webProject/mvc01/IBoardCUDDao.java
UTF-8
511
1.851563
2
[]
no_license
package com.webProject.mvc01; public interface IBoardCUDDao { BoardInfoDto sltOne(int bodNo); // 단건 조회 int sltMaxNum(); // 글번호 MAX값 조회 //가이드 int insertBoard(BoardInfoDto dtoBoard); //게시글 등록 //그룹 int insertGroupBoard(BoardInfoDto dtoBoard); //게시글 등록 int updateBoard(BoardInfoDto dtoBoard); //게시글 변경 int updateCnt(int cnt); // 조회수 +1 // int deleteBoard(int ctgryNo, int textNo); //게시글 삭제 }
true
a42f0922d46f69a554a792ca527f47cac30d1b56
Java
Innov8FIRST/Innov8RobotCode-2018
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Innov8_Red_Sensor_Calibration.java
UTF-8
4,006
2.703125
3
[ "BSD-3-Clause" ]
permissive
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; @Autonomous(name = "Innov8_Red_Sensor_Calibration", group = "Auto") public class Innov8_Red_Sensor_Calibration extends LinearOpMode { // color sensor test /* Declare OpMode members. */ HardwareInnov8Auto robot = new HardwareInnov8Auto(); // Use a Innov8's hardware /*Declare variables */ double startPositionR = 0; double startPositionL = 0; double endPositionR = 0; double endPositionL = 0; double MID_SERVO = 0.3; // mid position of the servo double START_SERVO = 0; // "down" position of the servo double END_SERVO = 0.9; // "up" position of the servo int Numbers = 0; // how many values have been created int FDrive = 2; int multR = 1; // multiplier used if wheels are positioned or initialized backwards int multL = 1; int[] r = new int[10]; // creates new values for red, green, blue int[] g = new int[10]; int[] b = new int[10]; int Time = 0; // Used to make a timer int ar = 0; // averages of red, green, and blue values from OrangeySensor int ag = 0; int ab = 0; int[] fr = new int[10]; // creates new values for red, green, blue with FruitySensor int[] fg = new int[10]; int[] fb = new int[10]; int far = 0; int fag = 0; int fab = 0; public void runOpMode() throws InterruptedException { robot.init(hardwareMap); waitForStart(); for (Numbers = 0; Numbers < 10; Numbers++) { // getting 10 different readings to put into an array telemetry.addData("blue", robot.OrangeySensor.blue()); telemetry.addData("red", robot.OrangeySensor.red()); telemetry.addData("green", robot.OrangeySensor.green()); telemetry.addData("BlueFruit", robot.FruitySensor.blue()); telemetry.addData("RedFruit", robot.FruitySensor.red()); telemetry.addData("GreenFruit", robot.FruitySensor.green()); r[Numbers] = robot.OrangeySensor.red(); b[Numbers] = robot.OrangeySensor.blue(); g[Numbers] = robot.OrangeySensor.green(); telemetry.addData("number", Numbers); Time = 0; while (opModeIsActive() && Time < 1000) { // timer while telemetry updates telemetry.addData("blue", robot.OrangeySensor.blue()); telemetry.addData("red", robot.OrangeySensor.red()); telemetry.addData("green", robot.OrangeySensor.green()); telemetry.addData("BlueFruit", robot.FruitySensor.blue()); telemetry.addData("RedFruit", robot.FruitySensor.red()); telemetry.addData("GreenFruit", robot.FruitySensor.green()); telemetry.addData("snickersnack", Time); telemetry.update(); Time = Time + 1; } telemetry.update(); } ar = (r[0] + r[1] + r[2] + r[3] + r[4] + r[5] + r[6] + r[7] + r[8] + r[9]) / 10; //red average ab = (b[0] + b[1] + b[2] + b[3] + b[4] + b[5] + b[6] + b[7] + b[8] + b[9]) / 10; //blue average ag = (g[0] + g[1] + g[2] + g[3] + g[4] + g[5] + g[6] + g[7] + g[8] + g[9]) / 10; //green average if (ar > 100 && ab < 70 && ag > 55) { //red Time = 0; while (opModeIsActive() && Time < 100) { telemetry.addData("RED", Time); telemetry.update(); } robot.jewelArm.setPosition(0.55); } if (ar < 100 && ab > 70 && ag < 55) { // blue Time = 0; while (opModeIsActive() && Time < 100) { telemetry.addData("BLUE", Time); telemetry.update(); } robot.jewelArm.setPosition(0.55); } else { robot.jewelArm.setPosition(0.55); } robot.leftJewelArm.setPosition(0.38); } }
true
88b1b3a251d581f53da0f0a84644c8725600bc7d
Java
zzyzzyxx/FFBFv1.4
/main/java/com/example/ffbfv14/EateryAdapter.java
UTF-8
1,388
2.28125
2
[]
no_license
package com.example.ffbfv14; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class EateryAdapter extends RecyclerView.Adapter<EateryAdapter.EateryHolder> { ArrayList<Eatery> aList; // make the constructor for the list public EateryAdapter(ArrayList<Eatery> aList) { this.aList = aList; } @NonNull @Override public EateryHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.eaterycard, parent,false); EateryHolder holder = new EateryHolder(v); return holder; } @Override public void onBindViewHolder(@NonNull EateryHolder holder, int position) { } @Override public int getItemCount() { return 0; } public class EateryHolder extends RecyclerView.ViewHolder{ TextView tv; ImageView iv; public EateryHolder(@NonNull View itemView) { super(itemView); tv = itemView.findViewById(R.id.tv_list_name); iv = itemView.findViewById(R.id.iv_list_image); } } }
true
e3a061ca2cee091ed2b4934f32421c1ddf47309b
Java
guccio618/LC
/src/Q026_Remove_Duplicates_from_Sorted_Array.java
UTF-8
489
2.984375
3
[]
no_license
public class Q026_Remove_Duplicates_from_Sorted_Array { public int removeDuplicates(int[] nums) { if(nums == null || nums.length == 0){ return 0; } int n = nums.length; int front = 0, back = 0; for(; front < n; ++front){ nums[back++] = nums[front]; while(front + 1 < n && nums[front] == nums[front + 1]){ front++; } } return back; } }
true
482775b0f85b3a33e721053fad30fbb3b2b0999c
Java
823811845/algorithmPractice
/src/牛客网算法题/ACMfirst.java
GB18030
874
3.234375
3
[]
no_license
package ţ㷨; /** * ڳȱ˶СڷԼӷ࣬뽡׼ȷ˵Ǽʡ * СһԲε̺ӣǷֳȷֱ֣A,B,C֮Ϊ̺˶ʽÿζAʼÿζ飬A * Ҳԭ.ΪﵽЧСÿ춼nΣͻȻ֪nʱ˺üû_ * ھܹж * * @author 823811845 */ public class ACMfirst { /** * ˼· n-1벻AϣҲ еȥ n-1Aпܵ * Ҳǵݹ飬f(n)=2nη-fn-1; */ }
true
edbdc827328ef28c36ece8ef9a8d85a1e88aef1d
Java
JimWang-pan/JimBlogSystem
/JimBlogSystem/src/com/java1234/servlet/RegisterServlet.java
GB18030
2,983
2.40625
2
[]
no_license
package com.java1234.servlet; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.crypto.hash.Md5Hash; import com.java1234.dao.UserDao; import com.java1234.model.User; import com.java1234.utils.DbUtil; import com.java1234.utils.Md5Util; /** * ûעҵ * */ public class RegisterServlet extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; private User user = new User(); private UserDao userDao = new UserDao(); private DbUtil dbUtil = new DbUtil(); private Md5Util md5Util = new Md5Util(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("userName"); String mail = request.getParameter("mail"); String verifyCode = request.getParameter("verifyCode"); String password = request.getParameter("password"); Connection con = null; try { con = dbUtil.getCon(); //жûǷѾ if(userDao.selectUserName(con, userName)){ request.setAttribute("userName", userName); request.setAttribute("mail", mail); request.setAttribute("passwprd", password); request.setAttribute("confirmPassword", password); request.setAttribute("error", "û"); request.getRequestDispatcher("register.jsp").forward(request, response); return; }else{ //жǷѾע˺ if(userDao.selectMail(con, mail)){ request.setAttribute("userName", userName); request.setAttribute("mail", mail); request.setAttribute("passwprd", password); request.setAttribute("confirmPassword", password); request.setAttribute("error", "һֻעһ˺"); request.getRequestDispatcher("register.jsp").forward(request, response); return; }else{ if(verifyCode.equals(SendVerifyCodeServlet.getVerify_code())){ User user = new User(userName, md5Util.md5(password), mail); if(userDao.insertUser(con, user)!=0){ response.sendRedirect("index.jsp"); } }else{ request.setAttribute("userName", userName); request.setAttribute("mail", mail); request.setAttribute("passwprd", password); request.setAttribute("confirmPassword", password); request.setAttribute("error", "֤"); request.getRequestDispatcher("register.jsp").forward(request, response); return; } } } } catch (SQLException e) { e.printStackTrace(); }finally { if(con!=null){ dbUtil.conClose(con); } } } }
true
3c684d5be7cc1531fd8461ec29859535452f6bcd
Java
EugeneChung/algorithm-training
/src/hackerrank/array/HourglassSum.java
UTF-8
1,241
3.171875
3
[]
no_license
package hackerrank.array; import helpers.TestHelper; public class HourglassSum { public static void main(String[] args) { int arr[][] = {{-9, -9, -9, 1, 1, 1}, {0, -9, 0, 4, 3, 2}, {-9, -9, -9, 1, 2, 3}, {0, 0, 8, 6, 6, 0}, {0, 0, 0, -2, 0, 0}, {0, 0, 1, 2, 4, 0}}; // int arr[][] = {{1, 1, 1, 0, 0, 0}, {0, 1, 0, 0, 0, 0}, {1, 1, 1, 0, 0, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0}}; TestHelper.printSolution( hourglassSum(arr) ); } // Complete the hourglassSum function below. static int hourglassSum(int[][] arr) { int[][] prefixSum = new int[6][4]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length - 2; j++) { prefixSum[i][j] = arr[i][j] + arr[i][j + 1] + arr[i][j + 2]; } } //TestHelper.printMatrix(prefixSum); int answer = Integer.MIN_VALUE; for (int i = 0; i < prefixSum.length - 2; i++) { for (int j = 0; j < prefixSum[i].length; j++) { int sum = prefixSum[i][j] + arr[i + 1][j + 1] + prefixSum[i + 2][j]; answer = Math.max(answer, sum); } } return answer; } }
true
6390bbd42e2fbb1c1fb54b5e673b56482ddab6b4
Java
davidbasto/coursera-courses
/forum/src/main/java/br/com/courseracourse/forum/web/InsereTopicoServlet.java
UTF-8
1,410
2.34375
2
[]
no_license
package br.com.courseracourse.forum.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import br.com.courseracourse.forum.model.GerenciadorTopico; /** * Servlet implementation class InsereTopicoServlet */ public class InsereTopicoServlet extends HttpServlet { private static final long serialVersionUID = 1L; private GerenciadorTopico gerenciadorTopico; /** * @see HttpServlet#HttpServlet() */ public InsereTopicoServlet() { super(); this.gerenciadorTopico = new GerenciadorTopico(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String loginUsuarioLogado = (String) request.getSession().getAttribute("usuarioLogado"); if(loginUsuarioLogado != null ) { String tituloTopico = request.getParameter("titulo"); String conteudoTopico = request.getParameter("conteudo"); gerenciadorTopico.insereTopico(loginUsuarioLogado, tituloTopico, conteudoTopico); request.setAttribute("tituloTopicoInserido", tituloTopico); request.getRequestDispatcher("TopicoServlet").forward(request, response); } } }
true
0b656d0d3d47f89d9034d9c1e2e663fef73d4647
Java
xybed/MeiShiJia_App
/app/src/main/java/com/mumu/meishijia/test/TestActivity.java
UTF-8
1,197
1.78125
2
[]
no_license
package com.mumu.meishijia.test; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import com.mumu.meishijia.R; import com.mumu.meishijia.adapter.football.LeaguePagerAdapter; import com.mumu.meishijia.model.football.Ranking; import com.mumu.meishijia.view.BaseActivity; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class TestActivity extends BaseActivity<TestPresenter> implements TestView { @BindView(R.id.tab_layout) TabLayout tabLayout; @BindView(R.id.view_pager) ViewPager viewPager; private LeaguePagerAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); ButterKnife.bind(this); adapter = new LeaguePagerAdapter(getSupportFragmentManager()); viewPager.setOffscreenPageLimit(6); viewPager.setAdapter(adapter); tabLayout.setupWithViewPager(viewPager); tabLayout.setTabMode(TabLayout.MODE_FIXED); } @Override public void getSuccess(List<Ranking> rankings) { } }
true
af896b4112aef7fa51c39f3fc5fad4cfb366c759
Java
CodeKul/Java16Dec2019-4-5-pm
/src/multithreading/ThreadClass.java
UTF-8
763
3.5625
4
[]
no_license
package multithreading; public class ThreadClass extends Thread { public void run(){ for (int i=0;i<5;i++){ try { Thread.sleep(500); System.out.println("Hi"); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) throws InterruptedException { ThreadClass threadClass1=new ThreadClass(); ThreadClass threadClass2=new ThreadClass(); threadClass1.setName("A"); threadClass2.setName("B"); threadClass1.start();//worker thread threadClass2.start(); threadClass1.join(); threadClass2.join(); threadClass1.run();//main thread } }
true