text:
Q: Как запустить PostgreSQL MacOS? Пытаюсь поднять PostgreSQL так как по команде pg_ctl выдает это:
pg_ctl: no database directory specified and environment variable PGDATA unset Try "pg_ctl --help" for more information.
По инструкции так и должно было быть, но после того как я введу следующую команду, должно было все работать, результат ниже:
macbook@MacBook-Pro-macbook ~ % pg_ctl -D /opt/homebrew/opt/postgresql/bin/postgres -D /opt/homebrew/var/postgres start           pg_ctl: another server might be running; trying to start server anyway waiting for server to start....2022-08-07 10:29:23.448 EEST [58711] FATAL:  lock file "postmaster.pid" already exists 2022-08-07 10:29:23.448 EEST [58711] HINT:  Is another postmaster (PID 16484) running in data directory "/opt/homebrew/var/postgres"? stopped waiting pg_ctl: could not start server Examine the log output.


text:
Q: Workflow for modifying existing crud scaffolded model, views & controllers I am in the process of learning Yii framework. I have always previously built plugins in wordpress and I have never used a PHP MVC framework before.

*

*Assuming I have designed my database

*Used Yiic shell - console to model the db and create crud classes etc.

*Modified the controllers and views to my custom requirements.

Now the client requirements change and an extra field is required in the database.

*

*I modify the database to add for example "tel2" field to the customer table.

Do I need to update the model, view and controller manually to incorporate these changes or do I save customisations then get Yiic shell to re-scaffold the model, view & controller, then re-write the customisations manually?
I am sure that I can do either, but is there an easier way / is there a way in which you all work which makes your lives easier?

A: This was a question on my mind also when I began Yii.
The simple answer to it is you dont have to change everything. The Gii module is a really powerful feature of Yii and after making the CRUD and the model after a DB table, and if you have your own custom functions and methods and then you decide that you need to alter a table and add a new column to it, all you need to do remake the model in gii and it shall show the the modified code in a seperate link tagged as "diff".
Gii only generates the code, it does not overwrite it.
Now all you need to do is open up the "diff" make sure that you do not overwrite the code as there would be an overwrite button as well. After you check out the "diff" code, it shall show the new columns and the new properties highlighted, now all you need to do is copy the requisite changed code into your original code.
This way, you can do as many changes as you want with everything remaining intact.
There is also another method. You can use a base class and extend all your code into another file. This way, all you need to do is change the base model and everything still remains intact.

I think this should have answered your question.
Regards,

A: You should look at gii as a tool that gets you started quickly. But once you created your models and maybe CRUDs you can usually forget about it. Your project code evolves and - if it's not a very simply project - you will have a lot of manual changes to the auto generated code anyway.
So every time you touch your DB you will update the related files. Often this only involves to add a new attribute rule in rules() in your model, and adding another input field to the form view.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to host Web app on Azure's Windows Server 2012R2 VM (and resolve new site names)? Generally, having created Windows 2012R2 VM in Azure, the name of which is something.cloudapp.net, I have a default Web site hosted on IIS (it's in terns is reacheble from outside by something.cloudapp. net), but how to create another Web apps/ host them in IIS/selfhost (and absically, say self-host Nancy/Simple.web apps) on that VM? What whould be the domain name reacheble from outside? (how can I reach them from my PC browser), can I also set appache/nginx servers to the same VM and host webapps usig them and so on..

A: You can setup as many web servers as you like. You could expose them externally using different ports or different domain names.
To do this using different domain names you would need to setup the CNAME records with your DNS provider to point to something.cloudapp.net and setup IIS to bind to only the correct domain name. (http://www.domainmonster.com/glossary/dns/cname/)
To do this using ports you would need to run your sites on different ports and allow incoming traffic on these ports. (http://social.msdn.microsoft.com/Forums/windowsazure/en-US/28100eb3-6e9b-4012-a273-84062f4e293a/azure-firewall-how-to-allow-outbound-and-inbound-traffic-on-vm)
The best solution may be to run nginx/apache on port 80/443 and then use that as a reverse proxy to IIS.


text:
Q: Using GPU with Tensorflow and Keras I have python code that use Keras (with tensorflow backend)
I have trouble using my GPU to reduce processing time of my computations
I am using PyCharm to import my dependencies.
When I import tensorflow, my code run well but is very slow since it does not use GPU at all.
If I use tensorflow-gpu instead of basic tensorflow (I created a new Python env in which I have never imported the basic tensorflow), I get the following error :
Using TensorFlow backend.
Traceback (most recent call last):
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\UserName\AppData\Local\Programs\Python\Python36\lib\imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\UserName\AppData\Local\Programs\Python\Python36\lib\imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/UserName/PycharmProjects/MyProject/my-package/my_code.py", line 9, in <module>
    from pyimagesearch.smallvggnet import SmallVGGNet
  File "C:\Users\UserName\PycharmProjects\MyProject\my-package\pyimagesearch\smallvggnet.py", line 2, in <module>
    from keras.models import Sequential
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\keras\__init__.py", line 3, in <module>
    from . import utils
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\keras\utils\__init__.py", line 6, in <module>
    from . import conv_utils
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\keras\utils\conv_utils.py", line 9, in <module>
    from .. import backend as K
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\keras\backend\__init__.py", line 89, in <module>
    from .tensorflow_backend import *
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\keras\backend\tensorflow_backend.py", line 5, in <module>
    import tensorflow as tf
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\venv2\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\UserName\AppData\Local\Programs\Python\Python36\lib\imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\UserName\AppData\Local\Programs\Python\Python36\lib\imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

Notes :

*

*The error seems to appear when I have both keras and tensorflow-gpu imported

*Both tensorflow and tensorflow-gpu use version 1.12

*Keras use version 2.2.4 (Tried with 1.6.0 too)

*Python 3.6 (Tried with 3.7 too)

*CUDA 10.0 (Tried with 9.0 too) and the associated cuDNN version

*As proposed here, I added path to CUDA & cuDNN bin folders to PyCharm project Content Root.

*My computer have two GPU :

*

*Intel(R) UHD Graphics 630 (The basic one)

*NVIDIA Quadro P1000 (The one I want to use)

What can I do to make this work ?


text:
Q: if(usersData.getNumber().equals(number)){ NullPointerException Whenever I try to Login to start the HomeActivity, I get this error even though I double-checked the Getters and Setters in Users. I think this may have to something with this fragment of code mentioned below. It shows the the .getNumber may produce NullPointerException.
if(usersData.getNumber().equals(number)){

Here is a fragment of my LoginActivity
            if(dataSnapshot.child(parentDbName).child(number).exists())
            {
                Users usersData = dataSnapshot.child(parentDbName)
                        .child(number).getValue(Users.class);

                if(usersData.getNumber().equals(number))
                {
                        if(usersData.getPw().equals(pw))
                        {
                        Toast.makeText(Login.this, "Logged In Successfuly!", Toast.LENGTH_SHORT).show();
                        prog1.dismiss();

Every time I try to Login using the existing account stored in Firebase, it says
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference

This is what I've generated in Users.java
package com.robihidquicaygabinvalencia.ecommerce.shopmore.Model;

public class Users
{
    private String name, number, pw;

    public Users()
    {

    }

    public Users(String name, String number, String pw) {
        this.name = name;
        this.number = number;
        this.pw = pw;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getPw() {
        return pw;
    }

    public void setPw(String pw) {
        this.pw = pw;
    }
}

And here's what I've got in Logcat.
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
        at com.robihidquicaygabinvalencia.ecommerce.shopmore.Login$2.onDataChange(Login.java:83)
        at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@19.1.0:179)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.1.0:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.1.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.1.0:55)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

A: You are correct.  getNumber() is returning null.  This likely means there is no value in the database at the location that you're converting into a Users object, but since you haven't show the exact data at the location you're reading, it's not possible to say for sure.  In any event, you should check for that before calling toString() on the result.


text:
Q: jQuery .load() with data argument does not post In documentation it says, that when using load() with second (data) argument, the data will be post. But it does not work.
$('#open').load('ajax/open_map.php',$('.frm_open').serialize());

The request made is:
GET /ajax/open_map.php?filter_name=blahblah&filter_id=1 HTTP/1.1

How do I force it to POST and not GET?

A: $('#open').load('ajax/open_map.php',{data:$('.frm_open').serializeArray()});

You should post like object

A: jQuery load is simply equivalent to $.get so use $.post . http://api.jquery.com/load/
$.get(url, data, success)


text:
Q: Levensthein distance with different values for vowels I need this function to return the Levensthein distance of two strings. Normally, insertion , deletion, and substitution all have a cost of 1. But in this case I need the cost of insertion and deletion of a vowel to be not 1 but 0.5.
Here's my code so far:
def levenstheindist(word1, word2):

    if len(word1) > len(word2):
        word1, word2 = word2, word1

    distances = range(len(word1) + 1)
    for it2, char2 in enumerate(word2):
        if char2 in 'aeiuo':
            distances_ = [it2 + 0.5]
        if char2 not in 'aeiuo':
            distances_ = [it2 + 1]
        for it1, char1 in enumerate(word1):
            if char1 == char2:
                distances_.append(distances[it1])
            if char1 in 'aeiuo':
                distances_.append(distances[it1 + 0.5])
            if char1 not in 'aeiuo':
                distances_.append(1 + min((distances[it1], distances[it1 + 1], distances_[-1])))

        distances = distances_

    return distances[-1]

The output for the strings 'aaax' and 'x' should be 1.5, but as of now my function returns 2.5. What am I doing wrong?


text:
Q: Intellij and maven templating plugin: how to reference java-templates I want to use the Templating Maven Plugin in my project, but I don't understand where to put my sources. The plugin docs specify:
${basedir}/src/main/java-templates

but Intellij does not recognize this as a sources folder, and therefore won't allow me to create classes in it. If I make it a sources folder manually, then I run into the issue that I can't reference my classes from the src/main/java folder.
Where should I put the classes to be fitered, or how do I configure Intellij to work with the Templating Plugin?

A: CrazyCoder answered my question. This feature has just not been implemented yet in Intellij.


text:
Q: Вывод скопированного текста на место курсора по кнопке android У меня есть скопированный текст в буфере, мне нужно чтобы при нажатии на кнопку send_btn выводился текст в место где сейчас стоит курсор, по скольку это браузер я не могу задать определенное textview. Заранее спасибо за помощь

A: Для копирования текста в буффер используйте такой вариант:
ClipboardManager clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("your_text_to_be_copied");
clipboard.setPrimaryClip(clip);

Для получения текста используйте такой вариант:
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
String pasteData = "";

 // If it does contain data, decide if you can handle the data.
if (!(clipboard.hasPrimaryClip())) {

} else if (!(clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN))) {

    // since the clipboard has data but it is not plain text

} else {

    //since the clipboard contains plain text.
    ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);

    // Gets the clipboard as text.
    pasteData = item.getText().toString();
}

Первоисточник


text:
Q: Images being stretched in WPF RibbonRadioButton I've already posted a message about this, but I've lost it! And I can paste code now too...
I have a RibbonRadioButton whose image is being stretched, XAML below (I haven't changed the code-behind from its default). I have checked that the PNG is at 96dpi but the problem remains.
XAML:
<Window x:Class="DashboardTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ribbon:Ribbon x:Name="Ribbon">
            <ribbon:RibbonGroup x:Name="LiveStatusGroup"
                                    Header="RibbonGroup Header">
                <ribbon:RibbonRadioButton x:Name="Dashboard"
                                              LargeImageSource="images\LiveStatus_Dashboard.png"
                                              HorizontalContentAlignment="Center"
                                              HorizontalAlignment="Center"
                                              VerticalContentAlignment="Center"
                                              VerticalAlignment="Center"
                                              Label="RibbonRadioButton Label"
                                              ToolTip="RibbonRadioButton ToolTip"/>
            </ribbon:RibbonGroup>
        </ribbon:Ribbon>
    </Grid>
</Window>

Can anyone shed light on why this is happening? I am running Windows 7 with text size set to medium (125%).
J


text:
Q: Find the equilibrium point and its variance in stochastic data? I have some data of the form
I need to find the point where it starts reaching equilibrium (as I can see from the graph around 1000 iteration) and how much fluctuating the data points are. Is there a function to do that? I have been playing around with autocorrelation but nothing works.
Any guidance/readings suggestion is truly appreciated.
DISCLAIMER: I have zero to minimum background in statistics but I have been asked to present my data that way...


text:
Q: cannot open Singular on a running emacs I am a newbies in Singular. I just downloaded Singular4-0-2_64.dmg, mounted the image, right-ckick, show the package contents, then moved the contents folder to the Applications directory. double-clicking Contents/MacOS/Singular (or Esingular) I have Singular running in a terminal (or via emacs in a terminal). But when I try M-x singular in a running emacs, it says "cannot open load file : no such file or directory, singular".
Then I copied .emacs-general and .emacs-singular to the home directory. Adding the following lines to .emacs
(setq load-path (cons "" load-path))
(autoload 'singular "singular"
  "Start Singular using default values." t)
(autoload 'singular-other "singular"
  "Ask for arguments and start Singular." t)
changing singular-emacs-home-directory into /Applications/Singular.app/Contents/share/singular/emacs/ it still doesn't work.
Also when I replace .emacs with .emacs-singular, replacing the above directory, it gives the error:
Warning (initialization): An error occurred while loading `/Users/Me/.emacs':
Symbol's value as variable is void: /Applications/Singular.app/Contents/share/singular/emacs
Am I not finding the right singular-emacs-home-directroty or is there any other problem?
I appreciate your help.
Also I must mention that I am a user of emacs for Macaulay2. For that I have changed .emacs and .emacs-Macaulay2 in order to teach emacs where to look for M2. Is there anything similar to be done for Singular? Shall I have a file .emacs-singular somewhere?
Thanks for your help.

A: Here are some basic settings that assume the Singular.app has been installed to the /Applications folder.  I chose to set the absolute path to the executable, instead of setting the PATH in Emacs.  The PATH in Emacs on OSX is (by default) not the same as what one would generally except to see in let's say Terminal.app.  [But, setting the PATH is beyond the scope of this basic answer.]
My personal preference is to have all of the lisp and configuration files in a custom directory for purposes of editing and backup up.  This limited example just leaves everything where they are.
In the Emacs master branch (February 7, 2016), there is no built-in variable named current-menubar -- the configuration files are looking for the existence of that variable.  I did not spend the time to debug the built-in configuration files to find out what version of Emacs they were designed for, and I did not spend the time to make the Singular elisp libraries compatible with the latest Emacs master branch.
Add the following lines of code to the .emacs file in the home directory, save the file, and restart Emacs.  Then type M-x singular RET
(add-to-list 'load-path "/Applications/Singular.app/Contents/share/singular/emacs/")
(require 'singular)
(setq singular-emacs-home-directory "/Applications/Singular.app/Contents/share/singular/emacs/")
(defvar current-menubar nil)
(setq singular-executable-default "/Applications/Singular.app/Contents/MacOS/Singular")
(load-file "/Applications/Singular.app/Contents/share/singular/emacs/.emacs-general")
(load-file "/Applications/Singular.app/Contents/share/singular/emacs/.emacs-singular")


text:
Q: Redirect running process STDOUT/STDERR to SSH STDOUT using GDB I have a process running on an embedded system (linux).
its STDOUT/STDERR is the console which is on a serial port.
I would like to redirect its ouputs (standard and error) to that of an SSH session.
I have read you can do similar operations with GDB, but I don't know how you would redirect to the SSH session's STDOUT/STDERR instead of to a file.
I can't do it to a file because of low disk resources. Also I have seen some examples using a named pipe, but I don't have mkfifo command available. I do have GDB.
Also, assuming this is possible, would the process terminate when I close the SSH session? If so, could I redirect back before I do?
Thanks.

A: You can do it as long as you can call libc functions from gdb.
#ssh root@embedded

Query daemon output location:
# ls -l /proc/`pidof daemon`/fd/1
/proc/13202/fd/1 -> /dev/null

It can be not null, it can point to some other console or even some pipe or file, store this location somewhere. Query your ssh session output location:
# ls /proc/self/fd/1 -l
lrwx------ 1 root root 64 дек.  15 16:51 /proc/self/fd/1 -> /dev/pts/9

or simply call tty if you have it.
Now goes the work:
# gdb -p `pidof daemon`
..
81      ../sysdeps/unix/syscall-template.S: No such file or directory.
(gdb) call open("/dev/pts/9",2,0)
$1 = 0x3
(gdb) call dup2(3,2)
$2 = 0x2
(gdb) call dup2(3,1)
$3 = 0x1
(gdb) quit
Detaching from program: /root/daemon, process 13202
 daemon output/errorput

Repeat the same steps before exit from ssh session, just replace /dev/pts/9 with initial output location in the open syscall.


text:
Q: Strange issue with Django form and initial values I'm going crazy trying to understand why the default value that I defined using "initial" in my form are not printed in my template. The form is something like this:
class MyForm(forms.Form):
    # ...
    proximity = forms.IntegerField(required=False, initial=50)

in my template:
{{ myForm.proximity }}

prints:
<input id="id_proximity" name="proximity" type="number">

BUT, if I run the following in the shell:
print MyForm()

In the output I find:
<input id="id_proximity" name="proximity" type="number" value="50" />

that is what I was expecting in my template! Why in the shell it works and in the template it doesn't?
(I'm using Django 1.6)
SOLVED!
I was initializing the form in this way in my view:
MyForm(self.request.GET)

and since there is no data in GET the initial is replaced with None :P

A: you are right.. it take me 30 minutes to solve:)
we can read the django/forms/fields.py in  source code of django as follow:
# initial -- A value to use in this Field's initial display. This value
#            is *not* used as a fallback if data isn't given.

and the forms.Form._init_ first param is data, so it means that you set the data and the initial will be used as a fallback.:)


text:
Q: React.js setState of objects property from array Right now i need to increment/decrement a property value of state's array of  objects. I have tried throwing everything that came to my mind to setState. At times it didnt throw any errors, but wasn't updating the value either Right now i get error message:

this.state.products[key] is undefined

constructor(props) {

    super(props)

    var products = [
        { name: "Motorhead glasses", price: 300, amount: 1 },
        { name: "Judaspriest glasses", price: 499, amount: 1 }
    ]

    this.state = { products: products }
    this.handleMinus = this.handleMinus.bind(this)

}

handleMinus(key) {
    var stateCopy = Object.assign({}, this.state);
    stateCopy.products = stateCopy.products.slice();
    stateCopy.products[key] = Object.assign({}, stateCopy.products[key]);
    stateCopy.products[key].amount += 1;
    this.setState({ [this.state.products[key].amount]: stateCopy });
    console.log(this)
}

A: You you clone a state object, you can modify it directly and setback to state
handleMinus(key) {
    var stateCopy = [...this.state.products];   /Create a copy of products array using spread operator syntax.
    stateCopy[key].amount += 1;
    this.setState({products : stateCopy });

}

If you wanna know what [...this.state.products] mean check this answer: What is the meaning of this syntax "{...x}" in Reactjs

A: Use this (check the comments):
handleMinus(key) {
    var stateCopy = this.state.products.slice();        //create a copy of products array
    stateCopy[key] = Object.assign({}, stateCopy[key])  //create a copy of object at that key
    stateCopy[key].amount += 1;                         //modify the value
    this.setState({products : stateCopy });             //update the state variable
}

Your code will also work with a small change, change the way you are using setState to update the state value, use this:
handleMinus(key) {
    var stateCopy = Object.assign({}, this.state);
    stateCopy.products = stateCopy.products.slice();
    stateCopy.products[key] = Object.assign({}, stateCopy.products[key]);
    stateCopy.products[key].amount += 1;
    this.setState(stateCopy);   //use this
}

A: You're making unnecessary shallow copies of your state.
handleMinus(key) {
  const product = this.state.products[key];

  this.setState({
    products: [
      ...this.state.products,

      [key]: Object.assign({}, product, {
        amount: product.amount + 1
      })
    ]
  })
}


text:
Q: Peskin and Schroeder's QFT eq. (7.88) On Peskin and Schroeder's QFT book, page 251, the book discussed how things will be changed in $d$ dimensions. For example $g_{\mu \nu}g^{\mu \nu}=d$.
In eq. (7.88), the book gave how Dirac matrices can be manipulated as a set of $d$ matrices:
$$\{\gamma^{\mu} ,\gamma^{\nu}\}=2g^{\mu \nu}, \ \ \ \ \ tr[1]=4 \tag{7.88}$$
How to understand $tr[1]=4$? is this "$1$" identity matrix? why not $tr[1]=d$?

A: In $d=2N$, and in $d=2N+1$, dimensions the trace of the gamma-matrix space identity matrix is ${\rm tr}({\mathbb I}_{\rm spinors})$ is $2^N$.


text:
Q: Advanced forkbomb immune to kill signal In assignment given in one of my CS courses, we are tasked with creating a fork bomb that is very difficult to stop.
It needs to be immune control-c, control-z, and control-d closing the terminal. It also must be immune to sigkill and signal 9, we have gone over signal handling shortly with sigsegv but that was all. I read that sigaction cannot catch sigkill or sigstop signals.
I also read that daemonizing the process will allow it to run in the background so closing the terminal will not stop it.
How can i make the fork bomb process immune to a sigkill signal?
This is the fork bomb we made before.
#include<unistd.h>

int main(){

    while(1){
        fork();
    }
    return 0;
}

Also i am using a virtual box to safely test this.

A: Not possible to avoid/immune  sigkill signal. Read the man page of signal()
it says  The signals SIGKILL and SIGSTOP cannot be caught or ignored
and
while(1){
        fork();
    }

it's not a good idea because you can't create processes as much as you want,there is some limit, check ulimit. At once stage when there is no resource it fails(sh will display the error message).


text:
Q: Custom training in Keras I am using a custom function to define a deep neural network with Keras.
import tensorflow as tf
# Xavier initialization (a.k.a Glorot initialization)
Xavier = tf.keras.initializers.GlorotNormal()

def Dnn(num_uints_per_layer = 3*[16], act_hidden = 3*['tanh'], num_outputs = 1, act_output = None):
    model = tf.keras.models.Sequential()

    ## Input layer
    model.add(tf.keras.layers.Dense(num_uints_per_layer[0],
                                 activation = act_hidden[0],
                                 input_shape = (1,),
                                 kernel_initializer = Xavier,
                                 bias_initializer= Xavier))
    ## Hiden layers
    for layer in range(1, len(num_uints_per_layer)):
        model.add(tf.keras.layers.Dense(num_uints_per_layer[layer],
                               activation = act_hidden[layer],
                               kernel_initializer = Xavier,
                               bias_initializer= Xavier))
    ## Output layer
    if act_output:
        model.add(tf.keras.layers.Dense(num_outputs, activation = act_output,
                                kernel_initializer = Xavier,
                                bias_initializer= Xavier))
    else:
        model.add(tf.keras.layers.Dense(num_outputs,
                                kernel_initializer = Xavier,
                                bias_initializer= Xavier))
    return model

I define a simple training function and try training
import time

# tf.config.run_functions_eagerly(True)
@tf.function
def train(x, y, epochs=10000):
  for e in range(epochs):
    with tf.GradientTape() as tape:
      prediction = model(x)
      error = tf.square(y-prediction)
      mean_error = tf.reduce_mean(error)
    gradient = tape.gradient(mean_error, model.trainable_weights)
    optimizer.apply_gradients(zip(gradient, model.trainable_weights)) # Can add tol cond. to exit after certain accuracy level is reached

    if e % 500 == 0:
      print('Epoch {:5d}/{}, Mean squared error: {:.8f}'.format(e, epochs, mean_error))

x = tf.linspace(-2, 2, 201)
x = tf.cast(x, tf.float32)

def f(x):
  y = x**2 + 2*x - 5
  return y

y = f(x) #+ tf.random.normal(shape=x.shape[0]) # If we include noise we can illustrate overtraining

print('Using Keras')
## Define DNN model instance
model = Dnn()
optimizer = tf.optimizers.Adam(learning_rate=0.001)
model.compile() #(x)

untrained_model   = tf.keras.models.clone_model(model) # with Keras
# untrained_model = copy(model)

## Train model
start = time.time()
train(x, y, epochs = 2000)
end = time.time()
print('Finished training with Keras in {:.4f} seconds'.format(end-start))

However, no training takes place. But if I use an alternative custom class with the following skeleton code
class Model(tf.keras.Model):
  def __init__(self, units, activation = 'tanh'):
    super().__init__()
    self.dense1 = ...
    ...
    ...
    self.dense4 = tf.keras.layers.Dense(1)

  def call(self, x, training=True):
    ## Pass x through layers

    return tf.squeeze(x, axis=1)

everything works as expected. Can someone explain why when I instantiate with def Dnn(...) no training takes place?
Output from the two (normally more epochs are necessary but as is clear from the output training stalls when def Dnn(...) is used).
Using Keras
Epoch     0/2000, Mean squared error: 17.13852501
Epoch   500/2000, Mean squared error: 6.84089518
Epoch  1000/2000, Mean squared error: 6.83755589
Epoch  1500/2000, Mean squared error: 6.83745432
Finished training with Keras in 18.2301 seconds

Using custom dnn class
Epoch     0/2000, Mean squared error: 22.75801659
Epoch   500/2000, Mean squared error: 0.06296246
Epoch  1000/2000, Mean squared error: 0.04824752
Epoch  1500/2000, Mean squared error: 0.03582729
Finished training with custom class in 14.7489 seconds


text:
Q: Does a analytic joint distribution necessarily have continuous marginals? Although the question actually popped up in a course about evolution equations, it seemed most natural to ask this in the context of joint distributions. Namely:

Suppose $X$ and $Y$ are two variables with joint distribution $f_{X,Y}(x,y)$, which is jointly analytic in $x$ and $y$. Does this imply that the marginal distributions $f_X(x)$ and $f_Y(y)$ are continous?

I could create counterexamples if the statement is strengthened to imply differentiability (see below), or starting from smooth joint distributions, but the latter all had essential singularities (take for example this, as provided by hcl14 ).
However, the derivatives of $f$ in $x$ and $y$ would not necessarily be integrable, so an obvious expansion in power series would not work, unfortunately. For (a little convoluted) example:

Consider
  \begin{equation}
f_{X,Y}(x,y):=\frac{2 \sin (x y)e^{-y} }{x^2+1}, \qquad x\geq0, y\geq 0
\end{equation}
  Then $f$ is analytic in $x$ and $y$ (however it is not holomorphic, it has poles in $x=\pm i$), and a straightforward calculation verifies that it defines a joint distribution. However, its power series in $y$ around $0$ is not integrable in $x$:
  \begin{equation}
f_{X,Y}(x,y)=\frac{2 x y}{x^2+1}-\frac{2 x y^2}{x^2+1}+\mathcal{O}[y]^3
\end{equation}
  Finally, the marginal distribution $f_Y(y)$ (with a little help from Mathematica) seems not be differentiable in $0$.

Any insight is greatly appreciated!


text:
Q: System doesn't boot anymore. Error: file initrd.img-3.11.0-20-generic not found By mistake the file initrd.img-3.11.0-20-generic has been deleted in directory /boot.
Now the system doesn't boot anymore.
Is there a possibility to restore initrd.img-3.11.0-20-generic?
Output of blkid from live-cd:
ubuntu@ubuntu:~$ sudo blkid
/dev/loop0: TYPE="squashfs"
/dev/sda1: UUID="999feae4-d45b-4cbf-8015-ef5d62d952cd" TYPE="ext2"
/dev/sda5: UUID="9k5hUW-e2Hq-IfIN-08zV-jjDd-0mHm-CHySv4" TYPE="LVM2_member"
/dev/sr0: LABEL="Ubuntu 14.04 LTS amd64" TYPE="iso9660"
/dev/mapper/ubuntu--vg-root: UUID="8cf4d204-bbf8-44e2-a3e4-0f8c618e67ef" TYPE="ext4"
/dev/mapper/ubuntu--vg-swap_1: UUID="6a0999af-2cee-453f-9a01-7c878df6213e" TYPE="swap"

Update 29.05.2014:
Here's what I've entered (following the recommendations of mniess) with the system responses:
ubuntu@ubuntu:~$ sudo -i
root@ubuntu:~# mount /dev/mapper/ubuntu--vg-root /mnt
root@ubuntu:~# mount /dev/sda1 /mnt/boot
root@ubuntu:~# for i in dev dev/pts proc sys sys/firmware; do mount --bind /$i /mnt/$i; done
root@ubuntu:~# cp /etc/resolv.conf /mnt/etc/resolv.conf
root@ubuntu:~# chroot /mnt
root@ubuntu:/# apt-get update

System response after command apt-get update:
Ign http://extras.ubuntu.com trusty InRelease
Ign http://security.ubuntu.com trusty-security InRelease
Get:1 http://security.ubuntu.com trusty-security Release.gpg [933 B]
Get:2 http://extras.ubuntu.com trusty Release.gpg [72 B]
Ign http://de.archive.ubuntu.com trusty InRelease
Get:3 http://security.ubuntu.com trusty-security Release [58.5 kB]
Hit http://extras.ubuntu.com trusty Release
Ign http://de.archive.ubuntu.com trusty-updates InRelease
Ign http://de.archive.ubuntu.com trusty-backports InRelease
Ign http://de.archive.ubuntu.com trusty-proposed InRelease
Hit http://de.archive.ubuntu.com trusty Release.gpg
Hit http://extras.ubuntu.com trusty/main Sources
Get:4 http://security.ubuntu.com trusty-security/main Sources [16.0 kB]
Get:5 http://de.archive.ubuntu.com trusty-updates Release.gpg [933 B]
Hit http://extras.ubuntu.com trusty/main amd64 Packages
Hit http://extras.ubuntu.com trusty/main i386 Packages
Get:6 http://de.archive.ubuntu.com trusty-backports Release.gpg [933 B]
Get:7 http://security.ubuntu.com trusty-security/restricted Sources [14 B]
Get:8 http://security.ubuntu.com trusty-security/universe Sources [4,212 B]
Get:9 http://de.archive.ubuntu.com trusty-proposed Release.gpg [933 B]
Get:10 http://security.ubuntu.com trusty-security/multiverse Sources [687 B]
Hit http://de.archive.ubuntu.com trusty Release
Get:11 http://security.ubuntu.com trusty-security/main amd64 Packages [51.8 kB]
Get:12 http://de.archive.ubuntu.com trusty-updates Release [58.5 kB]
Get:13 http://security.ubuntu.com trusty-security/restricted amd64 Packages [14 B]
Get:14 http://security.ubuntu.com trusty-security/universe amd64 Packages [17.9 kB]
Get:15 http://security.ubuntu.com trusty-security/multiverse amd64 Packages [1,154 B]
Get:16 http://de.archive.ubuntu.com trusty-backports Release [58.6 kB]
Get:17 http://security.ubuntu.com trusty-security/main i386 Packages [49.4 kB]
Get:18 http://security.ubuntu.com trusty-security/restricted i386 Packages [14 B]
Get:19 http://de.archive.ubuntu.com trusty-proposed Release [58.5 kB]
Get:20 http://security.ubuntu.com trusty-security/universe i386 Packages [17.9 kB]
Get:21 http://security.ubuntu.com trusty-security/multiverse i386 Packages [1,404 B]
Hit http://de.archive.ubuntu.com trusty/main Sources
Ign http://extras.ubuntu.com trusty/main Translation-en_US
Hit http://de.archive.ubuntu.com trusty/restricted Sources
Hit http://de.archive.ubuntu.com trusty/universe Sources
Get:22 http://security.ubuntu.com trusty-security/main Translation-en [24.4 kB]
Hit http://de.archive.ubuntu.com trusty/multiverse Sources
Ign http://extras.ubuntu.com trusty/main Translation-en
Hit http://de.archive.ubuntu.com trusty/main amd64 Packages
Ign http://extras.ubuntu.com trusty/main Translation-de
Hit http://security.ubuntu.com trusty-security/multiverse Translation-en
Hit http://de.archive.ubuntu.com trusty/restricted amd64 Packages
Hit http://security.ubuntu.com trusty-security/restricted Translation-en
Hit http://de.archive.ubuntu.com trusty/universe amd64 Packages
Hit http://de.archive.ubuntu.com trusty/multiverse amd64 Packages
Get:23 http://security.ubuntu.com trusty-security/universe Translation-en [9,065 B]
Hit http://de.archive.ubuntu.com trusty/main i386 Packages
Hit http://de.archive.ubuntu.com trusty/restricted i386 Packages
Hit http://de.archive.ubuntu.com trusty/universe i386 Packages
Hit http://de.archive.ubuntu.com trusty/multiverse i386 Packages
Hit http://de.archive.ubuntu.com trusty/main Translation-en
Hit http://de.archive.ubuntu.com trusty/main Translation-de
Hit http://de.archive.ubuntu.com trusty/multiverse Translation-en
Hit http://de.archive.ubuntu.com trusty/multiverse Translation-de
Hit http://de.archive.ubuntu.com trusty/restricted Translation-en
Hit http://de.archive.ubuntu.com trusty/restricted Translation-de
Hit http://de.archive.ubuntu.com trusty/universe Translation-en
Hit http://de.archive.ubuntu.com trusty/universe Translation-de
Get:24 http://de.archive.ubuntu.com trusty-updates/main Sources [45.7 kB]
Get:25 http://de.archive.ubuntu.com trusty-updates/restricted Sources [14 B]
Get:26 http://de.archive.ubuntu.com trusty-updates/universe Sources [28.2 kB]
Ign http://security.ubuntu.com trusty-security/main Translation-en_US
Get:27 http://de.archive.ubuntu.com trusty-updates/multiverse Sources [2,234 B]
Ign http://security.ubuntu.com trusty-security/main Translation-de
Get:28 http://de.archive.ubuntu.com trusty-updates/main amd64 Packages [109 kB]
Ign http://security.ubuntu.com trusty-security/multiverse Translation-en_US
Ign http://security.ubuntu.com trusty-security/multiverse Translation-de
Get:29 http://de.archive.ubuntu.com trusty-updates/restricted amd64 Packages [14 B]
Ign http://security.ubuntu.com trusty-security/restricted Translation-en_US
Get:30 http://de.archive.ubuntu.com trusty-updates/universe amd64 Packages [74.9 kB]
Ign http://security.ubuntu.com trusty-security/restricted Translation-de
Ign http://security.ubuntu.com trusty-security/universe Translation-en_US
Get:31 http://de.archive.ubuntu.com trusty-updates/multiverse amd64 Packages [7,089 B]
Ign http://security.ubuntu.com trusty-security/universe Translation-de
Get:32 http://de.archive.ubuntu.com trusty-updates/main i386 Packages [107 kB]
Get:33 http://de.archive.ubuntu.com trusty-updates/restricted i386 Packages [14 B]
Get:34 http://de.archive.ubuntu.com trusty-updates/universe i386 Packages [75.3 kB]
Get:35 http://de.archive.ubuntu.com trusty-updates/multiverse i386 Packages [7,273 B]
Get:36 http://de.archive.ubuntu.com trusty-updates/main Translation-en [51.2 kB]
Hit http://de.archive.ubuntu.com trusty-updates/multiverse Translation-en
Hit http://de.archive.ubuntu.com trusty-updates/restricted Translation-en
Get:37 http://de.archive.ubuntu.com trusty-updates/universe Translation-en [33.8 kB]
Get:38 http://de.archive.ubuntu.com trusty-backports/main Sources [14 B]
Get:39 http://de.archive.ubuntu.com trusty-backports/restricted Sources [14 B]
Get:40 http://de.archive.ubuntu.com trusty-backports/universe Sources [4,123 B]
Get:41 http://de.archive.ubuntu.com trusty-backports/multiverse Sources [768 B]
Get:42 http://de.archive.ubuntu.com trusty-backports/main amd64 Packages [14 B]
Get:43 http://de.archive.ubuntu.com trusty-backports/restricted amd64 Packages [14 B]
Get:44 http://de.archive.ubuntu.com trusty-backports/universe amd64 Packages [4,099 B]
Get:45 http://de.archive.ubuntu.com trusty-backports/multiverse amd64 Packages [619 B]
Get:46 http://de.archive.ubuntu.com trusty-backports/main i386 Packages [14 B]
Get:47 http://de.archive.ubuntu.com trusty-backports/restricted i386 Packages [14 B]
Get:48 http://de.archive.ubuntu.com trusty-backports/universe i386 Packages [4,114 B]
Get:49 http://de.archive.ubuntu.com trusty-backports/multiverse i386 Packages [619 B]
Hit http://de.archive.ubuntu.com trusty-backports/main Translation-en
Get:50 http://de.archive.ubuntu.com trusty-backports/multiverse Translation-en [307 B]
Hit http://de.archive.ubuntu.com trusty-backports/restricted Translation-en
Get:51 http://de.archive.ubuntu.com trusty-backports/universe Translation-en [2,506 B]
Get:52 http://de.archive.ubuntu.com trusty-proposed/main amd64 Packages [88.4 kB]
Get:53 http://de.archive.ubuntu.com trusty-proposed/restricted amd64 Packages [14 B]
Get:54 http://de.archive.ubuntu.com trusty-proposed/multiverse amd64 Packages [14 B]
Get:55 http://de.archive.ubuntu.com trusty-proposed/universe amd64 Packages [16.6 kB]
Get:56 http://de.archive.ubuntu.com trusty-proposed/main i386 Packages [85.5 kB]
Get:57 http://de.archive.ubuntu.com trusty-proposed/restricted i386 Packages [14 B]
Get:58 http://de.archive.ubuntu.com trusty-proposed/multiverse i386 Packages [14 B]
Get:59 http://de.archive.ubuntu.com trusty-proposed/universe i386 Packages [16.7 kB]
Get:60 http://de.archive.ubuntu.com trusty-proposed/main Translation-en [40.7 kB]
Hit http://de.archive.ubuntu.com trusty-proposed/main Translation-de
Hit http://de.archive.ubuntu.com trusty-proposed/multiverse Translation-en
Hit http://de.archive.ubuntu.com trusty-proposed/multiverse Translation-de
Hit http://de.archive.ubuntu.com trusty-proposed/restricted Translation-en
Hit http://de.archive.ubuntu.com trusty-proposed/restricted Translation-de
Get:61 http://de.archive.ubuntu.com trusty-proposed/universe Translation-en [10.4 kB]
Hit http://de.archive.ubuntu.com trusty-proposed/universe Translation-de
Ign http://de.archive.ubuntu.com trusty/main Translation-en_US
Ign http://de.archive.ubuntu.com trusty/multiverse Translation-en_US
Ign http://de.archive.ubuntu.com trusty/restricted Translation-en_US
Ign http://de.archive.ubuntu.com trusty/universe Translation-en_US
Ign http://de.archive.ubuntu.com trusty-updates/main Translation-en_US
Ign http://de.archive.ubuntu.com trusty-updates/main Translation-de
Ign http://de.archive.ubuntu.com trusty-updates/multiverse Translation-en_US
Ign http://de.archive.ubuntu.com trusty-updates/multiverse Translation-de
Ign http://de.archive.ubuntu.com trusty-updates/restricted Translation-en_US
Ign http://de.archive.ubuntu.com trusty-updates/restricted Translation-de
Ign http://de.archive.ubuntu.com trusty-updates/universe Translation-en_US
Ign http://de.archive.ubuntu.com trusty-updates/universe Translation-de
Ign http://de.archive.ubuntu.com trusty-backports/main Translation-en_US
Ign http://de.archive.ubuntu.com trusty-backports/main Translation-de
Ign http://de.archive.ubuntu.com trusty-backports/multiverse Translation-en_US
Ign http://de.archive.ubuntu.com trusty-backports/multiverse Translation-de
Ign http://de.archive.ubuntu.com trusty-backports/restricted Translation-en_US
Ign http://de.archive.ubuntu.com trusty-backports/restricted Translation-de
Ign http://de.archive.ubuntu.com trusty-backports/universe Translation-en_US
Ign http://de.archive.ubuntu.com trusty-backports/universe Translation-de
Ign http://de.archive.ubuntu.com trusty-proposed/main Translation-en_US
Ign http://de.archive.ubuntu.com trusty-proposed/multiverse Translation-en_US
Ign http://de.archive.ubuntu.com trusty-proposed/restricted Translation-en_US
Ign http://de.archive.ubuntu.com trusty-proposed/universe Translation-en_US
Fetched 1,250 kB in 8s (145 kB/s)
Reading package lists... Done
root@ubuntu:/#

Then I've entered:
   root@ubuntu:/# apt-get --reinstall install linux-image-3.11.0-20-generic

...and got the following reply:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reinstallation of linux-image-3.11.0-20-generic is not possible, it cannot be downloaded.
The following package was automatically installed and is no longer required:
  linux-image-generic
Use 'apt-get autoremove' to remove it.
0 upgraded, 0 newly installed, 0 to remove and 1674 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue [Y/n]? Y
Setting up icaclient (12.1.0) ...
/var/lib/dpkg/info/icaclient.postinst: 696: /var/lib/dpkg/info/icaclient.postinst: nspluginwrapper: not found
dpkg: error processing icaclient (--configure):
 subprocess installed post-installation script returned error exit status 2
Errors were encountered while processing:
 icaclient
E: Sub-process /usr/bin/dpkg returned an error code (1)

Next I've entered:
root@ubuntu:/# update-grub

System replied:
Generating grub.cfg ...
Found linux image: /boot/vmlinuz-3.11.0-20-generic
Found linux image: /boot/vmlinuz-3.11.0-19-generic
Found linux image: /boot/vmlinuz-3.11.0-18-generic
Found linux image: /boot/vmlinuz-3.11.0-17-generic
Found linux image: /boot/vmlinuz-3.11.0-15-generic
Found linux image: /boot/vmlinuz-3.11.0-12-generic
Found memtest86+ image: /memtest86+.bin
done

Then I've entered:
root@ubuntu:/# grub-install

And got this:
Install device isn't specified.
Usage: grub-install [OPTION] [INSTALL_DEVICE]
Install GRUB on your drive.

  -h, --help              print this message and exit
  -v, --version           print the version information and exit
  --modules=MODULES       pre-load specified modules MODULES
  --boot-directory=DIR    install GRUB images under the directory DIR/grub
                          instead of the /boot/grub directory
  --target=TARGET         install GRUB for TARGET platform
                          [default=current]
  --directory=DIR         use GRUB images from DIR. Takes precedence
                          over target
  --grub-setup=FILE       use FILE as grub-setup
  --grub-mkimage=FILE     use FILE as grub-mkimage
  --grub-mkrelpath=FILE   use FILE as grub-mkrelpath
  --grub-probe=FILE       use FILE as grub-probe
  --allow-floppy          make the drive also bootable as floppy (default
                          for fdX devices). May break on some BIOSes.
  --recheck               delete device map if it already exists
  --force                 install even if problems are detected
  --force-file-id         use identifier file even if UUID is available
  --disk-module=MODULE    disk module to use (biosdisk or native). This
                          option is only available on BIOS target.
  --no-nvram              don't update the `boot-device' NVRAM
                          variable. This option is only available on
                          IEEE1275 targets.
  --removable             the installation device is removable. This option
                          is only available on EFI.
  --bootloader-id=ID      the ID of bootloader. This option is only
                      available on EFI.
  --efi-directory=DIR     use DIR as the EFI System Partition root.
  --uefi-secure-boot      install an image usable with UEFI Secure
                          Boot. This option is only available on EFI and if
                          the grub-efi-amd64-signed package is installed.
  --no-uefi-secure-boot   do not install an image usable with UEFI Secure
                          Boot, even if the system was currently started
                          using it. This option is only available on EFI.

INSTALL_DEVICE must be system device filename.

grub-install copies GRUB images into /boot/grub, and uses grub-setup
to install grub into the boot sector.

Report bugs to <bug-grub@gnu.org>.

As you can see above the procedure has shown some errors. The result is that the system still doesn't boot. Does someone have an idea about how to resolve the errors?

A: First of all, especially as a beginner, you should never edit files outside your user home directory. Don't manually mess with your system. Let Ubuntu take care of what files it needs when and where.
That said: It is a bit more involved but you can repair Ubuntu using a live-dvd or USB stick (USB is faster). I'll guide your through it:
Boot live-system and gather information
It is the same you did when installing Ubuntu. Just make sure to chose "Try Ubuntu". When you see the desktop, open a terminal (CTRL+ALT+T) and run the following:
sudo blkid

which will give you a result like this
/dev/sda1: LABEL="EFI" UUID="70D6-1701" TYPE="vfat"
/dev/sda2: UUID="68ca53b3" LABEL="OSX" TYPE="hfsplus"
/dev/sda3: UUID="49526001" LABEL="Recovery HD" TYPE="hfsplus"
/dev/sda4: LABEL="BOOTCAMP" UUID="FCF67D7DF67D394A" TYPE="ntfs"
/dev/sda6: UUID="c1c76922" TYPE="ext4"
/dev/sda7: UUID="3b171268" TYPE="ext4"
/dev/sda8: UUID="bf3dd1b7" TYPE="swap"

Please post the result of this command back here, so that we can help you further. I will continue with the above example.
Chroot into the installed system
With chroot you can use a live linux and switch to the Linux installed on your harddrive to repair it. It is important whether your system uses EFI or BIOS. If you have/had Windows 8 on the machine, it is a good indicator for EFI. In the example above there is a small vfat partition that is even called EFI so the above system uses EFI to boot. The two ext4 partitions are Linux partitions. You can just open them from the launcher to see which one contains to root filesystem (contains folders like etc, usr, var, ...). In the above case /dev/sda6 is the root partition and /dev/sda1 is the EFI partition.
In a terminal run the following commands to prepare and open the chroot.
sudo -i
mount /dev/sda6 /mnt
mount /dev/sda1 /mnt/boot/efi
for i in dev dev/pts proc sys sys/firmware; do mount --bind /$i /mnt/$i; done
chroot /mnt

The EFI partition only needs to be mounted if EFI is actually used, otherwise you can omit that line.
The list of partitions you posted indicates you use LVM, so we need to account for that. Replace the two mount commands above with these:
mount /dev/mapper/ubuntu--vg-root /mnt
mount /dev/sda1 /mnt/boot

Repair
To repair your system continue to run the following commands.
apt-get update
apt-get --reinstall install linux-image-3.11.0-20-generic
update-grub
grub-install
exit

Now reboot the machine and you should be all set.

A: *

*Open "Advanced options for Ubuntu" from GRUB (if it's only OS, use Shift after BIOS screen).

*Boot older kernel.

*Use
sudo update-grub

(I think it works in newer Ubuntu's)

*Reboot.

A: The files in this directory are vital to your installation so you should be very careful with them as you just found out :-)
But not everything is lost, I think. You should be able to reinstall the file. In order to do so you will probably have to use a Ubuntu live CD/USB stick to boot the machine. The steps would be

*

*Mount the local partitions of your machine in your live environment and chroot into the mounted root directory.

*Re-install the linux-image-3.11.0-20-generic which, IIRC, should generate the file for you.

I will not be able to further detail these two steps here. Googling for them should turn up some guides that will help you along the way.
Edit: See emniess' great post who was faster than me and nicely guides you through the process.

A: Sorry to bring up such an old post. I had something similar to this happen and ran into a few roadblocks along the way, here they, and their solutions, are:
I had a bunch of issues getting apt-get running in chroot. You have to install/run resolvconf from another console:
sudo dpkg-reconfigure resolvconf

You also have to copy the file over:
mv mnt/etc/resolv.conf{,.bak}
cp /etc/resolv.conf mnt/etc/resolv.conf

apt-get got stuck a few times and gave all sorts of errors you have to purge it and some other commands I forget.
You can verify it worked by looking in /mnt/boot and looking for the boot files.
When you reboot you have to delete /etc/resolv.conf and run reconfigure resolvconf again to get DNS back up.
To get grub going again, I had just used
Boot-Repair previously, but didn't need it again.
Thanks ** mniess**


text:
Q: How to activate Einstein bots in a new sfdx scratch org? I tried a lot of combinations, but not matter what I do, the "Einstein bots" menu of my generated scratch orgs only targets to "Contact support to activate Einstein Bots"
According to the trailhead, we need Service Cloud, Live Agent, Knownledge .
I also saw the value Chatbot in the (not very documented) Features page
All of them are activated in my my project-scratch-def.json file , but as result I continue to be unable to use Einstein Bots in my scratch org.
{
    "orgName": "DNV_NicoV_Home112_Bot3",
    "edition": "Developer",
    "country": "FR",
    "language": "en_US",
    "username": "nvuillamy@dnv_xxxxxx-scratch.com",
    "adminEmail": "nvuillam@xxx.com",
    "features": [
        "AddCustomApps:10",
        "AddCustomTabs:30",
        "API",
        "AuthorApex",
        "Chatbot",
        "Communities",
        "ContactsToMultipleAccounts",
        "DebugApex",
        "EinsteinAssistant",
        "Knowledge",
        "LightningServiceConsole",
        "LiveAgent",
        "LiveMessage",
        "MultiCurrency",
        "ServiceCloud",
        "SiteDotCom",
        "Sites",
        "StateAndCountryPicklist"
    ],
    "settings": {
        "orgPreferenceSettings": {
            "chatterEnabled": true,
            "networksEnabled": true,
            "s1DesktopEnabled": true,
            "s1EncryptedStoragePref2": false,
            "translation": true
        },
        "liveAgentSettings": {
            "enableLiveAgent": true
        },
        "securitySettings": {
            "sessionSettings": {
                "enableSMSIdentity": false,
                "identityConfirmationOnTwoFactorRegistrationEnabled": false
            }
        }
    }
}

A: * UPDATE *
It now appears to be possible to create scratch orgs with Einstein Bots enabled. For ease, this is the project-scratch-def file I used:
{
    "edition": "Enterprise",
    "features": ["ServiceCloud","Chatbot","CPQ","Communities","Knowledge","LiveAgent","LightningServiceConsole","LiveMessage"],
    "settings": {
        "lightningExperienceSettings": {
            "enableS1DesktopEnabled": true
        },
        "mobileSettings": {
            "enableS1EncryptedStoragePref2": false
        },
        "communitiesSettings": {
            "enableNetworksEnabled": true
        },
        "omniChannelSettings": {
            "enableOmniChannel": true
        },
        "liveAgentSettings": {
          "enableLiveAgent": true
        }
    }
  }

A: I think at the current release there is no possibility to automatically turn on Einstein bots on scratch orgs.
Instead, as suggested in this knowledge article, you will have to download a form

Download a copy of the Order Form Supplement for Einstein features
  found here:
  https://www.salesforce.com/content/dam/web/en_us/www/documents/legal/misc/order-form-supplement-for-einstein-features.pdf

Then have it signed

Have the form signed by an authorized representative of your company.
  Please be sure to include Account number(s) or orgID(s) for all orgs
  that you want to have access to Einstein features. Org IDs can be
  found by following these instructions:
  https://help.salesforce.com/articleView?id=000006019&type=1. Account
  numbers appear on Salesforce invoices.

And file a Salesforce Support Case

Log a Case with Support Go to Salesforce Help & Training and login
  with your Salesforce credentials Click on the Feature Activation topic
  and then on Einstein Bots category Scroll down and click Log a New
  Case Enter "Enable Einstein" in the Subject line of the Case Enter a
  Description, ensure the orgID is accurate and click the Submit button

The last step you might have to repeat for each and every scratch org which may be nasty.
However, you can change default duration of scratch org to maximum value of 30 days to ensure that the scratch org is still alive when Support would turn on Einstein bot feature for you on it.

A: It's not possible to create scratch org with enabled Einstein Bots feature now. And you can't enable it manually.
You need to create regular developer edition org or Trailhead Playground to have the possibility to enable it.


text:
Q: VSCode extension: How to render colored output in output channel? I have custom output from API and I want to format it to string with some colored values.

A: The output channel can be colorized with a TmLanguage grammar. The Output Colorizer extension extension does exactly that:

You can do this by targeting the text/x-code-output mimetype:
"contributes": {
    "languages": [{
        "id": "code-output",
        "mimetypes": [
            "text/x-code-output"
        ]
    }],
    "grammars": [{
        "language": "code-output",
        "scopeName": "code.output",
        "path": "./syntaxes/code-output.tmLanguage"
    }]
}

However, since this colorization is mimetype-based, you can't apply the highlighting to a specific output channel only. This means that two extensions providing output channel colorization will conflict.

A: In v1.65 Proposed Extension API is the ability to "create an output channel with custom language id" so as to avoid conflicts with other extensions that may be syntax coloring the output.

Output Channel with Custom Language Id
There are extensions which are able to define token or syntax coloring
and code-lens features to their output channels given that they are
text documents (read-only) by themselves. Since all output channels
share the same lanugage id, these customizations can be wrongly
applied to other output channels. Hence there has been an ask to
create an output channel with custom language id so that extension
authors can define customizations by language. Hence in this
milestone, we have introduced the
proposal
to create an output channel with a custom language id. Please try it
out and give us feedback.

*

*from v1.65 Release Notes


text:
Q: How to call a name from a dictionary in Python 3? Say that I have the following dictionary:
mydict = {"3322": 4 , "3323": 3 , "3324": 5}

Now say that I want to print "3323" once the the user inputs 3.
What I've got so far:
printer = input("please enter a number: ")

Now i'm not sure how to use "printer" to print 3323 once the user inputs 3.

A: Since you are looking for keys (which must be unique) by their corresponding values (that can be repeated more than once in a dictionary,) it is possible for there to be more than one resulting key that maps to a given value.
Fortunately, we can find all of the keys using a list comprehension:
results = [k for k,v in mydict.items() if v == int(printer)]

And of course you can print them all out like so:
print('\n'.join(results))

This way, all of the keys found will be printed (separated by newlines,) and nothing will be printed if nothing is found.

A: First your dictionary is "backwards", ie what you want to use a key is actually stored a value, flip it around with a dictionary comprehension:
mydict = {v:k for (k,v) in mydict.iteritems()}

Then it is best to capture user input in a while loop:
while 1:
    key = input("please enter a number: ")
    try:
        if int(key) in mydict:
            print mydict[int(key)]
            break
        else:
            print "{n} not present!".format(n = key)
    except ValueError:
        print "please enter a number!"

This way if the user messes up they can try again..


text:
Q: Sendgrid not sending email? I am trying to implement sendgrid into my backend api rails system so that when a user signs up I can send them a welcome email. After making a post request and handling user creation, I get this verification:
UserMailer#send_sign_up_email: processed outbound mail in 43.5ms
Sent mail to *******@gmail.com (185.8ms)
Date: Wed, 28 Feb 2018 16:54:05 -0800
From: *******@gmail.com
To: *******@gmail.com
Message-ID: <5a974f2d39c92_c5b2abcd76769fc423e0@albert-VirtualBox.mail>
Subject: Welcome to BottlesTonight albert jin!
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: quoted-printable

My code looks exactly like in this link https://sendgrid.com/docs/Integrate/Frameworks/rubyonrails.html.
This looks all fine and well, but the email is just not sending (I put stars here for the email but I actually put in my email, and I used another one of emails as the default for sending). There is no email in my outbox or inbox.
However, now that I think about it, I never "logged in" with my email or entered the password, so the application shouldn't have access to send emails with my email. I also never did anything with the api key that I made on my sendgrid account. Furthermore, for the environment.rb file, I wasn't sure what to put in domain, so I put gmail.com. These all seem kinda sketchy to me, I think the tutorial doesn't contain everything. Does anyone know how to configure this? I've been stuck on it for a while.
Edit:
I tried doing it on production and it is not working. Here is more info:
My production.rb looks like this:
config.action_mailer.raise_delivery_errors = true
  config.action_mailer.delivery_method = :smtp

  config.action_mailer.default_url_options = { :host => ENV['DEFAULT_HOST'] }

  ActionMailer::Base.smtp_settings = {
    :address        => 'smtp.sendgrid.net',
    :port           => '587',
    :authentication => :plain,
    :user_name      => ENV['SENDGRID_USERNAME'],
    :password       => ENV['SENDGRID_PASSWORD'],
    :domain         => 'heroku.com',
    :enable_starttls_auto => true
  }

I have a heroku sendgrid add on. I have set the heroku config vars. In my registrations controller I merely added the line:
UserMailer.send_sign_up_email(@current_user).deliver

My mailer class looks like:
def send_sign_up_email(user)
   @user = user
   mail(to: @user.email, subject: "Welcome! #{@user.first_name}")
   end

However, when I sign up on my website, the user gets added to the database but the email is not sending. Does anyone know why, or how I can debug?

A: I would suggest to remove all config for ActionMailer from your environment files (i.e. files under /config/environments), except following ones
  # Don't care if the mailer can't send.
  config.action_mailer.perform_caching = false

  # Reference: http://stackoverflow.com/a/20770131/936494
  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true

Then create an initializer /config/initializers/mail_config.rb and add following code to it:
TEST_ENVS = %w(test)
FILESYSTEM_ENVS = TEST_ENVS + %w(development)

# ===========  DELIVERY METHOD SETTING
delivery_method = case Rails.env.to_sym
                    when :production, :staging, :experimental
                     :sendmail
                    when :test
                     :test
                    else
                     :smtp
                  end

ActionMailer::Base.delivery_method = delivery_method

# ===========  SMTP SETTINGS
ENVS_TO_USE_GMAIL_CONFIG = %w(development test)

gmail_config = {
  address:              'smtp.gmail.com',
  port:                 587,
  domain:               'gmail.com',
  user_name:            ENV['MAIL_USER_NAME'],
  password:             ENV['MAIL_PASSWORD'],
  authentication:       :plain,
  enable_starttls_auto: true
}

if :smtp == delivery_method
  use_gmail_config = ENVS_TO_USE_GMAIL_CONFIG.include?(Rails.env)

  smtp_settings = ( use_gmail_config ? gmail_config : {} )
  ActionMailer::Base.smtp_settings = smtp_settings
end

# =========== DEFAULT URL OPTIONS

default_url_options_settings = Settings.default_url_options
host = default_url_options_settings.host
port = default_url_options_settings.port
protocol = default_url_options_settings.protocol

default_url_options = {}
default_url_options[:host] = host if host.present?
default_url_options[:port] = port if port.present?
default_url_options[:protocol] = protocol if protocol.present?

ActionMailer::Base.default_url_options = default_url_options

The Settings object is available as part of using config gem. If you do not want to use that gem for configuring env-specific values then you can just hard-code them in the initializer and try it.
My /config/settings.yml looks like
default_url_options:
  host: ''
  port: ''
  protocol: ''

and my /config/settings/development.yml looks like
default_url_options:
  host: 'localhost'
  port: '3000'

Having a centralized mailer config helps in diagnosing mailer settings related issues in quick manner.
First try it for Gmail account and if it works you can be sure that sending email works. Just make sure in your Gmail account Less Secure Apps setting is enabled.


text:
Q: Node.js custom Module When I run app.js, I get this error:
MBPdiDaniele3:Desktop danielemartini$ node app.js
events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: connect ECONNREFUSED 127.0.0.1:8080
    at Object.exports._errnoException (util.js:870:11)
    at exports._exceptionWithHostPort (util.js:893:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)
MBPdiDaniele3:Desktop danielemartini$

Here's the code for make_request.js:
var http = require('http');

var makeRequest = function(message) {

    var options = {
        host: 'localhost', port: 8080, path:'/', method: 'POST'
    }

    var request = http.request(options, function(response) {
        response.on('data', function(data) {
            console.log(data);
        });
    });
    request.write(message);
    request.end();
};
module.exports = makeRequest;

Here's the code for app.js:
var makeRequest = require('./make_request');

makeRequest("Here's looking at you, kid");
makeRequest("Hello, this is dog");

A: There are several possible causes :

*

*No service is running on localhost:8080

*A service runs on 8080 which refuses connections actively.

To check what is running, use one of those 2 commands (Unix) :

*

*lsof -i :8080 -S

*netstat -a | grep 8080
3 - Your running service isn't bound to your internal IP.
I've encountered the issue a few times on Cloud servers, where localhost/127.0.0.1 are not recognized. Try using the external IP of your machine (and make sure the firewall lets you make requests), or force your service to bind to all interfaces.
Hope it helps.


text:
Q: Downloading file in php has the path of the file also which I dont want I am trying to download files using the following code which is in "download.php":
<?php
$file = $_GET['file'];
header ("Content-type: octet/stream");
header('Content-Disposition: attachment; filename="'.$file.'"');
//header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>

I am calling this download.php from a link. eg.,

download.php?file=user_songs/57/mp3/Satru_Munbu.mp3

But the donloaded file name is changed. It appears like "user_songs-57-mp3-Satru_Munbu.mp3"
It seems like the full path that I am passing gets appended. Can anyone help me how can I remove it?

A: "/" is a reserved character so you need to URL encode your path:
download.php?file=user_songs%2F57%2Fmp3%2FSatru_Munbu.mp3

By the way, be careful because anyone can access any file in your system with your code (as long as the Apache process can access it). For example, download.php?file=%2Fetc%2Fpasswd would download your /etc/passwd file.

A: $file contains the full contents of the file= URL parameter, which is the full pathname. You can use basename() to extract just the filename part.
header('Content-Disposition: attachment; filename="'.basename($file).'"');


text:
Q: Rails application behind proxy, with SSL, renders paths as "http://" To start with, this sounds more like a bug then anything else.
My rails application is served by Unicorn. Then, using Nginx as a reverse proxy, I serve the application to the outside world using SSL.
So far so good, no problem. I'm using relative paths (Restful path helpers), so there should be no problem to produce this (for https://www.example.com):
new_entry_path => https://www.example.com/entries/new

This works fine in most cases.
The problem however appears when in a controller I try to redirect to a "show" action (using resources), let's say after a successful update (suppose Entry with id 100):
redirect_to @entry, flash: {success: "Entry has been updated"}

or
redirect_to entry_path(@entry), flash: {success: "Entry has been updated"}

they both produce a redirect to:
http://www.example.com/entries/100 # missing 's' in https...

instead of
/entries/100 # implying https://www.example.com/entries/100

As far as I've noticed, this only happens with show action and only in controller redirects.
I'm bypassing this by doing something horrible and disgusting:
redirect_to entry_url(@entry).sub(/^http\:/,"https:"), flash: {success: "Entry has been updated"}

Has anyone ever confronted something similar? Any ideas will be gratefully accepted...

A: I had a similar problem. By default Rails will use the current protocol for the *_url helpers.
We use nginx as web server and unicorn as application server. Nginx takes the request, unwrapps the SSL part and then passes it on to unicorn. Hence, unicorn always receives a http request. If we now want Rails to know about the original protocol, we can need to add the X-Forwarded-Proto header.
Example config:
upstream app {
    server unix:/var/run/myserver/unicorn.sock fail_timeout=0;
}
server {
    listen       443 ssl;
    server_name  myserver;

    ssl_certificate "/etc/pki/nginx/myserver.crt";
    ssl_certificate_key "/etc/pki/nginx/private/myserver.key";

    root /myserver/public;

    try_files $uri/index.html $uri @app;
    sendfile on;

    location @app {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https; # <--- will be used
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app;
   }
}

A: So far, I've managed to get a workaround by adding a rewrite rule to Nginx, under plain http:
rewrite ^/(.*)$  https://www.example.com/$1? permanent;

Which redirects all plain http requests to the https server.
Update:
Apparently, as I want the app not to care about how the front web server is serving it, it's up to the same web server to "clean the mess" of redirections the app by itself cannot handle unless it's been specifically configured (not desired). So, I will stick to this answer (workaround rather...)
UPDATE
Following papirtiger's answer, I saw that I ended up missing the flashes, which should be added to the overriding redirect_to as a parameter.
But I've found a way to do my life a lot easier, simply by overriding a different function, that is called from within redirect_to.
def _compute_redirect_to_location(options) #:nodoc:
    case options
    # The scheme name consist of a letter followed by any combination of
    # letters, digits, and the plus ("+"), period ("."), or hyphen ("-")
    # characters; and is terminated by a colon (":").
    # See http://tools.ietf.org/html/rfc3986#section-3.1
    # The protocol relative scheme starts with a double slash "//".
    when /\A([a-z][a-z\d\-+\.]*:|\/\/).*/i
        options
    ## WHEN STRING: THIS IS REMOVED TO AVOID ADDING PROTOCOL AND HOST ##
    # when String
    #   request.protocol + request.host_with_port + options
    when :back
        request.headers["Referer"] or raise RedirectBackError
    when Proc
        _compute_redirect_to_location options.call
    else
        url_for(options)
    end.delete("\0\r\n")
end

Thus, without having to change anything else in my code, I have a working relative redirect.

A: I think force_ssl is what you are looking for.
class AccountsController < ApplicationController
  force_ssl if: :ssl_configured?

  def ssl_configured?
    !Rails.env.development?
  end
end

Edit, if you really want to do redirects to relative paths you could always create your own helper:
module ActionController
  module RelativeRedirectingHelper
    extend ActiveSupport::Concern

    include AbstractController::Logger
    include ActionController::RackDelegation
    include ActionController::UrlFor

    def redirect_to_relative(path, response_status = 302) #:doc:
      raise ActionControllerError.new("Cannot redirect to nil!") unless options
      raise ActionControllerError.new("Cannot redirect to a parameter hash!") if options.is_a?(ActionController::Parameters)
      raise AbstractController::DoubleRenderError if response_body

      self.status        = response_status
      self.location      = path
      self.response_body = "You are being redirected."
    end
  end
end

This is a quick'n'dirty copy paste job . Will take a little more effort if you want have the same signature as redirect_to


text:
Q: Approximation of a monotone function by continuous functions Let $\mu$ be a Radon measure on $\mathbb{R}$. (i.e., a locally finite Borel measure)
Let $I$ be an interval of $\mathbb{R}$.
Let $\gamma : I \mapsto \mathbb{R}$ be a monotone function that is Lebesgue-Stieltjes integrable with respect to $\mu$:
$$\int_I \gamma(x) \mathrm{d}\mu (x) < \infty.$$
I would like a simple argument to prove that there exists a sequence $(\gamma_n)_{n\in\mathbb{N}}$ of continuous and monotone functions $\gamma_n : I \mapsto \mathbb{R}$ such that
$$\int_I \gamma_n(x) \mathrm{d}\mu (x) < \infty$$
and
$$\lim_{n\to\infty} \int_I | \gamma(x) - \gamma_n (x)| \mathrm{d}\mu (x) =0.$$
I have thought I could use the Lusin theorem, but it would require to adapt its statement and proof to show the approximating functions are monotone.
Besides, my hypotheses are much simpler ($\mathbb{R}$, no compacity of the support of approximating functions). So maybe a weaker theorem could give the answer? I am interested by any reference to such theorem.
N.B.: a proof of this is very common if $\mu$ is the Lebesgue measure, but here there is no absolute continuity assumption on $\mu$.

A: I don't think your version of Lusin's theorem can be used to give a short proof of the result, since we need some control over the continuous functions we get. Here's a solution, using a slightly weaker version of Lusin's theorem, and constructing the continuous functions more explicitly.
Let's assume $\gamma$ is non-decreasing (otherwise, work with $-\gamma$). First let's consider $I$ a compact interval of the form $I=[a,b]$, and let's deal with the general case later.
Let $\epsilon>0$. By Lusin's theorem, there exists a subset $A\subseteq I$ of measure $\geq \mu(I)-\epsilon$ such that $\gamma|_A$ (the restriction of $\gamma$ to $A$) is continuous. (This is the slightly weaker form of Lusin's theorem than the one you linked to). Moreover, by regularity of $\mu$, we can assume $A$ is closed.
We can also assume that $b\in A$: If this is not the case, then since $A$ is closed, $A\cup\{b\}$ is also closed and $\gamma|_{A\cup\{b\}}$ is continuous. Similarly, we can assume $a\in A$.
Now we will extend $\gamma|_A$ to a continuous, non-decreasing function on $I$. The complement $O=I\setminus A$ of $A$ is an open set, so it can be written as a countable union of disjoint open intervals $O=\bigcup_n (a_n,b_n)$. Note that $a_n,b_n\in A$ for all $n$.
Define $g=\gamma$ on $A$, and on each set $(a_n,b_n)$, define $g(x)=\gamma(a_n)+\frac{x-a_n}{b_n-a_n}(\gamma(b_n)-\gamma(a_n))$. Let's show that $g$ has the desired properties:

1. $g$ is monotone

Suppose $x<y$ in $I$. We have some cases:
1.1. $x,y\in A$.
Then $g(x)=\gamma(x)<\gamma(y)=g(y)$.
1.2. $x\in A$, $y\not\in A$.
In this case, $y$ is in some set of the form $(a_n,b_n)$, and we must have $x\leq a_n$, so
$$g(x)=\gamma(x)\leq\gamma(a_n)\leq g(y)$$
1.3. $x\not\in A$, $y\in A$.
This is similar to 1.2.
1.4. $x,y\not\in A$.
Then $x\in (a_n,b_n)$ and $y\in(a_m,b_m)$ for certain $n,m$. If $n=m$ then it is clear that $g(x)\leq g(y)$. If $n\neq m$, then the interval $(a_n,b_n)$ stands to the left of the interval $(a_m,b_m)$ (since they are disjoint and contain $x$ and $y$, respectively, and $x<y$), so $b_n\leq a_m$ and thus
$$g(x)\leq g(b_n)=\gamma(b_n)\leq\gamma(a_m)=g(a_m)\leq g(y).$$

2. $g$ is continuous.

We leave the following result as an exercise:

Proposition: Suppose $g:[a,b]\to\mathbb{R}$ is monotone and $x\in [a,b)$. Suppose that there exists a sequence $x_n\in[a,b]$ with $x_n>x$, $x_n\to x$ and $g(x_n)\to g(x)$. Then $g$ is right-continuous as $x$.

Let's use this result: Let $x\in[a,b)$, and let's find a sequence as in the proposition. If $x\not\in A$, then $x\in(a_n,b_n)$ for some $n$ and it is easy enough to find such a sequence (e.g. $x_i=x+(b_n-x)/i$). So suppose $x\in A$. We have two cases:
2.1. There is a sequence $x_n\in A$ with $x_n>x$, $x_n\to x$.
Since $\gamma|_A=g|_A$ is continuous, we immediately have $g(x_n)\to g(x)$.
2.2. There is no sequence $x_n\in A$ with $x_n>x$, $x_n\to x$.
This means that there is some open interval of the form $(x,c)$ which does not intersect $A$, i.e., $(x,c)\subseteq I\setminus A$ and thus $(x,c)\subseteq(a_n,b_n)$ for some $n$. But $x\in A$, so $x=a_n$. Now it is again easy to construct the desired sequence (say $x_i=x+(b_i-a_i)/i$).
Therefore $g$ is right-continuous. Left continuity is similar and therefore $g$ is continuous.

3. $\int_I|\gamma-g|d\mu$ is small.

Both $\gamma$ and $g$ are bounded on $I$ by $\max(|\gamma(a)|,\gamma(b)|)$, and they coincide on a set of measure $\geq\mu(I)-\epsilon$, thus
$$\int_I|\gamma-g|d\mu\leq\max(|\gamma(a)|,\gamma(b)|)\epsilon$$
which is as small as necessary, by adjusting $\epsilon$.
Note that from this it follows that $\int_I|g|d\mu<\infty$.

The above solves the case of a compact interval $I$. If $I$ is of the form $I=[a,b)$, with $b\in(a,\infty]$, then we can write $I=\bigcup_{n=1}^\infty[a_n,a_{n+1}]$, where $a=a_1<a_2<\cdots$ and $a_n\to b$.
Given $\epsilon>0$, for each $n$ find a function $g_n$ on $[a_n,a_{n+1}]$, as above, which is continuous, monotone, $g_n(a_n)=\gamma(a_n)$, $g_n(a_{n+1})=\gamma(a_{n+1})$, and $\int_{[a_n,b_n]}|g_n-\gamma|d\mu<2^{-n}\epsilon$. Define $g$ on $I$ as $g|_{[a_n,a_{n+1}]}=g_n$, and we have the desired properties.
The last case is of intervals of the form $I=(a,b)$, with $-\infty\leq a<b\leq\infty$, and it follows from the previous case with arguments similar to the ones in the paragraph above.

Alternative solution:
We can assume that $I=[a,b]$ is compact and $\gamma$ is non-decreasing and non-constant. Moreover, up to normalization, we can assume $\gamma(a)=0$ and $\gamma(b)=1$. Let's start with the usual simple functions approximating $\gamma$: For each $n$ and $1\leq i<2^n$, take $A_{n,i}=\gamma^{-1}[\frac{i-1}{2^n},\frac{i}{2^n})$, and $A_{n,2^n}=\gamma^{-1}[\frac{2^n-1}{2^n},1]$.
Since $\gamma$ is monotone, each $A_{n,i}$ is an interval (possibly degenerate). Whenever $A_{n,i}$ has nonempty interior (i.e., it is not a point), take $a_{n,i}<b_{n,i}$ with $\operatorname{int}(A_{n,i})=(a_{n,i},b_{n,i})$. Notice that $a_{n,i}=0$ for precisely one $i$, and $b_{n,i}=1$ for precisely one $i$, and $\left\{a_{n,i}\right\}\setminus\left\{0\right\}=\left\{b_{n,i}\right\}\setminus\left\{1\right\}$.
Now take a decreasing sequence $\delta_n$ converging to $0$, in such a way that $a_{n,i}+\delta_n<b_{n,i}-\delta_n$ for all $n,i$. Let $B_{n,i}=(a_{n,i}+\delta_n,b_{n,i}-\delta_n)$.
Given $n$, define $g_n:I\to[0,1]$ as follows: $g_n(a_{n,i})=\gamma(a_{n,i})$, and $g_n(b_{n,i})=\gamma(b_{n,i})$ for all $i$. If $x\in B_{n,i}$ for some $i$, set $g_n(x)=i2^{-n}$. Then extend $g_n$ arbitrarily to some continuous, monotone function on $I$.
Let's show that $g_n$ converges pointwise to $\gamma$. For convenience, for each $n$ consider the partition $\mathscr{P}_n=\left\{A_{n,i}:i\right\}$. Note that $\mathscr{P}_m$ refines $\mathscr{P}_n$ whenever $m\geq n$.
Let $x\in I$ and $k\in\mathbb{N}$. We have two cases:
If $x=a_{k,i}$ for some $i$, then for every $m\geq k$ there will be some $j$ with $x=a_{m,j}$. This happens because $\mathscr{P}_m$ refines $\mathscr{P}_k$. So in this case we have $g_m(x)=\gamma(x)$ for all $m\geq k$. The same happens if $x=b_{k,i}$ for some $i$.
Now suppose $x$ is not any of the $a_{k,i}$ nor any of the $b_{k,i}$. Choose $i$ for which $x\in A_{k,i}$. Then $x$ lies in the interior of $A_{k,i}$, i.e., $x\in(a_{k,i},b_{k,i})$. Choose $N>k$ large enough such that $a_{k,i}+\delta_N<x<b_{k,i}-\delta_N$.
Now let's show that for any $m\geq N$, we have $|g_m(x)-\gamma(x)|\leq 2^{1-k}$. Again, we have some cases:
If $x$ is of the form $a_{m,j}$ or $b_{m,j}$ then $g_m(x)=\gamma(x)$, and we are done. So suppose $x$ is not of the form $a_{m,j}$ nor $b_{m,j}$. Again, there will be some $j$ for which $x\in\operatorname{int}(A_{m,j})=(a_{m,j},b_{m,j})$.
Take $p$ for which $b_{m,p}=b_{k,i}$. Again, since $\mathscr{P}_m$ refines $\mathscr{P}_k$, we have $A_{m,p}\subset A_{k,i}$, and the definition (and nonemptyness) of these sets garantees that $p2^{-m}\leq (i+1)2^{-k}$. Indeed, given $y\in A_{m,p}$, we have
$$(p-1)2^{-m}\leq\gamma(y)\leq p2^{-m}\qquad\text{and}\qquad (i-1)2^{-k}\leq\gamma(y)\leq i2^{-k}$$
so
$$p2^{-m}\leq\gamma(y)+2^{-m}\leq\gamma(y)+2^{-k}\leq (i+1)2^{-k}.$$
By our choice of $\delta$, we have $x<b_{n,i}-\delta_N\leq b_{m,p}-\delta_m$, so we can find some $y\in B_{m,p}$ with $x\leq y$. Since $g_m$ is monotone,
$$g_m(x)\leq g_m(y)=p2^{-m}\leq (i+1)2^{-k}$$
With the same kind of reasoning (now working with the $a_{m,j}$), we can prove that
$$(i-1)2^{-k}\leq g_m(x)$$
so we have
$$(i-1)2^{-k}\leq g_m(x)\leq(i+1)2^{-k}$$
and also, now by definition of $A_{k,i}$,
$$(i-1)2^{-k}\leq \gamma(x)\leq i2^{-k}\leq (i+1)2^{-k}$$
so $|g_m(x)-\gamma(x)|\leq 2^{1-k}$, as we wanted.
Therefore $g_m\to \gamma$ pointwise (everywhere!), and dominated convergence implies $\int g_m\to\int\gamma$. We did not assume anything about the measure (just that it was finite on $I$).

A: @Luiz Cordeiro: thanks for your answer.
I may have an alternative answer for the case $I = [a, b]$, with is reminiscent of the good old Riemann integration and does not use Lusin theorem.
Assume $\gamma(a) \neq \gamma (b)$ (else, there is nothing to do).
Let $\epsilon > 0$. Define $\tilde\epsilon := \epsilon / |\gamma(b)-\gamma(a)|$.
Since $\mu$ is locally finite, $\mu$ must have a finite number of atoms whose mass is $\geq \tilde\epsilon$. Therefore, there exists a finite partition $(A_n)_{n=1}^N$ of $I$ (with $N \in \mathbb{N}^*$) such that

*

*for all $n \leq N$, $\mu (\mathring{A}_n) \leq \tilde\epsilon$,

*$A_n := [x_n, x_{n+1})$ for all $n < N$, and $A_N := [x_N, x_{N+1}]$,

*$a = x_1 < x_2 < \ldots < x_N < x_{N+1} = b$.

(the idea is to choose some of the $(a_n)$ as those big atoms)
Define $f$ piecewise with
$$\forall x \in A_n, \qquad f(x) := \gamma(x_{n}) + (\gamma(x_{n+1}) - \gamma(x_n)) \frac{x-x_n}{x_{n+1}-x_n}.$$
Since $\gamma$ is monotone,

*

*$\forall x \in A_n, \quad |f(x)-\gamma(x)| \leq |\gamma(x_{n+1})-\gamma(x_n)|,$

*$\sum_{n=1}^N  |\gamma(x_{n+1})-\gamma(x_n)| = |\gamma(b)-\gamma(a)|,$

*$f$ is continuous, monotone and coincides with $\gamma$ on the boundaries of all $A_n$.

In addition,
$$\int_I |\gamma-f| \mathrm{d}\mu = \sum_{n=1}^N \int_{A_n} |\gamma-f| \mathrm{d}\mu = \sum_{n=1}^N \int_{\mathring{A}_n} |\gamma-f| \mathrm{d}\mu$$
$$\leq \sum_{n=1}^N \int_{\mathring{A}_n} |\gamma(x_{n+1})-\gamma(x_n)| \mathrm{d}\mu (t)$$
$$\leq \sum_{n=1}^N  |\gamma(x_{n+1})-\gamma(x_n)| \int_{\mathring{A}_n} \mathrm{d}\mu \leq \frac{\epsilon}{|\gamma(b)-\gamma (a)|} \sum_{n=1}^N  |\gamma(x_{n+1})-\gamma(x_n)|,$$
so
$$\int_I |\gamma-f| \mathrm{d}\mu \leq \epsilon.$$
For the case $I$ is not compact, Luiz Cordeiro's argument can be used.


text:
Q: Why can't I use float value as a template parameter? When I try to use float as a template parameter, the compiler cries for this code, while int works fine.
Is it because I cannot use float as a template parameter?
#include<iostream>
using namespace std;

template <class T, T defaultValue>
class GenericClass
{
private:
    T value;
public:
    GenericClass()
    {
        value = defaultValue;
    }

    T returnVal()
    {
        return value;
    }
};

int main()
{
    GenericClass <int, 10> gcInteger;
    GenericClass < float, 4.6f> gcFlaot;

    cout << "\n sum of integer is "<<gcInteger.returnVal();
    cout << "\n sum of float is "<<gcFlaot.returnVal();

    return 0;
}

Error:
main.cpp: In function `int main()':
main.cpp:25: error: `float' is not a valid type for a template constant parameter
main.cpp:25: error: invalid type in declaration before ';' token

main.cpp:28: error: request for member `returnVal' in `gcFlaot',
                    which is of non-class type `int'

I am reading "Data Structures for Game Programmers" by Ron Penton, the author passes a float, but when I try it it doesn't seem to compile.

A: If you are ok to have a fixed default per type you can create a type to define it as a constant and specialize it as needed.
template <typename T> struct MyTypeDefault { static const T value; };
template <typename T> const T MyTypeDefault<T>::value = T();
template <> struct MyTypeDefault<double> { static const double value; };
const double MyTypeDefault<double>::value = 1.0;

template <typename T>
class MyType {
  public:
    MyType() { value = MyTypeDefault<T>::value; }
  private:
    T value;
 };

If you have C++11 you can use constexpr when defining the default value. With C++14, MyTypeDefault can be a template variable which is a bit cleaner syntactically.
//C++14
template <typename T> constexpr T MyTypeDefault = T();
template <> constexpr double MyTypeDefault<double> = 1.0;

template <typename T>
class MyType {
  private:
    T value = MyTypeDefault<T>;
 };

A: The current C++ standard does not allow float (i.e. real number) or character string literals to be used as template non-type parameters. You can of course use the float and char * types as normal arguments.
Perhaps the author is using a compiler that doesn't follow the current standard?

A: Just to provide one of the reasons why this is a limitation (in the current standard at least).
When matching template specializations, the compiler matches the template arguments, including non-type arguments.
By their very nature, floating point values are not exact and their implementation is not specified by the C++ standard.  As a result, it is difficult to decide when two floating point non type arguments really match:
template <float f> void foo () ;

void bar () {
    foo< (1.0/3.0) > ();
    foo< (7.0/21.0) > ();
}

These expressions do not necessarily produce the same "bit pattern" and so it would not be possible to guarantee that they used the same specialization - without special wording to cover this.

A: Indeed, you can't use float literals as template parameters. See section 14.1 ("A non-type template-parameter shall have one of the following (optionally cv-qualified) types...") of the standard.
You can use a reference to the float as a template parameter:
template <class T, T const &defaultValue>
class GenericClass

.
.

float const c_four_point_six = 4.6; // at global scope

.
.

GenericClass < float, c_four_point_six> gcFlaot;

A: You can always fake it...
#include <iostream>

template <int NUM, int DEN>
struct Float
{
    static constexpr float value() { return (float)NUM / (float)DEN; }
    static constexpr float VALUE = value();
};

template <class GRAD, class CONST>
struct LinearFunc
{
    static float func(float x) { return GRAD::VALUE*x + CONST::VALUE; }
};

int main()
{
    // Y = 0.333 x + 0.2
    // x=2, y=0.866
    std::cout << " func(2) = "
              << LinearFunc<Float<1,3>, Float<1,5> > ::func(2) << std::endl;
}

Ref: http://code-slim-jim.blogspot.jp/2013/06/c11-no-floats-in-templates-wtf.html

A: The other answers give good reasons why you probably do not want floating point template parameters, but the real deal breaker IMO is that equality using '==' and bitwise equality are not the same:

*

*-0.0 == 0.0, but 0.0 and -0.0 are not bitwise equal

*NAN != NAN
Neither kind of equality is a good cancidate for type equality:
Of course, point 2. makes using == invalid for determining type equality.
One could use bitwise equality instead, but then x != y does not imply that MyClass<x> and MyClass<y> are different types (by 2.), which would be rather strange.

A: THE SIMPLE ANSWER
The standard doesn't allow floating points as non-type template-arguments, which can be read about in the following section of the C++11 standard;

14.3.2/1      Template non-type arguments      [temp.arg.nontype]
A template-argument for a non-type, non-template template-parameter
shall be one of:

*

*for a non-type template-parameter of integral or enumeration type, a converted constant expression (5.19) of the type of the
template-parameter;

*the name of a non-type template-parameter; or

*a constant expression (5.19) that designates the address of an object with static storage duration and external or internal linkage
or a function with external or internal linkage, including function
templates and function template-ids but excluding non-static class
members, expressed (ignoring parentheses) as & id-expression, except
that the & may be omitted if the name refers to a function or array
and shall be omitted if the corresponding template-parameter is a
reference; or

*a constant expression that evaluates to a null pointer value (4.10); or

*a constant expression that evaluates to a null member pointer value (4.11); or

*a pointer to member expressed as described in 5.3.1.

But.. but.. WHY!?
It is probably due to the fact that floating point calculations cannot be represented in an exact manner. If it was allowed it could/would result in erroneous/weird behavior when doing something as this;
func<1/3.f> ();
func<2/6.f> ();

We meant to call the same function twice but this might not be the case since the floating point representation of the two calculations isn't guaranteed to be exactly the same.

How would I represent floating point values as template arguments?
With C++11 you could write some pretty advanced constant-expressions (constexpr) that would calculate the numerator/denominator of a floating value compile time and then pass these two as separate integer arguments.
Remember to define some sort of threshold so that floating point values close to each other yields the same numerator/denominator, otherwise it's kinda pointless since it will then yield the same result previously mentioned as a reason not to allow floating point values as  non-type template arguments.

A: Starting with C++20 this is possible.
This also gives the answer to the original question:
Why can't I use float value as a template parameter?

Because nobody implemented it in the standard yet. There is no fundamental reason.
In C++20 non-type template parameters can now be floats and even class objects.
There are some requirements on class objects (they must be a literal type) and fulfil some other requirements to exclude the pathological cases such as user defined operator == (Details).
We can even use auto
template <auto Val>
struct Test {
};

struct A {};
static A aval;
Test<aval>  ta;
Test<A{}>  ta2;
Test<1.234>  tf;
Test<1U>  ti;

Note that GCC 9 (and 10) implements class non-type template parameters, but not for floats yet.

A: Wrap the parameter(s) in their own class as constexprs. Effectively this is similar to a trait as it parameterizes the class with a set of floats.
class MyParameters{
    public:
        static constexpr float Kd =1.0f;
        static constexpr float Ki =1.0f;
        static constexpr float Kp =1.0f;
};

and then create a template taking the class type as a parameter
  template <typename NUM, typename TUNING_PARAMS >
  class PidController {

      // define short hand constants for the PID tuning parameters
      static constexpr NUM Kp = TUNING_PARAMS::Kp;
      static constexpr NUM Ki = TUNING_PARAMS::Ki;
      static constexpr NUM Kd = TUNING_PARAMS::Kd;

      .... code to actually do something ...
};

and then use it like so...
int main (){
    PidController<float, MyParameters> controller;
    ...
    ...
}

This allows the compiler to guarantee that only a single instance of the code is created for each template instantiation with the same parameter pack. That gets around all the issues and you are able to use floats and doubles as constexpr inside the templated class.

A: If you don't need the double to be a compile-time constant, you can pass it in as a pointer:
#include <iostream>

extern const double kMyDouble = 0.1;;

template <const double* MyDouble>
void writeDouble() {
   std::cout << *MyDouble << std::endl;
}

int main()
{
    writeDouble<&kMyDouble>();
   return 0;
}

A: If you only want to represent a fixed precision, then you can use a technique like this to convert a float parameter into an int.
For example an array with a growth factor of 1.75 could be created as follows assuming 2 digits of precision (divide by 100).
template <typename _Kind_, int _Factor_=175>
class Array
{
public:
    static const float Factor;
    _Kind_ * Data;
    int Size;

    // ...

    void Resize()
    {
         _Kind_ * data = new _Kind_[(Size*Factor)+1];

         // ...
    }
}

template<typename _Kind_, int _Factor_>
const float Array<_kind_,_Factor_>::Factor = _Factor_/100;

If you dont like the representation of 1.75 as 175 in the template argument list
then you could always wrap it in some macro.
#define FloatToIntPrecision(f,p) (f*(10^p))

template <typename _Kind_, int _Factor_=FloatToIntPrecision(1.75,2)>
// ...


text:
Q: Concatenate Integers without calculate PHP On my database, dates are in the format DD-MM-YYYY. But for a SELECT, I need to be between two dates.
I know I must use BETWEEN syntax but with this, I need the date to be in the format YYYY/MM/DD.
So here's my code to change the syntax :
// my URL is : '.../pdf.php?date1=22-05-2015&date2=29-05-2015'
$date1=explode('-',$_GET["date1"]); // $_GET["date1"] = '22-05-2015'
$date2=explode('-',$_GET["date2"]); // $_GET["date2"] = '29-05-2015'

$date1_good = $date1[2].'/'.$date1[1].'/'.$date1[0];
$date2_good = $date2[2].'/'.$date2[1].'/'.$date2[0];

The problem is, $date1_good and $date2_good are now float values and not a string like '2015/05/29'.
I have tried using strval() and (string) but nothing worked.
Do you have any idea to make it work ? Thank you !

A: It's simple to do like this:-
$date1_good = date('Y/m/d',strtotime($_GET["date1"]));
$date2_good = date('Y/m/d',strtotime($_GET["date2"]));

Note:- I gave an example just change format according to your wish. Good-luck. Thanks. check this:-
<?php

$_GET["date1"] = '22-05-2015';
$_GET["date2"]= '29-05-2015';
$date1_good = date('Y/m/d',strtotime($_GET["date1"]));
$date2_good = date('Y/m/d',strtotime($_GET["date2"]));

echo $date1_good.'----------------'.$date2_good;

?>

Output:-  http://prntscr.com/7aofp6

A: You can try this:
date('Y-m-d', strtotime("23/10/2009"));

A: Simply you can do it using DateTime function as
$date1 = "22-05-2015";
$date2 = "29-05-2015";
$date_1 = DateTime::createFromFormat("d-m-Y",$date1);
$date_2 = DateTime::createFromFormat("d-m-Y",$date2);
echo $date_1->format('Y/m/d')."<br>";
echo $date_2->format('Y/m/d');