java – Embedded Redis for Spring Boot

java – Embedded Redis for Spring Boot

java – Embedded Redis for Spring Boot

You can use an embedded Redis like https://github.com/kstyrc/embedded-redis

  1. Add the dependency to your pom.xml
  2. Adjust the properties for your integration test to point to your embedded redis, for example :
    spring:
      redis:
        host: localhost
        port: 6379
    
  3. Instanciate the embedded redis server in a component that is defined in your tests only :
    @Component
    public class EmbededRedis {
    
        @Value(${spring.redis.port})
        private int redisPort;
    
        private RedisServer redisServer;
    
        @PostConstruct
        public void startRedis() throws IOException {
            redisServer = new RedisServer(redisPort);
            redisServer.start();
        }
    
        @PreDestroy
        public void stopRedis() {
            redisServer.stop();
        }
    }
    

You can use ozimov/embedded-redis as a Maven(-test)-dependency (this is the successor of kstyrc/embedded-redis).

  1. Add the dependency to your pom.xml
    <dependencies>
      ...
      <dependency>
        <groupId>it.ozimov</groupId>
        <artifactId>embedded-redis</artifactId>
        <version>0.7.1</version>
        <scope>test</scope>
      </dependency>
    
  2. Adjust your application properties for your integration test
    spring.redis.host=localhost
    spring.redis.port=6379
    
  3. Use the embedded redis server in a test configuration
    @TestConfiguration
    public static class EmbededRedisTestConfiguration {
    
      private final redis.embedded.RedisServer redisServer;
    
      public EmbededRedisTestConfiguration(@Value(${spring.redis.port}) final int redisPort) throws IOException {
        this.redisServer = new redis.embedded.RedisServer(redisPort);
      }
    
      @PostConstruct
      public void startRedis() {
        this.redisServer.start();
      }
    
      @PreDestroy
      public void stopRedis() {
        this.redisServer.stop();
      }
    }
    

java – Embedded Redis for Spring Boot

Another neat way is to use the testcontainers library which can run any type of application that can in a Docker container and Redis is no exception. What I like best is that it is lightly coupled with the Spring Test ecosystem.

mavens dependency:

<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>testcontainers</artifactId>
    <version>${testcontainers.version}</version>
</dependency>

simple integration test:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = {management.port=0})
@ContextConfiguration(initializers = AbstractIntegrationTest.Initializer.class)
@DirtiesContext
public abstract class AbstractIntegrationTest {

    private static int REDIS_PORT = 6379;

    @ClassRule
    public static GenericContainer redis = new GenericContainer(redis:5-alpine).withExposedPorts(REDIS_PORT);

    public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
        @Override
        public void initialize(ConfigurableApplicationContext ctx) {
            // Spring Boot 1.5.x
            TestPropertySourceUtils.addInlinedPropertiesToEnvironment(ctx,
                spring.redis.host= + redis.getContainerIpAddress(),
                spring.redis.port= + redis.getMappedPort(REDIS_PORT));

            // Spring Boot 2.x.
            TestPropertyValues.of(
                spring.redis.host: + redis.getContainerIpAddress(),
                spring.redis.port: + redis.getMappedPort(REDIS_PORT))
                .applyTo(ctx);
        }
    }
}

Since Spring Framework 5.2.5 (Spring Boot 2.3.x) you can use the powerful DynamicPropertySource annotation.
Here is an example:

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public abstract class AbstractIT {

    static GenericContainer redisContainer = new GenericContainer(redis:5-alpine).withExposedPorts(6379);

    @DynamicPropertySource
    static void properties(DynamicPropertyRegistry r) throws IOException {
        r.add(spring.redis.host, redisContainer::getContainerIpAddress);
        r.add(spring.redis.port, redisContainer::getFirstMappedPort);
    }
}

Related posts on java  :

Table like java data structure

Table like java data structure

Table like java data structure

There is a generic TreeBasedTable class from Google library which does exactly what you are asking for. It also offers many other useful utility methods and its usage is shown in the user guide.

From the TreeBasedTable docs:

Implementation of Table whose row keys and column keys are ordered by their natural ordering or by supplied comparators.

Example usage:

RowSortedTable<Vertex, Vertex, Double> weightedGraph = TreeBasedTable.create();
weightedGraph.put(v2, v3, 4.0);
weightedGraph.put(v1, v2, 20.0);

System.out.println( weightedGraph.rowKeySet() ); // prints [v1, v2]

What do you mean with:

i have to be able to sort it by the sij parameter

Whats wrong with:

Object [][] data

EDIT

Ok, just guessing that what you need is a StrangeDataStructure which holds the array, and helps you to sort by the first column, then the only thing that you need is something like this:

class Structure {
    Object [][] data;
    Object [] indexColumn; // the sij?
}

And thats it: you should add a sort method indicating the direction, and sort using the indexColumn

It is VEEERY simple I think ( and If I understood your question )

You know what? Im going to implement it.

// time elapses…

Here it is:

import java.util.Comparator;
import java.util.Arrays;

public class StrangeStructure {

    private Integer [][] data;
    private Integer [] sij; // what is sij anyway?

    public StrangeStructure( Integer [][] matrix  ) {
        data = matrix;
        sij = new Integer[ data.length ];
        for( int i = 0 ; i < data.length ; i++ ) {
            sij[i] = data[i][0];
        }
    }

    public void sort( Direction direction  ) {

        Comparator sijComparator  = new DataComparator( direction, true );
        Comparator dataComparator = new DataComparator( direction, false );

        Arrays.sort( sij, sijComparator );
        Arrays.sort( data, dataComparator  );

    }

    public static void main( String [] args ) {

        StrangeStructure s =  
            new StrangeStructure( new Integer[][]{
                                  { 45, 5, 7 }, 
                                  { 33, 1, 6 }, 
                                  { 31, 0, 9 }, 
                                  { 12, 8, 2 }    
                            });

        System.out.printf(Original:n%s, s );       

        s.sort( Direction.MIN_TO_MAX );  
        System.out.printf(Min to max:n%s, s );       

        s.sort( Direction.MAX_TO_MIN );  
        System.out.printf(Max to minn%s, s );       

    }


    public String toString() {
        StringBuilder b = new StringBuilder();
        for( Integer [] row : data ) {
            for( int i : row ) {
                b.append( i+,);
            }
            b.append(n);
        }
        return b.toString();

    }

}
class DataComparator implements Comparator {

    private Direction direction;
    private boolean isSij;

    public DataComparator( Direction d, boolean isSij ) {
        this.direction = d;
        this.isSij = isSij;
    }

    public int compare( Object one , Object two  ) {
        if( isSij ){
            return doCompare( direction, (Integer) one, (Integer) two );
        } else {
            return doCompare( direction, ((Integer[])one)[0], ((Integer[])two)[0]);
        }
    }
    public int doCompare( Direction d, int one, int two  ) {
        int a = ( d == Direction.MIN_TO_MAX? one: two );
        int b = ( d == Direction.MIN_TO_MAX? two: one ) ;
        return a - b;
    }
    public boolean equals( Object o ) {
        return false;
    }
}



enum Direction{
    MIN_TO_MAX,
    MAX_TO_MIN
}

Output:

Original:
45,5,7,
33,1,6,
31,0,9,
12,8,2,
Min to max:
12,8,2,
31,0,9,
33,1,6,
45,5,7,
Max to min
45,5,7,
33,1,6,
31,0,9,
12,8,2,

Table like java data structure

Read the section from the Swing tutorial on How to Use Tables. The tutorial shows how to create a table as well as how to add sorting capability to the table.

If you only need to store the data but not display it, then you can use a 2-dimensional array or a List of Lists. Then you can use the Column Comparator to do the sorting.

Edit: added code demonstrating use of the ColumnComparator

import java.util.*;

public class SortSIJ
{
    public static void main(String args[])
    {
        Object[] data = new Object[4];
        data[0] = new Integer[] {45, 5, 7};
        data[1] = new Integer[] {33, 1, 6};
        data[2] = new Integer[] {31, 0, 9};
        data[3] = new Integer[] {12, 8, 2};

        ColumnComparator cc = new ColumnComparator(0);
//      cc.setAscending( false );

        Arrays.sort(data, cc);

        for (Object row: data)
        {
            Integer[] theRow = (Integer[])row;
            System.out.println( Arrays.asList(theRow) );
        }
    }
}

I also agree with the suggestion to create an Object to store the 3 variables. In this case you can use the BeanComparator which can be found at the above link.

Related posts on java data structure  :

Exception open failed: EACCES (Permission denied) on Android

Exception open failed: EACCES (Permission denied) on Android

Exception open failed: EACCES (Permission denied) on Android

Google has a new feature on Android Q: filtered view for external storage. A quick fix for that is to add this code in the AndroidManifest.xml file:

<manifest ... >
    <!-- This attribute is false by default on apps targeting Android Q. -->
    <application android_requestLegacyExternalStorage=true ... >
     ...
    </application>
</manifest>

You can read more about it here: https://developer.android.com/training/data-storage/use-cases

Edit: I am starting to get downvotes because this answer is out of date for Android 11. So whoever sees this answer please go to the link above and read the instructions.

For API 23+ you need to request the read/write permissions even if they are already in your manifest.

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We dont have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

AndroidManifest.xml

<uses-permission android_name=android.permission.READ_EXTERNAL_STORAGE />
<uses-permission android_name=android.permission.WRITE_EXTERNAL_STORAGE />

For official documentation about requesting permissions for API 23+, check https://developer.android.com/training/permissions/requesting.html

Exception open failed: EACCES (Permission denied) on Android

I had the same problem… The <uses-permission was in the wrong place. This is right:

 <manifest>
        <uses-permission android_name=android.permission.WRITE_EXTERNAL_STORAGE/>
        ...
        <application>
            ...
            <activity> 
                ...
            </activity>
        </application>
    </manifest> 

The uses-permission tag needs to be outside the application tag.

Related posts on Android :

sql – snowflake substring by pattern

sql – snowflake substring by pattern

Use the REGEXP_SUBSTR(…) built-in function to extract substrings using a regular expression pattern.

If there will only be one number in each column value, a number pattern or a numeric characters range syntax will suffice:

SELECT
accountNumber:123456 i1,
regexp_substr(i1, [0-9]+) r1,
{accountNumber:123456} i2,
regexp_substr(i2, [0-9]+) r2;

+----------------------+--------+----------------------------+--------+         
| I1                   | R1     | I2                         | R2     |
|----------------------+--------+----------------------------+--------|
| accountNumber:123456 | 123456 | {accountNumber:123456} | 123456 |
+----------------------+--------+----------------------------+--------+

If the number will be exactly 6 digits wide, use the {n} repetition syntax:

select
accountNumber:123456,anotherNumber:123 i1,
regexp_substr(i1, [0-9]{6}) r1,
{accountNumber:123456, anotherNumber: 123} i2,
regexp_substr(i2,[0-9]{6}) r2;

+----------------------------------------+--------+--------------------------------------------------+--------+
| I1                                     | R1     | I2                                               | R2     |
|----------------------------------------+--------+--------------------------------------------------+--------|
| accountNumber:123456,anotherNumber:123 | 123456 | {accountNumber:123456, anotherNumber: 123} | 123456 |
+----------------------------------------+--------+--------------------------------------------------+--------+

If the number must only follow the text accountNumber, you can introduce (capture groups):

select
accountNumber:123456,anotherNumber:123,somethingElse:456789 i1,
regexp_substr(i1, accountNumber[: ]+([0-9]{6}), 1, 1, e, 1) r1,
{accountNumber:123456, anotherNumber: 123, somethingElse: 456789} i2,
regexp_substr(i2, accountNumber[: ]+([0-9]{6}), 1, 1, e, 1) r2;

+-------------------------------------------------------------+--------+---------------------------------------------------------------------------+--------+
| I1                                                          | R1     | I2                                                                        | R2     |
|-------------------------------------------------------------+--------+---------------------------------------------------------------------------+--------|
| accountNumber:123456,anotherNumber:123,somethingElse:456789 | 123456 | {accountNumber:123456, anotherNumber: 123, somethingElse: 456789} | 123456 |
+-------------------------------------------------------------+--------+---------------------------------------------------------------------------+--------+

Building a fully correct regular expression will require more knowledge about all of the variances possible in the data. Try building out your patterns interactively with a good test-set on sites such as Regex101, RegExr, etc. that make it easier to develop them.

Note: If your data is actually in a JSON format throughout, Snowflake permits parsing them into a VARIANT data type to query them more naturally:

select
parse_json({accountNumber:123456, anotherNumber: 123, somethingElse: 456789}):accountNumber::integer account_number;

+----------------+                                                              
| ACCOUNT_NUMBER |
|----------------|
|         123456 |
+----------------+

sql – snowflake substring by pattern

Read Also

Snowflake Substring

loops – C++ – using glfwGetTime() for a fixed time step

loops – C++ – using glfwGetTime() for a fixed time step

All you need is this code for limiting updates, but keeping the rendering at highest possible frames. The code is based on this tutorial which explains it very well. All I did was to implement the same principle with GLFW and C++.

   static double limitFPS = 1.0 / 60.0;

    double lastTime = glfwGetTime(), timer = lastTime;
    double deltaTime = 0, nowTime = 0;
    int frames = 0 , updates = 0;

    // - While window is alive
    while (!window.closed()) {

        // - Measure time
        nowTime = glfwGetTime();
        deltaTime += (nowTime - lastTime) / limitFPS;
        lastTime = nowTime;

        // - Only update at 60 frames / s
        while (deltaTime >= 1.0){
            update();   // - Update function
            updates++;
            deltaTime--;
        }
        // - Render at maximum possible frames
        render(); // - Render function
        frames++;

        // - Reset after one second
        if (glfwGetTime() - timer > 1.0) {
            timer ++;
            std::cout << FPS:  << frames <<  Updates: << updates << std::endl;
            updates = 0, frames = 0;
        }

    }

You should have a function update() for updating game logic and a render() for rendering. Hope this helps.

loops – C++ – using glfwGetTime() for a fixed time step

iterating over each character of a String in ruby 1.8.6 (each_char)

iterating over each character of a String in ruby 1.8.6 (each_char)

I have the same problem. I usually resort to String#split:

ABCDEFG.split().each do |i|
  puts i
end

I guess you could also implement it yourself like this:

class String
  def each_char
    self.split().each { |i| yield i }
  end
end

Edit: yet another alternative is String#each_byte, available in Ruby 1.8.6, which returns the ASCII value of each char in an ASCII string:

ABCDEFG.each_byte do |i|
  puts i.chr # Fixnum#chr converts any number to the ASCII char it represents
end

Extending la_f0kas comment, esp. if you also need the index position in your code, you should be able to do

s = ABCDEFG
for pos in 0...s.length
    puts s[pos].chr
end

The .chr is important as Ruby < 1.9 returns the code of the character at that position instead of a substring of one character at that position.

iterating over each character of a String in ruby 1.8.6 (each_char)

ABCDEFG.chars.each do |char|
  puts char
end

also

ABCDEFG.each_char {|char| p char}

Ruby version >2.5.1

java – SimpleStringProperty and SimpleIntegerProperty TableView JavaFX

java – SimpleStringProperty and SimpleIntegerProperty TableView JavaFX

You dont need to use Properties in your table data objects for them to display, although use of Properties in certain circumstances is desirable.

The following code will display a table of people based on a Person class which has only String fields.

import javafx.application.Application;
import javafx.collections.*;
import javafx.geometry.Insets;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class ReadOnlyTableView extends Application {
  private TableView<Person> table = new TableView<Person>();
  private final ObservableList<Person> data =
    FXCollections.observableArrayList(
      new Person(Jacob, Smith, [email protected]),
      new Person(Isabella, Johnson, [email protected]),
      new Person(Ethan, Williams, [email protected]),
      new Person(Emma, Jones, [email protected]),
      new Person(Michael, Brown, [email protected])
    );

  public static void main(String[] args) { launch(args); }

  @Override public void start(Stage stage) {
    stage.setTitle(Table View Sample);
    stage.setWidth(450);
    stage.setHeight(500);

    final Label label = new Label(Address Book);
    label.setFont(new Font(Arial, 20));

    TableColumn firstNameCol = new TableColumn(First Name);
    firstNameCol.setMinWidth(100);
    firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>(firstName));

    TableColumn lastNameCol = new TableColumn(Last Name);
    lastNameCol.setMinWidth(100);
    lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>(lastName));

    TableColumn emailCol = new TableColumn(Email);
    emailCol.setMinWidth(200);
    emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>(email));

    table.setItems(data);
    table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);

    final VBox vbox = new VBox();
    vbox.setSpacing(5);
    vbox.setPadding(new Insets(10, 0, 0, 10));
    vbox.getChildren().addAll(label, table);

    stage.setScene(new Scene(new Group(vbox)));
    stage.show();
  }

  public static class Person {
    private String firstName;
    private String lastName;
    private String email;

    private Person(String fName, String lName, String email) {
      this.firstName = fName;
      this.lastName = lName;
      this.email = email;
    }

    public String getFirstName() { return firstName; }
    public void setFirstName(String fName) { firstName = fName; }
    public String getLastName() { return lastName; }
    public void setLastName(String lName) { lastName = lName; }
    public String getEmail() { return email; }
    public void setEmail(String inMail) { email = inMail; }
  }
}

Explanation

The purpose of using Properties and ObservableLists is that these are listenable elements. When properties are used, if the value of a property attribute in the datamodel changes, the view of the item in the TableView is automatically updated to match the updated datamodel value. For example, if the value of a persons email property is set to a new value, that update will be reflected in the TableView because it listens for the property change. If instead, a plain String had been used to represent the email, the TableView would not refresh as it would be unaware of email value changes.

The PropertyValueFactory documentation describes this process in detail:

An example of how to use this class is:

TableColumn<Person,String> firstNameCol = new TableColumn<Person,String>(First Name);
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person,String>(firstName));  

In this example, the firstName string is used as a reference to an
assumed firstNameProperty() method in the Person class type (which is
the class type of the TableView items list). Additionally, this method
must return a Property instance. If a method meeting these
requirements is found, then the TableCell is populated with this
ObservableValue. In addition, the TableView will automatically add an
observer to the returned value, such that any changes fired will be
observed by the TableView, resulting in the cell immediately updating.

If no method matching this pattern exists, there is fall-through
support for attempting to call get() or is() (that
is, getFirstName() or isFirstName() in the example above). If a method
matching this pattern exists, the value returned from this method is
wrapped in a ReadOnlyObjectWrapper and returned to the TableCell.
However, in this situation, this means that the TableCell will not be
able to observe the ObservableValue for changes (as is the case in the
first approach above).

Update

Here is a contrasting example to the first example which demonstrates how a TableView can observe and automatically refresh based on changes to its ObservableList of items and changes to the value of a property based item attribute.

import javafx.application.Application;
import javafx.beans.property.*;
import javafx.collections.*;
import javafx.event.*;
import javafx.geometry.Insets;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class PropertyBasedTableView extends Application {
  private TableView<Person> table = new TableView<Person>();
  private final ObservableList<Person> data = FXCollections.observableArrayList();
  private void initData() {
    data.setAll(
      new Person(Jacob, Smith, [email protected]),
      new Person(Isabella, Johnson, [email protected]),
      new Person(Ethan, Williams, [email protected]),
      new Person(Emma, Jones, [email protected]),
      new Person(Michael, Brown, [email protected])
    );
  }

  public static void main(String[] args) { launch(args); }

  @Override public void start(Stage stage) {
    initData();

    stage.setTitle(Table View Sample);
    stage.setWidth(450);
    stage.setHeight(500);

    final Label label = new Label(Address Book);
    label.setFont(new Font(Arial, 20));

    TableColumn firstNameCol = new TableColumn(First Name);
    firstNameCol.setMinWidth(100);
    firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>(firstName));

    TableColumn lastNameCol = new TableColumn(Last Name);
    lastNameCol.setMinWidth(100);
    lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>(lastName));

    TableColumn emailCol = new TableColumn(Email);
    emailCol.setMinWidth(200);
    emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>(email));

    table.setItems(data);
    table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
    table.setPrefHeight(300);

    final Button setEmailButton = new Button(Set first email in table to [email protected]);
    setEmailButton.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent event) {
        if (data.size() > 0) {
          data.get(0).setEmail([email protected]);
        }  
      }
    });

    final Button removeRowButton = new Button(Remove first row from the table);
    removeRowButton.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent event) {
        if (data.size() > 0) {
          data.remove(0);
        }  
      }
    });

    final Button resetButton = new Button(Reset table data);
    resetButton.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent event) {
        initData();
      }
    });

    final VBox vbox = new VBox(10);
    vbox.setPadding(new Insets(10, 0, 0, 10));
    vbox.getChildren().addAll(label, table, setEmailButton, removeRowButton, resetButton);

    stage.setScene(new Scene(new Group(vbox)));
    stage.show();
  }

  public static class Person {
    private final StringProperty firstName;
    private final StringProperty lastName;
    private final StringProperty email;

    private Person(String fName, String lName, String email) {
      this.firstName = new SimpleStringProperty(fName);
      this.lastName = new SimpleStringProperty(lName);
      this.email = new SimpleStringProperty(email);
    }

    public String getFirstName() { return firstName.get(); }
    public void setFirstName(String fName) { firstName.set(fName); }
    public StringProperty firstNameProperty() { return firstName; }
    public String getLastName() { return lastName.get(); }
    public void setLastName(String lName) { lastName.set(lName); }
    public StringProperty lastNameProperty() { return lastName; }
    public String getEmail() { return email.get(); }
    public void setEmail(String inMail) { email.set(inMail); }
    public StringProperty emailProperty() { return email; }  // if this method is commented out then the tableview will not refresh when the email is set.
  }
}

java – SimpleStringProperty and SimpleIntegerProperty TableView JavaFX

visual c++ – filling up an array in c++

visual c++ – filling up an array in c++

Using C++11

#include <algorithm>
#include <iostream>

int main() {
    char array[80];
    std::fill(std::begin(array),std::begin(array)+10,r);
}

Or, as mentioned in the comments you can use std::fill(array,array+10,r).

You can use the [] operator and assign a char value.

char y[80];
for(int b=0; b<10; ++b)
    y[b] = r;

And yes, std::fill is a more idiomatic and modern C++ way to do this, but you should know about the [] operator too!

visual c++ – filling up an array in c++

// ConsoleApp.cpp : Defines the entry point for the console application.
//

#include stdafx.h
#include <iostream>
#include <string>

using namespace std;

int fun(bool x,int y[],int length);
int funx(char y[]);
int functionx(bool IsMainProd, int MainProdId, int Addons[],int len);
int _tmain(int argc, _TCHAR* argv[])
{
    int AddonCancel[10];

    for( int i = 0 ; i<4 ;++i)
    {
        std::fill(std::begin(AddonCancel)+i,std::begin(AddonCancel)+i+1,i*5);
    }
    bool IsMainProduct (false);
    int MainProduct =4 ; 
    functionx(IsMainProduct,MainProduct,AddonCancel,4);

}

int functionx(bool IsMainProd, int MainProdId, int Addons[],int len)
{
    if(IsMainProd)
        std::cout<< Is Main Product;
    else
    {
        for(int x = 0 ; x<len;++x)
        {
          std::cout<< Addons[x];
        }
    }

    return 0 ; 
}

java : convert float to String and String to float

java : convert float to String and String to float

Using Java’s Float class.

float f = Float.parseFloat(25);
String s = Float.toString(25.0f);

To compare its always better to convert the string to float and compare as two floats. This is because for one float number there are multiple string representations, which are different when compared as strings (e.g. 25 != 25.0 != 25.00 etc.)

Float to string – String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

String to Float – Float.parseFloat()

String strAmount=100.20;
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

java : convert float to String and String to float

You can try this sample of code:

public class StringToFloat
{

  public static void main (String[] args)
  {

    // String s = fred;    // do this if you want an exception

    String s = 100.00;

    try
    {
      float f = Float.valueOf(s.trim()).floatValue();
      System.out.println(float f =  + f);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println(NumberFormatException:  + nfe.getMessage());
    }
  }
}

found here

apache spark – Difference in usecases for AWS Sagemaker vs Databricks?

apache spark – Difference in usecases for AWS Sagemaker vs Databricks?

SageMaker is a great tool for deployment, it simplifies a lot of processes configuring containers, you only need to write 2-3 lines to deploy the model as an endpoint and use it. SageMaker also provides the dev platform (Jupyter Notebook) which supports Python and Scala (sparkmagic kernal) developing, and i managed installing external scala kernel in jupyter notebook. Overall, SageMaker provides end-to-end ML services. Databricks has unbeatable Notebook environment for Spark development.

Conclusion

  1. Databricks is a better platform for Big data(scala, pyspark) Developing.(unbeatable notebook environment)
  2. SageMaker is better for Deployment. and if you are not working on big data, SageMaker is a perfect choice working with (Jupyter notebook + Sklearn + Mature containers + Super easy deployment).
  3. SageMaker provides real time inference, very easy to build and deploy, very impressive. you can check the official SageMaker Github.
    https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-python-sdk/scikit_learn_inference_pipeline

Having worked in both environments within the last year, I specifically remember:

  • Databricks having easy access to stored databases/tables to query out of and use Scala/Spark within the Jupyter Notebooks. I remember how nice it was to just see and preview the schemas and query quickly and be off to the races for research. I also remember the quick functionality to set up a timed job on a Notebook (re-run every month) and re-scale to job instance types (much cheaper) with some button clicks. These functionalities might exist somewhere in AWS, but I remember it being great in Databricks.
  • AWS SageMaker + Lambda + API Gateway: Legitimately, today, I worked through the deployment of AWS SageMaker + Lambda + API Gateway, and after getting used to some syntax and specifics of the Lambda + API Gateway it was pretty straightforward. Doing another AWS deployment wouldnt take more than 20 minutes (pending unique specificities). Other things like Model Monitoring and CloudWatch are nice as well. I did notice Jupyter Notebook Kernels for many languages like Python (what I did it in), R, and Scala, along with specific packages already pre-installed like conda and sagemaker ml packages and methods.

apache spark – Difference in usecases for AWS Sagemaker vs Databricks?