text:
Q: Get the coordinate of that point every 100 meters along a route I have a start point and a destination point. I want to take the coordinates of that point on the map every 100 meters on this route. How can I do it ? Is there anyone who can help?
I've been searching for google maps api but couldn't find it

A: Mike Williams wrote an extension for the Google Maps JavaScript API v2 called epoly, which contains the method GetPointsAtDistance, which sounds like what you are looking for.

.GetPointsAtDistance(metres)
Returns an array of GLatLngs of points at the specified interval along the path.
By calculating all the points in a single pass, this runs a lot faster than calling GetPointAtDistance() in a loop. If the path is shorter than the specified distance, then it returns null.

There is a version ported to v3 here: http://www.geocodezip.com/scripts/v3_epoly.js
proof of concept fiddle

code snippet:

let map;
let polyline;
let markers = [];

function initMap() {
  initEpoly();
  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer();
  map = new google.maps.Map(document.getElementById("map"), {
    zoom: 7,
    disableDefaultUI: true,
    center: {
      lat: 41.85,
      lng: -87.65
    },
  });
  polyline = new google.maps.Polyline({
    path: [],
    strokeColor: '#0000FF',
    strokeWeight: 3,
    map: map
  });
  directionsRenderer.setMap(map);
  calculateAndDisplayRoute(directionsService, directionsRenderer);

  const onChangeHandler = function() {
    calculateAndDisplayRoute(directionsService, directionsRenderer);
  };

  document.getElementById("btn").addEventListener("click", onChangeHandler);
}

function calculateAndDisplayRoute(directionsService, directionsRenderer) {
  polyline.setPath([]);
  clearMarkers();
  directionsService
    .route({
      origin: {
        query: document.getElementById("start").value,
      },
      destination: {
        query: document.getElementById("end").value,
      },
      travelMode: google.maps.TravelMode.DRIVING,
    })
    .then((response) => {
      directionsRenderer.setDirections(response);
      renderDirections(response, map);
      var points = polyline.GetPointsAtDistance(100);
      console.log(points.length);
      for (var i = 0; i < points.length; i++) {
        var marker = new google.maps.Marker({
          map: map,
          position: points[i],
          title: "" + i,
          icon: {
            url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
            size: new google.maps.Size(7, 7),
            anchor: new google.maps.Point(3.5, 3.5)
          }
        });
        markers.push(marker);
      }
    })
    .catch((e) => window.alert("Directions request failed due to " + status));
}

function renderDirections(response, map) {
  var bounds = new google.maps.LatLngBounds();

  var legs = response.routes[0].legs;
  for (i = 0; i < legs.length; i++) {
    var steps = legs[i].steps;
    for (j = 0; j < steps.length; j++) {
      var nextSegment = steps[j].path;
      for (k = 0; k < nextSegment.length; k++) {
        polyline.getPath().push(nextSegment[k]);
        bounds.extend(nextSegment[k]);
      }
    }
  }
}

function clearMarkers() {
  for (var i = 0; i < markers.length; i++)
    markers[i].setMap(null);
  markers = [];
}

window.initMap = initMap;

function initEpoly() {
  /*********************************************************************\
   *                                                                     *
   * epolys.js                                          by Mike Williams *
   * updated to API v3                                  by Larry Ross    *
   *                                                                     *
   * A Google Maps API Extension                                         *
   *                                                                     *
   * Adds various Methods to google.maps.Polygon and google.maps.Polyline *
   */
  // === A method which returns an array of GLatLngs of points a given interval along the path ===
  google.maps.Polyline.prototype.GetPointsAtDistance = function(metres) {
    var next = metres;
    var points = [];
    // some awkward special cases
    if (metres <= 0) return points;
    var dist = 0;
    var olddist = 0;
    for (var i = 1;
      (i < this.getPath().getLength()); i++) {
      olddist = dist;
      dist += google.maps.geometry.spherical.computeDistanceBetween(this.getPath().getAt(i), this.getPath().getAt(i - 1));
      while (dist > next) {
        var p1 = this.getPath().getAt(i - 1);
        var p2 = this.getPath().getAt(i);
        var m = (next - olddist) / (dist - olddist);
        points.push(new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m));
        next += metres;
      }
    }
    return points;
  }
}
/*
 * Always set the map height explicitly to define the size of the div element
 * that contains the map.
 */

#map {
  height: 100%;
}

/*
 * Optional: Makes the sample page fill the window.
 */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: "Roboto", "sans-serif";
  line-height: 30px;
  padding-left: 10px;
}
<!DOCTYPE html>

  <title>Directions Service</title>

    Start:
    <input id="start" value="New York, NY" />
    End:
    <input id="end" value="Soho, NY" />
    <input id="btn" type="button" value="get directions" />


text:
Q: SignalR library throws error when it application run without debug points and work fine while debugging I have created a .net core chat application using SignalR and I need move to next user by clicking next button. When I click the next button it will trigger the method "getRemoteClientNext" inside the Hub class
public async Task getRemoteClientNext(string RemoteUserId)
{

      var name = Context.User.Identity.Name;
        var CurrentAppUser = _userManager.FindByNameAsync(name);

        if(RemoteUserId != null) {
            using (var db = _dBContext)
            {
                var remotename = db.Users.Find(RemoteUserId);

                var RemoteUser = db.Connections.Where(c => c.UsersId != CurrentAppUser.Result.Id && c.UsersId != RemoteUserId && c.RemoteConnected == false).AsEnumerable().GroupBy(c => c.UsersId);

                //var remoteConnection = db.Connections.Where(u => u.UsersId == CurrentAppUser.Result.Id || u.UsersId == RemoteUserId).ToList();
                //remoteConnection.ForEach(i => i.RemoteConnected = false);
                var currntUserConnection = db.Connections.Where(u => u.UsersId == CurrentAppUser.Result.Id).AsEnumerable().FirstOrDefault();
                currntUserConnection.RemoteConnected = false;
                db.SaveChanges();

                var RemoteUserConnection = db.Connections.Where(u => u.UsersId == RemoteUserId).AsEnumerable().FirstOrDefault();
                if (RemoteUserConnection != null)
                {
                    RemoteUserConnection.RemoteConnected = false;
                }
                db.SaveChanges();

                var connec = db.Connections.Where(c => c.UsersId == RemoteUserId);

                if (connec.Count() == 0)
                {
                    await Clients.Caller.SendAsync("ClienErrors", "The user is no longer connected");
                }
                else
                {
                    foreach (var connection in connec)
                    {
                        await Clients.Client(connection.ConnectionID).SendAsync("maintainConnectionStatus", "Connecting a remote user......");
                    }

                }
                await Clients.Caller.SendAsync("maintainConnectionStatus", "Connecting a remote user......");

                if (RemoteUser.Count() == 0)
                {
                    await Clients.Caller.SendAsync("maintainConnectionStatus", "Connecting a remote user......");
                }
                else
                {
                    var selectedRemoteUser = RemoteUser.First().ToList();
                    var currentUserConnection = db.Connections.Where(u => u.UsersId == CurrentAppUser.Result.Id).AsEnumerable().FirstOrDefault();
                   // selectedRemoteUser.ForEach(c => c.RemoteConnected = true, c.Remo) ;
                    foreach(Connections con in selectedRemoteUser)
                    {
                        con.RemoteConnected = true;
                        con.RemoteConnectionID = currentUserConnection.ConnectionID;
                        currentUserConnection.RemoteConnectionID = con.ConnectionID;
                    }
                    // var currentUserConnection = db.Connections.Where(u => u.UsersId == CurrentAppUser.Result.Id).AsEnumerable().FirstOrDefault();
                    var RemoteId = selectedRemoteUser.Select(u => u.UsersId).FirstOrDefault();
                    var RemoteName = db.Users.Find(RemoteId);
                    currentUserConnection.RemoteConnected = true;

                    db.SaveChanges();

                    //var RemoteId = selectedRemoteUser.Select(u => u.UsersId).FirstOrDefault();
                    //var RemoteName = db.Users.Find(RemoteId);

                    var connec2 = db.Connections.Where(c => c.UsersId == RemoteId);

                    if (connec2.Count() ==0)
                    {
                        await Clients.Caller.SendAsync("ClienErrors", "The user is no longer connected");
                    }
                    else
                    {
                        foreach (var connection in connec2)
                        {
                            await Clients.Client(connection.ConnectionID).SendAsync("SendRemoteUserId", CurrentAppUser.Result.Id, CurrentAppUser.Result.FirstName);
                        }

                    }
                    await Clients.Caller.SendAsync("SendRemoteUserId", RemoteId, RemoteName.FirstName);
                }
            }
        }
    }

in java script the event is like
document.getElementById("next").addEventListener("click", function (event) {
connection.invoke("getRemoteClientNext", RemoteUserId);
});

The issue I got is when I click the next button "getRemoteClientNext" will be triggered and work fine when it is debugging. If I disable all the debug points and run the application this will not work. But other functions like sending the chat messages using hub are working finely. Then I check the console and I saw the error message
Uncaught (in promise) Error: An unexpected error occurred invoking 'getRemoteClientNext' on the server.
at _this.callbacks. (signalr.js:2088)
at HubConnection.processIncomingData (signalr.js:2182)
at WebSocketTransport.HubConnection.connection.onreceive (signalr.js:1905)
at WebSocket.webSocket.onmessage (signalr.js:3949)

I removed the SignalR and try to install it again but it is not working and in add client side library also only showing Jquery.SignalR.js and Jquery.SignalR.min.js files. So I added Signalr.js file manually from another project.
Can any one tell me why this is happening is it error in SignalR library

A: This smells like a race condition just as SomeStudent suggested. Reading through the first couple of lines of code inside the getRemoteClient() method, you are missing an await.
I can't say with 100% certainty this will fix it, but I'm certain it could become a problem even if this wasn't the culprit.
// Add await here.
var CurrentAppUser = await _userManager.FindByNameAsync(name);

redpajama_set_name: RedPajamaStackExchange


text:
Q: git checkout only certain file types for entire project Is there a way to perform a git checkout for only certain file types (.xlf), which recurses down through the entire repository? The results should contain the struture of the repository, meaning the folders, and the contained files of a certain extension.
Repo A
file.xlf
file.txt
level2/
    file2.xlf
    file2.txt
    level3/
        file3.xlf
        file3.txt

After checkout repo B looks like:
Repo B
file.xlf
    /level2
    file2.xlf
        /level3
        file3.xlf

This is what I have so far:
$ git checkout FETCH_HEAD -- '*.xlf'

This gives all of the ".xlf" files at the root level, but is not recursive down to subdirectories.
Thank you for the help.

A: Dadaso's answer git checkout -- "*.xml" checks out all .xml files recursively from index to working directory.
However for some reasons git checkout branch-name -- "*.xml" (checking out files from branch-name branch) doesn't work recursively and only checks "xml" files in root directory.
So IMO the best is to use git ls-tree then filter file names you are interested in and pass it to git checkout branch-name --. Here are the commands you can use:

*

*Bash (and git bash on windows) version:
git ls-tree branch-name --full-tree --name-only -r | grep "\.xml" | xargs git checkout branch-name --

*cmd (windows) version (if you don't have "C:\Program Files\Git\usr\bin" in you PATH):
git ls-tree branch-name --full-tree --name-only -r | "C:\Program Files\Git\usr\bin\grep.exe" "\.xml" | "C:\Program Files\Git\usr\bin\xargs.exe" git checkout branch-name --

*for powershell it's still better to call cmd.exe because it's much faster (powershell doesn't have good support for native stdin/stdout pipelining):
cmd.exe /C 'git ls-tree branch-name --full-tree --name-only -r | "C:\Program Files\Git\usr\bin\grep.exe" "\.xml" | "C:\Program Files\Git\usr\bin\xargs.exe" git checkout branch-name --'

*However you you have small number of files you can try this in powershell (like in @aoetalks answer). But I found it extremely slow for couple of houndeds files:
git ls-tree branch-name --full-tree --name-only -r | sls "\.xml" | %{ git checkout branch-name -- $_ }

A: You don't need find or sed, you can use wildcards as git understands them (doesn't depend on your shell):
git checkout -- "*.xml"

The quotes will prevent your shell to expand the command to only files in the current directory before its execution.
You can also disable shell glob expansion (with bash) :
set -f
git checkout -- *.xml

This, of course, will irremediably erase your changes!

A: On PowerShell (Windows, haven't tried PowerShell Core+Linux), I was able to do it like this
git ls-tree master -r --name-only | sls ".cscfg" | foreach { git checkout origin/master -- $_ }

A: UPDATE: Check Dadaso's answer for a solution that will work in most of cases.
You can try something like this, using git ls-tree and grep:
git checkout origin/master -- `git ls-tree origin/master -r --name-only | grep ".xlf"`

Note this expects a remote origin in a master branch. Also you must provide the right filter/extension to grep.

Before this command, you should have done something like this:

git init
git remote add origin <project.git>
git fetch

A: No; git operates at a whole-repository (and whole-history) level; there's no way of getting a partial checkout of a repository. You can of course check out the repository and then delete everything that doesn't match your file, but of course you gain virtually nothing by doing so.

A: I had troubles with the solutions provided, and here is my solution

*

*checkout all change from the other branch git checkout branch -- ./

*only stage the certain type git add \*.type

*commit staged files git commit

*reset the other files git reset --hard


text:
Q: How to map requests from a path? I have the following domain:
https://example.com
I want, when the following /path/ is hit:
https://example.com/path/subpath/?param1=value1&param2=value2

the content from this url to be served:
https://example.com/subpath/?param1=value1&param2=value2

without performing a redirect.

I have tried using an alias like this:

location /path/ {
alias /home/forge/example.com/current/;
}

where current is a symlink pointing to the latest release:

current -> /root/example.com/releases/timestamp/

But it doesn't work. it gives 404.
How can I achieve this?
The entire server block:
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com;
    server_tokens off;
    root /home/forge/example.com/current;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    location /path/ {
        alias /home/forge/example.com/current/;
    }

    location / {
        gzip_static on;
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log /var/log/nginx/example.com-access.log;
    error_log  /var/log/nginx/example.com-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
    gzip on;
}

A: I don't see any reason why
rewrite ^/path(/.*) $1;

didn't work as expected. But if you want to use an alias solution instead, you should take into account that regex matching locations have a greater priority than prefix ones and any request for /path/subpath/index.php would be processed by location ~ \.php { ... } rather than location /path/ { ... }. You can override this with ^~ location modifier using a second nested PHP handler:
location ^~ /path/ {
    alias /home/forge/example.com/current/;
    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}


text:
Q: Oracle Delete more than one node in XMLTYPE I have a XMLTYPE content and I want to remove more than one tag in that XML.
I'm using XMLQUERY to remove the tag recordType inside the Header, like this:
   SELECT XMLQUERY (
             'copy $i := $p modify
                  delete nodes $i//Header/recordType
                return $i'
             PASSING pv_header AS "p" RETURNING CONTENT)
     INTO result
     FROM DUAL;

What if I want to remove more than one tag without creating a new SELECT statement using XMLQUERY. I can't do this:
SELECT XMLQUERY (
                 'copy $i := $p modify
                      delete nodes $i//Header/recordType
                      delete nodes $i//Header/interfaceType
                    return $i'
                 PASSING pv_header AS "p" RETURNING CONTENT)
         INTO result
         FROM DUAL;

Note: I could use deleteXML but it is declared as a deprecated function in Oracle 12c.
Thanks in advance!
Filipe
EDIT: I'm using this as reference: https://docs.oracle.com/database/121/ADXDB/xdb04cre.htm#ADXDB6086

A: You can have a sequence of calls to delete nodes, enclosed in parentheses for grouping, and separated by commas for sequence concatenation:
WITH t (pv_header) AS (
  SELECT xmltype('<recordType/><interfaceType/><other/>')
  FROM dual
)
SELECT XMLQUERY (
  'copy $i := $p modify
    (delete nodes $i//Header/recordType,
      delete nodes $i//Header/interfaceType)
    return $i'
  PASSING pv_header AS "p" RETURNING CONTENT)
FROM t;

XMLQUERY('COPY$I:=$PMODIFY(DELETENODES$I//HEADER/RECORDTYPE,DELETENODES$I//HEADE
--------------------------------------------------------------------------------
<other/>


text:
Q: lpsolve - how to define variable to accept values only from two intervals I need to set up all my variables to accept only values from two intervals, e.g. for var C1:
    C1 = 0 or
    100 <= C1  <= 1000

and so on for each variable.
I can specify either first (=0) or second ([100;1000]) constraints for every variable but I need lpsolve model to to be able to assign either 0 ot any value from given interval.
Any advice appreciated.


text:
Q: How to output from a .NET console app to an existing Notebook in Mathematica? I'm wondering if its possible push output from a .NET console application to an existing Notebook that is open in Mathematica.
The reason I'd like this is that I want to use Mathematica as a "debugging console" for intermediate calculations that I am performing in .NET, by pushing out text, graphics, etc.
p.s. I'm fairly familiar with C# and Mathematica, so all I want to know is if this is possible, or not.

A: See http://reference.wolfram.com/mathematica/tutorial/ManipulatingNotebooksFromTheKernel.html
If we send the following four commands to the Mathematica Kernel, via Net/Link, it will create a new notebook, and graph the result of an equation:
n = CreateWindow[]
NotebookWrite[n, "Plot[Sin[x],{x,0,6 Pi}]"]
SelectionMove[n, All, CellContents]
SelectionEvaluateCreateCell[n]

Here is the output in Mathematica. I think this is pretty cool: now I can use Mathematica as a kind of super charged debugging console from a .NET application, one which can plot graphic as well as print text. Any output graphs can then be interacted with, i.e. rotated, animated, etc.

Update
Unfortunately, this didn't end up working at all.
The following command does not work from .NET/Link, as its a function call contained in the user interface, and not the kernel:
n = CreateWindow[]

Currently, I'm still stuck. The only option I can think of is to create a standalone Windows service that sits in the background, accepting arrays from the standalone .NET app, and serving them to a Mathematica Notebook on demand (I havn't implemented this yet).


text:
Q: How to turn off Turbo Boost temporarily? In our application we have many versions of the same routine optimized for different kind of processor architectures. During install we run performance tests and select the best version of routine.
Latest processors can boost their frequencies if few cores are in use, so sometimes our tests peeking wrong version of routine. Is there some way to temporarily turn off Turbo Boost?

A: I don't know the opcode for enabling/disabling turbo boost directly, but apparently it's possible because TMonitor - which is a Windows application - can do it at runtime.

A: There are MSR registers (https://en.wikipedia.org/wiki/Model-specific_register) in Intel CPUs to disable/enable per-core turbo boost. In linux, there are msr-tools package which allow root to read/write to MSR registers. There are two posts about Turbo Boost disabling/enabling in Linux:
https://askubuntu.com/questions/619875/disabling-intel-turbo-boost-in-ubuntu "Disabling Intel Turbo Boost in ubuntu", answer by Maythux from 2015
http://luisjdominguezp.tumblr.com/post/19610447111/disabling-turbo-boost-in-linux
Disabling Turbo Boost in Linux, Luis J. Dominguez P, 2012-2013; Sandy Bridge - "38th bit of the 0x1a0 register."
http://notepad2.blogspot.com/2014/11/a-script-to-turn-off-intel-cpu-turbo.html
And there is kext for OSX to do the same: Disable Turbo Boost on Core i7 Mac?

A: In windows OS you can add the following reg key.
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\be337238-0d82-4146-a960-4f3749d470c7]
"Attributes"=dword:00000002

Then in advanced power settings you will get new option that allows you turning off turbo boost.


text:
Q: Drupal 7, EntityFieldQuery Pager doesn't work I was using a EntityFieldQuery to collect my data and print it on my page. After that, I decided to add a pager to it all. Somehow, I do not understand the pager didn't work. I then tried integrating this on my localhost on an old drupal 7.22 installation I had. Since I had the same field names I was okay. To my astonishment I saw that my code was working perfectly. I tried installing a recent drupal version to see how it would go along. Nothing worked.
Now to my actual question. What could be different on my older drupal installation that could let the pager work and not make it work on a recent 7.24 clean install?
Also I tried implementing this code to test out the pager:

    $header = array(
      array('data' => 'Title',     'field' => 'title'),
      array('data' => 'Date created', 'field' => 'created'),
      array('data' => 'Type',           'field' => 'type'),
    );

    $nodes = db_select('node', 'n')
      ->fields('n', array('title', 'created', 'type'))
      ->extend('PagerDefault')
      ->limit(10)
      ->extend('TableSort')
      ->orderByHeader($header)
      ->execute();

    $rows = array();
    foreach ($nodes as $node) {
      $rows[] = array(
        check_plain($node->title),
        format_date($node->created),
        $node->type
      );
    }

    $output = theme('table', array('header' => $header, 'rows' => $rows));
    $output .= theme('pager');

    print render($output);

Everything was working on my older installation and not on the recent ones..
Help would be really appreciated.. Thanks

A: Anyway I finally made the pager work by setting up a homepage in drupal's settings.


text:
Q: Why is my dockerfile working on Windows but not on Mac? I'm building a NextJS 13 application. I'm usually working on Windows but out of my home I'm using a Mac. Everything is working correctly on Windows, but when I build the image on my Mac everything crashes (chip M1 by the way).
This is my dockerfile:
FROM node:16-alpine

WORKDIR /app

COPY package*.json .

RUN npm install

COPY . .

EXPOSE 3000

CMD npm run dev

This dockerfile crashes in the RUN npm install step just on Mac and throws a huge amount of errors
 => [internal] load build definition from .dockerfile-dev                    0.0s
 => => transferring dockerfile: 179B                                         0.0s
 => [internal] load .dockerignore                                            0.0s
 => => transferring context: 34B                                             0.0s
 => [internal] load metadata for docker.io/library/node:16-alpine            1.3s
 => [1/5] FROM docker.io/library/node:16-alpine@sha256:029a85552a270cd6dfae  0.0s
 => => resolve docker.io/library/node:16-alpine@sha256:029a85552a270cd6dfae  0.0s
 => [internal] load build context                                            0.1s
 => => transferring context: 1.69kB                                          0.0s
 => CACHED [2/5] WORKDIR /app                                                0.0s
 => [3/5] COPY package*.json .                                               0.0s
 => ERROR [4/5] RUN npm install                                             10.0s
------
 > [4/5] RUN npm install:
#8 9.721 npm notice
#8 9.722 npm notice New major version of npm available! 8.19.3 -> 9.5.0
#8 9.722 npm notice Changelog: <https://github.com/npm/cli/releases/tag/v9.5.0>
#8 9.722 npm notice Run `npm install -g npm@9.5.0` to update!
#8 9.722 npm notice
#8 9.723 npm ERR! code 1
#8 9.724 npm ERR! path /app/node_modules/bufferutil
#8 9.725 npm ERR! command failed
#8 9.725 npm ERR! command sh -c -- node-gyp-build
#8 9.725 npm ERR! gyp info it worked if it ends with ok
#8 9.725 npm ERR! gyp info using node-gyp@9.1.0
#8 9.725 npm ERR! gyp info using node@16.19.1 | linux | arm64
#8 9.725 npm ERR! gyp ERR! find Python
#8 9.725 npm ERR! gyp ERR! find Python Python is not set from command line or npm configuration
#8 9.725 npm ERR! gyp ERR! find Python Python is not set from environment variable PYTHON
#8 9.725 npm ERR! gyp ERR! find Python checking if "python3" can be used
#8 9.725 npm ERR! gyp ERR! find Python - "python3" is not in PATH or produced an error
#8 9.725 npm ERR! gyp ERR! find Python checking if "python" can be used
#8 9.725 npm ERR! gyp ERR! find Python - "python" is not in PATH or produced an error
#8 9.725 npm ERR! gyp ERR! find Python
#8 9.726 npm ERR! gyp ERR! find Python **********************************************************
#8 9.726 npm ERR! gyp ERR! find Python You need to install the latest version of Python.
#8 9.726 npm ERR! gyp ERR! find Python Node-gyp should be able to find and use Python. If not,
#8 9.726 npm ERR! gyp ERR! find Python you can try one of the following options:
#8 9.726 npm ERR! gyp ERR! find Python - Use the switch --python="/path/to/pythonexecutable"
#8 9.726 npm ERR! gyp ERR! find Python   (accepted by both node-gyp and npm)
#8 9.726 npm ERR! gyp ERR! find Python - Set the environment variable PYTHON
#8 9.726 npm ERR! gyp ERR! find Python - Set the npm configuration variable python:
#8 9.726 npm ERR! gyp ERR! find Python   npm config set python "/path/to/pythonexecutable"
#8 9.726 npm ERR! gyp ERR! find Python For more information consult the documentation at:
#8 9.726 npm ERR! gyp ERR! find Python https://github.com/nodejs/node-gyp#installation
#8 9.726 npm ERR! gyp ERR! find Python **********************************************************
#8 9.726 npm ERR! gyp ERR! find Python
#8 9.726 npm ERR! gyp ERR! configure error
#8 9.726 npm ERR! gyp ERR! stack Error: Could not find any Python installation to use
#8 9.726 npm ERR! gyp ERR! stack     at PythonFinder.fail (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:330:47)
#8 9.726 npm ERR! gyp ERR! stack     at PythonFinder.runChecks (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:159:21)
#8 9.727 npm ERR! gyp ERR! stack     at PythonFinder.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:202:16)
#8 9.727 npm ERR! gyp ERR! stack     at PythonFinder.execFileCallback (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/find-python.js:294:16)
#8 9.727 npm ERR! gyp ERR! stack     at exithandler (node:child_process:410:5)
#8 9.727 npm ERR! gyp ERR! stack     at ChildProcess.errorhandler (node:child_process:422:5)
#8 9.727 npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
#8 9.727 npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12)
#8 9.727 npm ERR! gyp ERR! stack     at onErrorNT (node:internal/child_process:485:16)
#8 9.727 npm ERR! gyp ERR! stack     at processTicksAndRejections (node:internal/process/task_queues:83:21)
#8 9.727 npm ERR! gyp ERR! System Linux 5.15.49-linuxkit
#8 9.727 npm ERR! gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
#8 9.727 npm ERR! gyp ERR! cwd /app/node_modules/bufferutil
#8 9.727 npm ERR! gyp ERR! node -v v16.19.1
#8 9.727 npm ERR! gyp ERR! node-gyp -v v9.1.0
#8 9.727 npm ERR! gyp ERR! not ok
#8 9.729
#8 9.729 npm ERR! A complete log of this run can be found in:
#8 9.729 npm ERR!     /root/.npm/_logs/2023-02-22T02_35_48_229Z-debug-0.log
------
executor failed running [/bin/sh -c npm install]: exit code: 1

Would appreciate any insight in this, I have no idea why this is happening

A: I was able to solve this by simply stop ignoring the node_modules and removing some steps, but still have no idea why the container can't execute RUN npm install properly.
Dockerfile now:
FROM node:16-alpine

WORKDIR /app

COPY . .

EXPOSE 3000

CMD npm run dev

Was able to access the page from the browser too. If anyone has any idea about the errors when executing the step RUN npm install or any way I can improve my Dockerfile, please post an answer.

A: #8 9.725 npm ERR! gyp ERR! find Python - "python3" is not in PATH or produced an error
#8 9.725 npm ERR! gyp ERR! find Python - "python" is not in PATH or produced an error
#8 9.726 npm ERR! gyp ERR! find Python You need to install the latest version of Python.

npm is complaining that it can't find python installed on your mac.


text:
Q: JWT token - Passcode for private key I am trying to build a JWT token using an online JWT generator located at http://kjur.github.io/jsjws/tool_jwt.html
I understand how a JWT is put together but one thing that is confusing me is a field the form asks for termed a "passcode for private key". I understand what a private key is, however, I am not familiar with a passcode for a private key.
Does anyone know what this is referring to?

A: A PKCS#8 private key can be encrypted with a password using a DES3 or AES symmetric encryption algorithm
The online generator is asking you for a key like this and the corresponding password
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQI9Gl6VRM+2s8CAggA
MBQGCCqGSIb3DQMHBAj5X9pErhcqLgSCBMhbG7htniJ8vUmZRVq8rF00MYp5IbLU
CFwj8yPEizGf9p65yFfxM1YdgsqSpJV2oHSFyZDumXyL1ujmfG1w0VeK8Vw4/T74
ttpo8JAnUI7Z7qS/xi3jbdACJKHCcrGq9QhWikeDdtWn8cCw9EaM5EtybB7ecshu
kJxSPmeenT28GD05aM5tUkExsInZmMJboUDGHaJ6zJQgad1PwIylwWfsmSn4Lw9z
U2MD0PmiqxQ796k4kjrJtQ8is8XCh8u7IFvlaibn/DKTK8WTLJB10KeRQ6TDxqcP
0X25tVN/FIWfHE8KIDdWCo2oYqqWyjWv9cuyoYDR0pmye0Gq3jlMjZcsg0r/DLhU
fqhZ7TxnuPUaS1aJ4MZXuKLR8nBqOalDeI/IXZSGV9ZTNIndqZkTxCPegD6/1Kdg
WCYZ6K3oxn1DCu9IUt/haJ4YSbAC+mEAgApGnVMllxb1W4yHgERpgKcz0cLl8zQ9
KUkB6gTe7upmTQilXJze73w6sP1l6t047EgMiCnleuNElZ/+WYd+B8V6qJ0izKJp
9uZqWu6P+JwlppDhKMfjIIdSwKi+UbtUPTYmu1FN0MzgjEwnp2hTiHwrSKv1LsI3
kgn0ML1xI9eXbU1bNfwydFLi3A725A/S1/eK0gOnzid+vlRJdPgY9kC37Q/EcrqM
auYbY1ThK+iu2d5Dtdkr/L2XQoeHEh7/mCs/J2o50CPl8XvxozDa34FHFG41phGU
6jur0/kejg/QQ9pFAjMPV67xD/D+d3DxAGjs2goqwOHhcvByvuEH5i+fqs8Xmqhh
Xgl2SnYm3mMVXDNE9adqpvWJTl93A8gIJlfZz4rKgJbUJDMYDXTroL+cqiFjeYCZ
U5NRh8c/LYrpG+RWzK0rm9omEf8ja3kSQK5KIsiuMoGwPQ+W0cZ0dZGBntJeM9aH
rM5lgAfVQLPW73ZfoxKYPNMMZ7gIXTRMmoRT3tGG+52mCL8dyS6ry6Ej98DEOJEH
Akc9ejRqiLvoW8D4Qaw79udPVCKpt/wHa7XvPbAq/SskOjuhG3gcMfgsvX+aBmHu
XjkbQFEAUG9t4UC2C12zodn7o5M0/xr2IdLxxWigkh1X20uuVZuonLfxduMjwhjP
qym506o9R9uw6nApw5cZLyJfCkVas5e5KJmjzZThhA0cpG5GdmChtj1ytvNx/PvU
qJGs7M0t00AS75HMB4U4Yte3ZFIac6d/YOZzunPZYhRAivjLuzOnasCX6X+Z4I7P
QLIoprHdYU3tL5kDmtcep/Yh6FKK9yMdSQ9+2nM8KFE1lOsSVPV/NTClFI1s9sEv
4FchPDwsiXhawgHz57N97bORblGchX23BcpPG3mCv23NM/S4cA7RhfQUSzcxZ6SS
/vPqrU1bG56MnbcMF71QqMW3V8aLwl3pKwY28FNuPCg4KpxkE4NM2BtwysiIixBw
l8hUv7x8ZFF1UMc2h0Cxdm0FNt358l2U9LfnjZMSiLdElWjKVDm8ZGz8iEF6EYWM
du9XX2VHkgAbyoeb9m2wBOX79nQ9/lOawUy70gZOXD+alvnfKdyHWxV9Ij90RB0K
HTc28h7Bvn2pmsghGOeHU83cIZ5CWFZns5jOr7AX4WfK+5IEd8ftc896/Iy4XsZ8
gRo=
-----END ENCRYPTED PRIVATE KEY-----


text:
Q: How to block zero byte lock file (An object of Class InputStream)? I have a code as shown and it works successfully. However, on including the commented line       lock =f.tryLock() it throws IOException. This is because of the lock on the file. I dont want the lock files to be read/copied (I need to filter lockfiles from InputStream) and thereby the code should not throw IOException in this case. Can somebody help me on this ?
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;

public class Lock {

  public static void main(String args[]) throws IOException, InterruptedException {
    RandomAccessFile file = null; // The file we'll lock
    FileChannel f = null; // The channel to the file
    FileLock lock = null; // The lock object we hold
    OutputStream out = null;
    InputStream in = null;

    try {
      String tmpdir = System.getProperty("java.io.tmpdir");
      String filename = Lock.class.getName() + ".lock";
      File lockfile = new File(tmpdir, filename);

      file = new RandomAccessFile(lockfile, "rw");
      f = file.getChannel();
     // lock = f.tryLock();
      in = new FileInputStream(lockfile);

      byte[] buffer = new byte[1024];
      if(in.read(buffer)!=0){
      int len = in.read(buffer);
      while (len != -1) {
        out.write(buffer, 0, len);
        len = in.read(buffer); }
        }

      in.close();
      if (lock != null) {
        lockfile.deleteOnExit(); // Just a temporary file
      }

     } catch (IOException e) {
        System.out.println(e);
        throw e;
        }
        finally{
        if (lock != null && lock.isValid())
        lock.release();
        if (file != null)
        file.close();
        }

  }
}

The exception:
java.io.FileNotFoundException: The system cannot find the file specified
Exception in thread "Main Thread" java.io.FileNotFoundException: The system cannot find the file specified
at java.io.FileInputStream.readBytes(FileInputStream.java)
at java.io.FileInputStream.read(FileInputStream.java:198)
at Lock.main(Lock.java:32)

A: If you're reliably getting an IOException of some kind when reading locked files, merely catching it and aborting/cleaning up the copy appears to completely solve your problem. You have to do that anyway on any IOException, not just this one, so there's nothing special about this situation.
InputStream.available() doesn't have anything to do with either file locks or file sizes. See the Javadoc.


text:
Q: How can I create a dynamic proxy out of a List I'm using Castle Dynamic Proxy CreateClassProxyWithTarget using an already existing list. Basically, I'd like to to intercept the calls being made to the list indexer.
I've tried a bunch of combination to achieve this goal but each time the created proxy returns an empty list.
For example :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.DynamicProxy;

namespace DP
{
    class Program
    {
        private static readonly ProxyGenerator _generator = new ProxyGenerator(new PersistentProxyBuilder());

        static void Main(string[] args)
        {
            ListString ls = new ListString();
            ls.Add("hello");

            List<string> ls2 = (ListString)_generator.CreateClassProxyWithTarget(typeof(ListString), ls, new Interceptor());

            var x = ls2[0];
        }
    }

    public class ListString : List<String>
    {
        public ListString() : base() { }
        public ListString(IEnumerable<String> strings) : base(strings) { }
    }
}

Please help! It's driving me mad ! I tried Castle 3.2 and 2.5, none of them seem to work. I can achieve good result with "normal" objects.

A: Indexer on List<T> is not virtual and cannot be intercepted by DynamicProxy.
You can proxy IList<T> instead.


text:
Q: Fsharp.data "Illegal characters in path" I'm just getting started in F# and was exploring FSharp.Data. I'm trying to use a web service from www.ncdc.noaa.gov. The first problem is ncdc wants a token in the request. I attempted to work around that with the following:
let apiUrl = "http://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&locationid=ZIP:28801&startdate=2010-04-01&enddate=2010-04-01"
    let aRequestString =
            Http.RequestString(
                apiUrl,
                httpMethod="GET",
                headers = [ "token", "mytoken"])
    let sf = WeatherData.Load(aRequestString)

This seems to work - fiddler says I get a result that looks good to me and JSONLint, but I get "Illegal characters in path." from the provider.
The stack trace shows:
System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
System.IO.Path.Combine(String path1, String path2)
FSharp.Data.Runtime.IO.UriResolver.Resolve(Uri uri)
FSharp.Data.Runtime.IO.asyncRead(FSharpOption`1 _tp, UriResolver uriResolver, String formatName, String encodingStr, Uri uri)
FSharp.Data.Runtime.IO.asyncReadTextAtRuntime@238.Invoke(Uri uri)

A: The Load method takes a URL or a file path and it loads data from there. If you're downloading the data on your own, you need to use the Parse method instead.
let apiUrl = "http://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=...."
let aRequestString =
        Http.RequestString(
            apiUrl,
            httpMethod="GET",
            headers = [ "token", "mytoken"])
let sf = WeatherData.Parse(aRequestString)
//                   ^^^^^


text:
Q: Double integration in polar coordinates between two circles I am trying to integrate converting to polar coordinates, between two circles.
$$A = \iint_D x \,\mathrm{d}A $$
Ant the domain of integration is set to be the region in the first quadrant between the circles:
$x^2 + y^2 = 4$ and $x^2 + y^2 = 2x$
I have plotted the circles, and I suppose the region I am being asked for is what I have painted in red:

Now, I would know how to proceed if one circle was perfectly inside of the other (same center), I would set $\theta$ to be between $0$ and $\pi / 4$ and $r$ to be between the radius of the smallest circle and the radius of the other one. However, I cannot do any of those here.
So how should I convert this integral to a polar-coordinate integral?
Any help would be very appreciated.

A: For circle one, the equation is simply
$$C_1: r=2$$
For circle two $x^2+y^2=r^2,\quad x=r\cos\theta$, so
$$C_2: r^2=2r\cos\theta \implies r(r-2\cos\theta)=0 \implies r=0,r=2\cos\theta$$
Of these only the second solution is useful (the first just says $C_2$ passes through the origin), so the inner and outer radii for the integral are $2\cos\theta$ and $2$, respectively. And $\theta$ varies from $0$ to $\pi/2$ in the first quadrant.
Since $dA=r\,dr\,d\theta$, we get
$$A=\int_{0}^{\pi/2}{\int_{2\cos\theta}^{2}{r}\,dr\,d\theta}$$
(The original integral for area should have been $A=\iint{dA}$.)

If $I=\iint{x\,dA}$ is required, then from $x=r\cos\theta$
$$I=\int_{0}^{\pi/2}{\int_{2\cos\theta}^{2}{r^2\cos\theta}\,dr\,d\theta}$$


text:
Q: How to stop a mask-image from overlaying a div? How do I make the div maintain its background color? I added a red-white gradient to show what I mean. When its background is colored it works as-is on top of the background image. However, once I set it to white the background image bleeds through and the div apparently becomes transparent.
I have tried setting the opacity for the div, changing the z index as well. It's my first time using mask-image so ik that is causing it, I just am not sure how to make it work.

A: Your post seems to suggest you added the red to white graident for example only so I am unsure what the background is meant to be. But.... background: linear-gradient(to right, red, white 50%); is making the gradient in your div cover only 50% of it from the left hand side. You could change that to 100% and it should go from red to white all the way across from left to right..... Is my best suggestion from what you have posted.


text:
Q: Negative correlation between regression residual and predicted value In multiple regression, the residual plots show a negative relation between the residual and the predicted value. What does it mean? How should I address this issue?
Here is an image, to help explain the situation. Thanks again for the help!

A: My guess is something's amiss.  By "negative relation" I assume that you are seeing what looks like negative correlation.  But, perhaps what looks like negative correlation is not really negative correlation because of (for example) overlapping points in your plot.  If you are fitting a multiple linear regression with the usual loss function (least squares), then there should be no correlation between the residuals and the predicted values.

A: In the bottom-left corner of the top-left plot (predicted vs residuals) you have a single large outlier. This point looks like it's distorting your fitted trend.
Interestingly, the predicted value and residual are both about -8, so the observed response is about 0 -- which would be in the middle of the distribution of the response.


text:
Q: MYSQL How to grant all privileges to user only to the databases which he created? im creating a few users:
user1
user2
user3
i want to give them ALL PRIVILEGES to the bases(creating/removing) inside their account
i want them to see and affect databases only inside their account...
how should i do this with shell ?

A: Do you allow users to run CREATE DATABASE ...?
Don't allow a user to run that SQL.  Instead, provide a STORED PROCEDURE to create the database for him and provide permissions to him.  The trick is to be root when you define the SP and use SQL SECURITY DEFINER.  And have GRANT ALL PRIVILEGES ON dbname.* TO user@...  (with the pieces suitably filled in).


text:
Q: Why does cooking.sty produce empty output (and overfull hboxes)? For a few years, I've been using the cooking package to create a nice book with recipes.
Some time ago, the resulting PDF started to be empty, only the TOC is readable, the rest is a white page. What could it be?
\documentclass{scrartcl}
\usepackage{cooking}
\pagestyle{recipe}

\begin{document}
\tableofcontents

\section{Salate}
\begin{recipe}{Salade Olivier}

\ingredient{Eine kleine  Zwiebel} \ingredient{fünf größere Essiggurken} und
\ingredient{Kapern} fein Hacken. \ingredient{500g Schinken}
in kleine Quadrate schneiden. \ingredient{Vier Eier} hart
kochen. \ingredient{ca. zehn große Kartoffeln} kochen und pellen. Eier und
Kartoffeln würfeln. Alles zusammen mit \ingredient{einer Dose Erbsen} in eine große Schüssel geben.
\end{recipe}
\end{document}

Just as I wanted to attach the log of building mini.pdf, I saw that there are massively overfull hboxes:
Running `LaTeX' on `mini' with ``pdflatex -shell-escape  -interaction=nonstopmode "\input" mini.tex''
This is pdfTeX, Version 3.14159265-2.6-1.40.17 (TeX Live 2016/Debian) (preloaded format=pdflatex)
 \write18 enabled.
entering extended mode
LaTeX2e <2016/03/31> patch level 3
Babel <3.9r> and hyphenation patterns for 8 language(s) loaded.
(./mini.tex (/home/markus/texmf/tex/latex/koma-script/scrartcl.cls
Document Class: scrartcl 2015/04/02 v3.17.2062 KOMA-Script document class (article)
(/home/markus/texmf/tex/latex/koma-script/scrkbase.sty
(/home/markus/texmf/tex/latex/koma-script/scrbase.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty)
(/home/markus/texmf/tex/latex/koma-script/scrlfile.sty
Package scrlfile, 2015/04/02 v3.17.2062 KOMA-Script package (loading files)
                  Copyright (C) Markus Kohm

))) (/home/markus/texmf/tex/latex/koma-script/tocbasic.sty)
(/home/markus/texmf/tex/latex/koma-script/scrsize11pt.clo)
(/home/markus/texmf/tex/latex/koma-script/typearea.sty
Package typearea, 2015/04/02 v3.17.2062 KOMA-Script package (type area)
                  Copyright (C) Frank Neukam, 1992-1994
                  Copyright (C) Markus Kohm, 1994-

)) (/usr/share/texlive/texmf-dist/tex/latex/cooking/cooking.sty) (./mini.aux)
(./mini.toc)
Overfull \hbox (2481.99472pt too wide) in paragraph at lines 9--9
[]\OT1/cmr/m/it/12 Salade |

Overfull \hbox (2483.9448pt too wide) in paragraph at lines 9--9
\OT1/cmr/m/it/12 Olivier  |

Overfull \hbox (2448.99443pt too wide) in paragraph at lines 11--11
[]|

Overfull \hbox (2448.99443pt too wide) in paragraph at lines 11--11
|

Overfull \hbox (2448.99443pt too wide) in paragraph at lines 11--12
[]|

Overfull \hbox (2467.24446pt too wide) in paragraph at lines 11--12
\OT1/cmr/m/n/10.95 und |

Overfull \hbox (2448.99443pt too wide) in paragraph at lines 12--12
[]|

Overfull \hbox (2466.33195pt too wide) in paragraph at lines 12--12
\OT1/cmr/m/n/10.95 fein|

Overfull \hbox (2486.71112pt too wide) in paragraph at lines 12--12
\OT1/cmr/m/n/10.95 Hacken. |

And so on for many lines ...
Overfull \hbox (2461.22194pt too wide) in paragraph at lines 15--16
\OT1/cmr/m/n/10.95 sel|

Overfull \hbox (2479.7153pt too wide) in paragraph at lines 15--16
\OT1/cmr/m/n/10.95 geben. |
[1{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}] [2] (./mini.aux) )
(see the transcript file for additional information)</usr/share/texlive/texmf-dist/fonts/type1/public/amsfonts/cm/cmr10.pfb></usr/share/texlive/texmf-dist/fonts/type1/public/amsfonts/cm/cmssbx10.pfb></usr/share/texlive/texmf-dist/fonts/type1/public/amsfonts/cm/cmti10.pfb></usr/share/texlive/texmf-dist/fonts/type1/public/amsfonts/cm/cmti12.pfb>
Output written on mini.pdf (2 pages, 49544 bytes).
Transcript written on mini.log.

Can you help me to print my recipes again? All I can offer is the German text of really delicious food ;)

A: Well, KOMA-Script adds some more functionality that standard class article has.
With an current MiKTeX 2.9 and the current KOMA-Script version 2016/06/14 v3.21 I can compile your given code with only one, IMHO very clear warning:
Class scrartcl Warning: incompatible usage of \@ssect detected.
(scrartcl)              You've used the KOMA-Script implementation of \@ssect
(scrartcl)              from within a non compatible caller, that does not
(scrartcl)              \scr@s@ct@@nn@m@ locally.
(scrartcl)              This could result in several error messages on input line 11.

Your used version of KOMA-Script seems to be outdated: your log file tells us: 2015/04/02 v3.17.2062
It seems (I can not test it, I have not that old version of KOMA-Script) that that old KOMA-Script and package cooking have a problem to work together.
Please update your system to get the current KOMA-Script.
Please add \listfiles as first command of your TeX code, compile three times and compare the resulting list of used packages including version numbers (sic!) with my list:
 *File List*
scrartcl.cls    2016/06/14 v3.21 KOMA-Script document class (article)
scrkbase.sty    2016/06/14 v3.21 KOMA-Script package (KOMA-Script-dependent basics and keyval usage)
 scrbase.sty    2016/06/14 v3.21 KOMA-Script package (KOMA-Script-independent basics and keyval usage)
  keyval.sty    2014/10/28 v1.15 key=value parser (DPC)
scrlfile.sty    2016/06/14 v3.21 KOMA-Script package (loading files)
tocbasic.sty    2016/06/14 v3.21 KOMA-Script package (handling toc-files)
scrsize11pt.clo    2016/06/14 v3.21 KOMA-Script font size class option (11pt)
typearea.sty    2016/06/14 v3.21 KOMA-Script package (type area)
 cooking.sty    1999/06/24 v0.9b Cooking recipes
 ***********

I'm sure you will see the differences at once.
Btw that is the resulting pdf on my computer:


text:
Q: Get container behind std::stack I am using a std::stack to keep a list of possibilities in my program.
std::stack<int, std::deque<int> > myStack;

Now, for debugging purposes only, I want to have access to all the elements of my std::stack (for instance as a std::deque). But the following syntax is illegal:
std::deque<int> myDeque = myStack; // Does not compile

What is the simplest way to do it?

The way I would do it is:
std::stack<int, std::deque<int> > newStack = myStack;
std::deque<int> myDeque;
while(!newStack.empty()){
    myDeque.push_back(newStack.top());
    newStack.pop();
}

but it looks a bit ugly.

A: Adding to Maxim's answer (not enough rep to comment):
std::stack doesn't have a virtual destructor, so attempting to delete MyStack from a base-class pointer to std::stack is unsafe. You can decide to trust that your compiler will generate warnings in these cases, or use private inheritance to prevent this scenario in most cases.
template<class T, class C>
struct MyStack : private std::stack<T, C>
{
    typedef std::stack<T, C> Stack;
    using Stack::Stack;
    using Stack::operator=;
    using Stack::c; // expose as public
    // Private inheritance, explicitly forward functions we need
    using Stack::size;
    using Stack::push;
    using Stack::pop;
    // etc
};

A: The underlying container of std::stack is accessible as protected member c. Hence:
template<class T, class C>
struct MyStack : std::stack<T, C>
{
    typedef std::stack<T, C> Stack;
    using Stack::Stack;
    using Stack::operator=;
    using Stack::c; // expose as public
};

And if you cannot change definitions and recompile, then:
template<class T, class C>
C& get_underlying_container(std::stack<T, C>& s) {
    static_assert(sizeof s == sizeof(MyStack<T, C>), "Size mismatch.");
    static_assert(alignof s == alignof(MyStack<T, C>), "Alignment mismatch.");
    return static_cast<MyStack<T, C>&>(s).c;
}


text:
Q: Help understanding a lemma on modules over a PID.
Lemma 1.84
Let $R$ be a PID. Suppose that $M\simeq R/(a)$ where $a$ is a nonzero element of $R$. Moreover, suppose $p$ is an irreducible element of $R$. Then
(a) If $p\nmid a \implies M_p=\{0\}$ and $pM=M\simeq R/(a)$.
(b) If $p\mid a \implies M_p\simeq R/(p)$ and $pM\simeq R/(a/p)$

The proof for part (a) is:

Proof.  Suppose $p\nmid a$. Then since $p$ is irreducible, $p$ and $a$ are relatively prime. Also $aM=\{0\}$. Hence, $paM=\{0\}$. Thus
  $$ aM=M_p \text{ and } pM=M_a $$
  and
  $$ M=M_a\oplus M_p$$
  as proven before if $a$ and $p$ are relatively prime.
So $$M_p=aM=\{0\}$$
  Also $M=M_a\oplus M_p=M_a\oplus\{0\}=M_a$ and so
  $$pM=M_a=M\simeq R/(a).$$

The definition for $aM$ and $M_a$ is:
$$aM=\{ax:x\in M\} \text{ and } M_a=\{x\in M:ax=0\}$$
My only question for the above proof is how come $aM=\{0\}$? I was playing around with the assumptions, and I've failed to conclude why we can say that.
Any help is much appreciated.


text:
Q: Php don't send empty value I've created a code that updates an Sql entry, but when you leave an value blank, it removes the existing value.
<?php
$servername = "localhost";
$username = "root";
$password = "HahahNo";
$dbname = "DATA";
$id = $_POST["id"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET firstname='$firstname', lastname='$lastname', email='$email' WHERE id=$id";

if ($conn->query($sql) === TRUE) {
    echo "Success";
} else {
    echo "Error updating record: " . $conn->error;
}
?>

Is there any way not to clear the not filled in values? Im fairly new to php.

A: Check if $_POST contains values.
First check if $_POST value has been set with isset() (has been posted).
Then check if the string isn't empty with strlen():
if (!isset($_POST['firstname'] || strlen($_POST['firstname']) == 0) {
    echo 'Please enter first name';
} else {
    // Do your DB update
}

Edit: Naturally empty() is better because you only need one check to do:
if (empty($_POST['firstname']) {
    echo 'Please enter first name';
} ...

Thanks to @Fred -ii-
Edit II: As pointed out by @alex
if ($_POST['firstname']) {
    echo 'Please enter first name';
} ...

would work too. Explained in PHP type comparison tables

A: What you're looking for is validation of user-supplied data. You're right - a user who hasn't read the instructions of your form could cause unintended data loss. Additionally a malicious user or innocent child could cause more harm with SQL injection.
First check your field meets minimum requirements. You could validate email addresses, postcodes, phone numbers, URLs... but to answer your question Daenu's answer is perfect.
Once you are satisfied the data meets your databases' requirements, check it is safe. Strip it of any malicious SQL commands. You can use prepared statements with PDO or MySQLi.
Also think about the specification of the data. Is the data type of each field a string or integer or float? What character set is your web page in (UTF-8 is a safe choice) and therefore what character set does your data arrive with? Does your database match (UTF8MB4 is a good companion)?

A: You can write condition before execute function,
//all values are not null then update is perform
    if(!is_null($firstname) && !is_null($lastname) &&  !is_null($email)){
      if ($conn->query($sql) === TRUE) {
        echo "Success";
      } else {
        echo "Error updating record: " . $conn->error;
      }
    }


text:
Q: Prevent frontmatter to reset counting I would like to keep the same numbering throughout the whole document. But frontmatter and mainmatter are resetting the numbering. How can I prevent this behaviour?
\documentclass[oneside,12pt]{book}
\usepackage[french]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\begin{document}
\frontmatter
Some text here.
\mainmatter
\chapter{chapter1}
\chapter{chapter2}
\chapter{chapter3}
\chapter{chapter4}
\backmatter
\chapter{annexe}
\end{document}

A: The cleanest way is to redefine the commands: add
\makeatletter
\renewcommand\frontmatter{%
  \cleardoublepage
  \@mainmatterfalse
  %\pagenumbering{roman}% Don't reset
}
\renewcommand\mainmatter{%
  \cleardoublepage
  \@mainmattertrue
  %\pagenumbering{arabic}% Don't reset
}
\makeatother

before \begin{document}.
As you see, redefining \pagenumbering to do nothing, as suggested in another answer, would work. But maybe somebody could ask you to number differently the appendix…

A: The markup commands \frontmatter and \mainmatter use \pagenumbering to change the number style and reset the page number. It can be redefined to do nothing:
\renewcommand*{\pagenumbering}[1]{}

A: If you want to preserve the roman vs. arabic numbering that \frontmatter and  \mainmatter implement, then you can do the following.
\makeatletter
\renewcommand\mainmatter{
    \@mainmattertrue\cleardoublepage\renewcommand\thepage{\arabic{page}}}
\makeatother

If you want arabic numbering throughout, then egreg's answer works fine.


text:
Q: Когда и кем создается PSP (Program Segment Prefix)? Когда и кем (программа) создается PSP? Посмотрел книгу Финогенова, там написано, что создается "системой", но данная формулировка ничего не прояснила. И еще вопрос касаемо наличия этого самого PSP в файлах СОМ и ЕХЕ. PSP создается после загрузки в память или в файле ЕХЕ все-таки он есть?

A: @azaznioo, буквально как написано у Финогенова - блок PSP создается операционной системой DOS при загрузке исполняемого файла в память - для этого на ассемблере при создании COM файла и выполняется команда org 100h - чтобы система эти 100h (256) байт заполнила PSP, а дальше уже загрузилась сама программа.
Касательно наличия этого блока в EXE - он создается, но находится не непосредственно перед кодом/данными программы, а совершенно в другом месте. Адрес его сегмента при запуске программы лежит в ds, а смещение можно получить с помощью функции 62h прерывания 21h, результат будет находиться в регистре bx.
Статья на Википедии.
A: Предыдущий ответ немного неверный.
Для EXE программ PSP находится где то до данных и кода. Да, при запуске программы его сегмент находится в регистре DS. Когда выполняется стартовый код, обычно значение этого регистра DS изменяется на сегмент данных (или DGROUP) и потом его можно узнать вызвав функцию DOS 51h или 62h, которая вернет сегмент PSP в регистре BX. А смещение равно 0. Иными словами:
; получаем сегмент PSP
mov ah,51h  ; 62h тоже самое
int 21h
; адрес нашего PSP = BX:0


text:
Q: how to visualize binomial theorem geometrically? How does $ \binom{n}{k} $ 'n choose k' get involved with coefficient of $ (a+b)^n $. Is there any intuitive geometrical picture (interpretation) that it seems obvious?

A: Hint: Imagine writing $(a+b)^n$ as $(a+b)(a+b)\dots(a+b)$, and then multiplying out all the brackets. Ask yourself how many ways you can get a term involving $a^kb^{n-k}$.

A: Expanding on what Old John wrote, it might help to consider a "noncommutative" version of the binomial theorem.  $(a+b)^n = (a+b)(a+b)...(a+b)$ is going to have $2^n$ terms.  Each of the $2^n$ words of length $n$ consisting of the letters $a$ and $b$ will occur exactly once.  If you identify words via commutativity of multiplication, you will see there are $\binom{n}{k}$ words in the equivalence class of $a^{n-k}b^k$.

A: Here is how you visualize binomial theorem
https://upload.wikimedia.org/wikipedia/commons/4/47/Binomial_theorem_visualisation.svg


text:
Q: How do i prevent html/javascript code from running on a textbox I have a chat application wirtten in javascript, when a user enters an html code like
 <button>click</button>

a button appears on chat. I use this code
 if(message.indexOf('<button') != -1)
            {
              message = message.replace(message, '-');
            }

but this just replaces the < button
with a blank space, I want it to be displayed  as text and not an actual button.
Thanks

A: I just use this:
message = message.replace(/</g,"<");

That's all that's needed to prevent HTML from being inserted.

A: Your general encode procedure here would be:
value = value.toString().replace(/</g, "<").replace(/>/g, ">").replace(/'/g, "'").replace(/"/g, """);

A: what html element did you use for print the chat? try use textarea or pre tag.
try to control those errors in the back end because everybody can deactivate javascript.


text:
Q: Como eu seto uma value de um radio no jquery para o php O codigo para ver o radio é esse
//Começo para mostrar a carta 1 do jogador 1
        var $carta1 = $("Carta1	");
        $(".carta1").append($carta1);

//Começo do Ajax da carta que vai mostrar numero 1
         $.ajax({
                    type: "POST",
                    url: "carta1.php",
                    data: {data:novacarta},
                    success: function(html) {
                    $(".carta1_1").append(html);
                    }
                    });
//Fim do Ajax que vai mostrar carta numero 1
//Fim da mostra da carta 1 do jogdor 1

o codigo da carta1.php é esse aqui
include ('../../../../funcoes/conexao.php');
$sqlCartas = "SELECT * FROM maos";
$resultado = mysql_query($sqlCartas) or die (mysql_error());

$carta = $_POST["data"];

<input type="radio" name="carta1" id="radio49" value="ac.gif" />

    <input type="radio" name="carta1" id="radio50" value="ao.gif" />

    <input type="radio" name="carta1" id="radio51" value="ap.gif" />

    <input type="radio" name="carta1" id="radio52" value="as.gif" />

    <input type="radio" name="carta1" id="radio" value="2c.gif" />

    <input type="radio" name="carta1" id="radio2" value="2o.gif" />

    <input type="radio" name="carta1" id="radio3" value="2p.gif" />

    <input type="radio" name="carta1" id="radio4" value="2s.gif" />

    <input type="radio" name="carta1" id="radio5" value="3c.gif" />

    <input type="radio" name="carta1" id="radio6" value="3o.gif" />

    <input type="radio" name="carta1" id="radio7" value="3p.gif" />

    <input type="radio" name="carta1" id="radio8" value="3s.gif" />

    <input type="radio" name="carta1" id="radio9" value="4c.gif" />

    <input type="radio" name="carta1" id="radio10" value="4o.gif" />

    <input type="radio" name="carta1" id="radio11" value="4p.gif" />

    <input type="radio" name="carta1" id="radio12" value="4s.gif" />

    <input type="radio" name="carta1" id="radio13" value="5c.gif" />

    <input type="radio" name="radio" id="radio14" value="5o.gif" />

    <input type="radio" name="carta1" id="radio15" value="5p.gif" />

    <input type="radio" name="carta1" id="radio16" value="5s" />

    <input type="radio" name="carta1" id="radio17" value="6c.gif" />

    <input type="radio" name="carta1" id="radio18" value="6o.gif" />

    <input type="radio" name="carta1" id="radio19" value="6p.gif" />

    <input type="radio" name="radio" id="radio20" value="6s.gif" />

    <input type="radio" name="carta1" id="radio21" value="7c.gif" />

    <input type="radio" name="carta1" id="radio22" value="7o.gif" />

    <input type="radio" name="carta1" id="radio23" value="7p.gif" />

    <input type="radio" name="radio" id="radio24" value="7s.gif" />

    <input type="radio" name="carta1" id="radio25" value="8c.gif" />

    <input type="radio" name="carta1" id="radio26" value="8o.gif" />

    <input type="radio" name="carta1" id="radio27" value="8c.gif" />

    <input type="radio" name="carta1" id="radio28" value="8s.gif" />

    <input type="radio" name="carta1" id="radio29" value="9c.gif" />

    <input type="radio" name="carta1" id="radio30" value="9o.gif" />

    <input type="radio" name="carta1" id="radio31" value="9p.gif" />

    <input type="radio" name="carta1" id="radio32" value="9s.gif" />

    <input type="radio" name="carta1" id="radio33" value="10c.gif" />

    <input type="radio" name="carta1" id="radio34" value="10o.gif" />

    <input type="radio" name="carta1" id="radio35" value="10p.gif" />

    <input type="radio" name="carta1" id="radio36" value="10s.gif" />

    <input type="radio" name="carta1" id="radio37" value="jc.gif" />

    <input type="radio" name="carta1" id="radio38" value="jo.gif" />

    <input type="radio" name="carta1" id="radio39" value="jp.gif" />

    <input type="radio" name="carta1" id="radio40" value="js.gif" />

    <input type="radio" name="carta1" id="radio41" value="qc.gif" />

    <input type="radio" name="carta1" id="radio42" value="qo.gif" />

    <input type="radio" name="carta1" id="radio43" value="qp.gif" />

    <input type="radio" name="carta1" id="radio44" value="qs.gif" />

    <input type="radio" name="carta1" id="radio45" value="kc.gif" />

    <input type="radio" name="carta1" id="radio46" value="ko.gif" />

    <input type="radio" name="carta1" id="radio47" value="kp.gif" />

    <input type="radio" name="carta1" id="radio48" value="ks.gif" />
    </td


text:
Q: restart/reset and replay a transition css? I need to replay a css transition using javascript.
When I reset css style of my div and apply the new transition, nothing happens...
I think both code are executed in the same execution frame and by optimisation, it doesn't change anything...
Example : https://jsfiddle.net/f0s8a8jp/2/
test.css({transition: 'none', height: '0px'});
test.css({transition: 'height 1s linear', height: '100px'});

The only solution I found for the moment (not realy clean for me), is to use setTimeout beetween the properties reset and the application of new transition : https://jsfiddle.net/f0s8a8jp/3/
Better idea is welcome?!

A: The transition will apply on the computed dimension of the element. Setting the CSS property does not compute it. So, setting forth and back the property is like letting it unchanged. It's computed when the browser need to reflow the element.
setTimeout will eventually let the time to the browser to compute a reflow in the meanwhile. You could use requestAnimationFrame to achieve the same without flickering.
Another hack consists in forcing the browser to reflow right after altering the CSS properties, using test[0].offsetWidth; for instance.
The transition is then performed correctly: https://jsfiddle.net/f0s8a8jp/9/
A more in-depth discussion about reflow (and repaint) can be found here: http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/

A: Try this:
https://jsfiddle.net/f0s8a8jp/4/
I made it work on click, so you need to click on it to see the result.
The only thing I really changed was the order of the code.


text:
Q: jquery: switch chosen selectbox selected value on click i want to interchange the value from one selectbox to another using jquery,
MY selectbox is in the form of http://harvesthq.github.io/chosen/
Example:
say i have 2 dropdown selectbox,in first i have selected USD & on second i have selected EURO  , on click of switch button both the selectbox selected value & level should interchange
http://jsfiddle.net/34kcb/  (without chosen effect, works fine)
I tried below code but its now giving me what i am looking for, so may be you can help me
$("body").on("click", "#switchid", function(){
               var frm='';var to='';
               frm=$("#from_currency option:selected").val();
               to=$("#to_currency option:selected").val();
               $("#to_currency").val(frm);
              $("#from_currency").val(to);
              //currencyConverter();
  });

HTML code
 <select name="from_currency" id="from_currency">
                  <option value="USD">USD : United States Dollar</option>
                  <option value="EUR">EUR : Euro</option>
                  <option value="JPY">JPY : Japanese Yen</option>
                  <option value="INR">INR : Indian Rupee</option>
     </select>

    <select name="to_currency" id="to_currency">
                  <option value="EUR">EUR : Euro</option>
                  <option value="USD">USD : United States Dollar</option>
                  <option value="JPY">JPY : Japanese Yen</option>
                  <option value="INR">INR : Indian Rupee</option>
     </select>

<input type="button" id="switchid" value="Switch"/>

UPDATE:
In simple selectbox its working but after integrating with Choosen selectbox  ,same thing is
not working . any idea?

A: Try this:
$("body").on("click", "#switchid", function(){
  var frm = '';
  var to ='';
  frm = $("#from_currency").val();
  to = $("#to_currency").val();
  $("#to_currency").val(frm);
  $("#from_currency").val(to);
  $("#from_currency, #to_currency").trigger("chosen:updated");
});

Working here: http://jsfiddle.net/H5x5u/
You don't need to select the option:selected, the .val() jQuery does that for you.

A: try this one
$("#switchid").on("click", function(){
          var frm = '';
          var to ='';
          frm = $("#from_currency").val();
          to = $("#to_currency option:selected").val();
          $("#to_currency").val(frm);
          $("#from_currency").val(to);
          $("#from_currency, #to_currency").trigger("chosen:updated");
        });

The last line " $("#from_currency, #to_currency").trigger("chosen:updated");" should trigger chosen to update. I haven't tested this though, as I don't have chosen (or time at the moment)! :)

A: $("body").on("click", "#switchid", function(){
 var firstDropDownValue = $("#from_currency option:selected").attr('selected','selected').val();
 var secondDropDownValue = $("#to_currency option:selected").attr('selected','selected').val();
var afterSwitchFirstValue = $("#from_currency").val(secondDropDownValue);
var afterSwitchSecondValue = $("#to_currency").val(firstDropDownValue);
  });

pl chk the answer in http://jsfiddle.net/34kcb/2/ and the value is interchanging in selectbox its working as you need..


text:
Q: Filters - Ignore the other requests excluding the welcome file I wrote a filter to decide user landing page before it reach my welcome-file. The welcome-file is written in such a way that it takes input from the filter and navigate the user to a specific page.
My welcome-file tag is...
<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

and my filter configuration is
<filter>
    <filter-name>LandingPageFilter</filter-name>
    <filter-class>com.mypack.test.filters.LandingPageFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>LandingPageFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

The above format is working good whilst every request is passing through this filter, which I want to avoid. When I hit http://localhost:8000/landing it should reach the filter for the first time only and later even if I access http://localhost:8000/landing/edit it should actually execute the relevant servlet bypassing the filter.
I tried this as well <url-pattern>/*/index.jsp</url-pattern> but no use. Why I use this because the context may vary but the app would be same.

A: Use
<url-pattern>/index.jsp</url-pattern>
instead of
<url-pattern>/*/index.jsp</url-pattern>
So your filter mapping part will become like this
<filter-mapping>
    <filter-name>LandingPageFilter</filter-name>
    <url-pattern>/index.jsp</url-pattern>
</filter-mapping>

Irrespective of the context this works because / represents the path after the context path.
For example if you have two context paths say a and b with two deployments of same application in your server and you are accessing them using the URLs
http://localhost:8000/a/
and
http://localhost:8000/b/
then / in the url-pattern represents / after context roots a and b. So your filter will be executed only for index.jsp.


text:
Q: Diskfilter writes are not supported > What triggers this error? This message occurs when leaving the Grub menu and before the Ubuntu splash screen.
How do I fix the problem to clear the message?
And what doe is it mean?
error:  Diskfilter writes are not supported

System boots and seems to work just fine.

A: I think this error occur because of raid or LVM partition .
For a temporary fix for this problem  :
Edit :/etc/grub.d/10_linux
Replace 'quick_boot="1"' with 'quick_boot="0"'
Then :
sudo update-grub

A: It's a BUG!
This is a bug that occurs in the most recent version of Ubuntu Server LTS (Ubuntu Server 14.04 LTS), when you create the boot partition (or the root partition, when the boot partition doesn't exists) inside a LVM or a RAID partition.
You can get more info about this bug in Ubuntu Launchpad: Bug #1274320 "Error: diskfilter writes are not supported".
Update: This bug is already fixed in Ubuntu Server 14.04 and some newer Ubuntu versions. Probably, you only need to run apt-get upgrade.
Why does this bug occur?
When the system is booting, GRUB reads (load_env) data in /boot/grub/grubenv. This file is called GRUB Environment Block.
From the GRUB Manual:

It is often useful to be able to remember a small amount of information from one boot to the next.
[...]
At boot time, the load_env command (see load_env) loads environment variables from it, and the save_env (see save_env) command saves environment variables to it.
[...]
grub-mkconfig uses this facility to implement GRUB_SAVEDEFAULT

This behavior can be founded in /etc/grub.d/00_header (update-grub uses this file to generate the /boot/grub/grub.cfg file):
if [ -s $prefix/grubenv ]; then
  set have_grubenv=true
  load_env
fi

The problem is that the save_env statement only works in simple installations (you can't run save_env inside a RAID or LVM disk). From the GRUB manual:

For safety reasons, this storage is only available when installed on a plain disk (no LVM or RAID), using a non-checksumming filesystem (no ZFS), and using BIOS or EFI functions (no ATA, USB or IEEE1275).

The GRUB recordfail feature uses the save_env statement to update the recordfail state (see Ubuntu Help - Grub 2, "Last Boot Failed or Boot into Recovery Mode" section). However, in Ubuntu 14.04 (and in recent Debian versions), the save_env statement (inside the recordfail feature) is used even if GRUB is installed in a LVM or a RAID.
Let's see the lines from 104 to 124 in /etc/grub.d/00_header:
if [ "$quick_boot" = 1 ]; then
    [...]
    case "$FS" in
      btrfs | cpiofs | newc | odc | romfs | squash4 | tarfs | zfs)
    cat <<EOF
  # GRUB lacks write support for $FS, so recordfail support is disabled.
  [...]
  if [ -n "\${have_grubenv}" ]; then if [ -z "\${boot_once}" ]; then save_env recordfail; fi; fi

GRUB correctly skips the recordfail feature when using unsupported filesystems (btrfs, zfs, etc), but it doesn't skip LVM and RAID at any moment.
How does GRUB protect itself from writing inside RAID and LVM?
To read/write correctly in a filesystems, GRUB loads an appropriate module.
GRUB uses the diskfilter module (insmod diskfilter) in RAID partitions, and the lvm module in LVM partitions.
Let's see the read/write implementation of the diskfilter module:
apt-get source grub2
vim grub2-2.02~beta2/grub-core/disk/diskfilter.c

I'm pasting the code here (lines from 808 to 823). The warning showed in this question appears at line 821:
static grub_err_t
grub_diskfilter_read (grub_disk_t disk, grub_disk_addr_t sector,
                  grub_size_t size, char *buf)
{
  return read_lv (disk->data, sector, size, buf);
}

static grub_err_t
grub_diskfilter_write (grub_disk_t disk __attribute ((unused)),
             grub_disk_addr_t sector __attribute ((unused)),
             grub_size_t size __attribute ((unused)),
             const char *buf __attribute ((unused)))
{
  return grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
                 "diskfilter writes are not supported");
}

The grub_diskfilter_read function is implemented (and GRUB can read RAID filesystems). However, the grub_diskfilter_write function raises a GRUB_ERR_NOT_IMPLEMENTED_YET error.
Why does using quick_boot=0 solve the problem? And why is it the wrong solution?
If you look one more time in the /etc/grub.d/00_header code, you will see that the recordfail featured is only used when quick_boot=1. So, changing quick_boot from 1 to 0 disables the recordfail feature, and disables writes in the RAID/LVM partition.
However, it'll disable many other features too (run grep \$quick_boot /etc/grub.d/* and you'll see). More yet, if one day you change your /boot/grub directory to outside the RAID/LVM, the recordfail feature will still disabled.
Summarily, this solution unnecessarily disables features, and it's not generic.
What is the correct solution?
The correct solution should consider disable the save_env statements when GRUB is inside LVM or RAID partitions.
One patch was proposed in the Debian Bug Tracker system to implement this solution. It can be found in: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=754921
The idea behind this patch is:

*

*Run a grub-probe --target=abstraction "${grubdir}" command to get what kind of abstraction modules GRUB uses to read/write files in the /boot/grub directory;

*If GRUB uses the diskfilter or lvm module, skip the recordfail save_env statement and write an appropriated comment in the /boot/grub/grub.cfg file;

*

*For example, # GRUB lacks write support for /dev/md0, so recordfail support is disabled.
How to apply the correct solution?
If you don't want to wait for this patch be applied by the Ubuntu/Debian guys in the official code, you can use my patched 00_header:
# Download
wget https://gist.githubusercontent.com/rarylson/da6b77ad6edde25529b2/raw/99f266a10e663e1829efc25eca6eddb9412c6fdc/00_header_patched
# Apply
mv /etc/grub.d/00_header /etc/grub.d/00_header.orig
mv 00_header_patched /etc/grub.d/00_header
# Disable the old script and enable the new one
chmod -x /etc/grub.d/00_header.orig
chmod +x /etc/grub.d/00_header
# Update Grub
update-grub


text:
Q: Probability of drawing exactly two aces and two kings or one ace and three kings? I've been trying to calculate the probability of drawing exactly two aces and two kings, or exactly one ace and three kings when the player already has an ace in hand. The player draws 24 more cards, and the deck is full aside from the ace in hand.
I've calculated the probability of getting exactly two aces and two kings like so:
$\dfrac{{3\choose2}.{4\choose2}.{44\choose20}}{{51\choose24}} \approx 13.81\%$
Which seems a little high to me. However, moving on with the same equation for drawing exactly one ace and three kings:
$\dfrac{{3\choose1}.{4\choose3}.{44\choose20}}{{51\choose24}} \approx 9.20\%$
And so, the probability of getting one or the other is $13.81\% + 9.20\% = 23.01\%$.
Can someone tell me where I'm going wrong? Because I have trouble believing there's a $23.01\%$ chance of the described scenario arising.

A: For exactly two more aces and exactly two kings in 24 draws from a
deck of 51 cards (missing an ace), I also get
$$ \frac{{3 \choose 2}{4 \choose 2}{44 \choose 20}}{{51 \choose 24}} = 0.138,$$
(to three places), computed in R as:
 18*choose(44, 20)/choose(51,24)
 ## 0.1380654

Here is a simulation of a million such draws with probabilities
correct to 2 or 3 places.
 m = 10^6;  nr.ace = nr.kng = numeric(m)
 deck = 2:52 # aces are 1,2,3,4; kings 5,6.7,8
 for (i in 1:m) {
  draw = sample(deck, 24)
  nr.ace[i] = sum(match(2:4, draw, nomatch=0)>0)
  nr.kng[i] = sum(match(5:8, draw, nomatch=0)>0) }

 mean(nr.ace == 2)
 ## 0.357932
 mean(nr.kng == 2)
 ## 0.387775
 mean(nr.ace==2 & nr.kng==2)
 ## 0.137598  # approx 0.138 as in exact combinatorial result
 mean(nr.ace==1 & nr.kng==3)
 ## 0.092077

 AK = as.data.frame(cbind(nr.ace,nr.kng))
 table(AK)/m
           nr.kng
 ## nr.ace        0        1        2        3        4
 ##      0 0.007532 0.035196 0.055101 0.035380 0.007596
 ##      1 0.026295 0.109556 0.157987 0.092077 0.018387
 ##      2 0.027684 0.105594 0.137598 0.073657 0.013399
 ##      3 0.008706 0.030502 0.037089 0.017775 0.002889

The approximate probability of $P(A = 2, K = 2)$ is found in
cell $(2,2)$ of the table. The approximate probability $P(A = 1, K = 3)$ is in cell $(1, 3).$
Related probabilities can also be approximated from the table.
For example, the total probability
$P(A = 2) \approx 0.358$ is found separately in the printout
above and as the total of row 2 of the table.
 sum(c(0.027684, 0.105594, 0.137598, 0.073657, 0.013399))
 ## 0.357932

Its exact
probability (to three places) is
$$ \frac{{3 \choose 2}{48 \choose 23}}{{51 \choose 24}} = 0.358,$$
 3*choose(48, 22)/choose(51, 24)
 ## 0.3578391

However, to get the probability of either 'two aces and two kings' OR
'one ace and three kings', you should add only two entries in
the table $(2,2)$ and $(1,3).$
Addendum: 'Expanded' R code, demonstrating method of counting aces (cards 2 through 4) in 24 draws:
 draw = sample(deck, 24);  draw  # list of 24 cards drawn w/o replacement
 ## 17 40 46 51 44 30 50 24  4  7 52 31 13 28 25 18 22 42  3  5 43 48 19  8
 ace.posn = match(2:4, draw, nomatch=0);  ace.posn
 ## 0 19  9  # card 2 not drawn, 19th was card 3, 9th was card 4
 tf.aces = (ace.posn > 0);  tf.aces
 ## FALSE  TRUE  TRUE  # TRUE for each ace found
 nr.aces = sum(tf.aces);  nr.aces  # counts TRUE's
 ## 2  # count of aces in 'draw' is stored in vector 'nr.ace'

The count of the number of aces in a 'draw' does not depend on which aces or their order. This is done a million times.

A: Revised answer
Assuming you are respectively drawing $2$ or $1$ more aces, your answers are correct.
My suspicion that the first ace being unspecified would affect the result was unwarranted.
Here is a longer way for the first case (just to confirm the correctness).
The ace you have could be any of $4$, so numerator $= 4\times{3 \choose 2}{4 \choose 2}{44 \choose 20}$
But then you need to similarly structure the denominator as $4\times\binom{51}{24}$,
and the result will remain the same as what you got.


text: Q: Как перенести на хостинг сайт,  сделанный на Java, с помощью Spring? Практикую Spring. Использую ceрвер GlassFish. На данном этапе удалось создать несколько страниц веб. Но хотел бы их увидеть не на localhost, а на удаленном сервере(в моем понимании, перенести на хостинг, если правильно высказываюсь.)


text:
Q: PyQGIS (QgsProject.instance().homePath()) I used this line of code in PyQGIS to get to project's home path.
path=os.path.join(QgsProject.instance().homePath(), "tt.gpkg").replace("\\","/")

Now I thought this is the path to where the project lies. But it comes that this is the path to where first/original project was saved.
Is that so or I might be wrong here?

A: When you save the project with a different name, the project that is open now is the one in the path you just saved. QGIS closes the original project.
Let's say the project's path is C:\test1\project1.qgz. If you save as project2.qgs to C:\test2, QGIS closes C:\test1\project1.qgz and loads C:\test2\project2.qgz.
Therefore, homePath returns C:\test2 after saving as project2.qgz.


text:
Q: Is it possible to adjust column width per row in confluence wiki? Is it possible to have different number of columns in different rows but still keep the width of the row flush with each other.

A: I am assuming you are using Confluence v4.x
I would use the Confluence Source Editor plugin which will enable you to take a look at the new xhtml source format. From there, you can add a colspan attribute on the row tag to control the columns in that row.
I have used a similar approach to get a table with 2 rows having 1 column and 2 columns each.

A: Yes, to the best of my recollection, you just need to fill the columns with empties. If you could provide some code I could perhaps assist better.


text:
Q: How can I write my own ef core function that operatoes on the database entitites I am trying to add a new custom function to ef core that I can use on the database entites.
I need to add my own implementation of count on each entity.
db.xyz.count() does not work for me.

It does not work for me because its too slow owing to the number of rows.
I want to have a custom function which brings the counts from another view.
something like:
db.xyz.customcount();

I tried using ef core extension methods:
namespace xyz.Helpers
{
    public static class CustomCountExtension:DbContext
    {
        public static int CustomCount() => {....};

    }
}

But this function , I need it to query against a different view which has the counts of each entity stored.
.i.e
Myview:
table | row  |
______________

xyz   | n    |

when i call xyz.customcount() , I need it to return rowcount where table
  = xyz.

is this possible.
Is there a better of implementing the above idea?
I am using:
.net core 2.1
ef core 2.2

A: You can map an Entity directly to your View and query it like a table.
public class MyView
{
    public string Table { get; set; }
    public int Row { get; set; }
}

Then define it as a DbQuery instead of DbSet in your DbContext:
public virtual DbQuery<MyView> MyView { get; set; }

Then map it to your View in the OnModelCreating() method using .Query() instead of .Entity():
protected override view OnModelCreating(ModelBuilder modelBulder)
{
    //... Other tables

    modelBuilder.Query<MyView>(query =>
    {
        query.ToView("MyView");
    }
}


text:
Q: SocketError at /sidekiq/ getaddrinfo: nodename nor servname provided, or not known I'm a novice Rails dev building an app connected to redis + sidekiq. I must have some configuration error, but I'm not sure what exactly it is. Below, I'll write about what exactly confuses me here:
Upon running rails s, I get the following error:
2016-07-09 08:55:46 - SocketError - getaddrinfo: nodename nor servname provided, or not known:
/Users/rohitrekhi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:177:in `getaddrinfo'
/Users/rohitrekhi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:177:in `connect'
/Users/rohitrekhi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:260:in `connect'
/Users/rohitrekhi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/redis-3.3.0/lib/redis/client.rb:336:in `establish_connection'

So I figured it must be a redis connection error. When I ping redis to see if connection goes through, it shows the following:
$ redis-cli ping
=> PONG

So if the redis connection goes through, maybe it's a Sidekiq issue?
I implemented the Sidekiq web interface via Sinatra, and got the following error when I tried to view it:
SocketError at /sidekiq/
getaddrinfo: nodename nor servname provided, or not known

So now I'm guessing the error is actually via Sidekiq, but I'm not sure where I dropped the ball via configurations on the host/server/sockets. Any ideas what exactly is causing this and if it's an error with Sidekiq or redis?
This is my initializer file for sidekiq in config/initializers/sidekiq.rb:
Sidekiq.configure_server do |config|
config.redis = { url: 'redis://redis.example.com:6379/12', network_timeout: 5 }
end

Sidekiq.configure_client do |config|
  config.redis = { url: 'redis://redis.example.com:6379/12', network_timeout: 5 }
end

And this is my config/initializer/redis.rb:
$redis = Redis.new(:host => 'localhost', :port => 6379)

I've also opened three terminal windows turning on the redis server, sidekiq, and my rails server.
Thanks in advance!

A: This makes no sense:
redis://redis.example.com:6379/12

You do not have a Redis server at that URL; fix the URL.


text:
Q: Programmatically creating company signature on OWA 2007 Any advice on possible script hints or learning documentation is much appreciated.

A: I don't believe there's a built in tool for doing this - though there are a number of ASP and other type of tools that you can install.
Other people have written scripts to do work like this - here's one example of a script which generates signatures.

A: I am unsure whether there's a tool or not, but I am wondering if you can accomplish this with Disclaimers, which you can have the Edge Transport server add to messages that address various criteria you set up.
This Technet article will start you in the right direction:
http://technet.microsoft.com/en-us/library/bb124352.aspx


text:
Q: Click function on external loaded content I have some text that is loaded on my site, with the jQuery method load().
I want to close (empty()) the div I've loaded when its h2 is clicked.
My HTML:

Click on this h2 should empty the div with class="item"

this is a h3

this is a paragraph

My jQuery;
$("h2").on('click', function() {
   $(this).parent("div").empty();
});

Maybe my code is wrong, but even if I put in a alert() on click h2, on the loaded content, it does not react.
Thanks in advance.

A: You have to use delegation:
$(".info_item").on('click', "h2", function() {
   $(this).closest(".item").empty();
});

I use closest() here to make your code more generic.

A: As per your question "I want to close (empty()) the div I've loaded when its h2 is clicked" use jquery selector method, get the ID or NAME and EMPTY or
jQuery('#parentdivID div').html('');

A: use this
$('.item').on('click', "h2", function() {
   $(this).parent().empty();
});

DEMO
Demo loads ajax contents after 3 sec


text:
Q: Reporting Services Hyperlink to Report in Another Project I need to set up a hyperlink in a report in one reporting services project to a report in another project that's part of the same solution.  The standard "Specify a Report" option allows linkage only to reports within the project.  Is there a way around this?

A: Found the info I needed at:
http://www.mssqltips.com/tip.asp?tip=1336

Passing the parameter entirely through HTML
Start over with your browser at the ProdColor prompt. Instead of choosing the color from the >dropdown, add the following at the end of the URL:
&ProdColor=Green.


text:
Q: Getting values by pointer How I can get a value by key through a pointer?
m := map[interface{}]interface{}{
        "uid": "007",
        "msg": "Hi James!",
}

fmt.Println(m["msg"]) //Ok!

p := &m

fmt.Println(p["msg"]) //??

play with: http://play.golang.org/p/4LOBrog93t

A: just through the value of the pointer:
fmt.Println((*p)["msg"])


text:
Q: Transposing matrix twice using classes without numpy I need to implement a method transpose() that returns a new matrix that has been transposed. It also has to print out a string of that matrix. It works when using matrix.transpose() but it doesn't work when using matrix.transpose().transpose() because transpose() returns a string.
I can't use numpy or add more input to the methods. How would I go about this?
from copy import deepcopy

class Matrix:
    def __init__(self, rows):
        self.rows = rows[:]

    def transpose(self):
            copy = deepcopy(self.rows)
            transposed = [[copy[j][i] for j in range(len(copy))] for i in range(len(copy[0]))]

        matrix = ''
        for element in transposed:
            for i in element:
                matrix += '%2d' % ((i))
                matrix += ' '
            matrix = matrix[:-1]
            matrix += '\n'

       return matrix

a = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

A: You can create a new Matrix object in transpose and return that after printing its content.
For convenience I moved your printing code to a method for converting the matrix to a string (Note that a method called __repr__ will be implicit called by print).
Code:
from copy import deepcopy

class Matrix:
     def __init__(self, rows):
         self.rows = rows[:]

     def transpose(self):
         copy = deepcopy(self.rows)
         transposed = [[copy[j][i] for j in range(len(copy))] for i in range(len(copy[0]))]
         transposed_matrix = Matrix(transposed)
         print(transposed_matrix)
         return transposed_matrix

     def __repr__(self):
         matrix = ''
         for element in self.rows:
             for i in element:
                 matrix += '%2d' % ((i))
                 matrix += ' '
             matrix = matrix[:-1]
             matrix += '\n'
         return matrix

Additional improvements:

*

*in transpose you can change the matrix transposition to transposed = list(map(list, zip(*self.rows)))

*use format string instead of '%2d' % ((i)) -> f'{i:2}'

*join is very helpful for formatting the matrix:
return '\n'.join(' '.join(f'{i:2}' for i in row) for row in self.rows)
Now the full code looks like this
class Matrix:
     def __init__(self, rows):
         self.rows = rows[:]

     def transpose(self):
         transposed = list(map(list, zip(*self.rows)))
         transposed_matrix = Matrix(transposed)
         print(transposed_matrix)
         return transposed_matrix

     def __repr__(self):
         return '\n'.join(' '.join(f'{i:2}' for i in row) for row in self.rows)


text:
Q: Thread-Safe implementation of an object that deletes itself I have an object that is called from two different threads and after it was called by both it destroys itself by "delete this".
How do I implement this thread-safe? Thread-safe means that the object never destroys itself exactly one time (it must destroys itself after the second callback).
I created some example code:
class IThreadCallBack
{
  virtual void CallBack(int) = 0;
};

class M: public IThreadCallBack
{
private:
  bool t1_finished, t2_finished;

public:

  M(): t1_finished(false), t2_finished(false)
  {
    startMyThread(this, 1);
    startMyThread(this, 2);
  }

  void CallBack(int id)
  {
    if (id == 1)
    {
      t1_finished = true;
    }
    else
    {
      t2_finished = true;
    }

    if (t1_finished && t2_finished)
    {
      delete this;
    }
  }
};

int main(int argc, char **argv) {
  M* MObj = new M();
  while(true);
}

Obviously I can't use a Mutex as member of the object and lock the delete, because this would also delete the Mutex. On the other hand, if I set a "toBeDeleted"-flag inside a mutex-protected area, where the finised-flag is set, I feel unsure if there are situations possible where the object isnt deleted at all.
Note that the thread-implementation makes sure that the callback method is called exactly one time per thread in any case.
Edit / Update:
What if I change Callback(..) to:
void CallBack(int id)

{
  mMutex.Obtain()
  if (id == 1)
  {
    t1_finished = true;
  }
  else
  {
    t2_finished = true;
  }
  bool both_finished = (t1_finished && t2_finished);

  mMutex.Release();

  if (both_finished)
  {
    delete this;
  }
}

Can this considered to be safe? (with mMutex being a member of the m class?)
I think it is, if I don't access any member after releasing the mutex?!

A: Instead of using two separate flags, you could consider setting a counter to the number of threads that you're waiting on and then using interlocked decrement.
Then you can be 100% sure that when the thread counter reaches 0, you're done and should clean up.
For more info on interlocked decrement on Windows, on Linux, and on Mac.

A: Use Boost's Smart Pointer.  It handles this automatically; your object won't have to delete itself, and it is thread safe.
Edit:
From the code you've posted above, I can't really say, need more info.  But you could do it like this: each thread has a shared_ptr object and when the callback is called, you call shared_ptr::reset().  The last reset will delete M.  Each shared_ptr could be stored with thread local storeage in each thread.  So in essence, each thread is responsible for its own shared_ptr.

A: I once implemented something like this that avoided the ickiness and confusion of delete this entirely, by operating in the following way:

*

*Start a thread that is responsible for deleting these sorts of shared objects, which waits on a condition

*When the shared object is no longer being used, instead of deleting itself, have it insert itself into a thread-safe queue and signal the condition that the deleter thread is waiting on

*When the deleter thread wakes up, it deletes everything in the queue

If your program has an event loop, you can avoid the creation of a separate thread for this by creating an event type that means "delete unused shared objects" and have some persistent object respond to this event in the same way that the deleter thread would in the above example.

A: I can't imagine that this is possible, especially within the class itself.  The problem is two fold:
1) There's no way to notify the outside world not to call the object so the outside world has to be responsible for setting the pointer to 0 after calling "CallBack" iff the pointer was deleted.
2) Once two threads enter this function you are, and forgive my french, absolutely fucked.  Calling a function on a deleted object is UB, just imagine what deleting an object while someone is in it results in.
I've never seen "delete this" as anything but an abomination.  Doesn't mean it isn't sometimes, on VERY rare conditions, necessary.  Problem is that people do it way too much and don't think about the consequences of such a design.
I don't think "to be deleted" is going to work well.  It might work for two threads, but what about three?  You can't protect the part of code that calls delete because you're deleting the protection (as you state) and because of the UB you'll inevitably cause.  So the first goes through, sets the flag and aborts....which of the rest is going to call delete on the way out?

A: The more robust implementation would be to implement reference counting. For each thread you start, increase a counter; for each callback call decrease the counter and if the counter has reached zero, delete the object. You can lock the counter access, or you could use the Interlocked class to protect the counter access, though in that case you need to be careful with potential race between the first thread finishing and the second starting.
Update: And of course, I completely ignored the fact that this is C++. :-) You should use InterlockExchange to update the counter instead of the C# Interlocked class.


text:
Q: Size Diff : Copy command doesn't copy all contents I ran below command with root to take backup of a folder on the same host :
cp -r master master-backup
size of master : 76GB
size of master-backup : 71GB

any idea why am i getting size diff ?

A: It's probably a matter of directory sizes. Directory is (at some level of thinking) just a file that contains some filenames along other metadata. If a directory keeps getting additions and removals, then it can grow much bigger over time. The master-backup has all the directories freshly created, so they are rather smallish.
Verify the file contents with diff -r master master-backup
Check the largest directory sizes with:
find master -type d -size +200 -printf '%s %p\n' | sort -rn | head
# repeat for master-backup

Other than that, the cp -r doesn't preserve the size in cases where you use some unusual stuff. For example: sparse files, security context, xattr entries.