text:
Q: HTML5 Local Storage store form data for select box where multiple values are selected I have a form which saves a users preferance in local storage, it can be seen in this fiddle or below.
With what I have so far there are 2 main problems.

*

*On clicking the save button you are meant to empty the myStorage then append what you have just selected in there, so they can see the live result of what they have clicked.  It only remembers if you re-run the fiddle.

*My biggest problem is that what I have is great for select fields with one option but in this case the user can select multiple, so what do I need to add to it so that the user can save multiple values to local storage so next time they load the page there multiple selections will be saved?
<form name="Filter">
<select multiple="1" id="filter">
    <option value="111">Andrew</option>
    <option value="222">Bill</option>
    <option value="333">Charles</option>
    <option value="444">Dikembe</option>
    <option value="555">Edward</option>
</select>
</form>

click to store

People I have stored

JS
    var iSelectedTitle = localStorage.getItem('title');
    var iSelectedVal = localStorage.getItem('value');
    console.log("iSelectedTitle: " + iSelectedTitle);
    console.log("iSelectedVal: " + iSelectedVal);

    $("#filter option").each(function () {
        if ($(this).val() == iSelectedVal) {
            $(this).attr("selected", "selected");
        }
    });

    $("#store").click(function () {
        var mytitle = $("#filter option:selected").text();
        var storedTitle = localStorage.setItem("title", mytitle);
        console.log("mytitle: " + mytitle);
        console.log("storedTitle: " + storedTitle);

        var myValue = $("#filter option:selected").val();
        var storedValue = localStorage.setItem("value", myValue);
        console.log("myValue: " + myValue);
        console.log("storedValue: " + storedValue);

        if (iSelectedTitle != "undefined") {
            $('#myStorage').empty().append(iSelectedTitle);
        }
    });
    if (iSelectedTitle != "undefined") {
        $('#myStorage').append(iSelectedTitle + ' - View profile');
    }

A: You can add multiple options to an array using map of jQuery :
var optArray = $("#filter option:selected").map(function () {
        return {
            "title": this.innerHTML,
            "value": this.value
        }
}).get();

This will give you a nice array like this :
[
    { "title": "Andrew", "value": "111" },
    { "title": "Bill", "value": "222" },
    { "title": "Charles", "value": "333" }
]

For adding to localStorage :
$("#store").click(function () {
    //get the selected options in the form of an array
    var optArray = $("#filter option:selected").map(function () {
        return {
            "title": this.innerHTML,
            "value": this.value
        }
    }).get();
    console.log(optArray);
    //set that to localStorage
    localStorage["optArray"] = JSON.stringify(optArray);
    //refresh myStorage
    getFromStore();
});

For refreshing the myStorage container with your newly added people, you'll have to call this handler as the last event inside the `click event (above).
var getFromStore = function () {
    //check if store values are null, if null, make store =[]
    var store = [undefined, null].indexOf(localStorage["optArray"]) != -1 ? [] : JSON.parse(localStorage["optArray"]);
    console.log(store);
    //empty container before u put values
    $('#myStorage').html('');
    //check if store is empty
    if (store.length != 0) {
        //loop over store if it aint empty and append the content into myStorage div
        for (var k in store) {
            var str = '
' + store[k]["title"] + ' - View profile
';
            console.log(store[k]);
            $('#myStorage').append(str);
        }
    } else {
        //do this if no data is found in localStorage
        $("#myStorage").html("No people found in store");
    }
}

Then, in DOM ready, call getFromStore to refresh myContainer on load of the page:
$(function() {
  getFromStore();
})

Demo : http://jsfiddle.net/hungerpain/hqVGS/9/
EDIT
To select the checkboxes by default, add the folowing line in the getFromStore function :
  $("[value=" + store[k]["value"] + "]","#filter").prop("selected", true); //find the option with the corresponding value and select it

Updated demo : http://jsfiddle.net/hungerpain/hqVGS/10/

A: You could save multiple values in an array,
var myValuesArr = ['one','two','three'];

The array would need to be serialized before it is saved to localStorage
var serialVals = JSON.stringify(myValuesArr);
localStorage.setItem('numbers',serialVals);

Likewise, the stored data will have to be unserialized after it is read back
var serialVals = localStorage.getItem('numbers');
var myValuesArr = JSON.parse(serialVals);


text:
Q: Set replica set member host names on Secondary I have a replica set rset1 that consists of a primary, secondary, and a backup server.
I recently just changed their DNS names in Route53--the only name that didn't change was the Primary's, however since it can't connect to the secondaries, it stepped-down from being Primary.
I've been trying write a query to use in an update of local.system.replset, where local is the database and system.replset the collection; I can't seem to get anywhere with it, though.
Here's what system.replset looks like:
{ "_id" : "rset1",
  "version" : 7,
  "members" : [
    { "_id" : 0,
      "host" : "mongo-rs1-p.foo-bar.com:27017",
      "priority" : 3
    },
    { "_id" : 1,
      "host" : "mongo-rs1-s1.foo-bar.com:27017",
      "priority" : 2
    },
    { "_id" : 2,
      "host" : "mongo-rs1-s0.foo-bar.com:27017"
    }
  ]
}

I need to change members to this:
 [
   { "_id": 0,
     "host": "mongo-rs-p.foo-bar.com:27017",
     "priority": 3
   },
   { "_id": 1,
     "host": "mongo-rs1-s.foo-bar.com:27017",
     "priority": 2
   },
   { "_id": 2,
     "host": "mongo-rs1-b.foo-bar.com:27017"
   }
]

I've tried using:
cfg = rs.conf()
cfg.members[1].host = "mongo-rs1-s.foo-bar.com:27017"
cfg.members[2].host = "mongo-rs1-b.foo-bar.com:27017"
rs.reconfig(cfg)

But since the primary is no longer primary, I can't get this to run successfully, and running db.getMongo().setSlaveOk() didn't help with using rs.reconfig()
As a last resort (I've had this problem before) I can run rm -rf /data; mkdir -p /data to remove mongo's data directory (after killing the mongod process) and then I can start the mongod server again and rebuild the replica set from scratch, but I'd rather not do that.
So how can I update the members of the replica set without deleting the database on a primary that  stepped down?

A: There is a guide for how to do this (reconfigure a replica set with unavailable members) here:
http://docs.mongodb.org/manual/tutorial/reconfigure-replica-set-with-unavailable-members/
You essentially have to do a forced reconfig of the set because there is no primary available.  If you want to keep a set operational while doing this type of move, you can:

*

*Use your hosts file to temporarily point the old names to the new (or similar) and "fool" the primary into thinking they are up (then make the permanent changes one at a time)

*Temporarily add arbiters to prevent the primary from stepping down (2 more for example, so the primary is kept with 3/5 votes)

*Reconfigure the set to a single node before doing the moves

*Do the moves one server at a time, ensuring there are 2/3 nodes up to form a majority at all times (and hence keep a primary up)

redpajama_set_name: RedPajamaStackExchange


text:
Q: keytool error: java.io.IOException: Invalid keystore format Got an error while run the command in terminal:
"keytool -list -v -alias androiddebugkey -keystore %USERPROFILE%.android\debug.keystore"
Results in below error:
java.io.IOException: Invalid keystore format
        at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:663)
        at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:56)
        at sun.security.provider.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:224)
        at sun.security.provider.JavaKeyStore$DualFormatJKS.engineLoad(JavaKeyStore.java:70)
        at java.security.KeyStore.load(KeyStore.java:1445)
        at sun.security.tools.keytool.Main.doCommands(Main.java:941)
        at sun.security.tools.keytool.Main.run(Main.java:379)
        at sun.security.tools.keytool.Main.main(Main.java:372)

P.S: I have seen similar questions regarding this error, but none of the solutions solved my problem.

A: Solved: After Running Flutter -v in android studioFound Out That:
Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840)
which indicated that there was difference with the java version installed (was currently using java 1.8).
I solved the problem by installing the same java version (In my case 11.0.12) and adding it to the PATH in environmental variables.

A: A simpler way would be to use Android Java, change "YOUR_USERNAME_HERE"
"c:\Program Files\Android\Android Studio\jre\bin\keytool.exe" -list -v -keystore "C:\Users\YOUR_USERNAME_HERE\.android\debug.keystore"

Default password android


text:
Q: POST variable always stays empty This is the method in which i manage the data send with jquery.ajax. By default is send an empty string and on each change i watch the change on the input and resend it. Through console things are good but in php $this->searchField always has the value of an empty string
function checkInfo(){
        if(isset($_POST['searchField'])){
            $this->searchField = json_decode($_POST['searchField']);

                if ($this->searchField != ""){
                    $this->query = "SELECT * FROM myguests WHERE firstName like '%".$searchField."%'";
                }
                else if ($this->searchField == "") {
                    $this->query = "SELECT * FROM myguests ORDER BY id";
                }
                $this->tableDisplay();
                exit();
            }
            else{
                return "error";
            }
        }

This is my jquery ajax function :
function searchGuests(users){
  var data = {
    "searchField": users
  };
  console.log(data);
  $.ajax({
      type: "POST",
      dataType: "text",
      url: "controllers/manageTable.php",
      data: data
    })
    .done(function(tr) {
      $("#tableBody").empty();
      $("#tableBody").append(tr);
    })
    .fail(function(error){
      console.log(error);
    });
};

Any idea what I am missing?

A: Try encoding the users to a string before sending it over.
function searchGuests(users){
  var data = {
    "searchField": JSON.stringify(users);
  };
  console.log(data);
  $.ajax({
      type: "POST",
      dataType: "text",
      url: "controllers/manageTable.php",
      data: data
    })
    .done(function(tr) {
      $("#tableBody").empty();
      $("#tableBody").append(tr);
    })
    .fail(function(error){
      console.log(error);
    });
};


text:
Q: run async db read task in background I have function called get_active_allowed_systems_by_poll where I want to call it in the background 10 times/minute and refresh  new systems that I have gotten in last 10 seconds.
import asyncio
from threading import Thread

async def create_state_machine_at_init(app):

    worker_loop = asyncio.new_event_loop()
    worker = Thread(target=start_db_worker, args=(worker_loop,))
    worker.start()

    worker_loop.call_soon_threadsafe(get_active_allowed_systems_by_poll, app, 30)

async def get_active_allowed_systems_by_poll(app, interval=10):
    params = {
        param: key
        for param, key
        in app.config.get_active_allowed_systems_by_poll_params.items()
        }
    params['interval'] = interval

    operation = prepare_exec(
        app.config.get_active_allowed_systems_by_poll,
        **params
        )
    ACTIVE_ALLOWED_SYSTEMS
    ACTIVE_ALLOWED_SYSTEMS = (await app['database'].execute(operation)).all()
    return ACTIVE_ALLOWED_SYSTEMS

def start_db_worker(loop):
    """Switch to new event loop and run forever"""

    asyncio.set_event_loop(loop)
    loop.run_forever()

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/events.py:145: RuntimeWarning: coroutine 'get_active_allowed_systems_by_poll' was never awaited


text:
Q: A quantity associated to a compact Riemannian manifold with boundary(The pair of Laplacian) Let $M$ be a Riemannian manifold with boundary $\partial M$.
Are the following operators, Fredholm operators?Is there a geometric terminology and geometric interpretation for the fredholm index of these operators?
1) The first operator is the pair of Laplacian $(\Delta,\Delta_{\partial})$ defined on $M$ and $\partial M$, where $\Delta_{\partial}$ is the Laplacian associated to the Riemannian metric which $\partial M$ inherits from $M$.
2)The second operator is the standard Cauchy problem for Harmonic functions, $\Delta u=0$  but the boundary condition is  $\Delta_{\partial} u$.


text:
Q: Setting up Ruby on Rails How do you go about setting up a Rails application on a standard web server? I want to just throw my application into cgi-bin and run it, but Rails clearly wants to control the file system and how file accesses are routed. So it's all very well working on my application in its little sandbox, but how do you actually close the gap and serve an application?

A: You need to Create Ruby on Rails app first then you can deploy it on Heroku. Here is very nice reference link from scratch..
https://devcenter.heroku.com/articles/getting-started-with-rails4
Hope this will help you..to create Rails Demo App and all steps of deploying on Heroku.

A: Deploy
There are a plethora of tutorials on how to deploy rails applications correctly.
Most notable (we've recently used) are:

*

*DigitalOcean - Deploying to a VPS

*GoRails - Deploying on Ubuntu with Nginx

*Heroku - Deploying to Heroku with GIT

This will give you information on how to deploy to either the Heroku platform, or one of the many VPS type hosting providers out there. We use Rackspace, and the DigitalOcean & GoRails tutorials were invaluable when setting up our server again

Rails
Although I'm not totally in tune with how Rails runs on file-system level, you have to appreciate that Rails runs with a multitude of dependencies & can also be compiled at run time
Processing requests in this way has to be handled by more than just the standard hosting software, and indeed, the most recommended solution from the Rails core team is Phusion Passenger


text:
Q: Power Bi - Add calcuation to Group by in Advanced Editor I am working with PowerBi and somewhat new. I created a table by using the Group by function in the Power Bi Query Editor. In the group by, I am summing total duration in minutes by category. I want to get total duration in hours. Is it possible to divide by 60 to get the hour through the Advanced Editor. Below is the Advanced Editor code.
let
    Source = #"Data",
    #"Grouped Rows" = Table.Group(Source, {"category"}, {{"Total Minutes", each List.Sum([duration_in_min]), type nullable number}}),
    #"Filtered Rows" = Table.SelectRows(#"Grouped Rows", each ([category] <> null))
in
    #"Filtered Rows"

A: Yes sure, you either calculate the total hours instead of total minutes by using
    #"Grouped Rows" = Table.Group(Source, {"category"}, {{"Total Minutes", each List.Sum([duration_in_min]) / 60, type nullable number}}),

Or create a new column Total Hours so your query would be something like this:
let
    Source = Data,
    #"Grouped Rows" = Table.Group(Source, {"category"}, {{"Total Minutes", each List.Sum([duration_in_min]), type nullable number}}),
    #"Filtered Rows" = Table.SelectRows(#"Grouped Rows", each ([category] <> null)),
    #"Added Total Hours" = Table.AddColumn(#"Filtered Rows", "Total Hours", each [Total Minutes]/60)
in
    #"Added Total Hours"


text:
Q: How to know when a DataGridRow is clicked? I am using the Windows Community Toolkit WinUI DataGrid control. I would like to run some code when a row is clicked. How can I do that?
I have tried:

*

*SelectionChanged event: Only works the first time the row is clicked, as after that the same row is being selected. Also gets triggered if the row is moved to via the keyboard.

*CurrentCellChanged event: Only works the first time a cell is clicked, as after that clicking the same cell does not change the current cell. (And I could not find a way to clear the current cell programmatically.)

*Answers like this show how to add row event handlers via style in WPF, but this does not work in WinUI.

Any ideas?

A: I ended up using the PointerReleased event. (Previously I had discarded this event as I could not figure out which row was clicked.)
<ctWinUI:DataGrid
    PointerReleased="dgDesktops_PointerReleased"
    ...>

And to find the DataGridRow that was clicked I traverse the visual tree:
private async void dgDesktops_PointerReleased(object sender, PointerRoutedEventArgs e)
{
    DataGridRow clickedRow = ViewUtils.FindParent<DataGridRow>((UIElement)e.OriginalSource);
    if (clickedRow != null)
    {
        MyModel rowModel = (MyModel)clickedRow.DataContext;
        // Do stuff
    }
}

public static T FindParent<T>(DependencyObject childElement) where T : Control
{
    DependencyObject currentElement = childElement;

    while (currentElement != null)
    {
        if (currentElement is T matchingElement)
        {
            return matchingElement;
        }

        currentElement = VisualTreeHelper.GetParent(currentElement);
    }

    return null;
}

Not the most elegant solution, but it works :)


text:
Q: Why str.length() is output as a char? Here is my c++ code:
#include<bits/stdc++.h>
using namespace std;
int main()
{
    string str1;
    cin>>str1;
    int j=-1;
    cout<<typeid(str1.length()).name()<<endl;
    cout<<(j>str1.length())<<endl;
    int len=str1.length();
    cout<<len<<' '<<(j>=len);
}

I input:
abc

And the outcome is:
j
1
3 0

As can be seen, typeid(str1.length()).name() is j, and -1>str1.length()
I wonder why this is the case

A:
I wonder why this is the case
typeid(str1.length()).name() is j

Because that is how your language implementation happens to mangle the type name. On my system it is m.
To be clear, the type is same as std::size_t which is alias of an unsigned integer type.

and -1>str1.length()

This is because, being a negative number, -1 is outside the representable values of an unsigned type and when converted to the representable range, it becomes larger than 3. In fact, the -1 converted to unsigned will be the maximum representable value of that type.

A: The type of str1.length() is std::string::size_type, which is some unsigned integral type (usually size_t). In the comparison j>str1.length(), the signed integer j is converted to that unsigned type modulo 2^n for some n, whereby -1 becomes 2^n-1 - a large positive value.


text:
Q: remove a class element How to remove a class that has been appended to a div id? Earlier I appended a star to a label,when a checkbox is click.
 $(" * ").appendTo("#displayPanel #labelstr"+div_id);

Now,if the same checkbox is clicked again I want to remove that star.
I know there is a remove() option, but what is the proper code for it?
Please guide me.

A: By the looks of it, you're not trying to remove a class which would be the removeClass() command, but instead need to remove a child element from a

You could do
$("#displayPanel #labelstr" + div_id + " span.req").remove();

to remove the child span element with class 'req' from the
.

A: No need to use 2 id selectors as they 'should' be unique, so just do
$("#labelstr" + div_id + " span.req").remove();

A: My guess:
$('#displayPanel #labelstr'+div_id+' .req').remove();

if you want to remove the .req and only have one of them per element.

A: I found out the answer. It is
   $('.req').remove();

Earlier I tried the same,without the quotes, that is why I didn't get the required result.
@machine: Yes,it is jQuery. Thank you.


text:
Q: Choose printer when printing from JS I'm trying to write some code to print my page. However, I'd like to choose printer myself (e.g. virtual PDF) to make sure user has it by default when print dialogue pops up.
Is it even achievable in JS? I read multiple articles about print() function but I didn't find anything like printer selection.
Unfortunately, I don't have any code to provide since I don't know it it's even possible. In a nutshell, the question is if it's possible to choose some value from this dropdown programatically

Something like
function printPdf() {
   print({printer: "pdf"});
}

where print() is default printing function.


text:
Q: How does Linked List function to make another linked list with different order of elements. Explanation please struct node* question4(struct node *list){ //list = 66, 9, 14, 52, 87, 14, 17
      struct node* a = list; //a = 66, 9, 14, 52, 87, 14, 17 pointing to head (66)
      struct node* b = list; //b = 66, 9, 14, 52, 87, 14, 17 pointing to head (66)
      struct node* c;
      if(a == NULL) return NULL; // a is not NULL it's pointing to 66
      while(a->next != NULL) // run until a points to the last element (17)
            a = a->next;
      a->next = b; //next element of 17 points to b (which is 66).
      c = b->next; // c points to what b is pointing to next which is 9.
      b -> next = NULL; // next element of b is NULL(instead of 14). what happens here?
      return c;
}

So a is connected to b. so a's element goes like this?
66->9->14->52->87->14->17->66->9->14->52->87->14->17
and b is just 66->9->NULL?
c is 9->14->52->87->14->17? OR 9->14->52->87->14->17->66 ? why?
I'm currently learning about linked list, thank you guys for your help!

A: The program shifts the head of the linked list right by one element, and loops back the original first element to the end. You have followed correctly for the most part, the last few lines work as follows:
a->next = b;

This links the original last element to the original first element, i.e., creates a link 17->66.
c = b->next;

c here is used to store the new head element. Since b was pointing to the original head, and we want the second element to be the new head, c points to b's next element, i.e., 9.
b -> next = NULL;

The a->next = b; made the linked list circular, this breaks the circle, by removing the 66->9 link.
Finally, c is returned, so the list at the end is:
9->14->52->87->14->17->66

A: This code is used to rotate a singly-linked list to the right one node.
Let's consider this statement
c = b->next;

the pointer b after this declaration
struct node* b = list

points to the element with the value 66
b = 66, 9, 14, 52, 87, 14, 17

So c points to the next element with the value 9` (b->next).
Then after this statement
b -> next = NULL;

we have
66, NULL, 9, 14, 52, 87, 14, 17
          ^
          |
          c

But after the previous code snippet
  while(a->next != NULL) // run until a points to the last element (17)
        a = a->next;
  a->next = b

the last mode with the value 17 points to the previously first node with the value 66.
As a result you have
c =  9, 14, 52, 87, 14, 17, 66, NULL


text:
Q: How to draw a plot with a zoomed in portion next to it?
How to add zoom area and to give and label top x axis?
Here is my code:
\begin{tikzpicture}
 \begin{axis}[
   scaled ticks=false,
   xmin=0,
   ymin=0,
   xlabel=In,
   ylabel=out,
 ]
    \addplot[domain=15:140, blue, ultra thick,smooth] {10000/(9999*e^(-0.125*x)+10)+120};

\end{axis}
\end{tikzpicture}
\hspace{1cm}
\begin{tikzpicture}
 \begin{axis}[
   scaled ticks=false,
   xmin=20,
   ymin=80,
   xlabel=In,
   ylabel=out,

 ]
    \addplot[domain=5:40, blue, ultra thick,smooth] {10000/(9999*e^(-0.125*x)+10)+100};

\end{axis}
\end{tikzpicture}

A: Here's a suggestion. There are some comments in the code, ask if anything is unclear.

\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\usepackage{filecontents}

% if this is uncommented, all the instances of "axis cs:" below can be removed
%\pgfplotsset{compat=1.11}

% calc library required for the ($(..)+(..)$) coordinate syntax
\usetikzlibrary{calc}

\begin{document}
\begin{tikzpicture}[
  % as the function is used more than once, make a shorthand
  declare function={
   f(\x)=10000/(9999*e^(-0.125*\x)+10)+100;
  }
]
 \begin{axis}[
   scaled ticks=false,
   xmin=0,
   ymin=0,
   xlabel=In,
   ylabel=out,
   % add a name to the axis, used to position the second one
   name=ax1
 ]

 \addplot[domain=15:140, blue, ultra thick,smooth] {f(x)};

  % define coordinates at bottom left and top left of rectangle
  \coordinate (c1) at (axis cs:20,80);
  \coordinate (c2) at (axis cs:20,240);
  % draw a rectangle
  \draw (c1) rectangle (axis cs:42,240);

\end{axis}

 \begin{axis}[
   name=ax2,
   scaled ticks=false,
   xmin=20,xmax=42,
   ymin=80,ymax=240,
   xlabel=In,
   ylabel=out,
   % place second axis relative to first one
   % anchor is south west
   at={($(ax1.south east)+(2cm,0)$)},
   % turn on grid
   xmajorgrids=true,
   grid style={help lines,dashed},
   % to avoid clipping of a...e nodes
   clip=false
 ]
    \addplot[domain=20:40, blue, ultra thick,smooth] {f(x)};

    \foreach \x/\txt in {20/a,25/b,30/c,35/d,40/e}
    {
     \edef\temp{\noexpand\draw [dashed] (axis cs:\x,{f(\x)}) coordinate (tmp) -- ({rel axis cs:0,0}|-tmp) node[left] {\txt};}
      \temp
    }

\end{axis}

% third axis for the top axis
\begin{axis}[
at={(ax2.south west)},
% put x-axis labels etc. on top
axis x line=top,
% remove arrow tip
axis line style={-},
axis y line=none,
xmin=20,xmax=42,
ymin=0,ymax=5,
xlabel=stuff,
xticklabels={,10,9,8,7,6}
]

\end{axis}

% draw dashed lines from rectangle in first axis to corners of second
\draw [dashed] (c1) -- (ax2.south west);
\draw [dashed] (c2) -- (ax2.north west);
\end{tikzpicture}
\end{document}


text:
Q: Display an image on a Leaflet map using geojson attributes I have a geojson file "test.geojson" which contains image metadata for multiple images, including image url (as browseUrl) and image bounds (as imageBounds).
What I want to do is to display a corresponding image on my leaflet map by clicking on it's shape using ImageOverlay. Here is my code:
$.getJSON("test.geojson", function (geojson) {
    var geojsonLayer = new L.GeoJSON(geojson, {
        onEachFeature: function (feature, layer) {
            layer.on('click', function (feature) {
                L.imageOverlay(feature.properties.browseurl, feature.properties.imageBounds).addTo(map)
            })
        }
    }).addTo(map);
});

Unfortunatelly I get Uncaught TypeError: Cannot read property 'browseurl' of undefined when I click on a feature.

A: This appears to have been a bug at some point, unsure if resolved Uncaught TypeError: Cannot read property 'call' of undefined #555
A user does recommend using this as a possible workaround:

Can work around this by adding an empty function before creating the draw control:
  L.EditToolbar.Edit.prototype._editStyle = function() {};


text:
Q: Win32 App flickering when attempting to redraw. Any suggestions? I am working on a Tetris game and need to draw it in a WinAPI window. I draw the board using FillRect() function and clear the screen with a self-defined function that also uses FillRect() to clear the screen. It works great but the flickering is killing me! I have tried everything in my power. I tried to repaint the window in the WM_PAINT message but it poses another problem, it doesn't paint the board that it did before. I tried to paint my board again with the same procedure I used to paint the window but can't figure out how to do it, I passed the RECT structure with self-defined co-ordinates to the paint function but all it shows is a blank screen. Any suggestions would be much appreciated. Do tell me if this question needs any more clarification.

A: Sleep() is not specific to console. It's just the standard windows API to suspend the execution of the current thread for a given amount of time.
You should probably look into Windows Timers. Another viable approach, and often more useful for low latency applications like games, is to simply measure time at each iteration of the event loop and advance the game by that. You should use High Resolution Time Stamps for this, as regular system wall clock time may jump if the system clock gets adjusted from Internet network time; also wall clock time has some noticeable jitter.


text:
Q: When to use double braces in Laravel? I want to know when to use {{}} and when {!!!!} in Laravel? I know that it is an approach to prevent XSS but I have seen that all developers use {{}} for even the image address, stylesheet address, script address and so on while as I know XSS is something that can be done with malicious user INPUT not the one that is static and is set by developer. Am I right?
Thanks

A: From Laravel docs:

By default, Blade {{ }} statements are automatically sent through PHP's htmlentities function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:

Hello, {!! $name !!}.

A: I always use this thumb rule: Unless you need to output rendered HTML, use {{ }}. Else, use {!! !!}

A: You are absolutely right. if you want to escape the user input data then use {{}}, it is just like htmlentities function and if you don't want to escape the data then you can use {!!!!}.


text:
Q: OpenGL Shadow Map Mobile Version Doesn't work Summary
I have a problem porting my OpenGL 3.3 ("desktop") based game engine to OpenGL ES 3.2 ("mobile"). While everything works perfectly on the desktop, on mobile everything works but shadow maps.
My question is very simple: can someone spot a problem in the code I shared, or point me in the right derection?
Context

*

*All my engine code is written in C

*Apart from the application layer (I use glfw on desktop and glfm on mobile) the code base is identical: the exact same code is compiled for desktop and for mobile.

*The shaders - apart from injected headers like #version and precision defaults - are also identical across platforms

*The shadow map system in my engine is based on the tutorial found here: https://learnopengl.com/Advanced-Lighting/Shadows/Point-Shadows

*I am using an NVIDIA GTX 1080 for desktop for development, have tested with other NVIDIA PC's as well

*I am using a brand new ASUS ROG II Phone and an old LG G5 for testing, both run Android 9, both support OpenGL ES 3.2 according to the CPU-Z app, and both show the exact same flawed results.

Screenshots
My very simple light test level is rendered correctly on desktop. There is a yellow (invisible) light to the right of the column in the middle, so the shadow should be cast to the left as shown in the following desktop screenshot:

But it's very wrong on mobile:

As you can see the shadow on mobile is "just wrong". It's supposed to be on the left like on the desktop, but in stead it goes in the wrong direction, and looks "chopped off".
My own thoughts and actions

*

*I've taken great care to make sure that all my calls are available on OpenGL ES 3.2 just like they are on OpenGL 3.3 Core

*I've taken great care making sure that there are no problems with the OpenGL calls: I am using glDebugMessageCallback and there are no errors being reported at any time

*Since it "just works" on desktop, I feel like the math behind it isn't wrong

*My engine support caching of shadow maps for far away light as a performance optimization, but disabling this had no effect, so it's not causing the problem.

(Hopefully) relevant code
Shadow map setup in C
The code that creates the CUBE MAP textures to hold the shadows:
static GLuint r_createShadowmapTexture() {
    GLuint tex;
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_CUBE_MAP, tex);
    for (unsigned int i = 0; i < 6; ++i)
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT32F, r_shadowSize, r_shadowSize, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_FUNC, GL_GREATER);
    return tex;
}

The code that sets up the framebuffer for the shadow map:
glGenFramebuffers(1, &r_shadowDepthMapFBO);
glBindFramebuffer(GL_FRAMEBUFFER, r_shadowDepthMapFBO);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);

The code that renders the shadow map:
static struct {
    vec3 centerOffset, up;
} const g_shadowMapTransforms[6] = {
    { {1.0f, 0.0f, 0.0f}, {0.0f, -1.0f, 0.0f} },
    { {-1.0f, 0.0f, 0.0f}, {0.0f, -1.0f, 0.0f} },
    { {0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 1.0f} },
    { {0.0f, -1.0f, 0.0f}, {0.0f, 0.0f, -1.0f} },
    { {0.0f, 0.0f, 1.0f}, {0.0f, -1.0f, 0.0f} },
    { {0.0f, 0.0f, -1.0f}, {0.0f, -1.0f, 0.0f} },
};

static void r_shadowMapPass(const point_light_t* light, GLuint cubemapTexture) {
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

    glDepthMask(GL_TRUE);

    glBindFramebuffer(GL_FRAMEBUFFER, r_shadowDepthMapFBO);
    glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, cubemapTexture, 0);

    const float farPlane = min(r_far, light->radius);
    mat4x4 shadowProj;
    mat4x4_perspective(shadowProj, (float)M_PI_2, 1.0f, r_near, farPlane);
    mat4x4 shadowVP[6];
    for (int i = 0; i < 6; ++i) {
        vec3 center;
        vec3_add(center, light->origin, g_shadowMapTransforms[i].centerOffset);
        mat4x4 view;
        mat4x4_look_at(view, (float*)light->origin, center, (float*)g_shadowMapTransforms[i].up);
        mat4x4_mul(shadowVP[i], shadowProj, view);
    }

    rtech_shadowmap_enable();
    rtech_shadowmap_setLightPos((float*)light->origin);
    rtech_shadowmap_setFarPlane(farPlane);
    rtech_shadowmap_setShadowMatrices(shadowVP);
    render_entity_t* re = r_entities;

    glClear(GL_DEPTH_BUFFER_BIT);
    for (uint32_t i = 0; i < r_numEntities; ++i, ++re) {
        if (!re->castsShadow)
            continue;
        rtech_shadowmap_setModelMatrix(re->m);
        if (re->hasSolid) {
            const render_solids_t* const rs = r_solids + re->index;
            for (uint32_t j = 0; j < rs->count; ++j) {
                const uint32_t ao = rs->offset + j;
                r_renderBlock(ao, rs, j);
            }
        } else {
            render_model_t* const rm = &r_models[re->index];
            for (uint32_t j = 0; j < rm->count; ++j)
                r_renderArrayObject(rm->arrayObjects[j], rm->numIndices[j]);
        }
    }

    glDepthMask(GL_FALSE);
}

On desktop I prefix the following to ALL shaders (vertex, geometry and fragment):
#version 330 core

On mobile I prefix the following to ALL shaders:
#version 320 es
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp samplerCubeShadow;

The shadowmap vertex shader:
layout (location = 0) in vec3 aPos;

uniform mat4 gModel;

void main()
{
    gl_Position = gModel * vec4(aPos, 1.0);
}

The shadowmap geometry shader:

layout (triangles) in;
layout (triangle_strip, max_vertices=18) out;

uniform mat4 gShadowMatrices[6];

out vec4 FragPos; // FragPos from GS (output per emitvertex)

void main()
{
    for(int face = 0; face < 6; ++face)
    {
        gl_Layer = face; // built-in variable that specifies to which face we render.
        for(int i = 0; i < 3; ++i) // for each triangle's vertices
        {
            FragPos = gl_in[i].gl_Position;
            gl_Position = gShadowMatrices[face] * FragPos;
            EmitVertex();
        }
        EndPrimitive();
    }
}

The shadowmap fragment shader:

in vec4 FragPos;

uniform vec3 gLightPos;
uniform float gFarPlane;

void main()
{
    // get distance between fragment and light source
    float lightDistance = length(FragPos.xyz - gLightPos);

    // map to [0;1] range by dividing by gFarPlane
    lightDistance = lightDistance / gFarPlane;

    // write this as modified depth
    gl_FragDepth = lightDistance;
}

An extract from the point light pass that actually uses the shadow map:

...
uniform samplerCubeShadow gShadowCubeMap;
uniform float gFarPlane;
...

float ShadowCalcSinglePass(vec3 fragPos, vec3 lightPos) {
    vec3 fragToLight = fragPos - lightPos;
    float currentDepth = (length(fragToLight) - (0.005 * gFarPlane)) / gFarPlane;
    return texture(gShadowCubeMap, vec4(fragToLight, currentDepth));
}

I am aware this is a pretty open ended question, and a lot of code is involved. I am trying to supply the necessary relevant information, I can share more if required or requested!
Update 1
As per @MichaelKenzel's suggestion, I tried rendering the shadow maps to the screen. This worked perfectly for desktop as can be seen below. On mobile however, this showed an "all red" shadow maps, which (since my shader does 1.0 - sample) that the texture() function is returning 0 for every pixel. However, as can be seen on the "wrong" image above, there IS shadow somewhere, so this seems to be a problem with reading from the depth buffer in this fashion.
NOTE: the image below is from a different test level than the ones above, one with more complex shadows

in vec2 TexCoord0;

uniform samplerCube gTexture;
uniform int gSide;

out vec4 FragColor;

void main()
{
    vec3 vec;
    switch (gSide) {
    case 0:     vec = vec3(1.0, TexCoord0.xy); break;
    case 1:     vec = vec3(-1.0, TexCoord0.xy); break;
    case 2:     vec = vec3(TexCoord0.x, 1.0, TexCoord0.y); break;
    case 3:     vec = vec3(TexCoord0.x, -1.0, TexCoord0.y); break;
    case 4:     vec = vec3(TexCoord0.xy, 1.0); break;
    case 5:     vec = vec3(TexCoord0.xy, -1.0); break;
    default:    vec = vec3(1.0, 0.0, 0.0); break;
    }

    FragColor = vec4(vec3(1.0, 0.0, 0.0) * (1.0 - texture(gTexture, vec).r), /*alpha*/ 1.0);
}

Code that renders the shadow maps debug quads:
void r_debugPassShadowMap2() {
    if (!r_shadowmapDebug.initialized) {
        r_shadowmapDebug.initialized = true;

        const float margin = 16;
        const float mapWidth = (r_windowWidth - (margin * 7.f)) / 6.f;
        mat4x4 t, s;
        mat4x4_translate(t, 1, 1, 0); // quad verts range from -1x-1x0 to 1x1x0
        mat4x4_identity(s);
        s[0][0] = s[1][1] = s[2][2] = mapWidth / 2;
        mat4x4 m;
        mat4x4_mul(m, s, t);

        mat4x4 p;
        mat4x4_ortho(p, 0, (float)r_windowWidth, (float)r_windowHeight, 0, -1, 1);

        for (uint32_t i = 0; i < 6; ++i) {
            mat4x4 v;
            mat4x4_translate(v, margin + (margin + mapWidth) * i, margin, 0);
            mat4x4 mv;
            mat4x4_mul(mv, v, m);
            mat4x4_mul(r_shadowmapDebug.sideWVP[i], p, mv);
        }
    }

    glDisable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);
    glDisable(GL_BLEND);
    rtech_shadowmapdebug_enable();
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_CUBE_MAP, r_shadowmapDebug.texture);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_NONE);
    for (uint32_t i = 0; i < 6; ++i) {
        rtech_shadowmapdebug_setWVP(r_shadowmapDebug.sideWVP[i]);
        rtech_shadowmapdebug_setSide(i);
        glBindVertexArray(r_quadAO);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, NULL);
    }
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
}

Update 2 - First partial fix
Thanks to @MorrisonChang's link, I tried something different and it made a huge difference: I had set GL_TEXTURE_MAG_FILTER and GL_TEXTURE_MIN_FILTER to GL_LINEAR for the shadow map texture. When I changed it to GL_NEAREST I suddenly got some more results on mobile! However, as the image below clearly shows, for some reason it renders only to ONE face, instead of all 6! But at least I am a step further!

A: I found the answer, and (to me) it is baffling, but I found out it is according to specs. I made it work instantly after I changed my geometry shader from this:
void main()
{
    for(int face = 0; face < 6; ++face)
    {
        gl_Layer = face; // built-in variable that specifies to which face we render.
        for(int i = 0; i < 3; ++i) // for each triangle's vertices
        {
            FragPos = gl_in[i].gl_Position;
            gl_Position = gShadowMatrices[face] * FragPos;
            EmitVertex();
        }
        EndPrimitive();
    }
}

to this:
void emitFace(mat4 m) {
    for(int i = 0; i < 3; ++i)
    {
        FragPos = gl_in[i].gl_Position;
        gl_Position = m * FragPos;
        EmitVertex();
    }
    EndPrimitive();
}

void main()
{
    gl_Layer = 0;
    emitFace(gShadowMatrices[0]);

    gl_Layer = 1;
    emitFace(gShadowMatrices[1]);

    gl_Layer = 2;
    emitFace(gShadowMatrices[2]);

    gl_Layer = 3;
    emitFace(gShadowMatrices[3]);

    gl_Layer = 4;
    emitFace(gShadowMatrices[4]);

    gl_Layer = 5;
    emitFace(gShadowMatrices[5]);
}

Apparently, assigning to gl_Layer through a for loop variable is something that doesn't work in OpenGL ES!
On this page https://www.khronos.org/registry/OpenGL-Refpages/es3/html/gl_Layer.xhtml it says

If a shader statically assigns a value to gl_Layer, layered rendering mode is enabled.

It also says:

If the geometry stage makes no static assignment to gl_Layer, the input gl_Layer in the fragment stage will be zero.

But it doesn't say "you are not supposed to assign a non static value to gl_Layer ever", and the compiler also didn't warn at all!
In OpenGL Core the spec says the exact same thing actually: https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/gl_Layer.xhtml
However, my NVIDIA driver supports dynamic assignments to gl_Layer anyway, and because it does that, I never realized it was wrong...


text:
Q: How to add new input row to table on click? below is a component of my React project. The basis of the component is a table that displays initially one input row.
import React, { Component } from "react";
import { Navbar, Table, Form } from "react-bootstrap";
import Nav from "./Nav";
import "../client/scss/import.scss";

// import Logo from "./images/logo.svg";

class Import extends Component {
  state = {
    collapseID: ""
  };

  render() {
    return (

Import New Schedule

                  Queue
                  Start Date
                  End Date
                  Day of Week
                  Time Start
                  Time End
                  Capacity

                    <Form.Control as="select">
                      <option>Veteran Affairs</option>
                      <option>Older Australians</option>
                      <option>Disability Sickness Carers</option>
                      <option>Report Employment Income</option>
                    </Form.Control>

                    <input
                      className="form-control"
                      type="date"
                      value="2011-08-19"
                      id="example-date-input"
                    />

                    <input
                      className="form-control"
                      type="date"
                      value="2011-08-19"
                      id="example-date-input"
                    />

                    <Form.Control as="select">
                      <option>Monday</option>
                      <option>Tuesday</option>
                      <option>Wednesday</option>
                      <option>Thursday</option>
                      <option>Friday</option>
                      <option>Saturday</option>
                      <option>Sunday</option>
                    </Form.Control>

                    <input
                      className="form-control"
                      type="time"
                      value="13:45:00"
                      id="example-time-input"
                    />

                    <input
                      className="form-control"
                      type="time"
                      value="13:45:00"
                      id="example-time-input"
                    />

                    <input
                      className="form-control"
                      type="number"
                      value="0"
                      id="example-number-input"
                    />

            <button id="addRow">+ Add</button>

    );
  }
}

export default Import;

Towards the bottom you will see the <button id="addRow">+ Add</button> element. Every time this button is clicked, I would like a new row to be appended to the existing table so that additional input fields are visible. Should I be using jQuery to implement this? Could someone please assist in guiding me how to do this? Below is a screenshot how this currently appears on my browser if that helps:

A: If you are looking into a full fledged solution, you can use the below solution.
Stackblitz snippet can be found Here
Implementation
We initially created a form structure
  const initialForm = {
      id:1,
      queueType:'',
      startDate:'2011-08-19',
      endDate:'2011-08-19',
      week:'',
      startTime:'13:45:00',
      endTime:'13:45:00',
      capacity:0
    }

On each time the Add is pressed, a copy of the form structure is pushed to the formArray and this form array is iterated.
The setFormValue() function will update the formArray.
 setFormValue = (e, index)=>{
    let {formArray} = this.state;
    formArray[index][e.target.name] = e.target.value;
    this.setState({
      formArray
    })
  }

Update form is rendered in dom ( To see realtime update ), we used

{JSON.stringify(this.state.formArray)}

The component is implemented as class component.
import React, { Component } from "react";
import { Navbar, Table, Form } from "react-bootstrap";

const initialForm = {
  id:1,
  queueType:'',
  startDate:'2011-08-19',
  endDate:'2011-08-19',
  week:'',
  startTime:'13:45:00',
  endTime:'13:45:00',
  capacity:0
}
export default class Hello extends Component {
  constructor(props){
    super(props);
    this.state = {
      collapseID: "",
      formArray:[
        {
          ...initialForm
        }
      ]
    };
  this.addNewForm = this.addNewForm.bind(this);
  }

  addNewForm = ()=>{
    let newForm = {...initialForm};
    newForm.id = this.state.formArray[this.state.formArray.length -1].id +1;
    this.setState(prevState =>{
      return {
        ...prevState,
        formArray:[...prevState.formArray, newForm]
      }
    })
  }

  setFormValue = (e, index)=>{
    let {formArray} = this.state;
    formArray[index][e.target.name] = e.target.value;
    this.setState({
      formArray
    })
  }

  removeForm=(id)=>{
    const formArray = this.state.formArray.filter(form => form.id != id)
    this.setState({formArray})
  }
  render() {
    return (

Import New Schedule

                  Queue
                  Start Date
                  End Date
                  Day of Week
                  Time Start
                  Time End
                  Capacity

              {this.state.formArray.map((form,index)=>(

                    <select name="queueType"
                    defaultValue={form.queueType}
                    onChange={()=>this.setFormValue(event,index)}>
                      <option>Veteran Affairs</option>
                      <option>Older Australians</option>
                      <option>Disability Sickness Carers</option>
                      <option>Report Employment Income</option>
                    </select>

                    <input
                      className="form-control"
                      type="date"
                      name="startDate"
                      defaultValue={form.startDate}
                      onChange={()=>this.setFormValue(event,index)}
                      id="example-date-input"
                    />

                    <input
                      className="form-control"
                      type="date"
                      name="endDate"
                      defaultValue={form.endDate}
                      onChange={()=>this.setFormValue(event,index)}
                      id="example-date-input"
                    />

                    <select name="week" defaultValue={form.week}
                      onChange={()=>this.setFormValue(event,index)}>
                      <option>Monday</option>
                      <option>Tuesday</option>
                      <option>Wednesday</option>
                      <option>Thursday</option>
                      <option>Friday</option>
                      <option>Saturday</option>
                      <option>Sunday</option>
                    </select>

                    <input
                      className="form-control"
                      type="time"
                      name="startTime"
                      defaultValue={form.startTime}
                      onChange={()=>this.setFormValue(event,index)}
                      id="example-time-input"
                    />

                    <input
                      className="form-control"
                      type="time"
                      name="endTime"
                      defaultValue={form.endTime}
                      onChange={()=>this.setFormValue(event,index)}
                      id="example-time-input"
                    />

                    <input
                      className="form-control"
                      type="number"
                      defaultValue={form.capacity}
                      onChange={()=>this.setFormValue(event,index)}
                      name="capacity"
                      id="example-number-input"
                    />

                    <button type="button" onClick={()=>this.removeForm(form.id)}>- Remove</button>

                ))}

            <button id="addRow" onClick={this.addNewForm}>+ Add</button>

        {JSON.stringify(this.state.formArray)}

    );
  }
}

A: Make your table row into a seperate component. Lets call it a Row
// Create a state for the amount of rows you want to view
const [rowCount,setRowCount] = useState(1);

Do the following loop in the render method.
const rowArray = [];

for (let i = 0; i < rowCount; i++) {
  rowArray.push(<Row>)
}

Insert the rowArray variable insider the return of the render method.
{rowArray}

Your final code should look something like below.
class Import extends Component {
  state = {
    collapseID: "",
    rowCount: 1,
  };

  _addRow = () => {
     const { rowCount } = this.state;
     this.setState(rowCount + 1);
   }

  render() {
     const { rowCount } = this.state;
    const rowArray = [];

    for (let i = 0; i < rowCount; i++) {
      rowArray.push(<Row>)
    }

    return (

Import New Schedule

                  Queue
                  Start Date
                  End Date
                  Day of Week
                  Time Start
                  Time End
                  Capacity

               {rowArray}

            <button id="addRow" onClick={_addRow}>+ Add</button>

    );
  }
}

export default Import;


text:
Q: Android number format is wrong somehow, instead of 3.5 I get 3.499999999, why? I store some data in a database and I read those data with a cursor. All the data are 56.45 , 3.04, 0.03 type, so two numbers after the decimal point. Now I would like to sum them but it doesnt seem to be easy... I get those number with c.getDouble(3) then I add it to the sum variable like:
sum+= c.getDouble(4) * multi

multi is an integer between 1 and 100.  Now my problem is that, after getting the sum variable I get a number like: 59.51999999999999999. I do not post a code, but there is no conversion except a string.valueOf for making the number appear on my widget. So anybody experienced this? As I count it should be 59.52, but instead I get that number with 99999... Why is that happening?  (funny thing that with a Math.round() does not work, I get 59.0 even if I set (sum)*100 / 100..
Thanks in advance!

A: Your numbers are represented in decimal to you, but binary to a computer.
In both decimal and binary, some fractions cannot be represented precisely.
For example 1/3 cannot be represented precisely in decimal. You can merely approximate it with something like 0.3333333333.  But then if you try to do 3 * 0.3333333333, you end up with 0.9999999999 instead of 1.0000000000.
In binary, you have the same problem, but with different fractions.
So, sometimes when you convert from decimal to binary and back again (which is what the computer basically must do to do floating point arithmetic for you), you get small errors in precision even though all the numbers are perfectly precise in decimal. When the computer uses their binary near-equivalents, approximations are introduced and they result in small errors.
This is actually a very common issue in programming. For a lot more detail, see What Every Computer Scientist Should Know About Floating-Point Arithmetic.

A: Other approach, you can define your sum variable as double and then you can set NumberFormat for your sum variable.
Example:
double sum = 21.2015;
NumberFormat formatter = new DecimalFormat("#.##");
formatter.format(sum);


text:
Q: Are two proofs better than one? I have proved a simple conjecture two ways, for an essay I need to do for my highschool maths. How do I justify in my essay why I have included two proofs instead of one. Is there any good reason, to show that more than one proof is beneficial?

A: Sometimes that happens. For instance, it may be the the case that one proof is a smart but hard to find proof, whereas the other one, although longer and not particulary bright, is the natural approach to the problem.

A: Well, if you assume the pedagogical notion that the function of a proof is to convince the general reader of correctness of the result; then there being multiple proofs in general is good as it is more convincing.
On the other hand, the function of your writing should be considerate towards the reader's needs. How will the 2 proofs benefit them?
Perhaps if you must mention both proofs, then either confine one to an appendix or mention one in the minutest detail.


text:
Q: phpMyAdmin allow remote users I need to modify the file /etc/httpd/conf.d/phpMyAdmin.conf
in order to allow remote users (not only localhost) to login
# phpMyAdmin - Web based MySQL browser written in php
#
# Allows only localhost by default
#
# But allowing phpMyAdmin to anyone other than localhost should be considered
# dangerous unless properly secured by SSL

Alias /phpMyAdmin /usr/share/phpMyAdmin
Alias /phpmyadmin /usr/share/phpMyAdmin

<Directory /usr/share/phpMyAdmin/>
   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
       Require ip 127.0.0.1
       Require ip ::1
     </RequireAny>
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     Deny from All
     Allow from 127.0.0.1
     Allow from ::1
   </IfModule>
</Directory>

<Directory /usr/share/phpMyAdmin/setup/>
   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
       Require ip 127.0.0.1
       Require ip ::1
     </RequireAny>
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     Deny from All
     Allow from 127.0.0.1
     Allow from ::1
   </IfModule>
</Directory>

# These directories do not require access over HTTP - taken from the original
# phpMyAdmin upstream tarball
#
<Directory /usr/share/phpMyAdmin/libraries/>
    Order Deny,Allow
    Deny from All
    Allow from None
</Directory>

<Directory /usr/share/phpMyAdmin/setup/lib/>
    Order Deny,Allow
    Deny from All
    Allow from None
</Directory>

<Directory /usr/share/phpMyAdmin/setup/frames/>
    Order Deny,Allow
    Deny from All
    Allow from None
</Directory>

# This configuration prevents mod_security at phpMyAdmin directories from
# filtering SQL etc.  This may break your mod_security implementation.
#
#<IfModule mod_security.c>
#    <Directory /usr/share/phpMyAdmin/>
#        SecRuleInheritance Off
#    </Directory>
#</IfModule>

A: The other answers so far seem to advocate the complete replacement of the <Directory/> block, this is not needed and may remove extra settings like the 'AddDefaultCharset UTF-8' now included.
Update 2021
The config file is now simplified so just needs a single line adding:
<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   Require local
   # ADD following line:
   Require all granted
</Directory>

Original Answer
To allow remote access you need to add 1 line to the 2.4 config block or change 2 lines in the 2.2 (depending on your apache version):
<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
       # ADD following line:
       Require all granted
       Require ip 127.0.0.1
       Require ip ::1
     </RequireAny>
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     # CHANGE following 2 lines:
     Order Allow,Deny
     Allow from All
     Allow from 127.0.0.1
     Allow from ::1
   </IfModule>
</Directory>

A: Replace the contents of the first <directory> tag.
Remove:
<Directory /usr/share/phpMyAdmin/>
 <IfModule mod_authz_core.c>
  # Apache 2.4
  <RequireAny>
    Require ip 127.0.0.1
    Require ip ::1
  </RequireAny>
 </IfModule>
 <IfModule !mod_authz_core.c>
  # Apache 2.2
  Order Deny,Allow
  Deny from All
  Allow from 127.0.0.1
  Allow from ::1
 </IfModule>
</Directory>

And place this instead:
<Directory /usr/share/phpMyAdmin/>
 Order allow,deny
 Allow from all
</Directory>

Don't forget to restart Apache afterwards.

A: Try this
Replace
<Directory /usr/share/phpMyAdmin/>
    <IfModule mod_authz_core.c>
        # Apache 2.4
        <RequireAny>
            Require ip 127.0.0.1
            Require ip ::1
        </RequireAny>
    </IfModule>
    <IfModule !mod_authz_core.c>
        # Apache 2.2
        Order Deny,Allow
        Deny from All
        Allow from 127.0.0.1
        Allow from ::1
    </IfModule>
</Directory>

With this:
<Directory "/usr/share/phpMyAdmin/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order Allow,Deny
    Allow from all
</Directory>

Add the following line for ease of access:
Alias /phpmyadmin /usr/share/phpMyAdmin

A: My setup was a little different using XAMPP. in httpd-xampp.conf I had to make the following change.
Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
    AllowOverride AuthConfig
    Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

change to
Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
    AllowOverride AuthConfig
    #makes it so I can config the database from anywhere
    #change the line below
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

I need to state that I'm brand new at this so I'm just hacking around but this is how I got it working.

A: use this,it got fixed for me, over centOS 7
<Directory /usr/share/phpMyAdmin/>
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted
</Directory>

A: Just comment all lines in first Directory. Or you can remove these lines, but better to keep in case later you want to add some restrictions, you will uncomment.
#<Directory /usr/share/phpMyAdmin/>
#   <IfModule mod_authz_core.c>
#     # Apache 2.4
#     <RequireAny>
#       Require ip 127.0.0.1
#       Require ip ::1
#     </RequireAny>
#   </IfModule>
#   <IfModule !mod_authz_core.c>
#     # Apache 2.2
#     Order Deny,Allow
#     Deny from All
#     Allow from 127.0.0.1
#     Allow from ::1
#   </IfModule>
#</Directory>

A: My answer is based on getting a 403 error although I had all of the Apache settings mentioned in the other answers correct.
It was a fresh Centos 7 server and it turned out that the issue was not the Apache  settings but the fact that the PhpMyAdmin did not serve at all. The solution was to install php and add the php directive to apache.conf:

*

*sudo yum install php php-mysql

*vim /etc/httpd/conf/httpd.conf
add something like

*DirectoryIndex index.php index.phtml index.html index.htm
to serve php index files also
and then restart apache

Don't forget to restart Apache server to take effect
 - systemctl restart httpd.service
I hope this helps. I first thought my issue was Apache directives, so I post my solution here.


text:
Q: About $H^0(\mathcal{O}_X(-k))$ where $X$ is a curve on $\mathbb{P}^3$ $X$ is a locally complete intersection curve with each connected component X' satisfying $H^0(X',\mathcal{O}_{X'})=k$ on $\mathbb{P}^3_k$. There is an exact sequence for every $k\geq1$
$0 \to I_X(-k) \to \mathcal{O}_{\mathbb{P}^3}(-k) \to \mathcal{O}_X(-k) \to 0$
I need to prove that $H^1(I_X(-k))=0$ for $k\geq1$, but looking at the exact sequence it is enough to show $H^0(\mathcal{O}_X (-k))=0$ since $H^0(\mathcal{O}_{\mathbb{P}^3}(-k))=H^1(\mathcal{O}_{\mathbb{P}^3}(-k))=0$.
Any suggestions on how to think about the global sections of $\mathcal{O}_X (-k)$? or on how to compute $H^1(I_X(-k))$? (at first I tried to look at the extensions)


text:
Q: Finding a result vector from 2 vectors without cross product If I have 2 lines with its symmetric equations I can get the vectors U and V of each line, and with a cross product I can get the vector R; but how can I get the vector R without a cross product?

A: I'm not exactly certain I've understood your question correctly, but here is an attempt; I'll interpret the problem as follows: let $U = (U_1, U_2, U_3)$ and $V = (V_1, V_2, V_3)$ be vectors in $\mathbb{R}^3$. Find a vector $R = (R_1, R_2, R_3)$ that is perpendicular to both $U$ and $V$. This is the same as requiring that $U\cdot R = V \cdot R = 0$, or equivalently, that the vector $R$ solves the following linear system:
\begin{align*} U_1 R_1 + U_2 R_2 + U_3 R_3 &= 0 \\
V_1 R_1 + V_2 R_2 + V_3 R_3 & = 0
\end{align*}
Plug in the vectors $U$ and $V$ and solve using elimination for the unknowns $R_1$, $R_2$ and $R_3$. The system has more unknowns than equations, and hence it always has a nontrivial solution (in fact, infinitely many). If the vector $U$ is not a scalar multiple of $V$ (in other words, if the vectors are linearly independent), the solution space is $1$-dimensional, consisting of all scalar multiples of the cross product.
If, however, you require the actual cross product, rather than just a vector perpendicular to the ones given, there are additional complications (you need to determine the length and direction), and my guess is that it would be easier to just compute the cross product directly.


text:
Q: Filter Collection with String Descriptor Say I have List of objects that has some properties:
public class Class1
{
    public string s1 {get; set;}
    public string s2 {get; set;}
    public string s3 {get; set;}
}

I would like to filter this List<Class1> with a string, which let's say is in the format:
"s1=Hello,s3=Goodbye"

(perhaps via URL)
Of course I could parse the string the usual way, then cycle through through the filter items, compare to property names via reflection, etc.
But I was wondering if any one knew of a library or class that does something like this already? It's all rather tedious, and could be quite slow if not done properly, especially for a class with many properties. The problem sounds generic enough that I'm sure others have dealt with before, just wondering if anyone knows of any elegant solution?

A: Something like this perhaps (by using Linq and more specifically the Where clause):
var myList = new List<Class1> { new Class1 { s1 = "Hello", s3 = "Goodbye" }, new Class1 { s1 = "Goodbye", s3 = "Hello" } };

var filteredList = myList.Where(i => i.s1.Equals("Hello") && i.s3.Equals("Goodbye")).ToList();

filteredList will now contain only the first element from myList.


text:
Q: ...code... ?> vs
Possible Duplicate:
How to enable PHP short tags?

I am doing some JavaScript work on a Wordpress based legacy side. I am trying to get the page to run on my dev machine (OS X Lion), but am encountering a problem with code in the template not being interpreted. The template contains some code tags that look like <? echo($subpage_title); ?>. Those don't get interpreted. If I replace that with <?php echo($subpage_title); ?>, it gets interpreted correctly. I don't really want to replace that everywhere and it obviously works on the production server. Is there any server setting I have to change for this to work?
This is probably a silly question, but I have practically no PHP experience and Google is not really helpful when looking for symbols.
Thank you very much for any help!

A: Enable the setting called short_open_tag in the php.ini file.

A: This is controlled by the PHP short_open_tag configuration value. Turn that on for your dev machine and you should be good.

A: The short_open_tag configuration setting should be a good start.

A: Check short_open_tag PHP.INI directive.


text:
Q: pandas loc to check if value contains any of several words or a string I have a pandas DataFrame with a column containing strings.
(I take the example from Check if string is in a pandas dataframe)
import pandas as pd

BabyDataSet = [
    ('Bob and martin and Andrew', 968),
    ('Jessica and julia and anthony', 155),
    ('Mary and john', 77),
    ('John', 578),
    ('Mel and diana', 973),
    ('martin bob diana and Andrew', 968)
]

a = pd.DataFrame(data=BabyDataSet, columns=['Names', 'Births'])

                           Names  Births
0      Bob and martin and Andrew     968
1  Jessica and julia and anthony     155
2                  Mary and john      77
3                           John     578
4                  Mel and diana     973
5    martin bob diana and Andrew     968

Giving a string like "martin andrew bob", I would like to filter the DataFrame to get the subset with the rows containing in the name all the words (in any order and case) of the string.
Is there a better way that using a for loop adding the masks as lists of booleans? Because this solution seems cumbersome to me.

A: This is my suggestion:
my_str = 'martin andrew bob'

a[a['Names'].str.lower()
            .str.split()
            .apply(set(my_str.lower().split()).issubset)
 ].reset_index(drop=True)

Output:
                          Names  Births
0     Bob and martin and Andrew     968
1   martin bob diana and Andrew     968

I'm adding lower() function to my_str, but if you're sure that string is always given in lowercase you can skip it.


text:
Q: UseBasicParsing doesnt return HTML form I am working on creating a form login monitor for a webpage. Here is the code:
$loginbase = '<input omitted>'
$loginURL = $loginbase + '<input omitted>'
$r = Invoke-WebRequest -Uri ($loginURL + 'logonform.jsp')
return $r;

$form = $r.Forms[0];

return $form

$form.Fields['aps'] = '<input omitted>';
$form.Fields['usr'] = '<input omitted>';
$form.Fields['pwd'] = '<input omitted>';

$r = Invoke-WebRequest -Uri ($loginURL + $form.Action) -Method POST -Body $form.Fields;

if ($r.Content -match 'setup()') {

    if ($r.StatusCode -eq 200) {

        Write-Host 'Message:' $r.StatusDescription;
        Write-Host 'Statistic:' $r.StatusCode;
        Exit 0;
    }

    Write-Host 'Message:' $r.StatusDescription;
    Write-Host 'Statistic:' $r.StatusCode;
    Exit 1;
}

Write-Host 'Message: Did not login';
Write-Host 'Statistic: 1';
Exit 1;

This works just fine outside of the monitoring platform, but when I put this script into the platform I get the following error:
Invoke-WebRequest : The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again.
At line:3 char:6
+ $r = Invoke-WebRequest -Uri ($loginURL + 'logonform.jsp')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [Invoke-WebRequest], NotSupportedException
+ FullyQualifiedErrorId : WebCmdletIEDomNotSupportedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Cannot index into a null array.
At line:5 char:1
+ $form = $r.Forms[0];
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray

Cannot index into a null array.
At line:7 char:1
+ $form.Fields['aps'] = '<input omitted>';
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray

Cannot index into a null array.
At line:8 char:1
+ $form.Fields['usr'] = '<input omitted>';
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray

Cannot index into a null array.
At line:9 char:1
+ $form.Fields['pwd'] = '<input omitted>';
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray

Invoke-WebRequest : The remote server returned an error: (404) Not Found.
At line:11 char:6
+ $r = Invoke-WebRequest -Uri ($loginURL + $form.Action) -Method POST -Body $form. ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Following the suggestion of the first error, I added '-UseBasicParsing' to my initial Invoke-WebRequest statement. When I run the script either inside or outside of the monitoring platform what occurs is that none of the forms or inputfields are pulled from the HTML. I get the following:
StatusCode        : 200
StatusDescription : OK
Content           : <!--
                    ©2010 - 2013 SAP AG or an SAP affiliate company.  All rights reserved.

                    SAP and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered...
RawContent        : HTTP/1.1 200 OK
                    Content-Length: 2561
                    Content-Type: text/html;charset=utf-8
                    Date: Tue, 11 Oct 2016 15:31:12 GMT
                    Expires: 0
                    Set-Cookie: JSESSIONID=DE3280200E764687D90E63E50A65452F; Path=/AdminTools...
Forms             :
Headers           : {[Content-Length, 2561], [Content-Type, text/html;charset=utf-8], [Date, Tue, 11 Oct 2016 15:31:12 GMT], [Expires, 0]...}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        :
RawContentLength  : 2561

Ive tried to find an alternate solution on both google and the support forums of our monitoring platform, but neither have turned much up outside of the standard tutorials of how to use Invoke-WebRequest.

A: The feature you're trying to use, which is HTML parsed into an object model, requires Internet Explorer to be available and initialized. -UseBasicParsing specifically doesn't do that parsing, for the situation where you don't need it, and where IE is not available (like on Server Core).
If you are not running server core, and IE is actually available, then the problem is likely this:

Internet Explorer's first-launch configuration is not complete.

In that case, just run IE for the first time and that should fix it.
If the script is being run as a service account, then make sure that you log in once with that account and initialize IE (it's per-user).


text:
Q: Duplicate the audio ByteBuffer in ExoPlayer I'm trying to process the audio buffer in the Android ExoPlayer. In the writeBuffer function of the DefaultAudioSink class, Audio data's coming in a ByteBuffer object. In my case, I want to get the values (as Byte[] if possible) from this ByteBuffer to process the datas before to create a new ByteBuffer and give it to the audioTrack.
I firstly tried to clone the original ByteBuffer in a new ByteBuffer, then send it to the audioTrack (as described in Deep copy duplicate() of Java's ByteBuffer ), to verify it is still working. But the result is an empty buffer for the destination AND the original one (as with this solution)
public static ByteBuffer clone(ByteBuffer original) {
    ByteBuffer clone = ByteBuffer.allocate(original.capacity());
    original.rewind();//copy from the beginning
    clone.put(original);
    original.rewind();
    clone.flip();
    return clone;
}

or something like accelerated audio (if I remove the rewind calls).
A simple
ByteBuffer newBuffer = buffer.duplicate();

has the same behavior.
I'm trying to understand why I can't get a working duplicated audio ByteBuffer, that I can transfer to the AudioTrack and hear the same sound.

A: Have you tried copying and wrapping the returned ByteBuffer's array?  i.e.
byte[] copy = Arrays.copyOf(original.array(), original.array().length)
return ByteBuffer.wrap(copy, 0, copy.length)


text:
Q: mustache template in Rails Views I'm trying to get a mustache template to render in a rails view.
Here's what I did:
**Added to my gemfile:**
 gem "stache"

Then in my view:
<% @notifications.each do |n| %>
    <%= render "notifications/notification_item", n.attributes.symbolize_keys   %>
<% end %>

<%= template_include_tag "notifications/notification_item" %>

My mustache template is app/views/notifications/_notification_item.html.mustache
I get the following errors:
undefined method `attributes' for #<Hash:0x0000010749add8>

Ideas what I'm doing wrong? Suggestions? Thanks


text:
Q: Locking the orientation in an iPad app (plist or UIViewController?) I'd like the app to work like it would be as if I locked the orientation manually.  I'm trying to find how I can lock the orientation for an app.  In the info.plist, I have this setting:
Supported interface orientations (iPad)
Item 0 Landscape (right home button)
Item 1 Landscape (left home button)

I thought that would be enough to keep my viewControllers from staying in landscape mode and not portrait.  But it does not.  Do I need to do
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
       return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

in ALL my viewControllers?  Thanks!

A: All though implementing shouldAutorotateToInterfaceOrientation in all your view controllers will work, it is probably not the fastest or most practical way of doing what you are trying to accomplish.
If any of your view controllers in your hierarchy do not conform to the orientation change, then iOS will stop trying to rotate them. What this means is that only your root view controller needs to have implemented shouldAutorotateToInterfaceOrientation with only landscape orientations. Each view controller pushed or added will conform to that function.

A: I have had to do this in several of my apps and it was required for several reasons.
In the end and after a lot of testing, we determined that the condition has to be set on the info.plist AND on every viewController.
So make sure it is set on the plist and that every shouldAutorotateToInterfaceOrientationonly returns yes for the allowed orientation.
This is because the plist will help you with allowed LAUNCH orientations, but your app could still rotate afterwards, specially when using modal views.
You can download one of my free apps that does thins on iPad: http://itunes.apple.com/mx/app/hoteles-city/id471505865?mt=8

A: Yes you do.
I have a different solution however. In every UIViewController, I use:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft){
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
    } else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
    } else {
        return NO;
    }
}


text:
Q: How to defer execution of injected services in mvc controllers Consider a situation where you have some controller that uses some service which is injected by some IOC container like autofac or ninject. Service is initialized each time a request hits that controller, even if it just wants to trigger simple action that only calls a view. The question here is how to defer initialization for a service for when it's really needed so I can save some resources. Should I use here Lazy? Or perhaps should I inject this services into method instead of controller?
Example:
public class SomeController : Controller
{
    private readonly ISomeService _service;

    public SomeController(ISomeService service)
    {
        this._service = service;
    }

    // action that completely doesn't need to initialize service
    public ActionResult Index()
    {
        return View();
    }
    // this action needs to initialize
    public ActionResult Save()
    {
        this._service.DoSomething();
        return View();
    }
}

A: Just a few thoughts!. The constructor of your class (controller in this case) should not do anything except store the dependencies, for which it has to resolve the dependencies when the controller is resolved.
When you use any DI framework the container need to upfront know the dependency hierarchy and their lifetime management scopes so that when requested by any component, the container can provide the resolved instance.
You could use faster DI container if you are worried about the performance aspect of it.
If the creation of your injected object is expensive (I tend to keep it simple, by not having to much logic in the initialization) then one thing to consider might be to have a Singleton or Per Request lifetime scope for the object (if its possible)

A: Yes, most decent IoC containers allow you to inject Lazy<T> and defer initialization until the lazy object is used. Usually this just works automatically if you change the type of the constructor parameter from T to Lazy<T>
Specifically, I believe this is built into autofac, and can be added to ninject using the module Ninject.Extensions.Factory


text:
Q: How do Web Components and the Shadow DOM prevent leaky CSS across components? In 2008 our team investigated GWT - a technology for writing web components for Javascript in Java which would compile down.
A new member of the team said:

You will have a problem with the CSS of the component and the page clashing with each other.

It turned out he was correct.
I was having a conversation with a friend today about Web Components. I asked him how you stop the CSS of the page and the components clashing with each other.
He said:

With Web Components and the Shadow DOM it is all under control. It solves the problem of leaky CSS.

My question is: How do Web Components and the Shadow DOM prevent leaky CSS across components?

A: Because Shadow DOM was designed precisely to solve problems met when developping Web Components, as stated by Google in the introduction to Shadow DOM:

Isolated DOM: A component's DOM is self-contained (e.g. document.querySelector() won't return nodes in the component's shadow DOM).
Scoped CSS: CSS defined inside shadow DOM is scoped to it. Style rules don't leak out and page styles don't bleed in.
Simplifies CSS - Scoped DOM means you can use simple CSS selectors, more generic id/class names, and not worry about naming conflicts.

It is achieved by CSS Scoping with the introduction of a new, separate DOM tree called the Shadow DOM, that will locally replace the initial DOM called the Light DOM.


text:
Q: Why isn't boost::filesystem header only? Out of intellectual curiosity, I was wondering why the boost::filesystem library had a compiled component, while in other cases no compiled components are necessary. What is in the compiled portion that can not be in a hpp?
What really confuses me is that on my computer I compile this portion anyway (before using the library), and I would thus expect it to be possible or even preferred to perform the same compilation I did in BJam every time I build my application.
Why is there the additional .so/.a file?

A: Some boost libraries are header-only and some other need to be built (system, filesystem, graph, mpi, serialization, etc); several boost libraries can be configured to be either header-only or separately built.
The advantages of separately built libs are quite obvious: your own project compiles faster and depends on less external code.
However, build complexity is the tradeoff.


text:
Q: Difference between times in PHP I have a temporary table in the database that contains:
 userid | time
--------|---------------------
 1      | 13-01-24 00:04:01
 1      | 13-01-24 00:04:04
 1      | 13-01-24 00:05:06
 2      | 13-01-24 00:06:06
 2      | 13-01-24 00:06:08

I would like to get an answer as follows:
1,  0 second
1,  3 second
1,  62 second
2,  60 second
2,  2 second

I've tried 'TIMEDIFF' scripts (max(time), min(time)), but it does not output what I want.  Please help, I'm using PHP.

A: MySQL solution:
SET @prev_time = null;
SELECT userid, IFNULL(timediff(`time`,@prev_time), 0) diff,
       @prev_time := `time`
FROM mytable
ORDER BY time

SQLFIDDLE

A: PHP Solution:
(The same @Barmar 's solution but in php)
<?php
$timearray = array("13-01-24 00:04:01", "13-01-24 00:04:04", "13-01-24 00:05:06", "13-01-24 00:06:06", "13-01-24 00:06:08");
$prevtimestamp = null;
foreach($timearray as $it) {
    $datetime = explode(" ", $it);
    $date = explode("-", $datetime[0]);
    $time = explode(":", $datetime[1]);
    $newtimestamp = mktime($time[0], $time[1], $time[2], $date[1], $date[0], $date[2]);
    if($prevtimestamp == null) $prevtimestamp = $newtimestamp;
    echo $newtimestamp - $prevtimestamp . " seconds";
    $prevtimestamp = $newtimestamp;
}
?>


text:
Q: pandas dataframe plot precision I've got a question that I haven't been able to find the answer to.
It's in regards to loading high precision csv file into pandas dataframe, and plotting.
Specifically, it appears that using pd.plot() rounds my df columns to a point where the data looks wrong when plotted.
Here is a look at the df data in question:
new_df[10:20]

index     Base      Base_L10  Base_L20  Base_L30
20070115  1.000000  1.000000  1.000000  1.000000
20070116  1.000000  1.000000  1.000000  1.000000
20070117  1.000000  1.000000  1.000000  1.000000
20070118  1.000000  1.000000  1.000000  1.000000
20070119  1.000843  1.000843  1.000843  1.000843
20070122  1.001520  1.001520  1.001520  1.001520
20070123  0.998745  0.998745  0.998745  0.998745
20070124  1.000558  1.000558  1.000558  1.000558
20070125  1.002821  1.002821  1.002821  1.002821
20070126  1.001801  1.001801  1.001801  1.001801

So that's the pandas version of a plot.
When using excel however, the plot looks like this:

Is there any good explanation/solution to this?
Thank you.
EDIT - Clarifying Question:
The "wrong" aspect of the df.plot() is in regards to the y-axis. It is rounding values to a point that makes the plot look jagged with flat periods.
Whereas the excel version is able to plot the values as they are and looks much smoother.


text:
Q: date() is showing December 1969 $sql = "SELECT * FROM news ORDER BY `news_id` DESC LIMIT 1";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$date = $row['time_posted'];
echo "<i> " .date("Y/m/d", $date) . "</i>: ";

I used timestamp in mysql.

A: date('Y/m/d', strtotime($date));

TIMESTAMP columns are not displayed as unix timestamps (anymore).

TIMESTAMP columns are displayed in the
  same format as DATETIME columns. In
  other words, the display width is
  fixed at 19 characters, and the format
  is 'YYYY-MM-DD HH:MM:SS'.

A: The UNIX epoch was at January 1, 1970 at exactly midnight UTC. If you live in a timezone behind UTC, timestamp 0 will show up sometime in the evening of December 31, 1969. ($date is most likely 0)


text:
Q: Add/register external users to our office 365 without having to invite them inadvance to access a site collection Usually when i share a site with external users, i do the following steps:-

*

*Enable external sharing on the related site collection.

*I add/share the external users email addresses to a site collection's group (ie members group).

*Then the external users will receive an email, and once the external user login to sharepoint, his/her email address will be added a Guest account inside office 365, and will have this format user.name_ourpartner.net#EXT#@SPTenant.com.
but now i am facing this scenario:-

*

*we have sharepoint enterprise on-premises 2013. and we have 10 external users' accounts added to our on-premises active directory (those represents a partner company which have separate domain), and those external users were accessing the the on-premises sharepoint sites using VPN.

*now i am using a third party tool named sharegate, to migrate the on-premises site collections to sharepoint online.
But i want to map the on-premises external users to new external users (Guests) accounts. and to be able to do the mapping i have to add the external users in-advance to office 365 . so i am not sure if i can replicate the above 3 steps manually ?.. in other, words; can i without sending the external users invitation emails , to have their accounts added inside office 365 as external users (Guest)?

A: Based on my knowledge, user can't be add in office 365 without invitation. Even though if you are adding as new guest user in Azure Active Directory, User will get an invitation email and he need to accept it for create a new password and for email ID verification
I hope the mentioned external users were created as a contact in On-Premises Active Directory, so i suggest you to use the Azure Active Directory connect (Download Here)  to synchronize all the on-premises users to Azure Active Directory


text:
Q: How to straighten up this spiraling vector field? Let $X(x_1, x_2) = (x_1 -x_2)\partial_1 + (x_1 + x_2 + 1)\partial_2$ be a vector field on $\mathbb{R}^2$. I want to straighten it up around point $0$ . $X(0) = \delta_2|_0 \neq 0$. So it must be possible.
By straightening vector filed I mean finding a neighborhood $U$ of $0$ with equipped diffeomorphism $\varphi : U \to V \subset \mathbb{R}^2$ such that
$ \varphi_* X = \partial_1 $. Here $\varphi_*$ is a push forward defined by
$$
\varphi_* X(y) = D\varphi_{|\varphi^{-1}(y)} X(\varphi^{-1}(y))
$$
Generally I just plug vector field into the prove of the straightening theorem.
First I compute flow $F(t;a)$ by solving associated ode $\dot x = X(x) $ with an initial condition $x(0) = a$. Then for some $x \in U$, where  $U$ is a small neighborhood of $0$, I want to find point $(u,0)$ such that $ F(t_x;(u_x,0)) = x$. In the nice case this can be achieved by working with some equations, which will also restrict size of $U$. And then the straightening map can be defined by $\varphi(x) = (t_x,u_x)$
However, the  flow of $X$ turns out to  have a rather complicated expression:
$$ F(t;x_1,x_2) =e^t \binom{x_1 \cos(t) - x_2 \sin(t)}{x_2 \cos(t) + x_1 \sin(t)} +
\frac{1}{2}e^t \binom{\cos(t) - \sin(t) }{\cos(t) + \sin(t)} - \binom{1/2}{1/2},
$$
And I son't вщтэе know how to solve the equations
$$
\binom{x_1}{x_2} =F(t;u,0) = ue^t \binom{\cos(t)}{  \sin(t)} +
\frac{1}{2}e^t \binom{\cos(t) - \sin(t) }{\cos(t) + \sin(t)} - \binom{1/2}{1/2}
$$
So, I need to find better way to solve this problem.

Is there a trick to solve this equations? Are there a better (i.e. geometric) way which don't use flow equation explicitly?

Further thoughts:
I noticed that
$$
\left(x_1 + \frac{1}{2}\right)^2 + \left(x_2 + \frac{1}{2}\right)^2 =
u^2e^{2t} + \frac{1}{2}ue^{2t} + \frac{1}{2}e^{2t}
$$
Which can be rewritten as quadratic equation with
$0 = u^2 + \frac{1}{2}u + a$ with
$$a = \frac{1}{2} -  \frac{(x_1 + 1/2)^2 + (x_2 + 1/2)^2 }{e^{2t}}$$
On the other hand
$$x_1 - x_2  = u e^t (\cos(t) - \sin(t))  - e^t\sin(t),  $$
$$x_1 + x_2 + 1 =  u e^t (\cos(t) + \sin(t)) + e^t\cos(t);  $$
Then the sum of squares is
$$(x_1 - x_2)^2  + (x_1 + x_2 + 1)^2 = 2u^2 e^{2t}  + e^{2t}  + ue^{2t},$$
which is essentially the same equation.

A: I think I found a solution:
Use line spanned by the vector $(1,1)$ to catch the integral curves. Then the expression turns into
$$
\binom{x_1}{x_2} =F(t;u,u) = (u + 1/2)e^t  \binom{\cos(t) - \sin(t) }{\cos(t) + \sin(t)} - \binom{1/2}{1/2}
$$
or equivalently
$$
y=\binom{x_1 + 1/2}{x_2 + 1/2}  = (u + 1/2)e^t  \binom{\cos(t) - \sin(t) }{\cos(t) + \sin(t)} = (u + 1/2)e^t \left(\begin{array}{cc}\cos(t) & -\sin(t)  \\ \sin(t) & \cos(t) \end{array}\right)\binom{1}{1}.
$$
Note, that that the matrix on the right hand size represents rotation by the angle $t$. No other factors affect the sign of $y$. So it is safe to say that:
$$
t_x = \mathrm{Arg}(y) = \arctan\left(\frac{x_1 + 1/2}{x_2 + 1/2}\right) - \frac{\pi}{4}
$$
Now it is possible to express $u$ by
$$ \sqrt{(x_1 + 1/2)^2 + (x_2 +1/2)^2} =\|  y \| =  \sqrt{2}(u + 1/2)e^t $$
as
$$
u_x = \frac{\sqrt{(x_1 +1/2)^2 +(x_2 + 1/2)^2}}{\sqrt{2} \exp\Big(\arctan\big(\frac{2x_1 + 1}{2x_2 + 1}\big) - \pi/4\Big)} -\frac{1}{2}
$$
I think it is possible to take $U$ equal to an open ball of the radius $\frac{1}{2}$ centered at $0$.  And let $\varphi(x) = (t_x,u_x)$ as was planed.
Im still will be thankful for any advice.

A: By dividing it into several smaller transformations and applying some straightforward observations, we can rectify the given vector field without any heavy lifting.
First, note that we can eliminate the constant term in the coefficient of $\partial_{x^2}$ by making the affine coordinate change, e.g., $$y^i := 2 x^i + 1, \quad i = 1, 2 ,$$
and in these coordinates, the vector field is
$$X = (y^1 - y^2) \partial_{y^1} + (y^1 + y^2) \partial_{y^2}.$$
We can recognize this vector field as the sum of the Euler vector field, $y^1 \partial_{y^1} + y^2 \partial_{y^2}$, and the vortex vector field, $-y^2 \partial_{y^1} + y^1 \partial_{y^2}$. Both of these are rotationally symmetric (the former is radial, and the latter is the standard infinitesimal generator of rotations of the plane), hence so is $X$. Thus, it's natural to absorb this symmetry into a new coordinate: The point $(x^1, x^2) = (0, 0)$ is $(y^1, y^2) = (1, 1)$, and since this is away from the origin (in $y^i$-coordinates) we can choose coordinates $(z^1, z^2)$ in some neighborhood of this point for which
$$y^1 = e^{z^1} \cos z^2, \qquad y^2 = e^{z^1} \sin z^2 ;$$
in these coordinates, $$X = \partial_{z^1} + \partial_{z^2} .$$ But this vector field is constant, so a suitable linear transformation, e.g., $$z^1 = \frac{1}{2}(w^1 + w^2), \qquad z^2 = \frac{1}{2}(w^1 - w^2),$$ gives coordinates in which $$\boxed{X = \partial_{w^1}}$$ as desired.
Remark If we make the usual identification $\Bbb R^2 \leftrightarrow \Bbb C$, ${\bf x} := (x^1, x^2) \leftrightarrow x^1 + i x^2 ,$ we can write each of these transformations (and hence their composition) much more compactly: We have ${\bf y} = 2 {\bf x} + 1$, ${\bf y} = \exp {\bf z}$, and ${\bf z} = \frac{1}{2} (1 - i) {\bf w}$, and thus $${\bf w} = (1 + i) \log (2 {\bf x} + 1) $$ for an appropriate choice of branch cut of $\log$.


text:
Q: I need help using the 'at' command Hello guys I just started to use Ubuntu and Ubuntu Server, I'm stuck using the at command.
Don't know how to initiate the command. This is what I'm trying do to:
I'm trying to run this file at 5 AM using the 'at" command
/etc/holler.sh
Thank You In Advance!

A: You should be able to do that with at -
1) Install at
sudo apt-get install at

2) Schedule your command
at 05:00 /somePathTo/someCommand


text:
Q: Warning message: In is(object, Cl) : error while fetching rows R I am unable to fetch all rows from mysql using R.
There are around 900000 rows need to fetch but R is fetching only around 500000 rows. I am getting below warning.
  > response = fetch(res ,1000000)
    Warning message:
    In is(object, Cl) : error while fetching rows

Any help would be appreciated.


text:
Q: element moves left on hide I'm displaying an error message in the middle of the screen, then after a few seconds it will fade out.
This works, but what I don't want happening is the error message moving to the far left of the screen when fading out.
I'm not sure if this is being cause because of css or the actual jquery itself.
Here's an example of what's happening: http://jsfiddle.net/dLt51xwe/
$(document).ready(function () {
    $("button").click(function () {
        $('#error').html("
ERROR
").show();
        setTimeout(function () {
            $('#error').hide("slow");
        }, 1000);
    });
});

I was wondering if it was the margin on the css that was causing it, so I tried this instead:
left: 50%;
transform: translate(-50%, 0);
width: 40%;
position: relative;

But I still got the same problem where the element would move to the far left while fading out.
I've also tried using the fadeOut() option provided, but the fading doesn't work. The fadeOut() seems to only work in an event for me, and I'm using this in an else statement.
Example out of an event: http://jsfiddle.net/dLt51xwe/1/
Any help is greatly appreciated,
Thanks!

A: use .fadeOut("slow") instead of .hide("slow") the issue is to do with the default easing on hide(). I've always found it hard to find the available strings to use for the easing option - so its simpler to use fadeIn() and fadeOut().
$(document).ready(function () {
    $("button").click(function () {
        $('#error').html("
ERROR
").show();
        setTimeout(function () {
            $('#error').fadeOut("slow");
        }, 1000);
    });
});

in response to  ItsMatt's comment
See your fiddle updated: http://jsfiddle.net/dLt51xwe/2/
fadeOut() and hide() wasn't working on the <errormessage> element you created, so instead I edited the javascript to call fadeOut() on the internal div .error-message rather than the <errormessage> container element.
See here:
$(document).ready(function () {
  $('errormessage').html("
Please enter a valid message!
").show();
  setTimeout(function () {
      $('.error-message').fadeOut("slow");
  }, 1000);
});

A: Simply use jQuery function fadeOut() will solve the problem:
Change
$('#error').hide("slow");

to
$('#error').fadeOut("slow");


text:
Q: Script to append file with new results - sequence expected error I have wrote a python script that is supposed to use a regex on an existing column then write this to a new csv file.
The CSV has 6 columns, ID, book, author, category, keywords, rule.
The keywords column is actually the exact same as the rule column, however i want to update the keywords column with the output of my REGEX in my code.
I seem to be getting an _csv.Error: sequence expected error, script below:
#!/usr/bin/env

import csv
import re

file1 = open('test.csv', 'rb')
reader = csv.reader(file1, delimiter=';')
your_list = list(reader)
new_rows_list = []

for i in your_list:
    x = re.search(r"\"value\":(.*?)\,\"", i[5])
    new_rows_list.append(x)
file1.close()

file2 = open('test.csv', 'wb')
writer = csv.writer(file2)
writer.writerows(new_rows_list)
file2.close()

A: Could you try this one
import re
import csv

file1 = open('test.csv', 'r')
# using comma separete
reader = csv.reader(file1, delimiter=',')

lst_values = []

for idx, i in enumerate(reader):

    x = re.search(r"\"value\":(.*?)\,\"", i[5])
    # Add the result of regexp to keyword column
    try:
      i[4] += x.group(0)
    except AttributeError:
      None

    lst_values.append(i)

wr_file = open('test.csv', 'w')
for record in lst_values:

  wr_file.write(str(record))

wr_file.close()


text:
Q: How to Sum Total in Header Detail Tables Please, I need your help, I'm new to the subject, so I have tow tables Order table and Order Detail table. I want to sum order amount in the order table and group by the product id exists in the order detail table. I'm getting repeated rows.
select p.productName
       SUM(o.Amount - o.discount) as OrdersTotal
  FROM dbo.order o
       inner join
       OrderDetail d
    ON o.orderid = d.orderid
       inner join
       dbo.product p
    ON d.productid = p.productid
    where o.orderdate >= @fromdate
      and o.orderdate <= @todate
group by p.productname, o.discount

the result I'm getting is as follow
product name    orders total
------------    ------------
product A       150
product A       20
product B       45
product B       13

so please, how can I fix this result? Thanks

A: You should only group on the product name, so that all records with the same product name are included in the sum of the amount:
select p.productName
       SUM(o.Amount) as OrdersTotal
  FROM dbo.order o
       inner join
       OrderDetail d
    ON o.orderid = d.orderid
       inner join
       dbo.product p
    ON d.productid = p.productid
    where o.orderdate >= @fromdate
      and o.orderdate <= @todate
group by p.productname


text:
Q: How to store a time interval with HH:MM:SS:MS swift So this turned out to be way more complex than I was I expecting. I have four text fields that allows the user to enter HH:MM:SS:MS and I need to mash these together to create a number I can save in fireStore.
I then need to get this number out and convert it back to HH:MM:SS:MS again for use in a tables graphs etc.
I did initially consider using a string but that's not going to help me with graphs/ordering I want to do later. Done a lot of searching and haven't been able to find a workable solution that includes milliseconds.
Any help appreciated!
Some code below if that helps, all I have at the moment is me mashing these together into a string...
let goalHHText = UITextField()
let goalMMText = UITextField()
let goalSSText = UITextField()
let goalMSText = UITextField()

let goalCombined.append(goalHHText.text! + ":" + goalMMText.text! + ":" + goalSSText.text! + ":" + goalMSText.text!)

I'm then adding goalCombined into a dictionary and pushing into Firestore. Sorry that's as far as I've got, I am 100% coding noob.
I've looked at dateComponentsFormatter but that doesn't support milliseconds
let interval = 27005
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second ]
formatter.unitsStyle = .full
let formattedString = formatter.string(from: TimeInterval(interval))!
print(formattedString)

A: Convert it into smallest unit time, here milliseconds. Convert the entire time to milliseconds by :-
index = (((HH*60 + MM)*60 + SS)*60 + MS)*1000;

Store 'index' value in firestore as type "number". Also store individual HH, MM, SS, MS values separately in firestore for easy retrieval.