Consulta de API bloqueada por CORS

Question: Caros,
Estou realizando a chamada de uma API, porém está sendo bloqueada pelo CORS. Instalei uma extensão em meu navegador que habilita e desabilita o CORS. Quando habilito a API retorna os dados esperados, porém ao desativar retorna o seguinte erro no console:
Access to XMLHttpRequest at 'http://minhaurldaapi/rest/busca?cod=1080' from origin 'http://18.104.22.168' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Código da chamada:
  var settings = {
    "url": "http://minhaurldaapi/rest/busca?cod=1080",
    "method": "GET",
     "crossDomain": true,
    "timeout": 0,
    "headers": {
      "accept": "application/json",
      "Access-Control-Allow-Origin":"*",
      "Authorization": "Basic AJeqpLOKkiifhueARIjcmOrij7FEF5iodUhIKCPERWh6"
    },
  };

  $.ajax(settings).done(function (response) {
  json = JSON.stringify(response);
  json2 = JSON.parse(json);

  });

Procurei em diversos outros tópicos problemas semelhantes, mas ainda não resolvi o problema. Alguém teria alguma ideia de como solucionar este impasse ? Seria alguma configuração no APACHE ?
Obrigado
Comment: Você configurou o cors na sua api?
Comment: @adventistaam A API é de um fornecedor externo... Estou apenas consultando... Poderia dar mais detalhes?
Comment: Então eles tem que configurar o CORS da api deles para aceitar o seu cliente
Comment: Se é uma API externa e ela não está configurada para ser consumida do seu frontend, você deve implementar em seu backend a comunicação com eles.
Comment: Você consegue acessar via postman ou Insomnia?
Comment: Sim, via Postman consegui acessar sem problemas.
Comment: Muito provavelmente a api deve estar bloqueando a origem e porta de sua api
Comment: Tenta seguir essa [resposta](https://stackoverflow.com/a/49813910/6754506), volte sua atenção para o headers
Comment: Adicionei ao headers as seguintes informações:
         `code` "accept": "application/json",
          "Access-Control-Allow-Origin":"*",
Answer: Você pode solicitar ao dono da API para incluir a chave Access-Control-Allow-Origin no cabeçalho de resposta com o endereço do seu domínio ou um *. Exemplo:
Access-Control-Allow-Origin: http://seudominio.com ou Access-Control-Allow-Origin: *
Com isto o navegador irá identificar a chave e não apontará mais o problema de CORS.
Caso isto não seja possível, você pode construir um proxy em seu backend (mesmo domínio) para intermediar estas requisições. Em outras palavras, seu frontend efetua a requisição ao seu backend, seu backend efetua a requisição a API e devolve a resposta.
Vou deixar este link que na minha opinião dá vários detalhes sobre problemas como este.

Consulta de API bloqueada por CORS


Modeling mortgage prepayment behaviour using survival analysis

Question: I am doing a study of prepayment behaviour on mortgage loans where the partial prepayment (curtailments) are very frequent and sort of normal behaviour as there are no penalties for such events.
As a result of partial prepayments the final maturity of the contract can change (does not have to necessarily). As partial prepayments are recurrent events this poses a problem as the maturity should in principle decrease as more partial prepayment events occur. So we have recurrent events increasing with time and the final maturity of contract decreasing given the prepayments.
The event of interest is the time to termination of the contract or at least the time to a decrease in maturity of the contract (if the contract is still not closed).
So we are facing with increasing event of prepayment but decreasing times of maturity. Hence, the time to event is decreasing with time which is not technically ok. So I though to take only the last change of maturity conditional on the actual event happening. If there is no event then the observation is censored.
I am concerned with the following:
1. does this violate the general premises of using survival analysis?
2. How to treat censored events as they will definitely have a shorter time period than the uncensored event? This poses the problem in defining the risk data set which will inevitably have zero hazard rate at the beginning and will increase gradually much later on with time.
I would very much appreciate any suggestions how else to tackle this type of a problem.
Comment: I have similar question about using survival analysis on payment behavior now. How is your progress to solve the problem? Thanks.
Answer: I can suggest looking into models for recurrent events with a dependent terminal event. Indeed the terminal event (time to termination of the contract) is a dependent censoring for the recurrent events process, so the usual assumption of "independent censoring" does not hold.
The basic idea in tackling this is to use random effects (frailty). With this, you would have an intensity (hazard) for the recurrent events which depends on the random effect $z_i$:
$$ h_i(t|z_i) = z_i h_0(t) \exp(\beta'x_i)
$$
and a hazard for the terminal event
$$
\lambda_i(t|z_i) = z_i ^\alpha \lambda_0(t) \exp(\gamma'x_i)
$$
with $\beta$ and $\gamma$ regression coefficients.
This implies that when $\alpha<0$ a high rate of recurrent events is associated with a lower rate of terminal events, and when $\alpha>0$ a high rate of recurrent events is associated with a high rate of terminal events.
This is implemented in the R package frailtypack, which is available on CRAN. There you can specify $h_0$ and $\lambda_0$ in several forms (splines, constant, Weibull, etc). Perhaps this might give you a starting point.
For reading, a good starting point would be chapter 6.6 from The Statistical Analysis of Recurrent Events by Cook and Lawless. Good luck!


Metric connection

Question: How to prove that any vector bundle with a fiber metric g admits a metric connection? It seems I should use partition of unity, but I have no idea how to proceed.
Also it seems there are two definitions of connection on a vector bundle E, one is that
$\nabla: \Gamma(TM) \times \Gamma(E) \to \Gamma$(E),
and the other one is that $\nabla: \Gamma(E) \to \Gamma(E) \otimes\Gamma(T^\ast M)$, and they should be equivalent. But I don't see how to use this to show the following equations are equivalent:
If there is a fiber metric g on vector bundle E, then
$d(g(u,v))=g(\nabla u,v)+g(u,\nabla v)$ for all $u,v\in\Gamma(E)$
is equivalent to
$X(g(u,v))=g(\nabla_X u,v)+g(u,\nabla_X v)$ for all $X\in TM$,
is it because that
$d(g(u,v))(X)=X(g(u,v))$?
I am just not sure about how vector fields act on metrics.
Answer:
Yes, if you put an arbitrary metric on each trivialized restriction and then glue them together using a partition of unity, you'll get a metric on the whole thing.
To go from a map $\Gamma(E) \rightarrow \Gamma(E)\otimes \Gamma(T^*M)$ to a map $\Gamma(E)\otimes \Gamma(TM)\rightarrow \Gamma(E)$, if $s_0\mapsto s_1\otimes x$, then you can put $s \otimes v \mapsto s_1 \cdot x(v)$ -- basically, this all comes from the fact that $Hom_{\mathbb{R}}(V,W)\cong V^*\otimes W$.
It depends which version of $\nabla$ you're using.  From your notation it looks like either you're using the definition $\nabla:\Gamma(E)\rightarrow \Gamma(E)\otimes \Gamma(T^*M)$ or you're using the definition $\nabla:\Gamma(E)\otimes \Gamma(TM) \rightarrow \Gamma(E)$ and suppressing the vector field.  My guess is that for $s_0\otimes x\in \Gamma(E)\otimes \Gamma(T^*M)$ you're extending the metric by $g(s_0\otimes x,s_1)=g(s_0,s_1)\cdot x \in \Gamma(T^*M)$; in this case, yes the fact is true by what you said, which can be taken as the definition of applying a 1-form to a vector.

Metric connection


Linux smart card authentication

Question: I am using puttysc to authenticate to a remote Linux server with my smart card .  But as I understand, this isn't true PKI authentication - puttysc just unlocks the public key and matches it to a user account on the Linux server.  Is there a way that I can use puttysc along with pam_pkcs11 to perform true PKI authentication?  I know that you can use PAM along with the pam_pkcs11 module to require true PKI authentication.  I just don't know how to use the two (puttysc and PAM with pam_pkcs11) together.
Answer: I don't believe puttysc can. But I think this is what you are looking for
https://www.risacher.org/putty-cac/
Answer: The smartcard authentication on the client side performs a normal challenges response. I.e. the ssh server encrypts a challenge with the public ssh key from the .ssh/authorized_keys.
You smartcard decrypts this challenge using the private key on the smartcard.
But at this point no x509 certificates are involved. If you want to include x509 certificates and CRLs you need:

a patched SSH server, that supports DNs in the authorized_keys
a client, that supports handling certificates like the tectia ssh client.
Comment: Is it possible that this patched server/client exist somewhere within the far reaches of the net?  Sounds like a great project idea.
Comment: Take a look here: http://roumenpetrov.info/openssh/

Linux smart card authentication


Drupal rules discount matrix - look up by taxonomy term

Question: I'm having trouble applying a complex set of discounts to my products through rules.
The discounts are basically a user-category/product-category matrix with a different discount percentage for each cell. User categories and product categories are taxonomy lists. I have added a Field Collection field (with and infinite number of values) to the user category. In this field collection I combine a product category and a discount percentage (as a decimal), and then repeat for all product categories.
So when calculating the product sale price I need to:

Look up the product category (works fine)
Look up the user category and load the discounts list (works fine)
Look up the right discount in the discounts list by product category (having trouble with this)

I've been able to look up the right discount in a custom PHP action like this:
<code>$product_category = $product->field_product_category['und'][0]['tid'];

for($discount_index=0;$discount_index<count($user_discounts);$discount_index++){
    $discount = $user_discounts[$discount_index];
    if($discount->field_discount_product_category['und'][0]['tid'] ==  $product_category){
        return $discount->field_discount_percentage['und'][0]['value'];
    }
}

return 0;
</code>
But apparently returning values out of a custom PHP block is not supported.
Next I thought to install the Conditional Rules module.
I could loop through the discounts and check the current loop variable against the product category and apply the discount if it matched. Within the If I can't access my loop variable though.
Can anyone suggest a method that might work? I prefer not to have to write my own module if it can be avoided.
Answer: If you want to use rules (and with commerce I think it makes sense), and you are comfortable with PHP, I would recommend writing your own module that defines the custom conditions and actions that you need to look up and apply discounts.
In my experience, the rules interface starts to break down quickly when use cases become even moderately complex. You can spend a lot of frustrating time fiddling with the interface, trying to get it to do what you want.
By writing your own conditions and actions, you keep the complex logic in code, where you can easily debug, access, and compare any information you might need.
In addition, your custom actions and conditions will be nicely exposed in the rules interface, and keep the high-level logic of your commerce solution tidy in one place.
Docs are here: https://drupal.org/node/298486. Drupal commerce itself has many good examples of custom actions and conditions to use as reference.
Comment: As you can see from the answer I posted myself, I managed to fix this without resorting to writing my own php code.

I feel that this particular problem is not a good fit for writing my own action **unless** I set myself to writing a generic action for selecting an item from a list by configurable conditions that would be useful to many. I don't quite feel up to that.
Answer: I managed to solve this specific problem without resorting to writing custom actions in my own module.
I created a Rules component that takes a Field Collection Item (my loop variable), my Product Category taxonomy term and Commerce Line Item for parameters. Then I moved the conditional into the component, updated the price if the Product Category matched, and called the component from my loop. It even looks reasonably comprehensible.
I only needed to re-assert the fields on my Field Collection item (in my conditions) to be able to work with it.


Formatting Problem Date with DateTime

Question: I want to display a date with this format :

MM/dd/yyyy HH:mm:ss tt

for example :

01/04/2011 03:34:03 PM

but I have a problem with the following code
class Program
{
    static void Main(string[] args)
    {
        DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 0, 0, 0);
        string displayedDate = dt.ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
        Console.WriteLine(displayedDate);
        Console.Read();
    }
}

displays :

01/04/2011 12:00:00 AM

instead of

01/04/2011 00:00:00 AM

Anyone knows why ?
Thank you !
Comment: Well in the AM/PM system midnight is represented as 12:00:00 AM.
Comment: Ok, here was the confusionn. I thought midnight was represented as 00:00:00 AM instead of 12:00:00 AM :-/
Comment: That's a reasonable confusion. In the United States, a 12-hour format is far more popular, where 12:00 AM is midnight. As I understand, most everywhere else, a 24-hour format is preferred for its lack of ambiguity. Under that system, midnight is indeed 0:00 (with no need for an AM/PM specifier). Anyway, glad to see your problem is resolved!
Answer: Because you've specified a 12-hour clock format instead of a 24-hour format.
The documentation for the DateTime.ToString method gives a full table of format specifiers and what they mean. The choices for hour are as follows:

"h"     The hour, using a 12-hour clock from 1 to 12.
"hh"    The hour, using a 12-hour clock from 01 to 12.
"H"     The hour, using a 24-hour clock from 0 to 23.
"HH"    The hour, using a 24-hour clock from 00 to 23.

So, instead of the hh custom format specifier, you need to use HH. Change this line:
string displayedDate = dt.ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

to this:
string displayedDate = dt.ToString("MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);

Answer: You have specified that you want a 12-hour format instead of a 24-hour, that's why. You should use HHfor 24-hours. Please see the reference. This should work for you:
string displayedDate = dt.ToString("MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);

Comment: I know I've chosen a 12h format. In this format we write "midnight" as 12h00 AM ?
Answer: You'll want to change 'hh' to 'H' in your ToString() call.
Comment: Yeah, getting a little tired and read that it needed to be switched the other way around.  Somehow, that translated to changing to 'h'.

Formatting Problem Date with DateTime


what is the area of the region [ (x,y):0<x , y<1 , 3/4<x+y<3/2 ] do'nt use area of triangle & squares by conventional method?

Question: I was confused with the answer provided on my other question
since it doesn't fit the expected answer given in a multiple choice question:
 (A) 9/16 (B) 7/16 (C) 13/32 (D) 19/32
I would like to verify this result using integration.
I know how to integrate but concept of strip is new to me . can we solve this using only one strip ?
Comment: You just asked this question today and it went on hold. What is the point in asking it again ?
Comment: You can make this region by removing two triangles from a rectangle. No calculus is required to find its area.
Comment: You dont neccessary have to integrate, You can just find the points of intersection of different lines and then use normal geometry(area of triangles and rectangles) and find areas.
Comment: At the picture $x>1$
Comment: @Shailesh there was confusion in answer , because what I am getting is not in options acailable . so I have (want) to varify it using integral calculas .
Answer: You cannot get away with just one integral here. The easiest way is to integrate with respect to $y$. You will have to setup two integrals.
If you integrate with respect to $x$, you will have three integrals.
That being said, This shape is simply a polygon. You could partition it into rectangles and triangles, and add up their areas. If you don't have to use calculus, I would do it this way for sure.
Answer: Area$=\int_{0}^{1}\left(\frac{3}{2}-y\right)dy-\int_{0}^{3/4}\left(\frac{3}{4}-y\right)dy$


How to get Spring sleuth to work when using Feign builder

Question: I'm trying to get spring slueth to propogate the trace ids through our systems.
when checking the logs on the other service I noticed new Ids being generated.
I thought this may be due to my using a Feign builder and I was already using a okHttpClient.
I came across the following:
https://github.com/spring-cloud/spring-cloud-sleuth/issues/594
How to implement Sleuth Tracing With Feign.Builder?
I have my beans set up like the following:
<code>@Configuration
@RequiredArgsConstructor
public class OkHttpConfig {

  private final Properties properties;

  @Bean
  public OkHttpClient okHttpClient() {
    return new Builder()
        .connectTimeout(properties.getHttpTimeoutMillis(), TimeUnit.MILLISECONDS)
        .readTimeout(properties.getHttpTimeoutMillis(), TimeUnit.MILLISECONDS)
        .writeTimeout(properties.getHttpTimeoutMillis(), TimeUnit.MILLISECONDS)
        .connectionPool(new ConnectionPool(properties.getHttpPoolSize(),
            properties.getHttpKeepAliveMillis(), TimeUnit.MILLISECONDS))
        .build();
  }
</code>
<code>@Configuration
public class HttpClientConfiguration {

  @Autowired
  private Properties properties;

  @Autowired
  private Client client;

  @Bean
  public SomeClient SomeClient(Client client, ObjectMapper objectMapper {
    return feignClient(properties.getUrl(), SomeClient.class, client,
            objectMapper);
  }

  public static <T> T feignClient(String baseUrl, Class<T> clientClass,
      Client client, ObjectMapper objectMapper) {
    return Feign.builder()
        .client(client)
        .decoder(new JacksonDecoder(objectMapper))
        .encoder(new JacksonEncoder(objectMapper))
        .target(clientClass, baseUrl);
  }
</code>
I expected the client to be wrapped in a trace implementation but i kept getting the following error
<code>Unsatisfied dependency expressed through field 'client'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'feign.Client' available:
expected at least 1 bean which qualifies as autowire candidate.Dependency annotations:
</code>
Using the following versions:
Spring boot 2.1.2.RELEASE
org.springframework.cloud:spring-cloud-sleuth:2.1.0.RELEASE
Comment: If you're not using Sleuth you don't have this issue?
Comment: No, as I wasn't passing in a Client instead I was passing around OkHttpClient which spring recognised as bean.
Comment: I'm asking cause maybe it has nothing to do with Sleuth. Try doing the same without Sleuth and see if an exception is thrown.
Comment: Same issue without Sleuth. I also have intellJ warning "Could not autowire. No beans of 'Client' type found. more... (⌘F1)"
Comment: That's what I thought. So I guess you can rename the issue and untag sleuth cause it has nothing to do with it.
Comment: The alternative is to pass around okHttpClient, however then sleuth is not wrapping it in its trace representation. I changed it to use client for that reason
Answer: In the chat (https://chat.stackoverflow.com/rooms/188411/discussion-between-yk-47-and-marcin-grzejszczak) we've analyzed the current setup. It was missing bean definition and most importantly the spring-cloud starter for open feign.


Are orbits subsets of S

Question: In Serge Lang's Abstact ALgebra, he define orbits like this:

let G operate on a set S.  Let $s \in S$. The subset of $S$ consisting of all elements $xs, x\in G$, is called the orbit of $s$ under $G$

How is this a subset of $S$? Can't there be an $x \in G$ such that $xs \not \in S$?
For example, if $S = e$, where $e$ is the identity element, then isn't the orbit of $e$ under $G$,  $G$?
Comment: A group action is a function that takes in a group element, a set element and spits out a set element, **not** a group element.
Comment: A group action is a map $G\times S\to S$.
Comment: If $S = \{e\}$, then the orbit of $e$ under $G$ is simply $\{e\}$, and that's because there is only one way of giving a group action on a singleton. See Lord Shark's answer. Be careful of not mixing up $S$ and $G$.
Answer: For each element $s\in S$, the orbit of $s$ is defined by $O_s = \{gs\mid g\in G\}$.
Since $gs\in S$, this is clearly a subset of $S$.
In view of the identity element $e\in G$, by definition $es=s$ for each $s\in S$ and so the orbit of $s$ contains $s$ (choose $g=e$), i.e., $s\in O_s$.
Comment: [quote]For example, if S=e, where e is the identity element, then isn't the orbit of
e under G, G? [/quote]
Comment: If $S=\{e\}$, then $O_e = \{ge\mid g\in G\} = G$, since $ge=g$.

Are orbits subsets of S


Call javascript function from typescript in ionic project

Question: I added a plugin in my ionic project, so I have the java code and the JS code like this :
cordova.define("cordova-sms-plugin.Sms", function(require, exports, module) {
'use strict';

var exec = require('cordova/exec');

var sms = {};

function convertPhoneToArray(phone) {
    if (typeof phone === 'string' && phone.indexOf(',') !== -1) {
        phone = phone.split(',');
    }
    if (Object.prototype.toString.call(phone) !== '[object Array]') {
        phone = [phone];
    }
    return phone;
}

sms.send = function(phone, message, filename, options, success, failure) {
    // parsing phone numbers
    phone = convertPhoneToArray(phone);

    // parsing options
    var replaceLineBreaks = false;
    var androidIntent = '';
    if (typeof options === 'string') { // ensuring backward compatibility
        window.console.warn('[DEPRECATED] Passing a string as a third argument is deprecated. Please refer to the documentation to pass the right parameter: https://github.com/cordova-sms/cordova-sms-plugin.');
        androidIntent = options;
    }
    else if (typeof options === 'object') {
        replaceLineBreaks = options.replaceLineBreaks || false;
        if (options.android && typeof options.android === 'object') {
            androidIntent = options.android.intent;
        }
    }

    // fire
    exec(
        success,
        failure,
        'Sms',
        'send', [phone, message, filename, androidIntent, replaceLineBreaks]
    );
};

sms.hasPermission = function(success, failure) {
    // fire
    exec(
        success,
        failure,
        'Sms',
        'has_permission', []
    );
};

module.exports = sms;
});

And I want to call the sms.send(...)  function in my Typescript code.
I tried to import file like this :
import sms from '../../../plugins/cordova-sms-plugin/www/sms.js';

or
import * as Sms from '../../../plugins/cordova-sms-plugin/www/sms.js';

or
window['window']['sms']['send'](...)

but nothing work, ionic doesn't find the send() function, can you help me, please ?
Answer: You are not calling in a correct way.In your ts file do not need to import js file.
Either you can call directly by using global scope variable or you can create a .d.ts definition file for this plugin interface and can import on your .ts file.
After make sure that your plugin is installed correctly,Follow the below steps to call cordova-sms-plugin from TS file
Step-1. You can refer JS variable using windows object so declare it in .ts file
declare var window: any;

Step-2. Now you can call it like window.sms.send
 let phone: string;
//Set the value of phone
let message: string;
//Set the value of message
let options  = {
            "replaceLineBreaks: false"
            //
        };
 //Call the function
 window.sms.send(phone,message,options,(result: any) => {
            console.log("SuccessFully Done...");
        }, (err: any) => {
            console.log("An error has occuered :" + err.code);
        })

I also found a sample project on GitHub for you.You can refer this for look into the code:
https://github.com/abritopach/ionic-receiver-sms
Comment: Thank, I tried but I have an error :
 07-13 13:17:34.643 30659-30659/io.ionic.starter D/SystemWebChromeClient: ng:///AppModule/PhotoPage.ngfactory.js: Line 96 : ERROR
07-13 13:17:34.643 30659-30659/io.ionic.starter I/chromium: [INFO:CONSOLE(96)] "ERROR", source: ng:///AppModule/PhotoPage.ngfactory.js (96)
07-13 13:17:34.646 30659-30659/io.ionic.starter D/SystemWebChromeClient: ng:///AppModule/PhotoPage.ngfactory.js: Line 96 : ERROR CONTEXT
07-13 13:17:34.646 30659-30659/io.ionic.starter I/chromium: [INFO:CONSOLE(96)] "ERROR CONTEXT", source: ng:///AppModule/PhotoPage.ngfactory.js (96)
Comment: Ur application was working correctly without this plugin?
Comment: Yes no problem when I don't try to use this plugin.
(I answered below for add the screen of the error)
Comment: can you show your code where you calling the sms plugin?you can share it by any online IDE
Comment: @Nooby- you can refer this for refrence:https://github.com/abritopach/ionic-receiver-sms
Comment: I tried like this : https://ideone.com/YsAbiz and I have an html page wich call the function tryPlugin2().


can we run our node.js project from a compressed "zip" file without extracting Zip file?

Question: According to client requirement project should be less size. But generated source code size is much higher than the client demand. So this question raised how can we run node.js project from a zip file without extracting them. Is there any solution ? Please Help. Thanks You.
Answer: Added after initial post: It's not yet possible to run zipped code.
Have you looked into minifying the project's code?
There are packages that compress js and css files. They'll even concatenate them into a single js and a single css file for your deployment. This will decrease the file size and it will speed up page load because your application will be making fewer requests to the server.
If you want to do it with a minifier: https://github.com/mishoo/UglifyJS2
If you want to do it by hand: http://prettydiff.com/?m=minify
Also, have a look at webpack. I haven't used it personally, but it is described to do the same thing. It bundles your project for you.
https://webpack.js.org/
Comment: Thank You Mike Ferrari. I wil try this. But, is this possible to run project from a compressed file?
Comment: You can not run a code in a compressed format. Compression changes the content based on the algorithm used. As @mike correctly suggested you should minify your files it will reduce the size by a good amount.
Answer: You could try this approach, which will work if you're running on any Unix based system:
First, you need to combine your js source files into a single file. You could use a minifier to do this, or just cat them into one file.
Next, compress the file, e.g. gzip <src.js>. This will produce a compressed file like scr.js.gz.
You can now run this file using a command line like this: gzip -cd src.js.gz | node. What the command is doing is (1) unzipping the source file (-c) and writing the result to stdout (-d), and (2) piping the code to node, which will run it in interactive mode.
One caveat here is that, same as any other node app, any external dependencies in your code will need to be installed using npm before hand. If this is not possible in the target environment then you will need to remove those dependencies, perhaps by incorporating module code directly into your source.

can we run our node.js project from a compressed “zip” file without extracting Zip file?


embed rChart in Markdown

Question: I am trying to embed a NVD3 chart in a Markdown document. I am on a Ubuntu64 system with RStudio 0.98.932, R 3.1.0, rCharts 0.4.2, the browser is Chrome.
The instructions/code from this link:
 ```{r}

library(rCharts)
library(knitr)
opts_chunk$set(comment = NA, results = "asis", comment = NA, tidy = F)

hair_eye_male = subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = 'Eye',
  data = hair_eye_male, type = 'multiBarChart'
)
n1$set(width = 600)
# n1$show('iframesrc', cdn = TRUE)  # option 1
# n1$show('inline', include_assets = TRUE, cdn = TRUE)  # option 2
```

Neither of the options [n1$show] work, I just get code in a browser. Is there another way of including NVD3 documents in Markdown?
Answer: To get rCharts to work with knit2html, you will need to use the print method with the argument include_assets = TRUE. This is because knitr will not add the js and css assets required by an rCharts plot automatically. Here is a minimal working example.
## MorrisJS with Knit2HTML

```{r results = 'asis', comment = NA}
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
  data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)
```

Note that you need to use m1$print('chart2', include_assets = TRUE, cdn = TRUE) if you intend to publish your chart on RPubs, for otherwise the JS and CSS assets will be served from your local library.
Source:Knitr HTML in R Markdown
Answer: This code is working for me. I am using ubuntu64 and same config you mentioned.
```{r, echo=FALSE,results='asis',comment=NA}
library(rCharts)
hair_eye_male <- subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = "Eye", data = hair_eye_male, type = "multiBarChart")
n1$show('iframesrc',cdn=TRUE)
```

Note : you must write results='asis' and comment = NA in chunk options and not use opts_chunk$set as you have in your code block and what you pasted to copy.com.
Comment: Thanks koundy. You are right, the comment = NA appears twice, this is in the original code that I copy/pasted. Somehow the code does not work. When I knit HTML there is just code in a browser. I must be doing something wrong somewhere.
Comment: It doesn't. As said in the comment, there is just code in the browser. No graph.
Comment: you should be connected to internet and wait for sometime say 1-2 minutes for the chart to appear.
Comment: I do not see anything that looks wrong with the code.  Could you post the .Rmd and .html as a gist or on some other sharing site to see if I can reproduce your error?
Comment: @timelyportfolio : https://copy.com/paeRvRDKCYTr [sessionInfo], https://copy.com/NRCxrEV83xfn [html], https://copy.com/x1pddZTCRktK [Rmd].
Comment: sorry, I did not see this before, but `opts_chunk$set` does not apply to the current chunk, so you will need to start with

    ```{r results='asis'}
    ...
    ````

and you can eliminate the `opts_chunk$set` line.
Comment: which koundy alluded to, but appears the change did not get put into the code you posted to copy.com. You can then eliminate the opts_chunk$set line.  I added some bold to make sure this gets communicated in @koundy answer.
Comment: @timelyportfolio yeah thats what i meant. thanks for improving the answer. by the way im following your blog. good work. keep it up..:)
Comment: thanks timelyportfolio and koundy. it works now. Knit HTML opens in blank window, but opens correctly in browser.

embed rChart in Markdown


Redirect after updating nodes

Question: I've to redirect users, after updating a node, to /node/NID path and not to /node/NID/latest (I'm using content moderation).
I've tried to add this on hook_node_update() but have been ignored (without warning or errors):
if (!$entity->isNew()) {
    $path = URL::fromUserInput('/node/' . $entity->id())->toString();
    return new RedirectResponse($path);
}

Comment: Better to add this in hook_form_alter as a new submit handler, and then redirect inside of that.
Comment: Yes, and then don't return or send the redirect response, set the redirect in $form_state. Node forms often have set a destination too, then you need to handle both, see  https://drupal.stackexchange.com/questions/250465/how-to-force-a-redirect-override-the-destination-query-string-in-the-url
Answer: use \Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

function MYMODULE_node_update(Drupal\node\NodeInterface $node) {
  $path = Url::fromUserInput('/node/'.$node->id())->toString();
  $response = new RedirectResponse($path);
  $response->send();
}

You have to use like above. You are just returning the redirect response. You need to send redirectresponse to given path.
Comment: Sending a response is not a good idea, see the duplicate question.
Comment: Suggest of Ajay works but I'll take a look to the duplicate questio, thanks!

Redirect after updating nodes


How to make center lock image in HorizontalScrollView like in deprecated Gallery?

Question: I have LinearLayout inside of HorizontalScrollView.
 <?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/hsv"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <LinearLayout
        android:id="@+id/mygallery"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="horizontal" >
    </LinearLayout>

</HorizontalScrollView>

In LinearLayout I load images by:
myGallery = (LinearLayout) findViewById(R.id.mygallery);
for (int i = 1; i <= 5; i++) {
    ImageView iv = new ImageView(getApplicationContext());
    iv.setLayoutParams(new LayoutParams(screenWidth,LayoutParams.WRAP_CONTENT));
    iv.setImageBitmap(decodeSampledBitmapFromResource(getResources(),getResources().getIdentifier("pic0" + i, "drawable",getPackageName()), screenWidth, screenHeight));
    myGallery.addView(iv);

When user scrolls images I need to lock centered image (like in Gallery)
Comment: http://stackoverflow.com/questions/11345673/horizontalscrollview-with-imageviews-as-a-child-and-while-scrolling-the-center-o
Answer: You should use smoothScrollTo(x,y) so it will appear that the image is locked at the correct position. X and Y should be calculated manually.
Comment: Ok. I must do 'smoothScrollTo(x,y)' when user stoped scrolling. But how I can handle this moment? I didn't see any onStopScrollListener etc.
Comment: You should use MotionEvent.ACTION_UP on onInterceptTouchEvent(MotionEvent)
Answer: Here is my solution:
1.create custom view
public class CenteringHorizontalScrollView extends HorizontalScrollView implements View.OnTouchListener {

private static final int SWIPE_PAGE_ON_FACTOR = 5;
View targetLeft, targetRight;
CircleImageView leftImage, rightImage;
private Context mContext;
private int mActiveItem;
private float mPrevScrollX;

private int mItemWidth = 250;// or whatever your item width is.
private int centreItemWidth = 350;
private final int LEFT = 1;
private final int RIGHT = 2;
private final int NA = 0;
private final int emptyView = 2;
private static String TAG = CenteringHorizontalScrollView.class.getSimpleName();

public CenteringHorizontalScrollView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mContext = context;
    setOnTouchListener(this);

}

@Override
public boolean onTouch(View v, MotionEvent event) {
    int x = (int) event.getRawX();

    boolean handled = false;
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mPrevScrollX = x;
            break;
        case MotionEvent.ACTION_MOVE:

            break;
        case MotionEvent.ACTION_UP:
            int minFactor = mItemWidth / SWIPE_PAGE_ON_FACTOR;

            if ((mPrevScrollX - (float) x) > minFactor) {
                if (mActiveItem < getMaxItemCount() - 1 - emptyView) {
                    setCurrentItem(mActiveItem + 1);
                    CommonConstant.currentChildIdx = (mActiveItem - emptyView);
                }
            } else if (((float) x - mPrevScrollX) > minFactor) {
                if (mActiveItem > 0 + emptyView) {
                    setCurrentItem(mActiveItem - 1);
                    CommonConstant.currentChildIdx = (mActiveItem - emptyView);
                }
            }
            scrollToActiveItem(NA);

            handled = true;
            break;
    }

    return handled;
}

private int getMaxItemCount() {
    return ((LinearLayout) getChildAt(0)).getChildCount();
}

private LinearLayout getLinearLayout() {
    return (LinearLayout) getChildAt(0);
}

private void setCurrentItem(int cur) {
    if (cur < 0 + emptyView) {
        mActiveItem = 2;
    } else if (cur > getMaxItemCount() - 1 - emptyView) {
        mActiveItem = getMaxItemCount() - 1 - emptyView;
    } else {
        mActiveItem = cur;
    }
}

/**
 * Scrolls the list view to the currently active child.
 */
private void scrollToActiveItem(int direction) {
    int maxItemCount = getMaxItemCount();
    if (maxItemCount == 0) {
        return;
    }

    int targetItem = Math.min(maxItemCount - 1, mActiveItem);
    targetItem = Math.max(0, targetItem);

    setCurrentItem(targetItem);
    targetItem = mActiveItem;

    // Scroll so that the target child is centered
    View targetView = getLinearLayout().getChildAt(targetItem);
    LinearLayout centerLayout = (LinearLayout) targetView;
    ImageView centerImage = (ImageView) centerLayout.getChildAt(0);
    centerImage.setBackground(mContext.getResources().getDrawable(R.drawable.rectangle_background));

    //get the image to left of the centered image
    if ((targetItem - 1) >= 0) {
        targetLeft = getLinearLayout().getChildAt(targetItem - 1);
        LinearLayout ll = (LinearLayout) targetLeft;
        leftImage = (CircleImageView) ll.getChildAt(0);
        centerImage.setBackground(null);
    }
    //get the image to right of the centered image
    if ((targetItem + 1) < maxItemCount) {
        targetRight = getLinearLayout().getChildAt(targetItem + 1);
        LinearLayout ll = (LinearLayout) targetRight;
        rightImage = (CircleImageView) ll.getChildAt(0);
        centerImage.setBackground(null);
    }
    int targetLeftx = centerLayout.getLeft();
    int childWidth = centerLayout.getRight() - targetLeftx;
    int width = getWidth() - getPaddingLeft() - getPaddingRight();
    int targetScroll = targetLeftx - ((width - childWidth) / 2);

    super.smoothScrollTo(targetScroll, 0);
}

/**
 * Sets the current item and centers it.
 *
 * @param currentItem The new current item.
 */
public void setCurrentItemAndCenter(int currentItem) {
    setCurrentItem(currentItem + emptyView);
    scrollToActiveItem(NA);
}
}

2.in the activity/Fragment
   private void initScrollView() {
    tools_top_scroll = (CenteringHorizontalScrollView) getActivity().findViewById(R.id.horizontalScrollView);
    rl = (LinearLayout) getActivity().findViewById(R.id.tools_top);

    addEmptyChildView();
    addEmptyChildView();
    for (int i = 0; i < 5; i++) {
        setInnerChildView(getChildren().get(i));
    }
    addEmptyChildView();
    addEmptyChildView();
    tools_top_scroll.post(new Runnable()
    {
        @Override
        public void run()
        {
            tools_top_scroll.setCurrentItemAndCenter(CommonConstant.currentChildIdx);
        }
    });
}

private void setInnerChildView(ChildR childR) {
    View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_head_name, null);
    ImageView child_img = (ImageView) view.findViewById(R.id.child_img);
    TextView child_name = (TextView) view.findViewById(R.id.child_name);
    Log.i(TAG, "child name:" + childR.getChild().getC_name());
    child_name.setText(childR.getChild().getC_name());
    rl.addView(view);

}

private void addEmptyChildView() {
    View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_head_name, null);
    view.setVisibility(View.INVISIBLE);
    rl.addView(view);

}

3.in the xml
    <com.shouhu.angel.view.CenteringHorizontalScrollView

    android:id="@+id/horizontalScrollView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@mipmap/tool_f_top_bg"
    android:scrollbars="none">

    <LinearLayout
        android:id="@+id/tools_top"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:gravity="center"
        android:orientation="horizontal">

    </LinearLayout>
</com.shouhu.angel.view.CenteringHorizontalScrollView>


How to integrate a videocall API with Wordpress?

Question: I am having some problem in understand how to integrate a videocall API with a Wordpress site.
I am developing a website which has a "meeting room", this site is built using Wordpress. I am trying to use some videocalls APIs, but couldn't understand the steps in order to integrate with de Worpress. Do I have to build a plugin?
I know some existing plugins for videocall, but they do not have the features I need, therefore I found some videocalls APIs that have the features I need. I also know how to embbed a videocall using iframe.
Thanks in advance.
Answer: If you decide to write your own video communication plugin using WebRTC technology, pay attention to:

select signaling for videochat
creating of Turn server
try this example: https://wordpress.org/plugins/wp-webrtc2/


Jsystem: Thread.sleep() in testcase pauses Monitor

Question: I guess I miss some basical stuff, regadring threads. However, here my problem:
I have a monitor running. On the other hand I have a test. The test does execute a sql query several times, between each execution waiting some ms with Thread.sleep(xy).
for (int i = 0; (i < iterationsteps); i++) {
    rs = myQuery.execute();
    //check if rs is empty
    if (!rs.next()) { Thread.sleep(1000);
    }
}

Now the problem is that due to this Thread.sleep(1000) also the Monitor seems to sleep (at least it does not check). I thought a monitor is a seperate thread.
Comment: If there is only one thread to monitor for the `Monitor`, it won't do anything when the single thread is sleeping. Are there more than one thread?
Answer: I'm not sure what your aiming at with your code, but one thing is for sure myQuery.execute() will block until it is finished.
If you want to do it in the background, you would have to spawn a separate thread for it:
    new Thread() {
        public void run() {
            rs = myQuery.execute();
        }
    }.start();

However, this has many implications. Some are obvious, some are not, and it would definitely require some synchronization code.
Unless you know what you're doing, I would strongly encourage you to go with a single-threaded approach.
Comment: To explain: The test sends a message (e.g. txt file) to the application and then checks processing and if data has been added to the database. The processing time depends on the message and therfore I regurarly check the table for a specified max. time (-> iterationsteps). If there are no data in the table after the specifed time, the test will fail, otherwise going on.
The monitor itself checks another table and it has to warn or even stop test, if this table get a new entry.


Nested loop comparison in Python,Java and C

Question: The following code in python takes very long to run.  (I couldn't wait until the program ended, though my friend told me for him it took 20 minutes.)
But the equivalent code in Java runs in approximately 8 seconds and in C it takes 45 seconds.
I expected Python to be slow but not this much, and in case of C which I expected to be faster than Java was actually slower.  Is the JVM using some loop unrolling technique to achieve this speed?  Is there any reason for Python being so slow?
import time
st=time.time()
for i in xrange(0,100000):
    for j in xrange(0,100000):
        continue;
print "Time taken : ",time.time()-st

Comment: Actually, since the body of the nested loops is empty, I would expect that your C compiler should reduce the time to zero.  Clearly, you haven't turned all the optimizer options on when compiling in C.
Comment: @S.Lott: just tested. GCC already on -O1 removes the loops. Clearly the compiler optimization was not enabled in C, while Java has them always on.
Comment: Are you compiling with optimization?
Comment: @Dummy00001: strictly speaking Java does not do any compiler optimizations. The Java compiler does a relatively "dumb" translation of source code to byte code and applies (almost) no optimizations at that point. Only the JVM does real optimizations in the Java world.
Comment: @Joachim Sauer -- strictly speaking javac does not do any compiler optimizations ... java does real optimizations in the Java world :-)
Answer: Your test is not measuring anything meaningful.
A language's performance in the real world has little to do with how quickly it executes a tight loop.
Frankly, I'm intrigued that C and Java took as long as they did; I would have expected both of their compilers to realize that there was nothing happening inside the inner loop, and have optimized both of them away into nonexistence (and 0 seconds).
Python, on the other hand, is still interpreted (I could be wrong about this). In any case, it looks like the outer loop is needing to construct 100,000 xrange objects on which to run the empty inner loop, and that's unlikely to be optimized away.
So all you're really measuring is various compilers' ability to see through the fact that no real computing work is being done.
Comment: +1: Python is generally interpreted.  There are some Python-to-C tools that would lead to more C-like performance.
Comment: @Carl: C by default has optimizations disabled. Java has them by default enabled. E.g. GCC makes such loops a nop already on -O1.
Comment: @Carl
Actually i was running a program in python to solve a puzzle when i saw how slow loops in python is.The prog took 100sec in python to show result while in C it was 1-2 sec.Thats the reason why i tried the above code in different languages.
Comment: @Emil: If you're solving Project Euler problems with nested loops like the one shown above, you're doing it wrong.  Project Euler problems require careful design, not compiler optimizations.
Answer: The lesson is: Performance is never what you expect. Therefore, always measure, never believe.
Some reasons why you might see these numbers (and from the first sentence, some of these might be completely wrong):
C is compiled for an "i586" processor (also called Pentium). That CPU was sold from 1993 to about 2000. Have you seen one lately? Guess not. So the C code isn't really optimized for what your CPU can do (or to put it another way around: Today's CPUs try very hard to be a fast Pentium CPU). Java, OTOH, is compiled for your CPU as the code is loaded. It can pull some tricks that C simply can't. The price is that the C program starts in 15ms while the Java program needs 4 Seconds.
Python has no JIT (just in time compiler), yet. All code is converted into bytecode which is then interpreted. This means the loop above is turned into a dozen bytecode instructions which are then interpreted by a C program. That just takes time. Python is not meant for huge loops, it's meant for smart algorithms which you simply can't express in any other language (at least not with the same amount of code and readability).
So just as it doesn't make sense to go shopping with a 18t truck (you can transport anything but you won't find a space to park it), chose your programming language according to the problem you need to solve. It has to be small&fast? C. Just fast? Java. Flexible? Python. Flexible&Fast: Python with a helper library in C (like NumPy).
Comment: That reminds me of the oft-quoted saying, "There are lies, damned lies, and statistics." In this case you could say, "There are lies, damned lies, and benchmarks." -- That's one thing I learned a few years ago - most benchmarks, unless they're measuring on a useful task, are almost useless.
Comment: Actually my C compiler (gcc 4.2 + llvm) compiles for a processor called x86_64 by default.  The processor architecture thing is a red herring.  The real difference between the C figure and the Java figure is - as others have said - different optimisation levels.
Answer:
Is there any reason for Python being so slow?

Yes.
But what does it matter?  You've created 100,000 xrange objects.  Why?  What does that matter?  What is your real question on performance?  What algorithm do you actually have that's actually too slow?

for i in xrange(0,100000): # Creates one xrange object
    for j in xrange(0,100000): # Creates a fresh xrange object each time through the loop

Comment: @Emil: What does "u" mean?  What does "i" mean?  Please use English.  Not all of us read whatever shorthand you're using.
Answer: for i in xrange(0, 10000):
    for j in xrange(0, 10000):
        pass

or
for i in xrange(0, 100000000):
    pass

Python 2.6.5 - Time taken : 8.50866484642
PyPy 1.3 - Time taken : 1.55999398232
reason of slow work not in creation of xrange objects
Comment: so what do you think could be the problem?
Comment: I think there is no problem, Python is "high-level programming language" like Ruby, php, or Perl. Python faster then php ... and if you want to use it in web - it's a right way, but if want use it to write OS - it's bad idea
Comment: @nazca: I found your test interesting but it would be more useful if you could quote times not just for two Python environments but for both tests! There should be 4 different times to see here. I find it hard to believe there would be NO difference between the single and nested loops.
Comment: @Carl Smotricz: This time is the same for two tests... because the creation time of 10k xrange objects ~0,04s (on my machine) ...in this test difference between the single and nested loop is 0,5 percent
Answer: gcc 4.2 with the -O1 flag or higher optimize away the loop and the program takes 1 milli second to execute.
This benchmark is not very representative as it is very far from any real world use.
You're doing a nested loop for a reason, and you never leave it empty.
Python doesn't optimize away the loop, although I see no technical reason why it couldn't.
Python is slower than C because it's further from the machine language. xrange is a nice abstraction but it adds a heavy layer of machine code compared to a simple C loop.
C source:
int main( void ){
        int i, j;
        for (i=0;i<100000;i++){
                for (j=0;j<100000;j++){
                        continue;
                }
        }
        return 0;
}

Comment: The technical reason that it doesn't is simply the fact that python programs are executed/compiled on a line by line basis. Of course when unladen swallow (http://code.google.com/p/unladen-swallow/) is migrated in, it's *probable* that the JIT compilation process will actually optimize that away.
Answer: A good compiler would optimise away the loop.
Assuming the loop isn't optimised away, I'd expect Python to be something like 100 times slower than the C version


Mathematical induction used on Fibonacci Sequence

Question: I have no clue how to go about doing this question using induction. It states that the Fibonacci sequence is defined as:
F0 = 0
F1 = 1
Fn = Fn-2 + Fn-1 for  n>=2
Let S(n) = Fo + F1 + F2 +...+ Fn. Prove that S(n)= Fn+2 -1
Answer: Let us prove that
$$S(n)=\sum_{i=0}^{n}F_i=F_{n+2}-1$$
for all non-negative integers $n$ by induction.
For $n=0$, it holds trivially since $F_2=1$.
Assume that it holds for $n=k$, i.e.
$$S(k)=\sum_{i=0}^{k}F_i=F_{k+2}-1.$$
Then, we have
$$\begin{align}S(k+1)&=\sum_{i=0}^{k+1}F_i\\&=F_{k+1}+\sum_{i=0}^{k}F_k\\&=F_{k+1}+F_{k+2}-1\\&=F_{k+3}-1\\&=F_{(k+1)+2}-1.\end{align}$$
Hence, it holds for $n=k+1$.
Hence, $S(n)=\sum_{i=0}^{n}F_i=F_{n+2}-1$ for all non-negative integers $n$. Q.E.D.
Answer: Inductive step:
If $S(n)=F_0 + F_1 + \cdots + F_n=F_{n+2}-1$ then $S(n+1)=S(n)+F_{n+1}=F_{n+2} + F_{n+1} -1= F_{n+3}-1$


HTTP POST with axios: net::ERR_EMPTY_RESPONSE

Question: I am trying to make a HTTP Post request through axios:
    const onSubmit = (values) => {
      console.log("submit", values);
      // ctx.$i18n.locale = "en";
      axios.post("http://192.168.3.2:8081", { // HTTP POST
        name: state.name,
        age: state.age,
        message: state.message,
        canvas: state.canvas,
      });
    };

And my backend server is like (Python):
class S(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Content-type', 'text/html')
        self.end_headers()
    def do_OPTIONS(self):
        self.send_response(200, "ok")
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        # self.send_header("Access-Control-Allow-Headers", "X-Requested-With")
    def do_GET(self):
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        self._set_response()
        self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))
    def do_POST(self):
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        post_data = self.rfile.read(content_length) # <--- Gets the data itself
        logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",str(self.path), str(self.headers), post_data.decode('utf-8'))
        self._set_response()
        self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
        f = open(json.loads(post_data.decode('utf-8'))["name"]+ "-" + date.today().strftime("%m-%d-%Y") + ".txt", "w")
        f.write(post_data.decode('utf-8'))
        f.close()

I tested my backend server with Postman and it works fine, but it keeps returning this error in browser if I tried it with axios
POST http://192.168.3.2:8081/ net::ERR_EMPTY_RESPONSE
Uncaught (in promise) Error: Network Error
    at createError (createError.js?2d83:16)
    at XMLHttpRequest.handleError (xhr.js?b50d:84)

BTW: in server loggings, it seems like the server never receives a POST request, but only an OPTIONS request.
Answer: the request created by axios is a promise
you need to chain a .then to it for the request to be actually sent
otherwise use the keyword async / await in a newer browser
there are some examples in the README file of axios: https://github.com/axios/axios


What is the cardinality of the equivalence relation $R$?

Question: An equivalent relation $R$ has three equivalent classes of sizes $8,10,12$.
Then the cardinality of $R$ is ?

Any approach for such questions ?
Comment: The equivalence classes are pairwise disjoint.
Answer: Within the equivalence class, everyone is related to each other including itself. Also, if they are not in the same equivalent class, they are not related.
Hence $$8^2+10^2+12^2$$


How do you make sortable tables with a pager with data from a custom table?

Question: For Drupal 6 you could do something like this:
$header = array(
  array('data' => t('Order id'), 'field' => 'order_id'),
  ...
  array('data' => t('Transaction time'), 'field' => 'payment_time', 'sort' => 'desc'),
);
$sql = "...";
$sql .= tablesort_sql($header);
$limit = 25;
$result = pager_query($sql, $limit);
...

I took a look and for drupal 7 and both pager_query and tablesort_sql is now gone. It seems that instead the PagerDefault class can be used to create a pager query using DBTNG. I wasn't able to find any clues on a simple API for attaching a sortable table to the query like it is done in Drupal 6.
So how do you create a sortable table with a pager pulling data from a custom table?
Answer: You use the so called extenders.  In your case, the code would be similar to the following one.
$header = array(
  array('data' => t('Order id'), 'field' => 'order_id'),
  // ...
  array('data' => t('Transaction time'), 'field' => 'payment_time', 'sort' => 'desc'),
);

// Initialize $query with db_select().
$query = db_select('your table name');

// Add the fields you need to query.
// ...

// Add the table sort extender.
$query = $query->extend('TableSort')->orderByHeader($header);

// Add the pager.
$query = $query->extend('PagerDefault')->limit(25);
$result = $query->execute();

See HowTo: Convert a module to DBTNG, Dynamic queries: Table sorting and Extenders.
Comment: Don't forget to add the actual pager in your output:
// Build table.
  $output = theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('No strings available.')));
  // Add the pager.
  $output .= theme('pager');
Answer: Use the TableSort and PagerDefault extenders.
$query = db_select('node', 'n');
$query->fields('n', array('nid', 'title', 'status'));

$table_sort = $query->extend('TableSort') // Add table sort extender.
  ->orderByHeader($header); // Add order by headers.

$pager = $table_sort->extend('PagerDefault')
  ->limit(5); // 5 rows per page.

$result = $pager->execute();

Answer: Use the DataTables module.

The DataTables module integrates the jQuery plugin DataTables into Drupal as a views style and a callable theme function. DataTables lets you add dynamic features to tables, including:

Variable length pagination
On-the-fly filtering
Sorting with data type detection
Smart handling of column widths
Themeable by CSS
And more to come...
Comment: I'd advise against adding a module to do something that's part of the DB API and can be done with about 50 or fewer lines of custom code.
Answer: You can just include the same Drupal 6 tablesort_sql in your code and it works fine.
For pager:
$count = <Total No. of Table rows>

$sql = "...";
$sql .= tablesort_sql($header);
$limit = 25; //Pager limit

$results = db_query( $sql );
$rows = array();
//Loop through the result.
while ( $row = $results->fetchAssoc() ) {
$rows = <Get your array values for Table row>
}
$current_page = pager_default_initialize($count, $limit);
$chunks = array_chunk($rows,$limit, TRUE);
$output = theme( 'table', array( 'header' => $headers, 'rows' => $chunks[$current_page] ) );
$output .= theme( 'pager', array('quantity',$count ) );
print $output;


Difference Between Differentiation on Time vs Position

Question: I'm hoping somebody could help me understand the difference between the following:
$$∂_tc(x,t)$$
$$∂_xc(x,t)$$
My understanding is the the top derivative would be something like velocity but what would that make the bottom derivative?
Thanks.
Comment: What is $c$ modeling? The interpretation depends on what $c$ represents.
Comment: c is just the concentration of a molecule. So these describe the movement of the molecule as a function of position x and time t
Answer: $∂_tc(x,t)$ represents the rate of change in $c$ with respect to $t$ (temperature) at a fixed $x$ (position), whereas $∂_xc(x,t)$ represents the rate of change in n $c$ with respect to $x$ (position) at a fixed $t$ (time).
Here is an example:
Consider a thin metal pipe filled with an aqueous solution being heated at only one end. Let $C(x, \, y)$ denote the concentration of a reactive solute $x$ meters from the beginning of the pipe at time $t$.
Here, $∂_tC(x,t)$ represents the rate of change of concentration of the solute at a specific fixed position from the beginning of the pipe, at any time $t$.
On the other hand, $∂_xC(x,t)$ represents the rate of change of concentration of the  solute at a specific fixed time at any position $x$.
Does this help?
Comment: I edited all my temperatures into "time" :)
Comment: Sorry should have made that clearer. t is time and x is position. Could you give me an example that helps me understand what a change in time at a fixed position would be like? I can understand how velocity would be described by change in position over a fixed time. But what about the former?
Comment: Ok, I will edit my answer.
Comment: This is just what I'm looking for, but what about time not temperature?
Comment: Beautiful, this makes sense. Appreciate the help.
Comment: No problem. Happy to help!


Why do I get 'access denied' when viewing nodes?

Question: I'm testing my website and I have to cope with a strange problem. Although every role has the permission "View published content", only the administrator can access nodes: anonymous users and authenticated users can't. The same problem occurs with adding content. I've tried clearing caches, saving the permissions again and rebuilding the permissions, but nothing helps. I'm not using any modules that control node access either...
How can I solve this?
Comment: Have you tried rebuilding the permissions?
Comment: @MF82: I did, but it didn't fix the problem either...
Comment: You have any additional modules that control node access? Like nodeaccess, entity-access, content access or simple access that might be configured wrong?
Comment: @Neograph734: No, I'm only using Field Permissions, but I don't think that has anything to do with this...
Comment: As long you didn't disable the body field ;) You can try turning it off and see if it helps?
Comment: @Neograph734: Nope, it didn't help... :(
Comment: Just to be sure, but have you cleared the cache after disabling the module? Does example.com/admin/reports/fields/permissions look good? (With field permissions enabled) If there is noting there, I don't know either...
Comment: @Neograph734: Yes, I've cleared caches after disabling the Field Permissions module, but nothing happened. Also, no strange things are to be seen in the reports (almost every field is public). Anyway, I hadn't discovered the reports for fields yet, so your help was useful in a sense. ;)
Answer: Things to try when you get inexplicable "Access denied" when non-admins try to view nodes and you're sure every role has the permission "View published content":

Clear all caches. Note that you need to both clear your browser's cache and the Drupal cache on the server. To clear your browser's cache, hold down Shift and reload the page. To clear the server cache, navigate to Administration → Configuration → Development → Performance → Clear all caches. If you use Views, clear Views' cache: Administration → Structure → Views → Settings Advanced → Clear Views' cache. If you've got drush installed (always a good thing to have around), a quick way to clean all caches on the server is drush cc all.
Rebuild permissions: append the path: admin/reports/status/rebuild to your site's base URL, or navigate to Administration → Reports → Status report and look for the link "Rebuild permissions".
Repair the Sessions table: Use phpMyAdmin or a similar tool, choose your Drupal database, check the box next to the {sessions} table, and find the "With selected" drop-down near the bottom of the page. Choose "Repair table".
If you've just installed a new module, make sure that you've executed a database update. To execute a database update, append the path update.php to you site's base URL.  (There will be a link to this page on the Status reports page if Drupal thinks you need to do it.)
Use the DNA module (part of Devel) to debug node access problems. DNA will display a block telling you exactly what permissions are enforced and where they come from.  Remember to give give the anonymous and authenticated user roles permission to "Access developer information" to use DNA to debug access problems for these roles. Report your findings here by editing your question if you don't understand the output of DNA.
If none of the above works, start disabling modules to see if one of those causes the problem.  Remember to clear caches after disabling a module.  You may also want to rebuild permissions (see pt. 2 above) after disabling a module, even if the module don't tell you to do it.
Answer: Something very very silly may bring you at this  'access denied'.
There's a web server serving both http and https (without a proper redirect from "http" > "https").  In this scenario, it may happen that you login at "http" and the access content at "https". From the Drupal point of view, two different sessions. You will get thus "Access denied" if the content you want to read is not for anonymous guests. Again, it is very very silly, but it happens.


Convertendo camel case para underscore em Ruby

Question: Existe uma função pronta que converte Strings em camel case para strings separadas por underscores?
Gostaria que algo assim:
"CamelCaseString".to_underscore

retornasse "camel_case_string".
Answer: Rails' ActiveSupport
adiciona underscore a classe String usando esse código:
class String
  def underscore
    self.gsub(/::/, '/').
    gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
    gsub(/([a-z\d])([A-Z])/,'\1_\2').
    tr("-", "_").
    downcase
  end
end

Pronto:
"CamelCase".underscore
=> "camel_case"


Remove duplicates when converting multiple rows into CSV using SQL

Question: I am creating a view where I need to pull all the rows of one column and convert into CSV format.
SELECT
    SUBSTRING((SELECT ',' + CAST(s.marketConfigId AS varchar(MAX))
               FROM [Metric].[MetricGoalDefMarket] s
               WHERE [metricGoalDefId]=21
               ORDER BY s.marketConfigId
               FOR XML PATH('')),2,200000) AS marketConfigID

Using above query can create a CSV format but it is also displaying duplicates. When you run the above query it is displaying the output as
**marketConfigID**
751,751,742,751,751,784,1850,737

How can I remove duplicates?
PS: As I am creating a view, I don't want to use functions as I see using dbo.DistinctList from here can remove duplicates
Answer: It seems distinct would work :
SELECT SUBSTRING((SELECT DISTINCT ',' + CAST(s.marketConfigId AS varchar(MAX))
                  FROM [Metric].[MetricGoalDefMarket] s
                  WHERE [metricGoalDefId]=21
                  ORDER BY s.marketConfigId
                  FOR XML PATH('')
                  ), 2,200000) AS marketConfigID

You don't need to use substring() you can use stuff() instead :
SELECT STUFF ( (SELECT DISTINCT ',' + CAST(s.marketConfigId AS varchar(MAX))
                FROM [Metric].[MetricGoalDefMarket] s
                WHERE [metricGoalDefId]=21
                FOR XML PATH('')
                ), 1, 1, ''
             ) AS marketConfigID

Comment: I already tried that. It gives me an error showing "ORDER BY items must appear in the select list if SELECT DISTINCT is specified." Not sure where I could use, as I already used ORDER BY in the query
Comment: Thank for your answer. 2nd query works but how can I put ORDER BY in there. It throws me an error if I put ORDER BY after where clause
Answer: Have you tried DISTINCT?
Edit: Apologies think I misread your query. I think you want to fetch the marketConfigIds using a sub-select query (applying DISTINCT), rather than at the outer level like I did below
SELECT DISTINCT
    SUBSTRING((SELECT ',' + CAST(s.marketConfigId AS varchar(MAX))
               FROM [Metric].[MetricGoalDefMarket] s
               WHERE [metricGoalDefId]=21
               ORDER BY s.marketConfigId
               FOR XML PATH('')),2,200000) AS marketConfigID

Comment: Shouldn't that DISTINCT go inside the subquery being XMLPath'd?


What does `extends to' mean in this context?

Question: In the following statement, I don't understand what `extends to' should mean.
Every continuous map $S^1\to X$ extends to a continuous map  $D^2\to X$.
Any ideas?
Comment: There's an embedding $S^1 \to D^2$ given by considering $S^1$ as the boundary of $D^2$, and extension means there's a continuous map $D^2 \to X$ which restricts to any given continuous map $S^1 \to X$.
Comment: Given three sets $A,B,C$ such that $A \subset B$, and given a function $f : A \to C$, an *extension of $f$ to $B$* is a function $F : B \to C$ such that for all $x \in A$ we have $f(x)=F(x)$. In your example, $A=S^1$, $B=D^2$, $C=X$.
Answer: There is an inclusion map $\iota:S^1\to D_2$ embedding $S^1$
as the "boundary" of $D^2$. Then the continuous $f:S^1\to X$
extends to the continuous $g:D^2\to X$ if $f=g\circ \iota$.
Answer: Call the first map $f$ and the second  $g$.  Then $g|_ {S^1}=f$.


Dynamically adding new fields to a form in Django

Question: I want to let my users write content and I want them to specify how many sections with its titles they want to have. I already created a little Javascript function to insert the new elements into the existing form which will be submitted. This currently looks like this:
openTextarea.js
var i = 1;

function opentextarea() {
  "use strict";
  var hr = document.createElement('hr');
  var title = document.createElement('input');
  title.type = 'text';
  title.name = 'title_'+i;
  title.placeholder = 'Your section title!';
  title.className = 'form-control';
  var input = document.createElement('textarea');
  input.name = 'section_'+i;
  input.className = 'tiny-mce-init';
  var button = document.createElement('button');
  var newSection = document.getElementById('newSection');
  var form = document.getElementById('guide_form');
  form.appendChild(hr);
  form.appendChild(title);
  form.appendChild(input);
  loadTinyMCEEditor();
  i++;
}

template
{% extends "base.html" %}

{% load staticfiles %}
{% block body %}

  <form id="guide_form" class="form-horizontal" method="POST" action="{{ request.get_full_path }}"> {% csrf_token %}

    <fieldset>
      {% if form.title.errors %}

{{ field }}

              {% for error in form.title.errors %}{{ error }}{% endfor %}

      {% else %}

{{ form.title }}

      {% endif %}

      {% if form.public.errors %}

Check, if you want to make your guide public {{ field }}

              {% for error in form.public.errors %}{{ error }}{% endfor %}

      {% else %}

Check, if you want to make your guide public {{ form.public }}

      {% endif %}

    Neutral cards

    {% for card in form.cards %}
      {{ card }}
    {% endfor %}

    </fieldset>
  </form>

<button class="btn btn-primary" type="button"
  onclick="opentextarea();">
  Add Section!
</button>

  <button type="submit" form="guide_form" class="btn btn-success">Submit</button>

{% endblock %}

When I inspect the element, the new section appears in the form.

Apparently the new sections is not in the form.cleaned_data because when I print it out, I just receive the fields I initially created with my form:
class CreateGuide(FormView):
    template_name = 'hsguides/guide_create.html'
    form_class = GuideForm
    success_url = '/guides/search-guide/'

    def get_form_kwargs(self, *args, **kwargs):
        form_kwargs = super(CreateGuide, self).get_form_kwargs(**kwargs)
        form_kwargs['hero'] = self.kwargs['hero']
        return form_kwargs

    def form_valid(self, form, *args, **kwargs):
        # TODO
        # - check if cards are actually from selected class...
        # - implement sections
        form.instance.author = self.request.user
        form.instance.hero = Hero.objects.get(name=self.kwargs['hero'])
        dust = 0
        for card in form.cleaned_data['cards']:
            dust += Card.objects.get(id=card.id).dust

        for foo in form.cleaned_data:
            print(foo)

        form.instance.dust = dust
        form.save()
        return super(CreateGuide, self).form_valid(form)

The results are

cards
public
title

Which makes sense because my form looks like this
class GuideForm(BootstrapModelForm):
    class Meta:
        model = Guide
        exclude = ('author', 'created', 'modified', 'hero', 'dust', 'rating',)

    def __init__(self, *args, **kwargs):
        hero = kwargs.pop('hero', None)
        super(GuideForm, self).__init__(*args, **kwargs)
        if hero:
            self.fields['cards'].queryset = Card.objects.filter(Q(card_class='neutral') |
                                                                Q(card_class=hero))
        self.fields['title'].widget.attrs['placeholder'] = 'Title of your awesome guide!'
        self.fields['public'].widget.attrs.update({'class': 'checkbox'})

How can one dynamically add new elements into a form in django? Any help or suggestions are highly appreciated!
Answer: You can add them after calling super.
class GuideForm(BootstrapModelForm):
    class Meta:
        model = Guide
        exclude = ('author', 'created', 'modified', 'hero', 'dust', 'rating',)

    def __init__(self, *args, **kwargs):
        hero = kwargs.pop('hero', None)
        super(GuideForm, self).__init__(*args, **kwargs)

        #  add your fields here
        self.fields['title_1'] = forms.CharField()

You  can check out this good example https://stackoverflow.com/a/6142749/2698552
Comment: Well since your answer is the only one you are lucky to get the bounty :P I saw this question you referenced in your post before I asked my question but couldn't do anything with it. The reason I used my reputation for the question was, so people could help me with the problem on a more specific level. But what ever.. Here is the bounty :)


Installed fabric but still getting ' no module fabric.api'

Question: Currently, I am in a strange situation. I created a virtual environment and installed fabric via command
<code>pip install fabric
</code>
The installation is successfully complete but when I import the module, it shows me 'no module fabric.api'
Answer: Solved the problem by running below command in the virtual environment.

pip install fabric

instead of

sudo pip install fabric

I didn't get the reason but its just working fine now.


Help plugging Electric-acoustic into PC?

Question: Trying to plug my acoustic-electric bass into my PC.  I've never done this before, so pardon my newb.
PC picks up no audio, not sure what's up.
I bought this plug.  Takes two monos to a stereo.  One mono end just dangles when I plug it into my bass.

Here's my electronics.  I turned the tuner on just to show that the battery isn't totally dead.  Not sure how to make sure that this is working.

I've tried plugging both the red and white end into the guitar.  Tried changing various input settings on my PC.  I use a headset (phones+mic) for work and it's usually fine.  I also sometimes use just a mic, and that usually works fine.
I'm just at a loss of how to continue troubleshooting it.  Am I doing something obviously incorrect?  Does anyone successfully use a similar setup?  How can I troubleshoot by acoustic electric bass pipe to my PC mic-in?
UPDATE: To be clear, the "duplicate" questions all seem to suggest that something like my setup should "just work".  However, my setup doesn't work, and the linked questions don't address this problem at all.  My question isn't "how to plug a guitar into a PC", it is "why doesn't this particular setup work?"
Comment: See https://superuser.com/questions/1568508/pc-uses-speaker-of-headset-instead-of-microphone/1568512#1568512 and
https://sound.stackexchange.com/questions/48560/recording-audio-through-3-5mm-jack-on-a-mac both of which have TRS/TRRS plug guides. tbh, your question does boil down to "how to plug a guitar into a PC" because the first thing you need to know is "which plug to use".
Comment: Actually related: https://music.stackexchange.com/questions/118016/can-i-plug-in-an-electrified-acoustic-guitar-in-a-line-level-input. The most probable reason is that the preamp in guitar isn't compatible with the input jack despite what others believe. The other possibility is that if you're plugging the cable to a TRRS headset jack, it's the wrong connector and the guitar is actually connected to headphone output.
Comment: I do disagree with the dupes linked, though, as they start 'one step past' this requirement & assume the right plugs.
Comment: A mic on a TRS is an unusual beast in pro audio terms. They just don't do that, for a myriad reasons. 'Computer mics' [cheap, high impedance condensers] can be made like that [though the vast majority these days sit on TRRS for 'PC' compatibility as headset jacks are now ubiquitous. They need a couple of volts from a computer's mic input to make them work. & also, a TRS on a computer audio input is rare, unless it's a dedicated stereo line-in.
Comment: Not really.... [This answer to that question](https://music.stackexchange.com/a/35946/52004) says """If you just want to record audio out from your keyboard to your PC then you should be able to do audio out to audio in""" which suggests that my general process should work.... but it doesn't.  I'm just not sure what variables to check....
Comment: None of the linked questions help at all.  Can someone recommend a forum where questions like this would be on-topic?
Comment: Try changing the title of your question. I see your update clarifying your "question isn't 'how to plug a guitar into a PC'", but your title reads that way.
Comment: While this is not exactly perfect, it should work as your instrument does have a preamp. How do you check if you get audio into your PC?
Comment: @Tetsujin, I don't think it's a pinout problem.  My mic is TRS (which I guess implies stereo, but the mic only has the one membrane, I'm pretty sure.)  The guitar is basically a mic, right?  Maybe the 0V on the one pin is causing problems.... /shrug
Comment: The output from guitar is quite different from a mic. If the preamp has low output impedance it should be similar to line output, but nobody says it has.
Answer: You have a couple of issues which are not really music related, but that you need to get right for this to work:

Do not use that cable - use a standard mono - mono guitar lead. You don't know what is happening with respect to connections.

Use an audio interface of some kind with an input suitable for guitar. 3.5mm inputs on PCs are rarely likely to work with guitars.
Answer: If you are plugging this into a "headset" jack on your PC, that's the problem.  You have a Tip-Ring-Sleeve connector which only connects to the left and right headphone channels.  You probably need a Tip-Ring-Ring-Sleeve, which combines stereo headphones and a mono microphone input:

You may still not get great results without an audio interface intended for music recording, but having active electronics on your instrument should help as the bass output will be buffered and less sensitive to the impedance of the microphone input.


Editing canonical links without a module, contained in $head?

Question: I've not been using Drupal for long (< 3 weeks) but have good knowledge of standard PHP, so I really don't know the 'Drupal' way of doing things yet.
What I'm trying to do is edit the canonical tag for a mobile site. The current path is realtive, however I need it to be absolute, and link to the desktop version of the site.
As far as I can tell the current implementation is not using any module to insert the canonical tag.
By looking at the source code of the rendered page the code appears to be contained in the $head variable which is in html.tpl.php as below
<head profile="<?php print $grddl_profile; ?>">
<?php print $head; ?>
<title><?php print $variables['field_meta_title']; ?></title>

I've come across a couple of pages like this one that mention things like template_process_html, drupal_get_html_head() and hook_html_head_alter() as relevant functions, but in that example the request is to remove the canonical tags, not to edit them.
I wouldn't mind using a module (providing it would allow me to change the link from www.mysite.com... to m.mysite.com...) but I would need to remove the current canonical tags which comes back to my orignial issue of not being able to find where it is.
Answer: You need the Meta Tags module.
After you activate it, go to /admin/config/search/metatags/config/global and, under advanced, you can change the default canonical link.
Look at the path patterns used for PathAuto and prefix them with the desired base url.
Comment: I did come across that module, which looks useful, but adding that would then give me 2 canonical links as I'd still be left with the one I can't find, which I presume is a bad idea.
Comment: Drupal does not by itself provide a canonical link. What theme are you using?
Comment: The theme is a custom one. It may or may not have been based on another, I don't know as I've only just started working this site. Could this have been added by the theme then?
Comment: It could have been added by any module calling [drupal_add_html_head](http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_html_head/7)  or theme calling [hook_html_head_alter](http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_html_head_alter/7). I would suggest you search your code base for the word "contextual" and see where this is coming from.


Getting played note frequency using Unity and FFT

Question: I am working on a project using the Unity game engine, The idea of the project is that the user plays a note on a guitar (and other instruments) and the app should display the note frequency that the user played, I have found this block of code that uses Unity API to get the spectrum data based on FFT algorithm:
<code> using UnityEngine;

 public class AudioMeasureCS : MonoBehaviour
 {
     public float RmsValue;
     public float DbValue;
     public float PitchValue;

     private const int QSamples = 1024;
     private const float RefValue = 0.1f;
     private const float Threshold = 0.02f;

     float[] _samples;
     private float[] _spectrum;
     private float _fSample;

     void Start()
     {
         _samples = new float[QSamples];
         _spectrum = new float[QSamples];
         _fSample = AudioSettings.outputSampleRate;
     }

     void Update()
     {
         AnalyzeSound();
     }

     void AnalyzeSound()
     {

         GetComponent<AudioSource>().GetSpectrumData(_spectrum, 0, FFTWindow.BlackmanHarris);
         float maxV = 0;
         var maxN = 0;
         for (i = 0; i < QSamples; i++)
         { // find max
             if (!(_spectrum[i] > maxV) || !(_spectrum[i] > Threshold))
                 continue;

             maxV = _spectrum[i];
             maxN = i; // maxN is the index of max
         }
         float freqN = maxN; // pass the index to a float variable
         if (maxN > 0 && maxN < QSamples - 1)
         { // interpolate index using neighbours
             var dL = _spectrum[maxN - 1] / _spectrum[maxN]; //This line 1
             var dR = _spectrum[maxN + 1] / _spectrum[maxN]; //This line 2
             freqN += 0.5f * (dR * dR - dL * dL); //This line 3
         }
         PitchValue = freqN * (_fSample / 2) / QSamples; // convert index to frequency //This line 4
      }
  }
</code>
I have tested this code and it seems it works well only if I play a pure sine wave or pure note (no harmonics).
I have a few questions:

I don't understand the logic in the last 4 lines (theoretically) in the code which is critical, I understand that we searched the max amplitude index (maxN) but why do we need the next element and the previous element? and why it is divided by the value at index maxN, I will appreciate it if some one could give an explanation of the logic in the code.
The code above has some issue, most of the time it shows the frequency of the harmonics and not the fundamental, for instance, if I play a string with frequency 65HZ the code returns 130 or 195, What I can do to get the fundamental frequency or all the harmonics frequencies including the fundamental frequency
Comment: There is a DSP stack where you might get better answers.
Comment: I fear the [missing fundamental](https://en.wikipedia.org/wiki/Missing_fundamental) will foil your plans of obtaining the fundamental frequency.
Comment: I spent a couple of weeks trying to find heuristics and failed hard. I decided to just show the whole spectrogram and draw lines where the notes should be instead, much easier. I noticed that the fundamental often did not have the largest amplitude and that sometimes I got a large response for frequencies lower than the expected fundamental (perhaps some weird resonance). So I think if you want to go this route you need machine learning or a very very good heuristic (I even tried optimizing for harmonics and which strings where physically possible to play simultaneously and it still was crap).
Comment: Four methods with optional improvements are demonstrated here, with "pros" and "cons" for each method: https://gist.github.com/endolith/255291   (1) count distance between zero-crossings, (2) find peaks in FFT, optionally interpolating between bins for more accuracy, (3) find peak in autocorrelation, (4) find peaks in harmonic product spectrum
Answer: The FFT gives the amplitudes for a finite set of frequency, it is digitised. The first three lines you wonder about are a simple interpolation to improve the resolution on the frequency: it tries to see if the peak you detect is more toward the low frequencies or the high frequencies.
The last line you wonder is the standard way to compute the frequencies from a FFT: a set from 0Hz to Nyquist (fsample/2) with a number of different frequencies equals to the number of input samples.
In order to detect the fundamental and not the harmonics, you can try to weight a bit your FFT, for instance by dividing each element of your FFT by its index (equivalent to 1/f normalisation).
(Sorry, on a phone hence a bit limited, will expand if needed, hope it helps already !)
Comment: To understand this interpolation, i suggest to draw a curve with a maximum somewhere, on paper. Then, mark points at fixed x-interval (if you have a good on paper just use that) on that curve, that's the FFT estimation. Your points won't necessarily fall on the true maximum, but a bit next to it probably. The question is where is the true max compared to the point one. For that, the code you give just compare the neighbors and estimate the true max from that. (Would be easier with a blackboard ;))
Comment: Hi [Tom](https://music.stackexchange.com/users/69662/tom), thank you for the answer it is already useful, Yes please I would be very happy if you could expand more about this subject with more details in your free time, I was searching for this a lot.
 including materials/resources is also welcome, thanks in advance
Comment: @WhiteNight the subject is very broad, is there any specific part that need to be expanded or the whole? Note that this forum is focused on music practice and theory. Imo this falls into practice because that close to the way I'm doing music but I'm sure some will it as outside of the scope ;)
Comment: You are right :), I am having difficulty understanding the samples array that the FFT collects, I don't know what kind of manipulation/interpolation to do to get the results I desire, but I know the array contains amplitudes values for frequency ranges depends on my resolution (bin) size, for instance, an array of 1024 samples at index 0 will have an amplitude of frequency range 0-43.06 and next index will have the amplitude of the frequency 43.06 - 86.12, and so on, but I don't understand the interpolation part, is it a mathematical term? Is it integral?
Comment: No, it simply computes how big are the neighbouring bins compared to the max and shift the max toward the highest neighbor. Imagine you have a max, and it's t left neighbor is very close to that max (but not the right). Then the true maximum is between the max you found and the next bin to the left. This is just a simple way to estimate the true position of the maximum of a digitised signal.
Comment: thank you so much now I understand the code, take me a while :). Could you explain in more detail how to handle the harmonics? it will be perfect
Answer: Four common frequency estimation i.e. pitch detection methods with optional improvements are demonstrated here, with "pros" and "cons" for each method, along with links for more reading: https://gist.github.com/endolith/255291

(1) find distance between zero-crossings
(2) find peaks in FFT, optionally interpolating between bins for more accuracy
(3) find peak(s) in autocorrelation
(4) find peaks in harmonic product spectrum ("HPS")

The examples posted in the gist above are in Python+Numpy+Scipy, and you'll learn more about it by tweaking the Python code. I won't try to translate that for Unity.
Real learning happens by doing, not by reading. It's the same in music, but also in mathematics and programming, and learning this by using Python is a good choice. Python has all the needed signal processing and audio i/o handling tools like FFT, (auto)correlation, windowing, WAV reading/writing, live audio streaming, etc. readily available in library packages you can install with the pip package manager. When you've learned how it works, you have a much better chance to make it work in Unity.
I've tried using the Python methods in my own music-making, and they do work. The FFT peaks + parabolic interpolation method is very accurate, down to at least a 10th of a cent, i.e. 1/1000th of a semitone, and it has given the same numeric results as the Tuner plugin in Ableton Live.
In any case, you'll have to adjust, mix and match several different methods for your specific application needs. For example, how to deal with noise and how to set a threshold between note and non-note. "Note onset detection" could be a possible additional search term.


How to create a linux shared library including all binary dependencies into a single so file?

Question: I'm able to create a shared library in linux libMySharedLibrary.so.
But I'm including a bunch of header files referencing other libraries when I compile. I want to link all the binary code from these included header files so I can distribute my shared library in one .so file.
I'm using gcc to compile. Below the command line:
gcc -I$JAVA_8_HOME/include/ -I$JAVA_8_HOME/include/linux/ -I./include/ -I. -fPIC -o libMyLibrary.so -shared com__MyLibrary.c
The header files are inside ./include. I need to link the generated libMyLibrary.so with the binaries of the header files inside ./include.
How?
Comment: If you refuse to let your shared library be dependent on any others why
do you expect anybody else to be willing to link against *your* shared library?
Comment: Please **edit your question** to explain ***why*** you want to do that. Smells badly as some [XY problem](http://xyproblem.info). So you should give your motivation and context.
Comment: I think you can do it with ldd and patchelf magic.
Answer:
I want to link all the binary code from these included header files so I can distribute my shared library in one .so file.

You cannot do what you want (and that is against the whole idea of shared libraries, which, as their name imply, are shared between several processes and "loaded" into their virtual address space by the dynamic linker).
You should read Drepper's How To Write Shared Libraries paper and the Program Library HowTo. See also ld-linux(8) & elf(5) & objdump(1) & readelf(1) & ld(1) & ldd(1). Read about Invoking GCC.
To ease distribution of your software, you may want to build some package (e.g. a .deb one) targetting some package manager. And you might publish your source code as free software (e.g. on github).
You could (and perhaps should) link other lower-level shared libraries with your own one. But your user would still need to have these libraries installed. For example, you might compile with
 gcc -Wall -O -g -I$JAVA_8_HOME/include/ -I$JAVA_8_HOME/include/linux/ \
     -I./include/ -I. -fPIC -o libMyLibrary.so \
     -shared com__MyLibrary.c -lother

and check with ldd libMyLibrary.so that it depends on some libother.so.* (which your user should have installed to use your libMyLibrary.so).
You could compile all the code you are using (as position-independent code) -including the source code of "other libraries"- into a single shared library, but that is not recommended (if you did that, a program could practicaly not use some shared low-level function in several shared libraries above it).
You also need to understand that a library is not a set of header files, that is to understand the roles of the linker and of the preprocessor. Header files just describe (partly) the API of some C or C++ library. Read also Levine's Linkers and Loaders book. In practice, header files declare some stuff (classes, functions, variables, types...) and might define inline functions (but not global ones). You need to understand what translation units are.
You could, with the help of the /proc/ file system (see proc(5)), understand the virtual address space of some given process. For instance, try cat /proc/$$/maps in a terminal.
You may read some Linux programming book, perhaps the old ALP (freely downloadable) or something newer. You may read some textbook on operating systems, such as Operating Systems: Three Easy Pieces (also freely downloadable).
Look also for inspiration into the source code and build procedure of existing free software libraries (e.g. from your Linux distribution, or on github or elsewhere). You should consider using some build automation tool (e.g. GNU make, or ninja) to build your own library.


Bootstrap modal on show function not passing value

Question: I want to pass id of the button to modal but seems cant get through and the console didnt show any error so i dont understand whats the problem.
I have edited the form attribute :

$('.showModal').on('click', function() {
  var id = $(this).data('id');
  $('#data').modal('show');
  $('#data').on('show.bs.modal', function() {
    $('.form #username').val(id);
  });
});

modal

      <form method="post" action="" id="modalForm" class="form">

            <input type="file" name="file" accept="image/" />

            </input>

            NIS
            <input type="text" id="username" autocomplete="off" class="form-control" name="username" value="i_want_button_id_here">

      </form>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="modalSubmit">Save</button>

Answer: When you use .data('id') that mean you're trying to target the property data-id when you've just id, you could use .prop() instead, like :
var id = $(this).prop('id');

You could try to target the previous anchor like :
$('#data').on('show.bs.modal', function() {
    var id = $(this).prev('a').prop('id');

    $('.form #username').val(id);
});

Comment: You're welcome, try my uspdate using `$(this).prev('a').prop('id')`.
Comment: shows an error Uncaught ReferenceError: id is not defined.
Comment: Put the line before `$('.form #username').val(id);` directly
Comment: somehow when i rewrite the code, its now working. but still shows an error if i log that id. thankyou
Answer: I think that is bacause you dont have class .form. You try to set value using this
$('.form #username').val(id);

Did you mean tag <form>? If yes, this should looks like that
$('form #username').val(id);

Also when you want to get val you should use attr instead of data
var id = $(this).attr('id');

Comment: still not working, this is one of many data i want to edit and i want to pass the id to modal so i can edit it related to the data i click.
Answer: This is because the id variable is undefined (try to console.log(id) it).
In order to access the id attribute on the link that opens the modal, use  this.id:
var id = this.id;
Or with jQuery .attr():
var id = $(this).attr('id');
Comment: i change it to $(this).attr('id') but it shows error Uncaught ReferenceError: id is not defined
    at HTMLDocument. (data-siswa:1497)
    at j (jquery.min.js:2)
    at k (jquery.min.js:2)


Eigenvalue decomposition of Cross Gramian matrix

Question: For a symmetric state space system $G(s)=\left\{A,B,C,D\right\}$, the cross Gramain matrix $R$ is the solution of $$AR+RA+BC=0$$
Using eigenvalue decomposition, problem is to obtain a matrix U which diagonalizes the cross gramian matrix $R$, resulting a diagonal matrix $S$ such that $$S=U^{-1}RU$$
Note: For state space symmetric system, $A=A^T, C=B^T$ where $T$ is the transpose of a matrix.
Answer: Could you specify your question on the cross Gramian?
You can find more information about the meaning of the eigen-decomposition of the cross Gramian matrix in the article "Cross-Gramian Based Model Reduction for Data-Sparse Systems" ( http://emis.ams.org/journals/ETNA/vol.31.2008/pp256-270.dir/pp256-270.pdf ) and references therein.


Angular-cli: Module not found: Error: Can't resolve 'PouchDB'

Question: OS?

Linux (Amazon Linux AMI)

Versions.
angular-cli: 1.0.0-beta.22-1
node: 6.6.0
os: linux x64

Repro steps.
I installed recently PouchDB:
npm i pouchdb --save
npm i @types/pouchdb --save-dev

I added this in typings.d.ts:
declare module 'PouchDB';

And now I import PouchDB in my service:
import * as PouchDB from 'PouchDB';

Well, all is okey in my laptop (MacOS Sierra); ng serve, ng build without problems and PouchDB is working well.
But... Not the same thing in my server (Amazon Linux AMI)...
I'm getting the next error trying to execute ng build:
ERROR in ./src/app/pictures.service.ts
Module not found: Error: Can't resolve 'PouchDB' in '/home/aral/project/src/app'
 @ ./src/app/pictures.service.ts 11:0-35
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.ts
 @ multi main

I have the same angular-cli version and node version that in my laptop...
And I compared doing tree command in my laptop and my server and both have the same files. (Except some sub-dependency in node_modules).
Thank you!

Issue reported in GitHub: https://github.com/angular/angular-cli/issues/3698
Comment: is typings required with npm @types ?
Comment: yes. https://github.com/angular/angular-cli#3rd-party-library-installation
Answer: I was using Mac in my laptop and this is the reason why in my laptop don't have this issue: Because the Mac main filesystem is case insensitive. Linux is not so forgiving. So importing from PouchDB the system is looking for a node_modules names PouchDB, but it's really named pouchdb (lowercase).
Answer: Checking in package.json file whether the pounchbd dependency is included or not,
if it is not included, then add this dependency  "pouchdb": "^7.2.2" and run npm install