Circle inversion of a circle

Question: Given is a circle K with radius r and centre M1. K' is a second circle with radius r' and centre M2 that cuts K in two points A and B so that $[M1A]$ is orthogonal to $[M2A]$ and also $[M1B]$ is orthogonal to $[M2B]$.
We noted:

Now through inversion on K, every circle K' is being reflected onto itself.

Why is this so?
We also noted that a circle conversion of a line gives a line again. Again: why a line and not a circle? Trying to visualize it I get an arc..
Comment: This is completely wrong.
Comment: Inversion with which centre? which radius?
Comment: Inversion with centre of K. More it does not say.
Comment: By middlepoints, you mean centers of the circles?
Comment: @JeanMarie Yes, exactly. I should correct this above!
Comment: @darijgrinberg the thesis should now be correct, right?
Comment: As to the line issue: It's true that inversion of **a line through the center of inversion** is the same line (with its points rearranged). Lines not-through the center of inversion become circles through that center. (Just think about how the center of inversion and the point at infinity have to exchange places.)
Answer: I think this is the situation:

As you can see the inversion of any point C on K' is a point F which is also on K'.
Comment: Sorry, I did not save it. I created the red circle, then added a point outside of it for $M_2$. I took the tangent lines from that point and marked the tangent points $A$ and $B$. The blue circle goes through those points. Tangent lines are orthogonal to radial lines. To get the green points, I picked an arbitrary point on the blue circle and drew tangent lines to the red circle. Finally the inversion is on the midpoint between $D$ and $E$.
Comment: Thank you! How did you do it? Would you mind sending me the ggb-data? :)
Answer: Regarding a proof of the proposition, consider the following diagram:

So we are given:

The triangle formed by the two centres and $A$ is right. Algebraically $d^2=r^2+r'^2$.
$C$ is a random point on the second circle with inversion $C'$. $D$ is their midpoint. So $C,C'$ lie at distances $q+t,q-t$ from $M_1$ respectively.
$C,C'$ being inversions means that $(q+t)(q-t)=r^2$.

We are two show that:

$C'$ lies on the blue circle iff $C$ does.
This is equivalent to saying that the midpoint $D$ is placed in a way so that the dotted line $s$ meets the segment $C' C$ at a right angle.
In other words, $s$ must divide the triangle formed by the two centres and the point $C$ into two right triangles.
So if we can show that $d^2-q^2=s^2=r'^2-t^2$, we are done.

The steps to show this are:

From earlier on we have: $r^2=(q+t)(q-t)=q^2-t^2$.
Substituting this expression for $r^2$ into the equation $d^2=r^2+r'^2$ and subtracting $q^2$ from both sides leads to the desired goal.
Comment: Awesome! Thank you so much :)

Circle inversion of a circle


How many times have two teenagers combined for a goal in Europe's top 5 leagues?

Question: In Manchester United's game against Wolves last night some interesting piece of trivia happened. The goal that won it for United was both scored and assisted by a teenager. This was only the second time in PL history that this happened.
This made me wonder how many times it has happened in Europe's other top leagues.
Comment: I note that the Opta tweet was specifically talking about *winning* goals that were scored and assisted by teenagers, whereas the question is asking about *all* goals.
Comment: The source for the claim that this was the 2nd time in the Premier League is the [tweet by OptaJoe](https://twitter.com/OptaJoe/status/1753349905576308846)?
"2 - Kobbie Mainoo's (18) goal last night, assisted by Omari Forson (19), was only the second winning goal in @premierleague history to be both scored & assisted by a teenager, after Cristiano Ronaldo (19) assisting Wayne Rooney (18) for Man Utd v Liverpool (Jan '05). Carrington."
Answer: It happened yesterday, Saturday, February 3rd in LaLiga in the match of Deportivo Alaves against FC Barcelona: Hector Fort (2006-08-02 / 17y185d) assisted Vitor Roque (2005-02-28 / 18y6d) to score the decisive 1:3 for Barcelona in minute 63.
So, this is either an incredible coincidence that it happened twice in consecutive days, or it is not actually that rare.
It does seem that players get drafted at ever younger ages into top clubs, so I would expect this to be or at least become more common.
Some other notable facts are that both players were only substituted in during the second half, Fort in minute 46 and Roque in minute 59, only 4 minutes before he scored the goal. Roque also only played 13 minutes, collecting two yellow cards in minutes 67 and 72.


Downloading a folder with phpseclib Net_SFTP.get does not work

Question: I am trying to access a file in an SFTP folder server using phpseclib. But when I try using $sftp->get, it returns false. I am not sure how to debug the problem at all.
public function get_file_from_ftps_server()
{
    $sftp = new \phpseclib\Net\SFTP(getenv('INSTRUM_SERVER'));
    if (!$sftp->login(getenv('INSTRUM_USERNAME'), getenv('INSTRUM_PASSWORD'))) {
        exit('Login Failed');
    }

    $this->load->helper('file');
    $root  = dirname(dirname(__FILE__));
    $root .= '/third_party/collections_get/';
    $path_to_server = 'testdownload/';
    $result = $sftp->get($path_to_server, $root);

    var_dump($result);
}

In the $result, I get a false and I am not sure why its happening, I read their documentation but still not sure. Root is the directory where I want my information to be stored. Right now I only added a trial.xml file there, but also wondering how can I get multiple files if its in the folder.
Here is a picture of the server structure:
Comment: If you want to download a _folder_ with phpseclib try the technique described at https://stackoverflow.com/a/36558913/569976
Comment: @neubert thats a whole folder, why not just the file?
Comment: As Martin Prikryl pointed out, your post makes it sound like you're asking about a folder. Anyway, it looks like Martin Prikryl is on the right track.
Answer: Normally when I use sftp, I normally change directory and then try to download the information.
$sftp->pwd(); // This will show you are in the root after connection.
$sftp->chdir('./testdownload'); // this will go inside the test directory.
$get_path = $sftp->pwd()
//If you want to download multiple data, use
$x = $sftp->nlist();
//Loop through `x` and then download the file using.
$result = $sftp->get($get_path); // Normally I use the string information that is returned and then download using

file_put_contents($root, $result);

// Root is your directory, and result is the string.

Comment: how is this downloading the file to your local? aren't you just writing the content of a file from $get_path into string $result and then writing it into a file in the path $root?
Comment: how is your `file_put_contents` working? isn't `($fileName, $result)`?
Answer: The Net_SFTP.get method can download a single file only. You cannot use it to download a whole directory.
If you want to download whole directory, you have to use one of the "list" methods (Net_SFTP.nlist or Net_SFTP.rawlist) to retrieve list of files and then download the files one-by-one.
Comment: But your code cannot work. You cannot specify a path to a *folder* as `$remote_file` and `$local_file`. You have to use a path to a *file*: `$sftp->get("/testdownload/trial.xml", "/third_party/collections_get/trial.xml");`
Comment: "Doesn't work" doesn't work as problem description. Show us a log file.
Comment: I could not even download one file in the start. I can try the list method afterwards, first I need to get 1 file.
Comment: Hi Martin sorry for the late reply, but when I try to var_dump( $result ) I only get true or false, how can I show you the log file?
Comment: I made the edits to the code just like you said, it just returns a false in result.
Comment: `echo $sftp->getSFTPLog();` (first hit in google for *"phpseclib logging"*)
Comment: even the sftp->getSFTPLog() returns false.
Comment: You have to put `define('NET_SFTP_LOGGING', NET_SFTP_LOG_COMPLEX);` before the `new`?
Comment: This is what I get Array ( [0] => -> NET_SFTP_INIT (0.0007s) [1] => <- NET_SFTP_VERSION (0.0469s) [2] => -> NET_SFTP_REALPATH (0.0007s) [3] => <- NET_SFTP_NAME (0.0472s) [4] => -> NET_SFTP_OPEN (0.0007s) [5] => <- NET_SFTP_STATUS (0.0471s) )
Comment: What does `getLastSFTPError()` return? Are you using a correct path? Are you using the same credentials as in FileZilla?
Comment: Do `define('NET_SFTP_LOGGING', SFTP::LOG_COMPLEX');`. `NET_SFTP_LOG_COMPLEX` is what you do for the 1.0 branch - not for the 2.0 branch. So do `SFTP::LOG_COMPLEX`, put the output on pastebin.com and post the link.
Comment: @Bahman That's too many questions to be answered in a comment. Post a separate question.
Answer: <?php
use phpseclib\Net\SFTP;

$sftp = new SFTP("server");

if(!$sftp->login("username", "password")) {
    throw new Exception("Connection failed");
}

// The directory you want to download the contents of
$sftp->chdir("/remote/system/path/");

// Loop through each file and download
foreach($sftp->nlist() as $file) {
    if($file != "." && $file != "..")
        $sftp->get("/remote/system/path/$file", "/local/system/path/$file");
}
?>

Answer: I'm a bit late but nonetheless I wanted to share this.
The approach I take is to use zip files to download folders. The reason for this is that you will have a feedback that something is being downloaded.
If you don't want that, simply remove the things related to zip. Then, remove the headers and replace them with $sftp->get("remote/file", "local/file");
<?PHP
use phpseclib\Net\SFTP;

$sftp = new SFTP("IP:Port");

if(!$sftp->login("username", "password")) throw new Exception("Connection failed");

# Create directory variable
$directory =  "/remote/path/";

# Set directory
$sftp->chdir($directory);

# File Name
$name =  'file';

# Retrieve file
$file = $sftp->get('file');

# Check if is folder
if ($sftp->is_dir($file)) {

  # Temporarily file
  $tmp = sys_get_temp_dir()."\\yourSite_".rand().".zip";

  # Create new Zip Archive.
  $zip = new ZipArchive();

  # Open new Zip file
  $zip->open($tmp,  ZipArchive::CREATE | ZipArchive::OVERWRITE);

  function recursive($src, $zip, $sftp) {

    # Loop Through files
    foreach ($sftp->nlist($src) as $file) {

     # Skip . & ..
     if ($file == "." || $file == "..") continue;

     if (!$sftp->is_file($src . "/" . $file)) {

          # Make directory
          $zip->addEmptyDir($src . "/" . $file);

          # Run the loop again
          recursive($src . "/" . $file, $zip, $sftp);

        } else {
          # Add file to zip within folder
          $zip->addFromString($src . "/" . $file,  $sftp->get($src . "/" . $file));

      }

    }

  }

  # Run Recursive loop
  recursive($name, $zip, $sftp);

  # Close zip file
  $zip->close();

  header('Content-Description', 'File Transfer');
  header('Content-type', 'application/zip');
  header('Content-Disposition', 'attachment; filename="' . $name . '.zip"');
  header('Content-length', filesize($tmp));

  echo file_get_contents($tmp);

  # Delete temporarily file
  unlink($tmp);
  return;

}

# Otherwise download single file
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=\"". $name ."\"");

echo $file;
return;


Securing REST APIs with NGINX

Question: Hi I have an API behind NGINX. The API is configured to require authentication for all actions. I want to have an NGINX proxy in front of it to pass authentication parameters for some of the actions so they can be accessible without authentication.
Authentication works fine on the main location, however when I try to specify specific path in NGXINX location, it still prompts me for credentials.
Important thing here is that the only action I want to allow is STATUS. Everything else shouldn't be picked up by the second location.
Is there a way to do this without PCRE or regex matching?
<code>    location / {
            add_header 'Access-Control-Allow-Origin' *;
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Headers' 'Content-Type,Accept';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header X-Proxy-Cache $upstream_cache_status;
            proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie;
            proxy_hide_header Cache-Control;
            proxy_hide_header Set-Cookie;
            proxy_pass http://backend;
             add_header 'Location1' '1';

         location /1/2/3?action=STATUS {
                add_header 'Location2' '2';
                proxy_set_header Authorization "Basic BLAHBLAHBLAH";
                proxy_pass http://backend;

        }

    }
</code>
Answer: Location matching is done against a normalized URI that doesn't contain query string.
So it's necessary to use an if block in this case :
<code>location /1/2/3 {

    if ($arg_action != "STATUS") {
        return 403;
    }

    add_header 'Location2' '2';
    proxy_set_header Authorization "Basic BLAHBLAHBLAH";
    proxy_pass http://backend;

}
</code>

Securing REST APIs with NGINX


How do I use a standard distribution to guess where the value falls in the future?

Question: I have a mean value x and I want to model it into the future. I want to output a value of what it could be in 6 months. Assuming the value follows a normal distribution and we have the standard deviation how do I randomize the value x while following a normal distribution? I'm doing this in excel, but just understanding it would help too! Basically I want to produce numbers 68% of the time within 1 deviation, 95% of the time withing 2 deviation etc. etc.
Comment: We need to know the mean of the distribution too.
Comment: Apologize. X is the mean
Comment: possible duplicate of [Produce random numbers with specific distribution with Excel](http://stackoverflow.com/questions/6241784/produce-random-numbers-with-specific-distribution-with-excel)
Comment: I believe the Norminv will actually just give a uniform type distribution. RAND() is just a uniform 0-1
Comment: Basically I want to produce numbers 68% of the time within 1 deviation, 95% of the time withing 2 deviation etc. etc.
Answer: You can use the excel function 'NORMINV' to convert a random input 'RAND()' to a normal distribution.
<code>=NORMINV(RAND(),Mean,Std Dev)
</code>
i.e. if you repeat this many times, save and analyze the results, you'll see a bell curve over the input Mean value.
Does that get you started?
The tricky bit comes when you come up with the formula to predict what a value will be in the future using this.


Como tratar a permissão de KB por usuário

Question: Tenho uma KB que quero habilitar para determinado usuário.
E para outros usuários não quero acesso a esta KB.
Como tratar isto no Genexus Server ?
Answer: Pode definir um ROLE (papel) específico para o usuário dessa KB (isso desde o Tab Security do console principal).
Logo, na parte de segurança dessa KB (tab Security dentro da KB) o administrador pode dar privilégios para esse ROLE (papel) e tirar para os outros papéis.
Comment: A dúvida e foi comprovado é que existe e funciona é que o PAPEL(Role) a nível de KB(Admin, KBuser, Unknow) e configuração de papel por KB(KBUser), ai sim funciona.


SharePoint CustomAction button for edit user permissions

Question: everyone. Please tell what is the location and group for this ribbon (List settings - list permissions) for CustomAction element and for CommandUIDefinition?
I tryed different from this page https://msdn.microsoft.com/en-us/library/bb802730(v=office.14).aspx but not successfully.
Here is my element:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
  Id="BreakRoleInheritance"
  Location="CommandUI.Ribbon"
  Rights="FullMask">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
          Location="Ribbon.Permission.Parent">
          <Button
           Id="Ribbon.ListEdit.Permissions.BreakRoleInheritance"
           Alt="Break Role Inheritance"
           Sequence="1"
           Image32by32="/_layouts/1049/images/formatmap32x32.png"
           Image32by32Left="-384"
           Image32by32Top="-32"
           Command="BreakRoleInheritance"
           LabelText="Break Role Inheritance"
           CommandType="General"/>
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
         Command="BreakRoleInheritance"
         CommandAction="javascript:alert('Hello World');" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
</Elements>

Answer: I've never done this but hazrding a guess it would possibly be
Ribbon.BDCAdmin.PermissionManagement
Not sure if this is correct but have a try
https://msdn.microsoft.com/en-us/library/ee537543(office.14).aspx
Hope this helps
Answer: In this file I found all groups and locations and much more \14\TEMPLATE\GLOBAL\XML\CMDUI.XML
So, my customaction now looks like:
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction ScriptSrc="Script.js" Location="ScriptLink" Sequence="1">
  </CustomAction>
  <CustomAction
    Id="N.Ribbon.BreakRoleInheritanceButton"
    Location="CommandUI.Ribbon">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.Permission.Parent.controls._children">
          <Button
            Id="N.Ribbon.BreakRoleInheritanceButton"
            Alt="Прекратить и очистить наследование разрешений"
            Command="N.Ribbon.BreakRoleInheritanceButton.Command"
            Sequence="31"
            Image16by16="/_layouts/$Resources:core,Language;/images/formatmap16x16.png" Image16by16Top="-144" Image16by16Left="-112"
            Image32by32="/_layouts/$Resources:core,Language;/images/formatmap32x32.png" Image32by32Top="-32" Image32by32Left="-384"
            Description="Прекратить наследование разрешений и очистить имеющиеся"
            LabelText="Прекратить и очистить наследование разрешений"
            ToolTipTitle="Прекратить и очистить наследование разрешений"
            ToolTipDescription="Прекратить наследование разрешений и очистить все имеющиеся разрешения"
            TemplateAlias="o1" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
          Command="N.Ribbon.BreakRoleInheritanceButton.Command"
          CommandAction="javascript: breakSecurityInheritance();"
          EnabledScript="javascript: getObjectProperties();"/>
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
</Elements>


Continuous functions $f,g:X\rightarrow X.$

Question: Let $X\subseteq\mathbb{R}$ and let $f,g:X\rightarrow X$ be continuous functions such that $f(X)\cap g(X)=\emptyset$ and $f(X)\cup g(X)=X.$ Which of the following set can't equal to $X?$
$1.[0,1]$
$2.(0,1)$
$3.[0,1)$
$4.\mathbb{R}$
According to me $X$ can't equal to $[0,1]$ as if $X=[0,1]$ then both of the functions must have fixed points. But i don't know exact reason. Please help. Thanks.
Answer: If $X$ is compact and $f$ is continuous then $f(X)$ must be compact. Now, can you find such $f(X)$ and $g(X)$ s.t. $f(X)∩g(X)=\emptyset$ and $f(X)\cup g(X)=X$?


Match letter in any language

Question: How can I match a letter from any language using a regex in python 3?
re.match([a-zA-Z]) will match the english language characters but I want all languages to be supported simultaneously.
I don't wish to match the ' in can't or underscores or any other type of formatting. I do wish my regex to match: c, a, n, t, Å, é, and 中.
Comment: @Tony318 I happen to have majored in Japanese ... That approach is wrong on so many levels...
Comment: possible duplicate of http://stackoverflow.com/questions/2039140/python-re-how-do-i-match-an-alpha-character
Comment: I can't think of a logical way to go about this. Most languages do not match the english alphabet. For instance, if you tried to match a 'k' in japanese you wouldn't be able to do it. Their language only contains 'ka' 'ki' 'ku' 'ke' 'ko' but they are represented by symbols so a K would not match to any specific character. For this to work, you would essentially need to take a language and "translate" it into an english equivalent. So if you encountered "good morning" in japanese こんにちは you would have to "translate" that to "konnichiwa" before doing a regex match.
Comment: @Martin Despite it being "right" or "wrong" how else could you possibly go about using a regular expression to match an alphabet to a phonetic syllabary?
Comment: @Marty, good catch, the answer there even used `\d` in the negated character class (unlike my puny answer).
Comment: @Tony318: This is not only *not* hard, it is trivial with Unicode regular expressions, because Unicode has a derived property called Alphabetic that handles these.  Note that the Unicode property Alphabetic is **not the same** as all the letters.  Rather, it is GC=Letter + GC=Letter_Number + Other_Alphabetic, which picks up things like the Greek iota subscript and the circled letters.
Comment: I think what you want here is not a regex, but Python's built-in [isalpha](https://docs.python.org/2/library/stdtypes.html#str.isalpha).  For example: `str([c for c in s if c.isalpha()])`
Answer: For Unicode regex work in Python, I very strongly recommend the following:

Use Matthew Barnett's regex library instead of standard re, which is not really suitable for Unicode regular expressions.
Use only Python 3, never Python 2. You want all your strings to be Unicode strings.
Use only string literals with logical/abstract Unicode codepoints, not encoded byte strings.
Set your encoding on your streams and forget about it. If you find yourself ever manually calling .encode and such, you're almost certainly doing something wrong.
Use only a wide build where code points and code units are the same, never ever ever a narrow one — which you might do well to consider deprecated for Unicode robustness.
Normalize all incoming strings to NFD on the way in and then NFC on the way out. Otherwise you can't get reliable behavior.

Once you do this, you can safely write patterns that include \w or \p{script=Latin} or  \p{alpha} and \p{lower} etc and know that these will all do what the Unicode Standard says they should. I explain all of this business of Python Unicode regex business in much more detail in this answer. The short story is to always use regex not re.
For general Unicode advice, I also have several talks from last OSCON about Unicode regular expressions, most of which apart from the 3rd talk alone is not about Python, but much of which is adaptable.
Finally, there's always this answer to put the fear of God (or at least, of Unicode) in your heart.
Comment: yeah, except when u have to do it in redshift udf, which is only python 2 and doesn't support anything with an embedded c library, so barnett's regex library is out
Answer: What's wrong with using the \w special sequence?
# -*- coding: utf-8 -*-
import re
test = u"can't, Å, é, and 中ABC"
print re.findall('\w+', test, re.UNICODE)

Comment: `\w` matches also digit `[0-9]` and underscore `_`
Comment: Very good, that is the right answer under the standard Python library (although I always use Unicode literals myself).  Note that according to [UTS#18](http://unicode.org/reports/tr18/#Categories), a "word" char à la `\w` covers 102,724 code points in Unicode 6.0 and  is any GC=L (100,520), GC=M (1,492), GC=Nd (420), GC=Nl (224), or GC=Pc (10) code point. Python's `re` is a bit dated so hasn't kept up with the standard, but it is close-ish. You can use Matthew Barnett's `regex` instead if you want to match the Unicode Standard exactly; it also provides `\p{alpha}`, which is what you want here.
Comment: @M42: It's rather more complicated than that, but yes. Python's normal `re` library is [not good for Unicode](http://stackoverflow.com/questions/7063420/perl-compatible-regular-expression-pcre-in-python/7066413#7066413), although it's close to [RL1.2a](http://unicode.org/reports/tr18/#Compatibility_Properties) but lacks basic properties per [RL1.2](http://unicode.org/reports/tr18/#Categories) and full properties per [RL2.7](http://www.unicode.org/reports/tr18/tr18-14.html#Full_Properties). For almost any Unicode regex work in Python you should use Matthew Barnett's `regex` library instead.
Answer: You can match on
\p{L}

which matches any Unicode code point that represents a letter of a script. That is, assuming you actually have a Unicode-capable regex engine, which I really hope Python would have.
Answer: Build a match class of all the characters you want to match. This might become very, very large. No, there is no RegEx shorthand for "All Kanji" ;)
Maybe it is easier to match for what you do not want, but even then, this class would become extremely large.
Comment: @Baz: I recommend against the histogram.  BTW, You forgot to decode your text!!!  U+0092 is `PRIVATE USE TWO` and U+0094 is `CANCEL CHARACTER`, which are really never going to be found in legitimate Unicode text. Those are not printable characters. which is why Python escaped them. Somehow you have lied about your decoding, or something lied to you — I'll bet $100 that it was Microsoft, the usual culprit in these mendacities.  Change your decoder from real Latin-1, meaning ISO-8859-1, to the bogus proprietary non-Latin-1 version called Windows-1252, and those should go away.
Comment: I didn't realise it would be so tricky... I'll start by making a histogram of the characters in all the text I wish to process...
Comment: That depends on the regex engine. You can match on the script property in some engines, such as Perl's where you can just select the Han script (those are *Han* characters, even though they're used by the Japanese as well and called Kanji there).
Comment: Sure, you can do that for *one* script a time - but not for *every* one at the same time (Let's not discusss the Han/Kanji problematics here... that is a long, bloody history, no, many characters are not exactly alike)
Comment: My histogram:{'\x91': 3, '¡': 1, ' ': 559754, '£': 18, '$': 111, '&': 5, '.': 75528, '0': 1690, '2': 676, '4': 347, '6': 285, '8': 193, ':': 389, 'á': 2, 'ã': 1, 'b': 33405, 'å': 3, 'd': 75349, 'f': 36969, 'é': 35, 'h': 126063, 'j': 5085, 'í': 1, 'l': 89233, 'n': 141244, 'ñ': 6, 'p': 30443, 'ó': 7, 'r': 111273, 't': 201222, 'v': 20584, 'x': 2350, 'z': 2295, '\x92': 14, '\x94': 1, '!': 10896, '#': 568, '%': 5, "'": 33612, '+': 1, '-': 15667, '/': 12, '®': 1, '1': 968, '3': 332, '5': 520, '´': 3, '7': 232, '¶': 1, '9': 275, '=': 1, '?': 17280, '[': 2, 'a': 163349, 'à': 4, 'c': 47806, 'â': 1, ...
Comment: @Martin Of course there is a regex shorthand for "all Kanji": it's `\p{Script=Han}`, or just `\p{Han}` for short. You won't be able to get the thing's actual "name" without going through something like the Unihan database, but you certainly know which code points are CJK ideographs!  I regularly use pattern that restrict to certain scripts, like `[\p{Latin}\p{Greek}\p{Common}\p{Inherited}]`.
Answer:
import re

text = "can't, Å, é, and 中ABC"
print(re.findall('\w+', text))

This works in Python 3. But it also matches underscores. However this seems to do the job as I wish:

import regex

text = "can't, Å, é, and 中ABC _ sh_t"
print(regex.findall('\p{alpha}+', text))
Answer: As noted by others, it would be very difficult to keep the up-to-date database of all letters in all existing languages. But in most cases you don't actually need that and it can be perfectly fine for your code to begin by supporing just several chosen languages and adding others as needed.
The following simple code supports matching for Czech, German and Polish language. The character sets can be easily obtained from Wikipedia.
import re

LANGS = [
    'ÁáČčĎďÉéĚěÍíŇňÓóŘřŠšŤťÚúŮůÝýŽž',   # Czech
    'ÄäÖöÜüẞß',                         # German
    'ĄąĆćĘꣳŃńÓ󌜏źŻż',               # Polish
    ]

pattern = '[A-Za-z{langs}]'.format(langs=''.join(LANGS))
pattern = re.compile(pattern)
result = pattern.findall('Žluťoučký kůň')

print(result)

# ['Ž', 'l', 'u', 'ť', 'o', 'u', 'č', 'k', 'ý', 'k', 'ů', 'ň']

Answer: For Portuguese language, use try this one:
[a-zA-ZÀ-ú ]+

Match letter in any language


Add Clear Button to Comment Field?

Question: Use Case: User wants to clear his comments to rewrite it.
When the User is populating the Comment field, I would like to offer a Clear or Cancel button that will remove the content.
Answer: OPTION 1

Use hook_form_alter to add a Clear or Cancel button/anchor tag(blank)
Add simple JS code to clear the fields

OPTION 2

Use hook_form_alter to add a Clear or Cancel button/anchor tag(blank)
Use Drupal AJAX Framework

UPDATE
You can use the hook_form_alter() inside your template.php file which is better based on your comment being more on the front-end side.
Next is you just need to get the ID of the form you want to alter/update by its form id value and just converting the dashes to underscores. An example would be:
<form id="leo-form">
  // form elements here
</form>

then you need to target it in your hook_form_alter() like so:
// Implements hook_form_alter.
function themename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'leo_form') {
    // place your code to add the clear button here
  }
}

Comment: If you don't mind clearing the entire form, you could just do 1. Use hook_form_alter() to add  to the form.
Comment: That's awesome! I forgot about that. This solution is clean and straightforward than the options I've suggested.
Comment: Ok, am I to assume that I'm creating a custom module to use hook_form_alter ? I don't have significant custom dev exp. I more of a front-end GUI guy.
Comment: oh! thats alright too! i have updated my answer to suite your needs. hope it helps.

Add Clear Button to Comment Field?


Ruby HTTP POST - Errors

Question: Can someone explain to me why I am getting this error when doing this POST? I pulled the snippet from the Ruby-docs page.
undefined method `hostname' for #URI::HTTP:0x10bd441d8 URL:http://ws.mittthetwitapp.com/ws.phpmywebservice (NoMethodError)

Perhaps I am missing a require or something?
require 'net/http'

uri= URI('http://ws.mywebservice.com/ws.php')
req = Net::HTTP::Post.new(uri.path)
req.set_form_data('xmlPayload' => '<TestRequest><Message>Hi Test</Message></TestRequest>')

res = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end

case res
 when Net::HTTPSuccess, Net::HTTPRedirection
 # OK
else
 res.value
end

Comment: use ``URI.parse("http://ws.mywebservice.com/ws.php")``
Comment: Thanks. Same error when doing so:
Comment: Error: res = Net::HTTP.start(uri.hostname, uri.port) do |http|
Comment: It should be `uri.host`.
Comment: changing to uri.host fixed it thanks. please post as the answer so I can give you credit
Comment: `uri.host` is correct, as is `uri.hostname`. And, the example code works correctly on Ruby 1.9.3.
Answer: If you're using a version of Ruby prior to 1.9.3, you should use uri.host.
URI#hostname was added in Ruby 1.9.3. It is different than URI#host in that it removes brackets from IPv6 hostnames. For non-IPv6 hostnames it should behave identically.
The implementation (from APIdock):
def hostname
  v = self.host
  /\A\[(.*)\]\z/ =~ v ? $1 : v
end

Ruby HTTP POST - Errors


When should one use flats or sharps when transcribing?

Question: All I know is that:

if the song has an F chord then it should be flats
but if it has a B chord it should be sharps

In this song, the chords are Dm B♭ F C and a transition chord which is C♯dim/D♭dim
My question is do I use C♯dim or D♭dim?
For more context if needed:

Also, side question: is the key F or Dm?
This is important for the forum that I am uploading transcriptions to.
Edit: this question isn't specifically for this song.. It's in general. The song was just an example.
Comment: What's the copyright status of this piece of music? I think SE shouldn't condone people being able to download a transcription of the piece, free, if they should buy a copy.
Comment: This is just a transcription request. You need to learn about keys and key signatures to do this. It isn't a Q&A topic.
Comment: You could strip out the entire "for more context if needed" section and still have a perfectly coherent and answerable question. This is very obviously not a transcription request.
Comment: I think it's not really possible to give a simple answer to the broader question of how to know whether to transcribe with a sharp or flat in every situation. There are too many variables and the decision is a complicated one. The more music theory you learn, the better you'll understand when to use a sharp versus a flat.
Answer: The key signature says either F major or D minor. Sort of vague. Were there some C♯s in the piece, it would point more towards D minor - and I suspect the C♯ diminished chord could be used in evidence.
As far as changing key - obviously one is bound by the new key signature. If it went into E major, there'd be sharps, E♭ major, flats, but as far as diminished chords are concerned, we tend to take the lowest note as the root. They are symmetrical, so could have four (or more) names. I've seen the same diminished chord with different names in different places in the same piece.
Since in the original, that diminished leads to Dm, C♯o seems like a better option. So, transcribing it into, say, G major, it would become D♯o, into C major, it's G♯o - taking its name from the fact it's leading to the relative minor. But - if there was, say, in the last example, a bass note of D, it could be Do.
EDIT: the title needs addressing. It must mean accidentals, because the sharps or flats in the new key are a given. That can't be any other than one key signature. So, with that in mind, generally, in flat keys, additional accidentals are kept to flats, and vice versa. The reader already has his 'flat hat' on, so continuing with that mindset is good. There are occasions where technically an accidental neeeds to be disobeying that 'rule'. For example, in key F, if there's a C+, using C E and G♯, that accidental won't be correct written as A♭, even though the key sig. has a flat already. It also helps to explain the function of certain harmonies better that way.
Answer: First, to answer your title question, once you determine what the key of the song is then that will determine whether you use sharps or flats for the key signature. G,D,A,E,B are sharp keys and F, Bb, Eb, Ab, Db are flat keys. C is none and F#/Gb can go either way, 6 sharps or 6 flats.
Your first sentence isn't really accurate. If instead of saying "has an x chord" you were to say if the song were in the key of F or B then you would be right about the flats and sharps in the key signature.
Now, getting to this tune, the diminished chord should be a C#dim because it functions as a vii diminished chord going to Dm despite the one flat in the key signature of either Dm or F.
EDIT: since you mentioned that this song is an example, I will add that in general you want to go with the accidental that is best explained by standard harmonic analysis. For example, in F if you have an Eb chord this is typically analyzed as a bVII chord so it would be Eb and not D#. You use the letter sequence that goes with the analysis, (7-1 = E-F)
As for the key, some might hear it in either Dm or F and can state a case for either but I think F makes the most sense. It seems to resolve there both harmonically and melodically. That makes it: vi IV I V, a pretty standard progression. Either way the key would be one flat.
Comment: I'm sure I've heard that sequence - only about a million times so far. To me it'd sound more in Dm with a v or V chord, which is absent. Although I suppose the C could count as a sort of dominant to Dm, but, it's actually the dominant of F, and there's I IV V and vi of that key present.
Comment: @Tim Good points. It CAN be interpreted as Dm but what makes it sound more like F to me is also the fact that the chorus melody is centered around F. It seems like a very large amount of pop tunes nowadays are written with nothing but the 1,4,5,6 chords in varying orders. Those progressions remind me of Neil Young's "Heart of Gold" from back in the day.
Comment: Yeah, 1 6 4 5 was de rigueur back in the day. Still works well as an intro!
Answer: As a general rule, diminished chords are built on the seventh note of the corresponding scale and lead to the main chord of that scale. A typical use of C#dim would be leading to a D chord; a typical use of Dbdim would be leading to a Ebb chord.
Thus, with no other information, C#dim would be the better guess.
With the additional information that the song contains Dm, Bb, F, and C, that would further suggest C#dim -- as a lead-in to Dm. However, there is a complication: C#dim, Edim, Gdim, and A#/Bbdim all contain 3 of the same 4 pitches. So could it really be an Edim chord, which would make sense in the key of F?
Finally, listening to the song, it's confirmed that the diminished chord leads to the Dmin chord.
C#dim is the correct spelling for this chord
The piece as a whole is in Dmin. The end of a piece is the best place to determine the key, and the ending is where one usually puts the most stable chord. This piece ends on the C#dim chord, leaving us hanging, but we can still conclude Dmin, as that is the clearly implied resolution.
Answer: When deciding on enharmonic spellings and accidentals, harmony is usually considered from the common seven-note-scale perspective:

There are seven different scale degrees, using the letter names C D E F G A B (but not necessarily starting from C)
Each of the seven scale degrees can be in either natural, sharp or flat "mode". But only one of those at any given time, not e.g. sharp and natural at the same time.
Chords are constructed as stacks of thirds (even if voiced in different octaves)

If we assume that the song is in F major, the scale degrees are:

1:F
2:G
3:A
4:Bb
5:C
6:D
7:E

Now you have a dim chord between the 5th and 6th degrees, and your question can be transformed to:

is the 5th degree switched to "sharp mode", making C at least temporarily be C#, or
is the 6th degree switched to "flat mode", making D at least temporarily Db?

If the 6th degree is flattened, then you basically wouldn't use a D as a melody note but you would use C, while the dim chord is playing.
If the 5th degree is sharpened, then you basically wouldn't use a C as a melody note but you would use D, while the dim chord is playing.
Out of these two options, if you try them out, it should be very clear that C# is the correct choice. This also means that you can see the dim chord as an A7/C# chord without the A. A7 chord is a stack of thirds with the scale degrees 3, 5, 7 and 2, with 5 being switched to sharp mode.
The 7-note scale system doesn't cover all modern and jazz harmony, where you might have adjacent chromatic notes sounding at the same time or more than 7 notes per octave, but it works for the commonly used chords+melody pop way of thinking.


How can I make URL Alias required when creating new content

Question: When a user creates a new article they often forget to put in the URL path alias for the article. How can I make that field required before they can save the content?
Answer: The easiest solution is to use the pathauto module. If the user does not touch the URL path alias field, pathauto will automatically generate a URL for the node based on the node title.  Other configuration options are available.  The user may still uncheck the pathauto checkbox and type in a specific URL for their new node.
Update:
If the URL format is built from fields or metadata in the node that is created, pathauto can do that for you automatically through its pattern configuration page. For example, I have one content type with a pattern [node:field-gender:name]/[node:field-era:name]/[node:field-genre:name]/[node:field-item-type:name]/[node:title] to create four levels of nesting in the URL based on field values entered. If the user does not have the permission to create and edit url aliases, they will be stuck with the pattern pathauto provides.
If you want to allow users to also edit the URL, you could validate the field from hook_node_validate. I don't know if there is a way to do node validation with rules.
Update 2:
If you have a field called "tag" that is a taxonomy term, then [node:tag] will return all of the terms in this field, concatenated together, and [node:tag:1] will return just the first taxonomy term.  In both cases, spaces are converted to dashes.
Comment: My problem is that the URL format needs to be set in a certain format. The reason for this is because I am using rules to apply that new content to the correct menu according to its URL path.

Would there be a way to do this with rules?
Comment: Do you know if pathauto can create the url from the first tag of the content? This is actually what I need: urlpath = kb/[node:menu-2nd-level-parent's-name]/[node:first-tag]/[node:title]


Not all rows showing in map view for fusion table

Question: I have a Google fusion table that contains about 50k rows with kml data. When I bring up the map view in the fusion tables UI I only see data for about a few thousand rows.
When I do a spatial query to return data that fits within the boundaries, I don't get any results for rows after the first few thousand.
I looked at my kml and it appears to be correct. Is there some limitation that I am running into or should I be looking at something else. If needed I can provide the table id if someone wants to look at it.
Comment: The limit is 100k records, everything below should work. Are all the records already geocoded? Can you provide a link to your table?
Comment: I hadn't done the geocode. I went and selected that option now but it is staying at 0% so I don't know if it is working or not. Here is the link. https://www.google.com/fusiontables/DataSource?docid=16dZnxxkEz4XVrR8O1UcaNXgUYo86sY_mOw1G5BM
Comment: I guess it takes a while for 50k records to geocode. But this is a prerequisite to display the data on the map. If a record is not yet geocoded, the location column for that record has a yellow background. Are you still seeing too few records on the map?
Comment: Does kml need to be geocoded? That is what I have in my geometry column that I am trying to map. The progress bar never goes above 0% so I don't think there is anything for it to do, or it is broken.
Comment: Actually kml does not need to be geocoded. I [checked the docs](https://developers.google.com/maps/documentation/javascript/layers#FusionTables), and there is another limit that you likely hit: if you have more than 500 features per tile, they are thinned.
Answer: KML does not need to be geocoded.
KML can sometimes have very large files, even if only 50K rows. If your original file was very large, (>100 MB), you may be encountering performance issues. I'd recommend making the file smaller (simpler) and start again.
If you are running into an issue with more than 500 items for a given map tile, more items will appear as you zoom in. (Because more map tiles are used to cover the same area.)
-Rebecca
Comment: I think the problem was my kml was very large for every row. I did a reduce on the number of points to 1/20th the number of points. This worked and I still have a polygon that works.


Why does O Little Town of Bethlehem have two melodies?

Question: The version most familiar to us doesn't seem to be the original, and it is not favoured as the original tune. The one we are accustomed to hearing starts with the note on the third degree of the scale, with an accidental note going one half step down, then going back up one half step. Then it goes up one whole tone and one half tone to the fifth degree, then it drops down one hole tone and ends on the sixth degree, a minor sixth below the last note.
The other melody I heard was sung by the Cardiff Festival Choir, under the name O Little Town, O Little Town of Bethlehem. It's melody starts out on the fifth degree of the scale, then goes up a perfect fourth, rises then goes up one whole tone or major second, goes back donw a hole tone, back up a whole tone, and it goes up another whole tone. Then it goes up a half tone, and it goes up one whole tone, basically one octave from the first note of the tune.
Comment: Are you sure you can't link to some sheet music, a YouTube video, or something? Describing a melody (by tone only, no less) is a pretty rough way to go...
Comment: https://en.wikipedia.org/wiki/O_Little_Town_of_Bethlehem#Music Basically one is American the other European. I only know the European one, Forest Green
Comment: I bought a book of Christmas Carols once and when I started to play O Little Town of Bethlehem  I was surprised.  I previously only knew the European version but my book contained the US version.
Comment: @Tetsujin Wow, I didn't know this. Make that an answer!
Answer: Two versions, 'Forest Green' (English) and 'Wengen' both have the same metre - D.C.M. That means the tunes will both fit to the same set of words. Obvious! But what could happen is any other 8 line hymn with the same D.C.M meter would also work, so although these two tunes are the most commonly used, others will fit. D.C.M - double common meter: eight lines perverse, four couplets, eight syllables on first line, six on second.
I did that by accident years ago, whilst playing in school assembly - played a tune familiar with the singers, who sung a set of words which were also familiar, but not usually sung together.
The Forest Green melody is traditional English, the second written by Sir Henry Walford Davies, a Welshman who held many important posts in England and Wales. I guess it was written around 1900. Philip Brookes wrote the words, in 1866, for his Sunday school children in Philadelphia. Lewis Redner wrote the music - St. Louis, in 1869. Ralph Vaughan Williams paired the words with Forest Green in 1906, after the original tune was derided in England, reasons unknown.
Comment: I think you meant "per verse", not "perverse". lol
Comment: @Walt Does that just make it a half-dirty limerick?
Comment: The original tune 'St Louis' is American, as are the words. The EU versions are all later, according to wikipedia.
Comment: What is "D.C.M."?
Comment: @JohnDoe I like his version better though. Maybe make a new form of poetry or something - "Each stanza contains 4 lines common and 2 perverse."
Comment: I've typically seen "common meter double" and CMD, not DCM. Regarding "any other 8 line hymn with the same D.C.M meter would also work": this is not quite true; it has to have the same poetic scansion as well, but syllable counting ignores this. So, for example, *Deck Thyself, My Soul, With Gladness* and *The Spacious Firmament on High* are both long meter double (88. 88. D, or LMD), but the first is trochaic tetrameter while the second is iambic tetrameter, so it's unlikely that any tune would fit both texts.
Comment: @ToddWilcox - haven't found out yet ! Except it's a sort of meter, similar to 'While Shepherds Watched (C.M.), or 'Hark the Herald' (7777.7777.77).  Denotes syllables in lines. See edited answer.
Comment: This reminds me of [Axis of Awesome's Four Chord Song](https://www.youtube.com/watch?v=5pidokakU4I).
Comment: @Tim C. M. stands for "common meter" (8 6 8 6); D. C. M. stands for "double common meter" (8 6 8 6 8 6 8 6).
Answer: More broadly speaking, lots of songs (especially hymns) have different tunes that work. For example, I can think of three different melodies for "Away in a Manger".
I don't know about other denominations, but I know that the LDS hymnbook has a section in the back where they've taken all of the hymns in the book and separated them into groups whose tunes can be used interchangeably for each hymn in the group.
Comment: @BrianTHOMAS You can indeed sing "While shepherds watched" to the tune of "On Ilkley Moor baht 'at". Indeed that tune was used for "While shepherds watched" before the lyrics of "On Ilkley Moor baht 'at" were written. https://en.wikipedia.org/wiki/On_Ilkla_Moor_Baht_%27at#Tune https://en.wikipedia.org/wiki/Cranbrook_(hymn_tune)
Comment: In contrast, I can only think of one melody for "Away in a Manger"!
Comment: Additionally, while all three versions are in 3, two of them sound fairly similar and have a similar tempo, while the third is slower and "radically" (as radical as hymns get) different. Incidentally, the LDS children's songbook has a different version, with an added chorus that I've never heard anywhere else, than the LDS "adult" hymnbook.
Comment: I was at a Jewish song session were we decided to see how many versions of "L'cha Dodi" we knew.  I think we hit 7 or 8 and I'm sure there are more.  And there's a running joke that "Adon Olam" can be set to pretty much any 4/4 melody - ["I want it that way" by the Backstreet Boys](https://youtu.be/ZYMY7aHzbyE?t=50s) is moderately popular.
Comment: And you can sing 'While shepherds watched their flocks by night' to the tune of 'On Ilkely Moor Baht 'at'
Comment: @ArcanistLupus when you get into liturgical music there will be examples of people composing new music for ancient texts, so the existence of dozens of tunes is not surprising.  There are probably thousands of settings of *kyrie eleison,* for example.  The weird thing about Christian hymnody (perhaps not uniquely; I do not know) is this idea of fitting existing poems to existing music because the meter happens to fit.
Comment: Then there's Amazing Grace which can be squeezed into almost any melody. It actually can be quite funny to imagine the strange possibilities!
Comment: @HeatherS. any text can be squeezed into any melody if you're willing to tolerate (or are perhaps even seeking) absurd text underlay and mismatched lines.  For example, if you set Amazing Grace to Twinkle Twinkle Little Star, you get *A-maz-ING grace, HOW sweet THE/SOUND that SAVED a WRETCH like ME.*  The second line kind of works, but only because you've started it using the last word of the first line.  The first line is basically backwards, with all the stressed syllables unstressed, and vice versa.
Comment: @phoog, agreed, though Amazing Grace seems more flexible than many texts.


Filtro com 2 condições variáveis

Question: Tenho dois banco de dados, o primeiro tem umas 30 mil linhas o segundo 571.
Preciso filtrar o primeiro com duas condições do segundo banco.
Condição A: fctr seja ==
Condição B: data <=
Tentei fazer um for duplo mas não deu certo.
Exemplo:
df1 = c(col1(a,a,a,b,b,b,b,c,c),col2("10/02", "15/02", "14/03", "05/03", "07/03", "15/03", "20/03", "12/03", "15/03"))

df2 = c(col1(a,b,c), col2("15/02", "15/03", "15/03"))

Preciso de algo do tipo:
filter(df1, col1 == [i]df2.col1 & col2 <= [i]df2.col2)

Alguém tem ideia de como posso fazer isso?
Comment: Você poderia fornecer um exemplo reproduzível? [LINK](https://pt.stackoverflow.com/questions/264168/quais-as-principais-fun%c3%a7%c3%b5es-para-se-criar-um-exemplo-m%c3%adnimo-reproduz%c3%advel-em-r?noredirect=1&lq=1)
Mas, a priori, acho que seus df devem ter a mesma quantidade de linhas para realizar a ação da maneira que você idealizou.
Comment: Você tá tentando criar várias tabelas ou uma só? Tente deixar mais claro o objetivo, por favor. E dê uma olhada nos  que terminam com _join do dlpyr que talvez ajudem na comparação das duas tabelas.
Comment: Rafael, o código que você postou não é reproduzível. Verifique.
Answer: Os dados da pergunta estão numa linguagem (?) que não é o R nem outra que eu conheça, mas creio que com algum esforço se percebe o que é pretendido.

Os valores de col1 devem ser iguais nas duas tabelas.
Os valores de col2 da primeira não podem ser maiores que os da segunda.

Para obter valores iguais de col1 vou fazer um merge por essa coluna e depois obter um índice lógico a partir da comparação de col2. Mas estas colunas parecem ser datas, portanto um passo preliminar será transformá-las em datas com as.Date.
tmp <- merge(df1, df2, by = "col1")
i <- apply(tmp[-1], 1, function(x){
  x <- as.Date(paste(x, "2000", sep = "/"), "%d/%m/%Y")
  x[1] <= x[2]
})
rm(tmp)

df1[i, ]
#  col1  col2
#1    a 10/02
#2    a 15/02
#4    b 05/03
#5    b 07/03
#6    b 15/03
#8    c 12/03
#9    c 15/03

Dados.
df1 = data.frame(col1 = c("a","a","a","b","b","b","b","c","c"),
                 col2 = c("10/02", "15/02", "14/03", "05/03", "07/03", "15/03", "20/03", "12/03", "15/03"))

df2 = data.frame(col1 = c("a","b","c"),
                 col2 = c("15/02", "15/03", "15/03"))

Comment: Muito obrigado! Já tinha pegado a solução no stack em inglês. Sua solução funciona também, é até mais elegante. Grande Abç!

Filtro com 2 condições variáveis


Have a lot of optional data that user can download. where to start from?

Question: In my android app I have a lot of files that users can optionally download. The files are between 5 to 500 mb of data (mp3, txt files,...).
I thought I should zip each section so the app downloads 1 file and then extracts it, even if this mean I have to work hard before the release to zip everything and have all options covered. Is there a better way?
The app on the first run download 15 mb that are essential for the app to work, and then the user can download additional data.
Where should I start from? I thought I should make downloading in the background and notify the user of the progress in the drop-down menu.. Is this the best way to do this? How can I do this?
My apps target is 1.5
Answer: I would recommend creating a download Service for your application that can handle downloading these files in the background.  You should include current progress in the notification bar, as you have suggested, and you should give the user the ability to pause/resume downloads.  When your app first starts up, it should check to see if the necessary files have been downloaded; if not, it should begin downloading them with your Service and explain to the user that the files are being downloaded.


python regex not behaving as i think it should

Question: I am trying to sort through a some files using regex expression.
I have a file which contains the two following lines
NET "MBC_ADR_I1<1>" LOC = "R2";
NET "GP_O<7>" LOC = "R20";

I am using the following expression to get one of the lines only
f2MatchLoc = re.search('(LOC)[ ]+=[ ]+["]?({})'.format(f1LocValue), f2Line, re.IGNORECASE)

where f1LocValue = R2. However I'm getting a match on both lines.
I've tried to enter the same expression here
regex101.com
which shows that my argument should be correctly formatted
Answer: f2MatchLoc = re.search(r'(LOC)[ ]+=[ ]+["]?({}\b)'.format(f1LocValue), f2Line, re.IGNORECASE)
                                              ^^

You need to use \b after R2 so that there are no partial matches. See demo. Also use r or raw mode.
Comment: This r'(LOC)\s+=\s+"?({}\b)' works. thank you. however why does '(LOC)\s+=\s+"?({}\b)' not work (i removed the 'r' at the beginning)
Comment: @Ephreal python considers `\b` as an escape sequence and it will have a meaning of it as own.So `\b` will not be left for regex engine.So you use `r` or `raw` mode telling python to not apply its own escape sequqnces
Answer: Because you have no conditions how the string should end.
'(LOC)[ ]+=[ ]+["]?({})'
                       ^??

So it matches anything that starts with LOC = "R2. Following are all valid search results
LOC = "R2
LOC = "R2asd
LOC = "R2121
LOC = "R2   "

Simply, you can use double quotes or semicolon to identify end of search string. Also you can replace \s for white-space capturing and you can remove [] around single element lists
r'(LOC)\s+=\s+"?({})"?;'

Comment: using r'(LOC)\s+=\s+"?({})"?' still gives me both hits.
Comment: @Ephreal Did you check the value of the `f1LocValue` that you use in regexc string formatting. And did you run this in a loop or something?
Comment: `?` means 0 or 1, so R20 still matches, as it's R2 followed by no `"`. If you left on the `;` it would likely work
Comment: @GP89 it should evaluate as `r'(LOC)\s+=\s+"?(R2)"?;'` so `R2;"` or `R2;` should be matched but `R20` should not since after R2, it will wait for either `";` or `;`, not anything else...
Comment: I would beleve your suggestion should work. It was also what I did to begin with and is working on the regex101 site. However I only got it to work with the suggestion from vks.
Comment: @FallenAngel I know you're right. I was pointing out @Ephreal's first comment where the `;` was left off
Comment: @GP89 ahh ok a misunderstanding (:


Alphabetical view sorting in multilingual site not working for translated content

Question: I have created a view that alphabetically lists all nodes of type "glossary entry". A glossary with many terms. Besides German I need the glossary in English, too. The translation has worked great using Entity Translation module. I only have the problem that the alphabetical order of the English version is not correct. The English glossary has the same sort order than the German (original) version:

German version:

Adler (German word for eagle)
Hund (German word for dog)
Kuh (German word for cow)

English version:

Eagle
Dog
Cow

I crawled many forums but couldn't find a solution for my problem. I already added the relationship "Entity Translation" in my view but the additional filter and sorts don't help me here.
What I need is a sort "title (English Translation)". Does somebody has a clue how to get this work?!!
Please find here the view's query
Comment: Did you install the title module?
Comment: Yes, I have installed that.
Comment: You have to make sure you don't add the field "Content: Title
The content title" in your view. This i the core drupal title. You have to add the title field title. Can you report back if this fixes your problem?
Comment: Thanks Robin, but I am aware of this. My content type contains the title of the Title Module and so does the sort criteria that I added in my views.
Comment: Yes the sort criteria, but is your field you are displaying also the correct title field?
Comment: Yes, definitively it is.
Comment: Can you post a screenshot of your query (that is executed by views)?
Comment: I posted the screenshot in my question.
Answer: I solved that by adding this field as a relationship to the view and so name:field became accessible as sort criteria, which I then chose instead of content:field.


Condition on a matrix sum with equal determinant and trace

Question: Let $n$ be a positive integer, $J$ the matrix of all ones and $Q$ a symmetric  positive semidefinite matrix such that

$\det(nI-Q) = \det(Q+J)$
$\rm{tr}(nI-Q) = \rm{tr}(Q+J)$

and also

$nI-Q \ne Q+J.$

Are there any other properties of $Q$ that can be deduced from the above constraints?
I hope the question is not too shallow. I stumbled upon this while studying a unrelated problem and I am curious to see if there if there is anything more that can be said about $Q$ from these facts alone.
Comment: Isn't the second $\bullet$ mistyped? Isn't it ${\rm tr}(nI-Q)={\rm tr}(Q+J)$?
Comment: @berci Indeed. I have now corrected the question
Comment: Well $n^2 - tr(Q)=ntr(I)-tr(Q)=tr(nI-Q)=tr(Q+J)=tr(Q)+tr(J) = tr(Q)+n$ so $tr(Q)=\cfrac{n(n-1)}{2}$
Answer: Let $Q$ be $m\times m$. Two obvious properties are $\mathrm{tr}(Q)=\frac{m(n-1)}2$ and $0\le\lambda_\min\le\frac{\mathrm{tr}(Q)}{m}=\frac{(n-1)}2\le\lambda_\max\le n$.


Verificar carregamento de arquivo externo com JS

Question: Minha home page possui um vídeo como background porém em alguns momentos o vídeo demora para ser carregado. Nesta situação pensei em criar um loading antes da pagina ser exibida, minha duvida é de como posso verificar com o jquery/javascript se um arquivo (vídeo) já foi carregado completamente para então exibir a pagina por inteira.
O video é um arquivo local
<video id="video" autoplay loop muted>
    <source src="/public/video/capa_video.mp4" type="video/mp4">
</video>

Em minha pagina estou usando o plugin fullpage js, então em meu arquivo .js já possuo a função readydo jquery.
$(document).ready(function() { ... });

Como posso fazer para exibir um efeito de load antes do documento ser todo carregado (imagens, videos, fonts e etc) ?
Comment: Talvez possa te [ajudar](http://pt.stackoverflow.com/questions/182797/qual-a-diferen%C3%A7a-entre-document-ready-e-window-onload/182803#182803)!
Comment: Não consegue com o evento `window.onload`?
Comment: @AndersonCarlosWoss algumas vezes a pagina é carregada porém o video ainda não foi carregado completamente, logo, ele trava em algum ponto.
Comment: Pelo o que ele disse, o evento `onload` pode ser disparado antes do vídeo ser carregado por completo (talvez seria por quê o vídeo não é transferido de uma vez e sim *streamado*?)
Comment: Põe uma div cobrindo o conteúdo e um gif animado de loading e usa o window.onload pra esconder essa div quando a página for carregada por completo. (Veja link do Marconi no comentário acima que leva até a resposta do Jbueno em outra pergunta).
Comment: Poẽm o código junto a pergunta e especifique melhor o ambiente. O vídeo exibido é local ou do YouTube/etc?
Comment: @AndersonCarlosWoss melhorei a pergunta
Answer: Conforme alguns exemplos que encontrei na web, apenas utilizar o evento window.onload para ocultar a div de carregamento nem sempre é suficiente, pois em conexões mais lentas, o vídeo pode não estar pronto para a execução quando tal evento é disparado.
A forma mais prática que encontrei foi a deste site:
window.addEventListener('load', function() {
    var video = document.querySelector('#video');
    var preloader = document.querySelector('.preloader');

    function checkLoad() {
        if (video.readyState === 4) {
            preloader.parentNode.removeChild(preloader);
        } else {
            setTimeout(checkLoad, 100);
        }
    }

    checkLoad();
}, false);

Em que é executada a função checkLoad no evento window.load, porém, caso o vídeo ainda não esteja suficientemente pronto, ele volta a fazer a verificação 100 ms mais tarde, com a função setTimeout.
A verificação do estado do vídeo, no caso video.readyState === 4, é baseada na tabela abaixo, tirada deste site. Tradução livre: se retornado 4, já há dados disponíveis suficientes - e a velocidade da conexão é alta o bastante - então o vídeo poderá ser executado até o final sem interrupções.
Answer: O onload só é executado após todo conteúdo da página ser carregado.
Testei com um vídeo seguindo o link do Marconi para a resposta do Jbueno.
Segue o exemplo:

window.onload=function()
{  document.getElementById("loading").style.display='none';
}
    #loading{
 color:#fff;
 background-color:#000;
 width:100%;
 height:100%;
 position:absolute;
 top:0;
 left:0;
 z-index:9999;
 }

Carregando...

Página carregada.
<video width="400" controls>
  <source src="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>
Comment: A dúvida que fiquei é: o HTML5 transfere de uma só vez o vídeo assim como faz com a imagem ou vai transferindo os frames conforme o vídeo é executado, tal como o YouTube faz? Neste segundo caso, acredito que o evento é disparado antes do vídeo ser carregado por completo.
Comment: Mudei o código para um vídeo exibido com html5. Só esconde a div depois que o vídeo foi carregado.
Comment: Testei com uma velocidade menor de internet e o "loading" não aparece, a tela fica branca, e só quando o site carrega o loading aparece rapidamente e depois já troca para o video.
Como posso fazer para exibir o loading antes de tudo?
Comment: @RafaelAcioly tente colocando a _tag_ do _loading_ logo após a abertura da _tag_ `` e com o CSS embutido na _tag_ pelo atributo `style`;
Answer: Uma forma de fazer isso com vídeo, de forma mais rustica, é ficar verificando o status dele, e quando o status for 4, significa que ele foi carregado por completo:

var video = document.getElementById('video');

var interval = setInterval(function(){
   if (video.readyState === 4) {
      clearInterval(interval);
      document.getElementById('status').innerHTML = 'Carregado!';
   }
}, 500);
<video width="320" height="240" controls id="video">
  <source src="http://www.w3schools.com/tags/movie.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>


How to prove that the first quadrant of the plane is closed.

Question: How can I prove, in topology, that:
$$X = \{(x,y)\in\mathbb{R}^2;y<0;x\in\mathbb{R}\}\cup\{(x,y)\in\mathbb{R}^2;x<0,y\geq0\}$$
is open in $\mathbb{R}^2$?
I tried doing by its complement, but how can I prove that
$$Y= \mathbb{R}^2\setminus X=\{(x,y)\in\mathbb{R}^2;x,y\geq0\}$$
is closed in $\mathbb{R}^2$?
I tried to use, as well, this statement:
$Y$ is closed if and only if for each $y\in \mathbb{R}^2\setminus Y$ there is a neighbourhood $N$ of $y$ such that $N\subseteq \mathbb{R}^2\setminus Y$.
Comment: If you want to use the statement, then you intend to prove that $X$  is open. If $(x, y)$ is in the first term $\{(x,y)\in\mathbb{R}^2;y<0;x\in\mathbb{R}\}$, just take a disc of radius $-y/2$ around it. For the other term you will need to consider the value of $x$..
Comment: Just draw a picture, and you will see what I mean. I do not mean to be secretive, it is just that, as a teacher, I know how important it is for one to find a solution oneself, as opposed to just being told what the solution is.
Comment: @AndreasCaranti I got it. My doubt was about taking the disc as being open, because in my definition, the basics are rectangles. But the idea is similar, I just need to take the coordinates of my open strategically to be a neighborhood of (x, y). Thanks! Not really giving me any more tips was essential! You are a good teacher. I appreciate it!
Comment: Thanks a lot!
Comment: I still haven't been able to visualize your point. Can you explain it in another way? Sorry, I really didn't understand, @AndreasCaranti.
Comment: Okay. No problem, I respect your position and thank you for your help and patience, @AndreasCaranti.
Answer: Since $X=(\mathbb R\times\mathbb R^-)\cup(\mathbb R^-\times\mathbb R)$, you have that $X$ is the union of two obviously open sets.


How does GDB know where an executable has been relocated?

Question: I know modern OSs such as Linux don't always execute an application at the same address it was originally linked. When a debugger starts looking around though, it needs to know the relationship between the original link address and the final executing address. How does GDB calculate the offset?
Clarifications: I'm not talking about virtual memory. That is, I have (what I believe to be) a reasonable understanding of how Virtual memory works and am operating entirely with in that address space. I have symbols that are at one location when I dump the symbol table from the ELF, but at another location when I get their address out of memory.
In this particular case, I have a string which in the linked executable is at address 0x0E984141. In a dump of memory from that process, it is at address 0x0E3F2781. Everything in the .rodata section at least has been shifted by 0x5919C0. It appears to be something like Address Space Layout Randomization.
Answer:
I know modern OSs such as Linux don't always execute an application at the same address it was originally linked.

This is only possible for position-independent executables (linked with -pie flag).

When a debugger starts looking around though, it needs to know the relationship between the original link address and the final executing address.

Correct.

How does GDB calculate the offset?

The same way GDB calculates the offset for shared libraries (a PIE executable is really a special case of a shared library). There is a defined interface between ld.so and GDB, consisting of _dl_debug_state() function (on which GDB sets an internal breakpoint, and which ld.so calls whenever it maps a new ELF image into the process), and struct r_debug. The latter points to a linked list of struct link_maps, and l_addr member of that struct is the offset between linked-at and loaded-at address.
Answer: If i understand what you are getting at, I think what you are actually referring to is Virtual Memory addressing This is not handled by GDB, it is handled by the operating system.
http://www.cs.utexas.edu/users/witchel/372/lectures/15.VirtualMemory.pdf
Comment: I don't think this question is about virtual memory, but the fact that ELF segments can get loaded at different locations (in virtual memory) than the addresses (in virtual memory) the ELF file specifies for those segments. For an executable, this happens for instance when you have ASLR.
Answer: On Linux,  every process has its own address space in virtual memory.
The ELF executable contains a header describing the segments in memory (and their corresponding sections in the executable).
Comment: With ASLR, the segments can be loaded at different addresses than what the ELF file specifies.


Divergence theorem of region cut between cylinder and plane

Question: Use the Divergence Theorem to find the outward flux of $F = (6x^2 + 2xy)\vec{i} + (2y + x^{2}z)\vec{j} + (4x^{2}y^{3})\vec{k}$
across the boundary of the region cut from the first octant by cylinder $x^{2} + y^{2} = 4$ and the plane $z = 3$.
I have found $div F = 2(6x + y + 1)$ but I do not know how to set up the integral that can be evaluate after this step.
Answer: The divergence theorem states
$$ \iint_S \textbf{F}\cdot d\textbf{A} = \iiint_D (\nabla \cdot \textbf{F}) \,dV $$
where $D$ is the volume inside the cylinder $x^2 + y^2 = 4, x \ge 0, y \ge 0, 0 \le z \le 3$
All you have to do is integrate the divergence $\nabla \cdot \textbf{F}$ over this volume. Hope you know how to set up the bounds. The integral is:
$$ \int_0^3 \int_0^2 \int_0^\sqrt{4 - x^2} (12x + 2y + 2) \,dy \,dx \,dz$$
It might be easier to switch to cylindrical coordinates $(r, \theta, z)$
$$ \int_0^3 \int_0^{\pi/2} \int_0^2 (12r\cos\theta + 2r\sin\theta + 2) \,r \,dr \,d\theta \,dz$$


How to find a basis for subspace of functions

Question: I am doing this exercise:

The cosine space $F_3$ contains all combinations $y(x) = A \cos x + B \cos 2x + C \cos 3x$. Find a basis for the subspace that has $y(0) = 0$.

I am unsure on how to proceed and how to understand functions as "vectors" of subspaces.
Comment: "vectors" are just things you can add to each other and multiply by numbers. You can do that with functions, so you can say that functions are vectors.
Answer: Many people have problems understanding functions (among other things) as vectors. I believe this is caused by the fact that when introducing vectors one most frequently uses elements of $K^n$ where $K$ is a field such as $\mathbb{R}$, which easily leads to the wrong intuition that a vector must look like something such as $(x_1,\dots,x_n)$. But do not forget that a vector is simply an element of a vector space, and there are many examples besides $K^n$ for such spaces, you only need a field $K$, a set $V$ and two certain operations satisfying some basic properties.
For your case, I assume that the underlying field is $\mathbb{R}$. $F_3$ is $3$-dimensional, with $\{\cos x,\cos 2x,\cos 3x\}$ being a basis: These functions span $F_3$ by definition, and they are linearly independent because if $A\cos x + B\cos 2x + C\cos 3x = 0$ holds for all $x\in\mathbb{R}$, then it must be $A=B=C=0$ (check!). By this you know that any subspace of $F_3$ is at most 3-dimensional.
Now we should show that the functions that satisfy $y(0)=0$ actually form a subspace $W$, but this is clear since such functions are obviously closed under addition and scalar multiplication, and the zero function is contained in this subspace.
The functions $\cos x - \cos 2x$ and $cos x - \cos 3x$ (which are elements of $F_3$) clearly satisfy $y(0)=0$ and they are linearly independent, since $$A(\cos x - \cos 2x) + B(cos x - \cos 3x) = (A+B)\cos x - A\cos 2x - B\cos 3x = 0$$
implies $A+B=-A=-B=0$ and hence $A=B=0$. Thus, these two functions lie in (i.e. are vectors of) $W$, so $W$ must be at least 2-dimensional.
Now if $W$ was 3-dimensional, it would be $W=F_3$, but note that the function $\cos x$ does not satisfy $y(0)=0$ and hence is no element of $W$.
Hence $\{\cos x - \cos 2x,  \cos x - \cos 3x\}$ is a basis of $W$.
Comment: If $A\cos x + B\cos 2x + C\cos 3x = 0$ holds for all $x\in\mathbb{R}$, then it holds in particular for $x=\frac{\pi}{2}$ and $x=\frac{\pi}{6}$. For these values the resulting equations are $-B=0$ and $-A\cos(\frac{\pi}{6})+B\cos(\frac{\pi}{3})=0$. The first equation shows that $B=0$, and since $\cos(\frac{\pi}{6}) \neq 0$ the second equation shows that $A=0$. Hence it also must be $C=0$. So the idea is to take some specific $x\in\mathbb{R}$ so that the equation gets simplified.
Comment: Selecting these two functions was just my choice. I saw that the whole space is $3$-dimensional, and then I tried to find some linearly independent elements of the subspace given by $y(0)=0$. If you know how the cosine function (and its stretched versions) look like, then these two elements are not very hard to find. I would suggest you to review the topic "linear independence" somewhere. Since $\cos x$, $\cos 2x$ and $\cos 3x$ are linearly independent, they can only trivially be linearly combined to zero, this is why $A+B=0$, $-A=0$ and $-B=0$.
Comment: Sorry for the dumb question: how can I rigorously check that $A = B = C = 0$?
Comment: Why do you select $cos x - cos 2x$ and $cos x - cos 3x$ as elements? Moreover, I don't get the passage where there is the implication $A+B = -A = -B = 0$


Show that no integer of the form $a^3 +1$ is a prime for $a>1$

Question: Can someone please solve this and explain the steps taken to reach this solution ?
Comment: $x^3+1=(x+1)(x^2-x+1)$
Comment: In general, you have the following factorization for all odd $n$: $x^n+y^n=(x+y)(x^{n-1}-x^{n-2}y + x^{n-3}y^2-\ldots - xy^{n-2} + y^{n-1})$. It's a nifty thing to remember.
Comment: Dudes, this was handled 5 years ago and multiple times in between. In fact back in the day it was deemed only worth a link. Downvotes to all but the honest commenters.
Answer: Hint: $a^3+1=(a+1)(a^2-a+1)$, so...
Answer: Factorise $$a^3 +1 \equiv (a+1)(a^2 -a +1)$$
This is made up of the product of two integers if $a > 1$, namely $a+1$ and $a^2 -a + 1$. i.e: it is the very definition of a composite number. (that is, unless $a+1$ or $a^2 - a  + 1$ is equal to $1$, but the hypothesis $a>1$ immediately gives you that.
In fact, it's normally a good idea to factorise $$a^n + b^n = (a+b)(a^{n-1} - a^{n-2}b - \cdots - ab^{n-2} + b^{n-1})$$
in these sort of situations.
Comment: how do you know it is not prime ?
Comment: Added a bit to my answer to help explain.


Diagonalizable and Invertible matrix

Question: There is a problem that says for a matrix P such that $P^2 = P$, then P is diagonalizable.
However, I am kind of lost at how can we know that this matrix is diagonalizable, when we can't even show that it is invertible?
A related problem is "for a matrix A, if $(I - A)^k = 0$ for a positive integer k, then A is invertible". I have problems with this statement either. From the condition $(I - A)^k = 0$ I agree that we can conclude that one of the eigenvalues of A is 1, but we cannot rule out the possibility that A has 0 as eigenvalue. Why is this statement true? (By the way, A is a 3 by 3 matrix, though I don't think it matters here).
Thanks
Comment: If $P^2-P=0$, then the matrix satisfies the polynomial $t^2-t$; so the minimal polynomial divides this polynomials. If $(I-A)^k = 0$, then $0$ cannot be an eigenvalue: if $v$ were an eigenvector of $0$, then $(I-A)(v) = v$, and then what is $(I-A)^k(v)$?
Comment: You don't need a matrix to be invertible for it to be diagonalizable! And a matrix that satisfies $P^2=P$ may indeed not be invertible, but that is irrelevant. The zero matrix is not invertible, but is certainly diagonalizable.
Answer: Notice that $P(P-I)=0$, so that the minimal polynomial of $P$ divides the polynomial $t(t-1)$. A matrix $A$ is diagonalisable exactly when its minimal polynomial splits into linear factors (see this question for a proof), which is certainly true for factors of $t(t-1)$. Thus $P$ must be diagonalisable.

Diagonalizable and Invertible matrix


Ajuda Update Laravel

Question: Boa noite, estou começando a estudar Laravel e me deparei com um problema que já me tomou algumas horas em busca de uma solução. Preciso fazer um update em um formulário, e quando dou o submit recebo o erro:

Segue os meus códigos:
Rota:
Route::get('/produtos/edita/{id}', 'ProdutoController@edita')->where('id', '[0-9]+');
Route::post('/produtos/atualiza', 'ProdutoController@atualiza');

Blade:
@extends('layout.principal')
@section('conteudo')

Editar Produto: {{$p->nome}}

<form action="/produtos/atualiza" method="post">
<input type="hidden" name="id" value="{{$p->id}}">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />

    Nome
    <input name="nome" class="form-control" value="{{$p->nome}}">

    Descrição
    <input name="descricao" class="form-control" value="{{$p->descricao}}">

    Valor
    <input name="valor" class="form-control" value="{{$p->valor}}">

    Quantidade
    <input type="number" name="quantidade" class="form-control" value="{{$p->quantidade}}">

<button type="submit" class="btn btn-primary btn-block">Adicionar</button>
</form>
@stop

Controller:
 public function edita($id)
{
$produto = Produto::find($id);
return view('produto.editar')->with('p', $produto);
}

public function atualiza()
{
$params = Request::all();
$produto = Produto::find($params->id);
$produto->fill($params->except('id'));
$produto->save();
return redirect()->action('ProdutoController@lista');
}

Answer: Não precisa passar o id no verb post, você só precisa criar um input hidden e guardar o valor id nesse campo, mas, se ainda quiser do jeito que fez precisa passar na tag form o id porque o endereço realmente vai dar 404 (porque o endereço colocado não existe, ele precisa do código no final, igual está estipulado em sua rota), mude
<form action="/produtos/atualiza" method="post">

para
<form action="/produtos/atualiza/{$p->id}" method="post">

esse mudança é mediante a sua rota, mas, se eu fosse você faria corretamente assim:
Route:
Route::get('/produtos/edita/{id}', 'ProdutoController@edita')->where('id', '[0-9]+');
Route::post('/produtos/atualiza', 'ProdutoController@atualiza');

Html:
@extends('layout.principal')
@section('conteudo')

Editar Produto: {{$p->nome}}

    <form action="/produtos/atualiza" method="post">
    <input type="hidden" name="id" value="{{$p->id}}" />
    <input type="hidden" name="_token" value="{{{ csrf_token() }}}" />

        Nome
        <input name="nome" class="form-control" value="{{$p->nome}}">

        Descrição
        <input name="descricao" class="form-control" value="{{$p->descricao}}">

        Valor
        <input name="valor" class="form-control" value="{{$p->valor}}">

        Quantidade
        <input type="number" name="quantidade"
               class="form-control" value="{{$p->quantidade}}">

    <button type="submit" class="btn btn-primary btn-block">Adicionar</button>
    </form>
@stop

Controller:
public function edita($id)
{
    $produto = Produto::find($id);
    return view('produto.editar')->with('p', $produto);
}

public function atualiza()
{
    $params = Request::all();
    $produto = Produto::find($params['id']);
    $produto->fill($params);
    $produto->save();
    return redirect()->action('ProdutoController@lista');
}

Referencias:

HTTP Requests
Eloquent: Getting Started
Controllers
Comment: @João peço desculpas, faltou remover o `$id` do parâmetro agora deve funcionar
Comment: @João você mudou o form para está enviando o valor corretamente, em qual método é o erro agora? explica bem o problema!
Comment: Fazendo da segunda maneira que apresentou, recebo o erro "Too few arguments to function estoque\Http\Controllers\ProdutoController::atualiza(). 0 passed and exactly 1 expected". Pelo que entendi ele não esta conseguindo receber o id do form
Comment: eu ja havia testado retirando ele, ai recebo o erro na linha Produto::find, onde o erro é : "Trying to get property 'id' of non-object". Já estou a alguns dias tentando solucionar isso, ate consegui fazendo umas gambiarras ou de maneiras que acredito não serem as ideias, mais gostaria de deixar de uma maneira o mais próximo da ideal possível.
Comment: atualizei a postagem com uma foto do erro, e atualizei meus codigos para a maneira atual seguindo suas recomendações. Veja se consegue entender, qualquer coisa so avisar
Comment: Preste atenção no meu atualiza e no seu atualiza tem diferença ! @João
Comment: Tinha me esquecido de atualizar a parte de controller aqui no post, agora esta idêntico, na verdade cheguei a dar crt + c e crt + v no seu código no meu. Se não for lhe tomar muito mais tempo, posso subir meu projeto inteiro para você olhar.

Ajuda Update Laravel


Como invocar a própria função

Question: def R(n):

    if n == 1:
        return  1
    else:

        return  1/1/x-1/R(1/x+2/x)*n/1*n
x=int(input("entre com x:"))

print(R(2))

ela faz o seguinte pega 1 divide 1/x -1  a cada
iteração ela  divide 1/ 1/x -1/3/x
ela soma 2/x acada iteração minha duvida e como chamar função
o erro dela
RecursionError: maximum recursion depth exceeded in comparison
Comment: tinha que montar recursivo e transformar iterativo porem fiz code mas não sei  aonde posso chamar função? ai bug tudo
Comment: O que a função `R` deveria  fazer ?
Comment: 1/1/x-1/3/x-1 se reparar cresce 2/x cada iteração ai deveria calcular isso
Comment: Sua dúvida é como definir a condição de parada da chamada recursiva ?
Comment: Ou como invocar a função durante a execução  da mesma?
Comment: exatamente isso invocar funçao
Comment: Poderia detalhar melhor na pergunta, usando o botão [edit], o que exatamente a sua função deveria fazer e o que está acontecendo atualmente?
Comment: Tem uma variável x não declarada dentro da sua função. Não entendi que você está calculando. A variável x lida fora da função não é passada para a função.
Answer: É so usar o próprio nome da função - no caso, R - e chama-la da mesma forma como chama a mesma de fora.
para outros algoritmos que podem ser calculados com recursão, como fatorial, é mais fácil entender:
def factorial(n):
   if n == 1:
       return 1
   return n * factorial(n - 1)

Com a notação usada, e como eu não conheço a função, eu não consigo entender o que você quer calcular com a sua função para conseguir reescreve-la de forma recursiva.
Do jeito que está escrita ali, vocẽ chama R recursivamente com o valor (1/x+2/x) mas x e uam variável global definida fora da função - portanto, exceto em um único caso  especial, xnunca vai ser igual a 1,  e sua função nunca vai atingir o valor de parada - a função só vai encerrar a recursividade, e começar a retornar os valores, quando for chamada com o valor "1".
E mesmo que você troque "x" por "n" na chamada a R na linha  return  1/1/x-1/R(1/x+2/x)*n/1*n, eu não acho que a expressão "1/x + 2 / x" vai convergir pra "1" - isso só acontece com o valor "3" em x - portanto acho que você precisa explica rmelhor a fórmula que deseja calcular recursivamente se quer mais ajuda que isso.
Comment: escrevi recursiva mas não roda
Comment: aumentei a resposta com amis algumas considerações.

Como invocar a própria função


Equation of a rectangle

Question: I need to graph a rectangle on the Cartesian coordinate system. Is there an equation for a rectangle? I can't find it anywhere.
Comment: Do you mean the like of $0 \le x \le 1 \land 0 \le y \le 1$ ? Or do you need to parametrize the boundary of the rectangle ?
Comment: I'm looking for a cartesian equation of a rectangle. For example the equation of a circle is $x^2 + y^2=a^2$
Comment: An *implicit* Cartesian equation would be the one Peter gave. Methinks that ain't much. Maybe you want a parametric equation?
Answer: Based on Raskolnikov's answer here, one can build an implicit Cartesian equation for a $2p \times 2q$ rectangle:
$$\left(\frac{x}{p}\right)^2+\left(\frac{y}{q}\right)^2=\sec\left(\arctan\left(\frac{x}{p},\frac{y}{q}\right)-\frac{\pi}{2}\left\lfloor\frac2{\pi}\arctan\left(\frac{x}{p},\frac{y}{q}\right)+\frac12\right\rfloor\right)^2$$
Another one is based on modifying the implicit equation of a Lamé curve:
$$\left|\frac{x}{p}+\frac{y}{q}\right|+\left|\frac{x}{p}-\frac{y}{q}\right|=2$$

For purposes of plotting with a computer, the implicit equation isn't terribly convenient to handle, so I'll throw in a set of parametric Cartesian equations for free, based on the parametric equations of the Lamé curve:
$$\begin{align*}x&=p\left(|\cos\,t|\cos\,t+|\sin\,t|\sin\,t\right)\\y&=q\left(|\cos\,t|\cos\,t-|\sin\,t|\sin\,t\right)\end{align*}$$
Here's another one, based on a special case of the parametric equations given in this answer:
$$\begin{align*}x&=p\left(\cos\left(\frac{\pi}{2}\lfloor u\rfloor\right)-(2u-2\lfloor u\rfloor-1)\sin\left(\frac{\pi}{2}\lfloor u\rfloor\right)\right)\\y&=q\left(\sin\left(\frac{\pi}{2}\lfloor u\rfloor\right)+(2u-2\lfloor u\rfloor-1)\cos \left(\frac{\pi}{2}\lfloor u\rfloor\right)\right)\end{align*}$$
...and another one:
$$\begin{align*}x&=p\max\left(-1,\min\left(\frac4{\pi}\arcsin\left(\sin\left(\frac{\pi u}{2}+\frac{\pi}{4}\right)\right),1\right)\right)\\y&=q\max\left(-1,\min\left(-\frac4{\pi}\arcsin\left(\cos\left(\frac{\pi  u}{2}+\frac{\pi}{4}\right)\right),1\right)\right)\end{align*}$$
...and I suppose I should stop here. ;)
Comment: I did say "for plotting purposes", @Peter. There are things like GrafEq and *Mathematica* for plotting implicit Cartesian equations, but in general they require way much more effort on the part of the computer to plot than parametric equations (have you seen the algorithms behind implicit equation plotters?).
Comment: I posted a new question based on this one. I want the equation of a square where each point is at the same angle as the input angle $t$, which is not true of the parametric equation above.
Comment: Forgot link: http://math.stackexchange.com/questions/655369/coordinate-of-intersection-between-line-and-square
Answer: This is an equation for a rectangle which has corners at $(a,b)$ and $(c,d)$
$$(x-a)(x-c)(y-b)(y-d)=0$$
but it extends a little beyond the corners, so instead
$$\sqrt{(a-x)(x-c)}\sqrt{(b-y)(y-d)}=0$$
which would throw an error for square roots of negative numbers
Answer: Try plotting $x^n + y^n = p^n$ where $p$ is the side length and $n$ is an even number. The larger $n$ is, the sharper the sides are.
Comment: +1. This is a great generalization of "rectangular-ish" shapes since $\lim_{n \to \infty}$ of $x^n+y^n=p^n$ actually gives the Max Norm: https://en.wikipedia.org/wiki/Uniform_norm
Answer: I found recently a new parametric form for a rectangle, that I did not know earlier:
$$
\begin{align}
x(u) &= \frac{1}{2}\cdot w\cdot \mathrm{sgn}(\cos(u)),\\
y(u) &= \frac{1}{2}\cdot h\cdot \mathrm{sgn}(\sin(u)),\quad  (0 \leq u \leq 2\pi)
\end{align}
$$
where $w$ is the width of the rectangle and $h$ is its height.
I have used this in modelling parametric ruled surfaces, where it seems to be rather handy.
Answer: If the equations of the diagonals of the rectangle are Ax + By + C = 0 and Dx + Ey + F = 0 then an equation for the rectangle is:
M|Ax + By + C| + N|Dx + Ey + F| = 1
M and N can be found by substituting the coordinates of two adjacent vertices of the rectangle.
In fact, this equation can be used to describe any parallelogram.  Roughly speaking, M (together with A and B) and N (together with D and E) give the size of the diagonals of the parallelogram.
Answer: Maybe you're looking for something like this: for $x\in(-1,2)$ plot $y=|x|$ and $y=3-|x-1|$.
Answer: In general, the implicit formula for a rectangle a la $x^2 + y^2 = a^2$ for circles is not going to be well defined.  This should be at least somewhat clear, as the boundary of a rectangle is not analytic (smooth) like the boundary of a circle is.  I suppose we could generate a piece wise function to graph the edges, something like:  $$f(x,y) = \begin {cases} (x,b) , (x,0) &  0 \leq x \leq b \\

(0,y) , (a,y) &  0 \leq y \leq a \end {cases}$$
For a rectangle with its bottom left corner at (0,0) and sides a,b.  Such a function is messy, still non-analytic and doesn't help you that much.    Ultimately, I think searching for a good implicit function of a rectangle is going to be nonproductive. What problem are you trying to apply this to?  Any comment as to your next steps / applications for the equation you're searching for will prove helpful.
Answer: This is very easy. Instead of using all of that complex math, you can instead just use the rotation matrix to rotate a simple absolute value function.
$$
     \begin{pmatrix}
     \cos \theta & -\sin \theta \\
     \sin \theta & \cos \theta \\
     \end{pmatrix}
     \begin{pmatrix}
     x \\
     y \\
     \end{pmatrix}
$$
$$
      x_1 = x_0\cos \theta - y_0\sin\theta\\
      y_1 = x_0\sin \theta + y_0\cos \theta\\
$$
Afterwards substitute the angle to be 45°. The original equation is |x|+|y|=c
This is because the absolute value is at a 45 degree angle.
$$
      |\frac {\sqrt{2}}{2}x+\frac {\sqrt{2}}{2}y|+|\frac {\sqrt{2}}{2}x-\frac {\sqrt{2}}{2}y| = c
$$
Answer: There is another interesting form using the Heaviside step function: $\theta(x)$.
If the sides are $a$ and $b$ and the rectangle is centered at $(x_0,y_0)$ then:
$$(y-y_0)^2+\alpha\theta\left[(x-x_0)^2-\frac{a^2}{4}\right]=\frac{b^2}{4}$$
where $4\alpha>b^2$.

Equation of a rectangle


Prevent empty  item in Views (HTML List format)

Question: I'm using the HTML List format for my View, which has three fields (nid and title, both excluded and Custom Text).
The content of Custom Text is as follows:

View Project

[title]

Lorem Ipsum

I've noticed that using the
 item in my Custom Text field will result in an empty
 item wrapping my content. As such, the output I get from this is as follows:

View Project

Item 1

Lorem Ipsum

View Project

Item 2

Lorem Ipsum

My question to you is: How do I remove those empty
 tags?
I tried to set wrapping element to none but to no avail. I've also attempted to do it with an unformatted list and create everything in custom text but then I'd have a
 for each row and I do not have access to data-content="#colio_c[nid] that way.
An export of my view is available at http://ideone.com/KyNGO4
Answer: It sounds like you want to override the row style output so that it doesn't output the wrapping li tag. There are other posts on here asking about that process. To get started though, in views, expand the Advanced section and click "Theme" - a window will then pop up showing you information on the template files for your theme.
Comment: Ok, looking in to the theme section, this is what I did:
Comment: For Row Style Output, I created a new template file that removed `wrapper_prefix; ?>` and `wrapper_suffix; ?>`. This got rid of the extra `` tags, but now I still needed an `` wrap. Going into Style Output, I made a new template file with:

``
` $row): ?>`
      ``
  ``
``
``
This gave me the desired result. You reckon this is the best way to go?
Comment: It's up to you which way you go. Having template files is certainly more flexible for developers, but less flexible to control things in the views interface. To reduce the number of template files to maintain, you could alternatively ensure the view format is set to "HTML list", and then in the view style options set the "List class" to "portfolio".


How do know if a Markov chain converges?

Question: Suppose that $X_n$ is a Markov chain on the states $\{0,1,2,3,4\}$ with transition matrix:
$$\begin{bmatrix}
 0 & 0 & 0 & 0 & 1 \\
 2/3 & 0 & 0 & 1/3 & 0 \\
 1/5 & 1/5 & 1/5 & 1/5 & 1/5 \\
 0 & 0 & 1/2 & 0 & 1/2 \\
 1 & 0 & 0 & 0 & 0
 \end{bmatrix}$$
I have been asked to determine whether $X_n$ converges almost surely or in $L^1$? How do I know whether these statements are true?
When I think of convergence of a Markov chain, I think of the stationary distribution (if it's ergodic) but I'm not sure if this is right.. could someone please provide some hints?
Comment: Looks like all states are transient except states 0 and 4, and once we get to one of those we infinitely bounce between them.
Comment: What is the initial distribution of the Markov chain?
Comment: We were also told that $X_0 = i$ for $0 < i < 4$?
Answer: Let $\tau=\inf\{n>0: X_n\in\{0,4\}\}$. Because $P_{04}=P_{40}$ and $\{1,2,3\}$ are transient, it is clear that $$\mathbb P\left(\bigcap_{n=\tau}^\infty \{X_n\in\{0,4\}\}\right) =1. $$
Moreover, if $N$ is a positive integer such that $X_N=0$, then $X_{N+2k}=0$ for $k=1,2,3,\ldots$ with probability $1$ and similarly if $M$ is a positive integer such that $X_M=4$, then $X_{M+2k}=4$ for $k=1,2,3,\ldots$ with probability $1$. It follows that
$$
\mathbb P\left(\liminf_{n\to\infty} \left\{X_n = 0\right\} \right)
$$
while
$$
\mathbb P\left(\limsup_{n\to\infty} \left\{X_n = 4\right\} \right),
$$
so $X_n$ does not converge almost surely. By a similar argument it is clear that $X_n$ cannot converge in $L_1$.
Comment: Thanks for your response. How did you arrive at the conclusion that "if $N$ is a positive integer such that $X_N = 0$, then $X_{N+2k} = 0$ for $k=1,2,3,...$ with probability 1, and similarly if $M$ is a positive integer such that $X_M = 4$ then $X_{M+2k} = 4$ for $k=1,2,3,...$ with probability 1"? Why are you adding $2k$?
Comment: Conditioned on $\{X_N=0\}$, we have $\mathbb P(X_{N+1}=4)=1$, $\mathbb P(X_{N+2}=0)=1)$, and so on.


What is a variance component model?

Question: I was wondering what the definition of a variance component model is? I searched it online, and found it often appears with mixed-effect models, but couldn't understand what it is, and how it is different from and related to mixed-effect models.
Answer: Variance component models "estimate the variability accounted for by each level of the hierarchy". They can refer to mixed (fixed and random) intercept models, in the form of
$$y_{ij}=\beta_0+u_i+\epsilon_{ij},$$
where $u_i∼N(0,\sigma_u^2),\epsilon_{ij}∼N(0,\sigma_{\epsilon}^2)$ are the two variance components.
References:

http://blog.stata.com/tag/variance-components/
http://data.princeton.edu/pop510/lang1.html
http://essedunet.nsd.uib.no/cms/topics/multilevel/ch3/1.html
Comment: Solid. I'd add (1) Variance-component models are explicitly designed to model within cluster correlations (2) as above I've usually used the term for random effects models without covariates.
Comment: Thanks, @charles! I completely agree with you about the first point. For (2), I think a) generally speaking the intercept is also a covariate; b) do variance component models allow random slopes (i.e. covariates for random effects)?

What is a variance component model?


how to add header and sub header to grid in runtime

Question: I am a janous grid and i setup that in runtime , i need add header and sub header to grid.
and header contains two part ,that some field in one part and some field in other part.
could any one to explain how to do it.

I use C# windows form application;
        Col = new UltraGridColumn();
        Col.Caption = "Row";
        Col.Width = 10;
        Col.HeaderAlignment = Janus.Windows.GridEX.TextAlignment.Center;
        Col.Key = "Row";
        Col.DataMember = "Row";
        MyGrid.Columns.Add(Col);

        Col = new UltraGridColumn();
        Col.Caption = "Name";
        Col.HeaderAlignment = Janus.Windows.GridEX.TextAlignment.Center;
        Col.Key = "Name";
        Col.DataMember = "Name";
        MyGrid.Columns.Add(Col);

        Col = new UltraGridColumn();
        Col.Caption = "Family";
        Col.HeaderAlignment = Janus.Windows.GridEX.TextAlignment.Center;
        Col.Key = "Family";
        Col.DataMember = "Family";
        MyGrid.Columns.Add(Col);

        Col = new UltraGridColumn();
        Col.Caption = "Address";
        Col.Key = "Address";
        Col.Width = MyGrid.Width * 18 / 100;
        Col.DataMember = "Address";
        Col.HeaderAlignment = Janus.Windows.GridEX.TextAlignment.Center;
        MyGrid.Columns.Add(Col);

        Col = new UltraGridColumn();
        Col.Caption = "Tel";
        Col.Key = "Tel";
        Col.Width = 0;
        Col.DataMember = "Tel";
        Col.HeaderAlignment = Janus.Windows.GridEX.TextAlignment.Center;
        MyGrid.Columns.Add(Col);

Comment: Did you see this link?http://stackoverflow.com/questions/18327749/how-to-add-header-and-subheader-in-gridview
Comment: yes, i have a same problem but with janous grid in win form app.
Answer: You can use GridEXColumnSet class to group columns the way you want.
This is code snippet:
Janus.Windows.GridEX.GridEXColumnSet CS = new Janus.Windows.GridEX.GridEXColumnSet();
CS.Caption = "Department";
CS.HeaderAlignment = Janus.Windows.GridEX.TextAlignment.Center;
CS.ColumnCount = 2;
CS.Width = 200;
CS.Key = "Department";
MyGrid.RootTable.ColumnSets.Add(CS);

Then you can add your columns this way:
CS.Add(col1, 0, 0); // First parameter is GridEXColumn, Second is row in ColumnSet, third is col
CS.Add(col2, 0, 2);

Comment: hi adel , thanks for response ,
in line CS.Add(col1 ,0 ,0) , i get error
error : Operation is not valid due to the current state of the object.
Comment: in form load call SetupGrid method.


How to let JPArepository.save() do insert only and prevent update?

Question: I am using JPArepository.save() to insert the record to the database but it will automatically update the existing record in the database. What I want to do is let it throw exception if there are records with same primary key in the database.
I searched the solution in Google and find a solution that said use saveAndFlush instead of save can solve it. However, it still update the existing record after I used saveAndFlush.
Comment: Does this answer your question? [Spring JPA / Hibernate transaction force insert instead of update](https://stackoverflow.com/questions/37253175/spring-jpa-hibernate-transaction-force-insert-instead-of-update)
Answer: Finally, I've found the solution.
I just implement Persistable interface and ovrride the isNew() to be always true.
Example:
@Entity
public class ChessGame implements Persistable<Long> {

    @Id
    private Long id;

    @Override
    public boolean isNew() {
        return true;
    }
}

Comment: It would be great if Accepted answer has an code example without just saying the approach
Comment: @MenukaIshan updated example
Comment: this is not working...
Comment: @Michael why not working? can u show any error log?
Comment: @MichaelTsai i still have an update query
Comment: @Michael did u return true in the isNew method? or can u reproduce ur code sample?
Comment: Yeah i just return true
Answer: There is no way to do just an INSERT without UPDATE in JPA out-of-the-box.
You need to define your own INSERT method on your JpaRepository and then call it from your code.
public interface MyRepository extends JpaRepository<MyRecord, Integer> {

    ....

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "INSERT INTO my_table (field1, field2) "
        + "VALUES (:#{#c.field1}, :#{#c.field2})", nativeQuery = true)
    public void insert(@Param("c") MyRecord c);

}

And then in the code doing the insert:
final var newRecord = MyRecord.builder()
    .field1(...)
    ....
    .build();

try {
    myRepository.insert(newRecord);
} catch (DataIntegrityViolationException e) {
    ....
}