Mass virtual hosting: map any portnumber to own domain name

Question: I need to define rule (using mod_rewrite i think) to map any port to portnumber.domain.com. How to do that in Apache2 ? Now i have one config for each port number like below.
# 9003.domain.com
<VirtualHost *:80>
    ServerName 9003.domain.com
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:9003/
    ProxyPassReverse / http://127.0.0.1:9003/
</VirtualHost>

# 9004.domain.com
<VirtualHost *:80>
    ServerName 9004.domain.com
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:9004/
    ProxyPassReverse / http://127.0.0.1:9004/
</VirtualHost>

# and so on....

Answer: You should be able to do something with ProxyPassMatch, maybe something like
ProxyPassMatch ^([0-9{2,5}]) http://127.0.0.1:$1
Comment: I don't think this will work. ProxyPassMatch operates against the URL, not the HOST name.
Comment: He's looking to match the port in the URL.. my example is just theory though :)
Comment: He's trying to match 9003.domain.com and proxy it to localhost:9003. Since ProxyPassMatch only tries to match against the path part of the URL, not the Hostname part you can't use it here.
Comment: I think I see what you mean, but I can't find anything that says that it matches against the path only.. I ask seriously, can you link me to the documentation so I can inform myself?
Comment: I have the impression that the documentation is not very clear here:
http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypassmatch
The description of ProxyPass makes it clear that it is path, not url that is matched. The description of ProxaPassMatch seems to imply that it is URLs that are matched, but the examples given tell a different story.
Comment: Yeah, I've looked through it pretty thoroughly, and cross referenced every term they used in the glossary, they say url, and in the apache httpd glossary url is the entire address including http:// the FQDN and the path. Which is why I was hoping you had something I missed.. maybe we (or me) should ask them to update the documentation.
Comment: I tested it, and ProxaPassMatch appears not to match against the hostname part of the URL
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/8843/discussion-between-nickw-and-krist-van-besien)
Answer: I did some corrections on @Krist answer and make it works now. 403 error was from RewriteEngine On absence.
<VirtualHost *:80>
     RewriteEngine On
     ServerAlias *.domain.com
     RewriteCond %{HTTP_HOST}      (\d+).domain.com
     RewriteRule ^/(.*)$           http://localhost:%1/$1    [P]
</VirtualHost>

Answer: A RewriteRule would indeed do it.
<VirtualHost *:80>

Servername www.domain.com
ServerAlias *.domain.com

RewriteCond %{HTTP_HOST}      (\d+).domain.com
RewriteRule (.*)              http://localhost:%1/$1    [P]

</VirtualHost>

Comment: Thanks for You response, but i've got `403: Forbidden Error`. Do You know what can i do ?
Comment: Have a look in the error log of your webserver. A 403 means that the server won't give you the content for some reason, and the reason is usually mentioned in the log.


Why won't my angular data-bindings update in the view?

Question: I am working on a basic JavaScript racer program, and I'm trying to use Angular to update the score in the view. I have written the basic code to move the players and have different game states.
You can see how I set up my code here:
http://jsfiddle.net/ey8dk22r/1/
For some reason it isn't showing up in the fiddle, but on my end the angular code will show "0" for each score. If I change $scope.score_one or two to something like "hello", the word "hello" will show up in its place. Currently, I have {{ score_one }} and {{ score_two }} set to player1.score and player2.score. Whatever the number is initially set to will be what shows up (0). When a player wins and the player's score is successfully updated, the score in the view is not updated.
Here is part of my js file; the Player object and the scoreController:
function Player(element_id, name){
  this.el = $(element_id).selector;
  this.position = 1;
  this.name = name;
  this.score = 0;
  this.check = function(){
    if ($(this.el + ' td:last-child').hasClass("active")){
      this.score += 1;
      $(".winner").html("
" + this.name + " wins!
")
      game = false;
      $(".reset").show();
    }
  }
  this.move = function(position){
    $(this.el + ' td').removeClass('active');
    $(this.el + ' td:eq(' + (this.position) + ')').addClass("active");
    this.check();
    this.position += 1;
  }
}

function scoreController($scope){
  $scope.score_one = player1.score;
  $scope.score_two = player2.score;
}

And here is where I do the data-binding in the html file:

A Day at the Races

Mew: {{ score_one }}

Celebi: {{ score_two }}

So, I'm wondering if I have something wrong with the scope, and why the score is not correctly updating. I do correctly have angular linked and I was trying things with input fields that was correctly updating the view, but for some reason this isn't working. I looked at $apply and tried $scope.score_one in $apply(), but I'm not sure if I did that correctly.
Let me know if you have any ideas. Thank you.
Comment: you are correct that you should use `$apply` to update the models' values.
Comment: There are quite a few issues here. First, your jsfiddle has errors even finding your controller. Second, I don't see where you define your angular app: where's your `angular.module("App", [])`? Before we get to "third", can you fix this first?
Answer: I think your issue has more to do with how you are setting up your code, rather than a specific syntax problem. In general, jQuery and Angular don't mesh too well together. From the Angular docs:

Does Angular use the jQuery library?
Yes, Angular can use jQuery if it's present in your app when the application is being  >bootstrapped. If jQuery is not present in your script path, Angular falls back to its own >implementation of the subset of jQuery that we call jQLite.
Angular 1.3 only supports jQuery 2.1 or above. jQuery 1.7 and newer might work correctly with >Angular but we don't guarantee that.

I see that you're using jQuery 1.11 with Angular 1.2.15, so you fall in that "might" work correctly category. If I were you, I would pick one of these tools and go with it.
Finally, if you are to go with Angular, you need to first instantiate your module, then define your controllers. Something like this would work:
var myAppModule = angular.module('myApp', []);
myAppModule.controller('scoreController', '$scope', function($scope) {
    $scope.score_one = player1.score;
    $scope.score_two = player2.score;
}

And you would build the ways to increment the scores in a similar fashion. In short, I would keep everything in Angular, and not even think about jQuery. Angular is great for the two way bindings that you're doing in an app like this, so I think it's the best way to go. Good luck.
Comment: Thanks. I didn't realize the issues with using both Angular and jQuery.

I will go ahead and try again with just Angular.


Android SearchView without Intent

Question: It is little abstract question but i cannot find any solution for that. Is there any way for using searchview without intent ? I am trying to search something without creating activity again.
Comment: You may us:e https://github.com/MiguelCatalan/MaterialSearchView
Comment: No problem, I added an answer with some more libraries ;-)
Answer: Actually there are some libraries which you can use for this

MaterialSearchView: https://github.com/MiguelCatalan/MaterialSearchView
Android-Material-SearchView: https://github.com/EugeneHoran/Android-Material-SearchView
MaterialDialogSearchView: https://github.com/TakeoffAndroid/MaterialDialogSearchView
SerchView: https://github.com/lapism/SearchView

Of course, these are only examples of many others which you would find on GitHub page. So be patient and find the one which would be the most comfortable to you and the best fit for your app.
Answer: Actually you don't need use any of these if you want.
You may simply override the callbacks of the SearchView.OnQueryTextListener.
See the following example:
<code>public class MySearchActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SearchView searchView = (SearchView) findViewById(R.id.searchView);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                //Every hit on "Enter"
                doSearch(s);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                //Any change in the query string
                doSearch(s);
                return true;
            }
        });
    }

    /*
    * Implement your search into a SQLite database, webservice or anything else...
    * */
    private void doSearch(String query) {
        searchAndNotifyAdapterWithResult(query);
    }
}
</code>

Android SearchView without Intent


Transforming an improper integral to one with limits $0$ and $1$.

Question: I´m working on transforming an improper integral to an integral with limit 0 and 1. I know I can use the following identities, but they just work for limits from 0 to infinity.
Here are the indentities:

$$\theta=\int_0^\infty g(x)\,\mathrm dx,$$ we could apply the substitution $y=1/(x+1),\mathrm dy=-\mathrm dx/(x+1)^2=-y^2\mathrm dx,$ to obtain the identity $$\theta=\int_0^1h(y)\,\mathrm dy,$$ where $$h(y)=\dfrac{g\left(\tfrac1y-1\right)}{y^2}.$$

How can I apply them to the integral below?
$$\theta=\int_{-\infty}^\infty e^{-x^2}\mathrm dx=1.77245385090551602\ldots$$
Answer: Since the integrand $e^{-x^2}$ is even, we can write $\displaystyle\int_{-\infty}^{\infty}e^{-x^2}\,dx = 2\int_{0}^{\infty}e^{-x^2}\,dx$, and then apply the transformation to get $\displaystyle\int_{0}^{1}\dfrac{2}{y^2}e^{-\left(\frac{1}{y}-1\right)^2}\,dy$. Of course, there are better ways to evaluate the Gaussian Integral.
Comment: Thank you very much. I appreciate your answer.


Delete em mais de uma tabela com uma SQL?

Question: Estou tentando aplicar um DELETE em mais de uma tabela, as tabelas possuem uma coluna (não com o mesmo nome) com os mesmo atributos. Quero deletar através do ID. Mas tenho a tabela usuario com coluna id e areausuario com coluna idUsuario, são os mesmos atributos (id = 1, IdUsuario = 1).
Estava tentando com este código.
DELETE us.*
FROM usuarios us
INNER JOIN disponibilidade ds ON (us.id = ds.IdUsuarios)
INNER JOIN areausuarios au ON (ds.IdUsuarios = au.IdUsuarios)
INNER JOIN gestor g ON (au.IdUsuarios = g.id)
WHERE g.id = 7;

Mas este código esta deletando somente de uma tabela.
Tentei alguns outros mas ele aplica o erro 1451, onde eu não posso deletar o usuario, sem antes retirar ele da tabela areausuarios.
Answer: ON DELETE CASCADE.
A mensagem que diz que voce não pode "deletar o usuário sem antes retirar ele da tabela areausuario" indica que existe um relacionamento entre as duas tabelas através de uma chave estrangeira.
O que vc tem de fazer é exatamente isso, primeiro deletar o usuário da tabela areausuario e só depois excluir da tabela usuário. Na maioria dos bancos voce pode configurar o relacionamento de forma que ao deletar um um registro na tabela "pai", automaticamente os registros correspondente serão deletados na tabela "filho".
Veja como se faz em Mysql nesse link.
Answer: Suas tabelas estão relacionadas?
Existe foreign key na coluna IdUsuario na tabela areausuario?
Se sim, você pode utilizar o on delete cascade, como está explicado pelo @Sidon.

Senão, você pode executar duas queries distintas e depois efetuar o commit.
É possível utilizar o conceito de transaction para executar essas queries distintas e por fim executar o commit.
A pergunta tem as tags java e mysql, mas não possui código Java em seu corpo. Dessa forma fica difícil explicar detalhadamente como fazer, mas aqui em tem um exemplo de como usar transaction com Java e MySQL.


Convergence of a logarithmic sequence

Question: Is the sequence $\left\{\ln\left((1+\frac1n)^n\right)\right\}_{n=1}^{\infty}$ convergent or divergent?.
I tried to solve it by L Hospital's rule and arrived at 0...implying it is convergent..is it?
If it is right then is there an alternate method?
Comment: I would be happy to see how you applied L'Hospital's rule as well, just to be sure. After all, solving it by L'Hospital to arrive at $0$ is pretty unclear. What arrives at $0$? But I'll vote to reopen the question now anyway. Hopefully the community should reopen it soon. But I encourage you to provide your work in detail.
Comment: Welcome to MSE! Please add more details to the question, in particular where you encountered this problem and what you have tried so far. Otherwise the community will not be very willing to help you.
Comment: I found this problem in Thomas Calculus...I tried l hospital's rule and arrived at 0...which means it is convergent
Comment: these details must go into the question, and not in the comments. Moreover, if you applied l'Hospital's rule to get a precise answer, then what exactly is your question?
Comment: Just making if was right, if so, is there any. Alternate method for ir
Comment: i see...that is not an issue, all I'm reiterating is that all these details must go into the body of the question itself. Providing your work encourages the community to help you and also makes our work easier. There are also specific tags like [tag:proof-verification] and [tag:alternative-proofs] that you can add to your question if that's what you're really asking. Try not to just place a problem statement in the question, that is not considered good practice here.
Comment: Is it fine now?
Comment: @user445027 Please recall that if the OP is solved you can evaluate to accept an answer among the given, more details here https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Answer: HINT
Recall that by standard limit
$$\left(1+\frac1n\right)^n\to e$$
As an alternative we have by $x=\frac 1n \to 0$
$$\ln \left(1+x\right)^{\frac1x}=\frac{\ln (1+x)}{x}$$
which is also a standard limit and which, as an alternative, can be solved by l'Hopital rule.
Comment: How about applying l hospital's rule....then it will come out to be 0
Comment: @user445027 We don't need that, the given limit is a well known limit which should be proved a part. Once we have that by continuity lim_{n\to infty} $$\ln \left(1+\frac1n\right)^n=\ln e =1$$
Comment: @user445027 I've added something to solve it by l'Hopital. Anyway I suggest to learn the standard limits and how to prove them without l'Hopital if you really want to learn to calculate limits effectively.
Comment: @ gimusi: correct is $\ln \left(1+\frac1n\right)^n \to\ln e =1$ (not "$=$"):
Comment: @gimusi how can this be solved without l hospital's rule?
Comment: @Fred Yes of course sorry for tha typo. Thanks!
Comment: @user445027 The proof is not trivial without l'Hopital but it is really instructive. Notably we need to show that the sequence $\left(1+\frac1n\right)^n$ is increasing and bounded above (<3) then for the monotonic sequence theorem the limit exists. Take a look here https://math.stackexchange.com/questions/1867964/monotonicity-of-the-sequence-a-n-where-a-n-left-1-frac1n-right?noredirect=1&lq=1 and https://math.stackexchange.com/questions/1185660/prove-1-frac1nn-is-bounded-above?noredirect=1&lq=1.
Comment: Take also a look here http://www.milefoot.com/math/calculus/limits/LimitDefinitionOfE10.htm
Comment: @Fred I just note that I wrote correctly that $\lim_{n\to \infty} a_n=\ln e=1$ but there was a problem in the editing.

Convergence of a logarithmic sequence


C# 'Unassigned local variable'?

Question: I tried to make a piece of code which would roll a dice in the end to decide which character wins and it keeps on saying that there are errors (Use of unassigned local variable 'skillmodifier') & (Use of unassigned local variable 'strengthmodifier'). I would really appreciate any help. P.S I have only been doing programming for a short period of time on Visual Studio 2010. Please help me find a solution to this problem, the problem occurs because I use the variables 'strengthmodifier' and 'skillmodifier' twice. Thank you, yours faithfully, Vikash.
I will paste the task breif below and the code after that:
Task 3 Determining the outcome of an encounter
When there is an encounter between two characters the outcome is determined by the following
process:
• The differences between the strength attributes for the two characters is calculated
• This difference is divided by 5 and then rounded down to create a 'strength modifier'
• The process is repeated for the skill attribute to create a 'skill modifier'
• Each player throws a 6 sided dice.
• If the scores on both dice are the same, no changes are made
• If the scores are not the same, the player with the highest score adds the 'strength
modifier' to the strength value and the 'skill modifier' to the skill value for their
character
• The player with the lower score on the dice subtracts these modifiers from the
strength and skill values for their character
• If a skill value becomes negative, then it is stored as zero
• If a strength value becomes zero or negative, then the character dies.
The program should:
*• Allow the user to input the strength and skill for two characters.
• Display the outcome of the encounter using the process above.
Design an algorithm to describe this process. Write, test and evaluate the code.*
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

        namespace Task3
       {
         class Program
          {

            static void loopfsto()
             {

            Console.WriteLine("Please enter a value of strength, and then press enter");
            string csto = Console.ReadLine(); // Read string from console
            int csto1;
            if (int.TryParse(csto, out csto1)) // Try to parse the string as an integer
            {
                Console.WriteLine("Your chosen number is " + csto1 + ".");
                Console.ReadKey();
            }
            else
            {
                Console.Clear();
                Console.WriteLine("Not an integer!");
                Console.ReadKey();
                Console.Clear();
                loopfsto();
            }
        }

        static void loopfsko()
        {
            Console.WriteLine("Please enter a value of skill, and then press enter");
            string csko = Console.ReadLine(); // Read string from console
            int csko1;
            if (int.TryParse(csko, out csko1)) // Try to parse the string as an integer
            {
                Console.WriteLine("Your chosen number is " + csko1 + ".");
                Console.ReadKey();
            }
            else
            {
                Console.Clear();
                Console.WriteLine("Not an integer!");
                Console.ReadKey();
                Console.Clear();
                loopfsko();
            }
            Console.Clear();
        }

        static void loopfstt()
        {
            Console.WriteLine("Please enter a value of strength for, and then press enter");
            string cstt = Console.ReadLine(); // Read string from console
            int cstt1;
            if (int.TryParse(cstt, out cstt1)) // Try to parse the string as an integer
            {
                Console.WriteLine("Your chosen number is " + cstt1 + ".");
                Console.ReadKey();
            }
            else
            {
                Console.Clear();
                Console.WriteLine("Not an integer!");
                Console.ReadKey();
                Console.Clear();
                loopfstt();
            }
            Console.Clear();
        }

        static void loopfskt()
        {
            Console.WriteLine("Please enter a value of skill for, and then press enter");
            string cskt = Console.ReadLine(); // Read string from console
            int cskt1;
            if (int.TryParse(cskt, out cskt1)) // Try to parse the string as an integer
            {
                Console.WriteLine("Your chosen number is " + cskt1 + ".");
                Console.ReadKey();
            }
            else
            {
                Console.Clear();
                Console.WriteLine("Not an integer!");
                Console.ReadKey();
                Console.Clear();
                loopfskt();
            }

        }

        static void Main(string[] args)
        {

            string Character1;
            string Character2;
            int strengthmodifiertoround;
            int skillmodifiertoround;
            int strengthmodifier;
            int skillmodifier;
            Console.Title = "Strength and Skill";

            Console.WriteLine("Welcome to Strength and Skill, please press enter to continue.");
            Console.ReadKey();
            Console.Clear();

            Console.WriteLine("Please enter a name for character 1, then press enter.");
            Character1 = Console.ReadLine();
            Console.Clear();

            Console.WriteLine("Please enter a name for character 2, then press enter.");
            Character2 = Console.ReadLine();
            Console.Clear();

            Console.WriteLine("Please enter a value of strength for " + Character1 + ", and then press enter");
            string csto = Console.ReadLine(); // Read string from console
            int csto1;
            if (int.TryParse(csto, out csto1)) // Try to parse the string as an integer
            {
                Console.WriteLine("Your chosen number is " + csto1 + ".");
                Console.ReadKey();
            }
            else
            {
                Console.Clear();
                Console.WriteLine("Not an integer!");
                Console.ReadKey();
                Console.Clear();
                loopfsto();
            }

            Console.Clear();

            Console.WriteLine("Please enter a value of skill for " + Character1 + ", and then press enter");
            string csko = Console.ReadLine(); // Read string from console
            int csko1;
            if (int.TryParse(csko, out csko1)) // Try to parse the string as an integer
            {
                Console.WriteLine("Your chosen number is " + csko1 + ".");
                Console.ReadKey();
            }
            else
            {
                Console.Clear();
                Console.WriteLine("Not an integer!");
                Console.ReadKey();
                Console.Clear();
                loopfsko();
            }
            Console.Clear();

            Console.WriteLine(Character1 + " has a strength of " + csto1 + " and a skill of " + csko1 + ".");
            Console.ReadKey();
            Console.Clear();

            Console.WriteLine("Please enter a value of strength for " + Character2 + ", and then press enter");
            string cstt = Console.ReadLine(); // Read string from console
            int cstt1;
            if (int.TryParse(cstt, out cstt1)) // Try to parse the string as an integer
            {
                Console.WriteLine("Your chosen number is " + cstt1 + ".");
                Console.ReadKey();
            }
            else
            {
                Console.Clear();
                Console.WriteLine("Not an integer!");
                Console.ReadKey();
                Console.Clear();
                loopfstt();
            }
            Console.Clear();

            Console.WriteLine("Please enter a value of skill for " + Character2 + ", and then press enter");
            string cskt = Console.ReadLine(); // Read string from console
            int cskt1;
            if (int.TryParse(cskt, out cskt1)) // Try to parse the string as an integer
            {
                Console.WriteLine("Your chosen number is " + cskt1 + ".");
                Console.ReadKey();
            }
            else
            {
                Console.Clear();
                Console.WriteLine("Not an integer!");
                Console.ReadKey();
                Console.Clear();
                loopfskt();
            }
            Console.Clear();

            Console.WriteLine(Character2 + " has a strength of " + cstt1 + " and a skill of " + cskt1 + ".");
            Console.ReadKey();
            Console.Clear();
//--- Finds out if strength for character 1 is higher than 2 or vice versa. Then finds difference between two and makes a variable called strengthmodifier ---//

            {
                if (csto1 < cstt1)
                {
                    strengthmodifiertoround = cstt1 - csto1;
                    strengthmodifier = strengthmodifiertoround / 5;
                }
                if (cstt1 < csto1)
                {
                    strengthmodifiertoround = csto1 - cstt1;
                    strengthmodifier = strengthmodifiertoround / 5;
                }
            }
//--- Finds out if skill for character 1 is higher than 2 or vice versa. Then finds difference between two and makes a variable called skillmodifier ---//

            {
                if (csko1 < cskt1)
                {
                    skillmodifiertoround = cskt1 - csko1;
                    skillmodifier = skillmodifiertoround / 5;
                }
                if (cskt1 < csko1)
                {
                    skillmodifiertoround = csko1 - cskt1;
                    skillmodifier = skillmodifiertoround / 5;
                }
            }
//--- Tells user to put input and roll a virtual dice (which is actually creating a number between 1 and 6) ---//
            Console.WriteLine(Character1 + ", please press enter to roll dice");
            Console.ReadKey();
            Random rand = new Random();
            int character1RandomNumber = rand.Next(1, 6);

            Console.WriteLine(Character2 + ", please press enter to roll dice");
            Console.ReadKey();
            Random rand1 = new Random();
            int character2RandomNumber = rand1.Next(1, 6);
            Console.WriteLine(Character1 + " rolled a " + character1RandomNumber + " and " + Character2 + " rolled a " + character2RandomNumber + ".");
            Console.ReadKey();
            if (character1RandomNumber < character2RandomNumber)
            {
                int char2st = cstt1 + strengthmodifier;
                int char2sk = cskt1 + skillmodifier;
                int char1st = csto1 - strengthmodifier;
                int char1sk = csko1 - skillmodifier;
            }
            if (character2RandomNumber < character1RandomNumber)
            {

            }

                int ch2st = cstt1 - strengthmodifier;
                int ch2sk = cskt1 - skillmodifier;
                int ch1st = csto1 + strengthmodifier;
                int ch1sk = csko1 + skillmodifier;

        }
    }
}

Comment: Look to use ReSharper (http://www.jetbrains.com/resharper/) and this tool will help you discover such issues and give tips or suggestions on your code.  It simply highlights lines to indicate where your code has an issue.
Comment: Task 3 Determining the outcome of an encounter
When there is an encounter between two characters the outcome is determined by the following
process:
• The differences between the strength attributes for the two characters is calculated
Comment: • This difference is divided by 5 and then rounded down to create a 'strength modifier'
• The process is repeated for the skill attribute to create a 'skill modifier'
• Each player throws a 6 sided dice.
• If the scores on both dice are the same, no changes are made
• If the scores are not the same, the player with the highest score adds the 'strength
modifier' to the strength value and the 'skill modifier' to the skill value for their
character
• The player with the lower score on the dice subtracts these modifiers from the
strength and skill values for their character
Comment: • If a skill value becomes negative, then it is stored as zero
• If a strength value becomes zero or negative, then the character dies.
The program should:
• Allow the user to input the strength and skill for two characters.
• Display the outcome of the encounter using the process above.
Design an algorithm to describe this process. Write, test and evaluate the code.
Comment: Sorry for not briefing this earlier. I am new to this and I hope you understand. Thank you very much for the help.
Answer: Actually, i think your problem is because skillmodifier and strengthmodifier do not get assigned values on all code paths. ie. They are only assigned values from within if clauses and visual studio cannot determine whether or not they are assigned for all possible outcomes. This warning shouldn't stop your code compiling but if you want it to go away you can do something like
int skillmodifiertoround = 0;

instead of just
int skillmodifiertoround;

Now skillmodifiertoround is given a value on declaration.
Edit: "This warning shouldn't stop your code compiling" - Apparently it will stop the program from compiling correctly in c# but the same error in vb only gives a warning but still compiles.
Comment: Thank you for your help 5uperdan. It helped me to change another problem.
Comment: @vik1924 Instead of `if (csko1 < cskt1) { ... } if (cskt1 < csko1) { ... }` use `if (csko1 < cskt1) { ... } else { ... }`. That way the compiler will know that control has been through either of the two blocks, and it can then infer that the local variable has been assigned to before it is read.
Answer: Its rather simple really
int skillmodifier;

You need to assign it - that is give it a value, even a default one - before you can use it. Otherwise the program doesn't know what value it has.
So something like
int skillmodifier = -1;

will fix it for you.
Answer: When you declare int skillmodifier declare it as whatever the default value should be,e.g. int skillmodifier = 0;
Do the same for strengthmodifier and you should be good to go!
The problem is that the compiler can detect a way of executing your code without these parameters being set.
Comment: Thanks very much Ross Dargan, I really appreciate your help.
Answer:
Local variables in C# must be initialized before they are used.

From MSDN
Also see related questio Why aren't unassigned local variables automatically initialized?
For generics where type is not known, use default keyword
Comment: Thank you Tilak for this useful statement. I will try and go over mistakes.
Answer: I think the other people have given you the answer, but I spotted something else.
Instead of
//method
if(tryparse)
{
//done
}
else
//loop
you should turn the methods into methods that return ints and then...
int csko = loopCsko()

C# 'Unassigned local variable'?


KDoc: Insert code snippet

Question: How do I insert a code snippet in KDoc, Kotlin's default documentation tool?
In Java, I can use the following:
<code>/**
 * Example usage:
 *
 * <pre>
 * <code>@JavaAnnotation
 * public void foo() {
 *     // Code
 * }
 * </code>
 * </pre>
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface JavaAnnotation {}
</code>
There seems to be no equivalent in Kotlin. I tried using Markdown, but inserting 2 spaces after line end does not line-break.
Answer: You can use triple backticks:
<code>/**
 * Example usage:
 *
 * ```
 * @JavaAnnotation
 * public void foo() {
 *     // Code
 * }
 * ```
 */
</code>
Comment: Tilde (`~~~`) works, too. It might be easier to type.

KDoc: Insert code snippet


Prove that the area of $M$ is bigger than the area of $\mathbb{S}^2$

Question: Given $\mathbb{S}^2$ the unit sphere in $\mathbb{R}^3$ and let $f:\mathbb{S}^2\to \mathbb{R}$ be a $C^1$ function such that $f(x)\geq1$ for every $x\in\mathbb{S}^2$ and define $M=\{xf(x)|x\in\mathbb{S}^2\}$
1.Prove that $M$ is smooth manifold with dimension of $2$
2.Prove that the area of $M$ is bigger than the area of $\mathbb{S}^2$
Attempt:

I proved it with composition of a map and f and showed that it is a regular parametrization.
I've thought of doing the following
$r:U\to\mathbb{S}^2$  map of the unit sphere
$\int_M 1=\int_U \sqrt{\Gamma \left (\frac{d g}{dx_i} \right )}$ where $g(x_1,x_2)=r(x_1,x_2)f(r(x_1,x_2))$ but got stuck here and somehow to use the fact that $f(x)\geq1$

any hint?
Comment: 'area' of $M$ makes sense *because* $f$ is $C^1$ right?
Answer: Your idea can be made to work but it involves some calculations. Let's write vectors in $\mathbb{R}^3$ as column vectors and choose $X \colon U \rightarrow \mathbb{R}^3$ such that $U \subseteq \mathbb{R}^2$ is an open set and $X$ is a parametrization of almost all of $\mathbb{S}^2$. For example, $X$ can be defined using spherical coordinates but the specific form of $X$ does not matter. Then $Y \colon U \rightarrow \mathbb{R}^3$ given by
$$ Y(p) = \underbrace{f(X(p))}_{:=h(p)} X(p) $$
is a parametrization of almost all of $M$. First of all, note that $\| X(p) \|^2 = X^T \cdot X = 1$ for all $p \in U$. Differentiating this identity, we obtain
$$ X^T \cdot dX = 0 $$
(where $dX$ is the $3 \times 2$ matrix representing the differential).
Now, using the chain rule, we have
$$ dY = (X \cdot dh + h dX) $$
and so
$$ dY^T \cdot dY = \left( \nabla h \cdot X^T + h dX^T\right) \cdot \left(X \cdot \left( \nabla h \right)^T + h dX\right) = \nabla h \cdot \left( \nabla h \right)^T + h \left( \nabla h \cdot \underbrace{X^T \cdot dX}_{0} + \underbrace{dX^T \cdot X}_{0} \cdot \left( \nabla h \right)^T \right) + h^2 (dX^T \cdot dX) =
(\nabla h) \cdot \left( \nabla h \right)^T + h^2 (dX^T \cdot dX). $$
Using the matrix determinant lemma we get
$$ \det \left( Y^T \cdot Y \right) = \left( 1 +  \left( \nabla h \right)^T \left( h^2 \left( dX^T \cdot dX \right)\right)^{-1} \cdot  \nabla h \right) h^4 \det \left( X^T \cdot X \right) = \left( h^4 + h^2 \left< \nabla h, \left( dX^T \cdot dX \right)^{-1} \nabla h \right>\right) \det \left( X^T \cdot X \right). $$
Note that $\left( dX^T \cdot dX \right)^{-1}$ is a positive definite symmetric matrix and so $\left< \nabla h, \left( dX^T \cdot dX \right)^{-1} \nabla h \right> \geq 0$. Together with the fact that $h \geq 1$, we can conclude that
$$ \det \left( Y^T \cdot Y \right) \geq \det \left(X^T \cdot Y \right). $$
Finally,
$$ \textrm{Area}(M) = \iint_{U} \sqrt{\det \left( Y^T \cdot Y \right)} \geq \iint_{U} \sqrt{\det \left( X^T \cdot X \right)} = \textrm{Area}(\mathbb{S}^2). $$
Comment: You can even see from the calculation that if $f(q) > 1$ at some point $q \in \mathbb{S}^2$ then at that point, $\det(dY^T \cdot dY) > \det(dX^T \cdot dX)$ and so the area of $M$ is strictly larger than the area of $\mathbb{S}^2$, as expected.


What are the probabilities for more than +/- 3 standard deviations away from the mean in a normal distribution?

Question: With a normal distribution, I'm familiar with +/- 1, 2, and 3 standard deviations:
+/-
1: 68%
2: 95.45%
3: 99.73%
What are the probabilities for +/- 4, 5, 6, 7, 8, 9, or even 10 standard deviations away from the mean?
Comment: For large arguments, note that the upper tail probability, $1-\Phi(z)\approx \phi(z)/z \approx \frac{0.3989}{z}e^{-\frac12 z^2}$ and the probability in both tails is then $\approx \frac{0.7979}{z} e^{-\frac12 z^2}$. e.g. for $z=10$ (10 s.d.'s) this gives  $1.53892\times 10^{-23}$ while the exact answer is $1.52397... \times 10^{-23}$. The larger the number of standard deviations, the better this works.
Answer: We can figure this out by using the cumulative density function of the normal distribution.
In math notation, $\Psi(n)-\Psi(-n)$, where $\Psi$ is the cdf and $n$ the number of standard deviations.
In R for example:
<code>(pnorm(1:10)-pnorm(-(1:10)))
</code>
0.6826895 0.9544997 0.9973002 0.9999367 0.9999994 1.0000000 1.0000000 1.0000000 1.0000000
As we can see, it goes to 1 very quickly (though never quite reaches it; we observe exactly 1 due to numerical error).
Comment: It doesn't have to be expressed as a difference because the distribution is symmetric.  `10^(pnorm(-(1:10), log = TRUE)/log(10) + log10(2))` does the trick for the common logarithms* of the complementary* probabilities. Thus, for instance, because the last value output is `1.523971e-23`, we deduce your last "1.0000000" really is $0.9999999999999999999998476029...$
Comment: You can also use log=TRUE in pnorm to allow for higher-precision reporting of the probability, to give a better view of just how close to 1 the probability gets.
Comment: I never took an intro stats course ;-).
Comment: yeah but you have to be careful about how you do the computation because it's the log of a *difference*; it's not as simple as just doing log=TRUE in this case (we need to do the logsumexp trick).
Comment: nice moves @whuber. I bet you rocked intro stats ;)


How do I transfer my garageband project to logic pro without the vocals messing up?

Question: I exported a project to logic from garageband and everything lined up PERFECTLY. I got so excited because I recorded this song years ago before I had logic. I thought everything was perfect until I clicked play. All of the vocals had random sounds in them and there was a lot of extra noise and scratchiness in the logic project.
Any suggestions?
Answer: It sounds like something might have gone wrong during the export. You might need to manually export the raw audio of the vocal track and import it into Logic. Another option you could try is disabling any inserts (effects) one by one to see if that fixes the issue. Last thing I can think of is that there may be a buffer size issue. Through preferences in Logic you can increase the buffer size, this could solve crackles and pops you hear during playback.


meteor galaxy update node version

Question: Does anyone know what version of node is used by meteor galaxy?
I just tried to deploy and got the following error:
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

Therefore I assume that an old version of node is used.
The same code worked fine a couple of days ago.
Answer: Each version of Meteor is linked to a given version of Node. Galaxy probably uses the one linked to your project. You can see which version it is by running meteor node --version within your project directory (on your local computer), and (potentially) update it by running meteor update.

meteor galaxy update node version


Real Analysis proof $\sup T = r + t \sup S$

Question: $S$ is a set of real numbers bounded above, $r$ is a real number, and $t$ is a positive real number.
Let $T = \{r + tx : x ∈ S\}$
Show that $\sup T = r + t \sup S$
Can anyone provide me with links or start me off with this question? (or similar examples with this question) hints would be appreciated. Not expecting any full answers
Thanks in Advance
Answer: I'd do it in two steps; for a nonempty set of real numbers $X$ and a real number $r$, define
$$
r+X=\{r+x:x\in X\}
$$
Prove that, if $X$ is bounded above, then $\sup(r+X)=r+\sup X$.
Second step. For a real number $t$, define
$$
tX=\{tx:x\in X\}
$$
Prove that, if $X$ is bounded above and $t>0$, then $\sup(tX)=t\sup X$.
Put the two steps together for proving your assignment.
The first step should be easy. For the second one, note that, if $u$ is an upper bound for $X$, then $tu$ is an upper bound for $tX$ and, conversely, if $v$ is an upper bound for $tX$, then $v/t$ is an upper bound for $X$.


From log file into terminal in realtime

Question: I'm on Ubuntu.
Is it possible to open putty and watch as a log file updates right in terminal? Like if stdout would have been directed in terminal?
For example I have one application's stdout and stderr directed into a file and want to watch how my app is starting from another terminal.
Answer: If you want to follow a log file, you can use the famous:
$ tail -f /path/to/log/file

Comment: Damn forgot about tail :D ty again. Used it inside gltail.
Comment: @Beck: If you want to view the log while writing in the same terminal, you can use `tee`.
Comment: Perfect. For example if you have a homebrew installation of Apache httpd, you can open a terminal window and run
tail -f /opt/homebrew/var/log/httpd/access_log
then load a web page from that server and see all the http transactions in real time.
Answer: In addition to tail -f, you can also  use less with the +F parameter, which will allow you to keep track of new new input, but at the same time have access to all interactive functions of less, such as searching.
In some situations it is better to use tail -F (or less --follow-name) instead of tail -f. This assures that you continue following new input even if the file name changes. It is especially useful with some log-rotating software.
Comment: interesting, will check that out. have been thinking about such a feature...

From log file into terminal in realtime


Starting Varnish in a Docker Container fails for Unknown Reason

Question: I'm trying to get Varnish to run in a container, and I'm running into a weird issue. Things work fine if I log in, and then execute from a command line, but when I try to run it, using the same command, from Docker, it seems fails (I'm guessing it's not picking up the configs properly). Any ideas?
<code>$ docker run --add-host "web:127.0.0.1" -ti my-proxy /bin/bash
root@f81c7d3ca1c6:/# /usr/sbin/varnishd -F -f /etc/varnish/default.vcl -a :80 -T localhost:6082 -S /etc/varnish/secret -s malloc,256m
child (24) Started
Child (24) said Child starts
^CManager got SIGINT
Stopping Child
root@f81c7d3ca1c6:/# exit

$ docker run --add-host "web:127.0.0.1" my-proxy
WARNING: (-sfile) file size reduced to 0 (80% of available disk space)
child (14) Started
Pushing vcls failed:
CLI communication error (hdr)
Stopping Child
Child (14) died signal=6
Child (14) Panic message: Assert error in smf_open_chunk(), storage_file.c line 403:
  Condition(sz != 0) not true.
thread = (cache-main)
ident = Linux,4.0.9-boot2docker,x86_64,-sfile,-smalloc,-hcritbit,no_waiter
Backtrace:
  0x430935: /usr/sbin/varnishd() [0x430935]
  0x44b2cf: /usr/sbin/varnishd() [0x44b2cf]
  0x44b561: /usr/sbin/varnishd() [0x44b561]
  0x449a57: /usr/sbin/varnishd(STV_open+0x27) [0x449a57]
  0x42f74f: /usr/sbin/varnishd(child_main+0xbf) [0x42f74f]
  0x44255f: /usr/sbin/varnishd() [0x44255f]
  0x442e62: /usr/sbin/varnishd(MGT_Run+0x1d2) [0x442e62]
  0x40c2c0: /usr/sbin/varnishd(main+0x930) [0x40c2c0]
  0x7f9ccbc40ec5: /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5) [0x7f9ccbc40ec5]
  0x40c644: /usr/sbin/varnishd() [0x40c644]

Child (-1) said Child starts
Child cleanup complete
manager dies
</code>
Here's the Docker command:
<code>CMD ["/usr/sbin/varnishd", "-F", "-f", "/etc/varnish/default.vcl", "-a", ":80", "-T", "localhost:6082", "-S", "/etc/varnish/secret", "-s", "malloc,256m"]
</code>
Comment: Issues like this are frequently caused by environment variable issues. Make sure that your list of environment variables are being populated correctly.
Comment: Thanks for the suggestion! What env variables might be missing? I have no idea what variables would be present when I start with a script, vs. from a shell.
Answer: The failure here was totally Docker, and not related at all to Varnish. I had been doing a bunch of builds, and it turns out the issue was I was out of inodes.
https://gist.githubusercontent.com/michaelneale/1366325a7737c4cb80b0/raw/4a61279d8498758111533589d1de648a9a31f691/docker-clean
Running both of these solved my problem.


Filtering objects in underscore

Question: I'm trying to create a filterObject mixin in underscore. It's not going quite well, is there something I'm missing?
_.mixin({
  filterObject: function(collection, fn){
    var n = []
    _.each(collection, function(value, key){
      var decider = fn(value, key)
      if(decider){
        var temp = {}
        temp[key] = value
        n.push(temp)
      }
    })
    return _.extend.apply(null, n);
  }
})

var actionsFlags = {
  "wallpaper": {
    "images": true,
    "queue": false,
  },
  "notify":{
    "message": true,
    "open": true,
    "queue": false,
  },
}

var requiredFlags = _.filterObject(actionsFlags, function(flags){
  return _.filterObject(flags, function(flag){
    return flag
  })
})

I just need a way to have the actionsFlags object where it only contains props equal to true.
Answer: As of version 1.7 the _.pick function can take an iteratee which can be used instead of filterObject:
var requiredFlags = _.mapObject(actionsFlags, function(flags){
    return _.pick(flags, function(flag){
        return flag === true;
    })
})

Answer: This works, just have to mapObject then filterObject.
  var requiredFlags = _.mapObject(actionsFlags, function(flags){
    return _.filterObject(flags, function(flag){
      return flag
    })
  })

Comment: You can replace that call to _.filterObject with a call to underscore's _.pick which from version 1.7 can take an iteratee.
Comment: Thanks a bunch! If you want submit an answer and I'll accept it.
Answer: Here is how to do it using the open source project jinqJs http://www.jinqJs.com
See Fiddle
var result = jinqJs().from(actionsFlags).select( function(row) {
var ret = {};
for(var o in row)
{
    ret[o] = {};
    for(var i in row[o])
    {
        if (row[o][i])
            ret[o][i] = true;
    }

}

return ret;

});

Filtering objects in underscore


AngularJS - wrapping 3rd party asynchronic loaded library as a service

Question: I have a 3rd party library that loads to my page asynchronously and I would like to use it as a service.
How can I wrap the loading code inside an angular service? In general what would be the best practice?
At the moment my approach is something like so:
angular.module('myAPIServices', []).
factory('MyAPI', function () {
    return {
        \\ API is declared at the loaded script
        doStuff:function(){$window.API.doStuff()}
    };
});

and then on the page outside of the Angular scope
(function () {
    var js = document.createElement('script');
    var loc = document.getElementsByTagName('script')[0];
    js.async = true;
    js.src = "myAPI.js";
    loc.parentNode.insertBefore(js, loc);
}());

Answer: A posibility is to wrap your library call in $q. This angular service returns a promise, which you can resolve when the library is fully loaded.
Your doStuff function would be something like:
doStuff: function() {
   var deferred = $q.defer();

   myAsyncCall().success(function(data) {
      deferred.resolve(data);
   });
   return deferred.promise;
}

In your controller you use the then() function to process the results.
A second possibility is with a callback. Here is an example of both types.
If your library is manipulating the DOM, it is better to wrap it in a directive.
Comment: The examples on jsFiddle are awesome! Callback worked great for me.


Morris.js create graph data-attributes [rails4]

Question: I'm trying to show statistics with morris.js.
But I always got this error msg in the Firebug console.
TypeError: this.options.data is undefined

clients_controller:
 @stats = @user.treatments.pluck( :created_at, :effective )

show.html.erb
 <%= content_tag :div, "", id: "graph1337", data: { stats: @stats } %>

Javascript code version 1:
  $(function () {
      Morris.Line({
          element: 'graph1337',
          data: $('#graph1337').data('stats'),
          xkey: 'created_at',
          ykeys: ['effective'],
          labels: ['effective' ]
      });
  });

Error msg:
TypeError: e is undefined

Javasciprt code version 2:
  $(function () {
   var stats = $('#graph1337').data('stats');
     Morris.Line({
          element: 'graph1337',
          data: $.map(stats, function(element) { JSON.stringify(element)}),
          xkey: 'created_at',
          ykeys: ['effective'],
          labels: ['effective' ]
          });
      });

I did 2 versions because I think that this is some kind of a 2 dimensional array. So I've tried to make one(lik Ruby flatten).
if I inspect the DOM element with Firebug:

<svg height="342" version="1.1" width="1140" xmlns="http://www.w3.org/2000/svg" style="overflow: hidden; position: relative; top: -0.5px;">
<desc>Created with Raphaël 2.1.0</desc>
<defs>
</svg>

rails debug msg:
<%= debug @stats %>
---
- - 2014-07-11 14:44:16.528543000 Z
  - 5
- - 2014-07-11 14:41:33.340103000 Z
  - 4
- - 2014-07-11 13:58:11.967193000 Z
  - 3
- -
  - 5
- -
  - 4
- -
  - 3
- -
  - 2
- - 2014-06-08 09:47:16.260312000 Z
  - 1

It's either not showing anything or it's the same error, any suggestions?
Thank you for your time.
Answer:
For your script work you need 3 modifications. (There doesn't have enough element for that I give the ruby-on-rails script but I think that my advices will guide you).
Step 1 :
The line of the data-stats doesn't have null value, if you have null value you get an error.
Like this :
[
    ['2014-07-11T14:44:16.528Z', 5],
    ['2014-07-11T14:41:33.340Z', 4],
    ['2014-07-11T13:58:11.967Z', 3],
    ['2014-06-08T09:47:16.260Z', 1]
],

Step 2 :
You set bad value to xkey, an ykey. The value must to be key of the value in your array.
You get this :
Morris.Line({
    element: 'graph1337',
    data: [
        ['2014-07-11T14:44:16.528Z', 5],
        ['2014-07-11T14:41:33.340Z', 4],
        ['2014-07-11T13:58:11.967Z', 3],
        ['2014-06-08T09:47:16.260Z', 1]
    ],
    xkey: "0",
    ykeys: ["1"],
    labels: ["effective"]
});

Step 3 :
Replace string date by timestamp and use dateFormat function.
var stats = $('#graph1337').data('stats');

Morris.Line({
    element: 'graph1337',
    data: [
        [1405082656528, 5],
        [1405082493340, 4],
        [1405079891967, 3],
        [1405064836260, 1]
    ],
    dateFormat: function (x) { return new Date(x).toLocaleTimeString(); },
    xkey: "0",
    ykeys: ["1"],
    labels: ["effective"]
});

Demo : http://jsbin.com/zatoyudo/1/edit
See more :

Formatting timestamps with ruby-on-rails
Comment: Thank you for your answer. Since you didn't answer the question I'm not able to accept your answer, but since your gives some useful hints I have to up-vote it.


Limit of Cosine and Sine Fourier Transforms

Question: If I define the cosine and sine Fourier transform as (skipping constant prefactors $(2\pi)^{0.5}$):
$$\mathcal{F}_C\{f(x)\}=\int_0^{\infty}\,f(x)\,\cos(\omega x)\,dx$$
and
$$\mathcal{F}_S\{f(x)\}=\int_0^{\infty}\,f(x)\,\sin(\omega x)\,dx$$
with $\omega>0$ and $f(x)$ is a real continous function such as $\int_0^{\infty}\,f(x)\,dx=1$ and $\lim_{x \to +\infty}\,f(x) = 0$. Now I would like to calculate the following limits:
1.$$\lim_{\omega \to 0}\,\mathcal{F}_{C}\{f(x)\}=?$$
2.$$\lim_{\omega \to 0}\,\mathcal{F}_{S}\{f(x)\}=?$$
3.$$\lim_{\omega \to +\infty}\,\mathcal{F}_{C}\{f(x)\}=?$$
4.$$\lim_{\omega \to +\infty}\,\mathcal{F}_{S}\{f(x)\}=?$$
Limits 1 and 2 are easily calculated to be equal to 1 and 0, respectively. This result is obtained by interchanging the integral and limit operators. However, since the limits $\omega \to +\infty$ for $\cos(\omega x)$ and $\sin(\omega x)$ do not exist, I cannot use the same trick for limits 3 and 4.
By using $f(x)=\exp(-x)$ as test function, I see that both limits 3 and 4 goes to 0.
How can I prove this for a general $f(x)$?
Answer: The Riemann-Lebesgue Lemma states that if $f$ is $\mathscr{L}^1$ integrable, then
$$\lim_{\omega \to \infty}\int_{-\infty}^{\infty}f(t)e^{i\omega t}dt=0$$.
Obviously, for real-valued $f$, we have
$$\lim_{\omega \to \infty}\int_{-\infty}^{\infty}f(t)e^{i\omega t}dt=\lim_{\omega \to \infty}\int_{-\infty}^{\infty}f(t)\cos(\omega t)dt+i\lim_{\omega \to \infty}\int_{-\infty}^{\infty}f(t)\sin(\omega t)dt=0.$$
Thus, this implies that both
$$\lim_{\omega \to \infty}\int_{-\infty}^{\infty}f(t)\cos(\omega t)dt=0$$
and
$$\lim_{\omega \to \infty}\int_{-\infty}^{\infty}f(t)\sin(\omega t)dt=0.$$


PHP e base de dados

Question: Boas, estou a elaborar um site e preciso de armazenar numa base de dados um ficheiro inserido/carregado pelo utilizador.
Qual o tipo de dados que devo atribuir ao campo?
Comment: Da uma olhada neste link -> http://blog.fabianobento.com.br/2009/09/armazenar-arquivos-em-modo-binario-mysql-usando-php/
Comment: Usa BLOB ou VARCHAR, depende do tamanho do arquivo.
Comment: tentei usar o MEDIUMBLOB mas nao reconhece o tipo de dados
Comment: Use o VARCHAR e defina um bom tamanho para ele, o DB vai armazenar uma referencia para o seu arquivo e não o arquivo em si.
Comment: o que quer dizer com a frase "tentei usar o MEDIUMBLOB mas nao reconhece o tipo de dados" ?
Answer: Use VARCHAR colocando o caminho fisico no servidor. Faça uma analise de toda a aplicação para ver se não é necessário ter um tabela apenas para arquivos, assim você poderia colocar mais informações sobre os arquivos nesta tabela.
Como:

caminho fisico no servidor
url do arquivo
tamanho do arquivo

Dentre outras várias informações que poderia vir do arquivo.
Answer: Use um VARCHAR e armazene apenas o caminho físico do arquivo no seu servidor
Answer: Caso o link do ficheiro for completo, com http://... use VARCHAR com Tamanho 250 (o máximo suportado em um campo VARCHAR). Caso você venha ver que o campo é muito extenso e ultrapasse 250 caracteres, use TEXT que suporta muitos caracteres.
Comment: O  tipo VARCHAR é 0 ~ 255 para versões até 5.0.3. Acima dessa versão é 0 ~ 65535.  O tipo CHAR é mais apropriado.. https://dev.mysql.com/doc/refman/5.0/en/char.html

PHP e base de dados


"pointer passing convention" in UEFI module

Question: I want to know when I need to free a pointer that is returned from EFI functions
EFI_DEVICE_PATH_PROTOCOL *
BmExpandFileDevicePath (
  IN  EFI_DEVICE_PATH_PROTOCOL    *FilePath,
  IN  EFI_DEVICE_PATH_PROTOCOL    *FullPath
  )
{
  EFI_STATUS                      Status;
  UINTN                           Index;
  UINTN                           HandleCount;
  EFI_HANDLE                      *Handles;
  EFI_BLOCK_IO_PROTOCOL           *BlockIo;
  UINTN                           MediaType;
  EFI_DEVICE_PATH_PROTOCOL        *NextFullPath;
  BOOLEAN                         GetNext;

  EfiBootManagerConnectAll ();
  Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiSimpleFileSystemProtocolGuid, NULL, &HandleCount, &Handles);
  if (EFI_ERROR (Status)) {
    HandleCount = 0;
    Handles = NULL;
  }

  GetNext = (BOOLEAN)(FullPath == NULL);
  NextFullPath = NULL;
  //
  // Enumerate all removable media devices followed by all fixed media devices,
  //   followed by media devices which don't layer on block io.
  //
  for (MediaType = 0; MediaType < 3; MediaType++) {
    for (Index = 0; Index < HandleCount; Index++) {
      Status = gBS->HandleProtocol (Handles[Index], &gEfiBlockIoProtocolGuid, (VOID *) &BlockIo);
      if (EFI_ERROR (Status)) {
        BlockIo = NULL;
      }
      if ((MediaType == 0 && BlockIo != NULL && BlockIo->Media->RemovableMedia) ||
          (MediaType == 1 && BlockIo != NULL && !BlockIo->Media->RemovableMedia) ||
          (MediaType == 2 && BlockIo == NULL)
          ) {
        NextFullPath = AppendDevicePath (DevicePathFromHandle (Handles[Index]), FilePath);
        if (GetNext) {
          break;
        } else {
          GetNext = (BOOLEAN)(CompareMem (NextFullPath, FullPath, GetDevicePathSize (NextFullPath)) == 0);
          FreePool (NextFullPath);
          NextFullPath = NULL;
        }
      }
    }
    if (NextFullPath != NULL) {
      break;
    }
  }

  if (Handles != NULL) {
    FreePool (Handles);
  }

  return NextFullPath;
}

for example, In this code, can I free Handles after calling HandleProtocol and still be able to use BlockIo?
Is there a document that explains the "pointer passing convention" of edk2 functions?
Thanks.
Answer: You have to look into the specification, if you are responsible to free the pointer there is a note.
For your LocateHandleBuffer example:

Buffer
A pointer to the buffer to return the requested array of handles that
support Protocol. This buffer is allocated with a call to the Boot
Service EFI_BOOT_SERVICES.AllocatePool(). It is the caller's
responsibility to call the Boot Service EFI_BOOT_SERVICES.FreePool()
when the caller no longer requires the contents of Buffer."

You can use the BlockIO protocols after you free the buffer, you are not freeing the handle instances (which would be a very bad idea), instead you are freeing an array of them.


Azure Performance - Ping Test - Inconsistent values between Availability and Performance

Question: In Azure you can create simple ping test of your app. It's call ping but it is Get request of a url.
By default, the url is your root url.
The thing is the responses times of thes results are in the range of 2 to 10ms. However, I can never reach these response times nor with Fiddler or Postman. My range is more 100 to 400ms. And I'm closer to the datacenter than the computers running the ping tests in Azure.
It is a bit as if the ping tests where not downloading the content page.
Does anyone know?
UPDATE
I have setup my ping test in the Availability section. The responses times I mention above appear in the Performance section. Back in the Availability section, average response time is 1,6 sec. These two sections show inconsistent values.
Answer: UPDATED ANSWER:
The Performance section lists how long it took from your server receiving the request to sending something back to the client, it doesn't count network latency at all.

I believe they only check the response status without downloading the content if you don't require a content match.
Below is an example of the configuration for my blog.
If you wish, you can make sure the test downloads the content by ticking the Content match checkbox, and specifying that the content must contain the text that is somewhere near the end of your index page (like in a footer).
Comment: That's fine not to download the content. But how can I reproduce it with Fiddler or Postman?
Comment: Well, in Fiddler you can look at the Statistics tab to see when you got the response headers. You can't see when you got the status code though, as that is the first thing the client gets. ServerBeginResponse might be pretty close.
Comment: The raw time it took for the bytes to be sent to the server and for you to receive the headers would be GotResponseHeaders - FiddlerBeginRequest.
Comment: @François Updated answer. That section only counts server processing time, while availability counts network latency as well.


Checksum of a loop device file exactly reproducible?

Question: how can I mount and unmount a file as loop device and have exactly the same MD5 checksum afterwards? (Linux)
Here's the workflow:

I take a fresh copy of a fixed template file which contains a prepared
ext2 root file system.
The file is mounted with mount -t ext2 <file> <mountpoint> -o loop,sync,noatime,nodiratime
( Here, some files will be added in future--but ignore this for a moment and focus on mount / umount )
umount
Take the MD5 sum of the file.
I expect the same, reproducible checksum every time I perform exactly the same steps.

However, when I repeat the process (remember: taking a fresh copy of the template file), I always get a different checksum.
I assume on the one hand that still some timestamps are set internally (I tried to avoid this with the noatime option) or, on the other hand, Linux manages the file system on its own way where I have no influence. That means: the files and timestamps inside might might be the same, but the way the file system is arranged inside the file might be differnt and therefore kind of random.
In comparison, when I create a zip file of a file tree, and I touched all files with a defined timestamp, the checksum of the zip file is reproducible.
Is there a way to keep the mount or file access that controlled as I need at all?
Answer: it depends on the file system on disk format. I believe ext2 keep sat the least the mount count counter - how many time the file system was mounted. I don't remember any mount option to tell it not to write that counter (and perhaps other data items) but you can:
a. mount the file system read only. Then the checksum will not change of course.
b. Change the ext2 file system kernel driver to add an option to not change the counter and possible other data bits.
The more interesting question is why you are interested is such an option. I think there is probably a better way to achieve what you are trying to do - whatever it is.
Comment: `tune2fs` can list and reset some of internal variables.
Comment: @Banthar that is true, but since he is trying to keep the same checksum, changing the checksum (using mount/umount) and then changing it back (using tune2fs) is not exactly the same thing as keeping the same checksum
Comment: Read-only is not useful when I add some files later. And hacking the kernel driver... I didn't intent to go that far... ;-). The idea is to have a file system for an embedded product. For regulatory reasons it's mandatory to prove the identity of every file. We do this with the single files we copy in, and it was handy when we could do that with the deployed file system as well.


Calculating trait disparity between sister species

Question: I have a phylogeny and 3-D morphometric data. I want to calculate trait disparity between sister taxa PC scores. Is there a function in R or R script that will do this?
Comment: The [dispRity](https://rawgit.com/TGuillerme/dispRity/master/inst/gitbook/_book/index.html) R package might be useful. Unfortunately this question is likely to be closed, as it is [off-topic](https://stackoverflow.com/help/on-topic).
Answer: You can indeed use the dispRity package as suggested in the comments in combination with the geomorph package.
Once your 3D data is properly read into R via geomorph you can use this simple pipeline:
## Make sure the packages are installed
library(dispRity)
library(geomorph)

## Some example 2D dataset
data(plethodon)

## Performing some GPA
procrustes <- gpagen(plethodon$land, PrinAxes=FALSE)

## Creating a geomorph dataframe
geomorphDF <- geomorph.data.frame(procrustes, species = plethodon$species)

## Creating a dispRity object and performing and ordination
ordination <- geomorph.ordination(geomorphDF)

## Measuring disparity as the sum of variances
disparity <- dispRity(ordination, metric = c(sum, variances))

summary(disparity)
#         subsets  n   obs
# 1  species.Jord 20 0.004
# 2 species.Teyah 20 0.004

Of course, I strongly suggest the implications and decisions that you have to make at each step (detailed information for each steps can be found in the functions manuals).
Comment: This approach does not take phylogeny into account.
Comment: Correct, this only measures trait disparity within groups (as asked in your question) and does not test any hypothesis. I you want to test some hypotheses, there exist many ways and some do indeed take into account phylogenetic history. An recent overview of some of these methods is available [here](https://academic.oup.com/sysbio/article/67/1/14/3867043) (pay walled unfortunately).


Determinant of a symmetric zero-diagonal matrix

Question: I am trying to write an algorithm which computes determinants of $n\times n$ real-symmetric matrices of the form
$$\mathbf S = \begin{pmatrix}
0 & a_{1,1} & a_{1,2} & a_{1,3} & \cdots  &a_{1,n-1}\\
a_{1,1} & 0 & a_{2,1} & a_{2,2} & \cdots& a_{2,n-2}\\
a_{1,2} & a_{2,1} & 0 & a_{3,1} & \cdots& a_{3,n-3}\\
a_{1,3} & a_{2,2} & a_{3,1} & 0& \cdots& a_{4,n-4}\\
\vdots & \vdots & \vdots& \vdots& \ddots &\vdots\\
a_{1,n-1}&a_{2,n-2}& a_{3,n-3} & a_{4,n-4} & \dots &0
\end{pmatrix}$$
which are to be encoded in the form $\{\{a_{1,1},a_{1,2},\dots,a_{1,n-1}\},\{a_{2,1},a_{2,2},\dots,a_{2,n-2}\},\dots,\{a_{n-1,1}\}\}$.
For example, the encoding <code>{{1,2,3},{4,5},{6}}</code> corresponds to the $4\times 4$ matrix
$$ \begin{pmatrix}
0&1&2&3\\
1&0&4&5\\
2&4&0&6\\
3&5&6&0
\end{pmatrix}.
$$
Is there a way of efficiently finding the eigenvalues of $\mathbf S$, or, alternatively, finding the number of distinct eigenvalues, by taking advantage of its symmetric properties?
The only way I've managed so far is to compute is to evaluate $\det(\mathbf S - \mu \mathbf I)$ by treating $a_{i,j} = a_{j,i}$, but this is still $O(\frac{n^2}{2})$, i.e. $O(n^2)$.
Answer: You won't be able to do anything that's asymptotically better than an algorithm for computing general determinants (which is $O(n^3)$ the easy way, though there are algorithms that are $O(n^k)$ for $k \approx 2.373$). The reason for this is that a special case of your problem is finding the determinant of a block matrix of the form
$$ \begin{bmatrix} 0 & A \\ A^T & 0\end{bmatrix} = \begin{bmatrix} 0 & 0 & \cdots & 0 &a_{1,n/2} & a_{1,n/2+1} & \dots & a_{1,n-1} \\
0 & 0 & \cdots & 0 & a_{2,n/2} & a_{2,n/2+1} & \dots & a_{2,n-1} \\
\vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots & \vdots \\
0 & 0 & \cdots & 0 & a_{n/2,n/2} & a_{n/2, n/2+1} & \cdots & a_{n/2, n-1} \\
a_{1,n/2} & a_{2,n/2} & \cdots & a_{n/2,n/2} & 0 & 0 & \cdots & 0 \\
a_{1,n/2+1} & a_{2,n/2+1} & \cdots & a_{n/2, n/2+1} & 0 & 0 & \cdots & 0 \\
\vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots & \vdots \\
a_{1,n-1} & a_{2,n-1} & \cdots & a_{n/2,n-1} & 0 & 0 & \cdots & 0\end{bmatrix}$$
and this determinant simplifies to $(-1)^n \det(A)^2$, so computing it is as hard as computing the determinant of $A$, an arbitrary $\frac n2 \times \frac n2$ matrix.


How can I sum numbers extracted by Select-String?

Question: Supposing I have a file numbers.txt:

My number 1
...
My number 2
...
My number 3
...

I am trying to calculate sum of the numbers above. I extracted a number from each line like this:
PS > $numbers = gc .\numbers.txt | sls -Pattern "number\ (\d+)" |
>> select {$_.matches[0].groups[1].Value}
>>
PS > $numbers

$_.matches[0].groups[1].Value
-----------------------------
1
2
3

Looks like exactly what I want to sum. Next I am trying to apply the Measure-Object:
$numbers | measure -sum

measure : Input object "" is not numeric.
At line:1 char:12
+ $numbers | measure -sum
+            ~~~~~~~~~~~~
    + CategoryInfo          : InvalidType: (:PSCustomObject) [Measure-Object],
PSInvalidOperationException
    + FullyQualifiedErrorId :
NonNumericInputObject,Microsoft.PowerShell.Commands.MeasureObjectCommand

What am I doing wrong?
Answer: Your array doesn't consist of numbers, but objects with a very long property-name (your scriptblock-value) which contains a string-value.
Replace Select-Object with Foreach-Object to get the value, cast it to int and calculate. Ex:
$numbers = gc .\numbers.txt | sls -Pattern "number\ (\d+)" | Foreach-Object {$_.matches[0].groups[1].Value -as [int] }
($numbers | measure -sum).Sum

Comment: Cmdlets don't like the name because it contains many special characters since it's an expression. Why it won't work with single quotes when `$obj.'{$_.this.works}'`, I can't say. When using calculated columns, you are supposed to set a name like my example above. And with this limitation + the fact that you only store the number, I would say that foreach is still better than `.. | select @{n="Number";e={$_.matches[0].groups[1].Value -as [int]}}; ($numbers | Measure-Object -Property Number -Sum).Sum` (there are other ways to do it, but creating an object with one prop is still waste of time).
Comment: I can cast it to int even with Select-Object but I wonder is the length of property-name an obstacle for Measure-Object?
Comment: The casting-part was not the issue with `Select-Object`. The issue was that `Select-Object` used the expression (scriptblock) creates a property with the same name. We could give the column another name (@{n="ColumnName";e={$_.matches[0].etc}}`), but since you only want the number then it's much easier and cleaner to skip `Select-Object` in the first place and use `Foreach-Object`.
Comment: I see... It is not easier but useful for understanding. So when I tried to use `measure -sum "$_.matches[0].groups[1].Value"` it basically did not understand that name, right? Then what is the sense to have names we cannot access?
Comment: I am agree your way is better, just wanted to clarify things for myself.
Answer:
Looks like exactly what I want to sum

No it doesn't, the output has a header row. If it was a simple array of integers then it would not, it would show as simply:
1
2
3

What you have created is an array of PowerShell objects, each with a property called '$_.matches[0].groups[1].Value'. You need something like:
$numbers = gc .\numbers.txt | sls -Pattern "number\ (\d+)" | ForEach {$_.matches[0].groups[1].Value}

instead.
Answer: other method:
$template=@"
My number {number*:1}
My number {number*:2}
"@

#verbose version
(Get-Content C:\temp\number.txt |
    ConvertFrom-String -TemplateContent $template |
        measure -Sum number).Sum

#short version
(gc C:\temp\number.txt | cfs -TemplateContent $template | Measure -Sum number).Sum

Comment: It work if string are number (1, 2, 123, 123.456). Give a complet example of your content file
Comment: Nice, but it will work only if strings are of fixed format where only number can change, right? In real life I have log line like this: `{date} [{thread}] Got N messages {guid}`.
Comment: `23:52:49 [10] Got 2 messages \ 23:52:50 [12] Some irrelevant stuff \ 23:52:51 [42] Got 5 messages \ ...`


How to programmatically create a custom token in a module

Question: How would you go about programmatically creating a token? I wish to add some custom tokens for my module.
Comment: Additional documentation has been updated (Oct 31,2014) and can be found at https://www.drupal.org/documentation/modules/token
Answer: In Drupal 7 the code for handling tokens is part of the Drupal core module.
The hooks the token modules need to implement are:

hook_token_info() is the hook that provides information about the tokens implemented by a module.
hook_tokens() is the hook that needs to be implemented to provide the actual values that replace the tokens.

Other modules can alter the token implementation provided from a module using hook_token_info_alter() and hook_tokens_alter().
Differently from the Token module, the code in Drupal core allows to create the content of a token only when strictly necessary.
In Drupal 6, the Token module would ask to the modules implementing tokens all the values for their token using hook_token_values(); this means that a module can compute the value for a token which is then not required for the tokens being replaced. In Drupal 7, the implementation of hook_tokens() receives $tokens, an array of tokens to be replaced, as argument; the module is then able to compute the value of a token, knowing it will be used.
The function that in Drupal 7 is used to replace the tokens with their value is token_replace(), which is the only function used to replace the tokens with their values.
Other difference between the Token module for Drupal 6 and the code in Drupal 7 are:

In Drupal 7, [node:author] returns the name of the author; [node:author:mail] returns the email address associated with the author of a node, and [node:author:url] returns the URL of the user profile for the node author. In other words, it is possible to use [node:author:xyz], where "xyz" is one of the tokens returned for a user object.
In Drupal 7, there are not raw tokens; the implementation of hook_tokens() get a parameter that tells to the hook when the content of the token needs to be sanitized; when the token value doesn't need to be sanitized, the content is not passed to the functions check_plain() or filter_xss().
In Drupal 7, there isn't any function that show the list of the available tokens. If a module needs to show the list of available tokens, it must build the list of the tokens itself and show it in the description of a form field; alternatively, it can use the theme function still available in the Token module.
Answer: I wanted to add a new token to the Site information section of tokens, called City name. This is how I did it in Drupal 7.
 /**
 * Implements hook_token_info().
 */
function my_module_token_info() {

  // Add tokens.
  $site['city_name'] = array(
    'name' => t('Token Name'),
    'description' => t('Token Description'),
  );

  return array(
    'tokens' => array(
      'site' => $site,
    ),
  );
}

/**
 * Implements hook_tokens().
 */
function my_module_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

 if ($type == 'site') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'city_name':
          $city_name = variable_get('city_name');
          $replacements[$original] = $options['sanitize'] ? check_plain($city_name) : $city_name;
          break;
      }
    }
  }

  // Return the replacements.
  return $replacements;
}

Comment: So the token would be in above example: `[site:city_name]`. Make sure you clear the caches or restart memcached if used.
Comment: Thanks for providing an example.  They are always helpful
Comment: Note: `$sanitize` in above example is not defined, so you'll get `Notice: Undefined variable` about that.
Comment: @kenorb good eye, and I see this answer has since been updated :)
Comment: @WebMW Actually, it never was. I fixed it.
Comment: If you'd like to make a token for a certain entity type, change the type to the entity type's machine name, e.g. `node`, `user`, `message`, etc., then the entity will be available in the `$data` array.
Answer: In Drupal 6, you use hook_token_values().
This hook will allow you to create tokens. You can create them in the global scope or you can use an object like a node, or a user to seed the values.
You should also use hook_token_list() to explain what your tokens are.
The token.api documentation is quite clear.
function my_user_token_values($type, $object = NULL, $options = array()) {
  if ($type == 'user') {
    $user = $object;
    $tokens['name']      = $user->name;
    $tokens['mail']      = $user->mail;
    return $tokens;
  }
}

I won't X post the whole thing but that should give you a high level idea.
Answer: For Drupal 8, example using the node object:
You can put tokens in your module at mymodule.tokens.inc using hook_token_info() to register them and hook_tokens() for the the replacement data.
If you want to create a custom token for an existing token type, such as for nodes, you'll need to put your token within the subarray within hook_token_info().  Refer to node.tokens.inc in the node module to see what you're building off of.
mymodule.tokens.inc:
<?php

use Drupal\Core\Render\BubbleableMetadata;
use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_token_info().
 */
function mymodule_token_info() {
  $info = array();

  $info['tokens']['node']['custom_title'] = [
    'name' => t("Custom Title"),
    'description' => t("a custom node title token"),
  ];
  // Return them.
  return $info;
}

/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {

  $replacements = array();
  if ($type == 'node') {
    foreach ($tokens as $name => $original) {
      // Find the desired token by name
      switch ($name) {
        case 'custom_title':
          $node = $data['node'];
          $replacements[$original] = $node->label();
          break;
      }
    }
  }
  // Return the replacements.
  return $replacements;
}

Answer: For Drupal 8
// We need to include the needed class for tokens.

use Drupal\Core\Render\BubbleableMetadata;

/**
 * Implements hook_token_info().
 */
function modulename_token_info() {
  $info = array();
  // Add any new tokens.
  $info['tokens']['customtokentype']['customtoken'] = t('Telling drupal that you define custom token');
  // Return them.
  return $info;
}

/**
 * Implements hook_tokens().
 */
function modulename_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  $simple = $data["customanything"];
  if ($type == 'customtokentype') {
    foreach ($tokens as $name => $original) {
      // Find the desired token by name
      switch ($name) {
        case 'customtoken':
          $new = $simple;
          $replacements[$original] = $new;
          break;
      }
    }
  }
  // Return the replacements.
  return $replacements;
}

Getting the value of tokens in your function requires code similar to the following one.
$token = \Drupal::token();
$message_html = "hello my custom token is replaced see it here [customtokentype:customtoken]";

// Token data.
$data = array('customanything' => $tosendtotokens);
$message_html = $token->replace($message_html, $data);

Comment: What is `new` and `simple` in this example?
Comment: This should go in modulename.tokens.inc
Comment: use Drupal\Core\Render\BubbleableMetadata;
$token = \Drupal::token();                                                                                function modulename_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) { ... }
Answer: In my_module.tokens.inc place two functions like this:
<?php

/**
 * Implements hook_token_info().
 */
function my_module_token_info() {
  $info['tokens']['node']['my_custom_title'] = [
    'name' => t("Custom title"),
    'description' => t("The first 10 characters of the title"),
  ];
  return $info;
}
/**
 * Implements hook_tokens().
 */
function my_module_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  if ($type == 'node') {
    foreach ($tokens as $name => $original) {
      // Find the desired token by name
      switch ($name) {
        case 'my_custom_title':
          $node = $data['node'];
          $replacements[$original] = substr($node->getTitle(), 0, 10);
          break;
      }
    }
  }
  return $replacements;
}

Comment: I created this answer as previous answers by oknate and Karthikeyan had some unecessary complications.


Is a graduate homework question acceptable?

Question: I just stumbled on a graduate level question which is not marked or mentioned as a homework question, though the OP even posted the whole picture of the question without detailing his attempts. I am just wondering if a graduate level homework question like that one is acceptable to our forum.
Answer: Only if it follows the usual rules: the asker must have made some attempt to answer it themselves, they must show us what they've done, and they must explain which concept or aspect of it they're having trouble with.
The asker has done those things. However, as their actual question is just an image, that's useless for search engines, so the question should be closed anyway.


Retornar o maior número em Python com recursividade

Question: Meu professor começou a falar de recursividade, e passou alguns exercícios, só que eu travei em um.
Como diz no enunciado abaixo, devo criar uma função que retorne o maior valor contido em uma lista.
Minha dificuldade é: não estou conseguindo fazer isso usando a recursividade. Minha ideia foi fazer tipo um bubble sort e depois só exibir o último elemento, porém, está ocorrendo o seguinte erro:

RecursionError: maximum recursion depth exceeded in comparison

Não consigo pensar em outra forma de fazer.
Implemente recursivamente uma função Max que retorne o maior valor armazenado em um vetor V, contendo n números inteiros
global c
global c2
global temp

x = [5, 2, 8, 4, 6, 9, 0, 1]

c = 0
c2 = 1
temp = max(x)

def Max(x):
    global c
    global c2
    if x[c] > x[c2]:
        x[c], x[c2] = x[c2], x[c]
        c += 1
        c2 += 1
    if x[len(x)-1] != temp:
        Max(x)
    return x

print(Max(x))

Comment: A sua identação não está correta.  Isso em Python é erro de sintaxe, e torna muito difícil acompanahr suas ideias. Acho que você deve ter identado lina a linha com a barra de espaço para formatar a questão - isso não é necessário. Edite a questão, coleo código cmo está no seu editor, selecione o trecho de código e pressione o botão `{}` para formatar o código aqui, por favor.
Comment: Não sabia disso. Obrigada :)
Answer: Você deve ter percebido que não é a ideia deste site que as pessoas resolvam o problema pra você - mas podem ser dadas dicas.
No caso de função recursiva, a ideia é sempre:  a função verifica se tem uma resposta trivial - nesse caso seria apenas receber uma lista vazia e um outro parâmetro que seria "candidato ao valor máximo". Já que a lista não tem mais elementos, o candidato ao máximo é o próprio máximo - não tem outros concorrentes- e o valor é retornado.
Se a lista não está vazia, ela vai ter em mãos uma lista com alguns elementos e um candidato ao máximo - ela pode extrair o último elemento da lista (o método .pop() faz isso), verificar se esse elemento é maior que o candidato atual - se sim, substitui o candidato. Nesse momento, você tem em mãos uma lista mais curta e um candidato atualizado - e precisa decidir o que retornar para quem chamou a função original (e fazer uso da recursividade). Não vou acabar de descrever tudo - aí o exercício continua com algum desafio.
Outra dica: variáveis globais não são necessárias nesse problema. Sua função recursiva vai precisar de dois parâmetros - a lista e um "candidato a máximo".
Espero que essas dicas te ajudem
Comment: Muito obrigada pelas dicas. Com elas consegui fazer o codigo


Reformatting numbers such as data0000172 to 172 in python

Question: I have a list of strings. Each string has the form of data0*(\d*) if we use a regular expression form.
The following is an example the strings:
data000000, data000003, data0172, data2312, data008212312

I would like to take only the meaningful number portion. All numbers are integers. For example, in the above case, I would like to get another list containing:
0, 3, 172, 2312, 8212312

What would be the best way in the above case?
The following is the solution that I thought:
import re

string_list = ["data0000172", ..... ]
number_list = []
for string in string_list:
   match = re.search("data0*(\d+)", string)
   if match:
      number_list.append(match.group(1))
   else:
      raise Exception("Wrong format.")

However, the above might be inefficient. Could you suggest a better way for doing this?
Answer: If you are sure that the strings start with "data", you can just slice the string and convert to integer. Leading zeroes aren't an issue there. Building an integer from a zero-padded digit strings works.
lst = ["data000000", "data000003", "data0172", "data2312", "data008212312"]

result = [int(x[4:]) for x in lst]

result:
[0, 3, 172, 2312, 8212312]

or good old replace just in case the prefix can be omitted (but it will be slightly slower):
result = [int(x.replace("data","")) for x in lst]

Answer: import re

st = 'data0000172'

a = float(re.search('data(\d+)',st).group(1))
print(a)

Output:
172.0

This extract the numbers i.e useful part.Apply this to your list.
Comment: Why not use int()?
Comment: you can use it. That's not a problem.Based on our need.
Answer: In the case where the strings are might not be of the form data<num> and you want the solution to still be valid or if some of the entries are broken for some reason, you can do the following:
import re

ll = ['data000000', 'data000003', 'data0172', 'data2312', 'data008212312']
ss = ''.join(ll)
res = [int(s) for s in re.findall(r'\d+', ss)]
print(res)

The re.findall is applied to the entire list of strings but due to the fact it returns a list of tuples you will get the desired result.
Output:
[0, 3, 172, 2312, 8212312]

Note: applying the re.findall to the list without the join will raise an error.


Creating a tile dashboard using angular js

Question: I am creating a dashboard application in Angular JS, which will have different tiles. Each tile has its own specific data & HTML.
Thought of approaching the problem with

<dashboard-tile/>

where  is a directive. But i have following doubts-
1. Since each tile will have different HTML(content), how can i repeat it through a single directive template.
2. If i want to inherit from a base tile and add own properties (model+content) to the tile, how can i then repeat the tile in HTML.
Not sure how to proceed or design the solution.
Any help is appreciated.
Thanks & Regards,
Sonny
Comment: If these tiles are specific to the dashboard, and are not meant to replicated widgets, I wouldn't be concerned about making them inherit from a shared directive. You aren't really buying yourself anything if they all have unique html, css and js associated with them. They can (and should) be directives, just don't force it into an inherited relationship.

If there are shared properties, can you elaborate on them?
Comment: so what do you suggest, make them individual directives and include in the HTML rather than use ng-repeat? But what if there are a lot of unique tiles.
Comment: What are you even repeating against? `ng-repeat` is normally used to repeat an array of items of the same type. You have a bunch of disparate widgets seemingly. What are their unifying properties? Would you expect them to use the same data source & structure? Also, is the presence of the widget data driven? Is it always there, or only based on certain data points?
Comment: Okay, got your point. Is there any way to dynamically load a directive based on a condition. Like-

where everytime based on condition the directive is different.
Answer: Based on what you're looking for, I'd say you'd want to ng-repeat with a ng-switch, and then list out the possible widgets with ng-switch-when.

                <widget-activity-feed ng-switch-when="activity" >
                </widget-activity-feed>
                <widget-monthly-income ng-switch-when="income">
                </widget-monthly-income>

Comment: Hey Dylan, i think i found the way. But i'm facing one more issue for DOM manipulation. I was using the jquery UI drag and drop logic for the tiles initially. Now i want to write the same DOM logic somewhere in the parent directive, which will be applicable to all child directives instead of copy pasting in all the child directives. But iam unable to determine where to write that in the parent directive. Is there a place in the parent directive which says now the directive DOM is ready, place your logic here. something like jquery ready


How to show that $e_i \cdot Ae_j = a_{ij}$ - Matrices

Question: Let $e_j \in R^n$ be a vector whose $j$'th component is 1 and all other components are 0.
For example, if $n=3$ then $e_2$ = $\left(\begin{matrix} 0 \\ 1 \\ 0 \end{matrix}\right)$
Let $A= (a_{ij}) \in M_{m,n} (R)$
How would I show that:
$e_i \cdot Ae_j = a_{ij}$
Answer: Think about why if $v = Ae_j$, then the vector $v$ is the $j^{th}$ column of $A$. Now, think about if you have any vector $w$, why $e_i \cdot w$ will give you the $i^{th}$ entry in the vector $w$. Putting these together you can see that $e_i \cdot Ae_j$ should give you the $i^{th}$ entry of the $j^{th}$ column of $A$.
Comment: I understand. Would a worded solution like this be efficient?
Comment: Perhaps, depending on what rigor you're expected to produce. However, you can show it formulaically as well: For example, if $v = Ae_j$, let $[v]_k$ represent the $k^{th}$ element in $v$. Then by definition (of matrix multiplication), $[v]_k = \sum_{m=1}^n a_{km}[e_j]_m = \sum_{m=1}^n a_{km} \delta_{jm} = a_{kj}$. Therefore the $k^{th}$ element of $v$ is the same as the $k^{th}$ element of the $j^{th}$ column of $A$, implying that $v$ is the same as the $j^{th}$ column of $A$.


Is there a technical requirement to serve 404 responses?

Question: Is there a technical requirement (e.g., RFC) to serve a 404 response?
Or does some other problem emerge if requests not found are dropped or replies empty?
Comment: You may find the answer/videos on https://security.stackexchange.com/a/150762/10843 to be relevant to your second question.
Answer: An HTTP server is required to reply with an HTTP response message. Every HTTP request returns a status code, see RFC 1945.
The 4xx/5xx codes are just the error codes that are usually displayed to the user.
Comment: I understand that but (perhaps strangely) that's the way things are.
Comment: RFC 1945 is Informational (but still useful) - do you know if this is addressed in others?
Comment: Well, that RFC's pretty much the foundation block of the Web. But you can refer to RFCs 2068, 7231, 7540, ... as well. No, there's no "Internet Standard" anywhere but that's how it is.
Comment: I understand there isn't truly an official standard, but there is a difference the RFC statuses, for which [RFC 2026](https://datatracker.ietf.org/doc/html/rfc2026) was created to define, itself a "Best Current Practice" RFC (not even a standard!).
Answer: RFC 7230 Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing (Standards Track)

Section 2.1

...

A server responds to a client's request by sending one or more HTTP
response messages, each beginning with a status line that includes
the protocol version, a success or error code, and textual reason
phrase ...

According to this RFC, you can't simply drop the connection or send an empty reply.
Comment: i agree to the terms, the standard client is awaiting the status first and then it acts respectively to the answer imho
Comment: I apologize if I'm revising my question with this comment, but what I'm looking at is the obvious garbage thrown at the server. It seems like anything that has a Host header not matching anything I'm serving should just be dropped, because analysis of the logs shows it is 100% bots and likely to do with ancient assignments of the IP address, so 404 response is pointless. At some point, a request should be considered invalid or even hostile, and 100 requests/sec bot-generated 404 garbage looks hostile, at least to me, and I'd really rather drop it, but I do prefer to follow standards.
Comment: You can respond with `400` for an invalid `Host:` header (Section 5.4 of the RFC 7239). You can rate limit requests and respond with `429`. If a client host is really hostile and generates too many 4xx errors then you can block them at IP level (`fail2ban` etc.) and drop connection (RFC 6585 Section 7.2)


array of phone numbers checking using nspredicate

Question: I've an array of phone numbers from that i need to check a particular(given) phone number is contain in that array or not.So how can i do that by using NSPredicate.(NB currently i am using array contains object method.in my problem i need a solution using predicate). So If anyone know this please help me
 NSString *p = allUsers.phoneNumber;
            NSString *p1 = [p stringByReplacingOccurrencesOfString:@"-" withString:@""];
            NSString *p2 = [p1 stringByReplacingOccurrencesOfString:@"(" withString:@""];
            NSString *p3 = [p2 stringByReplacingOccurrencesOfString:@")" withString:@""];
            NSString *p4 = [p3 stringByReplacingOccurrencesOfString:@" " withString:@""];
            NSString *p5 = [p4 stringByReplacingOccurrencesOfString:@"+" withString:@""];
            NSString *p6 = [p5 stringByReplacingOccurrencesOfString:@"*" withString:@""];
            NSString *p7 = [p6 stringByReplacingOccurrencesOfString:@"#" withString:@""];

 if ([arrayAllPhoneNumbers containsObject:p7])
            {
                allUsers.isPhoneUser = YES;

            }

Answer: // For number kind of values:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF = %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];

// For string kind of values:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];

// For any object kind of value (yes, you can search objects also):
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];

Comment: @abymathew : just remember to do [result objectAtIndex:0] to get the actual result.
Comment: thanks both of u for great answers...my exact problem is this arrayallphonenumber[@12345,@5678], then in my p7 value is 345 so i need to take 12345 value from arrayallphonenumbers so how can i get this
Comment: ok guys thanks for your valueble answers...i got my solution...from your answers...
Comment: @abymathew, please accept this as an answer, so if other people try to face the smae issue then this will helpful to them.
Answer: One good solution is there in-spite of using NSPredicate you can try with NSDatDetector
Please try below:-
NSString *p = @"8147744507";
NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink|NSTextCheckingTypePhoneNumber
                                                           error:&error];
NSArray *matches = [detector matchesInString:p
                                     options:0
                                       range:NSMakeRange(0, [p length])];
for (NSTextCheckingResult *match in matches)
{
    if ([match resultType] == NSTextCheckingTypePhoneNumber)
    {
        NSString *phoneNumber = [match phoneNumber];
        NSLog(@"phone no valid=%@",phoneNumber);
    }
}


ARMA: selection of lagged variables

Question: In the arma{tseries} documentation in R, they select a few lagged variables:
library(tseries)
data(nino)
arma(nino3.4, lag=list(ar=c(1,3,7,10,12,13,16,17,19),ma=NULL))

http://www.rdocumentation.org/packages/tseries/functions/arma
What do I call such a model? Can I call it an ARMA(19,0) even if some lagged values in-between are ignored?
Comment: It might be helpful to complement the R code with mathematical notation of the model with restrictions.
Answer: I would call it ARMA(19, 0). The AR and MA terms are typically identified by the maximum lag, even if some values in between are ignored. If you think about the way the ARMA(p, q) model is specified
$$x_t = \sum_{i = 1}^p\alpha_i x_{t-i} + \sum_{j=1}^q\beta_j w_{t-j} + w_t$$
you can imagine some $\alpha_i$ and $\beta_i$ values which happen to equal to zero.
Comment: I'd also add that 19 is a pretty high number of lag periods, but I realize you're using an example from the documentation
Comment: Or, as @Aksakal notes, AR(19)
Answer: This is AR(19) model, not ARMA. It has constraints on some lags, i.e. $\phi_2=0$, $\phi_4=0$ etc.
$$y_i=c+\sum_{k=1}^{19}\phi_k y_{i-k}+\varepsilon_i$$
Generally, it's better to not have these constraints without a good reason. They tend to create weird effects.
Often, like with R, AR(P) processes are estimated by the same routine as ARMA or even ARIMA. MATLAB is the extreme case where they're all estimated by `arima' function. That's why some people would call this ARIMA or ARMA process, but I like to emphasize that it is AR(P). It's quite different from integrated processes, in that it is stationary. It's also quite different from ARMA processes, e.g. it can be estimated by OLS while ARMA process would require something like MLE.
Comment: One thing before I validate the answer: you say "it's better to not have these constraints without a good reason". When you do a summary on an arma model, R calculates for you the pvalue of the coefficient being relevant. I was always taught (in linear regressions) to remove the irrelevant variables. Should I always remove the "irrelevant" lagged variables in this kind of model? Would you? Is the negligible t-statistic a good reason to impose that constraint or should I just leave it there?
Comment: @RicardoCruz, I don't remove non-significant variables based solely on p-values even from OLS. In case of time series, it's even trickier. Your AR coefficients define frequency [spectrum](https://en.wikipedia.org/wiki/Autoregressive_model#Spectrum) of your process, seasonality etc. So, you've got to be careful with automatic lag-selections, they mess up your series
Comment: Yes, the model can be called AR(19) or, indeed, autoregressive of order 19. Equally valid, though, are both ARMA(19,0) and ARIMA(19,0,0). I think it depends on context which one is most suitable. Obviously, it's always good to be explicit about notation, too; e.g. p=19, d=0, etc.
Comment: There is an _obvious error_, _which I assert_, in the subscript notation. My edit was refused(?), so I suggest here to make the necessary amendments to avoid confusion.
Comment: @GraemeWalsh, thanks for pointing to an error, fixed. AR(P) is most specific characterization, given that d=q=0 in this case.

ARMA: selection of lagged variables


Infinte Horizontal scrolling in reactjs

Question: I was able to get vertical infinite scrolling working with redux-infinte-scroller ()
    <InfiniteScroll` containerHeight = {this.props.height} items={this._renderMessages()} loadMore={this._loadMore.bind(this)}>
      this.render_items();
     </InfinteScroll>

However while trying to implement horizontal infinite scroll with
    <InfiniteScroll horizontal = {true} containerHeight = {this.props.height} items={this._renderMessages()} loadMore={this._loadMore.bind(this)}>

    this.render_items();
   </InfinteScroll>

does not work.
How can I accomplish this?
Answer: Redux-infinite-scroll is used for vertical scrolling only, not for horizontal scrolling.
The horizontal prop only used to also take into account horizontal scrolling (due to the width of the content), while scrolling vertically.

Infinte Horizontal scrolling in reactjs