Geração de erro ao tentar criar um diretório usando o Python: [WinError 2] O sistema não pode encontrar o arquivo especificado

Question: Em uma vídeo aula que assisti, o professor usa o seguinte comando para criar um diretório usando o Python:
import os

res = os.path.join(os.getcwd(), 'geek')
os.chdir(res)
print(os.getcwd())

Literalmente, é só isso que ele faz. Como o diretório 'geek' não existe, esse comando o cria. Porém, ao executar exatamente o mesmo código aqui, é gerado o seguinte erro:
"Traceback (most recent call last):
File "D:\Program Files (x86)\JetBrains\PycharmProjects\Guppe\testes.py", line 4, in
os.chdir(res)
FileNotFoundError: [WinError 2] O sistema não pode encontrar o arquivo especificado: 'D:\Program Files (x86)\JetBrains\PycharmProjects\Guppe\geek'"
Ou seja, no computador no professor da aula, o comando funcionou e criou o diretório "geek". Já aqui, é gerado esse erro. Gostaria de saber o motivo do erro, já que o código está exatamente igual.
Vale lembrar que no vídeo da aula é usado Ubuntu, enquanto eu uso Windows 10.
Answer: Seu código atual irá completar com sucesso caso o diretório geek exista, porém irá falhar caso não exista. O comando os.chdir não cria um diretório caso o mesmo não exista. Essa é função do comando os.mkdir:
import os

res = os.path.join(os.getcwd(), 'geek')
os.mkdir(res)
os.chdir(res)
print(os.getcwd())

O código acima irá completar com sucesso caso o diretório geek não exista, porém irá falhar caso exista. Para resolver esse problema, basta usar a função os.path.isdir:
import os

res = os.path.join(os.getcwd(), 'geek')

# Verifica se a pasta já existe; caso não, a cria
if not os.path.isdir(res):
    os.mkdir(res)

os.chdir(res)
print(os.getcwd())

O código acima irá completar com sucesso, seja geek existindo ou não.
Comment: Entendi. Só acho estranho que, no caso do vídeo, o comando que cria o diretório é o `res = os.path.join(os.getcwd(), 'geek')`. O comando `os.chdir(res)`, pelo que entendi, só entraria no diretório após ele já ter sido criado, e o `os.mkdir(res)` não foi usado no vídeo. Porém, a vídeo aula é de 2018, então suponho que de lá pra cá devem ter alterado isso no Python, pois justamente por ser vídeo, dá pra ver o comando funcionando "em tempo real". Acredito que antes então era possível criar um diretório dessa forma, mas agora não deve ser.


Disabling Auto Scroll UITableView

Question: I want to disable autoscroll to top. I tried both
<code>    tableview.scrollsToTop=NO;
    [tableview setScrollsToTop:NO];
</code>
but that doesn't work.
Thanks
Comment: No that is not I want. May be I am wrong about what I say. The problem is i have a table view with many rows.When cell is selected. it push some view controller. After, I press back button. It scrolls up(the selected row is at the top cell).So I don't want it to scroll itself
Comment: Are your sure your tableview property is valid when you set the property? Try adding a "- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView" delegate method and return NO.
Comment: So you know that tableView is set - you added a log message to print it out NSLog(@"%@", tableView)", you set the value, your tableview is setup to use your class as a delegate, and you have the delegate method that returns NO? Add a log to scrollViewShouldScrollToTop to see if it gets called. ScrollToTop is where you tap the Status Bar - this is the feature you want to disable, right?
Answer: The automatic scrolling code resides in tableViewController, so auto-scrolling can't be disabled. Instead of subclassing from UITableViewController you can subclass from UIViewController and use a tableView inside it.
If you are willing to use UITableViewController itself, you can override viewWillAppear and don't call [super viewWillAppear].

Disabling Auto Scroll UITableView


access node title in field.tpl.php

Question: I would like to access the title of the node a field belongs to in a field.tpl.php file. My goal is to transform the field into a mailto link that would use the node title as the subject field.
Is it possible to access that information at this point?
Answer: You could get the node values from: $element['#object']: The entity to which the field is attached.
So in this case if the field is a node field the $element['#object'] is the node object.
print $element['#object']->title;

Documentation: https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7
Comment: Thanks! I just found it meandring around the aptana debugger and the docs. That's just what I was looking for!

access node title in field.tpl.php


different HRs and corresponding CIs with cph and coxph

Question: I tried a model using cph and coxph:
library(papeR)
library(survival)
library(rms)
dd <- datadist(d)
options(datadist="dd")
fit.cph <- cph(Surv(time, event) ~ x1+x2+x3, data=d)
fit.coxph <- coxph(Surv(time, event) ~ x1+x2+x3, data=d)

However, while "coef" are the same, ...
> fit.cph

Cox Proportional Hazards Model

cph(formula = Surv(time, event) ~ x1 + x2 + x3, data = d)

                     Model Tests       Discrimination
                                          Indexes
Obs        780    LR chi2     54.14    R2       0.114
Events      52    d.f.            3    Dxy     -0.489
Center -1.0564    Pr(> chi2) 0.0000    g        1.045
                  Score chi2  63.21    gr       2.844
                  Pr(> chi2) 0.0000

     Coef    S.E.   Wald Z Pr(>|Z|)
x1    0.2880 0.0631  4.57  <0.0001
x2   -0.0450 0.0130 -3.48  0.0005
x3=b  0.6767 0.2840  2.38  0.0172

> fit.coxph
Call:
coxph(formula = Surv(time, event) ~ x1 + x2 + x3, data = d)

      coef exp(coef) se(coef)     z       p
x1   0.288     1.334   0.0631  4.57 5.0e-06
x2  -0.045     0.956   0.0130 -3.48 5.1e-04
x3b  0.677     1.967   0.2840  2.38 1.7e-02

Likelihood ratio test=54.1  on 3 df, p=1.05e-11  n= 780, number of events= 52

...  "HR" and its CI seems to be not:
> summary(fit.cph)
             Effects              Response : Surv(time, event)

 Factor        Low  High Diff. Effect S.E. Lower 0.95 Upper 0.95
 x1             2.0  5.0  3.0   0.86  0.19  0.49       1.23
  Hazard Ratio  2.0  5.0  3.0   2.37    NA  1.64       3.44
 x2            43.3 57.6 14.3  -0.64  0.19 -1.01      -0.28
  Hazard Ratio 43.3 57.6 14.3   0.53    NA  0.37       0.75
 x3 - b:a       1.0  2.0   NA   0.68  0.28  0.12       1.23
  Hazard Ratio  1.0  2.0   NA   1.97    NA  1.13       3.43

> prettify(summary(fit.coxph))
Confidence intervals are experimental only;
Model refitted but original environment not available.

               coef Hazard Ratio CI (lower) CI (upper)   se(coef)         z Pr(>|z|)
1    x1  0.28801326    1.3337750   1.178690  1.5092647 0.06306712  4.566773   <0.001 ***
2    x2 -0.04504293    0.9559564   0.931991  0.9805381 0.01295390 -3.477172    0.001 ***
3 x3: b  0.67671538    1.9674049   1.127551  3.4328234 0.28401934  2.382638    0.017   *

Or do I just do/interpret in wrong? Anyway, I do not know what of the cph summary is what.
Answer: summary.rms prints the estimated effects and CIs for an interquartile range increase in the independent continuous variables by default whereas summary.coxph does not (it prints them for a one unit increase). The HR and CI for x3 agree (up to rounding errors) since x3 seems to be a categorical variable.
Try changing the summary call to something along the lines of summary(fit.cph, x1 = c(2, 3)) and it should be similar for x1.
A good way to understand the rms package is to get a copy of Frank Harrell's book Regression Modeling Strategies and work through the examples on the help pages to cph and summary.rms.
Hope this helps!


Reduce the 2nd order difference equation to 1st order

Question: I have the following 2nd order difference equation.
$\alpha X_{t+1}-X_{t+2} = \beta\alpha \left(\alpha X_{t}-X_{t+1}\right)$
Clearly, one solution is the process of $\alpha X_{t}=X_{t+1}$.
However, there is another solution which is $X_{t+1}=\beta\alpha X_{t}$.
The question is, WITHOUT the guess-and-verify method, how to derive the second one from the 2nd order difference equation at the beginning?
Comment: By the way, **welcome** to the site !
Answer: If you consider the recurrence equation
$$\alpha X_{t+1}-X_{t+2} = \alpha \beta \left(\alpha X_{t}-X_{t+1}\right)$$ let $X_t=e^{kt}$, replace, simplify to get
$$-\alpha^2 \beta+\alpha (\beta+1) e^k-e^{2 k}=0$$   and solve for $e^k$.
You should find two roots corresponding to $k=\log(a)$ and $k=\log(a b)$ making, as a general solution,
$$X_t=c_1 \alpha^t+c_2 (\alpha \beta)^t$$
Answer: Calling
$$
Y_t = \alpha X_t-X_{t+1}
$$
follows
$$
Y_{t+1} = \beta\alpha Y_t
$$
so solving first for $Y_t$ we have
$$
Y_t = C_1(\alpha\beta)^{t-1}
$$
and finally solving
$$
\alpha X_t-X_{t+1} =  C_1(\alpha\beta)^{t-1}
$$
we get
$$
X_t = C_2 \alpha ^{t-1}+\frac{C_1 \left(\alpha ^t-(\alpha  \beta )^t\right)}{\alpha ^2 (\beta -1) \beta }
$$


If dentro de if dentro while dentro de while (lento)

Question: Estou com um dúvida acerca de loop while:
tenho a seguinte query:
 $sql = "SELECT id,cod,nome,cnpj,insc_estadual,tributacao FROM empresas_base WHERE tributacao = '$filtro_regime_nome' AND responsavel = '$user' GROUP BY id ORDER BY id";

Essa query inicia um loop while, e dentro desse loop realizo outra consulta com base no 'cod' da empresa.
$sql2 = "SELECT * FROM controle_fiscal WHERE empresa = '$empresaCod' AND mes_correspondente = '$m' AND ano_correspondente = '$a' GROUP BY id ORDER BY id ";

E com essa segunda query eu efetuo mais um loop while dentro do loop anterior para pegar os valores que eu preciso, e ainda por cima, dentro desse segundo loop, existem varios ifs dentro de ifs, o que faz com que a consulta acabe ficando mais lenta do que o esperado.
OBS: Os loops e ifs são tratados por funções da classe model, não estão dispostos de forma linear, mas mesmo assim não deixam de ser ifs
Dúvida:

1 - É correto fazer isso ?
2 - Existe outra maneira de efetuar isso com apenas uma query ?
Comment: Correto é relativo, no geral dá para otimizar a maneira de fazer, se postar como fez até o momento talvez seja possivel fornecer uma sugestão melhor.
Comment: Tudo que funciona e traz um resultado satisfatório é correto. Claro, que há casos em que podemos otimizar para ganharmos alguns nanosegundos ou, não sobrecarregar o servidor.
Answer: A maneira de fazer isso só com uma query é utilizando o JOIN:

OBS: Fiz um exemplo de como ficaria, mas como não conheço seu banco de dados, pode ser que precise de alguns ajustes, te aconselho a dar uma estudada no JOIN e ver como ficaria melhor no seu caso.

SELECT e.id,e.cod,e.nome,e.cnpj,e.insc_estadual,e.tributacao, cf.*
FROM controle_fiscal cf
INNER JOIN empresas_base e ON cf.empresa = e.cod
WHERE e.tributacao = '$filtro_regime_nome' AND e.responsavel = '$user' AND cf.mes_correspondente = '$m' AND cf.ano_correspondente = '$a'
GROUP BY e.id
ORDER BY e.id

Alguns pontos merecem atenção,como:

campos com mesmo nome;
em qual tabela fazer o join;
a forma que vc quer os registros retornados;

Entre outros;
Aqui tem um link para vc dar uma olhada: http://www.devmedia.com.br/sql-join-entenda-como-funciona-o-retorno-dos-dados/31006


Setting up apache to view https pages

Question: I am trying to set up a site using vmware workstation,  ubuntu 11.10, and apache2.  The site works fine but now the https pages are not showing up.  For example if I try to go to https://www.mysite.com/checkout I just see the message

Not Found The requested URL /checkout/ was not found on this server.

I dont really know what I am doing and have tried a lot of things to get the ssl certificates in there right.
A few things I have in there, in my httpd.conf I just have :
ServerName localhost
In my ports.conf I have :
NameVirtualHost *:80
Listen 80

<IfModule mod_ssl.c>
    # If you add NameVirtualHost *:443 here, you will also have to change
    # the VirtualHost statement in /etc/apache2/sites-available/default-ssl
    # to <VirtualHost *:443>
    # Server Name Indication for SSL named virtual hosts is currently not
    # supported by MSIE on Windows XP.
    Listen 443 http
</IfModule>

<IfModule mod_gnutls.c>
    Listen 443 http
</IfModule>

In the /etc/apache2/sites-available/default-ssl :
<IfModule mod_ssl.c>
<VirtualHost _default_:443>
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

     .... truncated

in the sites-available/default I have :
<VirtualHost *:80>
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www
        #DocumentRoot /home/magento/site/
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
        #<Directory /home/magento/site/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all

        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
                Allow from all
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog ${APACHE_LOG_DIR}/access.log combined

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>
</VirtualHost>
<virtualhost *:443>
  SSLEngine on
  SSLCertificateFile /etc/apache2/ssl/server.crt
        SSLCertificateKeyFile /etc/apache2/ssl/server.key
        ServerAdmin webmaster@localhost
  <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
        #<Directory /home/magento/site/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all

        </Directory>

</virtualhost>

I also have in sites-availabe a file setup for my site url, www.mysite.com so in /etc/apache2/sites-available/mysite.com
<VirtualHost *:80>
        ServerName mysite.com
        DocumentRoot /home/magento/mysite.com

        <Directory />
                Options FollowSymLinks
                AllowOverride All
        </Directory>
        <Directory /home/magento/mysite.com/ >
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>

        ErrorLog /home/magento/logs/apache.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn
</VirtualHost>
<VirtualHost *:443>
        ServerName mysite.com
   DocumentRoot /home/magento/mysite.com

        <Directory />
                Options FollowSymLinks
                AllowOverride All
        </Directory>
        <Directory /home/magento/mysite.com/ >
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>

        ErrorLog /home/magento/logs/apache.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn
</VirtualHost>

Thanks for any help getting this setup!  As is probably obvious from this post I am pretty lost at this point.
Comment: can you open http://www.mysite.com/checkout on port 80 without any issues ?
Comment: yes, i disabled the secure pages from the magento app I am running and the pages load fine.
Answer: A couple of things you can try:

Since you're using <VirtualHost *:443> in /etc/apache2/sites-available/mysite.com, replace both instances of Listen 443 http with
NameVirtualHost *:443
Listen 443

in your ports.conf.
As far as I can tell, you are not using the default configurations to actually serve a website.
If I'm right, disable them:
a2dissite default default-ssl

In this case, you should also delete the line
ServerName localhost

from your httpd.conf.
Make sure your newest configuration and SSL are enabled.
a2ensite mysite.com
a2enmod ssl

After making any changes, remember to reload apache to activate the new configuration:
service apache2 reload

Comment: Thanks, I followed everything but now I get a SSL connection error when I try to go to https://  Also when I restart apache2 I see errors like `[warn] NameVirtualHost *:443 has no VirtualHosts `
Comment: I am also seeing this error : `VirtualHost *:443 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results`
Comment: Try removing the `NameVirtualHost *:443` lines.
Comment: hmm i tried and it was still giving me those errors.  I removed /conf.d/virtual.conf and error went away, but now I am back to a 404 on https pages
Comment: What do the log files say? Also, apache might not even be the culprit. This could have something to do with vmware.
Comment: ack.. hmm this sux. Logs no help... I dont think.. it does say client denied by server configuration (the local.xml of this magento install) but I dont think that is it
Answer: below part does not seem to be correct
this is a virtual host for ssl connections on 443,
<IfModule mod_ssl.c>
<VirtualHost _default_:443>
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

you are receiveing error due to inappropriate
DocumentRoot /var/www

change it to the same values as in
<VirtualHost *:443>

Setting up apache to view https pages


Multiple pagers in single page

Question: Hi I have a page in which I have added 2 blocks in both blocks I have paging,but when ever i click any page number of either a block both the page change simultaneously in Drupal7
$output .= theme('pager', array('tags' => array()));
This is generating pager.
Pls help
Answer: You can use the element parameter:

An optional integer to distinguish between multiple pagers on one page.

e.g.
First call:
$output .= theme('pager', array('tags' => array(), 'element' => 0));

Second call:
$output .= theme('pager', array('tags' => array(), 'element' => 1));

Answer: I've implemented the multipage on a single page in Drupal 8
Note:-  The $element value is the key here. It should be same for both query extend and pager element.
100% working solution. Please find the exact solution for the same below:-
public function multiplePagers() {
    $build['pager_table_0'] = $this->buildTestTable(0);
    $build['pager_pager_0'] = $this->getPagerElement(0);

    $build['pager_table_1'] = $this->buildTestTable(1);
    $build['pager_pager_1'] = $this->getPagerElement(1);

    $build['pager_table_2'] = $this->buildTestTable(2);
    $build['pager_pager_2'] = $this->getPagerElement(2);

    $build['pager_table_3'] = $this->buildTestTable(3);
    $build['pager_pager_3'] = $this->getPagerElement(3);

    //render your table and pager respectively in you template
    return [
        '#theme' => 'your_theme_name',
        '#data' => $build
    ]
}

public static function getPagerElement($element){
    return [
        '#type' => 'container',
        '#attributes' => ['class' => ['test-pager-'.$element]],
        '#use-ajax' => TRUE,
        'pager' => [
            '#type' => 'pager',
            '#element' => $element,
        ],
    ];
}

protected function buildTestTable($element) {
    $header = [
        ['data' => 'wid'],
        ['data' => 'type'],
        ['data' => 'timestamp'],
    ];
    $query = Database::getConnection()->select('watchdog', 'd')->extend(PagerSelectExtender::class)->element($element);
    $result = $query
        ->fields('d', ['wid', 'type', 'timestamp'])
        ->limit(20)
        ->orderBy('d.wid')
        ->execute();
    $rows = [];
    foreach ($result as $row) {
        $rows[] = ['data' => (array) $row];
    }
    return [
        '#theme' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#empty' => $this->t("There are no watchdog records found in the db"),
    ];
}

Feel free to thank me later :-)

Multiple pagers in single page


how to read user ROLES using XSJS?

Question: I would like to know what the session user has access to. For example if user X has access to a particular database or a set of tables. When looking into HANA I see that I have the PUBLIC role that allows me to see the database, how can I pull this information using XSJS so I can perform logic based on those roles?
I've used $.session.hasSystemPrivilege("PRIV");  but this is different than checking roles. I tried testing for "INSERT" for inserting into the database which returned false. I know that I can write to the tables. Looking in to the HANA, the system privileges tab is empty for me.
Could someone give me some guidance here?
Answer: Create your analytic/calculation view on top of SYS.GRANTED_ROLES or GRANTED_PRIVILEGES.
Expose your view as OData service and access this service in XSJS.

how to read user ROLES using XSJS?


Calculus Kinematic Question

Question: "A body moves in a straight line such that, t s after passing through a fixed point O, its displacement from O is s m. The velocity v ms^-1 of the body is such that v = 5cos(4t)"
a) Write down the velocity of the body as it passes through O.
b) Find the value of t when the acceleration of the body is first equal to 10ms^-2 .
For a) I got v = 5ms^1 .
For b) I did the following:
dv/dt = -20sin(4t)
10 = -20sin(4t)
-0.5 = sin(4t)
How do I get rid of the sine? Do I use the arcsine? When I do that I get 4t = (-1/6)pi , and after I divide it by 4 I get (-1/24)pi, which is not the correct answer... Any help would be appreciated!
Answer: Since time got no directions(at least in kinematics), don't take $-pi/6$ as the value. Since it is mentioned that the first time the acceleration goes to $10 ms^-2$. The value will be $4t= 210$. So the answer will be $52.5 sec$
Comment: Why would it be 210 though? I used the value -1/6pi since that was what I got from the division. The answer given by the book is t =(7/24)pi, and I cannot figure out exactly why. What does the part "first time" suggest?
Comment: Since the acceleration is in terms of sine and the sine value will repeat after one complete rotation i.e., after 360 deg.
Comment: @KakaS you should be using radians not degrees
Comment: Yeah....210 deg is 7*pi/6 which would give the answer.Thanks @David Quinn
Comment: Oh, right! -1/6pi is the same as 7/6pi when you go "the other way round". A question though. Why wouldn't -1/6pi be a suitable answer?  Just because it is negative?
Comment: Yes...in this case since it is the time we are after.

Calculus Kinematic Question


Deploy hundreds of thousands of short lived jobs per day

Question: I have a system that needs to deploy hundreds of thousands of short-lived jobs per day. Each job runs anywhere from a few seconds, to a couple of hours. Each job makes HTTP requests to external web servers, writes data to disk (anywhere from a few megabytes to hundreds of gigabytes), and makes a series of connections to databases.
Every job is the same Docker container, running the same single Java process. Each job has a different configuration, passed as a environment variable.
We currently deploy these jobs on a Kubernetes cluster using the "Job" spec. However, the cluster is not immediately available for jobs when a large influx of jobs are to be ran. We also have to constantly query the Kubernetes cluster to determine if the Job has been finished, or was killed (e.g. out of memory).
I'd like to find a solution that would allow us to deploy these jobs as quickly as possible with the least amount of concern about whether resources are available, or requiring us to query a system to determine if the job has completed.
AWS Lambda comes to mind, but I have little experience with it.
As a architectural note, we have our process that serves a scheduler, in that calculates what job should be ran, and when. that process currently submits the job to the Kubernetes cluster.
Given the above description, what architectures should I be evaluating to minimize the amount of concern this system has around 1) if resources are available to handle the job and 2) Whether that job fail for any "non application" reason.
This system currently runs on GCP and AWS. We're open to any solution, even if it means selecting a single (and potentially different) platform.
Answer: If the jobs are short-lived, your purpose might be better served by implementing a job queue, and a set of longer-lived workers which consume jobs from the queue. Is there a reason you need to run the jobs in k8s itself?
Comment: I think that's effectively what we are doing right now: We have a job queue, and each job is ran as a docker container a kubernetes cluster, where each pod node represents a "worker."

If we were to execute these outside of Kubernetes, we'd still the nodes, and we'd still have those nodes running when there were no jobs to do. I also don't know of another production-grade way to run the Docker images.
Comment: What you are doing now is starting a new worker process for each job. I'm proposing the idea of having longer-lived workers which process multiple jobs during their life cycle
Comment: Every task that is ran is a container inside a node (a long-lived instance).
Comment: Instead of starting and stopping hundreds of thousands of containers running the same code, but different configuration, start a set of these containers and have them read the hundreds of thousands of configurations from a queue and process them one at a time.
Answer: Presumably your cluster is resource limited. Achieving a higher job volume, if that is a requirement, must involve a more efficient application or more resources.
Large providers like you use will rent you as many instances as your budget allows. Scale up your cluster, possibly automatically. Possibly some spare capacity is needed if you schedule jobs on short notice.
An alternative to polling the Kubernetes job is your code passing a message. At the end of a job, do some kind of call back to your scheduler indicating finished.
Of course, it may have died and will never report back. Eventually this needs to become a failure state. Consider polling the job at intervals after your typical shortest job time, and giving up on it after a hard limit like  activeDeadlineSeconds.
Comment: Thanks. All jobs actually do make several requests to an API to update their status and progress. But when the job completes, we still have "delete" the job, as there is a limit to the number of completed jobs Kubernetes can store. There's a new API in the next release of Kubernetes that allows for Jobs to be automatically cleaned up. However, we still have to check on the Job in case it was terminated for thinks like OOM.

We do scale the cluster, but scaling it can take several minutes, during which jobs cannot be reliably submitted to the cluster.
Comment: Then you have to stay ahead of jobs by maintaining idle capacity 5 minutes before it is needed. At least enough for high priority jobs that need to start now. No way to avoid that if you always want jobs to have resources.
Comment: Of course, we do that. So the question in the post is what options are available to avoid doing this. AWS Lambda seems like an option, but the amount of data we write to disk might be a limit factor. We're looking to explore other options.


Why does backward recursion execute faster than forward recursion in python

Question: I made an algorithm in Python for counting the number of ways of getting an amount of money with different coin denominations:
@measure
def countChange(n, coin_list):
    maxIndex = len(coin_list)
    def count(n, current_index):
        if n>0 and maxIndex>current_index:
            c = 0
            current = coin_list[current_index]
            max_coeff = int(n/current)
            for coeff in range(max_coeff+1):
                c+=count(n-coeff*current, current_index+1)
        elif n==0: return 1
        else: return 0
        return c
    return count(n, 0)

My algorithm uses an index to get a coin denomination and, as you can see, my index is increasing in each stack frame I get in. I realized that the algorithm could be written in this way also:
@measure
def countChange2(n, coin_list):
    maxIndex = len(coin_list)
    def count(n, current_index):
        if n>0 and 0<=current_index:
            c = 0
            current = coin_list[current_index]
            max_coeff = int(n/current)
            for coeff in range(max_coeff+1):
                c+=count(n-coeff*current, current_index-1)
        elif n==0: return 1
        else: return 0
        return c
    return count(n, maxIndex-1)

This time, the index is decreasing each stack frame I get in. I compared the execution time of the functions and I got a very noteworthy difference:
print(countChange(30, range(1, 31)))
print(countChange2(30, range(1, 31)))

>> Call to countChange took 0.9956174254208345 secods.
>> Call to countChange2 took 0.037631815734429974 secods.

Why is there a great difference in the execution times of the algorithms if I'm not even caching the results? Why does the increasing order of the index affect this execution time?
Comment: yes ... this is how dynamic programming works (this is an example of dynamic programming, you start at the goal state, and work backwards allowing you to skip calculations that would result in an invalid solution)... however if you start at the initial state it takes an exaustive search and does not know an answer is invalid until after calculating it
Comment: The number of calls is dependent on the order of input. You can get the minimum number by sorting the list in descending order in `countChange`. `coin_list.sort(reverse = True)`
Comment: @JoranBeasley: Starting at the "goal state" and working back to the "start state" doesn't automatically make an algorithm "dynamic". Suppose I have a maze with exactly two doors, A and B. You're telling me that if I label A "enter" and B "exit", and you start at B, then you are doing some kind of "dynamic programming" maze solving? What if I switch the labels so that A reads "exit" and B reads "enter". Have I suddenly made your maze solver **not** dynamic anymore?
Comment: its just a timing decorator Im sure @JanVlcinsky
Comment: @rfrm where does `@measure` comes from?
Comment: @JoranBeasley This I understood, but do I have to define it or it is already somewhere prepared?
Comment: just comment it out ... and use timeit or something if you are trying to compare ...
Comment: {@measure} is only for timing as @JoranBeasley said. The question raises, because I'm NOT using any caching, any Dynamic Programming, in fact this is the previous step to make an Dynamic Programing algorithm, to express it in a recursive way.
Comment: when you start in the goal state and recusively work to the start state that is dynamic programing ... Im not sure where you are getting this information about requiring memory(caching) for dynamic programing..
Comment: "The dynamic programming approach seeks to solve each subproblem only once, thus reducing the number of computations: once the solution to a given subproblem has been computed, it is stored or "memo-ized": the next time the same solution is needed, it is simply looked up. " http://en.wikipedia.org/wiki/Dynamic_programming
Comment: working forward you examine all posibilities , working backwards you can eliminate invalid paths without exploring them.  this is indeed a dynamic programing solution (you are only calculating each subproblem once ... so why would you memoize it?) going forwards however you must exaustivly explore your search space ...
Comment: you can verify this behavior by putting a counter in the count function that is incremented each time count is called and print it at the end
Answer: This doesn't really have anything to do with dynamic programming, as I understand it.  Just reversing the indices shouldn't make something "dynamic".
What's happening is that the algorithm is input sensitive.  Try feeding the input in reversed order.  For example,
print(countChange(30, list(reversed(range(1, 31)))))
print(countChange2(30, list(reversed(range(1, 31)))))

Just as some sorting algorithms are extremely fast with already sorted data and very slow with reversed data, you've got that kind of algorithm here.
In the case where the input is increasing, countChange needs a lot more iterations to arrive at its final answer, and thus seems a lot slower.  However, when the input is decreasing, the performance characteristics are reversed.
Comment: @JoranBeasley: I think you really have misunderstood dynamic programming. Either that or you didn't take the time to examine the properties of this problem. See my edit.
Comment: it does though(make it a dynamic programming solution) with this problem specifically, since reversing it allows you to not even explore invalid path.  it also ensures that you only calculate each subproblem once ... (+1 all the same, since yes the reason it is slower is it calls more times ...)
Comment: your right .... im still not sure... I thought I understood dynamic programming, now im doubting myself (also I didnt really examine the algorithm OP was using... it looks like lots of stuff is recalculated ... all over the place, regardless of order) ...
Answer: thre number combinations are not huge
the reason is that going forward you have to explore every possibility, however when you go backwards you can eliminate large chunks of invalid solutions without having to actually calculate them
going forward you call count 500k times
going backwards your code only makes 30k calls to count ...
you can make both of these faster by memoizing the calls , (or changing your algorithm to not make duplicate calls)
Comment: This is not dynamic programming. Dynamic programming is fundamentally about dividing a problem into overlapping subproblems and reusing the results of subproblem computations. Nothing is reused here; in fact, `count` is called repeatedly with the same arguments in both versions. John Y's answer is significantly more accurate.
Comment: "Reversing it allows you to not even explore invalid path" @Joran this makes sense, Thank you.
Comment: Dynamic programming needs of a mean of saving previous results, as you can see, I'm NOT saving nothing.
Comment: no it doesnt it typically is recursively called(although nothing forces that its just the most intuitive way) ... just like you are doing ... this is  dynamic programing and this is also why starting in start state is much slower than starting in your goal state ... (in fact the tutorial I wrote is this exact same problem statement)
Comment: I figured bolding parts of my answer would help :P people were getting too hung up on semantics :P (me too ... maybe Im wrong and this isnt actually dynamic programming... but Im pretty sure :P)
Comment: Your dynamic programming tutorial isn't even using dynamic programming. What you have in your tutorial is the non-dynamic recursive approach; it needs to be memoized to make it dynamic.
Comment: there I got rid of the parts about dynamic programing ... that said I still say this is dynamic programming, and that memoization is not a requirement of dynamic programing, however it is often used...
Comment: Memoization is not a requirement, but reuse of subproblem results is. This may be done top-down (memoization) or bottom-up, but if it's not done, what you have is not dynamic programming at all.
Comment: Im pretty sure its just avoiding recalculating subproblems, which as you rightly pointed out is not the case in this subproblem implementation. (that said im fairly confident there are ways of implementing this problem without having any recalculations...)
Comment: The answer has been completely modified. Now the followup comments don't make any sense. Should have left the original answer and added a separate Update section..


generating function for $0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,\dotsc$

Question: I know that the generating functions is  $$x + x^4 + x^7 + x^{10} +\dotsb$$
and then we can factor out a $x$ to get
$$x(1+(x^3) + (x^3)^2 + (x^3)^3 + \dotsb )$$
Now I need my answer in closed form which is the part I do not know how to do. The text book answer is $x/(1-x^3)$, but I'm not sure how they got this.
Comment: When referring to yourself, capitalize the letter i. Also, format your posts. Formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: If you know that $$\frac{1}{1-z} = 1 + z + z^2 + z^3 + \cdots,$$ then letting $z = x^3$ immediately results in the desired equality.
Comment: Note for the future: Exploiting $\frac{1}{1-z}=1+z+z^2+\cdots$ will come up over and over.


ReferenceError: nokia is not defined. Getting this error only in Mozilla Firefox browser

Question: I am using nokia maps in my application. The map works perfectly fine in Chrome and IE. But it is not working in Mozilla Firefox browser.
The version of mozilla I am using is 51.0.1 (32-bit)
I tried to debug in the browser. If I add watch expression for nokia, Then also it is throwing the same error.
ReferenceError: nokia is not defined.
I am currently using the below URL.

Please help!
Answer: Finally I found the problem and solution.
In chrome and IE it is working fine because, it is allowing the content to load though the website does not support HTTPS.
But, In Mozilla Firefox, It is not loading the content at all.
I modified the URL with only HTTP, not with HTTPS.


how to design network for connectivity between private and corporate LANs?

Question: there is a bunch of servers connected to shared storage in a private LAN (10.x.x.x).
this privateLAN is managed by a windows server (DHCP, DNS and directory services)
these hosts need to be from outside of the datacenter Eg. Remote desktop.
can the NIC2 on each of the hosts be connected to the other public LAN (compromising speed or security?
what are improtant considerations:

additional hardware? like switches?
routing&DNS software?

currently available hardware : Dell Powerconnect 6224 switch .... planning this for storage network.
software: windows 2003 server for DHCP, DNS, A/D ? would it be more flexible to use Linux distributions like IPCOP, Untangle etc?
all that I am looking for is good isolation between private and other networks, avoid DHCP, DNS, AD clashes.
Comment: what are you trying to achieve here? What are your business requirements?
Answer: You would be able to perform the above using a router and NAT. If you require more information let me know.
We would need to know what router you have and what services on the network you need to access.
Comment: currently have a Dell managed switch 6224- dedicated for storage. only have few unmanaged switches at my disposal. software options for router, NAT? BTW my corporate LAN provides these services anyway, i think tweaking has to be done on the private LAN?
Answer: What i think your suggesting is multihoming. This can get messy & will mean you have to setup static routes on each host.  Not for the faint hearted.
Comment: thanks for the response, what ways can this be achieved without multi-homing? why is static routing hard? are there any softwares that do that?
Comment: does your 10.x.x.x have a default gateway? one way around it is only have 1 nic on the box with a default gateway, then theres no need for adding in static routes on the box.  the software is part of the OS
Comment: does not have one currently, but can setup one PC as gateway. Since the switch at my disposal is managed what does it need to establish connectivity between the two LANs?
Answer: Assuming you've got quality switches, and sensible NICs in your servers (Broadcom or Intel), then you might be able to do this with VLANs.  Those are two pretty big assumptions though.
And it should be less fragile than doing it with static routes.
In Theory.
Edit:
Oooh. Nice switch <3 .  That's definitely enough to support VLAN tagging.  Right.  So here's the theory.
Create a VLAN for your private stuff, and a VLAN for your public stuff.  You could probably use native VLAN 1 for the public, and put the private stuff on VLAN 2, or nearly any other number.
I'd probably buy a dedicated router too, to do the inter-VLAN routing.  Probably a Cisco 28xx or 29xx.  I'm not entirely convinced that the switch you've got can do interVLAN stuff with a low-enough overhead.
It's all a little complex, without more detail, but there should be plenty of information on the internets about how to set up separate VLANs.  You could probably do it port-based, where the physical port gets a different VLAN (meaning that the servers are tied to those switch ports, IMO, not a bad thing), and this works even if the devices don't support VLANs on their NICs.
I'm sure someone else can add more detail, or you can Google about, and see what you can find.
Comment: Dell powerconnect managed 6224 for storage n/w. all servers have Intel, Broadcom NICs- any specific features required on NIC?
Comment: VLAN support...
Comment: thank you Tom. I will dig into the details... Merry Christmas & happy holidays to you too!
Comment: @Jon I don't appreciate you bowdlerizing my answer.


Como liberar memoria apôs realizar certa tarefa?

Question: Em uma certa tarefa, tenho que carregar 6 fotos em 6 PictureBox, para isso utilizo o método abaixo:
 private void simpleButton1_Click(object sender, EventArgs e) // botao carregar foto
    {
        OpenFileDialog carrega_foto = new OpenFileDialog();
        carrega_foto.Filter = "jpg|*.jpg";

        if (carrega_foto.ShowDialog() == DialogResult.OK)
        {
            if(pic1 == 0)
            {
                pictureBox1.ImageLocation = carrega_foto.FileName;

                pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

                pic1 = 1;
            }
            else  if(pic2 == 0)
            {
                pictureBox2.ImageLocation = carrega_foto.FileName;

                pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;

                pic2 = 1;
            }
            else if (pic3 == 0)
            {
                pictureBox3.ImageLocation = carrega_foto.FileName;

                pictureBox3.SizeMode = PictureBoxSizeMode.StretchImage;

                pic3 = 1;
            }
            else if (pic4 == 0)
            {
                pictureBox4.ImageLocation = carrega_foto.FileName;

                pictureBox4.SizeMode = PictureBoxSizeMode.StretchImage;

                pic4 = 1;
            }
            else if (pic5 == 0)
            {
                pictureBox5.ImageLocation = carrega_foto.FileName;

                pictureBox5.SizeMode = PictureBoxSizeMode.StretchImage;

                pic5 = 1;
            }
            else if (pic6 == 0)
            {
                pictureBox6.ImageLocation = carrega_foto.FileName;

                pictureBox6.SizeMode = PictureBoxSizeMode.StretchImage;

                pic6 = 1;
            }
        }
    }

Então, pego as fotos, redimensiono elas, trasnformo em um array de byte[] e salvo no banco de dados, com o metodo abaixo:
            try
            {
                PictureBox[] List_Picture = { pictureBox1, pictureBox2, pictureBox3, pictureBox4, pictureBox5, pictureBox6 };

                foreach (PictureBox Pic in List_Picture)
                {
                    if (Pic.ImageLocation != null)
                    {
                        MemoryStream stream = new MemoryStream();

                        EncoderParameters myEncoderParameters = new EncoderParameters(1);

                        EncoderParameter myEncoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 10L);

                        myEncoderParameters.Param[0] = myEncoderParameter;

                        var codec = ObterCodec(Pic.Image.RawFormat);

                        Pic.Image.Save(stream, codec, myEncoderParameters);

                        byte[] Bfoto = stream.ToArray();

                        Classes.Cadastro.Crm.Analise_CRM Cad_Foto = new Classes.Cadastro.Crm.Analise_CRM();

                        Cad_Foto.Cad_Foto_Anal_Crm(textEdit8.Text, Bfoto);

                        Pic.Dispose();
                    }
                }
            }
            catch (Exception error)
            {
                MessageBox.Show("Erro, Contate o adiministrador!" + "\n" + error, "Salvar", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

então, realizando um debug vi que quando carrego as fotos, é utilizado bastante memoria para isso, ate ai tudo bem..
Porem, depois que eu salvo a foto no banco, como faço para liberar essa memoria utilizada?
tentei usar o metodo Dispose mas não deu certo!
Oque acontece e que se tento executar essa tarefa novamente, é gerado a exceção abaixo:
Comment: Basicamente é isso: https://pt.stackoverflow.com/q/163768/101. Esse código está criando vários recursos que nunca são liberados. Tem que ver a documentação de todos os objetos usados para saber quais precisam de liberação, ou usar alguma ferramenta que indique isto para você, como o [Resharper](https://www.jetbrains.com/resharper/). Na verdade esse código tem vários outros pequenos problemas.
Comment: @bigown me corrija se estiver errado, então oque posso fazer é, utilizar do metodo `using` e `dispose` e aguardar que o sistema "recolha o lixo"  sozinho?
Comment: O `using`, o `Dispose()` como você usou não será executado se houver uma exceção.
Answer: Uitilize o Garbage Collection:
GC.Collect();

mais informações:
https://msdn.microsoft.com/en-us/library/0xy59wtx(v=vs.110).aspx
Comment: Não, isso só agrava a situação: https://pt.stackoverflow.com/q/110854/101
Comment: interessante, obrigado
Answer: Consegui resolver o problema, com o seguinte código:
if (pictureBox1.Image != null)
{
   pictureBox1.Image.Dispose();
   pictureBox1.Image = null;
}

Refencia: Como definir imagens em tempo de execução (Windows Forms)


If substring in string, replace string with number

Question: I have the following mapping
mapping = {'sum12':2, 'sum6':1,
            'avg12':2, 'avg6':1,
            'diff':3, 'mean':4}

and I have a dataframe with variables like
        var1      var2
0  abc_sum12  mean_jkl
1   pqr_sum6  pqr_avg6
2   diff_xyz    qwerty

If any of the substrings are present in the strings in the dataframe, I want to replace them with their corresponding values. If no substring is present, I want to replace it with np.nan. At present, the only solution I can think of is going through every row, checking if any of the substrings is present in every string, and replacing it with the specific number corresponding with that substring. Is there a better way to do it.
The output in the end would be
   var1  var2
0     2   4.0
1     1   1.0
2     3   NaN

Answer: I believe if you replace using regex, it will partial match and give you the result you want.  The only exception is the qwerty value which will remain unchanged.  If you then coerce the entire df to numeric, it will return NaN for that value or any other non-numeric.
import pandas as pd
mapping = {'sum12':2, 'sum6':1,
            'avg12':2, 'avg6':1,
            'diff':3, 'mean':4}

df = pd.DataFrame({'var1': ['abc_sum12', 'pqr_sum6', 'diff_xyz'],
 'var2': ['mean_jkl', 'pqr_avg6', 'qwerty']})

df = df.replace(mapping, regex=True).apply(lambda x: pd.to_numeric(x, errors='coerce'))

print(df)

output
   var1  var2
0     2   4.0
1     1   1.0
2     3   NaN

Comment: I didn't know about df.replace, neat!
Comment: I didn't know about it either. That's pretty helpful.
Answer: Another approach:
mapping = {'sum12':2, 'sum6':1,
            'avg12':2, 'avg6':1,
            'diff':3, 'mean':4}

df = pd.DataFrame(
{'var1': {0: 'abc_sum12', 1: 'pqr_sum6', 2: 'diff_xyz'},
 'var2': {0: 'mean_jkl', 1: 'pqr_avg6', 2: 'qwerty'}})

df_new[:] = np.nan
df_new = df_new.astype('float')

for name,col in df.items():
    for key,val in mapping.items():
        df_new[name][col.str.contains(key)] = val

The resulting dataframe df_new:
   var1  var2
0   2.0   4.0
1   1.0   1.0
2   3.0   NaN

Comment: This works as well, but I was looking at transforming the entire df rather than going row by row. Thanks though!
Comment: @Tejas Technically, we're going column-by-column rather than row by row. In any case, you're welcome.
Comment: Oh right, sorry. In that case, this would work pretty well too!


Parser de data em C

Question: Estava fazendo uns testes para fazer parsers de data e fiz este exemplo baseado em um programa que formata através do sscanf() com uma string constante definida porem não entendi bem onde está o erro:
#include <cstring>
#include <iostream>

int main()
{
   int day, year;
   char weekday[20], month[20], dtm[100];

   printf
    (
     "\n\tDigite Dia Mes a ano em string"
     "\n\tex.(Saturday March 25 1989): "
    );

   scanf("%s80[^\n]",&dtm);

   sscanf(dtm, "%s %s %d  %d", &weekday, &month, &day, &year);

   printf("%s %d, %d = %s\n", month, day, year, weekday);

   return 0;
}

/*
 Input:
   Saturday March 25 1989

 Output:

  `l 0, 0 = Saturday

onde o Output deveria ser:
March 25 1989 Saturday
    */
Comment: Isso é uma pergunta ou uma resposta?
Comment: é uma pergunta queria entender qual o erro é que eu esqueci de descrever tentando formatar o codigo aqui mas nao consegui ai alguem formatou ele..
Comment: na verdade o output ai deveria ser:  March 25 1989  Saturday
Comment: Edite sua pergunta para ficar claro para todo mundo, isso deve atrair mais pessoas para responder.
Comment: Esse código nem compila. Pelo menos em um bom compilador.
Comment: C ou C++? Creio que você cometeu um ligeiro engano ao marcar a linguagem
Comment: @dark777 A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Comment: a resposta que me ajudou ja foi votada...
Answer: Isto não é exatamente um parse de data, é de uma string com 4 separações entre espaços que em tese os 2 últimos devem ser números, nada mais que isto.
Na verdade o erro está na entrada de dados. O padrão do scanf() está errado.
#include <stdio.h>

int main() {
    int day, year;
    char weekday[20], month[20], dtm[100];
    printf(
        "\n\tDigite Dia Mes a ano em string"
        "\n\tex.(Saturday March 25 1989): "
    );
    scanf("%[^\n]s80", dtm);
    printf("%s\n", dtm);
    sscanf(dtm, "%s %s %d  %d", weekday, month, &day, &year);
    printf("%s %d, %d = %s\n", month, day, year, weekday);
}

Veja funcionando no ideone, e no repl.it. Também coloquei no GitHub para referência futura.
Comment: agora sim deu certo... funfou legal na verdade eu me inspirei mais a procurar sobre isso baseado em um programa que tenho em linguagem D. como exemplo:  import std.format;

void main() {
    string s = "Name Surname 18";
    string name, surname;
    int age;
    formattedRead(s, "%s %s %s", &name, &surname, &age);
    // %s selects a format based on the corresponding argument's type
}
Comment: Ué, você removeu o `scanf()` inteiramente? Como é que os dados vão chegar na `dtm`?
Comment: @Wtrmute eu copiei o código errado :)

Parser de data em C


jtable not triggering to clicks made on custom action buttons

Question: My site is code in ASP.NET MVC 3.0.
with libraries:
jQuery 3.0.0,
jQuery Validation 1.17.0,
(I'm not sure which others can be useful mentioning).

My problem happens when testing in Internet Explorer 11, exactly when user press a button created as a "Custom Action" using jTable.org. This test happens in a Windows 2012 Server.
The same site tested on Firefox in same server is working without this or any other issue.

In IE, the regular buttons created by jTable for Create, Edit and Delete actions, are working.
This is the code for the View:
@model SuperSBL2.WebMVC3.ViewModels.HTEList

@{
    ViewBag.Title = "Administrar HTEs";
}

@section CssImport{

}

Administrar HTEs

    <form>
        Línea de Producción: <input type="text" name="ProductionLineName" id="ProductionLineName" />
        Area: <input type="text" name="AreaName" id="AreaName" />
        Operación: <input type="text" name="OperationName" id="OperationName" />

Modelo: <input type="text" name="ModelName" id="ModelName" />
        Tipo (ensameble/subensamble): <input type="text" name="HTETypeName" id="HTETypeName" />
        <button type="submit" id="LoadRecordsButton" class="btn btn-primary">Buscar registros</button>
    </form>

<button type="submit" id="GoBack" class="btn btn-default">REGRESAR</button>

@section scripts {

}

Now, this is the code for the _Layout.cshtml in use:
<!DOCTYPE html>
@{
    var jTableStyle = "metro/blue/jtable.css";
    if (!string.IsNullOrEmpty(Request["jTableStyle"]))
    {
        jTableStyle = Request["jTableStyle"];
    }
}

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Super Sistema Balanceo de Líneas - @ViewBag.Title - </title>

    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/themes/metroblue/jquery-ui.css")" rel="stylesheet" type="text/css" />

    @*<link href="@Url.Content("~/Content/highlight.css")" rel="stylesheet" type="text/css" />*@
    <link href="@Url.Content("~/Scripts/jtable/themes/" + jTableStyle)" rel="stylesheet" type="text/css" />

    <link href="@Url.Content("~/Scripts/syntaxhighligher/styles/shCore.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Scripts/syntaxhighligher/styles/shThemeDefault.css")" rel="stylesheet" type="text/css" />

    <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" />

    <link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/themes/base/core.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/themes/base/datepicker.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/themes/base/theme.css")" rel="stylesheet" type="text/css" />

    <link href="@Url.Content("~/Content/bootstrap-theme.min.css")" rel="stylesheet" type="text/css" />

    @RenderSection("CssImport", false)

@*    *@

    @Html.Partial("_NavBar")

        @RenderBody()

© @DateTime.Now.Year - Super Sistema Balanceo de Líneas

    @RenderSection("scripts", required: false)
    @RenderSection("CustomScripts", required: false)

This is a picture of system in Internet Explorer, displayed as expected:
page displayed in Internet Explorer
You can see the rendering is as expected, not issue on this area with Internet Explorer.

Red arrows indicates the buttons created as Custom Action, once pressed up, nothings happens. When the IE developer tools are displayed, I press the buttons indicated with Read arrows, nothing happens: not even an error in console, not even an error in Network tab, nothing at all. This is error I'm having.
Green arrows indicates the buttons created by jTable for EDIT, CREATE and DELETE actions as part of the grid. These buttons are working perfect. No issue on this area. See these pictures:

Page in IE showing modal for New record
Page in IE showing modal for Edit record

I hopes you guys can provide any idea.
Thanks,
Gerardo.
Comment: Please provide your code sample or jsfiddle.
Answer: This a complex senario, so I cannot replicate it.
I observe from your code, that you are adding click handlers via javascript in the button definitions. Have you tried applying the click handler via jQuery
display: function (data) {
    var $but = '';
    if (data.record) {
        $but = $('<button title=""  class="jtable-command-button glyphicon glyphicon-cog" ></button>');
        $but.click(transferAdmin(data.record.HTEHeaderId));
    }
    return $but;
}

I would also point out your original code was creating a button using the same id btnAdmin on every row of the table which is neither good practice or useful, so I have omitted that, as it is possibly another reason why IE gets confused.
Answer: Thanks @misterP for his reply. After having bad times with this, I managed to understand what was wrong, and fixed it.
Let me try to explain fixes to issue I was having.
1) Main problem was that in IE, my jQuery logic was not working, when it worked in Firefox and Chrome. I was not aware of IE compatilibity modes that are fixed with the meta tag at  level. So, on file _layout.chtml, I set the following:

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    ...

2) Regarding how I managed the functionality on the custom action, I read online that when working with jQuery targeting dynamic elements, we should start the filtering against a fixed tag --- hence I used ContainerForJTable. I declare a custom attribute seleccionable on the dynamic object:
    display: function (data) {
        if (data.record) {
            return '<button id="' + data.record.FileID + '"  class="jtable-command-button glyphicon glyphicon-eye-open seleccionable"></button>';
        }
    }

3) I wrote a function (outside of the jtable object creation --- $('#ContainerForJTable').jtable({..) to add an event to objects matching a filter using my custom attribute:
    $('#ContainerForJTable').on('click', '.seleccionable', function () {
        var theID = $(this).attr("id");
        //console.log("The id is " + theID);
        viewFiles(theID);
    });

After these changes, the jtables objects had been working without any issues.
thanks,


How do i solve this limit: $\lim_{x\to 0}{x-\sin(\sin(...(\sin x)))\over x^{3}}$

Question: I have the next limit :
$$\large \lim_{x\to 0}{x-\sin(\sin(\overbrace {\cdot \ \cdot \ \cdot }^n(\sin(x))\overbrace {\cdot \ \cdot \ \cdot }^n))\over x^{3}}$$
$\sin(\sin(...(\sin(x))...))$-is n times.
I have no idea. Someone can help me? Thank you!
Comment: Use L'hospital thrice
Comment: Related : https://math.stackexchange.com/questions/387333/are-all-limits-solvable-without-lh%C3%B4pital-rule-or-series-expansion
Answer: In a neighbourhood of the origin we have
$$ \sin(x)= x-\frac{x^3}{6}+O(x^5) \tag{1}$$
hence by applying $\sin(\cdot)$ to both terms and exploiting the sine addition formulas and $(1)$ we get
$$ \sin\sin(x) = x-\frac{x^3}{3}+O(x^5) \tag{2}$$
as well as
$$ \sin\sin\sin(x) = x-\frac{x^3}{2}+O(x^5)\tag{3} $$
and
$$ \sin^{[n]}(x) = x-\frac{nx^3}{6}+O(x^5)\tag{4} $$
by induction. It follows that:
$$ \lim_{x\to 0}\frac{x-\sin^{[n]}(x)}{x^3} = \color{red}{\frac{n}{6}}\tag{5}$$
Answer: $$\lim_{x \rightarrow 0}\frac{1-\cos(x)\cos(\sin(x))......\cos(\sin(\sin..(\sin(x)....))}{3x^2}$$
This tends to $\frac {0}{0}$ Use L'Hospital again
$$\lim_{x \rightarrow 0}\frac{\sin(x)(\cos(\sin(x))......\cos(\sin(\sin..(\sin(x)....)))+\sin(\sin(x)(.......)}{6x}$$
Basically, will give $\sin(x)$ oriented terms to provide you a $\frac{0}{0}$ again. Note: Numerator has $n$ terms
Now, again. when you use L'hospital, it will give you $n$ terms which will be  $\cos(x)$ oriented. Thus when $x\rightarrow 0$, these terms will $\rightarrow1$
giving you :
$$\frac{n}{6}$$ as the final answer
Answer: Let us rewrite
\begin{align}
\frac{x-\sin^{[n]}x}{x^3}&=\frac{x-\sin x+\sin x-\sin\sin x+\ldots+\sin^{[n-1]} x-\sin^{[n]} x}{x^3}=\\
&=\frac{x-\sin x}{x^3}+\frac{\sin x-\sin\sin x}{x^3}+\ldots+\frac{\sin^{[n-1]}x-\sin^{[n]}x}{x^3}
\end{align}
and calculte the limit of each fraction separately.

Since
$$
\sin t=t-\frac{t^3}{6}+o(t^3)
$$
we have the first fraction just as
$$
\frac{x-\sin x}{x^3}=\frac{\frac{x^3}{6}-o(x^3)}{x^3}=\frac16+o(x)\to\frac16.
$$
Similarly with notation $y=\sin^{[k-1]}x$ the $k$-th fraction is
$$
\frac{\sin^{[k-1]}x-\sin^{[k]}x}{x^3}=\frac{y-\sin y}{x^3}=\frac{y-\sin y}{y^3}\cdot\frac{y^3}{x^3}=\left(\frac16+o(y)\right)\cdot\left(\frac{y}{x}\right)^3\to\frac16\cdot 1^3=\frac16
$$
because
$$
\frac{y}{x}=\frac{\sin^{[k-1]}x}{x}=\frac{\sin^{[k-1]}x}{\sin^{[k-2]}x}\cdot\frac{\sin^{[k-2]}x}{\sin^{[k-3]}x}\cdot\ldots\cdot\frac{\sin x}{x}\to1\cdot 1\cdot\ldots\cdot 1=1.
$$
Finally the limit is
$$
\underbrace{\frac16+\frac16+\ldots+\frac16}_{n\text{ times}}=\frac{n}{6}.
$$


If the sum of two even integers is an even integer, what conclusion can you make about the difference of two odd numbers?

Question: "You can't make any conclusion from the 'if' statement, about the difference of two odd integers." That's what I said.
I tried to see if we could, from the equation "2m + 2n = 2(m + n)", have any equation of "m - n" (m and n being two odd integers here), but all I got was the truism "m + n = m + n".
No description
Solving the prompt with the new information given by fellow stack users
(Another correction: The result is 2(m - n); made a bad calculation there)
Comment: Looking at the image, I don't think it's asking you to make a conclusion from just the previous conclusion. You should be able to use other properties/facts as well. But I'm not so sure
Comment: I think it is a totally separate exercise, which follows the same patern as the one about the sum of even ntegers: write down some examples and then proof your 'conjecture': find the general form of a odd integer and then look at their difference. There is definitely an (interesting) conclusion to make :)
Comment: It's an awkwardly phrased question. "What conclusion..." has a meaning in regular language, and a more precise meaning in mathematics. If this is the *only* thing you know about even numbers, and that "odd" numbers are simply numbers that are not even numbers, then you are correct, there is nothing to be concluded.
Comment: But in the image, it's not clear you are being asked for a conclusion from the first result, but rather, what conclusion can you make via a similar process that let you conclude the first result.
Comment: If we want to be really picky, maybe: If $m$ and $n$ are odd, they are of the form $m = 2x + 1$ and $n = 2y + 1$. Let $a = 2x$ and $b = -2y$. Both $a$ and $b$ are even. By commutativity, distributivity and associativity, we have: $m - n = (2x + 1) - (2y + 1) = (2x - 2y) +1 - 1 = a + b$ which is an even number. This is all, of course, unnecessary.
Comment: Ok (to everyone). I'm working it; I'll post the picture for "critique".
Comment: @Student Added a new picture.
Comment: @swift: correct result, but you have a computational error: the term $-2$ should not be there.
Comment: @Student Corrected it. Another thing I'm working on, being thorough with "basic" computing that can render your whole operation false.
Comment: The question being asked is ambiguous IMO.  Give that a sum of even numbers is even; Odd is different  than even; and *nothing* else about the definitions of even or odd we can't conclude anything.  Even if we added that we knew all numbers are odd or even but never both.  We couldn't conclude anything.  But if we actually know the meaning of even and odds, we can very easily reach a conclusion that the difference is even.  Although it has nothing to do with the sum of evens being even.
Comment: Okay looking at the image, they are definitely *NOT* asking you what you can conclude from the sums of evens.   That are asking you to subtract some odds, notice a pattern, make a conjecture, and justify with deductive reasoning why the conjecture must be true.
Answer: Each odd integer $m$ can be represented by $m=2 m'+1$ (or equivanent $m'=\frac{m-1}2$).
Thus the difference of two odd integers is
$m-n=(2 m'+1)-(2n'+1)=2(m'-n')$. This is even for any numbers $m, n$.
Comment: Thank you. A quick question, if you don't mind: why did you choose to go with 2m' + 1 and 2n' + 1 to designate odd integers, as opposed to simply setting up the syllogism with m, and n...and saying: "given any two odd integers m and n, the difference m - n = 2k, k being the number obtained by dividing the result of m - n by 2" Then concluding that, given we can write m - n as the product of two and another number, that means the difference of any two odd integers m and n is an even number; couldn't we proceed as such?
Comment: @Swift : in this exercise I would not do it, since the main part is about showing that the 'odd parts' cancel out (and what you claim to be a proof is basically what you have to prove.)
Comment: You're right. But, since I knew the method only because I was inspiring myself from how they solved the "even integers problem", I was wondering if there was any reason to choose this specific set-up. @Student
Answer: We can employ the proposition that a sum of evens is even as follows:
$\qquad\ m,n$ odd $\,\Rightarrow\, m = j+1,\ n = k+1\,$ for even $\,j,k$
thus $\, m- n = j + (-k)$ is the sum of evens, so is even by the proposition.

More generally, $\bmod k\!:\,\  m\equiv a\equiv  n\,\Rightarrow\, m-n\equiv 0.\,$  Above is special case: $\,a=1,\, k= 2.$


recv does not return after udp socket closed in linux

Question: I am trying to write client server application using udp protocol, but I have problem with connection ending.
I open two sockets (one is a "server" and the other is a "client"), and while the server receiving from the client with async, the client send him one simple message that printed to the console.
After some sleep (to be sure the server will call again to recv) the client and server socket getting closed.
At this point I expected the recv will return -1 and the async will end.
But what actualy happen is that the recv stuck forever*.
If just before closing the socket I sending an empty package (sendToMakeExit variable set to true in the code), the recv return with that empty package, and only after next call it return -1, although the socket was closed in the first calling.
    const bool sendToMakeExit = false;
    const int port = 2000;
    const auto addr = "127.0.0.1";
    int serverSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    sockaddr_in target;
    target.sin_family = AF_INET;
    target.sin_port = htons(port);
    inet_pton(AF_INET, addr, &target.sin_addr);
    bind(serverSocket, (sockaddr *) &target, sizeof(target));
    auto readAsync = std::async(std::launch::async, [&serverSocket] {
        const int MAX_READ = 4096;
        char readBuf[MAX_READ];
        ssize_t actualRead;
        do {
            actualRead = recv(serverSocket, readBuf, MAX_READ, 0);
            if (actualRead > 0) {
                cout << readBuf << endl;
            }
        } while (actualRead != -1);
    });
    int clientSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    connect(clientSocket, (sockaddr *) &target, sizeof(target));
    this_thread::sleep_for(chrono::seconds(1));
    send(clientSocket, "test", 5, 0);
    this_thread::sleep_for(chrono::seconds(1));
    close(clientSocket);
    if (sendToMakeExit) {
        sendto(serverSocket, nullptr, 0, 0, (sockaddr *) &target, sizeof(target));
    }
    close(serverSocket);

*If I run this code in debug and create new breakpoint when the recv is stuck surprisingly the recv return with -1.
How can I getting the recv will return -1 when I close the socket?
Comment: BTW at least stream sockets return 0 when the peer has closed the other orderly
Comment: Your code is C++, why would you tag C?
Answer: Closing a socket does not guarantee that any function call in another thread that is still using that socket immediately returns. If you have calls that wait for data to come in, like recv(), select(), poll(), you must send some data to the socket for these calls to return. You do that in your code, but you don't actually exit when a zero-length UDP packet is received: change the end of the while-loop to:
} while (actualRead > 0);

However, I would recommend having a flag variable that indicates whether the thread should continue running or not, like so:
volatile bool running = true;

auto readAsync = std::async(std::launch::async, [&serverSocket, &running] {
    ...
    while (running) {
        ...recv()...
    }
});

...
running = false;
sendto(serverSocket, ...);
readAsync.wait();
close(serverSocket);

Note that I added a line to wait for readAsync to finish before closing the socket, in order to prevent any accidents from happening: there is a small window where the socket is invalidated, but readAsync might still call recv() on it. If you have even more threads, it might also happen that you close the socket in this thread, another thread opens a new socket and gets the same filedescriptor number as the one you just closed, and then the readAsync thread would use the wrong socket.
Comment: Maybe Windows does abort the `recv()` call when the socket is closed from another thread? There is nothing in the specifications for the `recv()` and `close()` functions that mention the behavior in a multi-threaded scenario, so it is up to the operating systems to decide how to handle it. Linux handles it by letting the `recv()` function wait indefinitely. See also: https://stackoverflow.com/a/6390101/5481471
Comment: "If you want the server to be notified when the client closes the UDP socket, you have to make the client send a packet that indicates that" - It's slightly more complicated than that. Since UDP is connectionless and delivery is not guaranteed, that "close" packet to the server might get lost and neither the server nor client would know that happened. So you need to design a protocol where each end acknowledge receipt and do re-sends if they don't get the expected replies (now you are close to implementing TCP). I suggest looking at [ENet](http://enet.bespin.org).
Comment: I know that udp is connectionless and I know that when I close the client there is no data that send to the server. but here I also close the **server** socket - the one that the recv operate on. that is why I expect that after closing the socket of the recv, the function will return because the socket get closed.
Comment: So I just need to always send data before closing the socket. Any idea why this behavior do not happen on windows?


Unconditional variance of MA(1)-GARCH(1,1) process

Question: Let $y_t = \Delta{p_t}$ denote a time series of asset log-returns, where $p_t$ are logarithmic prices; $y_t$ is generated by the conditionally heteroscedastic MA(1) process
$y_t = \epsilon_t + \theta \epsilon_{t-1}$,  where $\epsilon_t = \sqrt{h_t}z_t$ and
$z_t\sim i.i.d N (0,1) $ with $|\theta|<1$,
$h_t = \omega+\alpha \epsilon_t^2+\beta h_{t-1},\quad \omega>0, \alpha>0 ,\alpha+\beta<1$.

Derive the expressions for the unconditional mean $E(y_t)$, unconditional variance $Var(y_t)$ and autocorrelation function of $y_t, \rho(k),k=1,2,.....$

I computed the unconditional mean being equal to 0 because $E(\sqrt{h_t} z_t)+\theta E(\sqrt{h_{t-1}}z_{t-1})=0 $
for the unconditional variance $Var(y_t)= E(y_t^2)= (h_t z_t^2+\theta^2 h_{t-1} z_t^2)$ = $E(h_t+\theta^2 h_{t-1})$ because $z_t\sim i.i.d N (0,1)$.
From now on I am not sure. Should I substitute $h_t$ to be done?
Any help would be really appreciated.
Comment: I think that should be $\alpha \epsilon^2_{t-1}$ in your definition of $h_t$.
Comment: Consider adding a [`self-study`](https://stats.stackexchange.com/tags/self-study/info) tag.
Answer: So far so good.
To obtain an expression for the unconditional variance, you need to work out $\mathbb{E}(\epsilon_t^2) =\mathbb{E}(h_t)$. Call this $\sigma^2_t$.
Substituting in $h_t$ as you suggested gives
$$
\sigma^2_t = \mathbb{E}(\omega + \alpha \epsilon_{t-1}^2 + \beta h_{t-1}) = \omega + (\alpha + \beta) \sigma^2_{t-1}
$$
Now substitute in $\sigma^2_{t-1}$. Can you see what's going to happen?
Comment: Introducing $\sigma_t^2$ in addition to $h_t$ seems superfluous and perhaps even confusing, since both refer to the same object. Also, the notation of your expectation operators does not suggest they are conditional, but your second paragraph seems to imply they are.
Comment: is the variance equal to $\frac{\omega}{1-\alpha-\beta}+\theta^2 \frac{\omega}{1-\alpha-\beta}$?


iPhone dev - I have a bunch of addresses and want to plot them all in a MapView

Question: I've heard that there is no supported forward geocoding in corelocation. Can someone please guide me in the right direction to how I could figure this out? I've tried downloading a third party forward geocoding thing and I couldn't get it to work. Please help.
Answer: Try to get the location data from The Google Geocoding API and point the results to the map.
Answer: Check validity of address with Geocoding on iPhone
Refer to this link. Once you get coordinates, you can add annotations.


Action of $\text{PSL}(2,q)$ on the projective line: How to know if $(az+b)/(cz+d)$ belongs to $\text{PSL}(2,q$)?

Question: The special linear group $\text{PSL(2,$\mathbb{F}$) }$ over the finite field $\mathbb{F}$ acts on the projective line $\mathbb{F}\cup \{\infty \}$ by the way
$$ \text{z $\to $ }\frac{a\cdot z+b}{c\cdot z+d} $$
However, how to know if this transformation belongs to $\text{PSL(2,$\mathbb{F}$)}$ in the case $-\mathbf{1}$ is a square in $\mathbb{F}$?
So, let $-\mathbf{1}=\alpha ^2$ and let, for instance, $\text{z $\to $ }\frac{1}{z}=\frac{\alpha }{\text{$\alpha $z}}$.  Although it is the same transformation in both cases, the first case represent the matrix with determinant  $-\mathbf{1}$, and the second with determinant $\mathbf{1}$. Does this example belong to $\text{PSL(2,$\mathbb{F}$) }$ or not?
Answer: It does belong to $\operatorname{PSL}(2,\mathbb F)$. The matrices $M=\begin{pmatrix}a&b\\ c&d\end{pmatrix}\in \operatorname{SL}(2,\mathbb F)$ and $\alpha M\in\operatorname{GL}(2,\mathbb F)$ induce the same element of $\operatorname{PGL}(2,\mathbb F)\geq\operatorname{PSL}(2,\mathbb F)$, and it happens to be in $\operatorname{PSL}(2,\mathbb F)$.
It's enough that there is one matrix in $\operatorname{SL}(2,\mathbb F)$ which induces the given transformation. Not every matrix in $\operatorname{GL}(2,\mathbb F)$ which induces the same transformation has to be in $\operatorname{SL}(2,\mathbb F)$.


How to use the Postgres any-clause with JPA/Hibernate native queries (array parameters)

Question: So we've got a whole lot of Postgres SQL queries stored in files and used from PHP. The task is to replace PHP with Java. We want to reuse as much of the queries "as is" to keep the migration path short. I can't get the Array parameters to work.
Here's a query example:

update user_devices
set some_date = now()
where some_id in (
    select distinct some_id from user_devices
    where user_id = any(:userIDs) and device_id = any(:deviceIDs)
    and exists (select 1 from users where user_id = any(:userIDs) and customer_id = :customerID)
);

Note the "any" clauses, which cause the problem, because they expect an array type.
This is how we used them from PHP:

$this->allValues['userIDs'] = '{' . implode ( ",", $userIdNodes ) . '}';
$this->allValues['deviceIDs'] = '{' . implode ( ",", $deviceIdNodes ) . '}';
$this->allValues['customerID'] = customerID;
$this->db->runQuery ( $this->getQuery ( 'my_query' ), $this->allValues );

So as parameters the array types look like "{111,222}".
This is what I tried in Java:

    Integer customerID = 1;
    int[] userIDs  = new int[]{111,222};
    int[] deviceIDs= new int[]{333,444};
    //List<Integer> userIDs  = Arrays.asList(111,222);
    //List<Integer> deviceIDs= Arrays.asList(333,444);
    //java.sql.Array userIDs  = toArray("integer", new int[]{111,222}));
    //java.sql.Array deviceIDs= toArray("integer", new int[]{333,444}));
    //java.sql.Array userIDs  = toArray("integer", Arrays.asList(111,222)));
    //java.sql.Array deviceIDs= toArray("integer", Arrays.asList(333,444)));
    //String userIDs  = "{111,222}";
    //String deviceIDs= "{333,444}";
    //String userIDs  = "ARRAY[111,222]";
    //String deviceIDs= "ARRAY[333,444]";

    Query nativeQuery = em.createNativeQuery(queryString);
    nativeQuery.setParameter("userIDs", userIDs);
    nativeQuery.setParameter("deviceIDs", deviceIDs);
    nativeQuery.setParameter("customerID", customerID);
    //nativeQuery.setParameter(createParameter("userIDs",java.sql.Array.class), userIDs);
    //nativeQuery.setParameter(createParameter("userIDs",java.sql.Array.class), deviceIDs);
    //nativeQuery.setParameter(createParameter("customerID", Integer.class), customerID);
    query.executeUpdate();

//[...]
private Array toArray(String typeName, Object... elements) {
    Session session = em.unwrap(Session.class); // ATTENTION! This is Hibernate-specific!
    final AtomicReference<Array> aRef = new AtomicReference<>();
    session.doWork((c) -> {
        aRef.set(c.createArrayOf(typeName, elements));
    });
    return aRef.get();
}

private <T> Parameter<T> createParameter(final String name, final Class<?> clazz) {
    return new Parameter<T>() {
        @Override
        public String getName() {
            return name;
        }
        @Override
        public Integer getPosition() {
            return null; // not used
        }
        @Override
        public Class<T> getParameterType() {
            return (Class<T>) clazz;
        }
    };
}

None of these will work I will get one of these exceptions:
When using the "toArray" method:
Caused by: org.hibernate.HibernateException: Could not determine a type for class: org.postgresql.jdbc4.Jdbc4Array
    at org.hibernate.internal.AbstractQueryImpl.guessType(AbstractQueryImpl.java:550)
    at org.hibernate.internal.AbstractQueryImpl.guessType(AbstractQueryImpl.java:534)
    at org.hibernate.internal.AbstractQueryImpl.determineType(AbstractQueryImpl.java:519)
    at org.hibernate.internal.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:487)
    at org.hibernate.jpa.internal.QueryImpl$ParameterRegistrationImpl.bindValue(QueryImpl.java:247)
    at org.hibernate.

Or when using int[] or Strings, I'll get:
Caused by: org.postgresql.util.PSQLException: ERROR: op ANY/ALL (array) requires array on right side
  Position: 137
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1998)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:570)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:420)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:366)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.postgresql.ds.jdbc23.AbstractJdbc23PooledConnection$StatementHandler.invoke(AbstractJdbc23PooledConnection.java:453)
    at com.sun.proxy.$Proxy274.executeUpdate(Unknown Source)
    at com.sun.gjc.spi.base.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:125)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
    jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:582)

Using Wireshark I found this when both APIs are talking to the database:
Image: Comparison of database calls with Wireshark
select oid, typname from pg_type where oid in (0, 23, 1043) order by oid;

oid   |typname
------+-------
23    |int4
1043  |varchar

Has anyone managed to use array-parameters with native queries using Hibernate as backend for the JPA EntityManager? If so: How?
Answer: Change your query from where user_id = any(:userIDs) to where user_id IN (:userIDs), and change the userIDs array to a collection e.g. List<Long>. You will have to additionally protect it empty lists, but it will work.
Answer: I was able to work around this problem by unwrapping the Hibernate session from the EntityManager and use a JDBC PreparedStatement, which eats the java.sql.Array parameters without any complaint.
The NamedParameterStatement used in the example below is described here (I've modified it to my needs). It delegates to a PreparedStatement.
The rest of the code goes a little something like this:
public int executeUpdate(...){
    //....
    Integer customerID = 1;
    java.sql.Array userIDs  = toArray("integer", new int[]{111,222}));
    java.sql.Array deviceIDs= toArray("integer", new int[]{333,444}));

    final AtomicInteger rowsModifiedRef = new AtomicInteger();
    final Session session = em.unwrap(Session.class); // ATTENTION! This is Hibernate-specific!
    session.doWork((c) -> {
        try (final NamedParameterStatement statement = new NamedParameterStatement(c, queryString)) {
            statement.setObject("deviceIDs", userIDs);
            statement.setObject("userIDs", userIDs);
            statement.setObject("customerID", userIDs);
            rowsModifiedRef.set(statement.executeUpdate());
        }
    });
    return rowsModifiedRef.get();
}

private Array toArray(String typeName, Object... elements) {
    Session session = em.unwrap(Session.class); // ATTENTION! This is Hibernate-specific!
    final AtomicReference<Array> aRef = new AtomicReference<>();
    session.doWork((c) -> {
        aRef.set(c.createArrayOf(typeName, elements));
    });
    return aRef.get();
}


How to convert from lighttpd mod_fastcgi to Apache 2.2 mod_fcgid

Question: I have a Python script which contains:
from flup.server.fcgi import WSGIServer

def processRequest(environ, start_response):
    # proprietary business logic here
    return

WSGIServer(
    application = processRequest,
    bindAddress = ('0.0.0.0', 6543),
    umask = 0
    ).run()

I run this Python script from the command line on an ubuntu 12.04.2 LTS server with Python 2.7.3.
On that same server, I have lighttpd version 1.4.28 configured with
server.modules = (
    "mod_access",
    "mod_alias",
    "mod_compress",
    "mod_redirect",
    "mod_setenv",
    "mod_fastcgi",
    "mod_accesslog"
)

$SERVER["socket"] == ":443" {
    ssl.engine = "enable"
    ssl.pemfile = "/etc/lighttpd/ssl/secret.pem"
    server.document-root = "/var/www"

    fastcgi.server = (
            "/MyFCGI/" =>
            ((
                "host" => "127.0.0.1",
                "port" => 6543,
                "check-local" => "disable"
            ))
    )
}

When I request https://TheEffKyouDeeEnn/MyFCGI/blah/blahblah as a POST with a JSON object, the system behaves the way I would expect and passes my request through to the Python script running on the command line.
I need to configure that same functionality on an MS-Windows Server machine running Apache 2.2. I want to preserve the ability to deploy my Python script anywhere on the network, instead of only on the server with the Apache instance. Although the documentation seems to indicate that's possible, using at least mod_fcgid, I can't make it work myself and can't find a working example.
Can you confirm that mod_fcgid is the appropriate module and give an example of how to configure Apache and mod_fcgid to duplicate my lighttpd behavior?
Comment: http://httpd.apache.org/mod_fcgid/mod/mod_fcgid.html has examples for apache configs. That said, this question probably belongs on ServerFault
Answer: This duplicates the same functionality with Apache2.2.

    LoadModule fastcgi_module /usr/lib/apache2/modules/mod_fastcgi.so
    LoadModule headers_module /usr/lib/apache2/modules/mod_headers.so

    VirtualHost *:80

        DocumentRoot /var/www/

        Header set Access-Control-Allow-Origin "*"
        Header set Access-Control-Allow-Headers "Content-type"
        Header set Access-Control-Allow-Methods "POST,GET,OPTIONS"

        AliasMatch ^/MyFCGI/.*$ /var/my_fcgi.py

        Directory /MyFCGI/
            Options FollowSymLinks +ExecCGI
            AllowOverride All
            SetHandler fastcgi-script
        /Directory

         FastCgiExternalServer /var/my_fcgi.py -host localhost:6543

    /VirtualHost


Flex-box is stretched out

Question: In this example, I am trying to make an image gallery the problem is that the boxes from 1 to 9 are stretched down as you can see in the snippet.
I want to set them with a fixed size.
I tried align-content and align-items and still no result.
If I change the size of the browser the boxes are back to normal like this

const menu = document.querySelectorAll('.inner .box');
const cursors = document.querySelectorAll('.cursor')

cursors.forEach( c => {
  c.addEventListener('click', () =>{
    for(let i = 0; i < menu.length; i++){
      if(menu[i].classList.contains('scale')){
        if(c.innerText == "<"){
          if(i == 0){
            menu[0].classList.remove('scale')
            menu[menu.length - 1].classList.add('scale')
            break
          }
          menu[i].classList.remove('scale')
          menu[i-1].classList.add('scale')
          break
        }
        else if(c.innerText == ">"){
          if(i == menu.length - 1){
            menu[i].classList.remove('scale')
            menu[0].classList.add('scale')
            break
          }
          menu[i].classList.remove('scale')
          menu[i+1].classList.add('scale')
          break
        }
      }
    }
  });
});
body{
  height:90vh;
  background-image: radial-gradient( circle farthest-corner at 10% 20%,  rgba(0,93,133,1) 0%, rgba(0,181,149,1) 90% );
  background-repeat: no-repeat;
  animation: GradientAnimated 59s ease infinite;
}

.container{
  margin-top: 10vh;
  display: flex;
  padding:-1px;
  width: 100vw;
  align-items: center;
  justify-content: space-around;
}
.container.inner{
  margin-top:0;
  width: 50vw;
  height: 40vh;
  border: 2px solid black;
  align-items: center;
  justify-content: center;

}
.box{
  width: 15vw;
  height: 40vh;
  color: white;
  text-align: center;
  font-size: 4vw;
}

.box1{background-color:#f00;}
.box2{background-color:#fa0;flex-grow:1;}
.box3{background-color:#ff0;}
.box4{background-color:#080;}
.box5{background-color:#00f;}
.box6{background-color:#6ae;}
.box7{background-color:#90d;}
.box8{background-color:#408;}

.box.scale:hover{
  cursor: pointer;
}

.cursor{
  color: #222;
}

.cursor:hover{
  cursor: pointer;
  animation: shake 1s cubic-bezier(.36,.07,.19,.97) both infinite;
}

.scale{
  box-sizing: content-box;
  border: 2px solid black;
  animation-name: Scale;
  animation-timing-function:ease;
  animation-duration: 1s;
  animation-iteration-count:1;
  animation-fill-mode: forwards;
}

@keyframes Scale{
  from{transform: scale(1);}
  to{transform: scale(1.5);}
}

@keyframes shake {
  10%, 90% {
    transform: translate3d(-1px, 0, 0);

  }

  20%, 80% {
    transform: translate3d(2px, 0, 0);
  }

  30%, 50%, 70% {
    transform: translate3d(-4px, 0, 0);
  }

  40%, 60% {
    transform: translate3d(4px, 0, 0);
  }
}

@keyframes GradientAnimated {
    0%{background-position:0% 10%}
    50%{background-position:100% 91%}
    100%{background-position:0% 10%}
}

    <

1

2

3

4

5

6

7

8

>

Comment: You have `height: 40vh;` wouldn't that be the issue ? *If I change the size of the browser the boxes are back to normal like this* because `vh` is relative to the viewport
Answer: Use max-height instead of height otherwise it will use that height.

const menu = document.querySelectorAll('.inner .box');
const cursors = document.querySelectorAll('.cursor')

cursors.forEach(c => {
  c.addEventListener('click', () => {
    for (let i = 0; i < menu.length; i++) {
      if (menu[i].classList.contains('scale')) {
        if (c.innerText == "<") {
          if (i == 0) {
            menu[0].classList.remove('scale')
            menu[menu.length - 1].classList.add('scale')
            break
          }
          menu[i].classList.remove('scale')
          menu[i - 1].classList.add('scale')
          break
        } else if (c.innerText == ">") {
          if (i == menu.length - 1) {
            menu[i].classList.remove('scale')
            menu[0].classList.add('scale')
            break
          }
          menu[i].classList.remove('scale')
          menu[i + 1].classList.add('scale')
          break
        }
      }
    }
  });
});
body {
  height: 90vh;
  background-image: radial-gradient( circle farthest-corner at 10% 20%, rgba(0, 93, 133, 1) 0%, rgba(0, 181, 149, 1) 90%);
  background-repeat: no-repeat;
  animation: GradientAnimated 59s ease infinite;
}

.container {
  margin-top: 10vh;
  display: flex;
  padding: -1px;
  width: 100vw;
  align-items: center;
  justify-content: space-around;
}

.container.inner {
  margin-top: 0;
  width: 50vw;
  height: 40vh;
  border: 2px solid black;
  align-items: center;
  justify-content: center;
}

.box {
  width: 15vw;
  max-height: 40vh; /*  you need to add max-height instead of height */
  color: white;
  text-align: center;
  font-size: 4vw;
}

.box1 {
  background-color: #f00;
}

.box2 {
  background-color: #fa0;
  flex-grow: 1;
}

.box3 {
  background-color: #ff0;
}

.box4 {
  background-color: #080;
}

.box5 {
  background-color: #00f;
}

.box6 {
  background-color: #6ae;
}

.box7 {
  background-color: #90d;
}

.box8 {
  background-color: #408;
}

.box.scale:hover {
  cursor: pointer;
}

.cursor {
  color: #222;
}

.cursor:hover {
  cursor: pointer;
  animation: shake 1s cubic-bezier(.36, .07, .19, .97) both infinite;
}

.scale {
  box-sizing: content-box;
  border: 2px solid black;
  animation-name: Scale;
  animation-timing-function: ease;
  animation-duration: 1s;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
}

@keyframes Scale {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(1.5);
  }
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}

@keyframes GradientAnimated {
  0% {
    background-position: 0% 10%
  }
  50% {
    background-position: 100% 91%
  }
  100% {
    background-position: 0% 10%
  }
}

    <

1

2

3

4

5

6

7

8

>

Answer: For the styling of the boxes either use, fixed units for height or use max-height instead of height.
It should either look like this:-
.box{
height: 300px;
}

Or it should look like this:-
.box{
max-height: 40vh;
}

Using the max-height method is more preferable because you don't have to define other flex properties like Shrink And Grow.

Flex-box is stretched out


Como acessar uma propriedade de um objeto para compor o valor de outra propriedade?

Question: Estou tentando acessar a propriedade nome com this.nome na propriedade frase e estou recebendo o valor undefined.
Gostaria de saber porque não estou recebendo o valor que atribuí.

let livro = ['O senhor dos anéis', 1954, 'J. R. R. Tolkien'];

let objeto = {
    nome: livro[0].toUpperCase(),
    totalAnos: 2050 - livro[1],
    frase: this.nome + ' por ' + livro[2],
};

console.log(objeto);

Saída:
{
  "nome": "O SENHOR DOS ANÉIS",
  "totalAnos": 96,
  "frase": "undefined por J. R. R. Tolkien"
}

Comment: Se uma das respostas abaixo resolveu o seu problema e não restou nenhuma dúvida, escolha a que você mais gostou e marque-a como correta/aceita ao clicar no "✅" que está ao lado dela, o que também marca a sua pergunta como resolvida. Se ainda te resta alguma dúvida ou gostaria de maiores esclarecimentos, fique à vontade para comentar.
Answer: Diferente do que ocorre em uma função construtora, dentro do contexto duma expressão de objeto literal a variável this é ligada ao objeto global(em strict mode this tem seu valor undefined).
Então quando faz frase: this.nome + ' por ' + livro[2] o valor de this no navegador será o objeto Window enquanto no Node.js será o objeto global, o que causa o comportamento percebido na pergunta.
Porém, dentro do contexto de um método ou getter/setter this é ligado valor do objeto proprietário do método, ou getter/setter, chamado.

Getter é a sintaxe get que associa a uma propriedade de um
objeto a uma função que será chamada quando tal propriedade é lida.
Setter é sintaxe set que associa a uma propriedade de um
objeto uma função para ser chamada quando houver tentativa de definir
valor para essa propriedade.

Apenas modifique a propriedade frase para que seja um getter, que this dentro  do contexto da função associada será ligado ao objeto proprietário da propriedade.

let livro = ['O senhor dos anéis', 1954, 'J. R. R. Tolkien']

let objeto = {
  nome: livro[0].toUpperCase(),
  totalAnos: 2050 - livro[1],
  get frase() {
    return this.nome + ' por ' + livro[2]
  },
}

console.log(objeto)
Answer: Você não pode se referir ao próprio objeto no momento da declaração. Seria preciso fazer algo assim:

let livro = ['O senhor dos anéis', 1954, 'J. R. R. Tolkien']
let objeto = {
    nome: livro[0].toUpperCase(),
    totalAnos: 2050 - livro[1],
}
objeto.frase = objeto.nome + ' por ' + livro[2]
console.log(objeto)


Why does thunderbird move the style of the html header?

Question: I am creating responsive email templates, I use Thunderbird to send some tests.
In most email clients it works very well. However in Gmail the styles are not applied.
Checking the CSS support I found that gmail only supports

Hi Pierce,

        This text is blue if the window width is
        below 500px and red otherwise.

Jerry

Knowing this, I implanted my styles inside the head, however, the styles were not applied in GMAIL.
After researching on various forums and breaking my head I couldn't find the solution, so I checked the obvious, it turns out that Thunderbird moves the

When I send the template through mailutils, the behavior is as expected and the styles work correctly in gmail

X-Mailer: mail (GNU Mailutils 3.7)

Hi Pierce,

        This text is blue if the window width is
        below 500px and red otherwise.

Jerry

View of gmail:

How to prevent thunderbird from moving the style to the body?
I am using Thunderbird 78.7.1, Ubuntu 20.04.2 LTS
Comment: @gwally Re MailChimp, what you said could imply you can't use custom templates at all. So, they let you use custom templates, but they don't help you fix your code if that's the way you go.
Comment: I would suggest using an email service like mailchimp to send your emails. Its free for limited number of contacts. Thunderbird is an email client. If you send an email from MailChimp and open in thunderbird, you will see it renders very similar to Gmail.
Comment: Most email clients rewrite emails when they send or receive. They strip out tags the client does not support. Others like Gmail rewrite the entire email. I would go with advice from  @Syfer with one caveat. MailChimp does not support custom templates and also rewrites  HTML code. I would suggest another provider.
Comment: @Nathan I appreciate the clarification. Yes, you can use custom templates on MailChimp, but they modify your template and offer no technical support if you run into an issue.
Comment: If you can't use an actual ESP to send your tests, try a service like [useparcel.com](https://useparcel.com).

Note: ironically, Thunderbird has recently dropped support for `@media` queries, so HTML emails are no longer responsive in it right now (see [caniemail.com](https://www.caniemail.com/features/css-at-media/))
Comment: Thank you very much for your comments. I fixed it by simply downloading the plugin [ThunderHTMLedit](https://addons.thunderbird.net/en-US/thunderbird/addon/thunderhtmledit/) and it works as expected
Answer: Apparently this strange behavior occurs when the HTML code is inserted from the thunderbird options

To avoid this behavior you must use the plugin ThunderHTMLedit and insert the HTML template from the HTML tab when composing the email
Answer: There is an add-on, CustomCSS, for Thunderbird that adds CSS to the .
I have personally tried it and it works :)
There are two downsides to the add-on.
a) It applies to all email accounts, cannot customize per account.
b) The editor is very basic (cannot use a CSS file).
Link to the add-on:
https://addons.thunderbird.net/en-US/thunderbird/addon/customcss/
Screenshot


Rails 4.2 has_many through in-place editing nested form with xeditable

Question: I have the following list of models in a Rails 4.2 app:

User
Company
Marketplace

The associations look like the following:
User.rb
class User < ActiveRecord::Base
end

Company.rb
class Company < ActiveRecord::Base

  has_many :company_marketplaces
  has_many :marketplaces, through: :company_marketplaces

  accepts_nested_attributes_for :marketplaces, update_only: true
end

Marketplace.rb
class Marketplace < ActiveRecord::Base
  has_many :company_marketplaces
  has_many :companies, through: :company_marketplaces
end

I am trying to build a form to allow adding/removing marketplaces to a company with the help of in-place editing library x-editable. I was able to allow adding new marketplaces from an existing list but it fails on the removing because no data is submitted.
This is the relevant part of the view:
index.html.slim
        td
          = link_to company.marketplaces.join(", "), "", data: { :"name" => "marketplaces_attributes" , :"xeditable" => "true", :"url" => admin_agents_company_path(company), :"pk" => company.id, :"model" => "company", :"type" => "checklist", :"placement" => "right", :"value" => company.marketplaces.join(", "), :"source" => "/marketplaces" }, class: "editable editable-click"

And companies_controller.rb#update method looks like the following:
companies_controller.rb
def update
  respond_to do |format|
    if @company.update(company_params)
      format.html { redirect_to @company, notice: 'Company was successfully updated.' }
      format.json
      format.js
    else
      format.html { render :edit }
      format.json { render json: @company.errors, status: :unprocessable_entity }
      format.js
    end
  end
end

Most of the resources I was able to find do not deal with in-place editing or use fields_for to work with nested_forms.
Is there a solution to handle adding/removing has_many: through: associated objects in a form without relying on fields_for?
Thanks
Answer: You can provide marketplaces_attributes in params.
Example from: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
class Member < ActiveRecord::Base
  has_many :posts
  accepts_nested_attributes_for :posts
end

params = { member: {
  name: 'joe', posts_attributes: [
    { title: 'Kari, the awesome Ruby documentation browser!' },
    { title: 'The egalitarian assumption of the modern citizen' },
    { title: '', _destroy: '1' } # this will be ignored
  ]
}}

member = Member.create(params[:member])
member.posts.length # => 2
member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
member.posts.second.title # => 'The egalitarian assumption of the modern citizen'

Read more examples in that link above