text:
Q: How not to display DetailNoObjectsAvailable view via mobile? I've created a sapui5 project from master-detail template. What I want to achieve is showing an empty list (which is in the master view) via mobile without navigating to DetailNoObjectsAvailable view. I just can't find where DetailNoObjectsAvailable view is called from.
The reason why I want to achieve this is that when there are no objects in the list in the beginning and then an object is added to odata source, I see nothing but 'No objects available' and I can not navigate to the master list to refresh it manually. I have to refresh the whole page in fiori client browser to see it. When the list is not empty in the beginning and I add an object to odata source, the list refreshes automatically and I face no problems seeing it.
I haven't changed anything in the routing definition:

"routes": [
 {
  "pattern": "",
  "name": "master",
  "target": [
   "object",
   "master"
  ]
 }, {
  "pattern": "visitors_view/{objectId}",
  "name": "object",
  "target": [
   "master",
   "object"
  ]
 }
],
"targets": {
 "master": {
  "viewName": "Master",
  "viewLevel": 1,
  "viewId": "master",
  "controlAggregation": "masterPages"
 },
 "object": {
  "viewName": "Detail",
  "viewId": "detail",
  "viewLevel": 2
 },
 "detailObjectNotFound": {
  "viewName": "DetailObjectNotFound",
  "viewId": "detailObjectNotFound"
 },
 "detailNoObjectsAvailable": {
  "viewName": "DetailNoObjectsAvailable",
  "viewId": "detailNoObjectsAvailable"
 },
 "notFound": {
  "viewName": "NotFound",
  "viewId": "notFound"
 }
}

A: The mechanism routing to the notFoundobject is found in manifest.json:
manifest.json: bypassed + target in routing config
 "routing": {
            "config": {
                "routerClass": "sap.f.routing.Router",
                "viewType": "XML",
                "viewPath": "test.test.view",
                "controlId": "layout",
                "controlAggregation": "beginColumnPages",
                "bypassed": {
                    -------> "target": "notFound" <--------
                },
                "async": true
            },

"targets": {
                "notFound": {
                    "viewName": "NotFound",
                    "viewId": "notFound"
                }
            }

View in webapp/view:
<mvc:View
    controllerName="test.test.controller.NotFound"
    xmlns:mvc="sap.ui.core.mvc"
    xmlns="sap.m">
    <MessagePage
        id="page"
        title="{i18n>notFoundTitle}"
        text="{i18n>notFoundText}"
        icon="sap-icon://document">
    </MessagePage>
</mvc:View>

That is what you are looking for right?
Maybe your problem is solved by changing from "target": "notFound" to "target": "master" within the bypassed section in manifest.json.
UPDATE: Detail.controller.js
_onBindingChange : function () {
            var oView = this.getView(),
                oElementBinding = oView.getElementBinding();

            // No data for the binding
            if (!oElementBinding.getBoundContext()) {
                this.getRouter().getTargets().display("detailObjectNotFound");  <------------
                // if object could not be found, the selection in the master list
                // does not make sense anymore.
                this.getOwnerComponent().oListSelector.clearMasterListSelection();
                return;
            }

A: Solved the problem by commenting some lines in ListSelector.js. They caused an error in the console, which in its turn was the cause of my problem:

constructor : function () {
 this._oWhenListHasBeenSet = new Promise(function (fnResolveListHasBeenSet) {
  this._fnResolveListHasBeenSet = fnResolveListHasBeenSet;
 }.bind(this));
 this.oWhenListLoadingIsDone = new Promise(function (fnResolve, fnReject) {
  this._oWhenListHasBeenSet
   .then(function (oList) {
    oList.getBinding("items").attachEventOnce("dataReceived",
     function (oData) {
      if (!oData.getParameter("data")) {
       fnReject({
        list : oList,
        error : true
       });
      }
      var oFirstListItem = this.getFirstListItem();
      if (oFirstListItem) {
       fnResolve({
        list : oList,
        firstListitem : oFirstListItem
       });
      }
      // else {
      //  fnReject({
      //   list : oList,
      //   error : false
      //  });
      //}
     }.bind(this)
    );
   }.bind(this));
 }.bind(this));
},


text:
Q: Python object to file path? Error in Syntax When I trying to add the following file path,
data = 'c:/vehicles/etc'

I am wondering why I get the following error:
SyntaxError: invalid character in identifier ??

In addition to this, I have also tried:
data = 'C:\vehicles'

which produces a similar error:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Is there something new in python I'm missing to set up file paths?

A: data = 'c:/vehicles/etc'

Here you have fancy quotes that you probably copy/pasted from somewhere, like a Word document. Delete those and type in regular quotes.

data = 'C:\vehicles'

Here you need to escape the \ character so Python knows it's a literal \ and not an escape sequence.
data = 'C:\\vehicles'

Alternatively, prefix the sting literal with an r to tell Python it's a raw string.
data = r'C:\vehicles'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do Apple Apps run with higher privilege on Mac Its a silly question but I wouldn't be surprised if Apple did this on purpose.
Do their Apps run with higher privilege (hidden) than other 3'th party Apps do?
I recently switched from Apple Music to Spotify and sometimes, when my machine is under heavy load, the music interrupts shortly. I've never experienced this with Apple Music.

A: You are confusing privilege with priority. Privilege is what allows an app to run at all; priority is how much 'favour' it gets against other apps when the computer is busy.
tbh, this is an XY Problem - thinking up a wild theory as to the cause of a problem then looking for how to fix that, rather than trying to find the actual root of the issue.
Conspiracy theories aside, you can check an app's priority - it's nice value - using Activity monitor to quickly get the app's PID, then Terminal to show the current value.
Doing that for iTunes [I don't have Music, my OS is older] & Spotify gives…
$ ps -fl -C 92258 [iTunes]
  UID   PID  PPID   C STIME   TTY       TIME CMD                     F PRI NI       SZ    RSS WCHAN S ADDR
  501 92258     1   0  3:42pm ??     0:02.78 /Applications/iT     4084  61  0  7950436 286104 -     S    0
$ ps -fl -C 92263 [Spotify]
  501 92263     1   0  3:42pm ??     0:05.68 /Applications/Sp     40c4  46  0  7018612 188432 -     S    0

So, both have the same priority, zero - which is what most user-facing processes have.
Therefore you should look elsewhere as to why Spotify is buffering. I'd look at your network/router first.


text:
Q: Convert .log record to json I'm looking to take a log file in the following format and turn it into the json format of the snippet below.
2020:03:29-23:07:22 sslvpnpa ulogd[19880]: id="2001" severity="info" sys="SecureNet" sub="packetfilter" name="Packet dropped" action="drop" fwrule="60001" initf="eth0"

and turn it into the json format of the snippet below.
{"timestamp": "2020:03:29-23:07:22", "object": "sslvpnpa", "code": "ulogd[19880]", "id":"2001", severity="info", sys="SecureNet", sub="packetfilter" ...}

My start was to loop like this:
log_fields = log_row.split()

obj={}
for k in log_fields:
    if k.find('=') > -1:
        obj[k.split('=')[0]] = k.split('=')[1]

But then i realized some of the values have spaces and that there might be some list comprehension or generator expression that is more efficient or easier to read.
The object/json this generates will then be added to a field in a larger object.
Thanks in advance.

A: I think this will work out for you:
def split_string(s):
    d = {}
    ind = 0
    split_s = s.split()
    while ind < len(split_s):
        current_s = split_s[ind]
        if "=" in current_s:
            key, value, ind = get_full_string(split_s, ind)
            d[key] = value

        else:
            d[f"key{ind}"] = current_s

        ind += 1

    return d

def get_full_string(split_s, ind):
    current_s = split_s[ind]
    current_s_split = current_s.split("=")
    key = current_s_split[0]
    current_value = current_s_split[1]
    if current_value[-1] == '"':
        current_value = current_value.replace('"', '')
        return key, current_value, ind

    value_list = [current_value]
    ind += 1
    while ind < len(split_s):
        current_value = split_s[ind]
        value_list.append(current_value)
        if current_value[-1] == '"':
            break

        ind += 1

    value = " ".join(value_list)
    value = value.replace('"', '')
    return key, value, ind

Input:
s = '2020:03:29-23:07:22 sslvpnpa ulogd[19880]: id="2001" severity="info" sys="SecureNet" sub="packetfilter" name="Packet dropped" action="drop" fwrule="60001" initf="eth0"'
print(split_string(s))

Output:
{'key0': '2020:03:29-23:07:22', 'key1': 'sslvpnpa', 'key2': 'ulogd[19880]:', 'id': '2001', 'severity': 'info', 'sys': 'SecureNet', 'sub': 'packetfilter', 'name': 'Packet dropped', 'action': 'drop', 'fwrule': '60001', 'initf': 'eth0'}


text:
Q: Denial of Service Issue I found the issue below concerning inactive client connections (see Cassandra Security). We are using Cassandra 1.2.4 and the Cassandra JDBC driver as client. Is this still an existing issue?
Quoted from site above:
Denial of Service problem:
Cassandra uses a Thread- Per-Client model in its network code. Since setting up a connection requires the Cassandra server to start a new thread on each connection (in addition to the TCP overhead incurred by the network), the Cassandra project recommends utilizing some sort of connection pooling. An attacker can prevent the Cassandra server from accepting new client connections by causing the Cassandra server to allocate all its resources to fake connection attempts. The only pieces of information required by an attacker are the IP addresses of the cluster members, and this information can be obtained by passively sniffing the network. The current implementation doesn't timeout inactive connections, so any connection that is opened without actually passing data consumes a thread and a file-descriptor that are never released.

A: Directly exposing Cassandra to the public network is still a bad idea, and connection pooling is still a good idea, but the native protocol is fully asynchronous.


text:
Q: Eigenvalue solver in parallel using CUDA I have been searching and searching the web and I cannot seem to find the answer I'm looking for. I have a particular problem.
I'm editing this in order to simply the problem and hope it is more readable and understandable.
Let's say I have 5000 20x20 symmetric, dense matrices. I would like to create a kernel in CUDA that will have each thread responsible for calculating the eigenvalues for each of the symmetric matrices.
Sample code of the CUDA kernel would be great if possible.
Any and all help/suggestions would be appreciated!
Thanks,
Johnathan

A:
I would like to create a kernel in CUDA that will have each thread responsible for calculating the eigenvalues for each of the symmetric matrices.

It's questionable to me whether this would be the fastest approach, but it might be for very small matrices.  Even in this situation, there might be some data storage optimizations that could be made (interleaving global data across threads), but this would complicate things.
As stated, that request could be mapped into an "embarrassingly parallel" algorithm, where each thread works on a fully independent problem.  We need only find suitable single threaded "donor code".  After a quick google search, I came across this.  It is fairly straightforward to modify that code to run in this thread-independent way. We need only borrow 3 routines (jacobi_eigenvalue, r8mat_diag_get_vector and r8mat_identity), and suitably decorate these routines with __host__ __device__ for use on the GPU, while making no other changes.
The code in question, appears to be GNU LGPL licensed by J Burkardt at Florida State University.  Therefore, with this in view, and following conventional wisdom I have not included any significant amount of that code in this answer.  But you should be able to reconstruct my results experimentally using the instructions I give.
NOTE:  I'm not sure what the legal ramifications are of using this code, which claims to be GNU LGPL licensed.  You should be sure to adhere to any necessary requirements if you elect to use this code or portions of it.  My primary purpose in using it here is to demonstrate the concept of a relatively trivial "embarassingly parallel" extension of a single-threaded problem solver.
It should be trivial to reconstruct my full code by going here and copy-pasting the 3 indicated functions into the places indicated in the remaining code-skeleton.  But this doesn't change any of the previously mentioned notices/disclaimers.  Use it at your own risk.
Again, making no other changes might not be the best idea from a performance standpoint, but it results in a trivial amount of effort and can serve as a possibly useful starting point.  Some possible optimizations could be:

*

*seek out a data interleaving strategy so that adjacent threads are more likely to be reading adjacent data

*eliminate the new and delete functions from the thread code, and replace it with a fixed allocation (this is easy to do)

*remove unnecessary code - for example that which computes and sorts the eigenvectors, if that data is unneeded

In any event, with the above decorated donor code, we need only wrap a trivial kernel (je) around it, to launch each thread operating on separate data sets (i.e. matrices), and each thread produces its own set of eigenvalues (and eigenvectors - for this particular code base).
I've crafted it to work with just 3 threads and 3 4x4 matrices for test purposes, but it should be trivial to extend it to however many matrices/threads you wish.
For brevity of presentation, I've dispensed with the usual error checking, but I recommend you use it or at least run your code with cuda-memcheck if you make any modifications.
I've also built the code to adjust the device heap size upward to accommodate the in-kernel new operations, depending on number of matrices (ie. threads) and matrix dimensions.  If you worked on the 2nd optimization mentioned above, you could probably remove this.
t1177.cu:
#include <stdio.h>
#include <iostream>
const int num_mat = 3; // total number of matrices = total number of threads
const int N = 4;   // square symmetric matrix dimension
const int nTPB = 256;  // threads per block

// test symmetric matrices

  double a1[N*N] = {
      4.0,  -30.0,    60.0,   -35.0,
    -30.0,  300.0,  -675.0,   420.0,
     60.0, -675.0,  1620.0, -1050.0,
    -35.0,  420.0, -1050.0,   700.0 };

  double a2[N*N] = {
    4.0, 0.0, 0.0, 0.0,
    0.0, 1.0, 0.0, 0.0,
    0.0, 0.0, 3.0, 0.0,
    0.0, 0.0, 0.0, 2.0 };

  double a3[N*N] = {
    -2.0,   1.0,   0.0,   0.0,
     1.0,  -2.0,   1.0,   0.0,
     0.0,   1.0,  -2.0,   1.0,
     0.0,   0.0,   1.0,  -2.0 };

/* ---------------------------------------------------------------- */
//
// the following functions come from here:
//
// https://people.sc.fsu.edu/~jburkardt/cpp_src/jacobi_eigenvalue/jacobi_eigenvalue.cpp
//
// attributed to j. burkardt, FSU
// they are unmodified except to add __host__ __device__ decorations
//
//****************************************************************************80
__host__ __device__
void r8mat_diag_get_vector ( int n, double a[], double v[] )
/* PASTE IN THE CODE HERE, FROM THE ABOVE LINK, FOR THIS FUNCTION */
//****************************************************************************80
__host__ __device__
void r8mat_identity ( int n, double a[] )
/* PASTE IN THE CODE HERE, FROM THE ABOVE LINK, FOR THIS FUNCTION */
//****************************************************************************80
__host__ __device__
void jacobi_eigenvalue ( int n, double a[], int it_max, double v[],
  double d[], int &it_num, int &rot_num )
/* PASTE IN THE CODE HERE, FROM THE ABOVE LINK, FOR THIS FUNCTION */

// end of FSU code
/* ---------------------------------------------------------------- */

__global__ void je(int num_matr, int n, double *a, int it_max, double *v, double *d){

  int idx = threadIdx.x+blockDim.x*blockIdx.x;
  int it_num;
  int rot_num;
  if (idx < num_matr){
    jacobi_eigenvalue(n, a+(idx*n*n), it_max, v+(idx*n*n), d+(idx*n), it_num, rot_num);
  }
}

void initialize_matrix(int mat_id, int n, double *mat, double *v){

  for (int i = 0; i < n*n; i++) *(v+(mat_id*n*n)+i) = mat[i];
}

void print_vec(int vec_id, int n, double *d){

  std::cout << "matrix " << vec_id << " eigenvalues: " << std::endl;
  for (int i = 0; i < n; i++) std::cout << i << ": " << *(d+(n*vec_id)+i) << std::endl;
  std::cout << std::endl;
}
int main(){
// make sure device heap has enough space for in-kernel new allocations
  const int heapsize = num_mat*N*sizeof(double)*2;
  const int chunks = heapsize/(8192*1024) + 1;
  cudaError_t cudaStatus = cudaDeviceSetLimit(cudaLimitMallocHeapSize, (8192*1024) * chunks);
  if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "set device heap limit failed!");
    }
  const int max_iter = 1000;
  double *h_a, *d_a, *h_v, *d_v, *h_d, *d_d;
  h_a = (double *)malloc(num_mat*N*N*sizeof(double));
  h_v = (double *)malloc(num_mat*N*N*sizeof(double));
  h_d = (double *)malloc(num_mat*  N*sizeof(double));
  cudaMalloc(&d_a, num_mat*N*N*sizeof(double));
  cudaMalloc(&d_v, num_mat*N*N*sizeof(double));
  cudaMalloc(&d_d, num_mat*  N*sizeof(double));
  memset(h_a, 0, num_mat*N*N*sizeof(double));
  memset(h_v, 0, num_mat*N*N*sizeof(double));
  memset(h_d, 0, num_mat*  N*sizeof(double));
  initialize_matrix(0, N, a1, h_a);
  initialize_matrix(1, N, a2, h_a);
  initialize_matrix(2, N, a3, h_a);
  cudaMemcpy(d_a, h_a, num_mat*N*N*sizeof(double), cudaMemcpyHostToDevice);
  cudaMemcpy(d_v, h_v, num_mat*N*N*sizeof(double), cudaMemcpyHostToDevice);
  cudaMemcpy(d_d, h_d, num_mat*  N*sizeof(double), cudaMemcpyHostToDevice);
  je<<<(num_mat+nTPB-1)/nTPB, nTPB>>>(num_mat, N, d_a, max_iter, d_v, d_d);
  cudaMemcpy(h_d, d_d, num_mat*N*sizeof(double), cudaMemcpyDeviceToHost);
  print_vec(0, N, h_d);
  print_vec(1, N, h_d);
  print_vec(2, N, h_d);
  return 0;
}

compile and sample run:
$ nvcc -o t1177 t1177.cu
$ cuda-memcheck ./t1177
========= CUDA-MEMCHECK
matrix 0 eigenvalues:
0: 0.166643
1: 1.47805
2: 37.1015
3: 2585.25

matrix 1 eigenvalues:
0: 1
1: 2
2: 3
3: 4

matrix 2 eigenvalues:
0: -3.61803
1: -2.61803
2: -1.38197
3: -0.381966

========= ERROR SUMMARY: 0 errors
$

The output seems plausible to me, mostly matching the output here.


text:
Q: C++ error reading character of string I am trying to add an array to my Object which contains dynamic array
MyCollection.h
    template <typename T>
    MyCollection<T>::MyCollection(int size)
    {
        arraySize = size;
        anArray = new T[size];
    }

    template <typename T>
    MyCollection<T>::MyCollection(MyCollection<T>& coll)
    {
        arraySize = coll.arraySize;
        anArray = new T[arraySize];

        for (int i = 0; i < arraySize; i++)
        {
            SetValue(coll.GetValue(i), i);
        }
    }

    template <typename T>
    MyCollection<T>::MyCollection(T* myArray, int size)
    {
        anArray = myArray;
        arraySize = size;
    }

   template<typename T>
    void MyCollection<T>::AddAll(T pArray[], int size)
    {
        int plusSize = size - 1;
        int arrayIterator = 0;
        arraySize += size;

        for (int i = size; i < arraySize - plusSize; i++)
        {
            anArray[i] = pArray[arrayIterator];
            arrayIterator++;
        }

    }

Main
MyCollection<string> B = MyCollection<string>(new string[3], 3);
    B.SetValue("C", 0);
    B.SetValue("D", 1);
    B.SetValue("E", 2);

string C[3];
    C[0] = "X";
    C[1] = "Y";
    C[2] = "Z";

B.AddAll(C, 3);
    B.Display();

In the AddAll method I have error with acces violation. When I add watch anArray[i] = . Is there any idea why that happens? Is it problem with copy construcotr or so ?

A: In AddAll(), you need to resize the raw array anArray, there is no resizing going on (you just change the numeric value of arraySize, but do not allocate more memory). So you need something like
delete[] anArray;
// ...
anArray = new T[arraySize];

You may also think whether you want to copy the old elements into the newly allocated array, in which case you first have to reallocate with a temporary pointer, then copy into it, then delete the original anArray, and finally assign the temporary pointer to the original anArray, something like:
// save the old size
int oldSize = arraySize;
arraySize += size;
T* tmp = new T[arraySize];
// copy from anArray into tmp, use oldSize
// for(...){...}
delete[] anArray;
anArray = tmp;


text:
Q: 'New-AzureStorageContext' is not recognized I'm trying to run a PowerShell script that functions on a colleague's computer, but is failing on mine on this line:
Set-Variable -Name StorageContext -Value (New-AzureStorageContext -ConnectionString $storageConnectionString)

My error is:

New-AzureStorageContext : The term 'New-AzureStorageContext' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
  included, verify that the path is correct and try again.
  At C:\Users\dlogg\Documents\Repos\sd2\PowerShell Scripts\Eco\AddEco.ps1:22 char:43
  + Set-Variable -Name StorageContext -Value (New-AzureStorageContext -ConnectionStr...

I have confirmed I have PowerShell v.3, and I have installed Azure PowerShell with Microsoft Azure SDK and Microsoft Azure PowerShell (Standalone) from Web PI. What do I need to install to use this?
http://msdn.microsoft.com/en-us/library/azure/dn495246.aspx
UPDATE: Per the request below, I have included the output of Get-Module:
ModuleType Name                                ExportedCommands
---------- ----                                ----------------
Script     Common                              {Fetch, Get-BlobContainer, Get-ConfigurationFileName, Get-DeploymentTenantListFileName...}
Script     ISE                                 {Get-IseSnippet, Import-IseSnippet, New-IseSnippet}
Manifest   Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
Manifest   Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}

A: i have same problem with you.
my problem is using the wrong command :"AzureStorageContext".it shoud "AzStorageContext"

A: You haven't loaded the Azure PowerShell module (hence it is missing from the list you have). When you install the Cmdlets you will also get a new shortcut "Microsoft Azure Powershell" which will automatically load the module for you (and make the Cmdlets available).
If you don't want to do it that way you can import the module into an existing PowerShell session using this command (note that the path to the Azure module may differ depending on the version you have installed).
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1"

A: Which version of Azure PowerShell module are you using? Have you loaded the Azure module, or just running PowerShell (or via the Azure PowerShell shortcut).
Here is output from Azure PowerShell module 0.8.8.1
PS C:\> Get-Module

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   0.8.8.1    Azure                               {Add-AzureAccount, Add-AzureCacheWorkerRole, Add-AzureCert...
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Con...
Manifest   3.0.0.0    Microsoft.PowerShell.Security       {ConvertFrom-SecureString, ConvertTo-SecureString, Get-Acl...
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}

PS C:\> New-AzureStorageContext
cmdlet New-AzureStorageContext at command pipeline position 1
Supply values for the following parameters:
(Type !? for Help.)
StorageAccountName:

The best way to use Azure PowerShell cmdlets is to start the Azure PowerShell directly from the generated shortcut by the installer. Or use the Import-Module command to import Azure PowerShell module.
For detailed instructions, read the How to: Install and configure Azure Power Shell module. And also check this ServerFault question and answer.

A: You need to install the azure power shell as in microsoft site
https://learn.microsoft.com/en-us/powershell/azure/install-az-ps?view=azps-1.1.0
It works like a charm

A: Install Microsoft SDK for PowerShell from the URL - https://azure.microsoft.com/en-in/downloads/
Restart the Windows Machine and try executing the script. It will work as expected


text:
Q: Different citation style for footnotes and bibliography I have a document, using footnotes for citations and a custom bibliography style, where the footnotes need to be given with the author's name in the order "Name Surname" (example "John Doe"), but the entries in the bibliography need to follow the "Surname, Name" format (example "Doe, John"). I've figured out the part how to change the order of names/surnames in the .bst file. However, that doesn't solve the issue of the differing citation styles.
What I should have is, for footnotes(sorry for the image quality):

And in the bibliography:

Of course, it's possible to manually enter the reference in the footnotes each time, but given the length of the work, and the fact I will have to do similar things in the future, I'd like to see if there is a solution which doesn't require me to do it manually.
I've tried a few things (putting the bibliography in a separate file with a different citation style, but that doesn't work); but I'm not even sure if this is quite possible. The other solution I have is just doing the two files separately (i.e. the main text with the author name first citations; and then a separate file for the bibliography only with surname first, and then merging the two PDFs together, but that feels a bit like cheating, and probably removes bookmarks and links to the citations (and the document needs to be handed in electronically, so although this would work on actual paper, ...).
Thanks,
Minimum working example:
\documentclass[12pt]{article}
\usepackage{natbib}
\usepackage[french]{babel}
\usepackage{etoolbox}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{bibentry}
\usepackage[T1]{fontenc}
\usepackage{hyperref}
\urlstyle{same}
\usepackage{hanging}
\nobibliography*

\begin{document}

Some random text.\footnote{\bibentry{Webber1996}, p. 37-40}

\newpage
\hyphenpenalty=10000
\bibliographystyle{plainnat} %%not quite the exact style I need, but whatever
\setlength{\parskip}{6pt}
\addcontentsline{toc}{section}{Bibliography}
\bibliography{refs}
\end{document}

A: With bibentry you can only get the bibliography item exactly as it appears in the bibliography, so generally there is no way to slightly change the formatting between citations and bibliography.
bibentry is already quite a clever way to get around the fundamental limitation of the classical BibTeX/thebibliography approach that means that entry data is practically not available outside of the bibliography unless it is specifically "smuggled out".
While there are BibTeX-based solutions like jurabib that manage to overcome the limitations inherent in the BibTeX approach, the most flexible (and currently maintained!) solution is probably biblatex. biblatex's approach is quite different, but it makes all entry data available in both citations and the bibliography, which means that you can easily obtain the effect you are asking for.
There are even standard styles that come pretty close to what you seem to want
\documentclass[12pt]{article}
\usepackage[french]{babel}
\usepackage[T1]{fontenc}
\usepackage{csquotes}
\usepackage[backend=biber, style=verbose]{biblatex}
\usepackage{hyperref}

\addbibresource{biblatex-examples.bib}

\begin{document}
Some random text.\autocite[34-37]{nussbaum}

\printbibliography[heading=bibintoc]
\end{document}


text:
Q: Solving $2\cos \left( \frac{\pi }{2}-\theta \right)=3\cos \left( \frac{\pi }{3}+\theta \right)$ for $0 < θ < 2π$ I am required to solve this equation:

Find all the angles that satisfy the equation $$2\cos \left( \frac{\pi }{2}-\theta  \right)=3\cos \left( \frac{\pi }{3}+\theta  \right)$$
for $0 < θ < 2π$

I am aware that I can convert $$\cos \left( \frac{\pi }{3}+\theta  \right)=\cos\frac{\pi }{3}\cos\theta-\sin\frac{\pi }{3}\sin\theta$$ and $$\cos \left( \frac{\pi }{2}-\theta  \right)=\sin\theta$$ .
So,
$$2\cos \left( \frac{\pi }{2}-\theta  \right)=3\cos \left( \frac{\pi }{3}+\theta  \right)$$
$$2\sin\theta =3\left( \cos\frac{\pi }{3}\cos\theta-\sin\frac{\pi }{3}\sin\theta \right)$$
I stuck here,
If anyone can explain to me how to achieve this I would be very grateful.


text:
Q: Can we classify weakly compact subsets of $l^{\infty}$? My question is as stated. The motivation behind this is that I want to prove that such subsets are norm-separable.

A: Edit: my previous answer was plain wrong as the set $B_K$ need not be a ball of any space (for example, take the unit vector basis of $c_0$; $c_0$ does not contain any infinite-dimensional reflexive subspaces). Here is an easier argument.
Suppose that $K\subset \ell_\infty$ is weakly compact. As $\ell_\infty$ is isometric to the dual space of $\ell_1$, it carries the weak* topology, which is coarser than the weak topology of $\ell_\infty$. In particular, $K$ is also compact in the weak* topology and the two relative topologies agree on $K$. However, as $\ell_1$ is separable, weak* compact subsets of $\ell_\infty$ are second-countable. One may use Mazur's lemma (as explained here) to conclude that a set is weakly separable if and only if it is norm-separable.
Suppose that $K\subset \ell_\infty$ is weakly compact. Then, by Mazur's lemma, so is the closed convex hull of $K\cup \{0\}$, call it $B_K$. Consider $\ell_\infty$ as the dual space to $\ell_1$. Since the weak* topology on $\ell_\infty$ is coarser than the weak topology, by compactness, they must be equal on $B_K$. Since $B_K$ is weakly compact, $X_K$ is reflexive. However, the weak*-topology and the weak topologies of $\ell_\infty$ coincide on $X_K$, so $X_K$ is weak*-closed. Then, by reflexivity, $X^*_K$ is isomorphic to $\ell_1 / (X_K)_\perp$, where $(X_K)_\perp$ is the pre-annihilator of $X_K$ so $X_K$ (and hence $K$ itself) is norm-separable.
This can be generalised as follows. If $\Gamma$ is infinite, then each weakly compact subset of $\ell_\infty(\Gamma)$ has density at most $|\Gamma|$. (For example, for regular cardinals, it follows from Theorem 2.6 here.)

A: Another way to prove this is to use the following result:

Lemma: If $K \subset \ell_{\infty}$ is weakly compact, then it is weakly metrisable.
Proof: For $x,y \in K$ we set,
$$ d(x,y) = 2^{-n} |x_n-y_n|. $$
Since $K$ is norm bounded (by the uniform boundedness principle) the sum is finite and we can readily check this defines a metric on $K.$ Moreover it is a locally convex space defined by the coordinate maps $x \mapsto x_n.$
Since $(K,d)$ is generated by fewer functionals compared to the weak topology, it is coarser and so the identity map,
$$ (K,w) \rightarrow (K,d) $$
is continuous. Since $(K,w)$ is compact and $(K,d)$ is Hausdorff the map is a homeomorphism, so the topologies coincide.

Hence it follows that $K$ is weakly separable, by using total boundedness and taking $\frac1n$-nets.
Now let $\{x_n\}_{n=1}^{\infty}$ be a weakly dense subset of $K$ and set,
$$ C = \left\{ \sum_{i=1}^n t_i x_{k_i} \mid n \in \mathbb N, t_1, \dots, t_n \in [0,1] \cap \mathbb Q, \sum_{i=1}^n t_i = 1, k_1 < \dots < k_n \right\}. $$
That is, the rational convex hull of the $x_n$'s. One can easily show this is weakly dense in $\mathrm{conv}\ K,$ so by Mazur's lemma,
$$ \overline{\mathrm{conv}}^{\lVert\cdot\rVert} C = \overline{\mathrm{conv}}^w C = \overline{\mathrm{conv}}\ K. $$
Since $C$ is countable, $\overline{\mathrm{conv}}\ K$ and hence $K$ is norm separable.


text:
Q: How to loop through a string n times until it gets equal to the original string? I have few strings on which I need to loop and perform some operations such that I get back the original string after certain iterations.
For example in string "1010", on each iteration, I need to move the the front characters based on iteration number
First iteration (1 iteration):  0101   (moved 1 character from front)
Second iteration (2 iteration): 0101   (moved 2 characters from front)
Third iteration (3 iteration):  1010   (moved 3 characters from front)

So I get back the original string
But for a string like "1001", it will take 7 iterations
First iteration (1 iteration): 0011   (moved 1 character from front)
Second iteration (2 iteration): 1100   (moved 2 characters from front)
Third iteration (3 iteration): 0110   (moved 3 characters from front)
Fourth iteration (4 iteration): 0110   (moved 4 characters from front)
Fifth iteration (5 iteration): 1100   (moved 5 characters from front)
Sixth iteration (6 iteration): 0011   (moved 6 characters from front)
Seventh iteration (7 iteration): 1001   (moved 7 characters from front)

Here is my code below
string_list = ["1010", "1001"]

for i in string_list:
    print("i",i)
    t = 1
    print("starting t",t)
    new_string = i
    for j in i:
        num_letter = new_string[:t]
        print("num_letter", num_letter)
        new_string = new_string[t:] + num_letter
        print("intermediate new string",new_string)
        if new_string == i:
            print("no of iterations until same string occurs", t)
            break
        else:
            t += 1
            print("t",t)

Here for the first string, I get no of iterations to be 3 which is correct. But for the second string, it stops at the fifth iteration since the string's length is completely covered.
How do I ensure it keeps looping through the string untill I get back a string which is identical to the original string?

A: Use a while loop, iterate until same string occurs and do the slicing with i % len(s), where i is the current iteration and s is the current string:
Code
string_list = ["1010", "1001"]

for s in string_list:
    i = 1
    curr_s = s

    print("starting t", s)

    while True:
        k = i % len(s)
        new_s = curr_s[k:] + curr_s[:k]

        print("intermediate new string",new_s)

        if new_s == s:
            print("no of iterations until same string occurs", i)
            break

        i += 1
        curr_s = new_s

Output


text:
Q: How to enter the Django shell in read-only mode? I'm interested in using a form of the Django shell which only permits read operations. So far, I've read this blog article (https://chase-seibert.github.io/blog/2012/12/21/read-only-django-shell.html), which seems to be based on setting django.db.router.db_for_write to None.
Is this the recommended way to do this? As I understand from https://docs.djangoproject.com/en/2.1/topics/db/multi-db/#using-routers, the django.db.router is the 'master router' and it is not clear to me whether I can modify its attributes without affecting the environment in which the database is running.
Perhaps there is another way, like creating a database (in my case, MySQL) user with only read permission, and starting a Django shell connected as that user?

A: This is a slightly trickier than one might anticipate because it sounds like you'll need a separate set of settings to use for the shell command versus normal django operation.  So three step process:

*

*create your own router class

*create a separate settings file to be used with the shell command

*use an environment variable or a separate manage.py to run the shell command


text:
Q: Different PATH formats for .bash_profile There are few different formats I have seen so far:

*

*With quotes and brackets:
PATH="/usr/local/bin:${PATH}"

*With quotes only:
PATH="/usr/local/bin:$PATH"

*None:
PATH=/usr/local/bin:$PATH

Export all the same:
export PATH

Which is the correct/preferred way?

A: This is about shell variables in general, not just PATH.
Here are some examples of why "" and {} can reduce errors.
Putting it in quotes is safer: if you do a=hello world then you will not get what you expect, but for a="hello world" you will.
Using {} is also safer: doing h="hello"; echo "$hword" will not work, but h="hello"; echo "${h}word" will.

A: They all are effective. One isn't drastically better than the other, but I prefer:
export PATH=$PATH:/usr/local/bin

It takes care of the export and the setting of the path in one line. I also tend to not put the new path before the existing $PATH, but there are cases when that might be necessary to load newer self-compiled libraries before older system ones.

If you are trying to export variables then yes, you want to quote them, for instance:
export myservers="server1 server2 server3"

Now when you echo $myservers you will see:
[user]# echo $myservers
server1 server2 server3

But since this question relates to $PATH and not shell variables, then my original post still stands since there will never be a time where you are printing 'hello world' into your system path.
[user]# echo $PATH  ## Something you shouldn't be doing
/usr/local/bin:HELLO WORLD/sbin:/bin:/usr/sbin:WHY AM I DOING THIS?/usr/bin:/root/bin


text:
Q: Aborted job restarts I have an enqueued job using system.enqueueJob( new APEX_Job_Queueable() );
This job is a long running job which makes callouts to retrieve date. The callout returns a NextLink Url which, when populated, indicates that there are more data to retrieve. I check some governor limits and, when 1 is reached, I stop the current job and reenqueue the same job to continue.
I need to interrupt the job while testing and so I often use the link Abort.
The job aborts as expected but after 2-3 minutes, the job restarts.
What is the cause of this restart ? Is it an expected behavior ? Is it related to the fact that I reenqueue the job ?
Thank you


text:
Q: Detect odd characters in big text files I need to check if my entire files contained only 4 characters; "A", "T", "G" and "C".
I used to split the characters using sed and then grep -o and -v to exclude the targeted characters for checking.
Is there any simple and straight forward way to do this in linux? Using sed / awk / grep?
(There seemed to be suggestion on this related questions but they were including the whole texts in the command. My file size is too big for this.)
For example, there are four lines in the input file, with possibility of other characters existing in the line (other than ATGC). I would like to detect the odd characters and show the odd characters together with the number of line they are in, if possible.
Input:
ATTGTAAGGTAAGTGGATTYTCCGGGRETC
TTVGGATCGTTGACCAGTK
GCCCGGGCCGGTCCTTTGGTGCGTGGGG
CTCTCCCAACCCCCCCACCCTCGACCTGAGCTCAGGCXC

Desired Output:
1:Y
1:R
1:E
2:V
2:K
4:X

A: -n Prefix each line of output with the 1-based line number.
-o Print only the matched parts.
[^ATGC] exclude characters.
grep -no '[^ATGC]' file

A: If you have many files, and most of those are valid, there is an efficient way to make a preliminary check. Just count the invalid characters: if there are none, there is no point making a more precise test of the file. We use tr to remove the valid ones, and wc -c to count the others.
More precise reporting is needed for the case where the count is non-zero.
I would suggest using awk, and defining the FS (field separator) as 'FS=[^ATGC]+', which means "any sequence of characters that are not A, T, G or C". If there are no incorrect characters on a line, then there will be only one field.
If more than one field exists, we can use the GNU/awk extension to split(), which provides the exact text of each field separator.
#! /bin/bash

Awk='
BEGIN { FS = "[^ATGC]+"; }

function Show (tx, Local, f, c, fTxt, fSep) {
    split (tx, fTxt, FS, fSep)
    for (f = 1; f in fSep; ++f) {
        c += length (fTxt[f]);
        printf ("File %s Line %d Column %d Has :%s:\n",
            FILENAME, FNR, 1 + c, fSep[f]);
        c += length (fSep[f]);
    }
}
NF > 1 { Show( $0); }
'
    for fn in q??; do
        cc="$( tr -d 'ATGC\n' < "${fn}" | wc -c )"
        (( cc == 0 )) && { echo "$fn is OK"; continue; }
        awk "${Awk}" "${fn}"
    done

and to test:
Paul--) head q??
==> q01 <==
TTGTAAGGTAAGTGGATTYTCCGGGRETC
TTVGGATCGTTGACCAGTK
GCCCGGGCCGGTCCTTTGGTGCGTGGGG
CTCTCCCAACCCCCCCACCCTCGACCTGAGCTCAGGCXC
BAACCCCZ

==> q02 <==
GCCCGGGCCGGTCCTTTGGTGCGTGGGG

==> q03 <==
TTGTAAGGTAAGTGGATTYTCCGGGRETC
Paul--)
Paul--) ./qFix q01 q02 q03
File q01 Line 1 Column 19 Has :Y:
File q01 Line 1 Column 26 Has :RE:
File q01 Line 2 Column 3 Has :V:
File q01 Line 2 Column 19 Has :K:
File q01 Line 4 Column 38 Has :X:
File q01 Line 5 Column 1 Has :B:
File q01 Line 5 Column 8 Has :Z:
q02 is OK
File q03 Line 1 Column 19 Has :Y:
File q03 Line 1 Column 26 Has :RE:
Paul--)


text:
Q: Spearman Correlation on timeseries acquired at different resolutions in R I am working in R, and I have got these two timeseries:
structure(list(Date_SAR = c("10/05/2003", "14/06/2003", "19/07/2003",
"23/08/2003", "27/09/2003", "01/11/2003", "06/12/2003", "10/01/2004",
"14/02/2004", "20/03/2004", "24/04/2004", "29/05/2004", "03/07/2004",
"07/08/2004", "11/09/2004", "16/10/2004", "20/11/2004", "25/12/2004",
"29/01/2005", "05/03/2005", "09/04/2005", "14/05/2005", "18/06/2005",
"23/07/2005", "27/08/2005", "01/10/2005", "05/11/2005", "10/12/2005",
"14/01/2006", "18/02/2006", "25/03/2006", "29/04/2006", "03/06/2006",
"08/07/2006", "12/08/2006", "16/09/2006", "21/10/2006"), SAR = c(11,
9.175, 5.525, 1.875, -9.67, -18.3383, -16.235, -14.1317, -12.7163,
-11.9888, -11.2613, -10.5338, -7.97, -10.1583, -18.935, -27.7117,
-19.755, -8.98, 2.38, 5.1575, -15.1475, -24.5767, -23.13, -21.6833,
-22.59, -23.71, -21.485, -9.45, -2.32, -12.825, -27.455, -30.02,
-37.04, -44.0075, -34.4025, -27.3975, -22.9925)), class = "data.frame", row.names = c(NA,
-37L))

and
structure(list(Date_GWL = c("15/02/2003", "15/03/2003", "15/04/2003",
"15/05/2003", "15/06/2003", "15/07/2003", "15/08/2003", "15/09/2003",
"15/10/2003", "15/11/2003", "15/12/2003", "15/01/2004", "15/02/2004",
"15/03/2004", "15/04/2004", "15/05/2004", "15/06/2004", "15/07/2004",
"15/08/2004", "15/09/2004", "15/10/2004", "15/11/2004", "15/12/2004",
"15/01/2005", "15/02/2005", "15/03/2005", "15/04/2005", "15/05/2005",
"15/06/2005", "15/07/2005", "15/08/2005", "15/09/2005", "15/10/2005",
"15/11/2005", "15/12/2005", "15/01/2006", "15/02/2006", "15/03/2006",
"15/04/2006", "15/05/2006", "15/06/2006", "15/07/2006", "15/08/2006",
"15/09/2006", "15/10/2006", "15/11/2006", "15/12/2006", "15/01/2007"
), GWL = c(-173.41, -174.23, -175.06, -175.77, -176.2, -176.56,
-177.2, -177.7, -178.06, -177.94, -178.15, -178.7, -179, -179.15,
-179.51, -179.32, -179.14, -179.8, -180.2, -180.87, -180.4, -179.5,
-178.06, -179.38, -180.71, -180.3, -179.19, -178.09, -178.82,
-179.55, -180.28, -181.01, -179.67, -178.34, -178.1, -177.9,
-177.71, -177.77, -177.83, -178.5, -179.5, -180.5, -181.63, -181.24,
-180.86, -180.11, -179.37, -178.62)), class = "data.frame", row.names = c(NA,
-48L))

As you can see, these two time series are for the same timeframe (2003-2007) but have been acquired at different resolutions. I would like to perform a simple Spearman correlation, but I don't really know how to do it. I was thinking about some interpolation to let the data points match somehow, but unfortunately, I am not able to do this by myself.
Would you be able to help me out with this matter?

A: I have no idea

*

*what these variables are (and hence on whether one is a response, and so forth)

*how far each series is exact for or known at the daily dates specified (in particular,   GWL looks like monthly levels, with just a conventional publication or reference date of day 15 in each month)

*how to approach this in R, but on CV statistical answers are expected. I used Stata.
On the face of it interpolation could be indulged and most of the structure in the data comes from the first year or so of data, although it's exaggerated by extrapolation, which is as usual is probably a bad idea.
The plots show the original data, each series interpolated and extrapolated linearly and a scatter plot for the data in common, with join in time order.
I don't hold out much hope that a Spearman correlation would be helpful, but it is possible after interpolation.
I haven't tried to look at e.g. cross-correlation, let alone what kind of model could make sense here.


text:
Q: CSS animation for SVG in IE10/IE11 I have this code:

<svg height="100" width="100">

  <circle class="svg-circle" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

It works well in modern browsers. Can I make it works in IE10/IE11? Or I need to use only Javascript?

A: Well, is it force on rotating the <circle/>?
Because you can easily rotate <svg></svg> in all browsers!
If yes, so you are in big trouble because in IE your problem is not only CSS3 support, you going to have some problem with JS, and that's because of rotateX or rotateY!
And even worst, you going to have some problem with animating it in jQuery!
So I used VELOCITY.JS to animating it and you can see this [ SAMPLE ] on IE and change rotateZ by rotateY! (to see rotateY is not working on SVG childs like path, circle, etc)
It seems you have to change your plan!
Hope to help! And by the way! by puting transition on hover state, you don't have it on hover-back!

A: After long researching I came to the conclusion the best way for cross-browser support — put image in
 as background-image and apply CSS to it.
JSFiddle

.circle {
    width: 100px;
    height: 100px;
    background: url(http://imgh.us/circle_5.svg) no-repeat;
    background-size: 100px 100px;
    -webkit-transform: rotateY(0);
    transform: rotateY(0);
}

    .circle:hover {
        -webkit-transform: rotateY(360deg);
        transform: rotateY(360deg);
        -webkit-transition: all 0.7s;
        transition: all 0.7s;
    }


text:
Q: Динамический блок на сайте Есть блок с картой и есть зеленая панель, на которой отображается информация при клике на метку на карте:

Но когда метка не выбрана - зеленое поле пустое:

Я хочу скрывать его, когда метка на карте не выбрана и чтобы оно раскрывалось, когда я кликну по метке.
Вот часть кода, где реализован вывод информации при клике по метке:

                More details

Это зеленое поле - фон элемента .header-section. Этот элемент содержит и карту и выводимую при нажатии информацию.


text:
Q: Shopify - Change display when switching the variants (liquid) I would like to add a new function to the product details page that shows me the current quantity of the variant that is in stock.
I get this far with Liquid, only if another variant is selected, the display of the amount does not change,
Anyone of you have any ideas how I can do that?
This shows me the current variant, but does not change when I change the selection.
{% - for variant in product.variants -%}
{{current_variant.inventory_quantity}}
{% - endfor -%}

A: You can't use Liquid for this. Liquid is just Shopify's templating language and is only useful for the initial page render.

A: I know how to do this. You need to use vue so it's reactive on the front end, also each product with variants now has to be a collection. You will need to loop through the products in the collection and get the linked products with javascript.
So let's say you have a specific product and you have three versions of it, you would actually create three separate products.
The next thing to do is link them with liquid and javascript, so in your product.liquid file open a set of script tags and you would start it like this
{% assign current_product = product %}

const product = (function() {
  const product = {{ product | json }};
  return product
})();

const linked_products = (function() {
  const linked_products = []
  {% for collection in current_product.collections %}
    {% for product in collection.products %}
      {% if product.id != current_product.id and product.title == current_product.title %}
      product = {{ product | json }}

      linked_products.push(product);
      {% endif %}
    {% endfor %}
  {% endfor %}
  return linked_products;
})();

This is just to get the ball rolling but you will need to handle quite a bit of other things and this is quite a large project.


text:
Q: Facebook Android SDK 4.0.1 What is the App Call ID? Im using the Facebook SDK for android to post a photo to facebook, and i use FacebookBroadcastReceiver to later get confirmation that the post succeded, and my goal is to get that post id.
I noticed that because i share a photo, facebook always takes the upload to the background hence FacebookCallback<Sharer.Result> callback onSuccess(Sharer.Result result) always gets result.getPostId() as null, but unfortunately FacebookBroadcastReceiver's onSuccessfulAppCall(String appCallId, String action, Bundle extras) dont give me access to the post id either (afaik), i am assuming there is a way to use appCallId to get the post id, anyone knows how? or is there another way to get the post? whats this app call id purpose for the SDK user anyway?

A: At this time the SDK does not return the object ID of the completed image upload. If you inspect e.g. the Bundle in HelloFacebookBroadcastReceiver. onSuccessfulAppCall(String, String, Bundle) at runtime, you'll find that it contains nothing more than what the appCallId and action give you already.
Additionally, there is no way for your app to know which appCallId will be used beforehand. Because of this, you cannot create e.g. a progress bar in your app that completes when the photo was indeed uploaded.


text:
Q: How Lagrange equations imply Newton equation Sorry for my English (it's not my mother language).
 I'm self-studying Mechanics and I'm have a little problem :
We can see that in Landau's book or in Wikipedia that when we inject the Lagrangian in Euler-Lagrange equation the term $\frac{\partial v²}{\partial q}$ vanishes. So we get $$\frac{\partial L}{\partial q}= - \frac{\partial U}{\partial q}$$
here more details :
We want to proof that Euler-lagrange equation imply Newton's second law :
Euler-Lagrange equation state that

$$\frac{d}{dt}\frac{\partial L}{\partial \dot{q}} = \frac{\partial L}{\partial q}$$

And we set that, for conservative potential fields $ L= T-V(q)= \frac{1}{2}mv² - V(q) $
But if we inject L in Euler-Lagrange equation we will get
$$\frac{d}{dt}\frac{\partial L}{\partial \dot{q}} = m\frac{dv}{dt} - \frac{d}{dt}\frac{\partial V}{\partial \dot{q}}$$
And
$$\frac{\partial L}{\partial q} = \frac{1}{2}m\frac{\partial v²}{\partial q} + F$$
In Landau's  book the terms $\frac{\partial V}{\partial \dot{q}}$ and $ \frac{1}{2}m\frac{\partial v²}{\partial q}$ vanishes without any explanation! Then I'm asking:
Why these terms vanish?

A: This is quite simple. To better visualize Newton's law let's not use generalized coordinates, instead, let's use Cartesian ones. Euler-Lagrange equations hence stands:
$$
\frac{d}{dt}\frac{\partial L}{\partial\dot x} - \frac{\partial L}{\partial x} = 0
$$
Since $L = T - V$, it is clear to know that:
$$
\frac{\partial L}{\partial x} =
\frac{\partial T}{\partial x} - \frac{\partial V}{\partial x} =
-\frac{\partial V}{\partial x}   \quad\Longrightarrow\quad
\frac{\partial L}{\partial x} = -\frac{\partial V}{\partial x} = F
$$
Now, on the other term, the potential doesn't depends on the velocity. Hence:
$$
\frac{\partial L}{\partial \dot x} =
\frac{\partial T}{\partial \dot x} - \frac{\partial V}{\partial \dot x} =
\frac{\partial T}{\partial \dot x} \quad\Longrightarrow\quad
\frac{\partial L}{\partial \dot x} =
\frac{\partial T}{\partial \dot x} = p
$$
This can be easily seen:
$$
T = \frac{1}{2}m\dot x^2 \Longrightarrow
\frac{\partial T}{\partial \dot x} = m\dot x = p
$$
Taking those results and plugging into Euler-Lagrange equations, we have:
$$
\frac{dp}{dt} - F = 0
$$
Which are, Newton's law.


text:
Q: Storing css property inside JavaScript object array I am trying to store and retrieve the id and background colors of the clicked div elements of the class "square". However, when I try to print the stored value, I am getting 'undefined'.
var colorObject = [
    {
        objColor:null,
        squareId:null
    },
    {
        objColor:null,
        squareId:null
    }
];
document.getElementById("container").addEventListener("click", function(e) {
// Event delegation used to find the clicks on the squares within the "Container"
    // e.target was the clicked element
    if (e.target && e.target.matches("div.square")) {
        console.log("Square element clicked!");

        colorObject[0].objColor=this.style.backgroundColor;
        console.log(this.objColor);
        colorObject[0].squareId=this.getAttribute('id');
        console.log(this.squareId);
   }
});

A: If you re-examine what your are passing to console.log, you'll notice that it is this.objColor and this.squareId, which are not the values which you just set. Change these to colorObject[0].objColor and colorObject[0].squareId and you would have better luck I think:
colorObject[0].objColor=this.style.backgroundColor;
console.log(colorObject[0].objColor);
colorObject[0].squareId=this.getAttribute('id');
console.log(colorObject[0].squareId);

On a side note, it's a good practice to be consistent with your spacing, and careful when uploading to SO because sometimes it gets messed up a little.


text:
Q: How to authenticate web api calls from MVC client So I have an ASP.NET MVC application with its own users and using cookies and claim authentication. And I'm adding a Web Api application that will be hosted elsewhere. The MVC app is the only thing that should be calling the api. I'm wondering what is the proper way to authenticate the calls to the api. All the authorization checks are done in the MVC app, and for now the API doesn't care about authorization, just authentication.
My first thought was just have one "application user" that will request a bearer token then pass that along with each request. The web api will authenticate this user and give the token. Does that sound correct? Is there a better way?
And if, in the future, the web api does care about authorization, what would be the proper way to make the api calls as the logged in user?
Thanks!

A: If the applications don't share the cookie a proper way of doing this would be using the OAuth 2.0 protocol you will need

*

*OAuth server in Web Api

*OAuth client in your MVC app.

Your users will put username and password in your MVC app(OAuth client) and through that you will get a bearer token from the Web Api(OAuth server), you can use that token for every other session requests by putting it in the Authentication header.
This particular OAuth flow is called Password Credentials Flow and can be used when you need to authenticate a user from within a trusted application(as your MVC app).

*

*More about  OAuth

*More about  Password
Credentials Flow


text:
Q: How to create a list in dart with user defined index values? I want to create multidimensional array in Dart as follows:
arr[index1][0]=value1;
arr[index2][1]=value2;

index1 & index2 will not be 0&1, they should be user defined as required.
How can we define these type of arrays in dart? Please help.

A: index1 and index2 it is required to be 0 or 1.you can just, if it is not 0 or 1 ask him to type again.


text:
Q: Is it possible to set transition when linking like this? I have a problem with ajax requests, which forces me to use javascript linking. I link this way:
window.location.href = ('file:///android_asset/www/custom/kontakty.html');

I would like to know is it possible to set transition/animation when such link is clicked.

A: Not reliably, no..
If you are running a script until the browser changes location.. chances are that with most browsers the script would get killed once it established a connection.
What you could probably do is request the page via ajax and replace the body tag or whole page in the success handler, where you could also stop/finish your animation.


text:
Q: Twbs pagination unable to load new page data in datatable
Hi I am working on pagination and found that unable to load data from twbs plugin when i click on the 2nd page. in fact the method is called from the ajax call but the datatable data is still the same. can someone tell me what to do to fill the table with the new data from the server.
have a look to the code in thymeleaf and spring boot.

      Sr.No.
        Name

Page 1

The Controller is as folows:
@RequestMapping(value = "/getcompany", method = RequestMethod.GET)
    public String getCompany(Model model,HttpServletRequest request,Optional<Integer> pageSize, Optional<Integer> page){
        /// Getting Logged in user
        System.out.println("pageSize--------------------------------");
        System.out.println(page);
        //code added by sargam
        int evalPageSize = pageSize.orElse(INITIAL_PAGE_SIZE);
        int evalPage = (page.orElse(0) < 1) ? INITIAL_PAGE : page.get() - 1;

        System.out.println(evalPage+"--------------------------"+evalPageSize);

      Page<CompanyRegistration> compregPage = companyregister.findAll(PageRequest.of(evalPage, evalPageSize));
      List<CompanyRegistration> compregList = compregPage.getContent();
      model.addAttribute("compregList",compregList);
return "admin/company";
}

      @RequestMapping(value = "/helloo", method = RequestMethod.POST , consumes = MediaType.APPLICATION_JSON_VALUE)
        public String mainWithParamhello(@RequestBody String data, Model model, HttpServletRequest request,
                RedirectAttributes redirectAttributes) {

            System.out.println(data);
            System.out.println("Inside hello2");
             redirectAttributes.addAttribute("pageSize","10");
             redirectAttributes.addAttribute("page", "2");
            return "redirect:/getcompany";
        }

A: Some few things to look at:

*

*You want to update your HTML document once it has loaded, hence $(document).ready(...).

*Decide on the node you want changes to take effect. Use jquery selectors to update the DOM on Ajax success i.e. #shortstorage.

*Find a way to present your data from the Ajax response to a table. This example just dumps the output to the console and onto the page.

Here's something for you to learn more about, $( document ).ready()


text:
Q: function doesn't display the return value? Why it doesn't return any value?
The output should be 155 but it always display 0. why?
int main()
{
    int i=5;
    printf("%d",fun(fun(fun(fun( fun(i))))));
    return 0;
}

void fun(int i)
{
    if(i%2) return (i+(7*4)-(5/2)+(2*2));
    else return (i+(17/5)-(34/15)+(5/2));
}

But if I change
void fun(int i) // It doesn't work, case 1
    to
int fun(int i) //It works fine, case 2

If fun doesn't return any value in case 1 ( void fun(int i) ), then how come
fun(fun(fun(fun( fun(i)))))); this statement is working?

A: You have no declaration for your fun function at the time it is called so the compiler implicitly put a declaration with int return value.
In C89 if there is no visible declaration, it is as if the declaration:
extern int fun();

appeared before the function call. But as your function definition actually has void return value, your program invokes undefined behavior.
In C99, the rule for implicit function declaration has been removed and a diagnostic has to be issued.
EDIT: Actually as stated by @Shafik Yaghmour you are also having a return statement in a void function. This is a constraint violation in C89 (and C99 / C11) and the compiler has the right to stop the translation.

A: Case 1 is undefined behavior, if we look at the C99 draft standard section 6.8.6.4 The return statement says(emphasis mine):

A return statement with an expression shall not appear in a function whose return type
  is void. A return statement without an expression shall only appear in a function
  whose return type is void

but if you do not have a declaration then most likely the compiler is implying the return type as int but then there is a mismatch between the declaration and implementation, this as far as I can tell then become undefined behavior again. I am able to run this on the latest gcc with the same result but I do receive the following warnings:
warning: implicit declaration of function 'fun' [-Wimplicit-function-declaration]
warning: conflicting types for 'fun' [enabled by default]

A: Both answers provided so far (by Shafik and ouah) are correct and complementary (and +1).  But I want to stress something once more: do not ignore the warnings that a compiler gives you.  Warnings in C can often save you from a lot of trouble.
When you compile your code (e.g. in gcc), you will see:
warning: 'return' with a value, in function returning void

This plainly says that you have a function that shouldn't return anything and, still, you're trying to return an integer from it.  As the result type is explicitly declared to be void, the compiler chooses simply to ignore whatever you return; this appears as if you always return zero.  This may seem strange but, as what you're doing is undefined behavior, the compiler is entitled to do so.


text:
Q: Adding a CSS class to the options tag inside a select wrapper w/ Rails What if I need to add a class to the options tag?
<option value="testme1" class="selected">testme1</option>

I haven't been able to do this.
This is what I have
<%=  select(:user, :goalstext, Bodytarget.all.collect {|b| [ b.name, b.id ] },{"class", "test"}, :class => "selected", :class => "selected") %>

A: Try this:
<%= select(:user, :goalstext, Bodytarget.all.collect {|b| [ b.name, b.id ] },
   {}, {:class => "selected"}) %>

Remember the params' order:
select(object, method, choices, options = {}, html_options = {})

EDIT
I'm sorry, I read your question too fast. My code will add class to the select, not the options. I'll check how to do what you want... sorry!


text:
Q: checking if sum of logical variables is greater than n, with na, in r I have a dataframe with 5 binary variables (TRUE or FALSE, but represented as 0 or 1 for convenience) which can have missing values:
df <- data.frame(a = c(1,0,1,0,0,...),
                 b = c(1,0,NA,0,1,...),
                 c = c(1,0,1,0,NA,...),
                 d = c(0,1,1,NA,NA,...),
                 e = c(0,0,0,1,1,...))

     a  b  c  d  e
 1   1  1  1  0  0
 2   0  0  0  1  0
 3   1 NA  1  1  0
 4   0  0  0 NA  1
 5   0  1 NA NA  1
...

Now I want to make a variable that indicates whether the observation satisfies more than two conditions out of the five, that is, whether the sum of a, b, c, d, and e is greater than 2.
For the first row and the second row, the values are obviously TRUE and FALSE respectively. For the third row, the value should be TRUE, since the sum is greater than 2 regardless of whether b is TRUE or FALSE. For the third row, the value should be FALSE, since the sum is less than or equal to 2 regardless of whether d is TRUE or FALSE. For the fifth row, the value should be NA, since the sum can range from 2 to 4 depending on c and d. So the desirable vector is c(TRUE, FALSE, TRUE, FALSE, NA, ...).
Here is my attempt:
df %>%
  mutate(a0 = ifelse(is.na(a), 0, a),
         b0 = ifelse(is.na(b), 0, b),
         c0 = ifelse(is.na(c), 0, c),
         d0 = ifelse(is.na(d), 0, d),
         e0 = ifelse(is.na(e), 0, e),
         a1 = ifelse(is.na(a), 1, a),
         b1 = ifelse(is.na(b), 1, b),
         c1 = ifelse(is.na(c), 1, c),
         d1 = ifelse(is.na(d), 1, d),
         e1 = ifelse(is.na(e), 1, e)
         ) %>%
  mutate(summin = a0 + b0 + c0 + d0 + e0,
         summax = a1 + b1 + c1 + d1 + e1) %>%
  mutate(f = ifelse(summax <= 2,
                    FALSE,
                    ifelse(summin >= 3, TRUE, NA)))

This did work, but I had to make too many redunant variables, plus the code would be too lengthy if there were more variables. Is there any better solution?

A: I just noticed that you want NA in case the outcome of the missing value will determine the TRUE/FALSE outcome, so I have changed the answer.
Combining two if_else statements can first test if the row already have a sum of more than 2, and if not, check if the row sum plus the number of missing values is 2 or less.
library(tidyverse)
n <- 2
want <- ifelse(rowSums(df, na.rm = TRUE) > n,
               TRUE,
               if_else((rowSums(df, na.rm = TRUE) + rowSums(is.na(df)))<=n,
                        FALSE,
                        NA))

If you want to stick to base-R you can use the function ifelse() instead.

A: I am not sure what you mean by "For the fifth row, the value should be NA, since the sum can range from 2 to 4 depending on c and d."
But the following results in the vector you wish for:
test <- ifelse(is.na(df$c), NA, ifelse(rowSums(df[1:5,], na.rm=T) > 2, TRUE, FALSE))

If there is an NA value in the column c, an NA value will be inserted in the new vector test. Else, it is tested if the sum of the first 5 columns is greater than 2 - if true, TRUE will be inserted and FALSE when the sum is lower than or exactly two.


text:
Q: Prevent IIS from changing response when Location header is present I have a RESTful web service written in a PHP-based framework running on IIS which responds to a POST request with something like
Status: 201 Created
Location: [url of created object]
Content-length: [correct]

{ my: "created object" }

It seems because of the Location header IIS is adding text to the response so it becomes (HTML removed for clarity):
Status: 201 Created
Location: [url of created object]
Content-length: [incorrect!]

Document Moved
Object Moved This document may be found here
{ my: "created object" }

I don't mind the addition of the text so much, but IIS seems to be keeping the original content-length while changing the content, creating an invalid response and thus causing the consumer of the web service to give me a protocol violation error.
Is there a way to prevent IIS from mangling my response?
Edit: Never did find an answer - I ended up switching to Apache


text:
Q: iOS ES 2 render from RAM OK, verts in VBO OK but with indices in BO fails I'm extending the Xcode opengles template, got rid of the virtual es1 stuff.
Now I managed to render my model from RAM both vertexArray and indexArray,
then I managed to gen-,bind-,dataBuffer the vertexArray VBO and changed the regular RAM-pointers to offset-pointers.
This all works fine, however the next phase to place the indexAray in a BO and gen-,bind-,dataBuffer and change the RAM-pointers to offset-pointers fails :(
Are there any common pitfalls I haven't notice, to me anyone able to make a VBO should be able to make an indexArray-buffer...
The following code is done in the setupGL
    glGenBuffers(1, &geometryPtr->vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, geometryPtr->vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(geometryPtr->vertexNormalUV), geometryPtr->vertexNormalUV, GL_STATIC_DRAW);
    //
    glGenBuffers(1, &geometryPtr->vertexIndicesBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, geometryPtr->vertexIndicesBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(geometryPtr->indices), geometryPtr->indices, GL_STATIC_DRAW);

Then the basic idea in the render routine
    glBindBuffer(GL_ARRAY_BUFFER, geometryPtr->vertexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, geometryPtr->vertexIndicesBuffer);
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 32, BUFFER_OFFSET(0));
    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 32, BUFFER_OFFSET(12));
    glEnableVertexAttribArray(GLKVertexAttribNormal);
    glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_TRUE, 32, BUFFER_OFFSET(24));
    glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
    //
    glDrawElements(GL_TRIANGLES, trianglesCount*3, GL_UNSIGNED_SHORT, (void *)offset);
    glDrawElements(GL_TRIANGLE_STRIP, triangleStripOffsets[m], GL_UNSIGNED_SHORT, (void *)offset);

Please help? :)
Niels

A: I've answered the question in the comments, following the suggestion of Mr. Larson I will supply an (official) answer to close the question.
To elude further, I basically assumed sizeof() would make the system ask the system-memory-manager to ask the size, assigned to the pointer send...
Niels
Ps.
Thanks Mr. Larson.


text:
Q: Generate random variables with negative binomial distribution in R How do I create a function in R in order to generate "n" random variables with a negative binomial distribution?
This is for homework, so rnbinom doesn't help.

A: *

*The cdf of the Negative Binomial distribution $\mathrm{Neg}(m,p)$ is available as pnbinom(x,n,p), which means $\mathbb{P}(X\le x;n,p)$. You can alternatively recode it as
$$\mathbb{P}(X\le x;n,p)=\sum_{i=1}^x {n+i-1 \choose i-1} p^i (1-p)^{n-i}$$

*The distribution can be generated from the pdf $F$ by the inverse pdf method: namely, generate a uniform variate $U$ and, when $U=u$, return $F^-(u)$ as a simulation where $F^-$ denotes the generalised inverse of $F$:
$$F^-(u)=\max\{k\in\mathbb{N};\ F(k)\le u\}$$
This means you generate a uniform variate with value $u$ and check when the pdf gets above $u$.


text:
Q: Sort table via date I'm looking to sort my table that i have (on page load) by date
heres what i have
var sortTable1 = function() {

    $("#tabledirect tbody tr")
    .detach()
    .sort(function(a, b) {

        var dataA1 = $(a)
          .find("td:eq(5)")
          .text()
          .trim();

        var dataB1 = $(b)
          .find("td:eq(5)")
          .text()
          .trim();

        return parseFloat(dataA1.substring(1)) - parseFloat(dataB1.substring(1));

    })
    .appendTo('#tabledirect');

};

However this is sorting a price field for me.
My table is populated via rails, I'm wanting the date closest to time now to be shown first.
Sam


text:
Q: Excel pivot values column to Text
I have data in Excel pivot and my text data in value column shows number instead of Text . Any one can help me please. In below image of pivot value field red circled:

A: have you tried to click on that, then "Value Field Settings..." -> "Number Format" (in the middle left corner)
but also you must understand that pivot and text values are not good "friends"


text:
Q: Mysql Query optimization and update needed Here is my Codeigniter Query
 $this->db->select('o.*,seo.price as seo_price,SUM(domain.price) as domain_price,SUM(bes.price) as bes_price, SUM(op.price) as payment_price');
    $this->db->from('order as o');
    $this->db->join("order_package_seo as seo", "seo.order_id = o.id", "left");
    $this->db->join("order_package_domain as domain", "domain.order_id = o.id", "left");
    $this->db->join("order_package_bespoke as bes", "bes.order_id = o.id", "left");
    $this->db->join("order_payment as op", "op.order_id = o.id", "left");
    $this->db->where("o.id" , $id);
    $query = $this->db->get();
    return $query->row();

I have 3 records in "order_package_beskope" table and 1 in others all
I want to get price from all table by Order_id
is i need to use group_by distinct or any other method need you suggestion.

A: Change the first statement like this
$this->db->select('o.*,seo.price as seo_price,domain.price ,SUM(bes.price) as bes_price, op.price as payment_price');
$this->db->from('order as o');
$this->db->join("order_package_seo as seo", "seo.order_id = o.id", "left");
$this->db->join("order_package_domain as domain", "domain.order_id = o.id", "left");
$this->db->join("order_package_bespoke as bes", "bes.order_id = o.id", "left");
$this->db->join("order_payment as op", "op.order_id = o.id", "left");
$this->db->where("o.id" , $id);
$this->db->group_by("o.id");
$query = $this->db->get();
return $query->row();

Because, you mentioned the table "order_package_beskope" has 3 records, so only that table field "bes_price" needs the SUM. All the other tables has only one record so if you add SUM, it will get multiplied by 3(number of order_package_bespoke records).
So remove the SUM from other tables fields in SELECT and add group by o.id


text:
Q: Javascript : Extract validation object from Form configuration I am developing a dynamic form in react where the Form config data is defined in in the following format
let formConfig =  [
  //Row 1
  [
     //Column 1
    {
      code: "firstName",
      type: "text",
      required: true,
      validation: {
        type: "text",
        minLen: 4,
        maxLen: 20,
      },
    },
    //Column2
    {
      code: "lastName",
      type: "text",
      required: true,
      validation: {
        type: "text",
        minLen: 4,
        maxLen: 20,
      },
    },
  ],
  //Row 2
  [
    {
      code: "email",
      type: "email",
      required: true,
      validation: {
        type: "email",
      },
    }

  ],
];

I need to find an easy way to extract the validation data from all the fields. I have tried to use Array map function , but it looks like not the correct way to do this.
The expected result is ,
    {
      "firstName": {
      "validation": {
        "type": "text",
        "minLen": 4,
        "maxLen": 20
       }
     },

    "lastName": {
       "validation": {
          "type": "text",
          "minLen": 4,
          "maxLen": 20
        }
     },
     "email": {
        "validation": {
          "type": "email"
        }
     }
}

A: I could achieve this with the the following code

let formConfig =  [
  //Row 1
  [
     //Column 1
    {
      code: "firstName",
      type: "text",
      required: true,
      validation: {
        type: "text",
        minLen: 4,
        maxLen: 20,
      },
    },
    //Column2
    {
      code: "lastName",
      type: "text",
      required: true,
      validation: {
        type: "text",
        minLen: 4,
        maxLen: 20,
      },
    },
  ],
  //Row 2
  [
    {
      code: "email",
      type: "email",
      required: true,
      validation: {
        type: "email",
      },
    }

  ],
];

let formData = formConfig
      .flat() //Rows
      .reduce(
        //Column fields
        (obj, field) =>
          Object.assign(obj, {
            [field.code]: {
              validation: field.validation,
            },
          }),
        {}
      );

console.log("FormData : ",formData);


text:
Q: How many apps can be published in google play? I'm developing android applications. I haven't created a publisher account yet.
I want to publish my own created android apps in Google Play. There is fees of 25$. How many apps I can publish from my account? Is this one time fees (25$) or may I have to pay again in the future for this account?

A: Unlimited
This is a one-time fee (25$).

A: you can publish as many apps you want with one account & the One-Time-Fee

A: As many as you want, and Google doesn't test or really regulate what you put on the market. So if it's a half-broken demo you can still post it.


text:
Q: How to allow data to be visible and easily accessible even after closing the browser window? I am trying to create a website so that a school can input a student name, chromebook serial number, grade and if the chromebook is in the school or distributed to a students home. I want to make the data accessible even if they close the window. How can I do this? Here is my form data below:
Form.js

Add a new item to the table:

        <form onSubmit={this.props.handleFormSubmit}>

          Serial Number:
          <input id="laptopTag" value={this.props.newLaptopTag}
            type="text" name="laptopTag" maxLength="15" placeholder="ABCDE12345"
            onChange={this.props.handleInputChange} required/>

          Student Name:
          <input id="studentName" value={this.props.newStudentName}
            type="text" name="studentName" placeholder="John Doe"
            onChange={this.props.handleInputChange} required/>

          Student Grade:
          <input id="studentGrade" value={this.props.newStudentGrade}
            type="text" name="studentGrade" placeholder="6" maxLength="2"
            onChange={this.props.handleInputChange} required/>

          Status:
          <input id="status" value={this.props.newStatus}
            type="text" name="status" placeholder="D/H" maxLength="1"
            onChange={this.props.handleInputChange} required/>

          <button type="submit" value="Submit">Add Item</button>
        </form>

App.js

class App extends Component {
  constructor() {
    super();

    this.state = {
      laptopTag: '',
      studentName: '',
      studentGrade: '',
      status: '',
      items: []
    }
  };

  handleFormSubmit = (e) => {
    e.preventDefault();

    let items = [...this.state.items];

    items.push({
      laptopTag: this.state.laptopTag,
      studentName: this.state.studentName,
      studentGrade: this.state.studentGrade,
      status: this.state.status,
    });

    this.setState({
      items,
      laptopTag: '',
      studentName: '',
      studentGrade: '',
      status: '',
    });
  };

  handleInputChange = (e) => {
    let input = e.target;
    let name = e.target.name;
    let value = input.value;

    this.setState({
      [name]: value
    })
  };

  render() {
    return (

        <Form handleFormSubmit={ this.handleFormSubmit }
          handleInputChange={ this.handleInputChange }
          newLaptopTag={ this.state.laptopTag}
          newStudentName={ this.state.studentName }
          newStudentGrade={this.state.studentGrade}
          newStatus={this.state.status}
           />

    );
  }
}

Any help would be greatly appreciated!

A: To make the data persistent you can in the Browser world make use of Web Storage API called local Storage.
MDN Docs for LocalStorage:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Other best option is to make use of NodeJS(or any server BE technology and use Database(like Mongo DB) to store data and get, post data back and forth via APIs.


text:
Q: PouchDB - start local, replicate later Does it create any major problems if we always create and populate a PouchDB database locally first, and then later sync/authenticate with a centralised CouchDB service like Cloudant?
Consider this simplified scenario:

*

*You're building an accommodation booking service such as hotel search or airbnb

*You want people to be able to favourite/heart properties without having to create an account, and will use PouchDB to store this list

*

*i.e. the idea is to not break their flow by making them create an account when it isn't strictly necessary

*If users wish to opt in, they can later create an account and receive credentials for a "server side" database to sync with

At the point of step 3, once I've created a per-user CouchDB database server-side and assigned credentials to pass back to the browser for sync/replication, how can I link that up with the PouchDB data already created? i.e.

*

*Can PouchDB somehow just reuse the existing database for this sync, therefore pushing all existing data up to the hosted CouchDB database, or..

*Instead do we need to create a new PouchDB database and then copy over all docs from the existing (non-replicated) one to this new (replicated) one, and then delete the existing one?

I want to make sure I'm not painting myself into any corner I haven't thought of, before we begin the first stage, which is supporting non-replicated PouchDB.

A: It depends on what kind of data you want to sync from the server, but in general, you can replicate a pre-existing database into a new one with existing documents, just so long as those document IDs don't conflict.
So probably the best idea for the star-rating model would be to create documents client-side with IDs like 'star_<timestamp>' to ensure they don't conflict with anything. Then you can aggregate them with a map/reduce function.


text:
Q: different admin login result when setting DEBUG to false i encountered a very weird situation. Two VMs, one is rented from BandWagonHost, another one locates on my desktop, installed in VMware, same OS, cent OS 6.8. I use django-admin startproject to create the same project, then update the DEBUG from True to False in the settings.py file. Then start the development web server via 'python manage.py runserver 0.0.0.0:8000'. For the one rented from BandWagon, I can open the admin login page without losing stylesheet, while for another one, the sytlesheet can't be found, so the admin login page seems very ugly, no style. Any one encountered same before?

A: You should run this command first!
python manage.py collectstatic


text:
Q: Extending LoaderManager - How to implement "publishProgress"? Imagine I have a very simple long-running task as an AsyncTaskLoader:
public class DumbLoader extends AsyncTaskLoader{
   private static final String TAG = "DumbLoader";

   public DumbLoader(Context context) {
       super(context);
   }

   @Override
   public List<String> loadInBackground() {
       List<String> allData = new ArrayList<>();
       List<String> someData = DummyData.getItems();

       notify(someData.size()) ;// publish amount of elements of someData

       List<String> someOtherData = DummyData.getSomeOtherItems();
       notify(someOtherData.size()); //publish amount of elements of someOtherData
       allData.addAll(someData);
       allData.addAll(someOtherData);
       return allData;
   }
}

And I have an activity implementing LoaderCallbacks:
@Override
public Loader<List<String> onCreateLoader(int i, Bundle bundle) {
     return new DumbLoader(this);
}

@Override
public void onLoadFinished(Loader<String> dummyLoader, List<String> result) {
   // do something with result
}

@Override
public void onLoaderReset(Loader<String> dummyLoader) {

}

How would you implement an AsyncTask-like publishProgress?
The whole purpose of using LoaderManager is to not have to work with references, when Context/Orientation changes - however, with publishProgress the only way I can think of is passing a Handler into my DumbLoader which then notifies me. Is this a safe way? Are there better ways?
Edit: My example might be a bit misleading. In case of having two seperate functions which both return the values of my "final" result I could easily call the AsyncTaskLoader seperately for each function. I modified it to visualize that the data "published" can be different from the final result (in this example, I would like to know the size of the data, but not the data).

A: An indeterminate ProgressBar seems to me the obvious choice, for this use case. I would instantiate it when the onCreateLoader is called and dismiss it in onLoadFinished

however, with publishProgress the only way I can think of is passing a
  Handler into my DumbLoader which then notifies me. Is this a safe way?
  Are there better ways?

I would use the LocalBroadcastManager. The intent will be broadcasted only within your app. In your Activity/Fragment register a BroadcastReceiver and update the progress when onReceiver is invoked. Nice thing of BroadcastReceiver is that it runs always on the ui thread


text:
Q: Display dynamic modal vuetify v-dialog in component Nuxtjs3 I want to open a dynamic modal on v-card onclick, each card clicked will change the content of the v-dialog.
In my case it open once and then nothing happen.
here the view
<template>

        <OrderComment :display="display"/>

Commandes à Livrer

        <v-row>

            <v-col lg="3" sm="6" v-for="order in orders.orders" v-bind:key="order.id" class="mt-16">

                <v-card @click="displayModal(order.id)">
                    <v-card-title align="center" class="big-font">
                        {{ order.id }}
                    </v-card-title>
                    <v-divider class="mx-4"></v-divider>
                    <v-card-text>
                        {{ order.date_upd }}

                        <OrderPartialAddress :id_address_delivery="order.id_address_delivery"/>
                    </v-card-text>
                    <v-card-actions>
                        <v-btn @click="changeStatus(order.id)">
                            Passer en Livre
                        </v-btn>
                    </v-card-actions>
                </v-card>
            </v-col>
        </v-row>

</template>

method in script
const display = ref(false);
function displayModal(id_order: String) {
    display.value = true;
    console.log(display.value)
}

And my component
<template v-slot:activator="{ on, attrs }">

        <v-dialog
            v-model="props.display"
            width="500"
        >
            <v-card>
                <v-card-title class="text-h5 grey lighten-2">
                    Commentaires
                </v-card-title>

                <v-card-text>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                </v-card-text>

                <v-divider></v-divider>

                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn
                        color="danger"
                        text
                        @click="display = false"
                    >
                        Fermer
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>

</template>

So finally it works only once. I don't know what is wrong or how i have to achieve it. I even don't know if i have to use v-slot:activator


text:
Q: Memory consumption of jars with many classes? Scenario
Let's assume an application with a dependency. The dependency comes in form of a jar file. The  dependency jar file contains many classes. The application uses only one class from the dependency jar.
Question
Do the unused classes included in the dependency jar lead to higher memory consumption, even if they are not used (directly and indirectly) by the application.
I guess it's a question of the classloader implementation, but do classloaders really behave differently in this question? I think it would be enough to answer this question for the default JRE / JDK classloaders and maybe classloaders of common containers and application servers.
Does the classloaders load the entire jar file? And is it just temporary to load the needed classes and after that the jar file is removed from memory? Or are all classes loaded, even the unused ones?
Background
When I organize my projects, I tend to split the classes etc. in many small projects. I don't do this to save disk space, because disk space is relatively cheap. I do this because it increases reusability. I don't have much fear of the "dependency hell" even if the number of small projects gets pretty high. I use dependency- / build-tools to automatically resolve the dependencies for me.
So there is the diskspace aspect and the code / resuability aspect of project organization. The third aspect of project organization is the runtime / classloader aspect which I'd like to be answered. While applications rarely run out of disk space, the shortage of memory is a realistic scenario, depending on the enviroment.

A: The short answer is YES. Memory consumption is higher.
The classloader does not load the entire jar file. Through a ZipFile object it only keeps a list of classes and an offset on where they can be found in the jar file. If the jar file has a lot of classes this list is bigger thus it consumes more memory.
This memory consumption is not related to the jar file size itself but to the number of classes inside.
Beside this only loaded classes use memory.

A: Memory consumption will be higher due to sheer size of jars that need to be opened and processed. But as for the classes - no, in general classes are loaded "on demand", apart from perhaps a handful from the bootstrap classpath. It does depend on the classloader implementation indeed, though.
As for cleanup of unused classes... yes, the JVM does that, in a manner similar to ordinary, reachability-based garbage collection. Be wary of classloader leaks though - sometimes the class object remains reachable in a not-at-all-obvious way, which manifests itself especially nasty in containers, and easily leads to te dreaded OutOfMemoryException: PermGen space exceptions.


text:
Q: JNI stale local reference error accessing the caller object I can't get rid of this error message

JNI ERROR (app bug): accessed stale local reference 0x... (index ...)

I'm trying to access from native the isInterrupted() method of the JNI caller class, which is a Java thread. The thread loop is entirely native, spawns other pthreads and holds mutexes. I need a way for the main Android activity to inform the thread that it should stop e.g. by Java's interrupt() at the first safe moment.
The scenario is quite simple and clean, nothing else happens between the lines:
public class MyThread extends Thread {
  public native static int native_world_entry();
  public void run() {
    native_world_entry();
  }
  static {
   System.loadLibrary("mylib");
  }
}

The native code being the following:
jint Java_..._1entry(JNIEnv* env, jobject thiz) {
  //jobject jj = (*env)->NewGlobalRef(env, thiz);
  jclass sclass = (*env)->FindClass(env, "java/lang/Thread");
  jmethodID inted = (*env)->GetMethodID(env, sclass, "isInterrupted", "()Z");
  LOGI("Checking");
  jboolean status = (*env)->CallBooleanMethod(env, thiz, inted);
  ...
}

All good untill CallBooleanMethod() as previous calls are successful and "Checking" is displayed.
I've tried to add the commented line and change CallBooleanMethod()'s argument accordingly but the error is the same.
Besides the error I don't catch the reason why a global reference is needed in this case.. Any help is appreciated.

A: I think it is because native_world_entry is static. So thiz is not MyThread istance. It is MyThread class instance.
Add extra param to native_world_entry method to pass thread handler explicitly, e.g. native_world_entry(this).
P.S. Also you can use Thread.currentThread() to get current thread.


text:
Q: DUP! Errors in ping 10.0.1.0 When I ping my network at 10.0.1.0, I am seeing the following (DUP!) error. I know DUP! in pings  refers to duplicates, and is not good. Should I be concerned, and if so, can someone point me in a direction to solve this?
MacBook:~ pclark$ ping 10.0.1.0

PING 10.0.1.0 (10.0.1.0): 56 data bytes
64 bytes from 10.0.1.1: icmp_seq=0 ttl=255 time=1.171 ms
64 bytes from 10.0.1.2: icmp_seq=0 ttl=64 time=1.556 ms (DUP!)
64 bytes from 10.0.1.6: icmp_seq=0 ttl=64 time=3.649 ms (DUP!)
64 bytes from 10.0.1.3: icmp_seq=0 ttl=64 time=219.607 ms (DUP!)
64 bytes from 10.0.1.8: icmp_seq=0 ttl=64 time=221.927 ms (DUP!)
64 bytes from 10.0.1.1: icmp_seq=1 ttl=255 time=1.165 ms
64 bytes from 10.0.1.2: icmp_seq=1 ttl=64 time=1.445 ms (DUP!)
64 bytes from 10.0.1.3: icmp_seq=1 ttl=64 time=1.456 ms (DUP!)
64 bytes from 10.0.1.8: icmp_seq=1 ttl=64 time=4.549 ms (DUP!)
64 bytes from 10.0.1.6: icmp_seq=1 ttl=64 time=4.559 ms (DUP!)

A: Looks like you get the same response (the same ICMP sequence number) from different ip addresses. I guess that your subnet is 255.255.255.0 (your network uses ip address range 10.0.1.x). If that's the case, no device should use the .0 or .255 address. The first address (.0) is known as the network address and that last address is the broadcast address. Most devices in the network should respond if you ping the broadcast address. Some (but not all) devices will also respond if you ping the network address. It appears that several devices (.1, .2, .3, .6 and .8) responded to your ping request.
Your solution: give the device that's on .0 an other ip address. How you should do that dependes on your device. I think there are three common scenario's:

*

*The .0 device is your router: log in to your router management software and change its address.

*The .0 device had a static ip address: change it on that device to something else

*The .0 device gets it from a DHCP server: change your DHCP settings to hand out ip addresses starting at .1 instead of at .0


text:
Q: SpriteKit not loading Atlas with tga pics I made a simple program that uses a texture atlas to load an animation on the screen. When I used an atlas with png images everything worked fine. However when I tried using another atlas that used tga images all I got was the white box with the red x. Whats going on? Do SpriteKit atlases not support the tga format?

A: SKTextureAtlas does not support Truevision's TGA format. I suggest you convert the TGA images to one of the supported file formats: PNG, JPEG, TIFF, BMP, or GIF.


text:
Q: How to deploy multiple reactjs applications on server? I'm new to reactjs. I have some doubts on deploying react js on server.  Lets say, I have 2 react js build folders (admin panel, frontend) and one nodejs folder for backend. Is it possible to put/deploy all the three in same domain with different ports ?
For ex.,
Frontend - https://example.com/login (proxy configured) , port : 4200
Admin panel - https://example.com:5200/adminpanel , port : 5200
Backend (node) - https://example.com:8443/api/something , port : 8443
Or any other efficient way to deploy ?

A: Deploy all three apps and use nginx
location /adminpanel{
        proxy_pass  http://127.0.0.1:5200/adminpanel;
        }
location ~ ^/api/?(.*){
        proxy_pass  http://127.0.0.1:8443/api/$1;
        }
# root mapping
location /{
        proxy_pass  http://127.0.0.1:4200/login;
        }


text:
Q: SwiftUI How to dynamically make a view's leading equal to its top distance to superview The image below shows a VStack with three lines of text.
The VStack is inside a ZStack that also contains a blue square.
I have been able to position the blue square such that its vertical center is equal to the vertical center of the Text that reads "Line 1". This relationship has to be maintained regardless of the text size. In other words, I can't hardcode a specific value for the blue square's vertical offset because it depends on the size of the Text to its right.
Notice the green lines above and below the text. This represents the top and bottom edges of the container view.
What I'd like to be able to do (but can't figure out how) is position the blue square's leading edge the same distance to the right as the blue square's top edge is to the top green line.
For example, say after the blue box is positioned vertically its top happens to be 12 pts down from the top green line. In that case the box should move 12 pts to the right of the container's left edge.

Here is the code I've working on:
import SwiftUI

extension Alignment {
    static let blueBoxAlignment = Alignment(horizontal: .blueBoxLeadingAlignment, vertical: .blueBoxCenterAlignment)
}

extension HorizontalAlignment {
    private enum BlueBoxHorizontalAlignment: AlignmentID {
        static func defaultValue(in d: ViewDimensions) -> CGFloat {
            return d[HorizontalAlignment.leading]
        }
    }
    static let blueBoxLeadingAlignment = HorizontalAlignment(BlueBoxHorizontalAlignment.self)
}

extension VerticalAlignment {
    private enum BlueBoxCenterAlignment: AlignmentID {
        static func defaultValue(in d: ViewDimensions) -> CGFloat {
            return d[VerticalAlignment.center]
        }
    }

    static let blueBoxCenterAlignment = VerticalAlignment(BlueBoxCenterAlignment.self)
}

struct TestView: View {
    var body: some View {
        ZStack(alignment: .blueBoxAlignment) {
            VStack(spacing: 50) {
                Text("Line 1")
                    .alignmentGuide(.blueBoxCenterAlignment) { d in d[VerticalAlignment.center] }
                Text("Line 2")
                Text("Line 3")
            }
            .padding([.top, .bottom], 50)
            .frame(maxWidth: .infinity)
            .border(.green)

            Rectangle()
                .fill(.blue)
                .opacity(0.5)
                .frame(width: 50, height: 50)
        }
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
            .edgesIgnoringSafeArea(.bottom)
    }
}

A: Possible approach is to use anchor preferences, because they allows to read different position properties of targeted view and use within views layout cycle.
Here is a demo. Tested with Xcode 13.2 / iOS 15.2

Note: used padding instead of offset, because offset does not affect layout, just in case.
struct PositionPreferenceKey: PreferenceKey {   // << helper key !!
    static var defaultValue: [Anchor<CGPoint>] = [] // << use something persistent

    static func reduce(value: inout [Anchor<CGPoint>], nextValue: () -> [Anchor<CGPoint>]) {
        value.append(contentsOf:nextValue())
    }
}

struct TestView: View {
    @State private var offset = CGFloat.zero

    var body: some View {
        ZStack(alignment: .blueBoxAlignment) {
            VStack(spacing: 50) {
                Text("Line 1")
                    .alignmentGuide(.blueBoxCenterAlignment) { d in d[VerticalAlignment.center] }
                Text("Line 2")
                Text("Line 3")
            }
            .padding([.top, .bottom], 50)
            .frame(maxWidth: .infinity)
            .border(.green)

            Rectangle()
                .fill(.blue)
                .opacity(0.5)
                .frame(width: 50, height: 50)
                .anchorPreference(
                    key: PositionPreferenceKey.self,
                    value: .top               // read position from top !!
                ) { [$0] }
                .padding(.leading, offset)    // << apply as X !!
        }
        .backgroundPreferenceValue(PositionPreferenceKey.self) { prefs in
            GeometryReader { gr in
                Color.clear.onAppear {
                    self.offset = gr[prefs[0]].y  // << store Y !!
                }
            }
        }
    }
}