问:
What is a good practive to save hyperparamters for restoring and retraining
I just encounter an issue that I have a good model but forgot what hyperparamters I used. I just have the meta, index and data files. I searched if the hyperparamters are saved in those files. But it seems not the case. So what is the best way to save the hyperparamters together with the checkpoint files such that I can retrain at any times with the same parameters?</p>

答:
The simplest solution would be to pass them as a shorthand notation to the filename, e.g. naming the files something like:

```<code>Inceptionv4_bs64_lr0.001_Adam
</code>```

If that would make the filename too long, or if you already have a naming convention that you want to keep, just save a text file that has the same name as the other files with a different extension e.g. .hyperparams, that contains the information for the hyperparameters.

To save directly into the checkpoint or model files, you could define a tf.constant:

```<code>learning_rate = tf.constant(0.001)
</code>```

These would be saved in the graph definition and could therefore be recovered if you reload the model or checkpoint files.

If you want something more complex, tensorflow 2.0 has upgraded the HParams Class into a full Fledged API. This is a bit code heavy, but there is a tutorial notebook provided here. Functionality includes testing over hyperparameter ranges, writing hyperparameters to file and tensorboard visualizations.

Alternatively, there are also these external platforms that provide similiar functionality to 3., are more mature and also work with tensorflow:

MLflow

Comet.ml

Body:
The simplest solution would be to pass them as a shorthand notation to the filename, e.g. naming the files something like:

Inceptionv4_bs64_lr0.001_Adam

If that would make the filename too long, or if you already have a naming convention that you want to keep, just save a text file that has the same name as the other files with a different extension e.g. .hyperparams, that contains the information for the hyperparameters.

To save directly into the checkpoint or model files, you could define a tf.constant:

learning_rate = tf.constant(0.001)

These would be saved in the graph definition and could therefore be recovered if you reload the model or checkpoint files.

If you want something more complex, tensorflow 2.0 has upgraded the HParams Class into a full Fledged API. This is a bit code heavy, but there is a tutorial notebook provided here. Functionality includes testing over hyperparameter ranges, writing hyperparameters to file and tensorboard visualizations.

Alternatively, there are also these external platforms that provide similiar functionality to 3., are more mature and also work with tensorflow:

MLflow

Comet.ml


来源: stackexchange

问:
TableView cell request Focus
I'm new in JavaFX and have the following issue:

I have a tableview inside a BorderPane. I want it to focus on the last row/1st column when it's loaded. I have tried the following:

requestfocus()

scrollTo()

focusModel.focus()

selectionModel.select()

What happens is that the cell I want is indeed blue (as if it was selected) but the first cell has a blue border. So, when I try to use the arrow keys, the selected cell moves to the first row.

BTW, I'm using TornadoFX.

Any ideas?

Thanks in advance!

```<code>class CashflowTab : View() {
    override val root: HBox by fxml()
    private val mController : CashflowController by inject()
    private val mainView : MainView by inject()

    // Get the buttons
    private val buttonCashflow : Button by fxid("btnCashflow")

    init {
        // Setup the buttons
        buttonCashflow.action {
            setupCashflowTable()
        }
    }

    /** Displays the TableView for the Cashflow */
    private fun setupCashflowTable() {
        var initialFocus = true
        // List of entries for the category ComboBox
        val categoryList = mController.getCashFlowCategoryList()

        // Create the table
        val cashTable = tableview<CashEntry>(mController.getCashEntryList()) {
            isEditable = true
            column(Constants.COL_COUNT, CashEntry::countProperty)
            column(Constants.COL_DATE, CashEntry::dateProperty).makeEditable(LocaleDateConverter())
            column(Constants.COL_INCOME, CashEntry::incomeProperty).makeEditable(CurrencyConverter())
            column(Constants.COL_EXPENSES, CashEntry::expensesProperty).makeEditable(CurrencyConverter())
            column(Constants.COL_PROFIT, CashEntry::profitProperty).converter(CurrencyConverter())
            column(Constants.COL_TOTAL_PROFIT, CashEntry::totalProfitProperty).converter(CurrencyConverter())
            column(Constants.COL_COMMENTS, CashEntry::commentsProperty).makeEditable()
            column(Constants.COL_CATEGORY, CashEntry::categoryProperty).useComboBox(categoryList)

            // Scroll to and focus on the last cell on startup
            if (initialFocus) {
                val lastRow = mController.getCashEntryList().size - 1
                requestFocus()
                scrollTo(lastRow)
                focusModel.focus(lastRow)
                selectionModel.select(lastRow)
                initialFocus = false
            }

            onEditCommit {entry ->
                // Update the list
                mController.updateCashEntryList(entry)

                // Move to the next cell
                requestFocus()
                focusModel.focusRightCell()
                @Suppress("UNCHECKED_CAST")
                selectionModel.select(focusModel.focusedCell.row, focusModel.focusedCell.tableColumn as TableColumn<CashEntry, *>)
            }
            enableCellEditing()

            // Enable edit on key typed
            addEventHandler(KeyEvent.KEY_PRESSED) {keyEvent ->
                if (keyEvent.code.isDigitKey || keyEvent.code.isLetterKey) {
                    if (editingCell == null) {
                        val currentSelectedCell = selectedCell
                        if (currentSelectedCell != null && currentSelectedCell.tableColumn.isEditable) {
                            edit(currentSelectedCell.row, currentSelectedCell.tableColumn)
                        }
                    }
                }
            }
        }

        // Add the table to the view
        mainView.root.center = cashTable
        cashTable.tableMenuButtonVisibleProperty()

        // Ensure no other node can get focus
        cashTable.focusedProperty().onChange {
            val focusOwner = currentStage?.scene?.focusOwnerProperty()?.value

            // Check if the focus owner is the table or a cell
            if (focusOwner !is TableView<*> && focusOwner !is TextField) {
                cashTable.requestFocus()
            }
        }
    }
}
</code>```

答:
You should use

```<code>Platform.runLater(() -> {
    requestFocus();
    scrollTo(lastRow);
    ...
});
</code>```

to update the GUI.

ContentLicense: CC BY-SA 4.0

Title: TableView cell request Focus

Body:
I'm new in JavaFX and have the following issue:

I have a tableview inside a BorderPane. I want it to focus on the last row/1st column when it's loaded. I have tried the following:

requestfocus()

scrollTo()

focusModel.focus()

selectionModel.select()

What happens is that the cell I want is indeed blue (as if it was selected) but the first cell has a blue border. So, when I try to use the arrow keys, the selected cell moves to the first row.

BTW, I'm using TornadoFX.

Any ideas?

Thanks in advance!

class CashflowTab : View() {
    override val root: HBox by fxml()
    private val mController : CashflowController by inject()
    private val mainView : MainView by inject()

    // Get the buttons
    private val buttonCashflow : Button by fxid("btnCashflow")

    init {
        // Setup the buttons
        buttonCashflow.action {
            setupCashflowTable()
        }
    }

    /** Displays the TableView for the Cashflow */
    private fun setupCashflowTable() {
        var initialFocus = true
        // List of entries for the category ComboBox
        val categoryList = mController.getCashFlowCategoryList()

        // Create the table
        val cashTable = tableview<CashEntry>(mController.getCashEntryList()) {
            isEditable = true
            column(Constants.COL_COUNT, CashEntry::countProperty)
            column(Constants.COL_DATE, CashEntry::dateProperty).makeEditable(LocaleDateConverter())
            column(Constants.COL_INCOME, CashEntry::incomeProperty).makeEditable(CurrencyConverter())
            column(Constants.COL_EXPENSES, CashEntry::expensesProperty).makeEditable(CurrencyConverter())
            column(Constants.COL_PROFIT, CashEntry::profitProperty).converter(CurrencyConverter())
            column(Constants.COL_TOTAL_PROFIT, CashEntry::totalProfitProperty).converter(CurrencyConverter())
            column(Constants.COL_COMMENTS, CashEntry::commentsProperty).makeEditable()
            column(Constants.COL_CATEGORY, CashEntry::categoryProperty).useComboBox(categoryList)

            // Scroll to and focus on the last cell on startup
            if (initialFocus) {
                val lastRow = mController.getCashEntryList().size - 1
                requestFocus()
                scrollTo(lastRow)
                focusModel.focus(lastRow)
                selectionModel.select(lastRow)
                initialFocus = false
            }

            onEditCommit {entry ->
                // Update the list
                mController.updateCashEntryList(entry)

                // Move to the next cell
                requestFocus()
                focusModel.focusRightCell()
                @Suppress("UNCHECKED_CAST")
                selectionModel.select(focusModel.focusedCell.row, focusModel.focusedCell.tableColumn as TableColumn<CashEntry, *>)
            }
            enableCellEditing()

            // Enable edit on key typed
            addEventHandler(KeyEvent.KEY_PRESSED) {keyEvent ->
                if (keyEvent.code.isDigitKey || keyEvent.code.isLetterKey) {
                    if (editingCell == null) {
                        val currentSelectedCell = selectedCell
                        if (currentSelectedCell != null && currentSelectedCell.tableColumn.isEditable) {
                            edit(currentSelectedCell.row, currentSelectedCell.tableColumn)
                        }
                    }
                }
            }
        }

        // Add the table to the view
        mainView.root.center = cashTable
        cashTable.tableMenuButtonVisibleProperty()

        // Ensure no other node can get focus
        cashTable.focusedProperty().onChange {
            val focusOwner = currentStage?.scene?.focusOwnerProperty()?.value

            // Check if the focus owner is the table or a cell
            if (focusOwner !is TableView<*> && focusOwner !is TextField) {
                cashTable.requestFocus()
            }
        }
    }
}

Body:
You should use

Platform.runLater(() -> {
    requestFocus();
    scrollTo(lastRow);
    ...
});

to update the GUI.


问:
Android :: How To Read Not Visible Child Elements Of List View?
I have a list view which contains some 20 odd items from database along with a two Buttons and an extra TextView as a counter enclosed within linear layout. The two buttons usually for increment and decrement the value in an extra TextView. What i want is when i  press button outside the listView should fetch all items along with an value of an extra text. Right now I can fetch Linear layouts and there child items which are visible on screen i.e. out 20 items 10 are visible on screen, so my question is how to fetch the remaining items along with extra Textview values enclosed within linear layout which are not visible which can be viewed when we scroll the Listview?

Here is main.xml file

```<code>   <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation= "horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="#CBCBCB">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget64"
android:background="@drawable/toolbar_color"
android:layout_x="0px"
android:layout_y="0px"
android:layout_width="match_parent" android:layout_height="40dip">
    <Button
    android:id="@+id/save_creature_for_encounter"
    android:layout_marginTop="5px"
    android:textSize="10dip"
    android:textColor="#ffffff"
    android:textStyle="bold"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:background="@drawable/onclick_button_bg"
    android:layout_width="40dip" android:layout_height="50dip"
    android:text="Save"/>

    <Button
    android:id="@+id/back_show_encounter"
    android:layout_width="80dip"
    android:layout_marginTop="5px"
    android:text="Cancel"
    android:textSize="10dip"
    android:textColor="#ffffff"
    android:textStyle="bold"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:background="@drawable/button_color"
    android:layout_height="50dip">
    </Button>
  </RelativeLayout>

        <ListView
    android:id="@+id/list_view"
    android:background="#ffffff"
        android:fadingEdge="none"
        android:cacheColorHint="#ffffff"
        android:layout_weight="1"
               android:layout_gravity="center"
              android:scrollbars="vertical"
     android:layout_marginTop="28dip" android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>
      </FrameLayout>
</code>```

And here is my custom_list.xml file

```<code>        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:gravity="left|center"
        android:paddingBottom="5px"
        android:paddingTop="5px" android:paddingLeft="5px" android:layout_width="wrap_content" android:layout_height="wrap_content">
        <TextView android:text="test" android:id="@+id/item_creatures_to_encounter"
        android:layout_marginLeft="10px" android:layout_width="180dip" android:layout_height="wrap_content"></TextView>
        <Button
                android:id="@+id/desc"
                android:layout_width="30px"
                android:layout_height="30px"
                android:layout_marginTop="5px"
                android:text="-"
                android:textSize="10dip"
                android:textColor="#ffffff"
                android:textStyle="bold"
                android:layout_alignTop="@+id/widget66"
                android:layout_alignParentRight="true"
                android:onClick="myDescClickHandler">
                >
                </Button>
        <Button
                android:id="@+id/asc"
                android:layout_width="30px"
                android:layout_height="30px"
                android:layout_marginTop="5px"
                android:text="+"
                android:textSize="10dip"
                android:textColor="#ffffff"
                android:textStyle="bold"
                android:layout_alignTop="@+id/widget66"
                android:layout_alignParentRight="true"
                android:onClick="myAscClickHandler">

                >
                </Button>

                <TextView android:text="@string/counter" android:id="@+id/counter"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip" android:layout_width="30dip"></TextView>
        </LinearLayout>
</code>```

Here is my custom Adapter file

```<code>   public class DomainAdapter extends SimpleCursorAdapter{

    private LayoutInflater mInflater;

    public DomainAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
        mInflater = LayoutInflater.from(context);
    }

    public View getView(int position, View convertView, ViewGroup parent, Cursor data) {
        // A ViewHolder keeps references to children views to avoid unneccessary calls
        // to findViewById() on each row.
        //final ViewHolder holder;
        View row = super.getView(position, convertView, parent);
        ViewHolder holder=(ViewHolder)row.getTag();
        if (holder == null) {
            holder = new ViewHolder(row);
            row.setTag(holder);
            holder.add = (Button) row.findViewById(R.id.asc);
            Button.OnClickListener b =
                new Button.OnClickListener() {
                public void onClick(View v) {
                    LinearLayout parent = (LinearLayout)v.getParent();
                    TextView label=(TextView)parent.findViewById(R.id.counter);
                    Log.d("AAAAJJJAAA", ""+ parent);
                    CharSequence value = ((TextView) label).getText();
                    int count = Integer.parseInt((String) value);
                     count++;
                     String inc = String.format("%d", count);
                    label.setText(inc);
                    //parent.refreshDrawableState();
                }
            };
            holder.add.setOnClickListener(b);
        }
        return row;
    }
</code>```

}

答:
The Views that are outside the visible area does not exists. ListView creates only the amount of views that are on the screen.

When you scroll, and a View disappears it reuses that View. It actually asks for the Adapter to modify the parameters of the View and it uses the modified View.

Example:

Let view1 be your first row (the one that's text is avatar). When you scroll down, "avatar" disappears and a new one becomes visible at the bottom. The ListView doesn't need view1 anymore, because it is not visible. So it gives view1 to the Adapter and asks it to modify view1's parameters to be the new row. The adapter sets the text on view1 to the next row (eg. "human") and returns it to the ListView. The ListView will display the view1 at the bottom of the list.

So basically the views that are outside the visible area doesn't exists.

What you can do: save the count to the adapter when a user presses the + or - buttons.

Then you can ask for the data items (listView.getItemAtPosition(int position)) and count those.

Code sample for this:

```<code>class DataForView {
    int counter;
}

ListView mListView;
...

int sumCounter = 0;
for (int i=0; i<mListView.getCount(); i++) {
  sumCounter += ((DataForView)mListView.getItem(i)).counter;
}
</code>```

Look at the following tutorial for custom Adapters:

http://commonsware.com/Android/excerpt.pdf

ContentLicense: CC BY-SA 3.0

Body:
I have a list view which contains some 20 odd items from database along with a two Buttons and an extra TextView as a counter enclosed within linear layout. The two buttons usually for increment and decrement the value in an extra TextView. What i want is when i  press button outside the listView should fetch all items along with an value of an extra text. Right now I can fetch Linear layouts and there child items which are visible on screen i.e. out 20 items 10 are visible on screen, so my question is how to fetch the remaining items along with extra Textview values enclosed within linear layout which are not visible which can be viewed when we scroll the Listview?

Here is main.xml file

   <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation= "horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="#CBCBCB">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget64"
android:background="@drawable/toolbar_color"
android:layout_x="0px"
android:layout_y="0px"
android:layout_width="match_parent" android:layout_height="40dip">
    <Button
    android:id="@+id/save_creature_for_encounter"
    android:layout_marginTop="5px"
    android:textSize="10dip"
    android:textColor="#ffffff"
    android:textStyle="bold"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:background="@drawable/onclick_button_bg"
    android:layout_width="40dip" android:layout_height="50dip"
    android:text="Save"/>

    <Button
    android:id="@+id/back_show_encounter"
    android:layout_width="80dip"
    android:layout_marginTop="5px"
    android:text="Cancel"
    android:textSize="10dip"
    android:textColor="#ffffff"
    android:textStyle="bold"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:background="@drawable/button_color"
    android:layout_height="50dip">
    </Button>
  </RelativeLayout>

        <ListView
    android:id="@+id/list_view"
    android:background="#ffffff"
        android:fadingEdge="none"
        android:cacheColorHint="#ffffff"
        android:layout_weight="1"
               android:layout_gravity="center"
              android:scrollbars="vertical"
     android:layout_marginTop="28dip" android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>
      </FrameLayout>

And here is my custom_list.xml file

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:gravity="left|center"
        android:paddingBottom="5px"
        android:paddingTop="5px" android:paddingLeft="5px" android:layout_width="wrap_content" android:layout_height="wrap_content">
        <TextView android:text="test" android:id="@+id/item_creatures_to_encounter"
        android:layout_marginLeft="10px" android:layout_width="180dip" android:layout_height="wrap_content"></TextView>
        <Button
                android:id="@+id/desc"
                android:layout_width="30px"
                android:layout_height="30px"
                android:layout_marginTop="5px"
                android:text="-"
                android:textSize="10dip"
                android:textColor="#ffffff"
                android:textStyle="bold"
                android:layout_alignTop="@+id/widget66"
                android:layout_alignParentRight="true"
                android:onClick="myDescClickHandler">
                >
                </Button>
        <Button
                android:id="@+id/asc"
                android:layout_width="30px"
                android:layout_height="30px"
                android:layout_marginTop="5px"
                android:text="+"
                android:textSize="10dip"
                android:textColor="#ffffff"
                android:textStyle="bold"
                android:layout_alignTop="@+id/widget66"
                android:layout_alignParentRight="true"
                android:onClick="myAscClickHandler">

                >
                </Button>

                <TextView android:text="@string/counter" android:id="@+id/counter"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip" android:layout_width="30dip"></TextView>
        </LinearLayout>

Here is my custom Adapter file

   public class DomainAdapter extends SimpleCursorAdapter{

    private LayoutInflater mInflater;

    public DomainAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
        mInflater = LayoutInflater.from(context);
    }

    public View getView(int position, View convertView, ViewGroup parent, Cursor data) {
        // A ViewHolder keeps references to children views to avoid unneccessary calls
        // to findViewById() on each row.
        //final ViewHolder holder;
        View row = super.getView(position, convertView, parent);
        ViewHolder holder=(ViewHolder)row.getTag();
        if (holder == null) {
            holder = new ViewHolder(row);
            row.setTag(holder);
            holder.add = (Button) row.findViewById(R.id.asc);
            Button.OnClickListener b =
                new Button.OnClickListener() {
                public void onClick(View v) {
                    LinearLayout parent = (LinearLayout)v.getParent();
                    TextView label=(TextView)parent.findViewById(R.id.counter);
                    Log.d("AAAAJJJAAA", ""+ parent);
                    CharSequence value = ((TextView) label).getText();
                    int count = Integer.parseInt((String) value);
                     count++;
                     String inc = String.format("%d", count);
                    label.setText(inc);
                    //parent.refreshDrawableState();
                }
            };
            holder.add.setOnClickListener(b);
        }
        return row;
    }

}

Body:
The Views that are outside the visible area does not exists. ListView creates only the amount of views that are on the screen.

When you scroll, and a View disappears it reuses that View. It actually asks for the Adapter to modify the parameters of the View and it uses the modified View.

Example:

Let view1 be your first row (the one that's text is avatar). When you scroll down, "avatar" disappears and a new one becomes visible at the bottom. The ListView doesn't need view1 anymore, because it is not visible. So it gives view1 to the Adapter and asks it to modify view1's parameters to be the new row. The adapter sets the text on view1 to the next row (eg. "human") and returns it to the ListView. The ListView will display the view1 at the bottom of the list.

So basically the views that are outside the visible area doesn't exists.

What you can do: save the count to the adapter when a user presses the + or - buttons.

Then you can ask for the data items (listView.getItemAtPosition(int position)) and count those.

Code sample for this:

class DataForView {
    int counter;
}

ListView mListView;
...

int sumCounter = 0;
for (int i=0; i<mListView.getCount(); i++) {
  sumCounter += ((DataForView)mListView.getItem(i)).counter;
}

Look at the following tutorial for custom Adapters:

http://commonsware.com/Android/excerpt.pdf


问:
I can't import java.util.date in activity
In my project I need to to use current date and time. For this I'm importing java.util.Date.
This import is working fine few hours ago. But I have an error in R file ( r cannot resolve ) and this error is because of some xml mistake. When I resolved that issue and sync project again that error is gone. But after that I cannot able to import (java.util.Date , java.util.Calendar) in any of my project.

I tried to import this in my newly created project. But still not found java.util.Date.
Even in my old projects where this import is working fine few days ago. Currently it is not working and showing red.

```<code>import java.util.Calendar;

import java.util.Date;
</code>```

Date and Calendar are showing in red.

```<code>Date d=new Date();

SimpleDateFormat sdf=new SimpleDateFormat("hh:mm");
</code>```

Above Date and SimpleDateFormat are showing in red.
And when I hover over there and press (control+alt) IDE will give option to import java.sql.Date not java.util.Date.

答: I had this issue one time with java.util.calendar. Invalidating Cache/Restart worked for me.

Body:
In my project I need to to use current date and time. For this I'm importing java.util.Date.
This import is working fine few hours ago. But I have an error in R file ( r cannot resolve ) and this error is because of some xml mistake. When I resolved that issue and sync project again that error is gone. But after that I cannot able to import (java.util.Date , java.util.Calendar) in any of my project.

I tried to import this in my newly created project. But still not found java.util.Date.
Even in my old projects where this import is working fine few days ago. Currently it is not working and showing red.

import java.util.Calendar;

import java.util.Date;

Date and Calendar are showing in red.

Date d=new Date();

SimpleDateFormat sdf=new SimpleDateFormat("hh:mm");

Above Date and SimpleDateFormat are showing in red.
And when I hover over there and press (control+alt) IDE will give option to import java.sql.Date not java.util.Date.


问:
Weighted average element-wise between two arrays
I have two arrays of number and I want to compute a weighted average element-wise between these array and store it in a new array.

The solution I use for now is :

```<code>array_1 = [0,1,2,3,4]
array_2 = [2,3,4,5,6]

weight_1 = 0.5
weight_2 = 0.5

array_3 = np.zeros(array_1.shape)

for i in range(0, len(array_1)) :
    array_3[i] = np.average(a=[array_1[i], array_2[i]], weights=[weight_1, weight_2])

print(array_3)
>> [1,2,3,4,5]
</code>```

The problem is that it is not really efficient. How can I do that more efficiently ?

答:
Just use NumPy's vectorised operations. To do so, first convert your lists to arrays and then just multiply each array with the respective weight and take the sum

```<code>import numpy as np

array_1 = np.array([0,1,2,3,4])
array_2 = np.array([2,3,4,5,6])

weight_1 = 0.5
weight_2 = 0.5

array_3 = weight_1*array_1 + weight_2*array_2
# array([1., 2., 3., 4., 5.])
</code>```

A direct NumPy solution using np.average would be the following, where axis=0 means take the average row wise (using both columns). np.vstack() simply stacks the two arrays vertically.

```<code>np.average(np.vstack((array_1, array_2)), axis=0, weights=[weight_1, weight_2])
</code>```

As pointed out by @yatu, you can also pass a list of your arrays and specify the axis

```<code>np.average([array_1, array_2], axis=0, weights=[weight_1, weight_2])
</code>```

Timing comparison inspired by the comments on @yatu's answer: As you can see, list comprehension and zip is slightly faster here but then this performance is for small arrays. I am sure, for large arrays, the vectorised solution will take over

Devesh's method

```<code>%timeit result = [ item1 * weight_1 + item2 * weight_2 for item1, item2 in zip(array_1, array_2)]
# 25.5 µs ± 3.75 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

```<code>%timeit np.average([array_1, array_2], axis=0, weights=[weight_1, weight_2])
# 42.9 µs ± 2.94 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

```<code>%timeit np.average(np.vstack((array_1, array_2)), axis=0, weights=[weight_1, weight_2])
# 44.8 µs ± 4.98 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

Body:
I have two arrays of number and I want to compute a weighted average element-wise between these array and store it in a new array.

The solution I use for now is :

array_1 = [0,1,2,3,4]
array_2 = [2,3,4,5,6]

weight_1 = 0.5
weight_2 = 0.5

array_3 = np.zeros(array_1.shape)

for i in range(0, len(array_1)) :
    array_3[i] = np.average(a=[array_1[i], array_2[i]], weights=[weight_1, weight_2])

print(array_3)
>> [1,2,3,4,5]

The problem is that it is not really efficient. How can I do that more efficiently ?

Body:
Just use NumPy's vectorised operations. To do so, first convert your lists to arrays and then just multiply each array with the respective weight and take the sum

import numpy as np

array_1 = np.array([0,1,2,3,4])
array_2 = np.array([2,3,4,5,6])

weight_1 = 0.5
weight_2 = 0.5

array_3 = weight_1*array_1 + weight_2*array_2
# array([1., 2., 3., 4., 5.])

A direct NumPy solution using np.average would be the following, where axis=0 means take the average row wise (using both columns). np.vstack() simply stacks the two arrays vertically.

np.average(np.vstack((array_1, array_2)), axis=0, weights=[weight_1, weight_2])

As pointed out by @yatu, you can also pass a list of your arrays and specify the axis

np.average([array_1, array_2], axis=0, weights=[weight_1, weight_2])

Timing comparison inspired by the comments on @yatu's answer: As you can see, list comprehension and zip is slightly faster here but then this performance is for small arrays. I am sure, for large arrays, the vectorised solution will take over

Devesh's method

%timeit result = [ item1 * weight_1 + item2 * weight_2 for item1, item2 in zip(array_1, array_2)]
# 25.5 µs ± 3.75 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit np.average([array_1, array_2], axis=0, weights=[weight_1, weight_2])
# 42.9 µs ± 2.94 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit np.average(np.vstack((array_1, array_2)), axis=0, weights=[weight_1, weight_2])
# 44.8 µs ± 4.98 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)


问:
Im getting a wrong type in Edit Controller, what should i do?
I'm currently doing a Edit class in the main controller. It seems to be everything fine, but there's an error when I build the program

This is the class Edit in the MoviesController:

```<code>public ActionResult Edit(int? Id)
    {
        if (Id == null)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                MoviesData moviesData = db.MoviesData.Find(Id);
        if (moviesData == null)
            return HttpNotFound();

        return View(moviesData);
    }
</code>```

(MoviesData is the database's table instance)

This is the View model:

```<code>public class MovieViewModel
{
    public int MovieID { get; set; }
    public string MovieName { get; set; }
    public string MovieDescription { get; set; }
    public string MovieCategory { get; set; }
    public string MovieYear { get; set; }
}
</code>```

Everytime I try to build the program this error appears:

'System.Data.Entity.DynamicProxies.MoviesData_4D99853B016ED5E65AF8566A78AEB274D91AD066D99E2B2FA50D6EA0156AAA21', but this dictionary requires a model item of type 'WebApplication3.Models.MovieViewModel'

I understand what the error means, but I have no idea how to change it.

答:
You need to convert the DTO to your viewmodel:</p>

```<code>MovieViewModel viewModel = new MovieViewModel()
{
   MovieID = moviesData.MovieID (or maybe only .ID?),
   MovieName = moviesData.MovieName

   etc....

}

return View(viewModel );
</code>```

Body:
I'm currently doing a Edit class in the main controller. It seems to be everything fine, but there's an error when I build the program

This is the class Edit in the MoviesController:

public ActionResult Edit(int? Id)
    {
        if (Id == null)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                MoviesData moviesData = db.MoviesData.Find(Id);
        if (moviesData == null)
            return HttpNotFound();

        return View(moviesData);
    }

(MoviesData is the database's table instance)

This is the View model:

public class MovieViewModel
{
    public int MovieID { get; set; }
    public string MovieName { get; set; }
    public string MovieDescription { get; set; }
    public string MovieCategory { get; set; }
    public string MovieYear { get; set; }
}

Everytime I try to build the program this error appears:

'System.Data.Entity.DynamicProxies.MoviesData_4D99853B016ED5E65AF8566A78AEB274D91AD066D99E2B2FA50D6EA0156AAA21', but this dictionary requires a model item of type 'WebApplication3.Models.MovieViewModel'

I understand what the error means, but I have no idea how to change it.

Body:
You need to convert the DTO to your viewmodel:

MovieViewModel viewModel = new MovieViewModel()
{
   MovieID = moviesData.MovieID (or maybe only .ID?),
   MovieName = moviesData.MovieName

   etc....

}

return View(viewModel );


问:
Call a function defined inside script tags, from curly braces
I tried importing a javascript library with a script tag, and then called a function from it inside React curly braces. I got an error telling me that the function wasn't defined.

```<code><script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<p>{marked(string)}</p>
</code>```

I know that I could import the library inside the react App file, or that I could use another script tag to call the function, but my question is: is there a way to call functions defined inside a script tag from React curly braces?? And viceversa?

答:
It's not clear exactly what you're trying to do, but you can't import a library using the script tag. That's for html only. If you really want to do it that way, then you would have to do that script tag in the HTML file.

Or, the more standard approach, would be to install it using npm npm install myLibrary, then in the jsx file, you would do `import library from "myLibrary";

Let me know if you have any questions.

Body:
I tried importing a javascript library with a script tag, and then called a function from it inside React curly braces. I got an error telling me that the function wasn't defined.

{marked(string)}

I know that I could import the library inside the react App file, or that I could use another script tag to call the function, but my question is: is there a way to call functions defined inside a script tag from React curly braces?? And viceversa?


问:
How many wiki instances to install?
I've been asked to install Mediawiki to house documentation for a company intranet. Furthermore, I've been asked to install several instances - one per contributing group: non-technical users get one, developers one, management one, etc. The idea is to provide separate web spaces for each group. Is there a way to achieve separation within one instance?

答: The namespaces are there for a reason.</p>

ContentLicense: CC BY-SA 2.5

Title: How many wiki instances to install?

LastEditorDisplayName: nzpcmad

Body: The namespaces are there for a reason.

OwnerDisplayName: yancy


问:
How to convert array of string to simple string in JavaScript?
I have the following JavaScript array of strings:

```<code>arrayOfString = ['a', 'b,c', 'd,e', 'f'];
</code>```

And I would like to convert this array to an array similar to this:

```<code>myString = ["a", "b", "c", "d", "e", "f"];
</code>```

How I can accomplish that?

答:
Use map with split, reduce and concat:

const arrayOfString = ['a', 'b,c', 'd,e', 'f'];
const myString = arrayOfString.map(e => e.split(",")).reduce((acc, curr) => acc.concat(curr));
console.log(myString);```

Explanation:

Use map to iterate through the array, then split out each letter, then use reduce and concat as well-supported methods to flatten the resulting multi-dimensional array, and finally assign the result to myString.

Body:
I have the following JavaScript array of strings:

arrayOfString = ['a', 'b,c', 'd,e', 'f'];

And I would like to convert this array to an array similar to this:

myString = ["a", "b", "c", "d", "e", "f"];

How I can accomplish that?

Body:
Use map with split, reduce and concat:

const arrayOfString = ['a', 'b,c', 'd,e', 'f'];
const myString = arrayOfString.map(e => e.split(",")).reduce((acc, curr) => acc.concat(curr));
console.log(myString);

Explanation:

Use map to iterate through the array, then split out each letter, then use reduce and concat as well-supported methods to flatten the resulting multi-dimensional array, and finally assign the result to myString.


问:
How to fill forward value when specify one condition for another column?
I am analyzing one table like below. There are several None values in offer_id column when the event column shows transaction. I will like to fill None by the value forward only if the previous event is offer viewed, otherwise, fill the None value as 0 or just leave it as none.

The dataframe is:

```<code>df = pd.DataFrame({'event': ['offer_received', 'offer_viewed','transaction', 'transaction', 'offer_received', 'transaction'], 'user':['A','A','A','A','A','A'], 'value':[0, 0, 1.09, 2.55, 0, 3.02], 'offer_id': ['0b1e1539f2cc45b7b9fa7c272da2e1d7', '0b1e1539f2cc45b7b9fa7c272da2e1d7', 'None', 'None', '3f207df678b143eea3cee63160fa8bed', 'None'], 'days':[0, 0.25, 9.75, 11, 0,9.75]})
</code>```

```<code>event           user   value    offer_id                            days
offer received  A      0.00     0b1e1539f2cc45b7b9fa7c272da2e1d7    0.00
offer viewed    A      0.00     0b1e1539f2cc45b7b9fa7c272da2e1d7    0.25
transaction     A      1.09     None                                9.75
transaction     A      2.55     None                                11
offer received  A      0.00     3f207df678b143eea3cee63160fa8bed    0.00
transaction     A      3,02     None                                9.75

</code>```

I have tried to use df.offer_id.fillna(method = 'ffill') but I just don´t know how can I put the condition on the event column when the previous event is offer_viewed then fill offer_id of transaction by using (method = 'ffill').

My expect result will be like this:

```<code>event           user   value    offer_id                            days
offer received  A      0.00     0b1e1539f2cc45b7b9fa7c272da2e1d7    0.00
offer viewed    A      0.00     0b1e1539f2cc45b7b9fa7c272da2e1d7    0.2
transaction     A      1.09     0b1e1539f2cc45b7b9fa7c272da2e1d7    9.75
transaction     A      2.55     0b1e1539f2cc45b7b9fa7c272da2e1d7    11
offer received  A      0.00     3f207df678b143eea3cee63160fa8bed    0.00
transaction     A      3,02     None                                9.75

</code>```

答:
I think you can get there with shift(), ffill(), and where():

df = pd.DataFrame({'e': ['r', 'v', 't', 'r', 't'], 'oid': [1, 1, np.nan, 2, np.nan]})
df
#    e  oid
# 0  r  1.0
# 1  v  1.0
# 2  t  NaN
# 3  r  2.0
# 4  t  NaN
df.oid = df.oid.ffill().where(df.e.shift() == 'v', df.oid)
df
#    e  oid
# 0  r  1.0
# 1  v  1.0
# 2  t  1.0
# 3  r  2.0
# 4  t  NaN

```

<p>You can even skip the <code>ffill()</code> and use <code>shift()</code> twice:</p>

<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'e': ['r', 'v', 't', 'r', 't'], 'oid': [1, 1, np.nan, 2, np.nan]})

df.oid = df.oid.shift().where(df.e.shift() == 'v', df.oid)
df
#    e  oid
# 0  r  1.0
# 1  v  1.0
# 2  t  1.0
# 3  r  2.0
# 4  t  NaN
</code>```

Body:
I am analyzing one table like below. There are several None values in offer_id column when the event column shows transaction. I will like to fill None by the value forward only if the previous event is offer viewed, otherwise, fill the None value as 0 or just leave it as none.

The dataframe is:

df = pd.DataFrame({'event': ['offer_received', 'offer_viewed','transaction', 'transaction', 'offer_received', 'transaction'], 'user':['A','A','A','A','A','A'], 'value':[0, 0, 1.09, 2.55, 0, 3.02], 'offer_id': ['0b1e1539f2cc45b7b9fa7c272da2e1d7', '0b1e1539f2cc45b7b9fa7c272da2e1d7', 'None', 'None', '3f207df678b143eea3cee63160fa8bed', 'None'], 'days':[0, 0.25, 9.75, 11, 0,9.75]})

event           user   value    offer_id                            days
offer received  A      0.00     0b1e1539f2cc45b7b9fa7c272da2e1d7    0.00
offer viewed    A      0.00     0b1e1539f2cc45b7b9fa7c272da2e1d7    0.25
transaction     A      1.09     None                                9.75
transaction     A      2.55     None                                11
offer received  A      0.00     3f207df678b143eea3cee63160fa8bed    0.00
transaction     A      3,02     None                                9.75

I have tried to use df.offer_id.fillna(method = 'ffill') but I just don´t know how can I put the condition on the event column when the previous event is offer_viewed then fill offer_id of transaction by using (method = 'ffill').

My expect result will be like this:

event           user   value    offer_id                            days
offer received  A      0.00     0b1e1539f2cc45b7b9fa7c272da2e1d7    0.00
offer viewed    A      0.00     0b1e1539f2cc45b7b9fa7c272da2e1d7    0.2
transaction     A      1.09     0b1e1539f2cc45b7b9fa7c272da2e1d7    9.75
transaction     A      2.55     0b1e1539f2cc45b7b9fa7c272da2e1d7    11
offer received  A      0.00     3f207df678b143eea3cee63160fa8bed    0.00
transaction     A      3,02     None                                9.75

Body:
I think you can get there with shift(), ffill(), and where():

df = pd.DataFrame({'e': ['r', 'v', 't', 'r', 't'], 'oid': [1, 1, np.nan, 2, np.nan]})
df
#    e  oid
# 0  r  1.0
# 1  v  1.0
# 2  t  NaN
# 3  r  2.0
# 4  t  NaN
df.oid = df.oid.ffill().where(df.e.shift() == 'v', df.oid)
df
#    e  oid
# 0  r  1.0
# 1  v  1.0
# 2  t  1.0
# 3  r  2.0
# 4  t  NaN

You can even skip the ffill() and use shift() twice:

df = pd.DataFrame({'e': ['r', 'v', 't', 'r', 't'], 'oid': [1, 1, np.nan, 2, np.nan]})

df.oid = df.oid.shift().where(df.e.shift() == 'v', df.oid)
df
#    e  oid
# 0  r  1.0
# 1  v  1.0
# 2  t  1.0
# 3  r  2.0
# 4  t  NaN


问:
chart.js streaming data plugin data format or config error
I'm trying to implement a realtime streaming data chart that reads off a page that outputs the last few points of data every second, using the chart.js-plugin-streaming plugin by nagix.

I am reading off of an array in a URL because the chart "resolution" changes depending on which sensor is attached to the backend. Some of them output 1/second, but some of them output 10/second, and in the second case, refreshing the chart 10 times per second doesn't sound like a good idea, both because of processing power (old computers) and number of requests sent to the sensors.

So my URL outputs an array of objects for the last 20 points of data (roughly 2 to 20 seconds worth of data), and I refresh the chart 1 time a second.

I was hoping that the chart would just append only the new points, but I'm having weird behaviour. I've checked the timestamps and they are correct.

The data array is fetched using a simple jQuery $.get() call to the Django view URL that generates the array each time it is called.

This is an example of the URL output per call, for a 1/second sensor:

```<code>[
{y: 0.74, x: 1558531380957},
{y: 0.96, x: 1558531379950},
{y: 1.08, x: 1558531378942},
{y: 1.11, x: 1558531377939},
{y: 1.13, x: 1558531376932},
{y: 1.1, x: 1558531375930},
{y: 0.59, x: 1558531374914},
{y: 0.75, x: 1558531373911},
{y: 1.25, x: 1558531372902},
{y: 0.75, x: 1558531371898},
{y: 0.85, x: 1558531370893},
{y: 0.59, x: 1558531369889},
{y: 0.4, x: 1558531368887},
{y: 1.08, x: 1558531367879},
{y: 1.31, x: 1558531366871},
{y: 0.63, x: 1558531365866},
{y: 1.19, x: 1558531364859},
{y: 1.26, x: 1558531363854},
{y: 0.92, x: 1558531362848},
{y: 1.31, x: 1558531361837},
]
</code>```

The next time it is called, the output will have removed the first point, the array would "scroll" and 1 new points will be show up at the tail end.

The objects inside the array have format: {"y": <float>, "x": <timestamp-in-ms>}

My chart config:

```<code>$(document).ready(function() {

    var chartColors = {
        red: 'rgb(255, 99, 132)',
        blue: 'rgb(54, 162, 235)'
    };

    var color = Chart.helpers.color;

    var config = {
        type: 'line',
        data: {
            datasets: [{
                label: 'Z-Score',
                backgroundColor: color(chartColors.blue).alpha(0.75).rgbString(),
                borderColor: chartColors.red,
                fill: false,
                lineTension: 0,
                data: []
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            title: {
                display: false,
            },
            scales: {
                xAxes: [{
                    type: 'realtime',
                    realtime: {
                        duration: 60000,
                        refresh: 1000,
                        delay: 2000,
                        pause: false,
                        ttl: undefined,
                        frameRate: 48,

                        onRefresh: function(chart) {
                            var data = []
                            $.get( "{% url 'live_z_score' %}", function(zScoreJSON) {
                                data = zScoreJSON
                                Array.prototype.push.apply(
                                    chart.data.datasets[0].data, data
                                );
                            });
                        }
                    }
                }],
                yAxes: [{
                    scaleLabel: {
                        display: true,
                        labelString: 'value'
                    }
                }]
            },
            tooltips: {
                mode: 'nearest',
                intersect: false
            },
            hover: {
                mode: 'nearest',
                intersect: false
            }
        }
    };

    var ctx = document.getElementById('myChart').getContext('2d');
    window.myChart = new Chart(ctx, config);

});
</code>```

At this point it sort of works, except I'm having weird behaviour where a line would connect the first point to all subsequent points:

Example GIF (GIF size was too large, it's about 40 seconds long)

It seems like the graph is creating a new line each time it fetches new data, instead of dumping the previous line? I'm not sure how it handles data internally.

At this point I'm not sure exactly what the problem might be. The chart sort-of works, as it does create a line that is accurate to the graph, but then it seems like it's joining the first point in the array together with the latest point in the array. You can see this behaviour in the GIF.

答:
This is because you are pushing 20 data points in onRefresh() every second, but only one data point out of 20 points is new and the rest are already inserted ones. This plugin doesn't dedup the data even if the same data with the same timestamp exists, so you see the line iterating the same points over and over.

A workaround would be to store the latest timestamp in your array when it is inserted, and to filter out the older data in the next onRefresh call so that only new data is pushed to chart.data.datasets[0].data.

Body:
I'm trying to implement a realtime streaming data chart that reads off a page that outputs the last few points of data every second, using the chart.js-plugin-streaming plugin by nagix.

I am reading off of an array in a URL because the chart "resolution" changes depending on which sensor is attached to the backend. Some of them output 1/second, but some of them output 10/second, and in the second case, refreshing the chart 10 times per second doesn't sound like a good idea, both because of processing power (old computers) and number of requests sent to the sensors.

So my URL outputs an array of objects for the last 20 points of data (roughly 2 to 20 seconds worth of data), and I refresh the chart 1 time a second.

I was hoping that the chart would just append only the new points, but I'm having weird behaviour. I've checked the timestamps and they are correct.

The data array is fetched using a simple jQuery $.get() call to the Django view URL that generates the array each time it is called.

This is an example of the URL output per call, for a 1/second sensor:

[
{y: 0.74, x: 1558531380957},
{y: 0.96, x: 1558531379950},
{y: 1.08, x: 1558531378942},
{y: 1.11, x: 1558531377939},
{y: 1.13, x: 1558531376932},
{y: 1.1, x: 1558531375930},
{y: 0.59, x: 1558531374914},
{y: 0.75, x: 1558531373911},
{y: 1.25, x: 1558531372902},
{y: 0.75, x: 1558531371898},
{y: 0.85, x: 1558531370893},
{y: 0.59, x: 1558531369889},
{y: 0.4, x: 1558531368887},
{y: 1.08, x: 1558531367879},
{y: 1.31, x: 1558531366871},
{y: 0.63, x: 1558531365866},
{y: 1.19, x: 1558531364859},
{y: 1.26, x: 1558531363854},
{y: 0.92, x: 1558531362848},
{y: 1.31, x: 1558531361837},
]

The next time it is called, the output will have removed the first point, the array would "scroll" and 1 new points will be show up at the tail end.

The objects inside the array have format: {"y": <float>, "x": <timestamp-in-ms>}

My chart config:

$(document).ready(function() {

    var chartColors = {
        red: 'rgb(255, 99, 132)',
        blue: 'rgb(54, 162, 235)'
    };

    var color = Chart.helpers.color;

    var config = {
        type: 'line',
        data: {
            datasets: [{
                label: 'Z-Score',
                backgroundColor: color(chartColors.blue).alpha(0.75).rgbString(),
                borderColor: chartColors.red,
                fill: false,
                lineTension: 0,
                data: []
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            title: {
                display: false,
            },
            scales: {
                xAxes: [{
                    type: 'realtime',
                    realtime: {
                        duration: 60000,
                        refresh: 1000,
                        delay: 2000,
                        pause: false,
                        ttl: undefined,
                        frameRate: 48,

                        onRefresh: function(chart) {
                            var data = []
                            $.get( "{% url 'live_z_score' %}", function(zScoreJSON) {
                                data = zScoreJSON
                                Array.prototype.push.apply(
                                    chart.data.datasets[0].data, data
                                );
                            });
                        }
                    }
                }],
                yAxes: [{
                    scaleLabel: {
                        display: true,
                        labelString: 'value'
                    }
                }]
            },
            tooltips: {
                mode: 'nearest',
                intersect: false
            },
            hover: {
                mode: 'nearest',
                intersect: false
            }
        }
    };

    var ctx = document.getElementById('myChart').getContext('2d');
    window.myChart = new Chart(ctx, config);

});

At this point it sort of works, except I'm having weird behaviour where a line would connect the first point to all subsequent points:

Example GIF (GIF size was too large, it's about 40 seconds long)

It seems like the graph is creating a new line each time it fetches new data, instead of dumping the previous line? I'm not sure how it handles data internally.

At this point I'm not sure exactly what the problem might be. The chart sort-of works, as it does create a line that is accurate to the graph, but then it seems like it's joining the first point in the array together with the latest point in the array. You can see this behaviour in the GIF.


问:
squared boxes by height (not width) to create equal width (aspect ratio)
I know the squared solution with :before { padding-bottom }. This works only with a width value, because padding is always using a relation to the parents width. - But exactly this is my problem.

I ONLY have the value of the a fixed HEIGHT (by parent container) and I need squared boxes by that height value. I don't like to use JS. If there is a solution to REPLACE the STATIC WIDTH value with pure CSS, please tell me!

Here's a simple code sample:

div.wrapper {
  height: 70px;
  padding: 5px;
  background: black;
}

div.box {
  float: left;
  width: calc(70px - 10px); /* here is that static value for width, but better would be a relation to (parent) height */
  height: calc(100% - 10px);
  margin: 5px;
 }

div.box.b1 {
  background: orange;
}

div.box.b2 {
  background: red;
}

div.box.b3 {
  background: green;
}

div.box.b4 {
  background: dodgerblue;
}

div.box.b5 {
  float: right;
  background: grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="box b1">A</div>
  <div class="box b2">B</div>
  <div class="box b3">C</div>
  <div class="box b4">D</div>
  <div class="box b5">E</div>
</div></code>```

I also was looking for the "css-3 grid", but I didn't found a good solution. But if anyone know about thet problem, please tell me! :)

PS: Just for info... The width of the parent is always 100% (or vw). I want to create a navbar with a defined height, which may be changed via media queries. But only the height value, never the width value of the parent container.

PPS: I found some more question here about that problem, but nobody understood the enquirers. Because we are not looking for "var height = width", we're looking for "var width = height". ;)

答:
Okay, I found a way with grid and css-vars...

:root {
  --box-spacing: 10px;
  --box-length: 60px;
}

.grid {
  display: grid;
  grid-template-columns: repeat(4, var(--box-length)) auto var(--box-length);
  grid-auto-rows: var(--box-length);
  grid-template-areas:
    "a b c d . e";
  grid-gap: var(--box-spacing);
  padding: var(--box-spacing);
  background:black;
}

.grid > :nth-child(1) {
  grid-area: a;
  background:orange;
}

.grid > :nth-child(2) {
  grid-area: b;
  background:red;
}

.grid > :nth-child(3) {
  grid-area: c;
  background:green;
}

.grid > :nth-child(4) {
  grid-area: d;
  background:blue;
}

.grid > :nth-child(5) {
  grid-area: e;
  background:grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
</div></code>```

I simply use the same var() for width and width lengths. And grid-template-areas allows it to use . for an empty column at the fifth position. That column has an auto width.

It's not beauty, but it works... if you've a better solution, tell me! :)

Body:
I know the squared solution with :before { padding-bottom }. This works only with a width value, because padding is always using a relation to the parents width. - But exactly this is my problem.

I ONLY have the value of the a fixed HEIGHT (by parent container) and I need squared boxes by that height value. I don't like to use JS. If there is a solution to REPLACE the STATIC WIDTH value with pure CSS, please tell me!

Here's a simple code sample:

div.wrapper {
  height: 70px;
  padding: 5px;
  background: black;
}

div.box {
  float: left;
  width: calc(70px - 10px); /* here is that static value for width, but better would be a relation to (parent) height */
  height: calc(100% - 10px);
  margin: 5px;
 }

div.box.b1 {
  background: orange;
}

div.box.b2 {
  background: red;
}

div.box.b3 {
  background: green;
}

div.box.b4 {
  background: dodgerblue;
}

div.box.b5 {
  float: right;
  background: grey;
}

A

B

C

D

E

I also was looking for the "css-3 grid", but I didn't found a good solution. But if anyone know about thet problem, please tell me! :)

PS: Just for info... The width of the parent is always 100% (or vw). I want to create a navbar with a defined height, which may be changed via media queries. But only the height value, never the width value of the parent container.

PPS: I found some more question here about that problem, but nobody understood the enquirers. Because we are not looking for "var height = width", we're looking for "var width = height". ;)

Body:
Okay, I found a way with grid and css-vars...

:root {
  --box-spacing: 10px;
  --box-length: 60px;
}

.grid {
  display: grid;
  grid-template-columns: repeat(4, var(--box-length)) auto var(--box-length);
  grid-auto-rows: var(--box-length);
  grid-template-areas:
    "a b c d . e";
  grid-gap: var(--box-spacing);
  padding: var(--box-spacing);
  background:black;
}

.grid > :nth-child(1) {
  grid-area: a;
  background:orange;
}

.grid > :nth-child(2) {
  grid-area: b;
  background:red;
}

.grid > :nth-child(3) {
  grid-area: c;
  background:green;
}

.grid > :nth-child(4) {
  grid-area: d;
  background:blue;
}

.grid > :nth-child(5) {
  grid-area: e;
  background:grey;
}

<div class="grid">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
</div>

I simply use the same var() for width and width lengths. And grid-template-areas allows it to use . for an empty column at the fifth position. That column has an auto width.

It's not beauty, but it works... if you've a better solution, tell me! :)