Can't install my own Firefox AddOn (File seems to be corrupt)

Question: can't install my own Extension on Firefox 64. I tested it succesfully in debug mode. Now I have big problems while installing: Corrupted! I don't know what to do. Studied all documentation. No success. I zipped the whole folder with all files and renamed it into *.xpi!
File structure
icons/cancel.png
close.js
install.rdf
install.xpi
manifest.json

close.js

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
      if ((new Date().getTime() - start) > milliseconds){
        break;
      }
    }
  }

sleep(1000);
if (
    (
      document.documentElement.textContent || document.documentElement.innerText
    ).indexOf('Live your life') > -1
  ) {
    window.close();
}

manifest.json
    {
    "manifest_version": 2,
    "name": "pm",
    "version": "1.0",
    "description": "Schließt nach 121 Sekunden",
    "content_scripts": [
      {
        "matches": ["*://*/"],
        "js": ["close.js"]
      }
    ],
    "icons":
        {
            "64": "icons/cancel.png"
        }
    }

install.rdf
<?xml version="1.0"?>

<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
     xmlns:em="http://www.mozilla.org/2004/em-rdf#">

  <Description about="urn:mozilla:install-manifest">
    firstname.lastname@example.com
    1.0
    2

      <Description>
        {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
        1.5
        64.*
      </Description>

    sample
    A test extension
    Your Name Here
    http://www.example.com/
  </Description>
</RDF>

Comment: You should use the "edit question" feature to add new details to your question instead of adding multiple answers. If you answer your own question, others will be less inclined to provide their own. Always be clear with your question and remember SO is not a 'bug-fixing' service!
Answer:
No install.rdf needed
Unique identifier needed, see mozilla forum for further infos
LogOn and Register the Addon in the developer Forum Mozilla.


Can I disable a cookie from being sent automatically with server requests?

Question: I'm fairly new to website development. I'm working on a site where the user logs in with username/password, and gets a sessionID from the server in response. This sessionID is sent back to the server (and a new one returned) with each request.
I'd like the site to work properly if the user opens it in multiple tabs or windows. i.e. once logged in at one tab, opening a members-only URL in another tab works without loggin in. (And, logging out in one tab logs out from all.) I see no way of doing this without storing the latest sessionID in a cookie. That way the latest sessionID can be "shared" among all tabs.
However I am starting to read up on cookies, and some of the security threats. I was unaware that cookies were sent with every request. I don't need to send my cookie to the server, ever. The sessionID is added to the xhr request's headers -- not read as a cookie. So I'm wondering if there is a way to disable sending of this cookie. My only purpose for it is to allow multiple tabs/windows in the same browser to share the same session.
I was reading up on the path parameter for cookies. Apparently this can be used to restrict when the cookie is sent to a server? What if I set the path to something that would never be used? Would this prevent the cookie from ever being sent out automatically? I only want to access it from JavaScript.
A coworker has put a lot of safeguards into the server-side of this application, which I won't go into here. So this question is just about what client-side precautions I can and should take, particularly with cookies, for optimal security. If there is a better way to allow a members-only site to work properly with multiple tabs open at once, I'm all ears.
Answer: I discovered just now that in HTML 5 there is local storage, which stores key/value pairs much like a cookie, but is not sent with every server request. Since it's supported in every browser except IE 7 and earlier, I'll be switching to this to enable sharing data between tabs when available, and use cookies instead on IE 7 and earlier.
Comment: localStorage is indeed a good solution, but its important to notice that localStorage is not shared between http and https, while cookies do. so if you have mixed pages that won't work.
Comment: Also localStorage is not available in Private browsing mode on Safari. You have to fall back to cookies.
Comment: @AlexanderBurakevych localstorage works fine in private browsing mode, but of course storage is cleared when the session ends, as opposed to being persisted.
Answer: The sessionID is stored in a cookie already there's no need to manage it.  Because the HTTP protocol is stateless the only way to maintain state is through a cookie.  What happens when you set a session value the server will look up the dictionary of items associated with that cookie id (session Id).
What is meant by stateless is that between requests HTTP does not know if your still alive or have closed your browser.  Therefore with each request the browser will attach all cookie values to the request on the domain.  SessionId is stored in the cookie automatically when they go to your site.  The Server then uses that value to look up anything you've set in the users session.
Depending on which programming language and/or server you're using the session could be handled differently but that's usually abstracted away from the programmer.
Now with respect to sessions, there are a number of different things that make them insecure.  For example if an attacker were able to get their hands on your session cookie value they could replay that cookie and take over your session.  So sessions aren't a terribly secure way of storing user information.  Instead what most people do is create an encrypted cookie value with the users details, the cookie could be a "session cookie" meaning as soon as the user closes their browser window the cookie is thrown away from the browser.  The encrypted cookie contains user information and role information as well as some identifier (usually the clients ip address) to verify that the user who is submitting the request is the same user the cookie was issued to.  In most programming languages there are tools that help in abstracting that away as well (such as the ASP.NET membership provider model).
Check out some details on the HTTP protocol and HTTP cookies on Wikipedia first

http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
http://en.wikipedia.org/wiki/HTTP_cookie

and check out the membership provider model on ASP.NET, it's a really good tool for helping to secure your site.
http://msdn.microsoft.com/en-us/library/sx3h274z(v=vs.100).aspx
Comment: Thanks for the information, but the specific question I'm trying to ask is "What is the standard way to allow a user to access a site using multiple tabs or windows, but without having to log in again for each new tab/window he opens?" I use a cookie for this. Is that the normal way?
Comment: @VernJensen Yes as stated typically that is to use some sort of encrypted cookie with the users member information in there.  If you're using something like ASP.NET you can use the membership provider model which does that for you.
Answer: Preventing the browser sending cookies seems to defeat the object of using cookies in the first place.
If you don't want the sessionID to be sent with each request, why set the cookie? A better solution would be to use a custom response header that you send from the server to the browser - this will then be under your control and will not be sent automatically with all browser requests. You are using request headers to send your sessionID anyway so you could receive them from the server using a custom header and read this into your JavaScript from each XHR.
Comment: The point of using a cookie is to allow the members-only area of the website to be shared across multiple tabs or windows in the same browser. (So you don't have to log in again each time you open a new tab.) What is the proper way to do this, if not using a cookie? That's the question I'm trying to ask.
Comment: > "I don't need to send my cookie to the server, ever." Not quite true then, as you'll need this for the multiple tab support. Anyway, your local storage option you mentioned might be the way to go. Good luck!


Calculate Audio file duration

Question: I am using Drupal url field in which I input any external url of an MP3 file hosted on Twilio Server and I then use html5 audio tag to render it as an audio file in node display. Everything looks fine until my client asked me to calculate the duration of the audio and display it as a column in my views.
Is there any way I can achieve this?
Thanks!
Answer: getID3 can be used to calculate the size of the file.
<code>$fileinfo = getID3_analyze(drupal_realpath($name2));
$playtime_sec = round($fileinfo['playtime_seconds'] / 60);

//Generate playtime in minutes (for display only), @type String
$playtime_mins = $fileinfo['playtime_string'];
</code>
use the following modules to integrate with views.
https://www.drupal.org/project/computed_field
https://www.drupal.org/project/getid3
Comment: Its not basically a file, getID operates on a file but what I have is only url the file is hosted on remote server.
Comment: As per the code, i have posted you can specify remote path of the file to analyze the file attributes

Calculate Audio file duration


Erro ORA-01843 ao importar tabela no Sqoop

Question: Estou enfrentando um erro do qual não consigo entender a origem.
Anteriormente eu havia importado uma tabela com o mesmo formato de dados, com 54 milhões de linhas para o HDFS do meu cluster Hadoop.
Agora eu criei uma _View_ no meu banco de dados Oracle e selecionei uma parcela dos dados da tabela. Agora tem apenas 260k linhas, no entanto agora enfrento esse erro citado mesmo utilizando um comando similar.
SQOOP
O erro gerou isso aqui:

Error: java.io.IOException: SQLException in nextKeyValue      at
  org.apache.sqoop.mapreduce.db.DBRecordReader.nextKeyValue(DBRecordReader.java:277)
    at
  org.apache.hadoop.mapred.MapTask$NewTrackingRecordReader.nextKeyValue(MapTask.java:556)
    at
  org.apache.hadoop.mapreduce.task.MapContextImpl.nextKeyValue(MapContextImpl.java:80)
    at
  org.apache.hadoop.mapreduce.lib.map.WrappedMapper$Context.nextKeyValue(WrappedMapper.java:91)
    at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145)      at
  org.apache.sqoop.mapreduce.AutoProgressMapper.run(AutoProgressMapper.java:64)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)       at
  org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)      at
  java.security.AccessController.doPrivileged(Native Method)    at
  javax.security.auth.Subject.doAs(Subject.java:422)    at
  org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1709)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:162)
  Caused by: java.sql.SQLDataException: ORA-01843: not a valid month

Anteriormente consegui exportar, também com os dados vindos de uma View, só que com a tabela completa.
O comando usado foi:
sqoop import --connect jdbc:oracle:thin:<meu_host:porta:instancia> --username <user> --password <pass> --table <DB.TABLE> --split-by NUM_LINHA  --m 10 --target-dir  /user/rodrigo/RESUMO_TABELONA 2>&1|tee import_tab_menor.txt
Answer: O erro ocorreu pela forma como eu criei a View, usando uma literal para selecionar um intervalo de datas:

DT_F>'02/04/16

O erro deixou de ocorrer quando eu usei:

to_date('02/04/16' , 'dd/mm/yy)


Prevent trailing and leading spaces in VS Code multiline comments

Question: When multiline comment is added with Shift+Ctrl+A, trailing space is added at /* line, this may cause linter problems:

I'm comfortable with no-trailing-spaces linter rule regarding comments and would prefer to not change it because of VS Code quirks.
Leading space before */ doesn't cause linter problems but I would like to get rid of it because it looks displaced and I don't use intermediate asterisks in multiline comments like:
/*
 * multiline
 * comment
 */

Can a way spaces are added to multiline comments be changed in Visual Studio Code?
Answer: EDIT for v1.42 (setting is "Comments: Insert Space") :
Apparently coming to v1.42 is this setting editor.insertSpaceAfterComment which seems to solve your problem in the block comment case.  But if disabled no spaces will be inserted after line // comment notation, so //comment starts immediately instead of // comment starts after space.  This may or may not be acceptable to you.

See https://github.com/microsoft/vscode/pull/41747

If you have
"editor.trimAutoWhitespace": true

when you save the file  it will remove that trailing whitespace.  Alternatively, using the command editor.action.trimTrailingWhitespace will also remove the trailing spaces in the file Ctrl-K Ctrl-X.
Modifying the built-in snippets is tricky since they can be overridden upon updates.
You could make a macro that deletes the space in one go.  I presume you meant Shift-Alt-A: that is the command for toggling block comments on my vscode.  You said Shift+Ctrl+A in your question which is unbound for me.
Using the extension multiCommand: (in your settings.json)
{
  "command": "multiCommand.blockComment",

  "sequence": [
     "editor.action.blockComment",
     "editor.action.trimTrailingWhitespace",
     "cancelSelection",
     "deleteRight"
   ]
},

Those last two commands get rid of the leading space before the */ as you requested.
In your keybindings.json:
{
  "key": "shift+alt+a",
  "command": "-editor.action.blockComment",
  "when": "editorTextFocus && !editorReadonly"
},
{
  "key": "shift+alt+a",
  "command": "multiCommand.blockComment",
},

And then invoke with Shift-Alt-A, toggling off still works too.
.
[The gif goes a little nuts on the entered keystrokes, it Is only Shift-Alt-A.]
Comment: Thanks for the detailed answer.
Comment: Thanks ! Put me on the way, seems now the variable to play with is `editor.comments.InsertSpace` for leading spaces (version VSCode: 1.50.1)
Answer: Just to add to the answer above:
I was having trouble with the /**/ completion in VS Code.  As soon as the second * was typed, VS Code would add a */ to the end - extremely annoying, as we have set formatting for comments, and using the god awful:
/*
 * Some comment
 */

...format is abhorrent to me.
To combat this, navigate to the %ProgramFiles%\Microsoft VS Code\resources\app\extensions\javascript folder.  Make a backup of the javascript-language-configuration.json file, then edit it. In the autoClosingPairs section, change...
    "autoClosingPairs": [
        ...
        { "open": "/**", "close": " */", "notIn": ["string"] }
    ],

...to...
    "autoClosingPairs": [
        ...
        { "open": "/*", "close": "*/", "notIn": ["string"] }
    ],

Comment: Just a note that you might have to do this after every update, your changes may be overwritten if the default file got changed.


Which module creates the "Article" and "Basic page" content types?

Question: By Default we have two content types: Article and Basic page.
Which module creates those content types?
Comment: Those two content types are created by the Standard installation profile you chose when installing Drupal.
Comment: I found Node Entity and NodeType under core Node module. If it is a part of install then they should be written in install file or somethjing like that. Please correct me if I am wrong.
Answer: @Wim Mostrey was right.
In Drupal 7, the default configuration for modules (e.g. content types, field configuration, views) required custom PHP code to install and keep updated. In Drupal 8, these are stored with the configuration system in plain text YAML files, for example core/profiles/standard/config/install/node.type.article.yml.
References

Include default configuration in your Drupal 8 module


Distribution of absolute value of Elliptically Symmetric Random Variable

Question: I am studying Elliptically Symmetric Distributions and someone recommended me Symmetric Multivariate and Related Distributions by Fang (1990), which is the book I am reading for that purpose.
I know that if $X\sim N(\mu,\sigma^2)$, then $|X|$ follows a folded normal distribution. So, I wonder if there exists some generalization. For that, let $X\sim \operatorname{EC}_1(\mu,\sigma^2,\psi)$, what is the distribution of $|X|$?
I thought using PDF's definition of $X\sim \operatorname{EC}_1(\mu,\sigma^2,\psi)$:
$$f(x)=\frac{1}{\sigma}\psi\left(\frac{(x-\mu)^2}{\sigma^2}\right)$$
But I think it is the wrong way. Do you know what is the distribution of $|X|$ to know what I should have to prove? Or if you know an article that talks about this, It would be really helpful.
Answer: To my knowledge, this is still under active research, I am not aware of a generalization to elliptical distributions.
The latest article that I know of is On Moments of Folded and Truncated Multivariate Normal Distributions, which states in the conclusion:

Generalizing the results to multivariate elliptical distributions
requires a lot more work. Although the product moments of multivariate
elliptical distributions can be obtained from the product moments of
multivariate normal distributions (see, for example, Berkane and
Bentler (1986) and Maruyama and Seo (2003)), it is not clear how to
obtain product moments of folded and truncated multivariate elliptical
distributions. We leave this topic for future research.


Convert RSS pubDate to a timestamp

Question: How to convert a date string Mon, 24 May 2010 17:54:00 GMT from RSS feed to a timestamp in PHP ?
Answer: Try This:
$pubDate = $item->pubDate;
$pubDate = strftime("%Y-%m-%d %H:%M:%S", strtotime($pubDate));

Answer: You can use the built-in function strtotime(). It takes a date string as its first argument and returns a Unix timestamp.
http://php.net/manual/en/function.strtotime.php
Comment: It looks like strtotime give strange results when the string contains the timezone. For example with "Sat, 21 Sep 2010 00:00 GMT" I get 1285372800 (25-09-2010)
Answer: strtotime does not work with different timezones.
I have just written this function to convert RSS pubDates to timestamps which does take into account the different timezones:
function rsstotime($rss_time) {
    $day       = substr($rss_time, 5, 2);
    $month     = substr($rss_time, 8, 3);
    $month     = date('m', strtotime("$month 1 2011"));
    $year      = substr($rss_time, 12, 4);
    $hour      = substr($rss_time, 17, 2);
    $min       = substr($rss_time, 20, 2);
    $second    = substr($rss_time, 23, 2);
    $timezone  = substr($rss_time, 26);

    $timestamp = mktime($hour, $min, $second, $month, $day, $year);

    date_default_timezone_set('UTC');

    if(is_numeric($timezone)) {
        $hours_mod    = $mins_mod = 0;
        $modifier     = substr($timezone, 0, 1);
        $hours_mod    = (int) substr($timezone, 1, 2);
        $mins_mod     = (int) substr($timezone, 3, 2);
        $hour_label   = $hours_mod > 1 ? 'hours' : 'hour';
        $strtotimearg = $modifier . $hours_mod . ' ' . $hour_label;
        if($mins_mod) {
            $mins_label = $mins_mod > 1 ? 'minutes' : 'minute';
            $strtotimearg .= ' ' . $mins_mod . ' ' . $mins_label;
        }
        $timestamp = strtotime($strtotimearg, $timestamp);
    }

    return $timestamp;
}

Answer: How about this?
    date_create_from_format(DateTime::RSS, $item->pubDate);
I think this is the simplest solution.
Answer: The rsstotime() function did not work properly if the pubDate in rss feed had timezone other than +0000. The problem was with the $modifier, it had to be reversed. To fix that two lines had to be added, so the line:
$modifier = substr($timezone, 0, 1);

became:
$modifier = substr($timezone, 0, 1);
if($modifier == "+"){ $modifier = "-"; } else
if($modifier == "-"){ $modifier = "+"; }

Just to clarify the modification - for example if the pubDate was Wed, 22 May 2013 17:09:36 +0200 then the row
$timestamp = strtotime($strtotimearg, $timestamp

offsetted the time by two hours not resetted it to +0000 timezone as expected.
The Wed, 22 May 2013 17:09:36 +0200 shows that the time presented here is in the timezone GMT +2.
The code did not work properly and added extra two hours to the time, so the time became Wed, 22 May 2013 19:09:36 +0000, instead Wed, 22 May 2013 15:09:36 +0000 as it should have been.
Answer: function pubdatetotime($pubDate) {

$months = array('Jan' => '01', 'Feb' => '02', 'Mar' => '03',
'Apr' => '04', 'May' => '05', 'Jun' => '06',
'Jul' => '07', 'Aug' => '08', 'Sep' => '09',
'Oct' => '10', 'Nov' => '11', 'Dec' => '12');

$date = substr($pubDate, 5,11);
$year = substr($date, 7,4);
$month = substr($date, 3,3);
$d =  substr($date, 0,2);

$time = substr($pubDate, 17,8);

return $year."-".$months[$month]."-".$d." ".$time;
}

Try this function

Convert RSS pubDate to a timestamp


Problema com Solicitação AJAX

Question: Estou fazendo um sistema de login de usuários.
Quando o Usuário faz o submit do form a solicitação AJAX não está funcionando e a página muda para o login.php
JS
$("form").submit(function() {

    if ($("#login_username").value() != "" && $("#login_password").value() != "") {

        $.ajax({
           url: $("#login-form").attr('action'), //login.php
           data: $("#login-form :input").serializeArray(),
           method: $("#login-form").attr('method'), //post
           success: function(data) {
               alert(data);
           }
        });
    }
    else {
        $("#text-login-msg").text("Digite o Usuário e senha").css('color', 'red');
    }
    return false;
});

Parece que o return false não está funcionando
Comment: com o jquery é `val()` no lugar de `value()`
Comment: Parece ser erros de javascript. acho que o `atr()` deve ser  `attr()`
Comment: mesmo depois de corrigir os erros de `atr()` continua dando os mesmos erros
Comment: Qual erro? vc precisa ligar o console de erros no navegador da um `F12` ai.
Comment: Consegui arrumar o erro, era algum erro de syntax no IF
Answer: O return false; só funciona em JavaScript inline no HTML.
Por exemplo (https://jsfiddle.net/Lho9vpe4/1/):
<form onsubmit="return enviar();">

Para parar dentro de um event handler, que é o teu caso, tens de usar o .preventDefault();.
No teu caso ficaria assim:
$("form").submit(function(e) {
    e.preventDefault();

Contudo, se em nenhum caso vais enviar a form podias associar o auscultador de eventos a um botão ou outro elemento e chamar o ajax, sem ter de enviar a form. Sugestão apenas.
Comment: @rray _"event handler"_ -> http://portuguese.stackexchange.com/q/760/12
Comment: o que é "auscultador"? O.o

Problema com Solicitação AJAX


Como faço para criar um evento no momento que alguém digitar algo no EditText?

Question: Gostaria de criar um evento conforme o usuário vai digitando alguma palavra no meu EditText, porém não sei como acessá-lo.
Answer: Você pode usar o addTextChangedListener(). Veja o código abaixo:
seuEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {

// Aqui você coloca o evento

}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});

Veja mais detalhes na documentação.
Comment: Excelente, era isso mesmo que eu estava precisando. Obrigado.


Set query param value to default on type mismatch in spring boot rest api

Question: We have a rest api built with spring boot and the openapi code generator. Let's assume there is a path /user in our api spec:
...
"paths": {
    "/user": {
        "get": {
            "parameters": [{
                "name": "id",
                "in": "query",
                "required": false,
                "type": "integer",
                "format": "int64"
            }],
            "responses": { ... }
        },
    }
    // more paths
}
...

A call to this path could then be: /user?id=1234.
The code generator creates an interface MyControllerApi:
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "some date")
@Api(value="user")
public interface MyControllerApi {
    @ApiOperation(value="", nickname="userGet", response = User.class, /* ... */)
    @ApiResponse(/* ... */)
    @GetMapping(value="/user", produces = { "application/json" })
    ResponseEntity<User> userGet(@ApiParam(value = "id") @RequestParam(value = "id", required = false) Long id);
}

The controller then looks like this:
@RestController
public class MyController implements MyControllerApi
{
    @Autowired
    UserService service;

    @Override
    public ResponseEntity<User> userGet(@RequestParam(value = "id") Long id) {
        return service.get(id);
    }
}

If /user?id=<value> is requested, spring boot automatically checks if the type of the passed parameter value <value> matches the required type. If not BAD_REQUEST is returned:
{
    "timestamp": "2022-10-19T17:20:48.393+0000",
    "status": 400,
    "error": "Bad Request",
    "path": "/user"
}

We are now in a situation in which we want to pass null to each parameter of userGet that would cause a type mismatch. To be more clear: if /user?id=abcd is requested, userGet should be called with id set to null, so that we can return some default user. Is there a way to achieve this?
Of course there are a lot more paths and parameters and this behavior should apply for every query parameter of type Long or Boolean.
This example may not make much sense, but it is also just an example.
Thanks in advance
What I tried myself in the meantime
1. Setting the spring-boot useOptional option ...
... to true in the pom.xml (see here).
This has the affect that the query parameters in the controllers method are of type Optional<?>. In my example above this would lead to:
@Override
public ResponseEntity<User> userGet(Optional<Long> id) {
    Long id_val = id.isPresent() ? id.get() : null;
    return service.get(id_val);
}

But this did not work either and spring boot also creates a BAD_REQUEST response on parameter type mismatches.
2. Using a request interceptor
A request interceptor is a kind of middleware and can be created by implementing HandlerInterceptor and enables you to process the request before it is passed to the controller.
My interceptor looks like this:
public class CustomRequestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        HandlerMethod method = (HandlerMethod) handler;
        MethodParameter[] handlerParams = method.getMethodParameters();

        while (request.getParameterNames().hasMoreElements())
        {
            // the param name of the query
            String paramName = request.getParameterNames().nextElement();
             the param value
            String paramValue = request.getParameter(paramName);
            MethodParameter methodParam = null;

            for (MethodParameter mp : handlerParams)
            {
                // We can access annotations here ...
                Annotation anno = mp.getParameterAnnotation(RequestParam.class);
                if(anno != null)
                {
                    RequestParam rp = (RequestParam) anno;

                    // ... and am able to get the param name in the controller
                    // Check if we found the param
                    String requestParamName = rp.value();
                    if (requestParamName.toLowerCase().equals(paramName.toLowerCase()))
                    {
                        // and now?
                        break;
                    }
                }
            }

            if (methodParam != null)
            {
                Type type = methodParam.getGenericParameterType();
            }
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}

So far so good, but the RequestParam-Object does not hold any informations about the parameter type, nor about the index of that param in the methods param list. And the MethodParameter does not hold the name of the parameter (because its a compiled class I think).
What I'm wondering is how spring boot itself maps the query parameters to the ones in the controllers methods..... ?
Answer: After doing some research I found a solution by using a custom HandlerMethodArgumentResolver:
public class MyCustomResolver implements HandlerMethodArgumentResolver {
    @Override
    @Nullable
    public Object resolveArgument(
        MethodParameter methodParam,
        @Nullable ModelAndViewContainer mvContainer,
        NativeWebRequest request,
        @Nullable WebDataBinderFactory binderFac
    ) throws Exception {
        String paramValue = request.getParameter(methodParam.getParameterName());
        if (paramValue == null)
            return null;

        if (methodParam.getParameterType().equals(Long.class)) {
            try {
                // Set param value to the parsed one, if it can be parsed
                return Long.parseLong(paramValue);
            } catch (Exception e) {
                // Set param value to null otherwise
                return null;
            }
        }

        return null;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(Long.class));
    }
}

The method supportsParameter() gives you the opportunity to decide whether or not the passed parameter will be processed in resolveArgument.
resolveArgument then gets the parameter as MethodParameter. Unlike in the HandlerInterceptor the MethodParameter now contains the parameter name and type.
Using this approach id will have the following values:
id = 1     on /user?id=1
id = null  on /user?id=abc

Now I'am able to handle falsy parameter values in the controller directly.
Remarks
If you use a parameter of type Boolean the param value will not be null but "false" for every parameter value except true. Only if "true" is passed in the request resolveArgument will parse it to true and getUser will receive true.


Como fazer Gráfico Expansivel no Excel

Question: Estou tentando fazer um gráfico expansivel, que se ajusta automaticamente, porém estou utilizando essa fórmula e não está dando certo. Alguém pode me ajudar?

=DESLOC(CTC!$B$3;1;0;CONT.VALORES(CTC!$B$4:$B$18;"<>"&"0");1)

OU

=DESLOC(CTC!$B$3;1;0;CONT.VALORES(CTC!$B$4:$B$18;"<>0");1)

Como pode ver no gráfico não era pra estar aparecendo valores zero, e nem nulo, acrescentei no final da fórmula o: "<>"&"0" porém mesmo assim não ta funcionando, minha intenção com isso era "Se for diferente de 0, continua
Answer: Olá,
Para a fórmula que busca os status, tente usar:
=DESLOC(CTC!$A$4;0;0;CONT.SE(CTC!$B:$B;">0");1)
Ela vai buscar tudo o que é maior do que ZERO na coluna B, em vez de buscar tudo o que for diferente de ZERO. O problema de usar tudo o que for diferente de ZERO é que o Excel entende as células vazias como ZERO.
Para a fórmula que busca os valores, tente usar:
=DESLOC(CTC!$B$4;0;0;CONT.SE(CTC!$B:$B;">0");1)
O racional é o mesmo, mas agora a fórmula busca as nomenclaturas da coluna A baseado nos valores (tudo o que for maior que ZERO) da coluna B.

Como fazer Gráfico Expansivel no Excel


Update AWS Elastic Beanstalk solution stack name

Question: I have a Cloudformation template with the following Elastic Beanstalk environment:
Resources:
  BeanstalkEnvironment1:
    Type: AWS::ElasticBeanstalk::Environment
    Properties:
      ApplicationName: Application1
      Description: ignored
      EnvironmentName: Environment1'
      SolutionStackName: '64bit Amazon Linux 2017.03 v2.5.0 running Python 3.4'

My main goal is to update the environment's Python version from 3.4 to 3.6. I was able to update the solution stack name with the following command (taken from this answer)
aws elasticbeanstalk update-environment --solution-stack-name "64bit Amazon Linux 2018.03 v2.7.6 running Python 3.6" --environment-name "Environment1"

However, I cannot do subsequent updates using the existing template if I update it to the new solution stack name, because I get "Cannot update a stack when a custom-named resource requires replacing". It works if I keep the original one, but I would like to keep the running platform in sync with the template.
Any ideas?
Thanks!
Answer: I get the same problem.  This appears to be a limitation of Elastic Beanstalk and CloudFormation.  In the docs (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html) an update to SolutionStackName shows as Update requires: Replacement.
If you just change the EnvironmentName every time you change SolutionStackName it should work fine.
Answer: Check the documentation note of SolutionStackName:

Note: If you specify SolutionStackName, don't specify PlatformArn or
TemplateName.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Uniqueness Proof for Division Algorithm using Contradiction

Question: Let $a, b, \mathbb \in \mathbb {Z}$ and let there exist integers $q, q_1, r, r_1$ such that
the two pairs $(q,r)$ and $(q_1,r_1)$ satisfy the properties:
$$\ \ \ \ a = qb+r \quad \ \ \ \ \ \ \ ; 0 \le r \lt b \\
 also, \ a = q_1 b + r_1 \quad ; 0 \le r_1 \lt b$$
It is assumed that $|r-r_1| \lt b$. Also, assume for the sake of contradiction that $q \neq q_1$. Then come up with another inequality involving $|r-r_1|$ that contradicts $|r-r_1| \lt b$.
Answer: Hint: Just follow the given hint, noting that
$$ 0 = a -a = (q_1 - q)b + (r_1 - r) \iff r - r_1 = (q_1 - q)b $$
So $\def\abs#1{\left|#1\right|}$$\abs{r_1 - r} = \abs{q_1 - q}b$, if now $q \ne q_1$, what can you say about $\abs{r_1 -r }$?
Comment: Since $q \neq q_1$, then $r_1 \neq r$ which implies that $|r_1 - r|$ is a multiple of $|q_1-q|$ since b is an integer?
Comment: Almost. The point is that $q_1 -q$ is an integer and hence $r_1 - r$ is a multiple of b!
Comment: Ohh alright! Thanks so much for your help @martini! (:


node number evolution statistic?

Question: Im looking for a way to store the TOTAL number of nodes published on my drupal 6 web site at a particular month of the year so I can generate some curve from it :
timestamp | total node nb type x
2013/01   | 96
2013/02   | 100 (I mean 96+4, cumulative)
2013/03   | 120
[...]

the need seems simple to me, but I cant find any statistics module that cares about this. also the need is really simple compared to the features these modules offer.
I could write some piece of code about this using CRON and some requests to write such a table. maybe something with views count + cron.
but it certainly already exists somewhere as a module ?
thanks for any pointers/recipes.
jerome
Answer: Do you really need the publishing date? or just the created date?
If you need the former, well that date isn't tracked by core - http://drupal.org/node/1838918
You could try a contrib module to start tracking that for you... http://drupal.org/project/publication_date
If you're not worried about deleted nodes you can just do what you're after by running a query to count all the nodes that have a created date lower than month X. Or just get all nodes back, and then loop over them in php, successively incrementing counters for each month for your graph.
Otherwise, yeah you're going to have to do something with cron and get snapshots over time. I haven't heard of an existing offering for this in contrib.
Answer: You should give a try at the Count module :

The Count Nodes Module counts total number of nodes created (published and unpublished both) in each content type. It provide a total number of blocks equals to the total number of content types created such that administrator can use one block for each content type.
The Count Nodes module also provide a text box in each block to do a manual entry of total nodes. It helps administrator to show less or more count of actual nodes.
Comment: thanks I'll try it, but it seems it does exactly the same than a view that get a node type with > display as 'views calc table' style in count mode. I would need to store these values in some table.
Comment: uuuh, doesn't this module just get the *current* number of nodes? OP is asking for snapshots over time to help with graphing.
Comment: yep. (what is OP ? sry noob)
Comment: Original Poster/Original Post
Comment: I got the beginning of something with this : http://www.tylerfrankenstein.com/code/drupal-views-group-field-counts-and-links-better-way
Comment: got more features with this (wip)..) : http://drupal.org/node/389230
Answer: for this purpose, unfortunately, I cant find my way yet using views or this module http://drupal.org/project/views_groupby (it doesnt work when using date published field even using field rewrite).
so here is a snippet I wrote that can be pasted in a block (you need php input).
this generates a table with 3 columns : year/month, node created / month, total (cumulative). change the nod type  and  drupal table preffix by yours.
<?php
  $header = array('month','compte','total');
  $rows = array();
  $total = 0;

  $query = "SELECT
    DATE_FORMAT((FROM_UNIXTIME(node.created) + INTERVAL 3600 SECOND), '%Y/%m') AS node_created_month,
    COUNT(node.nid) AS node_count
    FROM <db>_node node
    WHERE node.type in ('<nodetype>')
    GROUP BY node_created_month
    ORDER BY node_created_month ASC";

  $results = db_query($query);

  while ($fld = db_fetch_object($results)) {
    $total += $fld->node_count;
    $rows[] = array(
      $fld->node_created_month,
      $fld->node_count,
      $total
    );
  }

  return theme('table', $header, $rows);
?>

using the google chart api module http://drupal.org/project/chart
one can also generate a chart using the same query.
    <?php
    // retrieve datas
      $query = "SELECT
        DATE_FORMAT((FROM_UNIXTIME(node.created) + INTERVAL 3600 SECOND), '%Y/%m') AS node_created_month,
        COUNT(node.nid) AS node_count
        FROM <db>_node node
        WHERE node.type in ('<nodetype>')
        GROUP BY node_created_month
        ORDER BY node_created_month ASC";

      $results = db_query($query);

      // prepare chart layout
      $chart = array(
          '#chart_id' => 'test_chart',
          '#title' => chart_title(t('blahblah'), 'cc0000', 15),
          '#type' => CHART_TYPE_LINE,
          '#size' => chart_size(545, 300),
          '#adjust_resolution' => TRUE,
          '#chart_fill' => chart_fill('c', 'eeeeee'),
          '#grid_lines' => chart_grid_lines(20, 20, 1, 5),
      );

      $chart['#legends'][] = '<nodetype>';
      $chart['#data_colors'][] = '00ff00';

      $chart['#mixed_axis_labels'][CHART_AXIS_Y_LEFT][1][] = chart_mixed_axis_label(t('nombre lieux'), 50);

      $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][2][] = chart_mixed_axis_label(t('temps'), 50);

      // inject datas into chart arrays
      $total = 0;
      while ($fld = db_fetch_object($results)) {
        $total = $total + $fld->node_count;
        $chart['#data']['<nodetype>'][] = $total;
        $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][1][] = chart_mixed_axis_label( $fld->node_created_month );
      };

      $chart['#mixed_axis_labels'][CHART_AXIS_Y_LEFT][0][] = chart_mixed_axis_range_label(0, $total);
      echo chart_render($chart);
    ?>

the generated graph png can be saved, and block is cachable so I wonder if its valuable to investigate about cron and add results to an existing sql table rather than to regenerate the whole thing, but well, that's a start.
Comment: one also needs to add the months where there was no node creations in the arrays. just ask if you need it I'll publish. pending : http://www.reseau-alpha.org/statistiques

node number evolution statistic?


Find .closest() .next() then toggleClass

Question: I'm trying to show many different categories of things on a page for a user to choose multiples of. When a category is clicked, a checkbox is checked. Upon clicking the I'm also trying to add a class to the covering mask, but its not finding it. I'm trying to find the closest, next class .mask
HTML:

    <input name="category[]" value="53" type="checkbox">

Art & Design

Art & Design

    <input name="category[]" value="54" type="checkbox">

People

People

JQuery
$('.Choose').click(function(){
    $(this).closest('.mask').next().toggleClass('active');
});

Comment: `.closest()` selects the closest parent element. You should use `.find()` method instead, Also the selector should be `.choose` not `.Choose` and the `.mask` elements don't have _next_ siblings, so the `.next()` method doesn't return any element, this means that the whole logic _unfortunately_ is wrong.
Comment: Possible typo `class="choose"` vs capitalized `.Choose`?
Comment: Actually, what do you want to do with `next()`?. `.mask` does not have any element 'next' to him.
Comment: @OlafDietsche Good catch, it was a typo on here only, actual code is case correct
Answer: While looking at your markup, You have to use .find() as per your need. .closest() will search for the elements by travelling up the DOM tree.
Try,
$('.choose').click(function(){
    $(this).find('.mask').toggleClass('active');
});

Comment: Awesome! Works perfectly


Why is $ N^\tau ( M - M^\tau ) $ a continuous local martingale if $ M $ and $ N $ are?

Question: Working through my stochastic calculus script, I encountered the following identity, for which no proof is given:  $ \langle M, N^\tau \rangle = \langle M, N \rangle^\tau $, if $ M, N $ are continuous local martingales, null at 0.
I know that (by uniqueness of the bracket) it suffices to show the following:
If both $ M,N $ are continuous local martingales and $ \tau $ is a stopping time, then
$ N^\tau ( M - M^\tau ) $ is again a continuous local martigale.
But why is this true?
I know how to proof this with the properties of the stochastic integral. But since the above identity is used in our script during the construction of the stochastic integral, I would like to prove it directly. Does anybody know how this can be done?
Trying to prove it, I started like this:
$ M,N $ continuous local martingales  $ \ \Rightarrow \ $  there are localizing sequences $ \tau_n, \sigma_n $ such that $ M^{\tau_n} $ and $ N^{\sigma_n} $ are bounded martingales. By the stopping theorem, $ N^{\tau_n \wedge \sigma_n \wedge \tau} $ and $ M^{\tau_n \wedge \sigma_n \wedge \tau} $ are bounded martingales, too.
Now I would like to proof that
$ N^{\tau_n \wedge \sigma_n \wedge \tau} (M^{\tau_n \wedge \sigma_n } - M^{\tau_n \wedge \sigma_n \wedge \tau}) $ is a martingale, since this would then imply that $ N^\tau ( M - M^\tau ) $ is a continuous local martigale (with localizing sequence $ \tau_n \wedge \sigma_n $).
Thanks a lot for your help!
Regards,
Si
Comment: The fact that $N$ is a local martingale is irrelevant. Any continuous adapted process will work.
Answer: Let $X^{(n)}=N^{\kappa_n}\cdot(M^{\varrho_n}-M^{\kappa_n})$, where $\varrho_n=\tau_n\wedge\sigma_n$ and $\kappa_n=\varrho_n\wedge\tau$ hence $\kappa_n\leqslant\varrho_n$. Then, $\mathrm dX^{(n)}_t=[\kappa_n\leqslant t\leqslant\varrho_n]\cdot N_{\kappa_n}\cdot\mathrm dM_t=[\kappa_n\leqslant t\leqslant\varrho_n]\cdot N^{\kappa_n}_t\cdot\mathrm dM_t^{\tau_n}$ and $M^{\tau_n}$ is a martingale hence $X^{(n)}$ is a martingale.
Comment: Nice! Thanks a lot!


Changing an array of arrays to an array of other datatypes in JavaScript

Question: In Javascript is there a better way to change [[1],[2],[3]] to ["1","2","3"] than what I have done in the code below?

let arr = [[1],[2],[3]];

let newArr = [];
arr.forEach(elem => {
elem.forEach(val=>{
newArr.push(val);
})
})

console.log(newArr);
Comment: It wowuld help if you add some formatted source code of what you tried, and the result you got so far.
Answer: Use Array.map() to convert each array to string using the String constructor function:

const arr = [[1],[2],[3]]

const numbersArr = arr.map(String)

console.log(numbersArr)

If you have multiple items in each array, flatten the array, and them map the array items to strings:

const arr = [[1, 2],[2, 3],[3, 4]]

const numbersArr = arr.flat().map(String)

console.log(numbersArr)
Answer: You can use Array.reduce to reduce your 2d array into a single array.

const arr = [[1],[2],[3]];

const result = arr.reduce( (acc, cur) => {
  acc.push(cur[0].toString())
  return acc;
}, []);

console.log(result);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Answer: It might be helpful.

// [1, [2, [3], [4, [[[5, 6]]]]]] => ['1', '2', '3', '4', '5', '6']

const flatternArray = (arr) => {
    return arr.flatMap(x => {
      if (Array.isArray(x)) {
        return flatternArray(x)
      } else {
        return x.toString();
      }
    })
  }

  console.log(flatternArray([1, [2, [3], [4, [[[5, 6]]]]]]))


Homology of $I$-bundles over the Klein bottle.

Question: Let $I=[0,1]$. I would like to compute the homology of $I$-bundles over the Klein bottle $K^2$. As far as I know there are three $I$-bundles over $K^2$: the trivial bundle $K^2\times I$ (I have no problem computing the homology of this one) and two twisted bundles: $K^2\tilde{\times} I$ and $K^2\hat{\times} I$. The bundle $K^2\tilde{\times} I$ is orientable while $K^2\hat{\times} I$ is non-orientable.
I have no idea how to start to compute the homology groups of such a bundle. I think I'm confused about them being twisted and this makes it confusing to me to even see what technique or theorem should I try to apply to compute the homology.
Comment: This is a very naive question but can't you retract $I$ to a point so you get homology of the Klein bottle ?
Comment: I presume $I$ is the unit interval.
Comment: Yes, that's correct. I will edit my question to add this information.
Answer: Let $E$ be such a bundle and $\pi :E \to K $ be the projection. Let $D_1, \dots, D_n$ be disks covering $K$, such that $E$ is trivial over any $D_i$. On $D_1$, you can deform retracts $\pi^{-1}(D_1) \cong D_1 \times I$ onto $D_1$. By induction, you can deform retract your bundle on $K$, in particular their homology groups coincide.
This works for any bundle with a contractible fiber, e.g a vector bundle.
Comment: Your induction argument does not really work, but the idea is correct: The bundle projection $E\to K$ is a retraction homotopic to the identity map. This is actually a general fact about fiber bundles with contractible fibers.
Comment: Dear @MoisheCohen, thanks for your comment ! Could you tell me why it's not working ? I was thinking "retracting in several step", so extend the retraction such that it is the identity map outside a little neighborhood of $D_1$ and then repeat the process. Would this work ?
( My first approach was to take a section by sending $x$ to the middle of the segment $I_x$ but I did realize that "the middle of $I_x$" is not defined if the bundle is just a topological bundle.)
Comment: @Sak Yes, this is how it is usually done.
Comment: After the 1st step you loose the induction assumption, since you no longer have a fiber bundle. (Just try to write a formal proof on a piece of paper and see how you get stuck.) There are several ways to handle this, one is to introduce a fiberwise metric and to observe the existence of a section of the bundle.  The other is to observe the existence of a trivial bundle which is a 2-fold cover of your bundle and then argue that the trivial bundle has $Z_2$-invariant deformation retraction.
Comment: Ok I see ! Many thanks for the explanations.
Comment: I assume standardly this is just an application of the long exact sequence for fiber bundles
Comment: Thank you very much for your answers! I see the idea and also the problem. Should I try to use obstruction theory then to prove that there is a section?


Append DataFrame to an Index Pandas

Question: I have lots of nests in my data. I have 6 time periods (but let's not worry about that), each time period has 19 quantiles, each quantile has a 51x51 covariance matrix (for all states and DC of USA). If represented as a dictionary, I would have:
my_data = {'time_pd_1' : {0.05 : pd.DataFrame(data=cov_var(data_for_0.05), columns=states, index=states),
                         {0.10 : pd.DataFrame(data=cov_var(data_for_0.10), columns=states, index=states),
                          ...
                         {0.90 : pd.DataFrame(data=cov_var(data_for_0.90), columns=states, index=states),
                         {0.95 : pd.DataFrame(data=cov_var(data_for_0.95), columns=states, index=states)},
           'time_pd_2' : {0.05 : pd.DataFrame(data=cov_var(data_for_0.05), columns=states, index=states),
                         {0.10 : pd.DataFrame(data=cov_var(data_for_0.10), columns=states, index=states),
                          ...
                         {0.90 : pd.DataFrame(data=cov_var(data_for_0.90), columns=states, index=states),
                         {0.95 : pd.DataFrame(data=cov_var(data_for_0.95), columns=states, index=states)},
            ...
           'time_pd_6' : {0.05 : pd.DataFrame(data=cov_var(data_for_0.05), columns=states, index=states),
                         {0.10 : pd.DataFrame(data=cov_var(data_for_0.10), columns=states, index=states),
                          ...
                         {0.90 : pd.DataFrame(data=cov_var(data_for_0.90), columns=states, index=states),
                         {0.95 : pd.DataFrame(data=cov_var(data_for_0.95), columns=states, index=states)}}

Easy enough, but the data is not created like this. I have two for loops that do the work:
for tpd in time_periods:
    for q in quantiles:
        tdf = pd.DataFrame(data=cov_var(data_for_q), index=states, columns=states)

If I were to print tdf it looks like this:
ST              Alabama         Alaska          Arizona         ...     West Virginia   Wisconsin   Wyoming
ST
Alabama         288.867628      50.000000       -100.062576     ...     37.719317       0           -75.000000
Alaska          50.000000       280.929272      -229.365427     ...     57.514555       0           -136.365512
Arizona         -100.062576     -229.365427     946.563177      ...     -113.805612     0           291.897723
...             ...             ...             ...             ...     ...             ...         ...
West Virginia   37.719317       57.514555       -113.805612     ...     342.195976      0           -214.243277
Wisconsin       0.000000        0.000000        0.000000        ...     0.000000        0           0.000000
Wyoming         -75.000000      -136.365512     291.897723      ...     -214.243277     0           684.146619

Now, what I want is this:
cov = {}
for tpd in time_periods:
    cov[tpd] = pd.DataFrame(index=[str(round(q,2)) for q in quantiles])
    for q in quantiles:
        tdf = pd.DataFrame(data=cov_var(data_for_q), index=states, columns=states)
        cov[tpd].loc[str(round(q,2)), :] = tdf

So if I print cov[tpd] it should look like:
        ST              Alabama         Alaska          Arizona         ...     West Virginia   Wisconsin   Wyoming
q       ST
        Alabama         288.867628      50.000000       -100.062576     ...     37.719317       0           -75.000000
        Alaska          50.000000       280.929272      -229.365427     ...     57.514555       0           -136.365512
        Arizona         -100.062576     -229.365427     946.563177      ...     -113.805612     0           291.897723
0.05    ...             ...             ...             ...             ...     ...             ...         ...
        West Virginia   37.719317       57.514555       -113.805612     ...     342.195976      0           -214.243277
        Wisconsin       0.000000        0.000000        0.000000        ...     0.000000        0           0.000000
        Wyoming         -75.000000      -136.365512     291.897723      ...     -214.243277     0           684.146619
        Alabama         288.867628      50.000000       -100.062576     ...     37.719317       0           -75.000000
        Alaska          50.000000       280.929272      -229.365427     ...     57.514555       0           -136.365512
        Arizona         -100.062576     -229.365427     946.563177      ...     -113.805612     0           291.897723
0.10    ...             ...             ...             ...             ...     ...             ...         ...
        West Virginia   37.719317       57.514555       -113.805612     ...     342.195976      0           -214.243277
        Wisconsin       0.000000        0.000000        0.000000        ...     0.000000        0           0.000000
        Wyoming         -75.000000      -136.365512     291.897723      ...     -214.243277     0           684.146619
...     ...             ...             ...             ...             ...     ...             ...         ...
...     ...             ...             ...             ...             ...     ...             ...         ...
        Alabama         288.867628      50.000000       -100.062576     ...     37.719317       0           -75.000000
        Alaska          50.000000       280.929272      -229.365427     ...     57.514555       0           -136.365512
        Arizona         -100.062576     -229.365427     946.563177      ...     -113.805612     0           291.897723
0.90    ...             ...             ...             ...             ...     ...             ...         ...
        West Virginia   37.719317       57.514555       -113.805612     ...     342.195976      0           -214.243277
        Wisconsin       0.000000        0.000000        0.000000        ...     0.000000        0           0.000000
        Wyoming         -75.000000      -136.365512     291.897723      ...     -214.243277     0           684.146619
        Alabama         288.867628      50.000000       -100.062576     ...     37.719317       0           -75.000000
        Alaska          50.000000       280.929272      -229.365427     ...     57.514555       0           -136.365512
        Arizona         -100.062576     -229.365427     946.563177      ...     -113.805612     0           291.897723
0.95    ...             ...             ...             ...             ...     ...             ...         ...
        West Virginia   37.719317       57.514555       -113.805612     ...     342.195976      0           -214.243277
        Wisconsin       0.000000        0.000000        0.000000        ...     0.000000        0           0.000000
        Wyoming         -75.000000      -136.365512     291.897723      ...     -214.243277     0           684.146619

Having this final structure will make my life so much easier, that I am willing to buy a beer for the person who gets it. That apart, I have tried various things:
cov[tpd].loc[str(round(q,2)), :] = tdf # Raises ValueError: Incompatible indexer with DataFrame
cov[tpd].loc[str(round(q,2)), :].append(tdf) # Almost gives me the frame I need, but removes the index level q, and inserts a column 0 with NaNs
cov[tpd].loc[str(round(q,2)), :].join(tdf, how='outer') # Raises AttributeError: 'Series' object has no attribute 'join'
pd.merge(cov[tpd].loc[str(round(q,2)), :], tdf, how='outer') # Raises AttributeError: 'Series' object has no attribute 'columns'

I understand all the error messages, and I also have a potential fix which involves pre-creating the DataFrame cov[tpd] the way I want it, then use indexing to insert the output from cov_var(). But that is a few extra lines of code to create the multiindex for cov[tpd] and then inserting the data. Does anyone know a better way?

Note: cov_var() is a simple covariance computing function that I wrote because my case is a little special, and I cannot use a built in function like np.cov().
Answer: So I finally gave in, and used the method I hinted at in the question above. It actually appears to be faster than the method I was so adamant at trying. All's good. Here is what I ended up doing:
cov = {}
ind_lev_1 = [str(round(q,2)) for q in quantiles]
ind_lev_2 = states
index = pd.MultiIndex.from_product([ind_lev_1, ind_lev_2], names=['QUANTILE', 'STATE'])
columns = pd.Index(ind_lev_2, name='STATE')

for tpd in time_periods:
    cov[tpd] = pd.DataFrame(index=index, columns=columns)
    for q in quantiles:
        q = str(round(q,2))
        cov[tpd].loc[(q,), :] = cov_var(arr=data_for_q, means=pop_means_for_q)

Append DataFrame to an Index Pandas


small company > Virtualization/server vs laptops vs desktops

Question: We are a rapidly growing startup in our 3rd financial year.
As we are expanding our resources (read team members) we feel the need to decide what is best
We are about 5-6 people expanding to 10-15
What is suggested?

Individual laptops to everyone on network (quite a regular solution)
Central server with login for each team member (keyboard + mouse + display)
Other?

Our requirement

We use MacOSX + Windows + Linux at different machines/projects for our products and services
All MacOSX machines so far are pro laptops. They need to seamlessly connect
All desktops (so far) are MS-windows + Linux dual-boot
We need a stable backup management (currently using physically attached disk with each computer)
We need security and safety of data (client + ours)

What are the most significant factors to consider?

safety & security?
versatility?
simplicity?
cost?
other?

Any help here would be appreciated.
Update (22-Sep-2011): Thanks to everyone for their valuable suggestions. We decided to just add a few more desktops in the existing network and keep using the google, skype, other collaboration techniques we have been using.
Comment: my best guess is that your costs/complexity will be nonlinear and grow rapidly based on number of users in relationship to OS type.
Comment: you couldn't have a worse combination of operating systems to work with.
Comment: You should consider standardizing your desktops. Maintaining Windows+OSX+Linux in a enviroment where everyone bascally need the same services (file shares, backups, backoffice, crm etc) takes a lot of time.
Comment: We must have MacOSX, Linux, Windows environments for different projects needs. We have been working appreciably good so far with dropbox file sharing, USB pen drives for large file sharing (people within reach), google apps for calendar, docs, time sheets, etc... and skype/gtalk/chat-channels for communication, teamviewer/vnc for screen shares, ... and so on.
Answer: I assume you're talking about a Virtual Desktop Infrastructure setup, where people connect to a bunch of virtual machines on a central virtual server from thin clients.
The most significant factors to consider are usability & flexibility. If your users find a Virtual Desktop setup difficult to use or unable to meet their needs then it doesn't matter if its a bit cheaper.
As for cost, you might find that the cost of the right network and server infrastructure to support a good reliable VDI environment isn't that cheap (keep in mind that right now if your PC goes down then YOU cannot work but if the VDI server goes down in a VDI environment then no-one can work, so you can't cut corners here) and don't forget the cost of the VDI thin client itself. It's not just a monitor, keyboard and mouse.
As for simplicity, it might make it easier for the person managing this stuff, but from the user's perspective this sort of change is either going to be neutral or a net disadvantage.
Answer: This is really a matter of preference. I would avoid going to a Virtual Desktop environment until you reach a lot larger size. My last couple organizations have had 100+ users and we were just barely starting to think about using VDI.
In a mixed mode environment like this I would probably go with a combination of windows and Mac laptops and have a collection of virtual Linux boxes. You could go either Parallels, Workstation or one of the server class products.
All of the factors that you have listed are important. As you environment grows dual booting will become a pain in the butt. From my history I'll tell you that most folks will prefer to have Windows as the main day to day OS.. You environment may differ of course.
Answer: If you want to get your feet wet with virtualization then you may consider making your dual boot machines just a Windows install and use a hosted virtualization solution - like VMware Workstation or Oracle Virtualbox.  That way you will have access to the Windows host and the linux OS (guest) at the same time - No need to reboot and boot into the other OS.  Also with VMware Workstation 8 that was just released you can share VMs (guests) between each other just using Workstation.  If you have some resource (software) that you want to centrally manage, one of the pros of running VDI, then you can keep it updated on that one VM and people can connect to that shared VM in your environment.


Como apagar conteúdo Html completo?

Question: Eu estou fazendo um chat utilizando PHP, JavaScript, Ajax e HTML. Eu sei que não é a melhor opção, mas eu optei por criar um arquivo html log.html que armazena todas as mensagens e é carregado pelo meu arquivo PHP index.php. Todas as mensagens são enviadas ao log através do arquivo post.php. Eu preciso apagar todas as mensagens, ou seja, apagar todo o conteúdo do html presente no log.html em um determinado horário. Como  posso fazer isso? Segue o código dos arquivos.
Index.php
/* Tentando apagar o conteúdo do arquivo */
$var = date('H:i:s');
if ($var == '02:00:00') {
    $fp = fopen("log.html", 'w');
    fwrite($fp, "");
    fclose($fp);
}

<form class="chat-form" name="message" action="">
    <textarea name="usermsg" id="usermsg"></textarea>
    <button name="submitmsg" type="submit" id="submitmsg"></button>
</form>

// JS && Ajax da página
function loadLog() {
    var a = $(".chatlogs").attr("scrollHeight") - 20;
    $.ajax({
        url: "log.html",
        cache: !1,
        success: function(t) {
            $(".chatlogs").html(t);
            var o = $(".chatlogs").attr("scrollHeight") - 20;
            a < o && $(".chatlogs").animate({
                scrollTop: o
            }, "normal")
        }
    })
}
$(document).ready(function() {}), $("#submitmsg").click(function() {
    var t = $("#usermsg").val();
    return $.post("post.php", {
        text: t
    }), $("#usermsg").attr("value", ""), !1
}), setInterval(loadLog, 1e3);

Post.php
<?php
    /* Envio da mensagem para o log.html */
    session_start();
    if(isset($_SESSION['usuarioUsuario'])){
        $text = $_POST['text'];
        $fp = fopen("log.html", 'a');
        if ($_SESSION["usuarioNivel"] == 9) {
            fwrite($fp, "

~".$_SESSION['usuarioUsuario']."".stripslashes(htmlspecialchars($text))." ".date("g:i A")."

");
        } else {
            fwrite($fp, "

~".$_SESSION['usuarioUsuario']."".stripslashes(htmlspecialchars($text))." ".date("g:i A")."

");
        }
    fclose($fp);
    }
?>

Como eu apago todo o conteúdo do log.html em um determinado horário sem precisar de uma interação do usuário?
Answer: Apagar
$var = date('H:i:s');
if (strtotime($var) < strtotime('09:34:00') && strtotime($var) > strtotime('15:00:00')) {
    $fp = fopen("log.html", 'w');
    fwrite($fp, "");
    fclose($fp);
}

esse strtotime() reduz a hora a "int" e apos isso ele verifica um horário para fazer o apagamento mas indico por um tempo de distancia para caso haja algum atraso não cancelar seu apagamento, você pode por uma cornjob se quiser automatico...
Apagar /cornjob
    $fp = fopen("log.html", 'w');
    fwrite($fp, "");
    fclose($fp);

Comment: Funciona, porém precisa de reload na página. Mas eu queria que não houvesse a necessidade de fazer uma requisição da página, ou seja, o usuário não deve dar um reload na página para que o log seja apagado. Eu gostaria que o log fosse apagado sem que houvesse interação em um horário (às 02:00 am).
Comment: CORNJOB entao para fazer automatico
Comment: http://blog.thiagobelem.net/o-que-sao-e-como-usar-as-cron-jobs ou ce usar cpainel procure por cornjob cpanel
Comment: você pode ate remover o if se for por cornjob
Comment: caso esteja solucionado o problema, marca como valida a resposta, para ficar como problema solucionado para os próximos

Como apagar conteúdo Html completo?


Printing Score - Pygame

Question: Does anyone know how I can get the score to be displayed on the screen of my game?
So far I have this code:
for bullet in bullet_list:

        block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)

        for block in block_hit_list:
        explosion.play()
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)
        score += 10
        font = pygame.font.Font(None, 36)
        text = font.render(score, 1, (WHITE))
        textpos = text.get_rect(centerx=background.get_width()/2)
        background.blit(text, textpos)

    if bullet.rect.y < -10:
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)

However, I recieve this error once I launch the game and shoot a bullet:
"text = font.render(score, 1, (WHITE))
TypeError: text must be a unicode or bytes"
Does anyone know how I can solve this issue?
Thank you
Answer: OK so first of all you asked how to correctly draw the site which would be just like how the previous answer did it, but then you are a but wrong in the way you blit  it to the screen.
You currently have the score blit to the screen every time through the for loop, this causes it to have the effect you're experiencing. This should be just after the for loop.
Example:
for bullet in bullet_list:
    block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)
    for block in block_hit_list:
        explosion.play()
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)
        score += 10
        #removed this line!!!! ~ font = pygame.font.Font(None, 36)
        #removed this line to!!!! ~ text = font.render(score, 1, (WHITE))
        #remove this line also!!! ~ textpos = text.get_rect(centerx=background.get_width()/2)
        #finally remove this line!!!! ~ background.blit(text, textpos)
    if bullet.rect.y < -10:
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)
#add in those removed lines after your for loop.
font = pygame.font.Font(None, 36)
text = font.render(score, 1, (WHITE))
textpos = text.get_rect(centerx=background.get_width()/2)
background.blit(text, textpos)

This should work. Please tell me if you need any further help.
Comment: @Oscar OK you should be blitting the text to the screen not the background. What is happening is that you draw the score to the background, but the backgrounds never gets cleared. You want to clear whatever you're drawing the text to. So to fix this, draw the text to the screen and not to the background, also draw the text after you draw the background to the screen.
Comment: @Oscar sorry for delayed response, but in the line `elif event.type == pygame.KEYDOWN:` you just need to check which key is pressed by using this: `elif event.type == pygame.KEYDOWN and event.key == K_SPACE:` More information regarding this is found at http://www.pygame.org/docs/ref/key.html
Comment: Thanks for your reply, this works perfectly but I still have an issue with scores being displayed on top of each other continuously? Rather than displaying 10 then clearing the score before 20 is displayed, it displays 10 on top of 20 etc leaving me with unreadable text
Comment: @Oscar Could you post your current code preferably a bit more of the mainloop?
Comment: Ah, this works great! Thanks so much for your help, I have another question to do with firing the bullet, I want the ship to only shoot when the space bar is pushed however it currently shoots when any key is pressed, also the "bullet" seems to be off center, any idea how to fix these issues? Thanks a lot for your replies :)
Answer: You need to convert the score into a string.
text = font.render(str(score), 1, (WHITE))

Comment: Works perfectly! Only one slight issue, scores appear on top of themselves if more than 1 point is scored, is there any way I can fix this? :) Thanks so much for your reply

Printing Score - Pygame


Problem about solution of an PDE system

Question: For the following system:
$\begin{cases} |\nabla f|^2=1 \\\\ \Delta f=0
\end{cases}$
where $f: \mathbb{R}^2 \rightarrow \mathbb{R}$ and $\nabla f$, $\Delta f$ are Gradient and Laplacian of $f$, respectively.
Are there solutions for this system where the $f$ function is not an affine function?
Answer: No, there are no solutions $f$ where the function $f$ is not an affine function.
To see this, note that differentiation of the identity $|\nabla f|^2=1$, once by $x$ and another time by $y$,
$$|\nabla f|^2=f_x^2+f_y^2\equiv1$$
implies
$$\langle\nabla f,(f_{xy},f_{yy})\rangle = 0$$
and also
$$\langle\nabla f, (f_{xx},f_{xy})\rangle = 0$$
where $\langle\cdot\rangle$ is the Euclidean dot product. We have two vectors perpendicular to the (non-zero) gradient, so they must be proportional, i.e., there exists a number $c(x,y)$ such that
$$(f_{xx},f_{xy})=c(x,y)(f_{xy},f_{yy})\quad\quad (1)$$
Note that if $f_{yy}\neq 0, f_{xx}\neq 0$ at a certain point, then $c(x,y)\neq 0$.
So far we have only used the fact that the gradient has unit length. Now we use the second condition, that the Laplacian vanishes. This means that $f$ is harmonic, and so it is the real part of some analytic function
$$F(x,y)=f(x,y)+ig(x,y)$$
Since $F$ is analytic, the Cauchy-Riemann equations are valid, so that
$$f_x=g_y,\quad f_y=-g_x$$
Therefore
$$f_{xy}=g_{yy}=-g_{xx}$$
Consequently,
$$(f_{xy},f_{yy})=(g_{yy},f_{yy}),\quad (f_{xx},f_{xy})=(f_{xx},-g_{xx})$$
so that (1) implies
$$(f_{xx},-g_{xx})=(f_{xx},f_{xy})=c(x,y)(f_{xy},f_{yy})=c(x,y)(g_{yy},f_{yy})=-c(x,y)(g_{xx},f_{xx})$$
but the vector $(g_{xx},f_{xx})$ is clearly perpendicular to the vector $(-f_{xx},g_{xx})$, so it cannot be proportional to it, unless $c(x,y)=0$, which implies that $f_{xx}=f_{yy}=0$, and subsequently also $f_{xy}=0$,   which implies that $f$ is an affine function.
Comment: Thank you very much, but if $f$ is not an harmonic function, (i.e. $\Delta f= a$ with $a$ constant not null), what's happen?
Comment: what do you think will happen? I'll take guesses.
Comment: I don't think change anything

Problem about solution of an PDE system


Algorithmically track a large number of shuffled decks

Question: Lets say an application needs to efficiently store a large number of shuffled decks.  Does there exist a constant-space, constant-time, algorithm  such that:
 index = draw_from_shuffled(element_count, number_of_draws_made, random_seed)

The value returned is the index of the next card to draw from a sorted set.  In addition,  the index will not repeat,  ie:  the same card won't be drawn twice.  The need to store a large number of differently shuffled decks would be replaced with a random number which provides a kind of Initialization Vector in which to order that set of cards.  Storing a n number of shuffled decks, would require storing n number of integer values.
So does an algorithm like this exist?  One way of doing it without constant-time is to use a bloom filter to keep track of cards that have already been drawn.   The data requirements would be constant, but the worst case algorithmic complexity is n!,  which is  not desirable.
Comment: I don't see how the worst case is `n!`. I mean the worst that could happen is that the next card is the last in the deck which will result in worst case of `n`
Comment: Do you mean that the memory used by the algorithm should not depend on the number of decks?
Comment: If you really want a random number, I don't think you can find something like that in constant space and constant time. Because you need to remember what cards you have taken. Unless you want something that is not truly random, in the sense that the next draw of a card is determined by the previous draw, or two previous draws, for example.
Answer: Keep an array of 52 integers where each item is the total number of the corresponding card in all decks (index 1 represents 1 of hearts and the item is initially 1000 for 1000 decks). In the draw function:

Pick a random value, R, between 0 and 1.
Set T to 0
For each item in array:
3-a. Let T = T + item / totalItems
3-b. If T >= R decrement item, decrement totalItems, return the item index
3-c. Go to 3

This algorithm has constant space and constant runtime complexity assuming the number of decks fit in an integer. Perhaps more precisely, the space complexity is O(logD).
Comment: This is exactly the algorithm I wish to avoid.   What if D was infinite?
Comment: @Rook added a new algorithm
Comment: I think algorithm II is right (and I upvoted). Can it be put in an answer on its own?
Comment: Does this algorithm have a name?  Do you have a link?
Comment: Sorry, I wrote this myself and don't have any reference even if it is known


How to display an image when hovering over its title in a View?

Question: In my style sheet (which does seem to be loaded), I have
.snhover_img a { position:relative; }
.snhover_img a span { position:absolute; display:none; z-index:99; }
.snhover_img a:hover span {
    display: block;
    width: 350px;
}

And in the Title field of my View, I have Rewrite results as

      {{ title }}

But I always see both the title and the image. Nothing happens on hover.
The debugger shows. What am I doing wrong?
Note: I am thinking that the style sheet is not really loading. If not, how do I fix that?
Comment: I am thinking that the style sheet is not really loading. If not, how do I fix that?
Answer: I post as answer because I have not reach 50 reputation to post as comment.
When you debug .snhover_img a span is the style { position:absolute; display:none; z-index:99; } applied?


Is it possible to use multi threading while we use singleItemPeekableItemReader in Spring Batch to read a csv?

Question: Is it possible to use multi threading while we use singleItemPeekableItemReader in Spring batch to read a CSV?
I have a CSV file of 100 000 records and need to read that file using Spring Batch and load it into a database. I have used 4 threads for it. But now I have a requirement of combining rows based on a condition and read at a time. For this I have used SingleItemPeekableItemReader of Spring Batch. But after this I am unable to use multithreading.
How to implement multi threading for SingleItemPeekableItemReader?
Comment: What is the use case?
Answer: File operations should not multi-threaded. Its recommended to use single thread alone. If you want performance then you can use batch operations. For faster CSV read operations you can use univocity CSV parser. Its very very fast and provides some useful methods as well.


Define domain of a function, equation is given

Question: Let's say I have
$\frac{d^{2}y(x))}{dx^2}=-\frac{A}{T}$
What can I say about the domain? T is constant,
Given calues for A are 0, 16,0.5
EDIT:
I know that the solution is a function whose domain is an open interval.
Boundary conditions: y(0)=19, y(1)=17
The equation can be solved via integration
Comment: Welcome to [math.se] SE. Take a [tour]. You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit]): What you understand about the problem, what you've tried so far, *etc.*; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Comment: can you share what you have tried?
Comment: It is the first time I encounter such a problem. Could you give me a hint how to solve this?
Comment: any other conditions such as boundary conditions? can you solve the differential equations?
Comment: Yes! Boundary condition y(0) = 19, y(1) = 17
Answer: Upon integrating twice, we get a quadratic equation.
You are given the boundary conditions $y(0)=19, y(1)=17$, the boundary would have defined the domain.
The question is how is domain being defined. If it can be a closed interval, then it is $[0,1]$ since $0$ and $1$ are the boundaries. Suppose there are additional restriction such that a domain must be open, then it is $(0,1)$.


Password as a function and ontime not working correctly

Question: I will try to be as explicit as I can with my problem.
I have a workbook which has all the sheets protected by password and on it lots of codes run when forms are run.
Now this workbook is run on 3 different departments, and in each has a department head who has his own password. The easiest way I tried doing this was first, setting in a module:
Public pass As String

I also have the workbook on a start event to define this variable:
pass = ThisWorkbook.Worksheets("Pass").Range("A1").Value
ThisWorkbook.Worksheets("Pass").Visible = xlSheetVeryHidden

So as you can see I store the password in a A1 of sheet "Pass"
This way the department heads can change there password whenever they want by a form I created. This makes their password secret.
Now all of the workbook goes fine except when it goes into the superuser mode that I created that shows the department heads some hidden sheets and allows them to do monthly audit.
They access this super user mode through a form which has this code:
Private Sub cmdAdd_Click()
   Dim min As Long
   Dim sVal As String
   Dim ws As Worksheet
   Dim wb As Worksheet
   Dim ktime As Date
   Dim wn As Worksheet
   Dim wc As Worksheet
   Set ws = Worksheets("Formularios")
   Set wb = Worksheets("LookupList")
   Set wn = Worksheets("Coordenador")
   Set wc = Worksheets("Time")

If Trim(Me.txtPass.Value) = "" Then
 Me.txtPass.SetFocus
 MsgBox "Por favor inserir Password"
 Exit Sub
End If

If Trim(Me.txtMinuto.Value) = "" Then
  Me.txtMinuto.SetFocus
  MsgBox "Por favor inserir Tempo"
  Exit Sub
 End If

min = CInt(txtMinuto)
sVal = txtPass.Value

If sVal = pass Then
  For Each Worksheet In ThisWorkbook.Worksheets
    Worksheet.Unprotect Password:=sVal
    Worksheet.Visible = xlSheetVisible
  Next

  ktime = Now + TimeSerial(0, min, 0)
  ThisWorkbook.Sheets("Pass").Visible = xlSheetVeryHidden
  ThisWorkbook.Sheets("Coordenador").Range("O" & Range("Coordenador!O1048000").End(xlUp).Row + 1).Value = ktime
  Application.OnTime ktime, "CloseC"
  ThisWorkbook.Sheets("Coordenador").Range("P11") = ktime
  ws.Protect Password:=pass
  wb.Protect Password:=pass
  wn.Protect Password:=pass
  wb.Visible = xlSheetHidden
  Calc
  wc.Unprotect Password:=pass
  wc.Range("I1").Value = "c"
  wc.Protect Password:=pass
  Audit
  Unload Me
  Else: MsgBox "There is a problem - check your password, capslock, etc."
End If
End Sub

As you can see the form asks how many minutes for them to be Super user. And it runs "CloseC" macro at the end of the time, which is the macro that puts everything back together with the passwords and ends Super user.
Here is my issue: If a department Head runs that form twice or more times, in theory it should just add the new time to "Ontime" feature of excel running the macro "CloseC" on the last time that he introduced, however this is not happening and excel is creating a new "Ontime" instance, and still running CloseC on the first time.
When this happens, something strange happens with the code that it no longer lets you run the Super user form, instead it gives the error that the password is incorrect. I can overpass this last error by closing and opening the workbook.
I appreciate any help or ways to improve my code.
Comment: Your theory is incorrect. `OnTime` will always simply add a new scheduled run - you have to explicitly cancel any previous scheduled one.
Comment: Why even put a time limit on the user anyway? There has to be better design than that, no?
Comment: Reading material for you:  https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-ontime-method-excel  and  http://www.cpearson.com/excel/OnTime.aspx
Comment: @Rory Just to see if I understood you correctly, for every time that someone runs the form I would have to cancel the older ontime schedule already been set?
Comment: Yes, that is correct.
Comment: @ScottHoltzman This is just a precaution so the Department heads don't leave super user open. It's a fail safe that helps keep the program from being tempered with.
Comment: @PedroTeixeiradeFreitas - Use the  `Workbook_Open` event to always user super user mode is turned off so everytime someone opens it there is no danger of them seeing SuperUser mode.
Answer: Based on @Rory comment I got this added to the code:
If wn.Range("O2") <> "" Then
        For Tsweep = 2 To Range("Coordenador!O1048000").End(xlUp).Row
        Application.OnTime EarliestTime:=Range("Coordenador!O" & Tsweep).Value, Procedure:="CloseC", Schedule:=False
        Next Tsweep
        wn.Range("O:O").ClearContents
    End If

It appears to be working.
Thank you for your help.


$k$ divides the product of $k$ consecutive integers (case $k=2,3)$

Question: How do I show that for any arbitrary integer $a$, $2|(a+1)$ and $3a|(a+1)(a+2)$?
$2|(a+1)$, if $a$ is even, $2k=a$  replacing $a$ , $2k=a$ for some $k$ in $Z$
\begin{align}a(a+1)&=2k(2k+1)\\
&=4k^2+2k\\
&=2(2k^2+k)\end{align}
shows clearly that $2$ is divisible $(a+1)$
but I can't prove the second part
Comment: @u8y7541 I suspect he/she does. But I was hoping he/she would edit the question to make this clear.
Comment: $2 \mid (a+1)$ is not true if $a$ is even.
Comment: Could you please try to express more clearly your actual problem.
Comment: It is not true that $2\mid (a+1)$ for "any arbitrary integer $a$". You only showed that $2\mid a(a+1)$. The second part is also false - take $a=5$.
Comment: Did you want to say $3\mid a(a+1)(a+2)$? (One of those factors is a multiple of $3$.)
Comment: @LordSharktheUnknown Maybe he meant $2|a(a+1)$ and $3|a(a+1)(a+2)$.
Comment: @LordSharktheUnknown Well, the first part must have been $2|a(a+1)$ because that's how he solves it.
Comment: $2 \not \mid a+1$ for any arbitrary integer as if $a$ is even then $a+1$ is odd and $2 \not \mid a+1$.  I suspect you meant $2| a(a+1)$ which is true.  But you only provd it for and even $a$.  You must also prove it for *every* $a$ even the $a$ that aren't even.  And $3a \not \mid (a+1)(a+2)$ unless $a = 1$.
Comment: "because that's how he solves it. "  But he only solves it for even a.
Comment: ... or a =2....
Comment: There is a typo, it should be $\, 2\mid a(a+1).\, $ See the linked dupe for the general case.
Comment: There are typos. it should be $2∣a(a+1)$ and $\,3\mid a(a+1)(a+2).\,$ See the linked dupe for the general case
Answer: Both statements are actually false.
for $a|(a+1)$ take $a = 2$. Clearly $2$ does not divide $3$
for $3a|(a+1)(a+2)$, take $a = 5$. Clearly $15$ does not divide $6*7 = 42$
Comment: Actually $3a|(a+1)(a+2)=a^2 + 3a + 2\iff a|2$ and $3|a^2 + 2$.  The only possible solution are a = 1 or a=2
Comment: The statement in the OP says for arbitrary $a$
Comment: Um... yeah?  So it is definitely false for an arbitrary $a$ because it is only true for two $a$...


View all allowed ports whether in firewalld or iptables

Question: How can I view the full list of all allowed ports and blocked ports in centos? And I particularly mean all ports and not only those that are in use certain processes. In other words, I am not interested in knowing what process is listening to what ports and I only and only want to know what ports are allowed and not allowed.
Comment: You should not use both iptables and firewalld. It's either the one or the other. Else, it can become messy.
Comment: @Krackout: I know, I'm using a VPS which is pretty messed up and I wanna find why a port does not work in there
Answer: iptables-save shows the full set of current active firewall rules and default policies. From the output you can deduce what is the current set of allowed / disallowed ports on the system.


Why can't I deep link directly to turn by turn navigation on any map app in iOS?

Question: After some searching, I've discovered that there's nothing I can do from my app to open one of the major map apps and start turn by turn navigation immediately. (If you know, please tell me)
In Google Maps, Apple Maps, and Waze, I can deep link into the app and have the route shown to me (usually by setting "saddr" and "daddr"), but human intervention is still required to actually start the navigation. All of these are one click away, but then the actually "Route, start, or go" button is quite small and hard to hit on a phone while you're actually in a car with your phone on a dock.
I'm just curious why this is, I can't figure it out. The only hunch I have is that they have to open a more persistent connection with the device and they want to avoid DoS attacks or something like that. It seems like an easy flag to put in their API, and I've seen various other questions trying to do what I'm trying to do.
And even if all that is true, they can still probably have a different flag where navigation is one click away with a button that covers half the screen, much better than a button barely the size of my fingertip.
Hopefully someone has some expertise on this so I don't go yelling at engineers working on the map apps.
Answer: The answer is simply that none of the major map app developers have allowed this. There is no technical reason why iOS apps couldn't do this; they just don't. The decision is probably because they want to require user interaction before starting directions, as most apps allow the user to edit parameters or choose one of several routes before navigation starts.


Find all windows beneath a point

Question: I want to find all the top-level windows (children of the desktop) beneath a given point on the desktop. I can't find an API for this.
My scenario is that I'm dragging a window across the screen and want to drop it into another (known) window. I can hit test the bounds of the target window ok, but that doesn't tell me whether it's occluded by another (unknown) window. Using WindowFromPoint and friends won't work, because the window being dragged is necessarily directly under the mouse. So I'm wondering if I can obtain all windows at the mouse position, and review them to see whether one of the windows I'm tracking is directly beneath the window I'm dragging.
Is there a way to do this without resorting to EnumDesktopWindows/GetWindowRect on every mouse drag? Or perhaps there's another solution I'm missing.
Comment: If you make the assumption that no new windows will be created while you're dragging, you can enumerate the top-level windows once at the start of the drag operation, and then use the result to test against at every mouse move during the drag.
Comment: I'd say that you are trying to solve this problem the wrong way around. In other words, this might be an XY question. Instead of the window being dragged deciding whether it can be dropped, the *destination* should decide if it is a drop target for the object being dragged. That way, the window being dragged isn't responsible for hit-testing and interrogating all objects that it passes over; rather, each object that it passes over (assuming it is drag-drop-aware) is responsible for deciding whether it can accept that object. Use the `RegisterDragDrop` function for this.
Comment: That's an optimisation worth investigating, thanks.
Comment: You might be able to get away with using `GetNextWindow` and just looking at the windows above your target in the Z Order.
Comment: @theB, thanks, that sounds quite promising too!
Comment: @JimMischel: you are assuming that other windows are not being moved around by their own app while the user is dragging the desired window.
Comment: @RemyLebeau: Yes, that's true. Probably a bad assumption on my part.
Comment: @theB, MSDN made an interesting observation about calling `GetNextWindow` in a loop: The `EnumChildWindows` function is more reliable than calling `GetWindow` in a loop. An application that calls `GetWindow` to perform this task risks being caught in an infinite loop or referencing a handle to a window that has been destroyed.
Comment: A nice tutorial is available here: http://www.catch22.net/tuts/drop-target
Comment: @CodyGray you're right that it's a bit backwards. The problem stems from the fact that the dragged window remains under the mouse which obscures the drop behaviour. I actually want the window to be dragged too. The target window doesn't receive any events as far as I can tell.
Comment: @DrewNoakes EnumChildWindow seems for child windows only while GetNextWindow considers more than children.
Comment: Chrome seems to do exactly what you want (when you drag a tab from one Chrome frame to another), but Spy++ doesn't give many hints.  Visual Studio, creates TOPMOST drop target windows, and I suspect those are found by WindowFromPoint since they remain above the window being dragged.
Comment: Why do you need to find all window under the cursor for *every mouse position*? Just do it once when you release the button.
Comment: @γηράσκωδ'αείπολλάδιδασκόμε, to give feedback during dragging. Whether I do it throughout or at the end, I still have a problem (see question).
Answer: If you ask kindly, WindowFromPoint will ignore your window (the one currently being dragged) and return the next window. This is what Internet Explorer does when you drag a tab.
To do that:

Handle WM_NCHITTEST in window being dragged
Return HTTRANSPARENT during dragging. Call default window proc otherwise.
WindowFromPoint will ignore HTTRANSPARENT windows, but only those belonging to the calling thread. This shouldn't be a problem for you, because you should be calling WindowFromPoint from the window owner thread anyway.
Make sure there're no child windows at point passed to WindowFromPoint, or handle WM_NCHITTEST for these child windows as well.

Troubleshooting (if you still get your window from WindowFromPoint)

Test GetCurrentThreadID() == GetWindowThreadProcessId(WindowFromPoint(), 0) to ensure you're calling from correct thread
In WM_NCHITTEST, test that hwnd parameter equals what you get from WindowFromPoint()

Example (the area within rectangle returns the underlying window from WindowFromPoint):
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static const RECT s_TransparentRect = {100, 100, 200, 200};

    switch (message)
    {
    case WM_NCCREATE:
        SetTimer(hWnd, 1, 100, 0);
        break;
    case WM_TIMER:
        {
            POINT cursorPos;
            GetCursorPos(&cursorPos);

            TCHAR buffer[256];
            _snwprintf_s(buffer, _countof(buffer), _TRUNCATE, _T("WindowFromPoint: %08X\n"), (int)WindowFromPoint(cursorPos));
            SetWindowText(hWnd, buffer);
        }
        break;
    case WM_PAINT:
        {
            PAINTSTRUCT ps;
            BeginPaint(hWnd, &ps);
            Rectangle(ps.hdc, s_TransparentRect.left, s_TransparentRect.top, s_TransparentRect.right, s_TransparentRect.bottom);
            EndPaint(hWnd, &ps);
        }
        break;
    case WM_NCHITTEST:
        {
            POINT cursorPos;
            GetCursorPos(&cursorPos);
            MapWindowPoints(HWND_DESKTOP, hWnd, &cursorPos, 1);

            if (PtInRect(&s_TransparentRect, cursorPos))
                return HTTRANSPARENT;
        }
        break;
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}

Comment: Thanks very much. This promises to avoid repeated (linear in number of top-level windows) API calls. Will experiment and get back to you.
Comment: Thanks again. With some experimentation this turned out quite well.
Comment: Did you need any extra steps I didn't mention?
Comment: And you're welcome, that was an interesting question to investigate.
Comment: @Codeguard Will this technique work if the drag is occurring using a standard title bar (i.e., the non-client area)?
Comment: I expect that yes, but just give it a try.
Comment: @Codeguard I've tried it out but can't get it to work.  Would you mind checking out my question here? https://stackoverflow.com/q/68701511/15284017
Answer: Right, you already know what WindowFromPoint() is going to return, should be the one you are dragging.  Then use GetWindow() with uCmd = GW_HWNDNEXT to get the one below it in the Z-order.  GetWindowRect() to get its bounds, IntersectRect() to compute the overlap.
Keep calling GetWindow() to find more windows that might be overlapped.  Until it returns NULL or the overlap is good enough.  If not then you'll normally favor the one that has the largest result rectangle from IntersectRect().
Comment: Took this for a spin and found that hit testing the rectangle is not enough. There are loads of windows on the desktop that get picked up, even though they're not visible from the user's perspective. For example, a window with title `AXWIN Frame Window` appears, having innocent enough (ex)styles. Is there some other means of testing visibility? Testing the rectangle can also fail for layered windows.
Comment: Add a test on IsWindowVisible()
Comment: Thanks, that seems to work well. Scanning on my machine runs sub-millisecond, which is great. Still it fails for layered windows having transparent regions.

Find all windows beneath a point


Prerequisites to measure theoretic statistics

Question: I am trying to teach myself statistics at a deep, measure theoretic level. I've started reading some statistics textbooks that teach statistics in this way, but I find that I am confused on background concepts like measure theory. I'm wondering what topics I should learn before tackling statistics in this way. I have familiarity with basic linear algebra (vectors, matrices, etc.) as well as basic pointwise topology. I am also reading through "Principles of Mathematical Analysis" by Rudin to prepare myself to learn measure theory.
My question is: are there any other concepts/fields I should look into/learn?
Answer: If you're going to learn measure theoretic probability theory, here's what I think should be the idea course of action; depending on how much you know already and wherever you want to stop, truncate it accordingly. I am assuming you have a fair working knowledge of basic probability at the level of say, Feller Vol 1.
First, get a good handle on analysis. Baby Rudin is a good book for this, but depending on your background, it can be intense. If you find it difficult initially like I did, consider moving to an easier, well written book. The one I went to was Terence Tao's Analysis. Once you're done with that, Rudin should be much easier to handle. You can skip the parts on multivariable calculus.
Next, get a good hold of measure theory. Rudin's next book, Real and Complex Analysis, is an option, but you might want to consider books like Analysis by Royden. Some knowledge
of $L^p$ spaces should be sufficient. An excellent but intense book for this is the text by Folland.
After this, you might want to move on to a proper text on probability. Books by Rick Durrett and Billingsley are the ones I've read, but there are a bunch of other texts in this regard that you might want to look up as well.
After this, there's a bunch of topics you can pick and choose to study (if you wish to). Brownian motion, stochastic calculus (Ito/Strato), martingale theory, and so on. You might not need much of this but even if you don't, it's possible you'll find a lot of it very interesting. And there are of course a ton of free resources available online; if you don't get access to these books themselves, you should be able to get a hold of their contents and look stuff up accordingly. Hope that helps!
Comment: There is a small typo in Brownian motion, and I would say that everyone who is serious about probability should know what martingales are.