text:
Q: how to catch and throw errors in JSP I asked a question along similar lines yesterday as well. In that question I was suggested to have a global filter (which I already had).
So I have a JSP like below
....code...code
..tags...html...code
Object [] res = iBatisDAO.getReport_pging(null,null,0,null); //call to DB
...more code...
...tags...end

In the above code I am intentionally passing null's because I want it to fail and when it fails I want it to go to our centralized error page. I have the following in my web.xml
  <error-page>
    <exception-type>com.ibatis.common.jdbc.exception.NestedSQLException</exception-type>
    <location>/errorpages/Error.jsp</location>
  </error-page>
  <error-page>
    <exception-type>org.springframework.dao.DataAccessException</exception-type>
    <location>/errorpages/Error.jsp</location>
  </error-page>
  <error-page>
    <exception-type>javax.servlet.ServletException</exception-type>
    <location>/errorpages/Error.jsp</location>
  </error-page>
  <error-page>
    <exception-type>java.sql.SQLException</exception-type>
    <location>/errorpages/Error.jsp</location>
  </error-page>
  <error-page>
    <exception-type>org.springframework.jdbc.UncategorizedSQLException</exception-type>
    <location>/errorpages/Error.jsp</location>
  </error-page>

the 'control' comes to the above JSP via a global filter that I have. it has chain.doFilter() wrapped in try/catch block. When exception happens it redirects to Error.jsp.
When the error happens...it is not being caught by the centralized error page and neither is it caught by the filter.  I think filter is not catching it because when filter 'calls' the jsp...there IS no error yet.
I know call to DB is BAD inside a JSP but I am dealing with lot of legacy code.
What can I do to have errors go to centralized error page in this scenario? Also, the JSP does not have the error page imported. I would not want the option of importing an error page to all JSP's I want to have a more general solution.

A: Exceptions in JSP cannot be handled nicely, because it's too late to change the response. JSP as being a view technology is responsible for the whole response at its own. It sends the response headers and the response content. When the response headers are sent, then it's a point of no return. Even a filter ain't going to help here.
Whenever an exception occurs halfway a JSP, then the response will be abruptly aborted and the client will face a blank or a halfbaked page and the exception can at highest only be logged to the server log. Maybe along an IllegalStateException: response already committed whenever an attempt is made to redirect/forward/display the error page while that's impossible, because the response is already committed.
In short: do not write raw Java code in JSP files. Put them in Java classes such as (in)direct in a Servlet. It get processed before the JSP get displayed. This way there's plenty of room to change the destination of the response.
If you insist in using JSP for business logic (which I do not recommend), then an alternative is to put all the business logic to the top of the JSP file, before any template text (HTML and so on) is to be sent to the response. If you're lucky, the servletcontainer will be able to change the response to an error page whenever an exception is been thrown.

A: You've undertaken a wrong approach. You must not have any logic processing code (business logic) in your JSP files. JSP is a view technology. Use servlets or some action/component framework (Struts2 / Spring MVC / JSF / etc.) to handle the business logic.
As for the filter approach - it is a good solution, but the filter must be mapped to /* (using <filter-mapping>):
<filter>
   <filter-name>exceptionFilter</filter-name>
   <filter-class>com.yourpackage.YourFilter</filter-class>
</filter>
<filter-mapping>
   <filter-name>exceptionFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>


text:
Q: Checking lines of a file against a regex I am using the Regex.Match method to find a credit card number within a file (for PCI compliance)
I interate through the lines (strLine) of a file and check each one against a regex (m_strRegEx):
Regex.Match(strLine, m_strRegEx)

string strLine = "4111111111111111"

This works fine, but if the line contains other characters, for example strLine might =:
string strLine = "fhj*4111111111111111op)"

The regex does not then pick the cc number up, how would it be possible to overcome this issue?
The regex I am using is:
^4[0-9]{12}(?:[0-9]{3})?$

A: This is because your regex is anchored to the start and end of the string with ^ and $. This means that the entire string has to match your regex and not just a substring.
Remove the ^ and $ from the regex to perform a substring match:
4[0-9]{12}(?:[0-9]{3})?

Quick test:
PS> 'fhj*4111111111111111op)' -match '4[0-9]{12}(?:[0-9]{3})?'; $Matches
True

Name                           Value
----                           -----
0                              4111111111111111

A: As your regex starts with ^ and ends with $ this means that the match must be from the start to the end of the line. Just remove these characters from your regex pattern and it should work as you require.

A: You should remove the anchors:
4[0-9]{12}(?:[0-9]{3})?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Por que o valor em bytes é exibido como 4? Eu estou usando uma matriz 2x2 com um simples ponteiro e quero exibir os valores do mesmo.
#include <stdio.h>
#include <stdlib.h>

typedef struct matriz mat;

struct matriz {

    int lin;
    int col;
    int *arr;
};

mat* cria(int lin, int col) {

    mat *m = malloc(sizeof(mat));
    m->lin = lin;
    m->col = col;
    m->arr = malloc(lin * col * sizeof(int));
    return m;
}

void exibe(mat *m) {

    for(size_t i = 0; i < sizeof(m->arr); i++) {
        printf("%3d", m->arr[i]);
    }
}
int main() {

    mat *m;
    m = cria(2, 2);
    m->arr[0] = 24;
    m->arr[1] = 16;
    m->arr[2] = 13;
    m->arr[3] = 56;

    exibe(m);

    return 0;
}

Assim sizeof(m->arr) exibe 4. Ele não deveria exibir 16 bytes (4 x 4)?

A: Não. O que está guardado em m->arr? O retorno de malloc(), que é um ponteiro. Em arquitetura 32 bits um ponteiro tem 4 bytes, se deseja o tamanho da sequência, tem que passar como argumento para a função. Mas tenho a impressão que nem é o caso, o que deseja é a quantidade de elementos, que também deveria passar. Como a estrutura tem essa informação, nem precisa passar nada, pode só usar lin * col.
Na verdade este código parece ter outros problemas, mas não investiguei a fundo. E o código não está criando matriz alguma, só uma sequência simples.

A: O programa que você quer deveria ser assim:
#include <stdio.h>
#include <stdlib.h>

typedef struct matriz mat;

struct matriz {
    int lin;
    int col;
    int *arr;
};

mat* cria(int lin, int col) {
    mat *m = malloc(sizeof(mat));
    m->lin = lin;
    m->col = col;
    m->arr = malloc(lin * col * sizeof(int));
    return m;
}

void destroi(mat *m) {
    if (m == NULL) return;
    free(m->arr);
    free(m);
}

int ler_elemento(mat *m, int i, int j) {
    return m[i * m->col + j];
}

int definir_elemento(mat *m, int i, int j, int valor) {
    m[i * m->col + j] = valor;
}

void exibe(mat *m) {
    for (int i = 0; i < m->lin; i++) {
        for (int j = 0; j < m->col; j++) {
            printf("%3d ", ler_elemento(m, i, j));
        }
        printf("\n");
    }
}

int main() {
    mat *m;
    m = cria(2, 2);
    definir_elemento(m, 0, 0, 24);
    definir_elemento(m, 0, 1, 16);
    definir_elemento(m, 1, 0, 13);
    definir_elemento(m, 1, 1, 56);

    exibe(m);
    destroi(m);

    return 0;
}

Observe que criei as funções ler_elemento e definir_elemento para centralizar, abstrair e encapsular a lógica de acessar-se os elementos nas posições corretas. Desta forma, as demais partes do código não precisam se preocupar com os detalhes mais complicados de como fazer para achar a posição correta no array de elementos da matriz e nem mesmo vão precisar se preocupar em saber que a estrutura mat tem um array lá dentro. Com isso, se mais tarde você quiser alterar a forma como a estrutura mat organiza os seus dados, apenas as funções ler_elemento, definir_elemento e cria precisarão ser alteradas, o que evita mudanças em cascata, onde a alteração de um pequeno detalhe forçaria a necessidade de promover-se grandes mudanças no código todo.
Também acrescentei uma função para desalocar o mat. É uma boa prática sempre desalocar aquilo que você aloca, e portanto, sempre que você tiver uma função que cria alguma coisa por meio de alocação dinâmica de memória, você já deve imediatamente ter a mão a função que desaloca essa mesma coisa.
Quanto ao sizeof(m->arr), isso daí vai te dar o tamanho do ponteiro m->arr ao invés do tamanho da matriz. Observe que arr é do tipo int *, e portanto sizeof(m->arr) é o mesmo que sizeof(int *). O resultado é 4 porque um ponteiro para inteiro ocupa 4 bytes no seu computador, não importando para onde esse ponteiro aponta ou mesmo se ele aponta ou não para um endereço de memória válido.
A finalidade do sizeof é medir quanta memória estática uma determinada estrutura ocupa, e ele é determinado em tempo de compilação, e não de execução. Para alocação dinâmica de memória, o tamanho dos dados alocados depende de informações que só estão disponíveis em tempo de execução, e portanto não há como o compilador saber qual ele seria. A solução é você calcular o tamanho você mesmo se precisar, e no fim das contas, você não precisa disso para apenas exibir a matriz na tela.


text:
Q: Google Earth Engine code for calculating NDWI from Sentinel 2 image collection I am trying to calculate NDWI from Sentinel 2 dataset from Landsat 8 Here's my code for Landsat 8
// Load an image.
var image = ee.ImageCollection('COPERNICUS/S2').filterDate('2017-09-01','2018-09-10');
// Define the visualization parameters.
var vizParams = {bands: ['B6', 'B5', 'B2'], min: 0, max: 0.5,gamma: [0.95, 1.1, 1]};
// Center the map and display the image.
Map.addLayer(image, vizParams, 'Band652');
// Load an image.
var image = ee.ImageCollection('COPERNICUS/S2').filterDate('2017-09-01','2018-09-10');
// Create an NDWI image, define visualization parameters and display.
var ndwi = image.normalizedDifference(['B3', 'B5']);
var ndwiViz = {min: 0.5, max: 1, palette: ['44c9f1', '1637f1']};
Map.addLayer(ndwi, ndwiViz, 'NDWI', false);

// Mask the non-watery parts of the image, where NDWI < 0.10.
var ndwiMasked = ndwi.updateMask(ndwi.gte(0.10));
Map.addLayer(ndwiMasked, ndwiViz, 'NDWI masked');

When I add Sentinel 2 imagecollection then I get an error like this

image.normalizedDifference is not a function

A: The normalizedDifference function can be applied to single images. You are trying to apply it to a collection of images.
You can either map over that collection and calculate the NDWI for each image or reduce the collection to a single image.
The latter can be done by calculating the mean over time and then calculating the NDWI:
var ndwi = image.mean().normalizedDifference(['B3', 'B5']);

A: // Load an image.
var image = ee.ImageCollection('COPERNICUS/S2').filterDate('2017-09-01','2018-09-10');
// Define the visualization parameters.
var vizParams = {bands: ['B6', 'B5', 'B2'], min: 0, max: 0.5,gamma: [0.95, 1.1, 1]};
// Center the map and display the image.
Map.addLayer(image, vizParams, 'Band652');
// Load an image.
var image = ee.ImageCollection('COPERNICUS/S2').filterDate('2017-09-01','2018-09-10');
// Create an NDWI image, define visualization parameters and display.
var ndwi = image.normalizedDifference(['B3', 'B5']);
var ndwiViz = {min: 0.5, max: 1, palette: ['44c9f1', '1637f1']};
Map.addLayer(ndwi, ndwiViz, 'NDWI', false);

// Mask the non-watery parts of the image, where NDWI < 0.10.
var ndwiMasked = ndwi.updateMask(ndwi.gte(0.10));
Map.addLayer(ndwiMasked, ndwiViz, 'NDWI masked');


text:
Q: How can I implement a modulus on a list of numbers? I have a list of numbers:

6,12,24,25,7,27

How can I make it so that there is modulus at 26 so that if numbers greater than 26 appear in the list it should go back to 1?
For example, in this situation all numbers should be left alone except 27 and that should become 1.
This is the code I'm trying to run:
message = zip(message, newkeyword)
positions = [(alphabet.find(m), alphabet.find(n)) for m, n in message]
sums = [alphabet.find(m) + alphabet.find(n) for m, n in message]
#sums is were the numbers are stored
sums%=26

But I get the error:

TypeError: unsupported operand type(s) for %=: 'list' and 'int'

Any help is greatly appreciated.

A: As an alternative, if you are willing/able to convert your list to a Numpy array you can achieve this in a really simple and pythonic way (by just applying the modulo to the array):
>>> import numpy as np
>>> a = np.array([6,12,24,25,7,27])
>>> a
array([ 6, 12, 24, 25,  7, 27])
>>> a%26
array([ 6, 12, 24, 25,  7,  1])

A: The modulo operator can only be applied to two numbers, not to a whole list. You have to apply it to each item, like this:
mod_sums = [s % 26 for s in sums]

Using a list comprehension you iterate through all numbers in the sums. In the new mod_sums list you save the number s modulo 26.
This basically is the same as:
mod_sums = []
for s in sums:
    mod_sums.append(s % 26)

Only written in a cleaner and more pythonic way.
You could also add the modulo directly into the first list comprehension:
sums = [(alphabet.find(m) + alphabet.find(n)) % 26 for m, n in message]


text:
Q: Transform json data into respective file type I made an Ajax get request to obtain a file from the API source, and was returned the json data (json data below).
The filename and file type are title, and file_type respectively as per the json object returned. How do I transform this into a PNG (as per  this json data example), or any other file type for that matter depending on the json data returned.
When making the request, I need to be able to transform the json file into its object and download automatically.
I have tried suggestions as per the link below without success:
Download JSON object as a file from browser
Thanks,
Sample JSON Data
{
  "body": "iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAeFBMVEUdHRv\/\/\/8AAAALCwfExMQbGxn6+vp\/f37Ly8urq6sUFBH19fW6uroODgsGBgCGhoV2dnbn5+fh4eFVVVT29vazs7Pa2trm5ubR0dFxcXDHx8deXl2Tk5KYmJg2NjVlZWSMjIxBQUAjIyFDQ0IzMzFMTEqioqEtLSvWSZHOAAAJcklEQVR4nO2d22LiIBCGKxGjMYmnaj1rt619\/zdcYnRNOISBkIRx\/a+6a6v5BGaGAYa33rPrresHaFwvQvx6EeLXixC\/XoT49SLErxehMw1m89Wwn2u4ms8GbX1w44TjVXyYLn6JqN\/F9BCvxk0\/QJOEs\/5+l2QsSUTfRNHo+mKw2\/dnDT5FU4Tz0SZijy9F40FT9h1sRvOGnqQJwkE\/ZHSJHq6AyZozmcZNDE7nhO\/LHet5JnRFysXS+bh0TBgzvMiC7i7W9rvY7SO5JFyF9fD+QYYrh0\/ljjD+IkFtvFwB+XTXkI4IB5fEQfM9FJH04MjsOCEc7AmxsS1VooScnVgdB4SDMyGO8XKl5OygHesTHhriy0TIoXPCOGmO78oYLDslXH06H3+8KPms5ztqEYZO7adKEZl2RNgPmu2gD6Wk3wHhYNN4B32IkpO1VbUlHAauAhiYAjJsl3DSYgPmoiRskXB8bGsEFkWOVqkAG8JhKyZUVGRlcCwID6330Lso2bdBeOqih95Fdo0TDjoZgg+l36YTDkPCWZR0CsgGY\/DRJOGqIxtTFCVmcaoR4bozG1MUNXP+JoRbLwCZjLyGAWG\/WxtTlAkinHDrD6ARIphw7RMgQwSPRSjhypcxeBfYogIJZ74BMosK9IswwkHUvR\/kRQNYdAMjPHYdycgUfbsj7DTYVisFheEQwoOfgMzanN0QDn0FhLlFPeHYOzNaENEnNvSEn\/6Z0YcA1kZLOPG3j2bSZ+B0hB4PwlxkW49wYLWrok1RosmGawg37Wa2bRSc6hB6NCVUi1Tvaqgm9L6PZtL000rCEEMTsuitcn2xinCFA1AzV6wi9NrXFxUd7QhjLE3IGrFiO0MFodH2yW5FiQ2ht3MmmSoWpZSEA0yADPHdmPCMizCdmBIia0LWiKq8lIoQWRNWNK...",
  "comments": null,
  "container": "ENC~77-977-977-977-9X--_ve-_vSfvv73vv70V77-9XO-_ve-_vT7DgO-_ve-_vX5-fn9FKQdumeQp5-W6Z1k_WPY=",
  "file_type": ".PNG",
  "is_container": false,
  "last_modified": "2020-01-09T11:37:05",
  "record_number": "00\/11",
  "record_type": "Inwards Document",
  "title": "Test",
  "unique_identifier": "13112318",
  "is_public": true,
  "site": null
}

A: using JavaScript use:
window.location.href = 'data:image/png;base64,' + body;
using HTML tag:
Download
JSFiddle Download

A: dont worry - figured it out..
Although, it does not work for safari. :(
 Ajax.request({
        url: _url,

        success: function (response, opts) {
            var obj = Ext.decode(response.responseText);
            if (obj !== null) {

                var docName = `${obj.title}${obj.file_type}`;
                var a = window.document.createElement('a');
                //debugger;

                var byteCharacters = atob(obj.body);
                var byteNumbers = new Array(byteCharacters.length);
                for (var i = 0; i < byteCharacters.length; i++) {
                    byteNumbers[i] = byteCharacters.charCodeAt(i);
                }
                var byteArray = new Uint8Array(byteNumbers);

                // now that we have the byte array, construct the blob from it
                var blob1 = new Blob([byteArray], { type: "application/octet-stream" });

                //saveAs(doc, docName);
                a.href = window.URL.createObjectURL(blob1);
                a.download = docName;

                // Append anchor to body.
                document.body.appendChild(a);
                a.click();

                //// Remove anchor from body
                document.body.removeChild(a);
            }
        },

        failure: function (response, opts) {

...
            }
        });


text:
Q: Report works on development PC but throws exception on the PC where it's deployed (CrystalDecisions.CrystalReports.Engine.ReportDocument) I developed an application with Crystal Reports, when i test the project on the development PC it works, but it gives an exception on the customer PC

The type initializer for
  'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an
  exception.

also the project was developed Using VS 2010 then it completed with VS 2008,so I am developing using VS 2008 now, I'm not sure if this Could Cause the problem, and about the Setup Project i make a reference to the following DLLs:
-CrystalDecisions.CrystalReports.Engine.dll
-CrystalDecisions.ReportSource.dll
-CrystalDecisions.Shared.dll
-CrystalDecisions.Web.dll
-CrystalDecisions.Windows.Forms.dll

All DLLs have the same version number :10.2.3600.0
And i install the setup without installing anything else then .net Framework 3.5, (Do i have to install a runtime Crystal Report engine and if have to which version to install? ).
Exception Details:

System.TypeInitializationException: The type initializer for
  'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an
  exception. ---> System.IO.FileNotFoundException: Could not load file
  or assembly 'CrystalDecisions.ReportAppServer.CommLayer,
  Version=10.2.3600.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'
  or one of its dependencies. The system cannot find the file specified.
  File name: 'CrystalDecisions.ReportAppServer.CommLayer,
  Version=10.2.3600.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'
  at CrystalDecisions.CrystalReports.Engine.ReportDocument..cctor()
WRN: Assembly binding logging is turned OFF. To enable assembly bind
  failure logging, set the registry value
  [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There
  is some performance penalty associated with assembly bind failure
  logging. To turn this feature off, remove the registry value
  [HKLM\Software\Microsoft\Fusion!EnableLog].

Thanks in advance for any Help.

A: On the client's machine you need to install the Crystal Runtime for your version. Normally if you are using VS2008 you need to install Crystal Reports 2008 Runtime Package for the .NET Framework (recommended), or embed the Merge Modules for Crystal Reports 2008 Runtime into your own setup (not recommended). From here: http://resources.businessobjects.com/support/additional_downloads/runtime.asp#08
That will install Crystal Report's assemblies needed on the client. Have you done that already?
If after that you still have problems, you need to verify that the Crystal.*.dll has the same version than the ones installed on the client's machine.
If you want to use specific version of the crystal assemblies on the properties of those assemblies change the Specific Version to True in the Properties within VS
Finally, check if you are missing a Crystal SP/HotFix which makes the assemblies version differ
http://wiki.sdn.sap.com/wiki/display/BOBJ/Crystal+Reports+2008+-+Version+and+Download+information+for+SPs+and+FPs

A: Runtime Crystal Report will call that DLL to create the report.
This is what happened to me, I run on win 10 - 64 bit, and use old application.
Error appeared on app :
System.TypeInitializationException: The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=10.2.3600.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The system cannot find the file specified.

I have tried to install CRRedist2005_X64.msi, but the error is still occured, but saying something different.
I have tried to install newer version, but it is useless.
You need to install this :
CRRedist2005_x86.msi
Make sure the version of dll file.
CrystalDecisions.ReportAppServer.CommLayer, Version=10.2.3600.0

is for CR2005. Maybe higher version is for newer CR version.


text:
Q: Is there any way to simulate entries for systemverilog? I have the following input: logic SWI[7: 0], which I would like to control from another executable, in C ++ for example.
And I have the following outputs: logic LED[7:0], SEG[7: 0], which I would like to get in real time.
Is there any way to simulate systemverilog in such a way that I can simulate inputs and get outputs (in this model)?
Example code that I would like to run:
logic T1, T2;
always_comb begin
    T1 <= SWI[0];
    T2 <= SWI[1];

    LED[0] <= T1 && T2;
end

I'm sorry for bad english.

A: You can use DPI (C/C++ code linked to the simulation) to get/set values of Verilog signals. Then you can implement some IPC from this DPI code to another executable (e.g. using sockets, pipes etc.).


text:
Q: ggplot2 - Discrete value to continuous scale error when making grouped bar chart I am currently trying to use ggplot2 package to create a grouped bar chart for some chemical data. Here is an example of the data:
Well Timepoint Nitrate_avg Nitrate_stdev
1  FW231         0   16.384000     3.9628882
2  FW231         7    0.822000     0.4730544
3  FW231        30    0.000000     0.0000000
4  FW231       150    0.000000     0.0000000
5   GP02         0   12.927306     1.7843047
6   GP02         7    1.776066     0.5034165
7   GP02        30    0.000000     0.0000000
8   GP02       150    0.000000     0.0000000
9   GP01         0   12.822762     3.4921348
10  GP01         7    0.000000     0.0000000
11  GP01        30    0.000000     0.0000000
12  GP01       150    0.000000     0.0000000
13  GP03         0   10.384000     0.2665536
14  GP03         7    0.000000     0.0000000
15  GP03        30    0.000000     0.0000000
16  GP03       150    0.000000     0.0000000

I'd like to make a chart that groups Wells together by Time point. However, when trying to do this I keep getting the error "Error: Discrete value supplied to continuous scale" and I'm not sure why. Here is the code I am using.
ggplot(data = cosm_geochem, aes(x = Well, y = Nitrate_avg)) +
  geom_bar(aes(fill=factor(Timepoint))) +
  scale_x_continuous(breaks = Well) +
  scale_colour_manual(breaks = c("0", "7", "30", "150"),
                      labels = c("Day 0", "Day 7", "Day 30",
                                 "Day 150"),
                      values = c("#E69F00", "#56B4E9", "#009E73",
                                 "#F0E442")) +
  scale_fill_manual(breaks = c("0", "7", "30", "150"),
                    labels = c("Day 0", "Day 7", "Day 30",
                               "Day 150"),
                    values = c("#E69F00", "#56B4E9", "#009E73",
                               "#F0E442"))

Does anyone know why I am getting this error? I am trying to have each well on the x-axis and a different bar (with unique color) for each time point. Is there a better way to go around this?


text:
Q: Call java function from javascript in play framework I am doing a project using play framework.
After clicking some link for example "show" then  for example
car.show(55) is being called and in car.show some db query is being performed. then
list operation is being done.
What I am trying to do is, call removegivencar function from java script file.
I mean,
when all cars are listed in html file. I will call a js function with the id of that car.
For example: Remove My Car
and I would like to call car.removegivencar function in js instead of html
Because I have an id of the car. I should do
@{car.removMyOwremovegivencar(mycar.id)} operation...
I tried
function removeMyCar(id)
{
window.location="@{car.removMyOwremovegivencar(id)}";
}

or window.location="@{car.removMyOwremovegivencar(" + id + ")"
etc. but could not do it :(((
please drive me on this issue...

A: If it is written properly then it should work. But in fact it is a bad example for deleting entities from your DB. That's because of the GET request you are trying to use. It is not only logical to use GET for deleting, but it also might be dangerous for your application in some cases. But if you use it this way check the following:
You route file should contain something like that:
GET    /car/remove/{id}         car.removMyOwremovegivencar()

Also make sure you pass id param to your view from which you are trying to call you js code. I don't see any other reasons making this code not working.
But consider better way:
It is to make this action POST or DELETE and make an AJAX call on it:
route:
DELETE   /car/{id}         car.removMyOwremovegivencar()

and your JS (with jQuery):
function removeMyCar(id)
{
   $.ajax({
    type: "DELETE",
    url: "@{car.removMyOwremovegivencar()}",
    data: {
      id:id
    }
   });
}

A: The short answer is you cannot directly call a java method/function from javascript.  You could however make an ajax request to a server-side resource that will call your function.  The results of the ajax request would be the results of your function in whatever format you so choose.

A: This post could help you: javaScriptRouter
In this example you can take the url with this code
var url = jsRoutes.controllers.Application.plus(num1,num2).url;


text:
Q: Android Studio previously running app does not run I am using Android Studio 1.2.1.1 on Ubuntu OS
while debugging an app the run button stops relaunching the app.
I noticed that on the run console [next to the android and TODO consoles] the each launch causes another app to start.

A: Sometimes I can solve this problem by

*

*stopping all the apps

*detaching and reattaching the device

*relaunching the app

Other times relaunching Android Studio helps
I would gladly endorse a better less speculative answer


text:
Q: Edit and compile Unix shell script from Windows without having to boot up Linux install When I write a shell script and compile it, I generally load Linux/Knoppix (Unix) in my Windows based PC. This is arduous and I am really tired of loading the entire OS each and every time.
Is there a quicker method than this?
I want to fire up a Unix editor, write up the shell script and have it run or interpreted without the slow process of booting up another operating system every time I want to do this.

A: You might try ideone.com. You can edit and run bash scripts there (like Dennis commented, shell scripts a hardly ever actually compiled). Input is limited to stdin and output is limited to stdout, so you could not use it to develop any file manipulation scripts. If you are just trying to avoid the dual-boot/reboot situation there is no need to look for an "online" solution though.
Dan's recommendation of Cygwin seems like a reasonable way to run shell scripts under Windows.
If you need something a bit more fully Unix-y you might try a virtual machine (run another OS "inside" Windows). I think you can use VMWare Player to run a variety of pre-installed GNU/Linux distributions.
Along the same lines, you could try VirualBox and install your preferred Unix-y system under it if you can not find a suitable VM image that is compatible with (or you prefer not to use) VMWare Player.

A: There are any number of free shell accounts available on the web. You would probably access them via ssh rather than a browser. This site is one list of some of them.

A: You should be able to do all your scripting in cygwin which is a Linux-like environment for Windows.

A: To get really creative, you could load up an Ubuntu distro on an Amazon S3 cloud, and basically set yourself up with an ubuntu-based server for free.
EDIT Chris in the comments has made the correct statement.  It's not S3 that allows for the Ubuntu installation, but rather the EC2 service. And though not 100% free, it is relatively inexpensive for light use, but most likely not worth it.  Thanks Chris for clarifying!

A: *

*Check out ׂGnu on Windows. You may find it less of a hassle then Cygwin.

*Perhaps you are really looking for a free shell account. Personally I got an account at devio.us. You will need an ssh client such as PuTTY to access it.

A: i don't script often but when i do i Execute Bash Shell Online


text:
Q: If $\sigma(n)/n = 5/3$, then $5 \nmid n$. Does it also follow that $3 \nmid \sigma(n)$? Let $\sigma(x)$ denote the sum of divisors of the positive integer $x$.  Denote the abundancy index of $x$ by $I(x)=\sigma(x)/x$.  If $\sigma(N)=2N$ (equivalently, when $I(N)=2$) then $N$ is called a perfect number.  Both $\sigma$ and $I$ are multiplicative functions.
It is easy to prove the following:

If $I(n) = 5/3$, then $5 \nmid n$.

Proof
Suppose that $I(n)=5/3$.  By this answer, we know that $n$ must be an odd square.
Hence $3^2 \mid n$ (since $n$ is a square and $3\sigma(n)=5n$, where we notice that $\gcd(3,5)=1$, so that $3 \mid n$).  If it is also the case that $5 \mid n$, then $5^2 \mid n$ (again, since $n$ is a square), so that we obtain
$$1.\overline{666} = \frac{5}{3}=I(n) \geq I(3^2)I(5^2) = \frac{13}{9}\cdot\frac{31}{25} = \frac{403}{225} = 1.79\overline{1},$$
which is a contradiction.
Hence, $5 \nmid n$, and $5n$ would be an odd perfect number if there exists an $n$ such that $I(n)=5/3$:
$$I(5n) = I(5)I(n) = \frac{6}{5}\cdot\frac{5}{3} = 2.$$
Here is my question in this post:

If $\sigma(n)/n = 5/3$, does it also follow that $3 \nmid \sigma(n)$?

MY ATTEMPT
Assume that $3 \nmid \sigma(n)$.  We can apply the $\sigma$ function to both sides of $3\sigma(n)=5n$, thereby yielding
$$\sigma(3\sigma(n))=\sigma(5n).$$
Since $3$ and $5$ are primes, $5 \nmid n$, and $3 \nmid \sigma(n)$ by assumption, then
$$\gcd(3,\sigma(n))=\gcd(5,n)=1.$$
Using the fact that $\sigma$ is multiplicative, we get
$$\sigma(3)\sigma(\sigma(n))=\sigma(3\sigma(n))=\sigma(5n)=\sigma(5)\sigma(n)$$
so that we obtain
$$I(\sigma(n))=\frac{\sigma(\sigma(n))}{\sigma(n)}=\frac{\sigma(5)}{\sigma(3)}=\frac{6}{4}=\frac{3}{2}.$$
This last equation implies that $\sigma(n)=2$, which violates the fact that $n$ is an odd square.
We therefore conclude that $3 \mid \sigma(n)$.

A: MY ATTEMPT
Assume that $3 \nmid \sigma(n)$.  We can apply the $\sigma$ function to both sides of $3\sigma(n)=5n$, thereby yielding
$$\sigma(3\sigma(n))=\sigma(5n).$$
Since $3$ and $5$ are primes, $5 \nmid n$, and $3 \nmid \sigma(n)$ by assumption, then
$$\gcd(3,\sigma(n))=\gcd(5,n)=1.$$
Using the fact that $\sigma$ is multiplicative, we get
$$\sigma(3)\sigma(\sigma(n))=\sigma(3\sigma(n))=\sigma(5n)=\sigma(5)\sigma(n)$$
so that we obtain
$$I(\sigma(n))=\frac{\sigma(\sigma(n))}{\sigma(n)}=\frac{\sigma(5)}{\sigma(3)}=\frac{6}{4}=\frac{3}{2}.$$
This last equation implies that $\sigma(n)=2$, which violates the fact that $n$ is an odd square.
We therefore conclude that $3 \mid \sigma(n)$.

A: Another (shorter) approach:
Since $3\sigma(n)=5n$ and $n$ is an odd square, then $3^2 \mid n$.  If $3 \nmid \sigma(n)$, then $3^2 \nmid \text{LHS}$, contradicting $3^2 \mid \text{RHS}$.


text:
Q: double quote in text to create href doesn't work on vb.net I have a problem to add the href into the Literal control. I spend an hour and didn't work on escape double quot. It shows the text instead of href. Would someone show me how to correct it.
There is my code:
dim id as integer=Cint(txtID.text.tostring())
dim href1 as string
Dim href1 As String = "" & Link & ""

Dim ltLink As New Literal
 ltLink.Text = href1
 pnlLink.Controls.Add(ltLink)

Thanks in advance

A: Ideally, if you want to create markup at server-side, you want to use server control. It is less error prone than creating them manually.
Dim id As Integer = Convert.ToInt32(txtID.text.tostring())
Dim hyperLink = New HyperLink()
hyperLink.Target = "_blank"
hyperLink.CssClass = "body"
hyperLink.NavigateUrl = "~/OrderForm/pop.aspx?cId=" + id
hyperLink.Text = "Open Window"
hyperLink.Attributes("onclick") = "window.open(this.href, 'targetWindow', 'width=500,height=270');return false;"
pnlLink.Controls.Add(hyperLink)

I don't know what is openWin. I just assume you want to open a new windows. If it is a custom fuction, you can just replace mine with yours.


text:
Q: Intercept img src for adding Authorization header with service worker in Vue 3 I want to show a private image served by Laravel. Since Laravel is working as an API any request must be done with Authorization header containing a Bearer token.
I'm working with Quasar, but I guess that it doesn't matter at all (unless Quasar has an proper way to do this)
I'm aware that I could attach the token in URL but it doesn't look pretty good, so I'd like to use service workers to intercept requests.
In my Vue component I have this
<template>
   <img :src="file" />
</template>

<script>
export default {
  name: 'MyComponent',

  setup(props, context) {
    const file = 'http://localhost:8888/files/stream/watermark.png'

    onMounted(async () => {
      await navigator.serviceWorker
        .register('/service-worker.js', { scope: 'http://localhost:9999/files/stream/' })
        .then(registration => {
            console.log('ServiceWorker registration successful with scope: ', registration.scope)
        })
        .catch(err => {
            console.log('ServiceWorker registration failed: ', err);
        })
    })

    return {
       file
    }
  }
</script>

My service-worker.js
self.addEventListener('fetch', event => {
    event.respondWith(customHeaderRequestFetch(event))
})

function customHeaderRequestFetch(event) {
    // decide for yourself which values you provide to mode and credentials
    const newRequest = new Request(event.request, {
      mode: 'cors',
      headers: {
        'Authorization': 'Bearer PyIlosdka73Jksdjklasd...'
      }
    })
    return fetch(newRequest)
}

As soon as component mounts, console log shows
ServiceWorker registration successful with scope:  http://localhost:9999/files/stream/

But i still have an 401 response error from Laravel because Authorization header is not sent
Request Headers
Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en,es;q=0.9,en-US;q=0.8,es-419;q=0.7
Connection: keep-alive
DNT: 1
Host: localhost:8888
Referer: http://localhost:9999/
sec-ch-ua: "Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Linux"
Sec-Fetch-Dest: image
Sec-Fetch-Mode: no-cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36

Any advice about how to solve this or use any other alternative will be appreciated.
EDIT: Just in case, I'm using docker with nginx and this is the config
server {
    listen 80;
    server_name localhost;
    index index.php index.html;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/public;
    client_max_body_size 32M;
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass api:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
    location / {
        try_files $uri $uri/ /index.php?$query_string;
        gzip_static on;
    }
    location /storage {
        add_header "Access-Control-Allow-Origin" "*";
    }
}

A: I think you don't need a service worker just for that. Use fetch API tu fetch the image url and send token header, then convert blop to base64
here is my way with composition API
<script setup>
import {onMounted,ref} from 'vue'
const imgURL =ref('')

onMounted(()=>{
  fetch('https://miro.medium.com/max/3150/0*4FYDBk1GzfynMjCI.',{
      headers: {
    }
  }).then(resp => resp.blob()).then(blob => {
    let reader = new FileReader()
    reader.readAsDataURL(blob)
    reader.onloadend = function() {
        var base64data = reader.result
        imgURL.value = base64data
        console.log(base64data)
    }
})
})
</script>

And in your templae
<img :src="imgURL"/>

here we define imgURL as a ref so we can bind it to the src via :src, then we use fetch api with header as second parameter, read it here. May be it will be a bit different if using Quasar since i dont know what version of vue do quasar use, but you can figure the main idea from my explanation.


text:
Q: Is there a way to cancel a handler after it was notified? I've got an enrvironment consisting of a stack of dockerized microapps, where some are dependant from others, linked to each other and communicate over http on the docker interface. My problem was that the docker-compose tracked only the docker-compose.yml file and recreated containers only when the docker-compose.yml has been changed.
With ansible i can finally start tracking config files, that get mounted as volumes inside the containers, so they can be deployed from templates - which works fantastically.
Before ansible I used to run:
 docker-compose stop <app> && docker-compose rm -f <app> && docker-compose up -d

to refresh a single app when I knew the mounted file has been changed and the volumes needed to be refreshed.
I've defined multiple roles with the docker_service module for each app each one with its own handler that, when notified, runs the code above, to refresh that particular app.
The problem is, when multiple apps have their mounted files changed, ansible notifies each handler and each one gets executed which is not exactly the case i need as when the primary container (on which others depend) gets recreated the others don't need to because they have already been recreated, yet their handlers also are being executed. So my question is: is there a way to cancel a notified handler? I know about flush_handlers but that just executes notified handlers, not exactly what I need.

A: You can use conditionals in handlers.
Use a flag variable to indicate that some handlers shouldn't execute.
- name: restart myapp1
  shell: docker ...
  when: not block_apps_restart


text:
Q: Timestamp field in cosmos db I am having a hard time using ts field in cosmos/document db with c#. Is it just better to create another date time field and use that instead of ts? How to decide when to use ts vs a custom date time field?

A: _ts represents a Unix Epoch and marks the time of the document's last modification. When a document is created, it has the creation time, but if later on the document is updated, then _ts is updated with that time.
Effectively it means the last modified time of the document.
It depends on your use case if you can use it or you need a custom date field. For example, if your intent it to track when a document was created, then you can't use it, as the value will change if the document is modified. If your intent is to track the last modified time, it can work (depends on the precision you need and if a Unix Epoch fills that requirement, otherwise you would need your own custom field).
Here is the official reference of system properties: https://learn.microsoft.com/azure/cosmos-db/account-databases-containers-items#properties-of-an-item


text:
Q: How to use exclude_properties and include_properties to exclude/include SQLAlchemy model attributes from corresponding Spyne model? I have model declared as:
class SAProduct(Base):

    sku = Column(PRODUCT_SKU_TYPE, primary_key=True)
    i_want_to_hide = Column(String(20), nullable=False)
    name = Column(Unicode(255), nullable=True)

    @property
    def my_property(self):
        return i_calculate_property_here(self)

and Spyne model declared as:
db = create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=db)

class TableModel(ComplexModelBase):
    __metaclass__ = ComplexModelMeta
    __metadata__ = MetaData(bind=db)

class SProduct(TableModel):
    __table__ = SAProduct.__table__

How can I make attribute i_want_to_hide to be excluded from Spyne model, and property my_property to be included as Spyne model attribute?
P.S.
Now I use monkey patching Spyne to support this syntax:
class SProduct(GComplexModel):
    __model__ = Product

    class Attributes:
        exclude_attrs = ('i_want_to_hide',)
        add_attrs = {'my_property': Boolean}

But I want get rid of it.

A: This doesn't directly answer your question, but please consider the following code:
from spyne import *

TableModel = TTableModel()

class SomeClass(TableModel):
    __tablename__ = 'some_table'

    id = Integer(pk=True)
    s = Unicode
    i = Integer(exc_table=True)

Here, pk stands for primary key (you can use the long form primary_key if you wish) and the i attribute will just be ignored by SqlAlchemy. e.g. it won't be created in the table, it won't be instrumented by SqlAlchemy's metaclass, etc.
As for an attribute that will be hidden from the RPC Parts of Spyne, but not from SqlAlchemy, that's a new feature coming in 2.12.
You will be able to say e.g.:
i = Integer(exc_table=True, pa={JsonObject: dict(exc=true)})

where pa stands for protocol attributes. (you can use the long form prot_attrs if you wish) Here i is ignored by every protocol that inherits JsonObject.
If you don't want it on the wsdl either, you'll have to do:
i = Integer(exc_table=True, exc_interface=True)

https://github.com/arskom/spyne/blob/fa4b1eef5815d3584287d1fef66b61846f82d2f8/spyne/interface/xml_schema/model.py#L197
Spyne offers a richer object model interface compared to SqlAlchemy. Trying to replicate this functionality without adding Spyne as a dependency means you'll have to duplicate all the work done in Spyne in your project. It's your choice!


text:
Q: Problem In OutPut Of Divided Number
Possible Duplicate:
Divide problem

Why does c# show the output of this code as 0??
 MessageBox.Show((5/6).ToString);

A: Because unless you specify that you want the operation to result in a Double the operation results in an Integer, and so the fractional result is dropped and you are left with just the whole number of 0.

A: It is dividing an integer by and integer and will return an integer, I believe it always returns the floor value.  Try Messagebox.Show((5.0/6.0).ToString());

A: 5/6 is basically integral division, which turns out to be 0. The type of both operands is int.
I think what you want is :  5.0/6.0.
In fact, 5.0/6.0, 5/6.0, 5.0/6, all would give same result. That is, as long as, one operand is double, it would be a double division, and the type of the result would be double as well.

A: Because you are doing integer division. If you want non-integer division you should do something like 5 / 6d

A: The compiler assumes that the numbers are Int, which must be whole numbers. Thus, it is rounding the answer. To return the decimal answer, use this:
MessageBox.Show((5d/6d).ToString());


text:
Q: SQL Injection with Plain-Vanilla NHibernate Plain-vanilla NHibernate setup, eg, no fluent NHibernate, no HQL, nothing except domain objects and NHibernate mapping files. I load objects via:
_lightSabers = session.CreateCriteria(typeof(LightSaber)).List<LightSaber>();

I apply raw user input directly to one property on the "LightSaber" class:
myLightSaber.NameTag = "Raw malicious text from user";

I then save the LightSaber:
session.SaveOrUpdate(myLightSaber);

Everything I've seen says that yes, under this situation you are immune to SQL injection, because of the way NHibernate parameterizes and escapes the queries under the hood. However, I'm also a relative NHibernate beginner so I wanted to double-check.
Thanks!

A: You're safe as long as you don't plug user input directly into HQL or SQL: nothing else (of the functionality hibernate provides) will allow users to inject malicious code.

A: Just to echo others, if you let NHibernate generate your SQL you're safe, at least in theory.
However, you still need to be careful with stored procedures, triggers, and functions in the database particularly with dynamic SQL. Even though the client uses parametrized queries everywhere, injection may still possible.

A: Yes, you're almost immune to SQL injection when using NHibernate. It uses parameterized queries for all generated SQL statements on all platforms that support these.
You can, however, circumvent this by using custom SQL for insertions/updates, or by executing SQL with a variation of execute_sql of some sort, or SQL Queries without parameters.


text:
Q: append a NSSet with array values How can i append my HKObjectTypes into a NSSet.
It always returns empty. Any better way???
     func getPermsFromOptions(_ options: NSArray) -> NSSet {
            var readPermSet = NSSet()
            var optionKey: String
            var val: HKObjectType

           for i in options{
            optionKey = i as! String
            val = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: optionKey))!

             readPermSet.adding(val)
             print("set", readPermSet)           //always empty

                      }
                  return readPermSet;
              }

A: readPermSet.adding(val)

Adding isn't a mutating method, it returns a new set that has the other value added
Try it with:
var readPermSet: Set<HKObjectType> = []

and
readPermSet.insert(val)

A: You cannot add to an NSSet. You can add to an NSMutableSet:
var readPermSet = NSMutableSet()
...
readPermSet.add(val)

adding is a method from Swift, that returns a new set with all the same elements, plus the new element. You are ignoring its return value here.
Since you are in Swift, why not use Set<HKObjectType> and [String]?
func getPermsFromOptions(_ options: [String]) -> Set<HKObjectType> {
    var readPermSet = Set<HKObjectType>()
    for optionKey in options {
        let val = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: optionKey))!
         readPermSet.insert(val)
         print("set", readPermSet)
     }
     return readPermSet;
 }


text:
Q: "in" operator in linq c#? I have a generic list which contains member details and I have a string array of memberIds..I need to filter the list and get the results which contains all the memberIds..How can I achieve this using LINQ.
I tried the following
string[] memberList = hdnSelectedMemberList.Value.Split(',');
_lstFilteredMembers = lstMainMembers.Where(p =>memberList.Contains(p.MemberId))
                                    .ToList();

But the above query is giving me only the results that match the first member ID..so lets say if I have memberIds 1,2,3,4 in the memberList array..the result it returns after the query contains only the members with member ID 1..even though the actual list has 1,2,3,4,5 in it..
Can you please guide me what I am doing wrong.
Thanks and appreciate your feedback.

A: Strings make terrible primary keys. Try trimming the list:
string[] memberList = hdnSelectedMemberList.Value
                          .Split(',')
                          .Select(p => p.Trim())
                          .ToList();

_lstFilteredMembers = lstMainMembers.Where(p => memberList.Contains(p.MemberId)).ToList();

Because I have a feeling hdnSelectedMemberList may be "1, 2, 3, 4".

A: Use a join:
var memquery = from member in lstMainMembers
               join memberid in memberList
               on member.MemberId equals memberid
               select member;

A: Try Enumerable.Intersect to get the intersection of two collections:
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.intersect.aspx
_lstFilteredMembers = lstMainMembers.Intersect(memberList.Select(p => p.MemberID.ToString())).ToList()

A: Why not just project the IDs list into a list of members?
var result = memberList.Select(m => lstMainMembers.SingleOrDefault(mm => mm.MemberId == m))

Of course, that will give you a list that contains null entries for items that don't match.
You could filter those out, if you wanted to...
result = result.Where(r => r != null)

Or you could filter it before the initial select...
memberList.Where(m => lstMainMembers.Any(mm => mm.MemberId == m)).Select(m => lstMainMembers.Single(mm => mm.MemberId == m))

That's pretty ugly, though.

A: With jmh, I'd use a join
var members = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var ids = new[] { 1, 3, 6, 14 };

var result = members.Join(ids, m => m, id => id, (m, id) => m);

foreach (var r in result)
    Console.WriteLine(r); //prints 1, 3, 6

A: The code you are showing is correct, and works in a Unit Test:
    public class Data
    {
        public string MemberId { get; set; }
    }

    [TestMethod]
    public void Your_Code_Works()
    {
        // Arrange fake data.
        var hdnSelectedMemberList = "1,2,3,4";
        var lstMainMembers = new[]
            {
                new Data { MemberId = "1" },
                new Data { MemberId = "2" },
                new Data { MemberId = "3" },
                new Data { MemberId = "4" },
                new Data { MemberId = "5" }
            };

        // Act - copy/pasted from StackOverflow
        string[] memberList = hdnSelectedMemberList.Split(',');
        var _lstFilteredMembers = lstMainMembers.Where(p => memberList.Contains(p.MemberId)).ToList();

        // Assert - All pass.
        Assert.AreEqual(4, _lstFilteredMembers.Count);
        Assert.AreEqual("1", _lstFilteredMembers[0].MemberId);
        Assert.AreEqual("2", _lstFilteredMembers[1].MemberId);
        Assert.AreEqual("3", _lstFilteredMembers[2].MemberId);
        Assert.AreEqual("4", _lstFilteredMembers[3].MemberId);
    }

There must be something wrong with your code outside what you have shown.


text:
Q: Django: Switching to Jinja2? I've got a couple small (500 or 600 lines of template code) Django sites, and I'd like to migrate them to using Jinja2… But I'd like to get some idea of how much work it will be. So, in general, about how much work is it to migrate a small Django site to Jinja2? And is it "worth it"?

A: While it's just my own experience, I found converting from Django to Jinja2 to be worthwhile for the following reasons:

*

*The design and implementation of Jinja2 seemed more intuitive to me, both as a software developer and template designer;

*Jinja2 is more extensible (at least in the ways I've sought to extend my template engine);

*Jinja2 is more flexible in terms of permitting logic-code to be run (but it gives you enough rope to hang yourself with);

*Jinja2 is regarded as significantly faster (though I haven't done any benchmarks, this is always subject to debate depending on the tests used, and in any event largely irrelevant in the total wait time for a query that has to do DB lookups);

*Jinja2 gives significantly more helpful error output than Django (i.e. traces to the line number in the template where the error occurred). Edit: According to Dor's comment, Django gives helpful error messages that point to the line and context of a problem, much like Jinja2.

If you haven't had any trouble with Django's template engine, Jinja2's should feel relatively intuitive, if perhaps a bit more polished (or it did to me, at any rate). As well, I found the Coffin project well written and reasonably helpful when converting from Django to Jinja2 – both for its use, and as an example of how to extend Jinja2.
All that being said, Django's template engine is solid and quite capable for most tasks. I believe it's being improved in the next revision of Django, and there is quite a lot of effort to add to its capabilities by quite a number of dedicated developers. As a result there are no worries of it becoming unsupported in the near to medium-term future.
Again, that's just my experience, for what it's worth – I hope that's helpful.

A: There's also django-jinja. https://github.com/niwibe/django-jinja
New and nice project. http://niwinz.github.io/django-jinja/latest/
It claims to be a simple and nonobstructive jinja2 integration with Django.

A: From what you have said, it's may not be worth the trouble to migrate to Jinja2. There are filters in Django Templates which could help you do any math operations.
Regarding list operations, what exactly are you talking about? If you want some particular list operation to be supported in Template, than write a custom filter.
There are also some existing 3rd party math filters for Django.
If you think about it, it's by design that Django templates does not have too much of "programming constructs" in them. HTML templates should be such...

A: Two projects which are trying to integrate Jinja in Django with simple integration steps and nicely hooks with Django -

*

*Coffin

*Chouwa
I am integrating them right away to experiment if they work too with Django contrib apps like Django Admin. But I feel, it will be available for project apps and Django default template system will be used in internal apps like Admin.


text:
Q: Ionic 3 diagnostic plugin not working throwing aapt error and processDebubgResource error ionic cordova plugin add cordova.plugins.diagnostic
npm install --save @ionic-native/diagnostic@4

used the above command to install diagnostic plugin inside my project
I am using a windows machine
Installed platforms:
  android 6.3.0
  ios 4.5.5
Available platforms:
  browser ~5.0.1
  osx ~4.0.1
  windows ~6.0.0

cordova.plugins.diagnostic 4.0.12 "Diagnostic"

when building it shows error
com.android.ide.common.process.ProcessException: Failed to execute aapt

A: removed my android platform using
ionic cordova platform rm android

and added it again using
ionic cordova platform add android@latest

resulted in android 8.0.0
and when i ran the code it showed some SDK error to update license which you can easily solve by
moving into android sdk location
:
C:\Users\username\AppData\Local\Android\sdk\tools\bin
Run command
sdkmanager --licenses

Accept the licence for SDK


text:
Q: Basic Circuit Question I need to confirm something.Do circuits like the one shown below in which there is no connection between points A and B,treated as separate loops with no connection between them?

A: While there is not a direct connection between A and B, they are linked together.
The voltage across the resistor in the A loop is defined as Vx.  There is a dependent voltage source in the B loop (directly under the B).  That voltage source delivers 3Vx.  Essentially, the voltage at B is 3 times the voltage at A.
Changing the A circuit will affect the B circuit.

A: What you show here is an "equivalent circuit" and is generally only useful for analysis and understanding how electrical parts behave. In this case you have a "voltage-controlled current source" in the B loop, whose current will be 3 x Vx. Since Vx is 5V as shown, you get 15A from that current source.
This circuit as shown is not realizable directly, but is useful for understanding the behavior of circuits using things like transistor, which "behave" like voltage controlled current sources.

A: Yes, you can consider these loops separate when using mesh analysis.
Naming the loops 1, 2 and 3 from left to right and choosing CW for positive current flow you get:
$$
I_1 = \frac{5\text{V}}{R_x}\\
I_2 = 3V_x\\
I_3 = 3\text{A}
$$
As you can see you have four unknowns, i.e. \$I_{1,2,3}\$ and \$V_x\$, but only three equations. Since you have a VCCS (voltage controlled current source) you should add an equation that relates its controlling parameter, \$V_x\$, with one or more loop currents. In this case:
$$
V_x = I_1R_x
$$
Solving the linear system is now trivial.


text:
Q: Java Script is not working inside the php public function actionAjaxUpdate()
    {
        $action = $_GET['act'];

        if(!isset($_POST['selectedId']))
        {
            echo '<script> alert("No row is selected"); </script>';
        }

        else
        {
        $selectedAll = $_POST['selectedId'];
        if(count($selectedAll)>0)
        {
            foreach($selectedAll as $selectedId)
            {
                $model=$this->loadCompositeModel($selectedId);
                switch ($action) {
                    case 'Delete':
                        $model['account']->delete();
                        break;
                    case 'Active':
                        $model['account']->active = '1';
                        break;
                    case 'Inactive':
                        $model['account']->active = '0';
                        break;
                    default:
                        break;
                }
                $model['account']->save();
            }
        }
        }

    }

*

*List item

In this code Alert is not working, if no id is selected.So some one help me out. i have tried alot but js is not working.
I have used js inside the php and this is the first time when js is not working inside the php

A: Without seeing the code that makes the HTTP request, it is hard to say what the problem is.
Them most likely explanation that selectedId is set to an empty string when no id has been selected. The condition !isset($_POST['selectedId']) will then not give you the result you want. Use empty() instead (and make sure that 0 is not an acceptable id value).

A: It seems $_POST['selectedId'] is an array. then you should use isset for elements of $_POST['selectedId'] for example if (!isset($_POST['selectedId'][0]))
EDIT 1: try this one
$array_id = array_filter($_POST['selectedId']);

then use  if (!empty($array_id)) instead of if (!isset($_POST['selectedId']))

A: Unless you're injecting the response back into the page, the Javascript will never be evaluated.
If you were to do...
document.write('<script src="/path/to/phpscript.php">')

then the response will be appended to the page and evaluated.
However, if you do...
$.ajax({
    success: function(response) {
        //Blah....
    }
});

or something to that effect, the response is never evaluated, it's passed to your success function as a string. So you could just get the PHP to print 1 or 0 for success/failure - or even better return a Json object
<?php

    ...
    if(!isset($_POST['selectedId']))
    {
        $Ret->Success = false;
        $Ret->Reason = "No row is selected";
        header("Content-Type: application/json");
        print json_encode($Ret)
    }
?>

Then use the $.getJson Ajax call to retrieve the response as a Js object (See this manual page)


text:
Q: Backslash URL of REST API Call Made with Invoke-RestMethod Generates Error I've got a snippet of code like the following:
$url = 'https://foo/accounts/thing%5CBSTNTZ-MTRFKR'
$request_content_type = 'application/xml'

$response_checkout = Invoke-RestMethod `
-Credential $credential `
-Method Get `
-Uri $url `
-ContentType $request_content_type

The Invoke-RestMethod generates the following exception:
PSMessageDetails      :
Exception             : System.Net.WebException: The remote server returned an error: (404) Not Found.
                           at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
                           at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
TargetObject          : System.Net.HttpWebRequest
CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
ErrorDetails          : Account not found: ?\thing
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}

The backslash in the account name (thing\BSTNTZ-MTRFKR) seems to be the culprit. I am encoding the backslash with %5c using [System.Uri]::EscapeUriString(). Is there some other trick to adding a blackslash to the URI?
The following link will take you to the API reference for the API I'm calling.
https://docops.ca.com/ca-privileged-identity-management/12-8/en/integrating/rest-based-api/checkout-an-account


text:
Q: ¿Cómo capturar body de una HTTP response en Python? Estoy recibiendo en mi consola sólo el estado (200) de un webhook de pipedrive, pero necesito obtener el body de dicha respuesta en python.

A: lo puedes hacer ya sea que se haga una peticion a tu servidor como al hacer una peticion a un endpoint
obteniendo body de una peticion a nuestro servidor
#aqui se usa flask para el servidor
from flask import request #importamos request de la libreria flask

# de esta forma obtenemos la propiedad name de un json
# enviado a nuestro servidor
@app.post('/'):
     name = request.json['name']

obteniendo respuesta de un endpoint
import requests #importamos request

#hacemos la peticion
req = requests.get('https://url.com')
code = res.status_code #obtiene el estado de la respuesta
contType = req.headers['content-type'] # obtenemos el content-type
res = req.json() #obtenemos la respuesta en formato JSON
#ppuedes hacer cualquier peticion incluso enviando datos con la propiedad payload

print(res) #imprimimos la respuesta
print(code) #imprimimos el codigo de estado

instalas la libreria con pip install requests
aqui te dejo la documentacion


text:
Q: MySQL PHP - Can't update text The table user_content has the columns id, context_text, email_last_edit.
This is my update method:
$content_text1 = utf8_decode($_POST['content_text1']);
$conn = new mysqli($servername, $username, $password, $dbname);
  // Check connection
  if ($conn->connect_error) {
    die("Datenbankverbindung fehlerhaft: " . $conn->connect_error);
  }

  $sql = 'UPDATE user_content SET content_text="' . $content_text1 . '" AND email_last_edit="' . $email . '" WHERE id=1';

  if ($conn->query($sql) === TRUE) {

    //echo "New record created successfully";

  } else {

    echo "Datenbank-Fehler: " . $sql . "
" . $conn->error;

  }

  $conn->close();

I send this text via post to the same php page:

Mitglied

Community
Kurzprofil,ßCommunity-Bereich</bChats.

Unfortunately, every update the column content_text becomes 0.
I think it is a problem with the special characters in the text, but uft8_decode() does anyhow not fix this problem.
Does anyone know a solution to this?
Thanks a lot :)

A: Change your query by
$sql = 'UPDATE user_content SET content_text="' . $content_text1 . '" , email_last_edit="' . $email . '" WHERE id=1';

Removed 'AND' and replaced with ','
You have to escape parameters too for security reasons


text:
Q: Hard drive activity creates noise every 3 seconds. Is there any way to deal with this without unplugging the drive? In my computer, I have an NVMe system drive and a 2TB Seagate HDD secondary drive. My hard drive has activity every 3 or so seconds. This wouldn't normally bother me except it makes a sound every time it has activity.
This is the sound it makes.
It isn't quiet either. I tried to just ignore it, but after a month of this I can't stand it anymore. Is there any way I can fix it other than unplugging the hard drive?

A: All drives (HDD and SSD) are always active to some extent. I have one machine left with a HDD (everything else is SSD). The HDD machine is near silent.
Most machines with Hard Drives (Customer machines) are near silent.
I have one old customer machine with a slow 5400-rpm HDD that makes a muffled sound when writing big amounts.
So 90% or more of my machines and customer machines are near silent in normal operation.
Keep that HDD of your unplugged unless you need it. Some drives (fewer than more) are noisier than others. The high level of noise can be a forerunner of failure also.  Consider replacing the drive with an SSD drive. Good quality (Samsung) SSDs have long life spans.
With Indexing, Search, update checking and so on, it is near impossible to stop a disk from reading / writing, so just unplug it.


text:
Q: React Hook Form reset Controller (value) to default Here is an example of my component, wrapped into Controller
<div className="mt-1">
    <Controller
       control={control}
       name="selectedBirthMonth"
       defaultValue={selectedMonth}
       render={({ field }) => (
       < SelectBirthMonth
         field={field}
         startYear={startYear}
         selectedYear={selectedYear}
         months={months}
         value={selectedMonth}
         reducedMonths={reducedMonths}
         onChange={useEffect(() => monthSelect(field.value)), [selectedMonth]}/>
   )}
 />
</div>

For now I am just trying to reset it with a button. Later I'd love to conditionally reset, depending on the value in a sibling component. Would be great to get it work with the button in the first place:
<input
  style={{ display: "block", marginTop: 20 }}
  type="button"
  onClick={() =>
   reset(selectedBirthMonth)
  }
  value="Reset with values"
/>

I get en error: selectedBirthMonth is not defined. Bassicaly, what I am aming for,on click, the whole component goes to default / a state it had when first rendered. What am I missing?

A: reset didn't do the job somehow, but setValue did. However I am setting to a value, not to the original state after first render, but in my case it's same.
<input
  style={{ display: "block", marginTop: 20 }}
  type="button"
  onClick={() =>
    etValue('selectedBirthMonth', lastAvaliableMonth)
  }
  value="Reset with values"
/>


text:
Q: Closing socket connection with XHR-polling Does anyone know why my socket connection does not close when using xhr-polling? This is the server code I would like to execute, but does not fire when using xhr-polling. The socket connection works fine ( I am running behind varnish with stunnel, since this a secure socket). I tried manually emitting a disconnect event on the browser unload, but this isnt an optimal solution for me.
client.on('disconnect', function () {

    delete connected_clients[id];
    console.log('   debug - ' + 'client ' + client.id + 'is disconnected');
    console.log('   debug - ' + 'total number of connected clients is ' + Object.keys(connected_clients).length);

});

In my client side code, I am connecting the socket like this:
socket = io.connect(BASE_URL, {
    "sync disconnect on unload":true
});

and my server side settings are this:
    io.enable('browser client minification');  // send minified client
    io.enable('browser client etag');          // apply etag caching logic based on version number
    io.enable('browser client gzip');          // gzip the file
    io.set('log level', 3);                    // reduce logging
    io.set('match origin protocol', true);     // ssl support
    io.set('sync disconnect on unload', true);
    io.set('transports', [                     // enable all transports (optional if you want flashsocket)
        'xhr-polling',
        'websocket',
        'flashsocket',
        'htmlfile',
        'jsonp-polling'
    ]);

This is the debug message I get when the client exits the browser
debug: xhr-polling closed due to exceeded duration

I am using socket.io version 0.9.10 with node 0.8.8.

A: Since the connection is between you (the server) and the client (the browser), you are at the mercy of the browser in regards to being notified of when the connection closes. If the browser does not notify you of that it considers the connection to be closed, then there is no way for you to be informed about it.
I suggest that you program your client to behave in a way that treats your server nicely, notifying it when the connection is discarded appropriately. In cases when the connection is simply neglected without notification, you simply close the connection after a certain period of time of inactivity (timeout).
Think of it like the scenario of when you are instant messaging a friend. Your friend may be kind enough to notify you of that they are leaving their desk and no longer are able to attend the conversation (disconnect), or they could also just leave their desk without notification (kill browser process), or worse, they could be having a heart attack that would disable them from attending (power outage). You will understand after a while that they are no longer actively participating in the session (timeout).
I'm sorry, there is just no magic here. You have to program your server to deal with the fact that it may be talking to a disconnected client.


text:
Q: Why am I getting this error, everything looks right: "Undefined index"? I am at a loss here.  I cannot for the life of me figure out why I am getting the error.
Notice: Undefined index: price in /home/*****/public_html/newfinal/home_view.php on line 14

Notice: Undefined index: description in /home/****/public_html/newfinal/home_view.php on line 15

Here are the relevant code snippets:
PHP/ SQL
function get_product($product_id) {
    global $db;
    $query = "SELECT * FROM prjProducts p"
            . " INNER JOIN prjCategories c"
            . " ON p.categoryID = c.categoryID"
            . " WHERE productID = :product_id";
    try {
        $stmt = $db->prepare($query);
        $stmt->bindValue(':product_id', $product_id);
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $stmt->execute();
        $result = $stmt->fetchAll();
        $stmt->closeCursor();
        return $result;
    } catch (PDOException $ex) {
        $error = $ex->getMessage();
        echo $error;
    }
}

PHP
// Set the featured product Id's in an array
$product_ids = array(3, 5, 10);

// Get an array of featured producst from the database
$products = array();
foreach ($product_ids as $product_id) {
    $product = get_product($product_id);
    $products[] = $product; // add the product to the array

}

HTML
<?php foreach ($products as $product) :
          // Get product data
          $price = $product['price'];
          $description = $product['description'];

I have been banging my head at this one for a couple of hours now.  I've tried to echo the arrays, and I can print out the arrays without issue.  I'm sure it is some small formatting error that I am missing somewhere.

A: *

*First check whether you have the price and description columns in your table prjProducts.

*In your foreach ($products as $product) loop, do a var_dump for $product and check to see whether it is an array or an object?
If it is not an array you should do $product->price instead of $product['price'].


text:
Q: auto delete new characters javascript I'm working on a lab for school, and the goal is to create a web control to will only accept a monetary value from the user.
Rules:
1st digit must be "-" or "$"
2nd digit must be "$" or a number
3rd digit on must be a number or a "."
Only two digits after decimal
Must have a "$"

The problem I'm having, is that while I can set up labels to display when something is or is not allowed, I can't figure out how to get it to auto delete new characters when the conditions haven't been met. (E.G. can't enter "-1", only "-$" or "$1".) Trying to set the substring's length doesn't seem to be working. The condition in the current example also only seems to work when the string consists only of "-". Any extra characters added do not trigger it.
Code:
    function text2money(e) {
        // get value of txt
        var str = document.getElementById("<%=txt.ClientID %>").value;

        if (str.substring(0, str.length) === "-" && str.substring(1, str.length) !== "$") {
                str.length = 2;
        }

        // goes through string one character at a time, converts them to char, then checks if char is a decimal digit
        if (str.substring(0, 1) === ('-') || str.substring(0, 1) === ('$')) {
            document.getElementById("<%= lbl1.ClientID %>").innerHTML = "True"; // must use .innerHTML with labels

            // check if second digit is '$' or numeric
            if (str.substring(1, 2) === ("$") || isFinite(str.substring(1, 2))) {
                document.getElementById("<%= lbl1.ClientID %>").innerHTML = "It's numeric";

                // check if third and any future characters are '.' or numeric

            } // end second char if

            else {
                document.getElementById("<%= lbl1.ClientID %>").innerHTML = "Second char must be '$' or numeric";
            } // end second char

        } // end first char if
        else {
            document.getElementById("<%= lbl1.ClientID %>").innerHTML = "First character must be '-' or '$'";
        } // end first char

        // check if $ is included anywhere in the string
        var result = str.indexOf("$") <= -1; // -1 == false
        if (result) {
            document.getElementById("<%= lbl2.ClientID %>").innerHTML = "$ is a required character";
            }
            else {
                document.getElementById("<%= lbl2.ClientID %>").innerHTML = "";
            }

        } // end text2money

A: Use a Regex object:
        (/^-?\$\d+\.\d{2}$/).test(inputString)

/^ define start of pattern as beginning of string
-? 1 optional -
\$ 1 obligatory $
\d+  1 or more digits
.  obligatory .
\d{2} exactly 2 digits
$/  obligatory end of string


text:
Q: Elasticsearch: Comparing two fields of the same document, where one of the fields is inside a nested document Consider the following document:
{
    "group" : "fans",
    "preferredFanId" : 1,
    "user" : [
        {
            "fanId" : 1,
            "first" : "John",
            "last" :  "Smith"
        },
        {
            "fanId" : 2,
            "first" : "Alice",
            "last" :  "White"
        },
    ]
}

where "user" is a nested document.  I want to get inner_hits (from 2.0.0-SNAPSHOT) where preferredFanId == user.fanId , and so I want only the John Smith record returned in the inner_hits.
Is it possible?  I've tried several approaches like using "include_in_parent" or "_source", but nothing seems to work.


text:
Q: Gate Threshold @ Id = X Confusion Kind of a follow up question to this one I asked the other day. So a lot of the parts I'm looking at are listed with Vth at a certain Id. I'm not entirely understanding the graphs so I'm not sure if I wanted my desired Vth to be reached at a bigger or smaller current. For example, there are parts listed as Vth: 600mV @ Id = 1mA and also 600mV @ Id = 250uA.
Could somebody explain how the current influences the gate threshold voltage and what that would mean for low power applications such as mine? Thanks.

A: The current at which \$V_{GS(th)}\$ is specified is a bit arbitrary, every manufacturer chooses the current at which he wants to specify it. These two are still comaparable, since they mention the same voltage. The 1 mA part has the lower \$V_{GS(th)}\$, because you'll have to go below the 600 mV to get the 250 µA the other one specifies.
Other parts can't be compared as easily. They often mention both different voltages and currents.
Note that \$V_{GS(th)}\$ is the voltage at which the FET begins to conduct, and that you need a somewhat higher voltage to get a reasonable current in the order of 1 A. Also note that there's much variation in \$V_{GS(th)}\$. The FDC855N has a \$V_{GS(th)}\$ of typically 2 V, but minimum 1 V and maximum 3 V, that's a 3:1 range. Always check both limits. The upper limit to be sure the FET is on at a minimum for a high level on the gate, the lower limit to be sure the FET will be off at the maximum for a low level.


text:
Q: How can I repaint a picturebox with the drawn on contents? I have a picturebox that gets some output on similar to this:
e = New PrintPageEventArgs(PictureBox1.CreateGraphics, New Rectangle(New Point(25, 25), New Size(New Point(825, 1075))), e.PageBounds, e.PageSettings)

'Draw box
e.Graphics.DrawRectangle(Pens.Gray, 20, 30, e.PageBounds.Width - 100, e.PageBounds.Height - 130)

DrawnImage = PictureBox1.Image

I need to update it in the Paint event:
Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint

    PictureBox1.Image = DrawnImage

End Sub

The problem is DrawnImage is NULL.  How do I capture the image?

A: I needed to use a bitmap instead of creating a graphics object from the picturebox.
For a complete description, please look here: How do I repaint my picturebox when the picture disappears?
Dim b As New Bitmap(PictureBox1.Width, PictureBox1.Height)

e = New PrintPageEventArgs(Graphics.GraphicsFromImage(b), New Rectangle(New Point(25, 25), New Size(New Point(825, 1075))), e.PageBounds, e.PageSettings)

'Draw box
e.Graphics.DrawRectangle(Pens.Gray, 20, 30, e.PageBounds.Width - 100, e.PageBounds.Height - 130)

PictureBox1.Image = b


text:
Q: Swipe effect for uiimageviews I have a little question. I've made a little image gallery with a swipe effect to skip through the uiimageviews. That works fine but I want to improve it. The next or previous picture is shown not until the swipe has finished. But I want it to behave like the photo library for example or the home screen, that the imageview 'follows' the touch and skips to the next or previous picture when a certain point is reached.
I hope I've made myself clear :-)
It's just that I want to simulate the swipe effect of the photo library.

A: The easiest by far is to use an UIScrollView and to enable paging like that:
 myScrollView.pagingEnabled = YES;

See here for details.


text:
Q: EF .Net core 2.0 - Using OwnOne with HasDefaultValueSql for Id (type: Guid) I have 2 Entities. Order and Address (as Value Object in DDD).
I want Id Property of Order to be generated by Guid.NewGuid(). I've configured as the following
class OrderEntityTypeConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> orderConfiguration)
    {
        orderConfiguration.ToTable("orders", OrderingContext.DEFAULT_SCHEMA);

        orderConfiguration.HasKey(o => o.Id);

        orderConfiguration.Ignore(b => b.DomainEvents);

        orderConfiguration.Property(b => b.Id).HasDefaultValueSql<Guid>("(newid())");

        //Address value object persisted as owned entity type supported since EF Core 2.0
        orderConfiguration.OwnsOne(o => o.Address);

    }
}

But, when using command "dotnet ef migrations add InitialDatabase" for creating migration, which throw error " 'Order.Id' and 'Order.Address#Address.OrderId' are both mapped to column 'Id' in  'ordering.orders' but are configured to use different default values ('(newid())' and '')."
Please, help me. I'm new in .net Core2, EF core as well. Thank you.


text:
Q: How to persist checkbox checked state after page reload? I am unable to persist checkbox checked after page is refreshed.

A: You need to use cookies for this... As soon as user clicks on check box, store its state into a cookie and just fetch the cookie value on page load to prepoulate the checkboxes as they were in previous selection.
HTML

  Option 1
  <input type="checkbox" id="option1">

  Option 2
  <input type="checkbox" id="option2">

  Option 3
  <input type="checkbox" id="option3">

<button>Check all</button>

Fetching checkboxes value and making a cookie out of them
var checkboxValues = {};
$(":checkbox").each(function(){
  checkboxValues[this.id] = this.checked;
});
$.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })

Function to read cookies to prepopulate on load
function repopulateCheckboxes(){
  var checkboxValues = $.cookie('checkboxValues');
  if(checkboxValues){
    Object.keys(checkboxValues).forEach(function(element) {
      var checked = checkboxValues[element];
      $("#" + element).prop('checked', checked);
    });
  }
}

Working Fiddle

A: You have to do this on server side. Either with PHP, ASP.NET or whatever you use.
This is the only way.
Or, if your website is client-side only, then you would have to implement it without any page refreshing.

A: Here how I do it:

<input type="checkbox" <?php echo file_get_contents(".cktest"); ?> onclick="getFileFromServer('write_ckfile.php?target=.cktest&value='+this.checked, function(text){ show_write(text)});"> cktest with php

<input id="withajax" type="checkbox" onclick="getFileFromServer('write_ckfile.php?target=.cktest&value='+this.checked, function(text){ show_write(text)});"> cktest with ajax

and the file write_ckfile.php:
    <?php
$strtarget=$_GET['target'];

$status=$_GET['value']=="true"?"checked":"";
file_put_contents($strtarget, $status );

?>

I hope this helps.
MiKL~


text:
Q: Trigonometric equation $5 \sin(x) + 4\cos(x) - 10\sin(x)\cos(x) = 2$ I need advice on solving this equation, I enclose my procedure.
$5 \sin(x) + 4\cos(x) - 10\sin(x)\cos(x) = 2$
$5 \sin(x)(1-2\cos(x)) -2(1-2\cos(x))=0$
$(1-2\cos(x))(5\sin(x)-2)=0 $
Here is my solution to this equation
$cos(x) = 1/2 \implies \pi/3 + 2k\pi, 5/3\pi+2k\pi $
$x = \arcsin(2/5)+2k\pi$
In entering the example, I still have the result of $\pi-\arcsin(2/5)$, but I don't know how to get to it. Thank you in advance for the advice

A: Use the tan half-angle subsitution $z = \tan (x/2)$ or  $$x = 2\, {\rm atan}(z)$$
Note that
$$\begin{aligned}
   \cos(x) & = \frac{ (1-z^2)}{ (1+z^2)} \\ \sin(x) & = \frac{ (2 z)}{ (1+z^2)}
\end{aligned}$$
which is substituted into the equation to get
$$ \begin{aligned}
5 \sin(x) + 4 \cos(x) - 10 \sin(x) \cos(x) & = 2 \\ \hline \\
5 \frac{ (2 z)}{ (1+z^2)} + 4 \frac{ (1-z^2)}{ (1+z^2)} - 10 \frac{ (2 z)}{ (1+z^2)} \frac{ (1-z^2)}{ (1+z^2)} & = 2 \end{aligned} $$
The above is simplified to
$$ -\frac{ 2 z^4 -15 z^3 + 5 z -2}{ (1+z^2)^2 } = 1 $$
or
$$ 3 z^4 - 15 z^3 + 2 z^2 + 5 z = 1  $$
$$ (z^2 -5 z +1) (3 z^2 -1) = 0 $$
The four (primary) solutions are
$$ \begin{aligned} z & = \begin{cases}
 \frac{1}{\sqrt{3}} \\ - \frac{1}{\sqrt{3}} \\ \frac{5}{2} + \frac{\sqrt{21}}{2} \\ \frac{5}{2} - \frac{\sqrt{21}}{2} \end{cases}
\end{aligned} \rightarrow
\begin{aligned} x & = \begin{cases}
 \frac{\pi}{3} \\
-  \frac{\pi}{3} \\
\frac{\pi}{2} + 2\, {\rm atan}\left( \frac{\sqrt{21}}{7} \right) \\
\frac{\pi}{2} - 2\, {\rm atan}\left( \frac{\sqrt{21}}{7} \right)
 \end{cases}
\end{aligned} $$

A: General solution for $\cos x=a$, $|a|\leq 1$ is $x=2k \pi \pm \cos^{-1} a$, $k \in \mathbb{Z}$ and general solution for $\sin x=b$, $|b|\leq 1$ is $x=n \pi + (-1)^n \sin^{-1} b$, $n \in \mathbb{Z}$. I think this solves your query.


text:
Q: Need help proving the standard topology is a topology Define $$\tau_s = \{ U \subseteq X| \forall x \in U, \exists \delta > 0 \text{ s.t. } B_\delta(x) \subseteq U\}$$

Show $\tau_s$ is a topology on $\mathbb{R}^n$

Can someone check if my proof is correct and help me resolve a problem with showing finite intersection?

*

*$\varnothing$ vacuously lies in $\tau_s$. Let $U_x$ be an open set for each $x$ that lies in $X$, then $\bigcup_{x \in X} U_x = X$. Arbitrary union of opens is open, hence $X$ is open.

*Let $\{U_i\}_{i=1}^n$  be a finite subcollection of sets in $X$, then let $x \in \bigcap\limits_{i = 1}^n U_i$, since $x \in U_i$, $U_i$ is open, then $\exists \delta_i>0$ for each $x \in U_i$$\ldots$
Here I want to say that we wish to pick $\delta = \min\{\delta_i\}_{i=1}^n$ so that $B_\delta(x) \subseteq \bigcap\limits_{i = 1}^n U_i$, but it is not clear (graphically) that such $\delta$ would work. What is the way to continue the proof from $\ldots$

*Let $\{U_\alpha\}_{\alpha \in I}$ be an arbitrary subcollection of sets in $X$, then $\forall x \in U_\alpha,  \exists \delta_\alpha >0$ s.t. $B_{\delta_\alpha} \subseteq U_\alpha \implies B_{\delta_{\alpha}}(x) \subseteq \bigcup_\limits{\alpha \in I} U_\alpha, \forall x \in\bigcup_\limits{\alpha \in I} U_\alpha  $

One more thing, can $X$ be any metric space?

A: Consider your finite collection $U_i$. If $x \in U_i$ for all $i$, you have $\delta_i$ such that $B(x, \delta_i) \subset U_i$. Now take $\delta = \min \delta_i$. Since $\delta \leq \delta_i$, for all $i$, $B(x,\delta) \subset B(x, \delta_i) \subset U_i$ for all $i$. Thus $B(x,\delta) \subset \cap_i U_i$.


text:
Q: GKGoal Avoid Boundary Obstacles I am seeming to have difficulty keeping my sprite nodes inside a map boundary that I have set up in the following way:
I have an SKNode *enemy that moves around an SKScene by goals and behaviors courtesy of GameplayKit from iOS 9. Currently the node wanders, and avoids obstacles that are defined GKPolygonObstacle objects. I have my bitmask set up so that any obstacle is deemd category wall, which the node is told to collide with (AKA disallow passing through).
In my didBeginContact:(SKPhysicsContact *)contact I am handling these collisions. All is working exactly as planned and there are no issues when manually moving this enemy.
However, the problem begins when I have the enemy wander around the scene through an SKGoal *wanderGoal set up as
    // Low --> 0.5     Lowest --> 0.25
    enemy.wanderGoal = [GKGoal goalToWander:low];
    [enemy.agent.behavior setWeight:lowest forGoal:enemy.wanderGoal];

    // Add obstacles to avoid for each of the inner map nodes
    // that act as impassible areas for the enemy to pass through.
    NSArray *obstacles = [SKNode obstaclesFromNodePhysicsBodies:innerMapArray];

    /** This goal does not change --> enemies will ALWAYS
     avoid the obstacles in the level map. This should always
     be set to the highest priority of the enemy goals
     */
    enemy.avoidGoal = [GKGoal goalToAvoidObstacles:obstacles maxPredictionTime:10];
    // Highest --> 250
    [enemy.agent.behavior setWeight:highest forGoal:enemy.avoidGoal];

The enemy moves randomly as expected, and seems to avoid the obstacles most of the time...yet on the occasion the enemy does in fact pass through the map barrier. Let me expand on this:
The map barrier is essentially a rectangle, and I have set up 2 nodes that act as a shell that represent the left half and the right half of this shape. These nodes have a thickness of 100 points so they are not simply CGPath refs but rather shapes. They act as these two brackets act:  [] (my halves are flush touching at the middle).
My question is such:

*

*How can I prevent the enemy from passing through these obstacles with using either physics with the bitmask categories, or by the goal behavior? (Or both together)

I understand that while a GKGoal is a suggested behavior it does not guarantee this goal to be reached (but it can be ~95% sure it wont happen as Apple's AgentsCatalog shows). But, what I don't understand is why the enemy does not simply "slide" along the edge of the boundary as the goal tells it to (try to) "pass" through such boundary.
This "sliding" behavior does happen when I manually move the enemy around the scene, and as I attempt to move it passed a boundary deemed an obstacle, it slides towards the direction that I am having it move (just as any video game does that has map boundaries).
SO
If someone can help me prevent this from happening / explain how to approach preventing the enemy from ever passing through these (supposedly) "impassible" areas, I would be most appreciative.
FYI: If you are unclear with what I am describing / how I have created any objects, please ask and I will provide more info to help.


text:
Q: How to read all mails using Gmail api efficiently? I am trying to read all the mails of a user using Gmail API filtering by inbox. But to read 16k+ mails it is taking around 2hrs. Is there any efficient way?
now = datetime.now()

timestamp = math.floor(datetime.timestamp(now))

count = 0
while True:
    results = service.users().messages().list(maxResults=50,userId='me',q='in:inbox before:{}'.format(timestamp)).execute()
    messages = results.get('messages')
    EmailRecepit=[]
    if messages==None:
        break
    for msg in messages:
        print("Count",count)
        count+=1
        # Get the message from its id

        txt = service.users().messages().get(userId='me', id=msg['id']).execute()
        try:
            # Get value of 'payload' from dictionary 'txt'
            payload = txt['payload']
            headers = payload['headers']
            attachment = payload['parts']
            for header in headers:  # getting the Sender
                if header['name'] == 'From':
                    msg_from = header['value']
                    name=sender_name(msg_from)#Sender Name Not email
            for a in attachment:
                if a.get('filename') != '' and len(a.get('filename')) != 0:
                    document = a.get('filename')
            if count % 50==0:
                timestamp = math.floor(datetime.timestamp(parser.parse(headers['Date']))

        except socket.error as error:
            pass
        except:
            pass

A: The less requests you perform, the more efficient your code will be
Therefore, you should modify the request
service.users().messages().list(maxResults=50,userId='me',q='in:inbox before:{}'.format(timestamp)).execute()
by increasing the maximum number of results per request, e.g.
Specify: maxResults=500
However, be aware that using service.users().messages().get() on a large number of emails means a large number of requests, which inevitably  will make you code slow.
Consider narrowing down the number of results retrieved with service.users().messages().list by expanding the q query and only retrieve emails that you are really interested in. For example: only emails with attachments, only emails from a certain sender or with a certain subject line.
If you must retrieve all 16k+ emails - the only way to speed up your code is using batch requests
Have a look e.g. here for a sample of how to implement a batch request for Gmail API in Python. Note that using batch requests can still result in excedding quota if you perform too many requests.


text:
Q: How to set domain to avoid overlapping dots and axis in d3 plot? I'm trying to create a simple scatter plot in d3 (similar to this one from matplotlib):

I use extent() to set the scale's input domain range.
xScale.domain(d3.extent(xvalues));

Using this approach results in some dots overlapping axises in d3 plot:

How to avoid axis overlapping and make a margin similar to the matplotlib's plot?
Input values vary, so simple increment / decrement of the extent() output doesn't look like a general solution.

A: In general, the best way of handling this is to call the scale's .nice() function, which will round the ends of the domain of the scale to nice values. In your particular case, this doesn't work, as the values are "nice" already.
In this case I would compute the extent of the domain and extend it by a fraction of that. For example:
var padding = (xScale.domain()[1] - xScale.domain()[0]) / 10;
xScale.domain([xScale.domain()[0] - padding, xScale.domain()[1] + padding]).nice();

A: In your matplotlib image, the dots are not overlapping and the x scale has negative value.
In d3:
var xScale = d3.scale.linear()
             .domain([
                    d3.min(data, function(d) {
                      return d.val;
                     })-10, //so the domain is wider enough for the zero value

                     d3.max(data, function(d) {
                      return d.val;
                     }),
             ])
              .range([height , 0])


text:
Q: how to give the drop down sub menu a slide down effect with delay I want to give the on hover submenu which shows fast a slidedown effects in CSS3
this is my fiddle
http://jsfiddle.net/cancerian73/BSZwP/
CSS
#nav > li:hover > a, #nav > a:hover {
    color: #008f43;
-webkit-transition: all .5s ease;
    -moz-transition: all .5s ease;
    transition: all .5s ease;
 }

But it's not working


text:
Q: pandas: rename axis in df I have a df which looks like this:
                Column 1
Channel
Apples            1.0
Oranges           2.0
Puppies           3.0
Ducks             4.0

I would like to rename the axis so it looks like this:
Channel         Column 1
Apples            1.0
Oranges           2.0
Puppies           3.0
Ducks             4.0

I tried these but got the same error msg:
merged_df.rename_axis("Channel")
merged_df.rename_axis("Channel", axis='columns')

TypeError: 'str' object is not callable

A: This is kind of a hack to get you what you eventually wanted it to look like.
df = pd.read_csv(data, sep='\s{2,}', index_col='Channel', engine='python')
df

df_excel_format = df.rename_axis('Channel', axis=1)
del(df_excel_format.index.name)
df_excel_format


text:
Q: pivot SQL query access When writing a query in MS Access my results return as such
MONTH   Field_Off_Code  test    test2   test3   test4   test5   Test6
1/1/2018    879 10669   11950   0.892803    8962    10452   0.857444
2/1/2018    870 10761   10819   0.994639    9097    9616    0.946027

However I would like them to return Like this
MONTH   MONTH
1/1/2018    2/1/2018
10669   10761
11950   10819
0.892803347 0.994639061
8962    9097
10452   9616
0.857443551 0.946027454

Can someone suggest the correct SQL tried using the crosstab function but no luck.


text:
Q: New review - Are all of the counts restarted from scratch? It has been quite a while since I last visited the review page. By now, the old review links are not there anymore and the new review system seems to be in use.
I would like to know, what will happen with the previous stats that I held? I remember I had actioned about 150 reviews (don't remember the number exactly). So, are all the previous counters/stat erased and won't they count now?

A: The only count that's been "backfilled" is the Suggested Edit count.
Apparently all the other counts were "too hard" to separate out from the old data.

A: You count up from now, mostly.
The old review badge has been replaced by three new badges that are easier to track based just on your review count. Stats for the old review system are not taken into account for these badges, except for your suggested edits review count.


text:
Q: Prove That R and an open set has the same cardinality -Prove  that R and the open set (-pi/2,pi/2) have the same cardinality. (*Hint: dfine the function f:R->(-pi/2,pi/2) by f(x)=tan^-1x. Then show f is well-defined, onto and one-to-one.)
-I am not sure how to prove a function is well defined. I understand that well defined means every point has a unique image,and I know it cannot be proved by showing a function is one to one.
I am unclear about showing how an inverse function is onto.
-Proof that f is one to one
If f(x)=f(y)
=>tan^-1x=tan^-1y
=>x=y
I think that this may be incorrect as well. but any type of guidance would be useful.

A: For well-defined, notice $\tan(x)$ is one-to-one on $(-\pi/2,\pi/2)$.
For one-to-one, the derivative of $\tan^{-1}(x)$ is positive. Or you can argue that since $\tan x$ is increasing on $(-\pi/2,\pi/2)$, so is it's inverse on $(-\infty,\infty)$.
For onto, it's more or less the definition of inverse tangent. Let $y\in(-\pi/2,\pi/2)$. Then let $x=\tan y$.


text:
Q: Keep getting same value from jQuery array I have two problems.

*

*I have a jQuery array which stores the URL's for images. Everything was working fine a few minutes ago, but now it's not. I have the following code for the images:
var images = ["link1","link2","etc","etc"];
index=0;
this to display them when you click their thumbnails:
$('.thumbnail').click(function(){
$('.large_view').prepend('');
});

and this to show the previous/next images in the array:
$('.next').click(function(){
         index = (index===0)?(images.length-1):(index-1);
          $('.large_view img').attr('src',images[index]);
         });

$('.previous').click(function(){
           index = (index==images.length-1)?0:(index+1);
           $('.large_view img').attr('src',images[index]);
           });

My problem is that when I click a thumbnail, the same image (the first one in the array) always shows up. After that I can change the image properly with my next/previous buttons.

*When I display the images in my array with code that includes the following, it shows up backwards, from the last item in the array to the first one: for(var i=0; i<images.length; i++)
P.S. the only reason the code inside .previous and .next are backwards is because the array is somehow backwards, like I said.

A: The first problem is that when any thumbnail is clicked, index will be at its original value of 0, which is what's always making the first one show up. To fix this, you'll need to determine the corresponding index from whichever thumbnail was clicked (perhaps using $(this).attr('data-image-index'), if you stuffed the index into an attribute like that).
The second problem is that you want to use .append instead of .prepend in the for loop to tack each new thumbnail onto the end of the set instead of the beginning.
Also, the click handlers for .next and .previous appear to be backwards.
And you might want to use $('.large_view').html(...) instead of $('.large_view').prepend(...) if you only want one large picture to be displayed at any given time.

A: 1) your index is 0, so you are going to get the first image every time.
this line

$('.large_view').prepend('');

should be changed, to reference the index of the clicked thumbnail instead of the variable called index. so something like

$('.large_view').prepend('');

You will add the index attr when creating the thumbnails, for example:

for( var i=0; i<images.length; i++){
  var thumbnails = '' + '';

  $('.gallery').prepend(thumbnails);

}

2) for your second problem, you are using prepend, which as the name implies PREpends. you will want to use append() to get them in the forward sequence as you want.