Java Code Examples for java.util.Arrays

The following are top voted examples for showing how to use java.util.Arrays. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: sslcertx   File: MySQLPreparedStatement.java View source code 7 votes vote down vote up
@Override
public int[] executeBatch() throws SQLException {
    int[] ret = new int[batchPreparedStatements.size()];
    int i = 0;
    try {
        synchronized (this.getProtocol()) {
            for(; i < batchPreparedStatements.size(); i++)  {
                PreparedStatement ps =  batchPreparedStatements.get(i);
                ps.execute();
                int updateCount = ps.getUpdateCount();
                if (updateCount == -1) {
                    ret[i] = SUCCESS_NO_INFO;
                } else {
                    ret[i] = updateCount;
                }
            }
        }
    } catch (SQLException sqle) {
        throw new BatchUpdateException(sqle.getMessage(), sqle.getSQLState(), Arrays.copyOf(ret, i), sqle);
    } finally {
        clearBatch();
    }
    return ret;
}
 
Example 2
Project: iot-server-appliances   File: EmailMessageProperties.java View source code 7 votes vote down vote up
@Override
public String toString() {
    return "EmailMessageProperties{" +
            "messageBody='" + messageBody + '\'' +
            ", mailTo=" + Arrays.toString(mailTo) +
            ", ccList=" + Arrays.toString(ccList) +
            ", bccList=" + Arrays.toString(bccList) +
            ", subject='" + subject + '\'' +
            ", firstName='" + firstName + '\'' +
            ", enrolmentUrl='" + enrolmentUrl + '\'' +
            ", title='" + title + '\'' +
            '}';
}
 
Example 3
Project: lettuce   File: StateMachineTest.java View source code 6 votes vote down vote up
@Test
public void multi() throws Exception {
    CommandOutput<String, String, List<String>> output = new ValueListOutput<String, String>(codec);
    ByteBuf buffer = buffer("*2\r\n$-1\r\n$2\r\nok\r\n");
    assertThat(rsm.decode(buffer, output)).isTrue();
    assertThat(output.get()).isEqualTo(Arrays.asList(null, "ok"));
}
 
Example 4
Project: raylew_algorithm   File: ProcessSchedule.java View source code 6 votes vote down vote up
/**
 * ??????
 */
public Linked_PCBQueue() {
    PCB[] pcbs = new PCB[5];
    for (int i = 0; i < 5; i++) {
        PCB pcb = new PCB();
        Random random = new Random();
        pcb.setPriority(random.nextInt(10) + 1);
        pcb.setName("P" + (i + 1));
        pcb.setRuntime(random.nextInt(10) + 1);
        pcb.setStatus(false);
        pcbs[i] = pcb;
    }
    Arrays.sort(pcbs);
    for (int i = 0; i < 5; i++) {
        pcbQueue.add(pcbs[i]);
    }
}
 
Example 5
Project: lettuce   File: Utf8StringCodecTest.java View source code 6 votes vote down vote up
@Test
public void decodeHugeBuffer() throws Exception {
    char[] huge = new char[8192];
    Arrays.fill(huge, 'A');
    String value = new String(huge);
    redis.set(key, value);
    assertThat(redis.get(key)).isEqualTo(value);
}
 
Example 6
Project: virgo.kernel   File: ParsedCommand.java View source code 6 votes vote down vote up
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + Arrays.hashCode(this.arguments);
    result = prime * result + ((this.command == null) ? 0 : this.command.hashCode());
    return result;
}
 
Example 7
Project: raylew_algorithm   File: ????.java View source code 6 votes vote down vote up
public static void dfs(int cur) {
    int sum = 0;
    for (int i = 0; i < cur; i++) {
        sum += res[i];
    }
    if (sum >= goal) {
        if (sum == goal) {
            total++;
            for (int i = 0; i < cur; i++) {
                System.out.print(res[i] + ",");
            }
            System.out.println();
        }
        return;
    }
    int index = Arrays.binarySearch(arr, 2);
    for (int i = index; i < N; i++) {
        if (cur == 0) {
            res[cur] = arr[i];
            dfs(cur + 1);
        } else {
            if (arr[i] >= res[cur - 1]) {
                res[cur] = arr[i];
                dfs(cur + 1);
            }
        }
    }
}
 
Example 8
Project: nikeplus-fuelband-se-reversed   File: CopperheadPacket.java View source code 6 votes vote down vote up
public byte[] getPayload(int paramInt) throws Exception
{
  int i = getPayloadSize();
  int j = paramInt + 3;
  if (j > i + 3)
    throw new Exception("Invalid packet buffer size");
  return Arrays.copyOfRange(this.mBuffer, j, i + 3);
}
 
Example 9
Project: richfaces   File: IterationTableStateBean.java View source code 6 votes vote down vote up
public void checkColumnOrderAfterDnd() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    AbstractExtendedDataTable edtComponent = (AbstractExtendedDataTable) facesContext.getViewRoot().findComponent("myForm").findComponent("edt");
    ExtendedDataTableState tableState = new ExtendedDataTableState(edtComponent);

    String[] expectedOrder = { "column3", "column1", "column2" };
    String[] order = tableState.getColumnsOrder();
    if (!Arrays.deepEquals(expectedOrder, order)) {
        checkColumnOrderAfterDndResult = MessageFormat.format("Expected columns order <{0}>, but have <{1}>.", Lists.newArrayList(expectedOrder), Lists.newArrayList(order));
        return;
    }
    checkColumnOrderAfterDndResult = PASSED;
}
 
Example 10
Project: property-db   File: SocketChannelImpl.java View source code 6 votes vote down vote up
@Override
public long read(ByteBuffer[] targets, int offset, int length) throws IOException {
    Arrays.checkOffsetAndCount(targets.length, offset, length);
    checkOpenConnected();
    int totalCount = FileChannelImpl.calculateTotalRemaining(targets, offset, length, true);
    if (totalCount == 0) {
        return 0;
    }
    byte[] readArray = new byte[totalCount];
    ByteBuffer readBuffer = ByteBuffer.wrap(readArray);
    int readCount;
    // read data to readBuffer, and then transfer data from readBuffer to targets.
    readCount = readImpl(readBuffer);
    readBuffer.flip();
    if (readCount > 0) {
        int left = readCount;
        int index = offset;
        // transfer data from readArray to targets
        while (left > 0) {
            int putLength = Math.min(targets[index].remaining(), left);
            targets[index].put(readArray, readCount - left, putLength);
            index++;
            left -= putLength;
        }
    }
    return readCount;
}
 
Example 11
Project: jlibs   File: Util.java View source code 6 votes vote down vote up
/**
 * returns hashCode of given argument.
 * if argument is null, returns 0
 */
public static int hashCode(Object obj){
    if(obj==null)
        return 0;
    else if(obj.getClass().isArray()){
        if(obj instanceof Object[])
            return Arrays.deepHashCode((Object[])obj);
        else if(obj instanceof boolean[])
            return Arrays.hashCode((boolean[])obj);
        else if(obj instanceof char[])
            return Arrays.hashCode((char[])obj);
        else if(obj instanceof byte[])
            return Arrays.hashCode((byte[])obj);
        else if(obj instanceof short[])
            return Arrays.hashCode((short[])obj);
        else if(obj instanceof int[])
            return Arrays.hashCode((int[])obj);
        else if(obj instanceof long[])
            return Arrays.hashCode((long[])obj);
        else if(obj instanceof float[])
            return Arrays.hashCode((float[])obj);
        else if(obj instanceof double[])
            return Arrays.hashCode((double[])obj);
        else
            throw new ImpossibleException("couldn't find hascode for"+obj.getClass().getComponentType().getSimpleName()+"[]");
    }else
        return obj.hashCode();
}
 
Example 12
Project: rapaio   File: MultiLayerPerceptronRegression.java View source code 6 votes vote down vote up
@Override
public String fullName() {
    StringBuilder sb = new StringBuilder();
    sb.append(name()).append("{");
    sb.append("function=").append(function.name()).append(", ");
    sb.append("learningRate=").append(formatFlex(learningRate)).append(", ");
    sb.append("layerSizes=").append(Arrays.deepToString(Arrays.stream(layerSizes).mapToObj(i -> i).toArray()));
    sb.append("}");
    return sb.toString();
}
 
Example 13
Project: sphereMiners   File: AIManager.java View source code 6 votes vote down vote up
/**
 * This method creates the list of the possible AIs.
 */
private void makeAiList() {

    // create Loader
    File fileloc = new File(AI_FILELOCATION);
    File[] classes = fileloc.listFiles();

    // if there are no files, classes will be null. (See JavaManual)
    if (classes == null) {
       return;
    }

    Arrays.stream(classes).map(f -> f.getName())
                           // only add ais if they are valid (extend SphereMiner2015 class)
                          .filter(f -> f.endsWith(".class"))
                          .map(f -> f.split(".class")[0])
                          .filter(f -> isValidAi(f))
                          .forEach(f -> aiList.add(f));
}
 
Example 14
Project: mldht   File: PopulationEstimator.java View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	NumberFormat formatter = NumberFormat.getNumberInstance(Locale.GERMANY);

	int keyspaceSize = 20000000;

	formatter.setMaximumFractionDigits(30);
	
	PopulationEstimator estimator = new PopulationEstimator();
	
	
	
	System.out.println(160-Math.log(keyspaceSize)/Math.log(2));
	
	Key[] keyspace = new Key[keyspaceSize];
	Runnable r = () -> {
		Arrays.parallelSetAll(keyspace, i -> Key.createRandomKey());
	};
	//Arrays.sort(keyspace);
	
	for(int i=0;i<100;i++)
	{
		if(i % 20 == 0)
			r.run();

		Key target = Key.createRandomKey();

		Arrays.parallelSort(keyspace, new Key.DistanceOrder(target));


		int sizeGoal = 8;

		TreeSet<Key> closestSet = new TreeSet<Key>();

		for(int j=0;j<sizeGoal;j++)
			closestSet.add(keyspace[j]);

		//estimator.update(closestSet);
		estimator.update(closestSet,target);
	}
	
}
 
Example 15
Project: mldht   File: EncoderTest.java View source code 6 votes vote down vote up
@Test
public void testSorting() {
	Map<String, Object> root = new LinkedHashMap<>();
	
	String[] keys = new String[256];
	
	Arrays.setAll(keys, (i) -> buf2str(ByteBuffer.wrap(new byte[] {(byte) i})));
	// clone to shuffle independently of original order
	List<String> keyList = Arrays.asList(keys);
	List<String> shuffledKeys = Arrays.asList(keys.clone());
	Collections.shuffle(shuffledKeys);
	
	shuffledKeys.forEach(s -> root.put(s, 1L));
	
	BEncoder enc = new BEncoder();
	ByteBuffer out = enc.encode(root, 2048);
	
	StringBuilder reference = new StringBuilder();
	
	reference.append("d");
	
	keyList.forEach(str -> {
		reference.append("1:");
		reference.append(str);
		reference.append("i1e");
	});
	
	
	reference.append("e");
	
	
	
	assertEquals(str2buf(reference.toString()), out);
}
 
Example 16
Project: nikeplus-fuelband-se-reversed   File: MainActivity.java View source code 5 votes vote down vote up
@Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     
     Logger.setLogView( this, (TextView)findViewById( R.id.log_view ) );

     _btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
     _btAdapter = _btManager.getAdapter();
     
     if( _btAdapter.isEnabled() == false ){
     	Logger.w( "Bluetooth is disabled." );
     	
     	Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);   
         startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
     }
                   
     _leScanCallback = new BluetoothAdapter.LeScanCallback() {
     	
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
	if( _scanning == false )
		return;
	
	try
	{
		/*
		 * Parse device advertisment data.
		 */
		final Bundle advData = AdvertisementData.parse(scanRecord);
		/*
		 * Is this a nike device?
		 */
		if( Arrays.equals(advData.getByteArray("COMPANYCODE"), NIKE_COMPANY_CODE ) )
		{
			Logger.i( "FOUND NIKE DEVICE [" + device +"]" );
			
			dumpDeviceAdvData( advData );
			
			_scanning = false;
			_btAdapter.stopLeScan(_leScanCallback);
			
			Logger.i( "Connecting to GATT server ..." );
			
			_ioqueue = new BLEIoQueue( new BLEIoQueue.QueueCallbacks() {	
				private BluetoothGattService	    _CopperheadService = null;
				private BluetoothGattCharacteristic _CommandChannel = null;
				private BluetoothGattCharacteristic _ResponseChannel = null;

				// add a raw packet to the queue
	        	private void addPacket( BLEIoQueue queue, byte[] data, BLEIoOperation.OnResponseCallback callback ){
	        		BLEIoOperation op = new BLEIoOperation( BLEIoOperation.Type.WRITE_CHARACTERISTICS, "Sending command.", callback );

	        		op.set_data( data );
	        		op.set_characteristic( _CommandChannel );
	        						        						        		
	        		queue.add(op);			        						        	
	        	}
	        	
	        	private void addPacket( BLEIoQueue queue, String s, BLEIoOperation.OnResponseCallback callback ){
	        		byte[] buffer = new byte[ s.length() / 2 ];
	        		
	        		for( int i = 0, j = 0; i < s.length(); i += 2, ++j ){
	        			buffer[j] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
	                             			+ Character.digit(s.charAt(i+1), 16));
	        		}
	        		
	        		addPacket( queue, buffer, callback );
	        	}

	        	// create the needed packet to request a specific setting from the device
	        	private void requestSetting( BLEIoQueue queue, int code )
	        	{
	        		CopperheadPacket oppacket = new CopperheadPacket(5);
	        		oppacket.setOpcode((byte)10);
	        		ByteBuffer b = oppacket.getPayloadBuffer();
	        		b.put( (byte)1 );
	        		b.put( (byte)code );
	        		
	        		Packet p = Packet.wrap(oppacket);
	        		
	        		p.setProtocolLayer( CommandResponseOperation.ProtocolLayer.COMMAND );
	        		p.setPacketCount(0);
	        		p.setPacketIndex(0);
	        		p.setSequenceNumber(1);
	        		
	        		addPacket( queue, p.getBuffer(), new BLEIoOperation.OnResponseCallback() {																	
	        			@Override
	        			public void onData(Packet config) {
	        				byte[] raw = config.getBuffer();
	
	        				try
	        				{
	        					Utils.processGetSettingsResponse(raw);
	        				}
	        				catch( Exception e )
	        				{
	        					Logger.e( e.toString() );
	        				}
	        			}
	        		} );
	        	}
	        	
				@Override
				public void onServicesDiscovered(BLEIoQueue queue, BluetoothGatt gatt, int status) {								
					dumpServices(gatt);
					
					_CopperheadService = gatt.getService( COPPERHEAD_SERVICE_UUID );
			    	if( _CopperheadService == null ){
			    		Logger.e( "No Copperhead service found." );
			    		return;
			    	}
			    	
			    	/*
			    	 * Get command and response channels.
			    	 */
			    	_CommandChannel = _CopperheadService.getCharacteristic( COPPERHEAD_CMD_UUID );						    	
			    	_ResponseChannel = _CopperheadService.getCharacteristic( COPPERHEAD_RSP_UUID );
			    	
			    	if( _CommandChannel == null ){
			    		Logger.e( "Could not find COPPERHEAD_CMD_UUID" );
			    		return;
			    	}
			    	else if( _ResponseChannel == null ){
			    		Logger.e( "Could not find COPPERHEAD_RSP_UUID" );
			    		return;
			    	}
			    	
			    	/*
			    	 * Enable the response channel to receive incoming data notifications.
			    	 */
			    	BluetoothGattDescriptor rsp_config_desc = _ResponseChannel.getDescriptor( CLIENT_CHARACTERISTIC_CONFIG_UUID );
			    	if( rsp_config_desc == null ){
			    		Logger.e( "RSP has no client config." );
			    		return;
			    	}

			    	BLEIoOperation notify = new BLEIoOperation( BLEIoOperation.Type.NOTIFY_START, "Enable response channel notifications." );
			    	
			    	notify.set_characteristic( _ResponseChannel );
			    	notify.set_descriptor( rsp_config_desc );
			    		
			    	queue.add(notify);
			    	
			    	final BLEIoQueue fq = queue;

			    	Packet auth = new Packet(19);
			    	
			    	/*
			    	 * Send the "START AUTH" packet -> 0x90 0x01 0x01 0x00 .....
			    	 */
			    	auth.setProtocolLayer( CommandResponseOperation.ProtocolLayer.SESSION );
			    	auth.setPacketCount(0);
			    	auth.setPacketIndex(0);
			    	auth.setSequenceNumber(1);
			    	auth.setCommandBytes( (byte)1, (byte)1 );
			    	
			    	addPacket( queue, auth.getBuffer(), new BLEIoOperation.OnResponseCallback() {									
						@Override
						public void onData( Packet challenge_packet ) {										
							
							Logger.d( "<< " + challenge_packet.toString() );

							ByteBuffer buffer = challenge_packet.getBuffered(ByteOrder.LITTLE_ENDIAN);
							
							// remove op code and length
							int opcode = buffer.get();
							int length = buffer.get();
																	
							switch( buffer.get() )
							{
								case 0x41:
									Logger.i( "Received authentication challenge" );
														
									/*
									 * Get 16 bytes of AUTH nonce
									 */
									byte[] nonce = new byte[16];
									buffer.get(nonce);

									if ((nonce == null) || (nonce.length != 16))
									{
										Logger.e("Missing or invalid authentication challenge nonce");
									}
									else
									{
									    CopperheadCRC32 crc = new CopperheadCRC32();
									    
									    byte[] auth_token = Utils.hexToBytes("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); 
							    												    
										Logger.d( "NONCE: " + Utils.bytesToHex( nonce ) );
										
										/*
										 * Create the response packet: 0xb0 0x03 0x02 [2 BYTES OF CRC] 0x00 ...
										 */
										Packet resp_packet = new Packet(19);
										
										resp_packet.setProtocolLayer( CommandResponseOperation.ProtocolLayer.SESSION );
										resp_packet.setPacketCount(0);
										resp_packet.setPacketIndex(0);
										resp_packet.setSequenceNumber( challenge_packet.getSequenceNumber() + 1 );
										
										ByteBuffer response = ByteBuffer.allocate(18);
										
										response.put( (byte)0x03 );
										response.put( (byte)0x02 );
										
										crc.update(nonce);
									    crc.update(auth_token);
									    
									    short sum = (short)((0xFFFF & crc.getValue()) ^ (0xFFFF & crc.getValue() >>> 16));
									    												    
									    response.putShort(sum);
									    
									    resp_packet.setPayload( response.array() );

										addPacket( fq, resp_packet.getBuffer(), new BLEIoOperation.OnResponseCallback() {														
											@Override
											public void onData(Packet challenge_response) {
												
												Logger.d( "<< " + challenge_response.toString() );
												
												ByteBuffer buffer = challenge_response.getBuffered(ByteOrder.LITTLE_ENDIAN);
												
												// remove op code and length
												int opcode = buffer.get();
												int length = buffer.get();
												
												/*
												 * Get the authentication reply code.
												 */
												int reply = buffer.get();
												
												if( reply == 0x42 ) {
													Logger.i( "Succesfully authenticated." );
														
													// Request some settings
													requestSetting( fq, Utils.getSettingCode( "BAND_COLOR" ) );
													requestSetting( fq, Utils.getSettingCode( "FUEL" ) );
													requestSetting( fq, Utils.getSettingCode( "FIRST_NAME" ) );
													requestSetting( fq, Utils.getSettingCode( "SERIAL_NUMBER" ) );
												}
												else {
													Logger.e( "Authentication failure, reply: " + reply );
												}
											}
										});
									}
									
								break;
								
								default:
									
									Logger.e( "Unknown auth code." );
							}
						}
					});	
				}
			});
							
			device.connectGatt( MainActivity.this, false, _ioqueue );
		}
	}
	catch( Exception e )
	{
		Logger.e( e.toString() );
	}
}
     };
     
     Logger.i( "Starting scann ..." );
     
     _scanning = true;
     _btAdapter.startLeScan(_leScanCallback);
 }